Hi,
I'm trying to send 1's and 0's from a C program on my PC(Windows 7) to my Arduino Diciemillia(ATMega 168) to light up and turn off the LED on pin 13.
The C code compiles and executes successfully and turns on the LED when I input 1 but crashes immediately after that and i get a write access violation error and some random address after that.
This is a real problem because in the end I intend to use the arduino to control 2 servos with the values of the angles coming as a continuous stream from the C code.
Heres the C code and arduino sketch:
C Code:
#include<windows.h>
#include<stdlib.h>
#include<stdio.h>
#include<ctype.h>
char ch;
char data_buf[1];
HANDLE h;
DCB dcb={0};
int i;
void main()
{
h=CreateFile("\\\\.\\COM15",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if(h==INVALID_HANDLE_VALUE)
{
if(GetLastError()==ERROR_FILE_NOT_FOUND)
{
printf("Serial port doesnt exist. Rectify and restart");
}
printf("Error opening port. Restart");
}
//FillMemory(&dcb,sizeof(dcb),0);
dcb.DCBlength=sizeof(dcb);
if(!BuildCommDCB("9600,n,8,1", &dcb))
{
printf("Error Building DCB. Rectify and restart");
}
else if(!SetCommState(h,&dcb))
{
printf("Error setting state to port. Rectify and restart");
}
dcb.BaudRate=9600;
//dcb.fParity=false;
dcb.ByteSize=8;
dcb.Parity=0 ;
dcb.StopBits=0 ;
//dcb.fAbortOnError = true;
//dcb.fOutX=true ;
dcb.fOutxDsrFlow = 0;
dcb.fOutxCtsFlow = 0;
dcb.fRtsControl=0 ;
dcb.fOutxCtsFlow=0 ;
dcb.fOutxDsrFlow=0 ;
dcb.fDtrControl=0 ;
printf("Enter 1 to turn on the LED, 0 to turn it off and 2 to exit");
//for(i=0;i<10;i++)
//{
ch=getchar();
data_buf[0]=ch;
while(ch!=2)
{
if(!WriteFile(h,data_buf,1,NULL,NULL))
{
printf("Error writing to device. Will ext");
exit(1);
}
}
//}
CloseHandle(h);
}
How long do you suppose it will take to fill up the serial buffer on the PC side? The Arduino resets when the C app opens the serial port. You immediately begin bombarding with with data. The Arduino's serial buffer will overflow long before the Arduino can process the incoming data. After each byte that is processed, you send a reply to the PC, but never process that reply. Perhaps the C app doesn't just silently discard data, like the Arduino does.
I just used Serial.println()'s as cross checks to see if any data is arriving or not to arduino.So i just printed it out on the serial monitor.Is that causing the problem?
I just removed all the Serial.println() functions. Its still giving a write access violation and VC++ is pointing the error at the WriteFile function. =(
Thanks a lot!
Got it to work!
There was a null pointer error bcause of the last two NULL's passed to WriteFile()!
Even i dont like C the only reason we are using it because we are usinga software called ARToolKit for motion control and its in C!!!