Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PySerial App runs in shell, by not py script

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?

like image 334
Jeremy Blum Avatar asked Feb 20 '10 05:02

Jeremy Blum


2 Answers

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!

like image 67
Jeremy Blum Avatar answered Sep 28 '22 02:09

Jeremy Blum


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
like image 43
yogansh Avatar answered Sep 28 '22 01:09

yogansh