psSerial: how to write a single byte value to the serial port?

Bengt Richter bokr at oz.net
Wed Nov 17 06:08:52 EST 2004


On 17 Nov 2004 00:57:23 -0800, mr_ravi_patil at yahoo.com (SoftwareTester) wrote:

>http://pyserial.sourceforge.net/ 
>example shows how to write string to serial port.
>
>
>#Open port 0 at "9600,8,N,1", no timeout
>
>>>> import serial
>>>> ser = serial.Serial(0) #open first serial 
>>>> ser.write("hello") #write a string
>>>> ser.close() #close port
>
>how do i write a single byte value to the serial port?

How is your single byte represented? A hex representation of the
_numeric_ code for a single character? E.g., you may need to convert
to a character string of length one (which the chr function does)
in order to pass it to ser.write (which apparently accepts the
5-char string "hello" all right).

 >>> 65
 65
 >>> chr(65)
 'A'
 >>> 0x41
 65
 >>> chr(0x41)
 'A'

thus, perhaps something like

    ser.write(chr(0x41))

or

    byte = chr(0x41)
    ser.write(byte)

(Untested, just judging from the example outputting "hello" above ;-).

Regards,
Bengt Richter



More information about the Python-list mailing list