I am trying to send arguments to my arduino. so i made this code:
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
HANDLE serialPortHandler;
char *comPort[8] = {"1", "2", "3", "4", "5", "6", "7", "8"};
char comPortName[5] = "COM";
int i = 1;
int openPort(char *name){
serialPortHandler = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if(serialPortHandler == INVALID_HANDLE_VALUE){
return -1;
}else{
DCB dcb;
FillMemory(&dcb, sizeof(dcb), 0);
if (!GetCommState(serialPortHandler, &dcb)){
return -1;
}
dcb.BaudRate = CBR_9600 ;
if (!SetCommState(serialPortHandler, &dcb)){
return -1;
}
}
return 1;
}
int writePort(char *lpBuf,DWORD dwToWrite){
DWORD dwWritten;
if(WriteFile(serialPortHandler, lpBuf, dwToWrite, &dwWritten, NULL)){
while(dwWritten < dwToWrite);
printf("User: %s, %d", lpBuf, dwWritten);
return 0;
}else{
printf("Error");
CloseHandle(serialPortHandler);
return 1;
}
return 0;
}
int main(int argc, char *argv[]){
if(argc != 2)
return 1;
strcat(comPortName, comPort[0]);
while(openPort(comPortName) < 0 && i < sizeof(comPort) / sizeof(int)){
comPortName[3] = *comPort[i];
//printf("%s", comPortName);
i++;
Sleep(0);
}if(i >= sizeof(comPort) / sizeof(int)){
printf("Cannot Find Port");
scanf("%d");
return 1;
}
printf("Port %s Is Opened - BaudRate 9600\n", comPortName);
printf("Sent Frequency: %s\n", argv[1]);
writePort(argv[1], strlen(argv[1]));
}
But it only works if i run it on debug mode and wait for a few moments at WriteFile.If i run it from cmd it doesnt output to my arduino.
The WriteFile function has the ability to run asynchronously. Have you checked for this case?
From:https://msdn.microsoft.com/en-us/library/windows/desktop/aa365747(v=vs.85).aspx
If the function fails, or is completing asynchronously, the return value is zero (FALSE). To get extended error information, call the GetLastError function.
The WriteFile function returns when one of the following conditions occur:
The number of bytes requested is written.
A read operation releases buffer space on the read end of the pipe (if the write was blocked). For more information, see the Pipes section.
An asynchronous handle is being used and the write is occurring asynchronously.
An error occurs.
(Meta: Can't blockquote a bullet list, I guess)
The problem was it takes time to initiate these two things:
1.SetCommState(serialPortHandler, &dcb)
so i added Sleep before and it fixed the problem.
Related
Suppose I create a named pipe on a Linux system:
$ mkfifo my_pipe
The next thing I want to do is write a little monitor program which tries to read() from my_pipe, but times out after a while. In the following pseudo-code, I have used a fictional function wait_for_avail(fd, timeout_ms):
int fd = open("my_pipe", O_RDONLY);
while (1) {
//Fictional wait_for_avail(fd, timeout_ms). Is there a real function
//that has this behaviour?
int rc = wait_for_avail(fd, 500);
if (rc == 1) {
char buf[64];
read(fd, buf, 64);
//do something with buf
} else {
fprintf(stderr, "Timed out while reading from my_pipe\n");
//do something else in the program
}
}
I thought poll with the POLLIN flag might work, but it does not. From my simple trials, I have found that it simply waits until another process has opened the named pipe for writing (but not for data to be available, i.e. read() would not block). By the way, for some reason, poll ignores your timeout and just seems to block forever until another process opens the pipe.
The only other solution I can think of is to open() the file with O_NONBLOCK, and sort of manually watch the time going by as I constantly try read()ing with a count of 0 bytes.
Is there a better solution out there?
EDIT: The process I have here blocks on opening the named pipe. However, if you use the O_NONBLOCK flag, the file opens right away. At that point, poll() can be used to wait (with an optional timeout) for the other end of the pipe to be opened for writing.
However, this still does have the behaviour of implementing a timeout for the read() function. It still appears to block as soon as you call read() (even if the pipe was opened with O_NONBLOCK)
Your idea about opening the fifo in non-blocking mode is correct. If you do that, poll()/select()/etc. can be used to wait for the other end to be opened, or timeout first.
The following example program just runs in an infinite loop waiting for other programs to write to my_pipe and echos the written text, with the occasional status update when there's no data or writer:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
while (1) {
int fd = open("my_pipe", O_RDONLY | O_NONBLOCK);
if (fd < 0) {
perror("open");
return EXIT_FAILURE;
}
struct pollfd waiter = {.fd = fd, .events = POLLIN};
while (1) {
// 10 second timeout
switch (poll(&waiter, 1, 10 * 1000)) {
case 0:
puts("The fifo timed out.");
break;
case 1:
if (waiter.revents & POLLIN) {
char buffer[BUFSIZ];
ssize_t len = read(fd, buffer, sizeof buffer - 1);
if (len < 0) {
perror("read");
return EXIT_FAILURE;
}
buffer[len] = '\0';
printf("Read: %s\n", buffer);
} else if (waiter.revents & POLLERR) {
puts("Got a POLLERR");
return EXIT_FAILURE;
} else if (waiter.revents & POLLHUP) {
// Writer closed its end
goto closed;
}
break;
default:
perror("poll");
return EXIT_FAILURE;
}
}
closed:
if (close(fd) < 0) {
perror("close");
return EXIT_FAILURE;
}
}
}
After a lot of help and patience from #Shawn, I managed to come up with an answer I found satisfying. Here are the contents of a file called pipe_watcher.c:
#include <stdio.h> //printf etc.
#include <errno.h> //errno
#include <string.h> //perror
#include <signal.h> //SIGALRM, sigaction, sigset
#include <time.h> //timer_create, timer_settime
#include <fcntl.h> //open, O_RDONLY
#include <unistd.h> //close
/* This code demonstrates how you can monitor a named pipe with timeouts on the
* read() system call.
*
* Compile with:
*
* gcc -o pipe_watcher pipe_watcher.c -lrt
*
* And run with:
*
* ./pipe_watcher PIPE_FILENAME
*/
//Just needed a dummy handler
void sigalrm_handler(int s) {
return;
}
int main(int argc, char **argv) {
//Check input argument count
if (argc != 2) {
puts("Usage:\n");
puts("\t./pipe_watcher PIPE_FILENAME");
return -1;
}
//Create a timer object
timer_t clk;
int rc = timer_create(CLOCK_REALTIME, NULL, &clk);
if (rc < 0) {
perror("Could not create CLOCK_REALTIME timer");
return -1;
}
//Create some time values for use with timer_settime
struct itimerspec half_second = {
.it_interval = {.tv_sec = 0, .tv_nsec = 0},
.it_value = {.tv_sec = 0, .tv_nsec = 500000000}
};
struct itimerspec stop_timer = {
.it_interval = {.tv_sec = 0, .tv_nsec = 0},
.it_value = {.tv_sec = 0, .tv_nsec = 0}
};
//Set up SIGALRM handler
struct sigaction sigalrm_act = {
.sa_handler = sigalrm_handler,
.sa_flags = 0
};
sigemptyset(&sigalrm_act.sa_mask);
rc = sigaction(SIGALRM, &sigalrm_act, NULL);
if (rc < 0) {
perror("Could not register signal handler");
timer_delete(clk);
return -1;
}
//We deliberately omit O_NONBLOCK, since we want blocking behaviour on
//read(), and we're willing to tolerate dealing with the blocking open()
int fd = open(argv[1], O_RDONLY);
if (fd < 0) {
char msg[80];
sprintf(msg, "Could not open [%s]", argv[1]);
perror(msg);
timer_delete(clk);
return -1;
}
puts("File opened");
while (1) {
//Buffer to read() into
char buf[80];
int len;
//Set up a timer to interrupt the read() call after 0.5 seconds
timer_settime(clk, 0, &half_second, NULL);
//Issue read() system call
len = read(fd, buf, 80);
//Check for errors. The else-if checks for EOF
if (len < 0) {
if (errno == EINTR) {
//This means we got interrupted by the timer; we can keep going
fprintf(stderr, "Timeout, trying again\n");
continue;
} else {
//Something really bad happened. Time to quit.
perror("read() failed");
//No point waiting for the timer anymore
timer_settime(clk, 0, &stop_timer, NULL);
break;
}
} else if (len == 0) {
puts("Reached end of file");
break;
}
//No error or EOF; stop the timer and print the results
timer_settime(clk, 0, &stop_timer, NULL);
write(STDOUT_FILENO, buf, len);
}
//Cleanup after ourselves
timer_delete(clk);
close(fd);
return 0;
}
The technique is to set up a timer before a (blocking) read() call. Then, we can simply check the return value of read() to see if it was interrupted due to a timeout, if a general error occurred, if EOF was reached, or if it successfully read data.
There's only one snag: you can't open the file in non-blocking mode; this causes open() to block until another process opens the pipe for writing. However, in my application this is actually a desirable feature. You could also set up SIGALRM to enforce a timeout on the open(), or maybe do it in another thread.
In fact, this technique should work with any other system call, so I might put together a little helper library to make this pattern easier to use.
EDIT
One more thing: it is very important to not use the SA_RESTART flag when registering the signal handler. Otherwise, even if a system call is interrupted by a signal, Linux will try it again after the signal is handled.
I have been coding on C/C++ for a while but now I have faced a major problem which I can not resolve. I am trying to communicate with COM port. First I am sending data with WriteFile(), this part works.But when it comes to receiving an answer from the port with ReadFile(), I do not get anything.
Here is the code:
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
#include <conio.h>
int main(int argc, char *argv[])
{
int n=0;
DCB dcb={0};
HANDLE hCom;
BOOL fSuccess;
char *pcCommPort = "COM3";
DWORD dwBytesRead=0;
DWORD dwRead;
DWORD dwBytesWrite=0;
DWORD dwWrite=0;
/***************************************CommTimeouts******************************************/
COMMTIMEOUTS timeouts={0};
timeouts.ReadIntervalTimeout=200;
//timeouts.ReadTotalTimeoutConstant=1;
//timeouts.ReadTotalTimeoutMultiplier=1;
timeouts.WriteTotalTimeoutConstant=2;
//timeouts.WriteTotalTimeoutMultiplier=1;
/*******************************************Handle*******************************************/
hCom = CreateFile( pcCommPort,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ, // must be opened with exclusive-access
NULL, // no security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
FILE_ATTRIBUTE_NORMAL, // not overlapped I/O
NULL // hTemplate must be NULL for comm devices
);
/***************************************SET*UP*COM*PORT**************************************/
if (hCom == INVALID_HANDLE_VALUE)
{
printf ("CreateFile failed with error %d.\n", GetLastError());
CloseHandle(hCom);
return (1);
}
if(!SetCommTimeouts(hCom, &timeouts))
{
/*Well, then an error occurred*/
}
fSuccess = GetCommState(hCom, &dcb);
if (!fSuccess)
{
/*More Error Handling*/
printf ("GetCommState failed with error %d.\n", GetLastError());
CloseHandle(hCom);
return (2);
}
dcb.BaudRate = 9600; // set the baud rate
dcb.ByteSize = 8; // data size, xmit, and rcv
dcb.Parity = EVENPARITY; // no parity bit
dcb.StopBits = ONESTOPBIT; // one stop bit
fSuccess = SetCommState(hCom, &dcb);
if (!fSuccess)
{
printf ("SetCommState failed. Error: %d.\n", GetLastError());
CloseHandle(hCom);
return (3);
}
printf ("Serial port %s successfully configured.\n", pcCommPort);
// return (0);
/*************************************Writing************************************************/
char bytes_to_send[] = {'36'};
if(!WriteFile(hCom, bytes_to_send, 2, &dwBytesWrite, NULL))
{
fprintf(stderr, "Error\n");
CloseHandle(hCom);
return 1;
}
printf("dwBytesWrite = %d | %x\n", dwBytesWrite, (dwBytesWrite));
/*************************************Reading************************************************/
char bytes_to_receive[7];
if(!ReadFile(hCom, bytes_to_receive, 7, &dwBytesRead, NULL)){
printf ("SetCommState failed. Error: %d.\n", GetLastError());
CloseHandle(hCom);
return (4);
} else {
printf("Bytes read %d -> %d\n",dwBytesRead, bytes_to_receive);}
/********************************************************************************************/
CloseHandle(hCom);
return(0);
}
There is a file pointer, both for read and write. After the WriteFile it is at the end of the file. If you try to read from it, you will read at the end of the file. To read what you just wrote you have to reposition the file pointer at the start of the file, using the SetFilePointer function:
SetFilePointer(hCom, 0, NULL, FILE_BEGIN);
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.
I can't send chunks of data bigger than 420 bytes. For example if i try to send 421 bytes, i can't read it with ReadFile. If I check the maislot info with GetMailslotInfo( handleRead, 0, &msgSize, 0, 0 ); then msgSize will always be -1.
So this will never work for me:
err = WriteFile( handleWrite, wcharArrayToSend, 421, &numBytesWritten, NULL );
Does anyone know a reason for this behavior? Is this a normal behavior?
Per MSDN's documentation on mailslots:
The data in a mailslot message can be in any form, but cannot be larger than 424 bytes when sent between computers.
To send messages that are larger than 424 bytes between computers, use named pipes or Windows Sockets instead.
I'm not sure what you've done wrong, but mailslots can definitely handle messages greater than 421 bytes. Here's some test code (that runs successfully):
Server:
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE mailslot = CreateMailslot("\\\\.\\mailslot\\myslot",
0,
MAILSLOT_WAIT_FOREVER,
NULL);
if (mailslot == INVALID_HANDLE_VALUE) {
fprintf(stderr, "Unable to create mailslot.");
return 1;
}
char buffer[2048];
OVERLAPPED ovlp = {0};
ovlp.hEvent = CreateEvent(NULL, false, false, NULL);
if (ovlp.hEvent == NULL) {
fprintf(stderr, "Unable to create Event.");
return 2;
}
DWORD read;
do {
ReadFile(mailslot, buffer, sizeof(buffer), &read, &ovlp);
buffer[read] = 0;
WaitForSingleObject(ovlp.hEvent, INFINITE);
printf("%s\n", buffer);
} while (strcmp(buffer, "exit"));
return 0;
}
Client:
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE mailslot = CreateFile("\\\\.\\mailslot\\myslot",
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_ALWAYS,
0,
NULL);
if (INVALID_HANDLE_VALUE == mailslot) {
fprintf(stderr, "Unable to open mailslot.\n");
return 1;
}
char buffer[2048];
DWORD written;
for (int i=0; i<1024; i++)
buffer[i] = 'A' + (i%26);
buffer[1023] = '\0';
size_t len = strlen(buffer);
WriteFile(mailslot, buffer, len, &written, NULL);
WriteFile(mailslot, "exit", 4, &written, NULL);
return 0;
}
Result:
E:\C\source>mailslot
ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZAB
CDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCD
EFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEF
GHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGH
IJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ
KLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKL
MNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOP
QRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQR
STUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRST
UVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX
YZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHI
exit
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.