Click to See Complete Forum and Search --> : Serial Port Code errors


Pitufo
February 6th, 2009, 01:46 PM
I get errors in the following code...can someone help me:
'dcbSerial' undeclared (first use this function)


#include <windows.h>
#include <commctrl.h>
using namespace std;

int main()
{
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){
//serial port does not exist. Inform user.
}

//some other error occurred. Inform user.
}
DCB dcb;
DCB dcbSerialParams = {0};
dcbSerial.DCBlength=sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams)) {
//error getting state
}
dcbSerialParams.BaudRate=CBR_19200;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
if(!SetCommState(hSerial, &dcbSerialParams)){
//error setting serial port state
}
}

Pitufo
February 6th, 2009, 02:30 PM
I found the problem...thanks anyways...

Pitufo
February 9th, 2009, 11:49 AM
I get an error in the Reading/Writing data:
variable-sized object 'szBuff' may not be initialized


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

int main()
{

//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){
//serial port does not exist. Inform user.
}
//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=50;
timeouts.ReadTotalTimeoutConstant=50;
timeouts.ReadTotalTimeoutMultiplier=10;
timeouts.WriteTotalTimeoutConstant=50;
timeouts.WriteTotalTimeoutMultiplier=10;
if(!SetCommTimeouts(hSerial, &timeouts)){
//error occureed. Inform user
}

//4 Reading/Writing data
int n;
char szBuff[n + 1] = {0};
DWORD dwBytesRead = 0;
if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
//error occurred. Report to user.
}

//5 Closing down
CloseHandle(hSerial);
}

Codeplug
February 9th, 2009, 12:10 PM
It's time to learn how to use code tags: http://www.codeguru.com/forum/misc.php?do=bbcode#code

http://www.cplusplus.com/doc/tutorial/arrays.html
The first "NOTE:" is particularly important in your case.

gg

ahoodin
February 9th, 2009, 03:13 PM
Agreed! Who has time to wade through poorly formatted code.