Reputation: 21
I want to retrieve data through the serial port from Arduino with the C programming language in realtime. The program at Arduino :
void setup() {
Serial.begin(9600);
}
int i=1;
void loop() {
Serial.println(i);
delay(1000);
i++;
}
Programs in c language:
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
int main()
{
HANDLE hComm;
hComm=CreateFile("\\\\.\\COM3",GENERIC_READ | GENERIC_WRITE, 0, NULL,OPEN_EXISTING,0,NULL );
BOOL Status;
DCB dcbSerialParams={0};
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
Status=GetCommState(hComm,&dcbSerialParams);
dcbSerialParams.BaudRate=CBR_9600;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
Status=SetCommState(hComm,&dcbSerialParams);
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout=50;
timeouts.ReadTotalTimeoutConstant=50;
timeouts.ReadTotalTimeoutMultiplier=10;
timeouts.WriteTotalTimeoutConstant=50;
timeouts.WriteTotalTimeoutMultiplier=10;
Status=SetCommMask(hComm,EV_RXCHAR);
DWORD dwEventMask;
Status=WaitCommEvent(hComm,&dwEventMask,NULL);
char TempChar;
char SerialBuffer[256];
DWORD NoBytesRead;
int i=0;
FILE *fp;
fp=fopen("data.txt", "w");
do{
Status=ReadFile(hComm,&TempChar,sizeof(TempChar),&NoBytesRead,NULL);
SerialBuffer[i]=TempChar;
printf("%c",SerialBuffer[i]);
fprintf(fp, "%c", SerialBuffer[i]);
i++;
}
while(1);
CloseHandle(hComm);
return 0;
}
When running, an error occurs:
Please help, what is the problem that caused the error? What is the correct program?
Upvotes: 0
Views: 145
Reputation: 28950
As mentioned in the comments 0xc0000005 is an access violation.
Without putting much time into reading your code (you should debug it yourself) I'd say it in general is a bad idea to increment a variable within an infinite loop if that variable is used to index an array.
Also you never check of your ReadFile actually succeeds.
There is a reason why C books do not cover reading files befor indexing arrays and using control structures properly.
Upvotes: 1