cliechti | 2297814 | 2009-07-21 01:58:11 +0000 | [diff] [blame] | 1 | ==================== |
| 2 | Short introduction |
| 3 | ==================== |
| 4 | |
cliechti | 86e8787 | 2009-07-21 13:32:45 +0000 | [diff] [blame^] | 5 | Opening serial ports |
| 6 | ==================== |
| 7 | |
cliechti | 2297814 | 2009-07-21 01:58:11 +0000 | [diff] [blame] | 8 | Open port 0 at "9600,8,N,1", no timeout:: |
| 9 | |
| 10 | >>> import serial |
| 11 | >>> ser = serial.Serial(0) # open first serial port |
| 12 | >>> print ser.portstr # check which port was really used |
| 13 | >>> ser.write("hello") # write a string |
| 14 | >>> ser.close() # close port |
| 15 | |
| 16 | Open named port at "19200,8,N,1", 1s timeout:: |
| 17 | |
| 18 | >>> ser = serial.Serial('/dev/ttyS1', 19200, timeout=1) |
| 19 | >>> x = ser.read() # read one byte |
| 20 | >>> s = ser.read(10) # read up to ten bytes (timeout) |
| 21 | >>> line = ser.readline() # read a '\n' terminated line |
| 22 | >>> ser.close() |
| 23 | |
| 24 | Open second port at "38400,8,E,1", non blocking HW handshaking:: |
| 25 | |
| 26 | >>> ser = serial.Serial(1, 38400, timeout=0, |
| 27 | ... parity=serial.PARITY_EVEN, rtscts=1) |
| 28 | >>> s = ser.read(100) # read up to one hundred bytes |
| 29 | ... # or as much is in the buffer |
| 30 | |
cliechti | 86e8787 | 2009-07-21 13:32:45 +0000 | [diff] [blame^] | 31 | Configuring ports later |
| 32 | ======================= |
| 33 | |
cliechti | 2297814 | 2009-07-21 01:58:11 +0000 | [diff] [blame] | 34 | Get a Serial instance and configure/open it later:: |
| 35 | |
| 36 | >>> ser = serial.Serial() |
| 37 | >>> ser.baudrate = 19200 |
| 38 | >>> ser.port = 0 |
| 39 | >>> ser |
| 40 | Serial<id=0xa81c10, open=False>(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0) |
| 41 | >>> ser.open() |
| 42 | >>> ser.isOpen() |
| 43 | True |
| 44 | >>> ser.close() |
| 45 | >>> ser.isOpen() |
| 46 | False |
| 47 | |
cliechti | 86e8787 | 2009-07-21 13:32:45 +0000 | [diff] [blame^] | 48 | Readline |
| 49 | ======== |
cliechti | 2297814 | 2009-07-21 01:58:11 +0000 | [diff] [blame] | 50 | Be carefully when using "readline". Do specify a timeout when opening the |
| 51 | serial port otherwise it could block forever if no newline character is |
| 52 | received. Also note that "readlines" only works with a timeout. "readlines" |
| 53 | depends on having a timeout and interprets that as EOF (end of file). It raises |
cliechti | 86e8787 | 2009-07-21 13:32:45 +0000 | [diff] [blame^] | 54 | an exception if the port is not opened correctly. |
| 55 | |
| 56 | Do also have a look at the example files in the examples directory in the |
| 57 | source distribution or online. |