views:

203

answers:

3

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?

A: 

show how you run it? take note not to name your python script as serial.py. Are you on *nix or Windows?

ghostdog74
I've tried running the script in two ways, one by opening it up with IDLE and hitting "Run Module", and two, just by double clicking it. When I click it, a cmd window opens for a moment, then closes, and nothing happens. I'm running on windows, but if you think it might make a difference, I could try it on linux too...
sciguy14
open up cmd.exe on windows. That's the "terminal". Then type `python myscript.py` and see what happens
ghostdog74
Executing via cmd does not work either. And, I tried it on linux and got the same response. It works when I type it manually into the python console, but not when run as an executable file. So, I assume there must be some kind of weird timing problem with the code... Any other ideas?
sciguy14
A: 

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.

mtasic
no luck with this method either...
sciguy14
Anybody have any other ideas! I've seen other people with the same problem all across the web, and nobody seems to have an answer!
sciguy14
+2  A: 

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!

sciguy14
The reset is required for programming the arduino. You can modify your arduino to not reset on serial attach if necessary.
Dustin