Pyserial problem with Arduino - works with the Python shell but not in a program

只愿长相守 提交于 2019-12-18 04:49:07

问题


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.

Now I made a Python program

import serial
ser = serial.Serial("COM4",9600)
ser.write("H")

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.

Any ideas?


回答1:


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.

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.




回答2:


I had the same problem and it works if I add a delay of about 2 seconds from opening the serial connection to writing on it, 1 second was not enough.




回答3:


Just to make it a bit more clear I'll modify the code so everyone can see what needs to be added!

import serial
import time
ser = serial.Serial("COM4",9600)
time.sleep(3)
ser.write("H")

Adding in a sleep statment helps to let the serial open up without any problems!




回答4:


Assuming you are using an Arduino Uno

The USB port and the Uno serial bus exposed on pins 1 and 0 share the same RX/TX lines. I suggest getting a USB to TTL adapter like the one here so that you can communicate to the Arduino without using the USB port. The Arduino IDE has its own method for disengaging from the USB driver such that a virtual serial port can be created. Have your Ardunio use SoftwareSerial instead.

Here is an example I found on the internet where somebody had clashing bus issues.



来源:https://stackoverflow.com/questions/1618141/pyserial-problem-with-arduino-works-with-the-python-shell-but-not-in-a-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!