Hi I'm trying to setup communication between an arduino and a raspberry pi through a usb connection but I am encountering a few strange problems that I just can't seem to fathom. I want to send some data from a python script to the arduino then have the arduino light an Led.
Edit* I have resolved this problem but I'm leaving the question here incase it help someone else. The problem was the serial initialization time. See below
Python code.
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=3)
ser.open()
ser.write('1')
arduino code
char serialRecieved;
/*output*/
int ledOne=8;
int ledTwo=12;
int ledThree=13;
/*input pins*/
int thermistor=1;
void setup(){
pinMode(ledOne, OUTPUT);
pinMode(ledTwo, OUTPUT);
pinMode(ledThree, OUTPUT);
Serial.begin(9600);
}
void loop(){
if (Serial.available() > 0) {
serialRecieved=Serial.read();
if(serialRecieved=='1'){lightLed(8,1000);}
if(serialRecieved=='2'){lightLed(12, 1000);}
if(serialRecieved=='3'){lightLed(13 , 1000);}
if(serialRecieved=='4'){sendTemp();}
delay(1);
}
}
void lightLed(int led, int time){
digitalWrite(led, HIGH);
delay(time);
digitalWrite(led, LOW);
}
void sendTemp(){
int temp=analogRead(thermistor);
Serial.print(temp);
}
When I run the python script as far as I can see the led on pin 8 should light up but it doesn't. The strange thing is that if I run a loop(see code below), It works fine except the serial data in the first iteration of the loop is not processed.
this script works except not first loop iteration
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=3);
ser.open();
i=0
while i < 5:
ser.write('1')
ser.write('2')
ser.write('3')
ser.write('4')
time.sleep(1)
serial_data = ser.readline()
print("temperature")
print serial_data
i=i+1
Does anybody have any ideas why the first part of the serial data is either being lost or not read? By the way if you cant tell already I'm new to python, linux pi and arduino , sorry!
EDIT, PROBLEM SOLVED
Ok I just found the problem, it was due to the time it takes to set up the serial connection between the pi and the arduino. If anybody is suffering from the same problem here's the link.
http://playground.arduino.cc/interfacing/python
Now I just need to find out how to know when the serial connection is ready to start sending and receiving data.