PySerial App runs in shell, by not py script

2020-02-09 19:27发布

I have a very simple python script that uses pySerial to send data over the serial port to my Arduino. When I execute this line-by-line in the python shell, it works just fine, but when I put it in a ".py" file, and try to run it, nothing happens. Though the serial lights on my UART do flash. So something is getting through, but it's garbage (I checked).

Here is the simple code.

import serial

ser = serial.Serial('COM3',9600,timeout=.2)
ser.write('A')
ser.close()

I've already tried adding sleeps, but nothing seems to be fixing it. Any ideas?

6条回答
Explosion°爆炸
2楼-- · 2020-02-09 19:56

OK, I've figured it out!

It's necessary to use code like this before performing the write:

time.sleep(1)
ser.setDTR(level=0)
time.sleep(1)

Otherwise, the arduino automatically resets upon receiving a serial connection for some reason. yay!

查看更多
爷、活的狠高调
3楼-- · 2020-02-09 19:57

I've noticed that if you're on Windows 64-bit then the pyserial simply does not work. I'm using Python 2.7, and after installing the x86 version via the administrator account, and using the mentioned code above

time.sleep(1)

ser.setDTR(level=0)

time.sleep(1)

appended before the write, and remembering the close the port afterwards, I was able to get it to work as a script and not just through the CLI. Also, make sure that you run the python GUI or command line as administrator. This also made a successful difference for me. Also, make sure the serial monitor on the Arduino is closed before running the code.

查看更多
小情绪 Triste *
4楼-- · 2020-02-09 20:00

Maybe be stupid, but try to type only "myscript.py" in cmd.exe, if you are on Windows. I've noticed that on Windows, you do not need to type "python" before script name. This is of course for standard CPython installation on Windows.

查看更多
贪生不怕死
5楼-- · 2020-02-09 20:02

In my case the following worked.

    time.sleep(1)
    ser.setDTR(level=1) 
    time.sleep(1)
查看更多
冷血范
6楼-- · 2020-02-09 20:07
import serial
import time 

ser = serial.Serial('/dev/ttyACM1', 9600, timeout=1)
time.sleep(3)      # this will needed for initializing arduino
serial.write(b'1') # b is necessary for byte
查看更多
Summer. ? 凉城
7楼-- · 2020-02-09 20:09

May I suggest one more sleep, this time, after you close the serial port.

import serial

ser = serial.Serial('COM3',9600,timeout=.2)

ser.write('A')

ser.close()

time.sleep(3000) 

//for a first test, give a whopping 3 seconds

//sleep(100), 100 ms (0.1 second) may be enough in final product

The rationale is that the computers are becoming so fast (exceed 1 millions time the performance of my first x86 at 4.77 MHz, probably one hundred thousand time faster than the Space Shuttle on board original computer) that it may have time to start Python, execute millions of instructions... close the console, all that before a single byte may have been sent on the serial port.

查看更多
登录 后发表回答