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);
}
Arduino Sketch:
const int ledPin=13;
int inp;
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop()
{
if(Serial.available()>0)
{
inp=Serial.read();
Serial.println(inp);
if(inp=='1')
digitalWrite(ledPin, HIGH);
else
digitalWrite(ledPin, LOW);
}
else
Serial.println("No input available");
}