Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Problem getting info out of serial port (http://www.go4expert.com/forums/getting-info-serial-port-t16283/)

Andres 20Feb2009 23:36

Problem getting info out of serial port
 
The code is working properly, but somehow I keep on getting 255
This code is suppose to get information out of the microcontroller via the serial port. The microcontroller has a program that should be sending different values.

Example:
X = 123
Y = 243
Z = 124

but instead it sends
X = 255
Y = 255
Z = 255
Is there something wrong with the serial port code?
Code:

#include <windows.h>
#include <commctrl.h>
#include <iostream>
#include <iomanip>
#include <fstream>
#include<stdio.h>
using namespace std;

int main()
{
   
FILE * pFileUCS;

int d;
char str [80];
int x;
fstream UCS;

UCS.open("UCS.txt");
pFileUCS = fopen ("UCS.txt", "w+");

//1 Opening the serial port
HANDLE hSerial;
hSerial = CreateFile("COM1",
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if(hSerial==INVALID_HANDLE_VALUE){
if(GetLastError()==ERROR_FILE_NOT_FOUND){
cout<<"Serial port does not exist";
}
//some other error occurred. Inform user.
}

//2 Setting Parameters
DCB dcbSerial;
DCB dcbSerialParams = {0};
dcbSerial.DCBlength=sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams)) {
//error getting state
}
dcbSerialParams.BaudRate=CBR_9600;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
if(!SetCommState(hSerial, &dcbSerialParams)){
//error setting serial port state
}

//3 Setting timeouts
COMMTIMEOUTS timeouts={0};
timeouts.ReadIntervalTimeout=1;
timeouts.ReadTotalTimeoutConstant=5;
timeouts.ReadTotalTimeoutMultiplier=1;
timeouts.WriteTotalTimeoutConstant=5;
timeouts.WriteTotalTimeoutMultiplier=1;
if(!SetCommTimeouts(hSerial, &timeouts)){
//error occureed. Inform user
}

int count=0;
do{
        count++;
//4 Reading/Writing data
char szBuff[10000] = {0};
DWORD dwBytesRead = 0;
ReadFile(hSerial,szBuff, 10000, &dwBytesRead, NULL);
cout<<szBuff<<endl;
//UCS << szBuff << endl;
if(!ReadFile(hSerial,szBuff, 10000, &dwBytesRead, NULL)){
cout<<"There was an error"<<endl;      //error occurred. Report to user.
}

}while(count!=100);
UCS.close();
fclose (pFileUCS);

 
//5 Closing down
CloseHandle(hSerial);
return 0;
}


xpi0t0s 21Feb2009 14:15

Re: Problem getting info out of serial port
 
You'll probably get a better response if you reformat the code so that it's readable.


All times are GMT +5.5. The time now is 11:14.