问题描述
好的,所以我很肯定我的 Arduino 电路和它的代码是正确的.我知道这一点,因为当我使用 Arduino IDE 中内置的串行监视器并发送H"时,LED 会亮起,而当我发送L"时,LED 会关闭.
All right, so I am positive my Arduino circuit is correct and the code for it. I know this because when I use the serial monitor built into the Arduino IDE and send 'H' an LED lights up, when I send 'L' that LED turns off.
现在我做了一个 Python 程序
Now I made a Python program
import serial
ser = serial.Serial("COM4",9600)
ser.write("H")
当我运行代码时,LED 会闪烁一秒钟然后又熄灭.但是,当我在 shell 中分别执行这些行时,它的工作原理就像它应该做的那样.
When I run the code the LED blinks on for a second then goes back off. However when I do each of these lines separately in the shell it works just like it is supposed to.
有什么想法吗?
推荐答案
当你打开串口时,这会导致 Arduino 重置.由于 Arduino 需要一些时间来启动,所有输入都进入 bitbucket(或者可能进入引导加载程序,上帝知道它会做什么).如果你插入一个睡眠,你等待 Arduino 出现所以你的序列号.这就是它以交互方式工作的原因;您正在等待软件启动所需的 1.5 秒.
When you open the serial port, this causes the Arduino to reset. Since the Arduino takes some time to bootup, all the input goes to the bitbucket (or probably to the bootloader which does god knows what with it). If you insert a sleep, you wait for the Arduino to come up so your serial code. This is why it works interactively; you were waiting the 1.5 seconds needed for the software to come up.
我确认打开串口会重置我的Arduino Uno;我闪烁了一个程序,该程序将使 setup()
例程中的 LED 闪烁——调用 open("/dev/ttyACM0")
足以触发重置.恕我直言,这是串行支持中令人困惑且未记录的问题.
I confirmed that opening the serial port resets my Arduino Uno; I flashed a program which will blink the LED from the setup()
routine -- calling open("/dev/ttyACM0")
was sufficient to trigger the reset. This is IMHO a confusing and undocumented wrinkle in the serial support.
这篇关于Arduino 的 Pyserial 问题 - 适用于 Python shell 但不适用于程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!