|
-
February 20th, 2009, 01:10 PM
#1
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?
#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;
}
-
February 23rd, 2009, 05:38 AM
#2
Re: Problem getting info out of serial port
Hi,
Try keeping no of bytes to be received less...! how many bytes do you receive in in single read ??? why do you used two calls for readfile...just use if..else..
-Anant
"Devise the simplest possible solution that solves the problems"
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|