I am having a very similar issue.
Here is my Arduino code:
int Dpin4 = 5;
int Dval4 = 0;
int ledPin = 13;
int val = 0;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // declare the ledPin as an OUTPUT
pinMode(Dpin4, INPUT);
}
void loop() {
Dval4 = digitalRead(Dpin4);
val = Serial.read();
if(val == '1')
{
if(Dval4 == LOW)
{
digitalWrite(ledPin, HIGH);
Serial.print(4);
}
else
{
Serial.print(0);
}
Serial.println();
}
}
What I am trying to do is read from a light sensor. An optical fiber channels light to a sensor. I read a HIGH or LOW from the digital inputs the sensors are wired to.
In the code above, I am only testing this for one sensor, namely Dval4 to the pin 5 (sorry for the poor naming convention).
Here is my python code:
import serial
ser = serial.Serial('COM4', 9600)
while True:
ser.write('1');
x = ser.readline()
The problem with the python code is that it just hangs at readline(). If I do a x = ser.readline() before the while loop, it works fine. The other interesting thing is when I do:
ser.write('1'); x=ser.readline(); print x
x will have nothing the first time (meaning it only gets the \r\n and when I repeat the command, it works fine (meaning it gets 4\r\n).
What is happening here? Is there some issue with the ser.write('1') call I am making and whether its getting to the Arduino board fast enough?
Any help would be greatly appreciated.