How to open serial port with Python

Hi ,guys

I came across some port problem when I try to use python to do some tests. My serial port is COM5, actually.
When I use processing, I open the serial port by writing:
String portstr = Serial.list()[2]; port = new Serial(this, portstr, 9600);

but what about python? I write the code:SERIAL_PORT = "COM5";
ser = serial.Serial(SERIAL_PORT, 9600, timeout=1);
But unfortunately it does not work, can you give me some advices?
Thanks~

Your python syntax is correct, so I think you have a problem in your connexion, or on the other side.

Can you tell us more about your project? What are you trying to do? I guess you try to dialog with Arduino; what is the code on that side?

Actually, I try to run the codes written by someone who used LEDs to show election result. But I found there is an problem on serial port.

I just modify this code: SERIAL_PORT = "/dev/ttyUSB0"
into SERIAL_PORT = "COM5", but it doesn't work.. Thanks~

This is the full codes:

#!/usr/bin/python

Quick and dirty AmbientOrb code to scrape and report election results

most of this code came from:

http://www.exothermia.net/monkeys_and_robots/2008/11/03/code-to-scape-cnncom-election-results/#more-34

import serial
import urllib2
import re
import time
from optparse import OptionParser

SERIAL_PORT = "/dev/ttyUSB0"
BAUD = 9600
UPDATE = 600

class ElectionWon(Exception):
pass

class CNN(object):
def init(self):
self.url = "President - Election Center 2008 - Elections & Politics from CNN.com"

def get(self):
"""return the electoral balance
(dpopular, delectoral), (rpopular, relectoral)
"""
u = urllib2.urlopen(self.url)
for line in u.readlines():
res = re.search(r'var CNN_NData=(.*?);', line)
if res is not None:
data = res.group(1)
data = data.replace("true", "True")
data = data.replace("false", "False")
data = eval(data)

d,r = None, None
for candidate in data['P']['candidates']:
if candidate['party'] == 'D':
d = candidate['votes'], candidate['evotes']
if candidate['winner']:
raise ElectionWon("D")
elif candidate['party'] == 'R':
r = candidate['votes'], candidate['evotes']
if candidate['winner']:
raise ElectionWon("R")

return d,r

def normalize(d,r, interval=0.5):
"""normalize to
-1 => democrat winning
+1 => republican winning
abs(1.0) is having "2interval" higher percent than the other guy
"""
if d+r == 0: return 0.0
rnorm = 2.0
(1.0r/(d+r) - 0.5) / (2interval)
if rnorm > 1.0: rnorm = 1.0
if rnorm < -1.0: rnorm = -1.0
return rnorm

def calc_color(value):
"""
Assumes a normaized -1:1 range and returns 0000FF through FF0000
Only manipulates the Red and Blue values
-1 ==> 0000FF
0 ==> 000000
1 ==> FF0000
"""
red = 0
blue = 0

if(value < 0):
blue = (value * -128) + 127
if(value > 0):
red = (value * 128) + 127

return('%02x00%02x' % (red, blue))

if name=='main':
POP_VOTE = 0
ELECTORAL_VOTE = 1

parser = OptionParser()
parser.add_option("-e", "--electoral", dest="vote_sel", action="store_const",
const=ELECTORAL_VOTE, help="Report based on electoral vote (default)")
parser.add_option("-p", "--popular", dest="vote_sel", action="store_const",
const=POP_VOTE, help="Report based on popular vote")

(options, args) = parser.parse_args()

vote_sel = options.vote_sel
if(vote_sel is None):
vote_sel = ELECTORAL_VOTE

cnn = CNN()
ser = serial.Serial(SERIAL_PORT, BAUD, timeout=1)
time.sleep(10)
try:
while True:
(d,r) = cnn.get()
ser.write("#" + calc_color(normalize(d[vote_sel], r[vote_sel])))
time.sleep(UPDATE)
except ElectionWon, elewon:
if(elewon.message == 'D'):
ser.write("%0000FF")
elif(elewon.message == 'R'):
ser.write("%FF0000")

while True:
time.sleep(UPDATE)

Are you sure that 'COM5' is the correct serial port? Did you try with other values, here?

When I was working on my version of the same project, serial port problems didn't just "have a problem" or "not work." Python gives you a pretty detailed description of the error. If you post the error, we'll have a much better idea of what's wrong.

According to the pyserial documentation, you should be on the right path...assuming that COM5 even exists. Maybe it's working great but your Arduino code is wrong. Tell us the error message from Python and that'll be a start.

Funny project, BTW :wink:

Why are you trying to open a USB port to read in a url?
Do you have a modem connected to a USB port????

As far as I have understand, there is a vote machine connected to the serial port (BTW, /dev/ttyUSB0 is the entry for a USB-to-Serial converter). The vote information are downloaded from the url "http://www.cnn.com/ELECTION/2008/results/president", using urllib2, and sent to the vote machine using pyserial module.

I just wanted to chime in here another approach to getting python and an arduino script talking:
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1230026454/0#0

If we could ever embed the proxy stuff in the ide then it would really simplify connecting from the "non serial port aware yet network friendly" languages.