问题
Recently, I am trying to make sort of "light control" on Arduino. I use Raspberry Pi to send the control message via serial port (USB cable).Here is the Arduino code :
int redled = 12;
int whiteled = 48;
void setup()
{
Serial.begin(9600);
pinMode(redled,OUTPUT);
pinMode(whiteled,OUTPUT);
}
void loop()
{
if(Serial.available())
{
char cmd = Serial.read();
switch(cmd)
{
case'r':
digitalWrite(redled,HIGH);
delay(2000);
digitalWrite(redled,LOW);
break;
case'w':
digitalWrite(whiteled,HIGH);
delay(2000);
digitalWrite(whiteled,LOW);
break;
}
}
else
{
Serial.println("hello pi");
delay(1000);
}
}
After that, I used pySerial from Python interpreter to control the pins, and everything was working fine. Here is a piece of interpreter output:
Python 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial
>>> ser = serial.Serial('/dev/ttyACM0',9600)
>>> x = ser.read(10)
>>> print 'x = ',x
x = hellhello
>>> ser.write('w') #white led turn on and off
1
>>> ser.close()
>>>
Everything worked fine and led did turn on and off, so I decided to write a simple Python script to do the same:
import serial
import time
ser = serial.Serial('/dev/ttyACM0',9600)
x = ser.read(10)
print 'x = ',x
time.sleep(2)
ser.write('w')
ser.close()
The following is the execution command and result:
pi@raspberrypi ~ $ python serialtest.py
x = helello pi
It only appeared the string from Arduino, but no led turn on at all. It looks like everything should be fine, so I don't know what the problem can be. I already search some articles and add "time.sleep(2)" before "ser.write()", but it still couldn't work.I would appreciate any help, many thanks in advance!
UPDATE : I made the controller send me back the data it was receiving and it looks like it isn't receiving anything when I am running the script, but receives everything when I send the data from the interpreter. The code of the arduino code now looks like this:
int redled = 12;
int whiteled = 48;
void setup()
{
Serial.begin(9600);
pinMode(redled,OUTPUT);
pinMode(whiteled,OUTPUT);
}
void loop()
{
if(Serial.available())
{
char cmd = Serial.read();
switch(cmd)
{
case'r':
digitalWrite(redled,HIGH);
delay(2000);
digitalWrite(redled,LOW);
Serial.println("Cmd received");
break;
case'w':
digitalWrite(whiteled,HIGH);
delay(2000);
digitalWrite(whiteled,LOW);
Serial.println("Cmd received");
break;
}
}
}
回答1:
The problem is that it takes some time to initiate the port. add a sleep of 5 seconds immediately after ser = serial.Serial()
time.sleep(5)
来源:https://stackoverflow.com/questions/28192190/pyserial-write-works-fine-in-python-interpreter-but-not-python-script