早上好!最近我买了一块 Arduino 板来在我的房间里做某种“灯光控制”。这是我写的固件代码:
int control = 0;
int pin = 0;
void setup()
{
Serial.begin(9600);
for(pin = 0; pin <= 13; pin++) pinMode(pin, OUTPUT);
}
void loop()
{
control = Serial.read();
if (control > 0 && control <= 13) digitalWrite(control, HIGH);
if (control < 256 && control >= (256-13)) digitalWrite((256-control), LOW);
}
之后,我使用 Python 解释器中的 pySerial 来控制引脚,一切正常。这是一段解释器输出:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial
>>> ser = serial.Serial('/dev/ttyUSB0', 9600)
>>> ser.write(chr(12))
>>> # The light turned on here
...
>>> ser.write(chr(256-12))
>>> # The light turned off here
...
然后我决定编写一个简单的 Python 脚本来做同样的事情:
#!/usr/bin/env python
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write(chr(12))
time.sleep(1)
ser.write(chr(256-12))
但它根本不起作用!Arduino 显示在我启动脚本期间收到了一些东西,但没有任何反应。这是脚本的一段 strace 输出:
open("/dev/ttyUSB0", O_RDWR|O_NOCTTY|O_NONBLOCK) = 3
ioctl(3, SNDCTL_TMR_TIMEBASE or TCGETS, {B9600 -opost -isig -icanon -echo ...}) = 0
ioctl(3, SNDCTL_TMR_TIMEBASE or TCGETS, {B9600 -opost -isig -icanon -echo ...}) = 0
ioctl(3, SNDCTL_TMR_TIMEBASE or TCGETS, {B9600 -opost -isig -icanon -echo ...}) = 0
ioctl(3, SNDCTL_TMR_START or TCSETS, {B9600 -opost -isig -icanon -echo ...}) = 0
ioctl(3, SNDCTL_TMR_TIMEBASE or TCGETS, {B9600 -opost -isig -icanon -echo ...}) = 0
open("/dev/ttyUSB0", O_RDWR|O_NOCTTY|O_NONBLOCK) = 4
ioctl(4, SNDCTL_TMR_TIMEBASE or TCGETS, {B9600 -opost -isig -icanon -echo ...}) = 0
ioctl(4, SNDCTL_TMR_TIMEBASE or TCGETS, {B9600 -opost -isig -icanon -echo ...}) = 0
ioctl(4, SNDCTL_TMR_TIMEBASE or TCGETS, {B9600 -opost -isig -icanon -echo ...}) = 0
ioctl(4, SNDCTL_TMR_START or TCSETS, {B9600 -opost -isig -icanon -echo ...}) = 0
ioctl(4, SNDCTL_TMR_TIMEBASE or TCGETS, {B9600 -opost -isig -icanon -echo ...}) = 0
write(4, "\f", 1) = 1
close(4) = 0
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f45cf4c88f0}, {0x4d9820, [], SA_RESTORER, 0x7f45cf4c88f0}, 8) = 0
exit_group(0) = ?
看起来一切都应该没问题,所以我不知道问题出在哪里。我会很感激任何帮助,非常感谢提前!
PS 当我在 PDB 下运行程序时,一切正常。一只海森堡。
更新:我让控制器将它收到的数据发回给我,当我运行脚本时它似乎没有收到任何东西,但是当我从解释器发送数据时它收到了所有东西。固件的代码现在如下所示:
int control = 0;
int pin = 0;
void setup()
{
Serial.begin(9600);
for(pin = 0; pin <= 13; pin++) pinMode(pin, OUTPUT);
}
void loop()
{
if (Serial.available() > 0)
{
control = Serial.read();
if (control <= 13) digitalWrite(control, HIGH);
if (control < 256 && control >= (256-13)) digitalWrite((256-control), LOW);
Serial.println(control);
}
}