Reading from serial port in C, having problems with ReadFile maybe? - c

Well I've been at this program for maybe four hours. I've been trying to create a little program to read what my arduino Uno is spitting out through the serial port.
What I find odd is that the program works only AFTER I've launched the arduino IDE's built in serial monitor. Perhaps this is an issue with initializing the port correctly?
If someone could help me out it'd be much appreciated. The program seems to hang during ReadFile, so maybe there's an issue with permissions...
#include Windows.h>
#include stdio.h>
#include tchar.h>//Removed to allow for stackoverflow format
void printCommState(DCB d);
int main() {
DCB dcb = { 0 };
HANDLE hPort;
BOOL success;
TCHAR *commPort = TEXT("COM3");
char buffer[40] = { 0 };
DWORD dwBytesRead = 0;
DWORD dwBytesWrite = 0;
int l;
/*COMMTIMEOUTS cTimeOut;
cTimeOut.ReadIntervalTimeout = 50;
cTimeOut.ReadTotalTimeoutConstant = 50;
cTimeOut.ReadTotalTimeoutMultiplier = 10;
cTimeOut.WriteTotalTimeoutConstant = 50;
cTimeOut.WriteTotalTimeoutMultiplier = 10;*/
dcb.DCBlength = sizeof(DCB);
dcb.BaudRate = CBR_9600;//Found on microsofts website
dcb.ByteSize = DATABITS_8;// standardized number?
dcb.Parity = NOPARITY;// found in comp management
dcb.StopBits = 1;
/*dcb.fBinary = 1;
dcb.fDtrControl = 1;
dcb.fTXContinueOnXoff = 1;
dcb.fRtsControl = 1;
dcb.XonLim = 2048;
dcb.XoffLim = 512;
dcb.XoffChar = 2;*/
//dcb.fDtrControl = DTR_CONTROL_DISABLE;//maybe unnecessary?
printCommState(dcb);
hPort = CreateFile(commPort, // This comm port is defined by TCHAR so that we can use TEXT() LPFILENAME
GENERIC_READ | GENERIC_WRITE,//DesiredAccess
0,//dwShareMode
NULL,//LPSecurity
CREATE_NEW| OPEN_EXISTING,//dwCreationDisposition
0,//Flags and attributes
NULL);//hTemplateFile
if (hPort == INVALID_HANDLE_VALUE) {
printf("CreateFile failed with the error %d.\n", GetLastError());
scanf_s("%d", &l);
return 1;
}
success = GetCommState(hPort, &dcb);
if (!success) {
printf("GetCommState failed with the error %d.\n ", GetLastError());
scanf_s("%d", &l);
return 2;
}
success = SetCommState(hPort, &dcb);
if (!success) {
printf("SetCommState failed with error %d.\n", GetLastError());
scanf_s("%d", &l);
return 3;
}
/*TIME TO READ STUFF*/
while (GetCommState(hPort, &dcb)) {
printf("We're in the while statement\n");
//+=+=+=+=+=+POSSIBLE PROBLEM?
if (ReadFile(hPort, buffer, 39, &dwBytesRead, NULL)) {
//hFile,lpBuffer,NumberofBytesToRead,LPnumberofbytestoread,lpOverlapped
printf("We're in the ifReadFile Statement!\n");
for (int j = 0; j < sizeof(buffer); j++) {
printf("in the for loop!\n");
printf("%c", buffer[j]);
}
printf("\n");
}
if (!ReadFile(hPort, &buffer, 39, &dwBytesRead, NULL)) {
printf("Error with ReadFile %d\n.", GetLastError());
}
}
scanf_s("%d", &l);
CloseHandle(hPort);
return 0;
}
void printCommState(DCB d) {
printf("\nBaudRate: %d\tByteSize: %d\tParity: %d\tStopBits: %d\n",
d.BaudRate,
d.ByteSize,
d.Parity,
d.StopBits);
}

The issue lies in the GetCommState line of the code
GetCommState code function
Here we have it setting the DCB to the settings returned by that function, so by adding another DCB (dcbRecieving, for instance as an example ) just as an error-catching device and having GetCommState point to that other DCB, we can keep our error catching DCB and set our original to the other one, or set the new parameters after the if statement.
Anyways, thanks a ton!

Related

writing and reading data to and from a serial port (to an intel galileo) windows c

I'm building a cnc machine for a school project, it consists of an Intel galileo with a shield that controls stepper motors, this is controlled by a program on a windows machine(windows 7), what the program basically does is read a text file containing gcode and then sends it line by line to the Galileo, the Galileo then takes that line breaks it down into coordinates and instructions, moves the spindle to where it needs to go and when the instruction is finished it sends a message back to the computer through serial telling it that its finished, the computer then sends the next line of code and the process is repeated.
so far I can read the gcode file and send it line by line (using a keypress to send each line) to the galileo and everything works fine. my problem is reading from the galileo I have tried a few methods with no joy. this is what I think is closest to what I should be doing. I wont post the whole source because I think it will be just to much to read through, ive posted the main() which has all the setup functions and the function that is supposed to read the serial.
/************************************************************************************************************
application for controling galileo or arduino cnc machine
by brendan scullion
10/11/2014
**********************************************************************************************************/
#include <string.h>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#include <ctype.h>
#include <conio.h>
#include "functions.h"
int main()
{
system("COLOR 1F");
// Declare variables and structures
unsigned char text_to_send[MAX_PATH];
unsigned char digits[MAX_PATH];
int baudrate = 19200;
int dev_num = 50;
char dev_name[MAX_PATH];
HANDLE hSerial;
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
DCB dcbSerialParams = {0};
COMMTIMEOUTS timeouts = {0};
printf("Searching serial ports...\n");
while(dev_num >= 0)
{
printf("\r ");
printf("\rTrying COM%d...", dev_num);
sprintf(dev_name, "\\\\.\\COM%d", dev_num);
hSerial = CreateFile(
dev_name,
GENERIC_READ|GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL );
if (hSerial == INVALID_HANDLE_VALUE) dev_num--;
else break;
}
if (dev_num < 0)
{
printf("No serial port available\n");
return 1;
}
printf("OK\n");
// Set device parameters (38400 baud, 1 start bit,
// 1 stop bit, no parity)
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (GetCommState(hSerial, &dcbSerialParams) == 0)
{
printf("Error getting device state\n");
CloseHandle(hSerial);
return 1;
}
//dcbSerialParams.BaudRate = CBR_38400;
dcbSerialParams.BaudRate = baudrate;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if(SetCommState(hSerial, &dcbSerialParams) == 0)
{
printf("Error setting device parameters\n");
CloseHandle(hSerial);
return 1;
}
// Set COM port timeout settings
timeouts.ReadIntervalTimeout = 1;
timeouts.ReadTotalTimeoutConstant = 1;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if(SetCommTimeouts(hSerial, &timeouts) == 0)
{
printf("Error setting timeouts\n");
CloseHandle(hSerial);
return 1;
}
char *cmd = NULL;
char *para1 = NULL;
char *para2 = NULL;
char *para3 = NULL;
char comPort[10];
float baudRate;
int keepGoing = 1;
unsigned char message[MAX_STRING_LENGHT];
//*********************************************************************************************************************
char cmdLine[200];
heading();
while(keepGoing == 1)
{
printf(">>");
gets(cmdLine);
cmd = strtok(cmdLine, " ");
if(cmd!=false)
{
if(cmd != NULL)
{
para1 = strtok(NULL, " ");
}
else if(para1 != NULL)
{
para2 = strtok(NULL, " ");
}
else if(para2 != NULL)
{
para3 = strtok(NULL, " ");
}
if(strcmp(cmd, "help")== 0)
{
help();
}
else if(strcmp(cmd, "comset")== 0)
{
setupComs(comPort, baudRate);
}
else if(strcmp(cmd, "getg")== 0)
{
getgcode(hSerial,text_to_send,dev_name);
}
else if(strcmp(cmd, "readserial")== 0)
{
read_serial(hSerial, message, dev_name);
}
else if(strcmp(cmd, "offset")==0)
{
getOffset(hSerial, text_to_send, dev_name);
}
else if(strcmp(cmd, "setup") == 0)
{
setup(hSerial, text_to_send, dev_name);
}
else if(strcmp(cmd, "exit") == 0)
{
keepGoing = 0;
}
else
{
printf("Unknown command!\n");
}
printf("\n");
}
}
// Close serial port
printf("Closing serial port...");
if (CloseHandle(hSerial) == 0)
{
printf("Error\n");
return 1;
}
printf("OK\n");
return 0;
}
and the function for reading
void read_serial(HANDLE hComm, HANDLE screen, char *message, char *devName )
{
char buffer[MAX_STRING_LENGHT];
unsigned char ch;
DWORD bytes_recieved = MAX_STRING_LENGHT, written = 0;
strcpy(buffer,""); //empty buffer
strcpy(buffer,"");
while(buffer!=NULL){ // wait untill serail message revieved
ReadFile(hComm, &buffer,sizeof(buffer), // read serial
&bytes_recieved, NULL );
if(bytes_recieved){ // if something to read
WriteFile(screen, buffer, bytes_recieved, &written, NULL);
strcpy(message, buffer);
printf("%s", message);
if(kbhit()){
ch = getch();
if(ch== 'q')
break;
}
}
}
}
i can post the entire source code if anybody wants to have a look at it
In read_serial, you can try replacing &buffer with buffer in the call to ReadFile. Name of a character array should be a pointer to the first element of the array.
What i would do is i would frame every message that goes from and to the Galileo board in a simple and useful protocol. For example i would use STX and ETX to frame and send messages from the Windows 7 via serial to the board, use ACK NAK to acknowledge the received packet and use SYN for signalling end of execution of a line on Galileo.
With the above framing you can construct receive and send functions where you can wait for specific characters (ETX,STX,SYN,ACK,etc) and exit once you have a full frame or an control character.

What does it mean for ReadFile to be "completing asynchronously", and why is it an error?

I'm (synchronously) reading serial input in Windows using ReadFile(), but instead of waiting for the serial port to have input then returning that as I thought it should, ReadFile() instead returns immediately with a value of FALSE, and a GetLastError() of 0. (Yes, I'm certain I have the right error code and am not making syscalls in between).
The ReadFile() documentation says that when the function "is completing asynchronously, the return value is zero (FALSE)." How is it that a synchronous read can be completing asychronously? Why would this be an error? It's worth noting that the data read is garbage data, as one might expect.
More generally, how can I force ReadFile() to behave like a simple synchronous read of a serial port, or at least behave something like the UNIX read()?
Edit: Here is some source code:
HANDLE my_connect(char *port_name)
{
DCB dcb;
COMMTIMEOUTS timeouts;
HANDLE hdl = CreateFile(port_name,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
GetCommState(port_name, &dcb);
dcb.BaudRate = 115200;
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;
dcb.Parity = NOPARITY;
if(SetCommState(hdl, &dcb) == 0)
{
fprintf(stderr, "SetCommState failed with error code %d.\n",
GetLastError());
return (HANDLE) -1;
}
/* TODO: Set a variable timeout. */
timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 5000; /* wait 5s for input */
timeouts.WriteTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 5000;
if(SetCommTimeouts(hdl, &timeouts) == 0)
{
fprintf(stderr, "SetCommTimeouts failed with error code %d.\n",
GetLastError());
return (HANDLE) -1;
}
return hdl;
}
int my_disconnect(HANDLE hdl)
{
return CloseHandle(hdl);
}
int my_send(HANDLE hdl, char *cmd)
{
DWORD nb = 0;
if(WriteFile(hdl, cmd, strlen(cmd), &nb, NULL) == 0)
{
fprintf(stderr, "WriteFile failed with error code %d.\n",
GetLastError());
return -1;
}
return (int) nb;
}
int my_receive(HANDLE hdl, char *dst, int dstlen)
{
int i;
DWORD r;
BOOL err;
char c = '\0';
for (i = 0; i < dstlen; err = ReadFile(hdl, &c, 1, &r, NULL))
{
if (err == 0)
{
fprintf(stderr, "ReadFile failed with error code %d.\n",
GetLastError());
return -1;
}
if (r > 0)
{
dst[i++] = c;
if (c == '\n') break;
}
}
if (i == dstlen)
{
fprintf(stderr, "Error: read destination buffer not large enough.\
Recommended size: 256B. Your size: %dB.\n", dstlen);
return -1;
}
else
{
dst[i] = '\0'; /* null-terminate the string. */
}
return i;
}
And my test code:
HANDLE hdl = my_connect("COM4");
char *cmd = "/home\n"; /* basic command */
char reply[256];
my_send(hdl, cmd);
my_receive(hdl, reply, 256);
puts(reply);
It's not completing asynchronously. If it were, GetLastError would return ERROR_IO_PENDING.
To do synchronous I/O, open the file without FILE_FLAG_OVERLAPPED.
It should not be possible for ReadFile to fail without a valid GetLastError code. ReadFile only returns false when the driver sets a non-success status code.

Serial communication between GSM module and computer

I am working on a project having GSM module and it is also communicating serially with computer.
I have written a code in C on Visual Studio 2010 to transmit and receive data serially.
Code is given below:-
#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <commdlg.h>
int nread,nwrite;
int main()
{
COMMTIMEOUTS timeouts;
COMMCONFIG dcbSerialParams;
char *words, *buffRead, *buffWrite;
DWORD dwBytesWritten,dwBytesRead;
HANDLE hSerial= CreateFile(L"COM1", GENERIC_READ | GENERIC_WRITE,
0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if ( hSerial == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_FILE_NOT_FOUND)
{
printf(" serial port does not exist \n");
}
printf(" some other error occured. Inform user.\n");
}
//DCB dcbSerialParams ;
//GetCommState( hSerial, &dcbSerialParams.dcb);
if (!GetCommState(hSerial, &dcbSerialParams.dcb))
{
printf("error getting state \n");
}
dcbSerialParams.dcb.DCBlength = sizeof(dcbSerialParams.dcb);
dcbSerialParams.dcb.BaudRate = CBR_9600;
dcbSerialParams.dcb.ByteSize = 8;
dcbSerialParams.dcb.StopBits = ONESTOPBIT;
dcbSerialParams.dcb.Parity = NOPARITY;
dcbSerialParams.dcb.fBinary = TRUE;
dcbSerialParams.dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcbSerialParams.dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcbSerialParams.dcb.fOutxCtsFlow = FALSE;
dcbSerialParams.dcb.fOutxDsrFlow = FALSE;
dcbSerialParams.dcb.fDsrSensitivity= FALSE;
dcbSerialParams.dcb.fAbortOnError = TRUE;
if (!SetCommState(hSerial, &dcbSerialParams.dcb))
{
printf(" error setting serial port state \n");
}
GetCommTimeouts(hSerial,&timeouts);
//COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = 1000;
timeouts.ReadTotalTimeoutConstant = 1000;
timeouts.ReadTotalTimeoutMultiplier = 1000;
timeouts.WriteTotalTimeoutConstant = 1000;
timeouts.WriteTotalTimeoutMultiplier= 1000;
if(!SetCommTimeouts(hSerial, &timeouts))
{
printf("error setting port state \n");
}
while(1)
{
//****************Write Operation*********************//
char data_tx[]="at\r";
words=&data_tx[0];
nwrite = strlen(words);
buffWrite = words;
dwBytesWritten = 0;
if (!WriteFile(hSerial, buffWrite, nwrite, &dwBytesWritten, NULL))
{
printf("error writing to output buffer \n");
}
printf("Data written to write buffer is\n %s \n",buffWrite);
//***************Read Operation******************//
dwBytesRead = 0;
nread = strlen(words);
buffRead = new char[nread +1];
memset(buffRead, 0, nread+1); // ensure that string will be null-terminated
if (!ReadFile(hSerial, buffRead, nread, &dwBytesRead, NULL))
{
printf("error reading from input buffer \n");
}
printf("Data read from read buffer is \n %s \n ",buffRead);
Sleep(10000);
}
CloseHandle(hSerial);
}
When command "at\r" is transmitted from computer to GSM module it receive it should respond to it by sending OK.
Now I am getting only O. If I send "at\r" again I am getting K.
I have verified it on hyper terminal GSM module is working properly.If I send "at" and enter it responds with OK.
Also I have verified my C code on other program it is working properly.
I want to know why it is not working properly with GSM module.
You need to call sleep before reading the result. 250 ms is more than enough

Interacting with a serial port using the C functions fopen, fread, and fwrite?

I have been attempting to communicate with a device of mine via an RS232 serial port(in my case it is COM6). My code is supposed to write a string of ascii values to the device and then read the response, however I cannot seem to get any response. The program seems to work relatively fine when I have it write and read to a file in my computer, but not for when I designate COM6. Here is the latest edition of my code:
using namespace std;
const char ASCII[ ]= "0123456789ABCDEF";
char *Checksum (char *buffer)
{
static char Hex[10];
static int a1, a2;
register unsigned int i;
int sum;
printf("%s \n", buffer);
sum = 256;
for ( i=0 ; i<strlen(buffer) ; i++ )
{
sum-=buffer[i];
if ( sum<0 )
sum+= 256;
}
a1 = (sum & 0xF0) >> 4;
a2 = sum & 0x0F;
Hex[0] = ASCII[a1];
Hex[1] = ASCII[a2];
Hex[2] = 0;
printf("the checksum is %s \n",Hex);
return(Hex);
}
int main()
{
char data[80], input[80], *data2;
char *response;
DCB dcb;
bool retVal;
DWORD dwBytesTransferred;
DWORD byteswritten;
printf("the variable response is initially: %d\n", response);
dcb.BaudRate = CBR_19200; //19200 Baud
dcb.ByteSize = 8; //8 data bits
dcb.Parity = NOPARITY; //no parity
dcb.StopBits = ONESTOPBIT; //1 stop
//New open port area
HANDLE hPort;
if ((hPort = CreateFile ( "\\\\.\\COM6",
GENERIC_READ | GENERIC_WRITE,
0, // exclusive access
NULL, // no security attrs
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL)) != INVALID_HANDLE_VALUE)
{
printf("SUCCESS opening the port\n");// success
}
//GetCommState
DCB Dcb;
GetCommState (hPort, &Dcb);
Dcb.BaudRate = CBR_19200;
Dcb.StopBits = ONESTOPBIT;
Dcb.ByteSize = 8;
Dcb.Parity = NOPARITY;
Dcb.fParity = 0;
Dcb.fOutxCtsFlow = 0;
Dcb.fOutxDsrFlow = 0;
Dcb.fDsrSensitivity = 0;
Dcb.fTXContinueOnXoff = TRUE;
Dcb.fOutX = 0;
Dcb.fInX = 0;
Dcb.fNull = 0;
Dcb.fErrorChar = 0;
Dcb.fAbortOnError = 0;
Dcb.fRtsControl = RTS_CONTROL_DISABLE;
Dcb.fDtrControl = DTR_CONTROL_DISABLE;
//Flushing
FlushFileBuffers( hPort );
PurgeComm (hPort, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
COMSTAT comStat;
DWORD dwErrorFlags;
ClearCommError ( hPort, &dwErrorFlags, &comStat );
//NEW commtimeouts area
COMMTIMEOUTS CommTimeOuts;
DWORD dwTimeout = 3000; // <- set timeout in milliseconds
if(!dwTimeout)
{ // Don't use timeout -> Read the bytes already in input buffer and return immediately
CommTimeOuts.ReadIntervalTimeout = MAXDWORD;
CommTimeOuts.ReadTotalTimeoutConstant = 0;
} else
{ // Use given timeout, wait until the requested number of bytes are read - or timeout
CommTimeOuts.ReadIntervalTimeout = 0;
CommTimeOuts.ReadTotalTimeoutConstant = dwTimeout;
}
CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutConstant = 0;
SetCommTimeouts (hPort, &CommTimeOuts);
printf("insert ASCII code string you wish to send:");
scanf("%s", input);
strcpy(data, "{0x02}");
strcat(data, input);
printf("%s \n", data);
data2=Checksum(data);
strcat(data, data2);
strcat(data, "{0x03}");
printf("the final sent message will be: %s \n",data);
retVal = WriteFile(hPort,data, strlen(data), &byteswritten, NULL);
printf("Number of bytes written: %d\n", byteswritten);
printf("Write Success? %d\n", retVal);
retVal=ReadFile (hPort, &response, 20, &dwBytesTransferred, NULL);
printf("Read Success? %d\n", retVal);
printf("Port Response: %d\n", response);
free(response);
return 0;
}
Summary of latest discoveries: Using the Free Serial Port Monitor that Habi suggested I now know for sure that WriteFile is functioning correctly and COM6 is in receiving the message. I'm still looking for a crossover cable to double check that the message is being transferred across the line. I figure while I try to figure that out if someone could look at this new edition and tell me if there is anything wrong, particularly in relation to the ReadFile function, it would be much appreciated. It bothers me that the Free Serial Port software is only showing the data passed from my computer and not a response from the device at all. =\
Instead of
"COM6"
try
"\\\\.\\COM6"
And I would recommend to use CreateFile(), ReadFile(), WriteFile().
To open the COM port try this:
HANDLE hComDev;
if ((hComDev = CreateFile ( "\\\\.\\COM6",
GENERIC_READ | GENERIC_WRITE,
0, // exclusive access
NULL, // no security attrs
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL)) != INVALID_HANDLE_VALUE)
{
// success
}
It seems that calling GetCommState() is missing in your code. Try this to configure the COM port:
DCB Dcb;
GetCommState (hComDev, &Dcb);
Dcb.BaudRate = CBR_19200;
Dcb.StopBits = ONESTOPBIT;
Dcb.ByteSize = 8;
Dcb.Parity = NOPARITY;
Dcb.fParity = 0;
Dcb.fOutxCtsFlow = 0;
Dcb.fOutxDsrFlow = 0;
Dcb.fDsrSensitivity = 0;
Dcb.fTXContinueOnXoff = TRUE;
Dcb.fOutX = 0;
Dcb.fInX = 0;
Dcb.fNull = 0;
Dcb.fErrorChar = 0;
Dcb.fAbortOnError = 0;
Dcb.fRtsControl = RTS_CONTROL_DISABLE;
Dcb.fDtrControl = DTR_CONTROL_DISABLE;
And to initially clear the COM port, I would do a reset like this before starting to send and receive bytes:
FlushFileBuffers( hComDev );
PurgeComm (hComDev, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
COMSTAT comStat;
DWORD dwErrorFlags;
ClearCommError ( hComDev, &dwErrorFlags, &comStat );
You ask for timeouts? To configure time outs try this:
COMMTIMEOUTS CommTimeOuts;
DWORD dwTimeout = .... // <- set timeout in milliseconds
if(!dwTimeout)
{ // Don't use timeout -> Read the bytes already in input buffer and return immediately
CommTimeOuts.ReadIntervalTimeout = MAXDWORD;
CommTimeOuts.ReadTotalTimeoutConstant = 0;
}
else
{ // Use given timeout, wait until the requested number of bytes are read - or timeout
CommTimeOuts.ReadIntervalTimeout = 0;
CommTimeOuts.ReadTotalTimeoutConstant = dwTimeout;
}
CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutConstant = 0;
SetCommTimeouts (hComDev, &CommTimeOuts);
My code is supposed to write a string of ascii values to the device
and then read the response, however I cannot seem to get any response.
Are you sure that the bytes are really sent to the device? If you have the option, take a oscilloscope and monitor the PC's Tx line. Send some bytes and check baudrate and start/stop bits. If you have no hardware to monitor this signal, take a software based serial monitor, e.g. Free Serial Port Monitor. I have no experience with that kind of software tools but they should show you at least that the Windows drivers try to send something via the COM port of your choice.
Greetings
Habi
If you have been trying for a month then I would recommend you look at the windows function CreateFile. I have used this for serial port comms and it works fine. You might also want to look at the DCB struct and GetCommState and SetCommState functions to configure the serial port. WriteFile can be used to write data to the serial port. I cannot post all of my code as it owned by my company, but this should help you get started.
Also ClearCommError may be of help to you to query if any data is on the serial port buffer when you are waiting to read from it.
I encountered a similar problem and found the other answers helpful, but I was not receiving characters.
Ultimately I found the problem was with RTS_CONTROL_DISABLE or DTR_CONTROL_DISABLE.
By having RTS and DTR held low, the program was indicating to the modem/device that the program was not ready to receive data, and the modem was respecting this signal and dutifully not sending.
By changing these to RTS_CONTROL_ENABLE and DTR_CONTROL_ENABLE, the program indicates to the modem that data may be sent, and I began receiving characters. Not all devices respect these signals so it may work in some configurations with DTR and RTS disabled -- the modem may send data anyway.
It's possible, but you need to config com port via cmd mode command,
and there is no way to config timeout value via cmd command.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
// use mode command to config port
// mode com2 dtr=off rts=off baud=9600 parity=N data=8 stop=1 to=on
FILE *f = fopen("\\\\.\\COM2", "wb+");
setvbuf(f, NULL, _IONBF, 0);
if(f == NULL) return -1;
while(1)
{
static char p[5];
int cnt = fread(&p, 1, sizeof(p), f);
printf("read[%d]:%s\n", cnt, p);
if(p[0] == '0') break;
memset(p, 0, sizeof(p));
}
fclose(f);
return 0;
}

Serial communication not working. Readfile goes wrong

After hours of browsing and reading, I still can't figure out why my code isn't working. I saw similar code snippets on different websites, but I can't seem to get it to work. The writing part is working, but the reading goes wrong. Every 'real character' is followed by three null terminators. Writing a string of 19 characters works and the FPGA I am using gives the correct data on the display. The FPGA should reverse the input and send this pack to the serial port. In the Hyperterminal this is working without any problem.
Can someone maybe point me on my mistake and tell me what I am doing wrong?
Thanks in advance =)
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <commdlg.h>
//#include <windef.h>
#define BUFFERLENGTH 19
void writeToSerial(char *line, HANDLE hSerial, DWORD dwBytesWritten);
void printBuffer(char * buffRead, DWORD dwBytesRead);
int main(){
HANDLE hSerial;
COMMTIMEOUTS timeouts;
COMMCONFIG dcbSerialParams;
char *line, *buffWrite, *buffRead;
DWORD dwBytesWritten, dwBytesRead;
/* Create a handle to the serial port */
hSerial = CreateFile("COM3",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
/* Check if the handle is valid */
if(hSerial == INVALID_HANDLE_VALUE){
if(GetLastError() == ERROR_FILE_NOT_FOUND){
printf("Serial port does not exist \n");
}else{
printf("Port occupied. Please close terminals!\n");
}
}else{
printf("Handle created\n");
/* Check the state of the comm port */
if(!GetCommState(hSerial, &dcbSerialParams.dcb)){
printf("Error getting state \n");
}else{
printf("Port available\n");
/* Configure the settings of the port */
dcbSerialParams.dcb.DCBlength = sizeof(dcbSerialParams.dcb);
/* Basic settings */
dcbSerialParams.dcb.BaudRate = CBR_57600;
dcbSerialParams.dcb.ByteSize = 8;
dcbSerialParams.dcb.StopBits = ONESTOPBIT;
dcbSerialParams.dcb.Parity = NOPARITY;
/* Misc settings */
dcbSerialParams.dcb.fBinary = TRUE;
dcbSerialParams.dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcbSerialParams.dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcbSerialParams.dcb.fOutxCtsFlow = FALSE;
dcbSerialParams.dcb.fOutxDsrFlow = FALSE;
dcbSerialParams.dcb.fDsrSensitivity= FALSE;
dcbSerialParams.dcb.fAbortOnError = TRUE;
/* Apply the settings */
if(!SetCommState(hSerial, &dcbSerialParams.dcb)){
printf("Error setting serial port state \n");
}else{
printf("Settings applied\n");
GetCommTimeouts(hSerial,&timeouts);
//COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier= 10;
if(!SetCommTimeouts(hSerial, &timeouts)){
printf("Error setting port state \n");
}else{
/* Ready for communication */
line = "Something else\r";
//****************Write Operation*********************//
writeToSerial(line, hSerial, dwBytesWritten);
//***************Read Operation******************//
if(ReadFile(hSerial, buffRead, BUFFERLENGTH, &dwBytesRead, NULL)){
printBuffer(buffRead, dwBytesRead);
}
}
}
}
}
CloseHandle(hSerial);
system("PAUSE");
return 0;
}
void printBuffer(char * buffRead, DWORD dwBytesRead){
int j;
for(j = 0; j < dwBytesRead; j++){
if(buffRead[j] != '\0'){
printf("%d: %c\n", j, buffRead[j]);
}
}
}
void writeToSerial(char *line, HANDLE hSerial, DWORD dwBytesWritten){
WriteFile(hSerial, line, 19, &dwBytesWritten,NULL);
if(dwBytesWritten){
printf("Writing success, you wrote '%s'\n", line);
}else{
printf("Writing went wrong =[\n");
}
}
In this line:
if(ReadFile(hSerial, buffRead, BUFFERLENGTH, &dwBytesRead, NULL))
the buffRead parameter is an uninitialised pointer. Change the declaration to:
char *line, *buffWrite, buffRead [BUFFERLENGTH+1];
Hyper terminal probably doesn't display null characters so it's possible that your fpga is actually sending them.
You could try testing it with Br#y Terminal in hex mode, or looking at the line with an oscilloscope.

Resources