python serial.write,pySerial write()在Python解释器中可以正常工作,但在Python脚本中不能正常工作...

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;

}

}

}

解决方案

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值