Casey Bralla wrote:
I'd like to read ASCII data from a serial port, but (once again) I'm having
trouble getting started. (Can't seem to find the basic level of docs to
get going <sigh>)
I'd like to use only standard "built-in" modules if possible.
Could somebody offer a simple code-snippet to get me started reading from a
serial port?
Thanks!
Here's some code which should help to get you started, I thought rather
than leaving you in the hands of Google (which is not your friend, no
more than MaccyDs is, as Flavour Flav said - 'Don;t believe the hype'),
this may be helpful :
Here's a bit cut out from my own code using pySerial - some of the
variables are not detailed but you can get the idea :
self.__objSeria lPort = serial.Serial(s elf._dctConnect ionParams
['ConnectionID'],
self._dctConnec tionParams
['BaudRate'],
self._dctConnec tionParams
['DataBits'],
self._dctConnec tionParams
['Parity'],
self._dctConnec tionParams
['StopBits'],
10000, #TimeOut
int(self._dctCo nnectionParams
['XONXOFF']),
int(self._dctCo nnectionParams
['RTSCTS']))
To send data with pyserial, you do this :
self.__objLock. acquire()
try:
try:
self.__objSeria lPort.write(pSt rMessage)
except StandardError:
self._objCurren tState = self._STATUS_CO NSTS.ERROR
raise
else:
self._objCurren tState = self._STATUS_CO NSTS.CONNECTED
finally:
self.__objLock. release()
The lock on this isn't needed for single threaded code but I would
recommend making a class which deals with the communication in a
thread-safe manner (the connection and disconnection as well - the above
bit should be in a lock as well).
PySerial doesn't have the concept of Observer patterns to get
message coming back in so you'll have to make a polling thread to
observe the serial port when you want to read data, here's the checking
bit - I'll leave the threading and observers up to you:
def __checkSerial(s elf):
"""
Checks serial port to see if anything is available to read
"""
self.__objLock. acquire()
try:
try:
intNoChars = self.__objSeria lPort.inWaiting ()
if intNoChars > 0:
strReceivedStri ng =
self.__objSeria lPort.read(intN oChars)
self.fireNewMes sage(strReceive dString)
except:
raise
finally:
self.__objLock. release()
PySerial wraps all the platform specific stuff you, so you should
really use that, it behaves fairly well - the only real problem is a
lack of an observer interface but you can solve that as detailed above.
One final thing, don;t forget that RS232 isn't really a standard - it's
more like a rumour :-).
Cheers,
Neil
--
Neil Benn
Senior Automation Engineer
Cenix BioScience
BioInnovations Zentrum
Tatzberg 47
D-01307
Dresden
Germany
Tel : +49 (0)351 4173 154
e-mail :
be**@cenix-bioscience.com
Cenix Website :
http://www.cenix-bioscience.com