Serial Port Communication on Slackware using PySerial


PySerial makes it awfully easy to interact with the serial port using Python. I am going to quickly demonstrate how to use PySerial on Slackware.

Before doing anything, ensure that serial port interrupt is enabled in BIOS. In other words, ensure serial port in not disabled. Source /etc/rc.d/rc.serial to initialise serial port(s) on Slackware after booting in like this:


   # chmod +x /etc/rc.d/rc.serial
   # /etc/rc.d/rc.serial

Install PySerial. A simple


   # python setup.py install

from within the source directory of PySerial would do. Fire up Python interactive shell (I use iPython), and use PySerial like this:


   # python
   >> import serial
   >> s = serial.Serial(
     port=0,
     parity=serial.PARITY_NONE,
     bytesize=serial.EIGHTBITS,
     stopbits=serial.STOPBITS_ONE,
     timeout=3,
     xonxoff=0,
     rtscts=0,
     baudrate=2400
   )
   >> s.write('ayaz')
   >> s.readline()

I would recommend you check out the documentation on PySerial’s homepage.

14 thoughts on “Serial Port Communication on Slackware using PySerial

  1. hi
    i needed a little help from your side. i m new to python.
    i need to do serially receive data and plot it graphically.
    Now, as soon as i plot the command …import serial..it gives me the following error

    Traceback (most recent call last):
    File “”, line 1, in
    import serial
    File “C:\Python25\Lib\site-packages\serial\__init__.py”, line 13, in
    from serialwin32 import *
    File “C:\Python25\Lib\site-packages\serial\serialwin32.py”, line 9, in
    import win32file # The base COM port and file IO functions.
    ImportError: No module named win32file

    can u help
    thanx

  2. Hi, Nimit.

    The module win32file cannot be located in your installation. Either it has not been installed, or it is not in PYTHONPATH (this is a list of directories where Python looks for in order to find modules it needs to load). You can easily ensure which of the two is the problem. Also, here is a somewhat related problem being discussed here: http://bytes.com/forum/thread684683.html

    I hope it helps.

  3. Hi Ayaz

    Thanks for helping me get off the ground here, perhaps you can help me with the next step?

    I am trying to capture the output of a device that prints to the serial port every 2 seconds. I want to capture this data in real time, do some text processing and log it a file (i guess i could store the text as a variable). in a bash script i do it:
    gawk … logfile &
    What’s the technique in python?

    I can open the device in python
    ser = serial.Serial(0,9600)
    ser.readline() gives me the last line, ending with \n\t
    ser.read(4095) gives me a long string made up some kind of buffer with the last couple of minutes’ recordings.

    Should I just run a loop doing a readline() every 2 seconds, or is there an elegant way to do this in python?

    Grateful for your advice
    Ben

    Python noob; Visual-Basic refugee.

  4. Hi,
    Myself Abhishek,
    I am working on serial port device for which I have to write a computer based application too.
    I am using pyserial to write that application.
    I want to know is there any serial receive interrupt is available in pyserial or not..
    what i want is one function which keep on reading what serial port sends in but it should not interrupt the main thread as main thread is control by user to send the data anytime ..
    pleas help me in this ..

    Abhishek

  5. Hi, Ben:

    You can use two features of pySerial to your advantage. One is the
    timeout parameter that you specify when creating a serial.Serial() object. If you set timeout=None, and call method read() or readline(), pySerial will wait forever until there is data in its receive buffer. The second feature is the inWaiting() method. It tells you how many characters are waiting in the receive buffer to be read.

    If you set timeout=None, run a loop, but call readline() once within the loop, your program will block until there are characters in the receive buffer. You can, then, do what you want with the data received. Or, you could loop around a call to inWaiting(), only calling read() or readline() whenever there are characters waiting in the receive buffer.

    I hope this helps.

  6. Hi Ayaz,

    I am trying to get Python to talk to my modem.
    I am having some success but I can’t get the modem to start an Auto Answer sequence.

    It I run Hyperterm and type AT A
    the modem starts to answer.

    But the following code only prints
    Serial(port=’COM1′, baudrate=2400, bytesize=8, parity=’N’, stopbits=1, timeout=3, xonxoff=0, rtscts=1, dsrdtr=1)
    AT A

    I put the time.sleep(3) lines in to give things time to work but it does not help.

    # python
    import serial
    import time

    s = serial.Serial(
    port=0,
    parity=serial.PARITY_NONE,
    bytesize=serial.EIGHTBITS,
    stopbits=serial.STOPBITS_ONE,
    timeout=3,
    xonxoff=0,
    rtscts=1,
    dsrdtr=1,
    baudrate=2400
    )

    time.sleep(3)

    s.write(“AT A”)
    time.sleep(4)
    a = s.readline()
    b = s.readline()
    print s
    print a
    print b

    s.close() #close port

  7. Hi Rupert:

    I am not sure exactly what is going on. Are you positive that the configuration settings, including the baudrate, you are specifying for the serial port are correct? Do they match those set in HyperTerminal?

    You could also use s.isOpen() to rule out whether the port is being opened by PySerial at all or not. Instead of using s.readline(), how about reading specific number of bytes instead: for example, s.read(number_of_bytes).

    I have never tested PySerial on Windows. I have only ever used it on Linux. Please do let me know if it works out or not.

  8. Hi,
    I am working on serial RFID Reader for which i am writing a software application too.

    I am using pyserial to write that application.

    I want the application to be such that it gets the data read from RFID reader only when the card is flashed to the rfid reader.

    I dont want the application to keep on polling for the data from serial port.

    What i want is one function which would read only when there is serial port interrupt and does not keep on polling for the serial port data.

    Please help me on this.

    thanks!

    Regards,

    Saurabh

  9. Hi, Saurabh:

    I don’t know anything within PySerial that exactly matches your requirement. However, if you set the “timeout” parameter to a reasonable enough value, and put the call to Serial.read() or Serial.readline() in an infinite loop, you can get away with needless polling. This is how I did it for my RFID reader project.

  10. We are trying to read data from a microcontroller and interface it through serial port. The output is then displayed in Python using Pyserial or the hyperterminal, the former is more important

    When you touch the input pins of the microcontroller the value changes real time in hyper terminal. But In the case of the pyserial module, even though you touch the input pins, the value does not change. We have actually noticed that python records and prints the input to the pins of the microcontroller before the code is executed in python. Hence, it does not record and print new inputs once the code was been executed.

    What could possibly be wrong with this?

    CODE:
    import serial,csv,sys

    print(‘Tactile Sensing Feedback for Medical Palpation in MIS\n Pyserial Testing Module\n’)
    ch= raw_input(“Enter a to initialize pyserial module, b to quit:”)

    if ch == ‘a’:
    print ‘Initializing Pyserial module’
    ser = serial.Serial(0,baudrate=57600,timeout=0,xonxoff=0)
    print ser.portstr
    ser.flushInput()

    for x in range (0,100):
    s = ser.readline()
    print repr(s)
    ser.close()

    elif ch == ‘b’:
    print ‘closing port……\n’
    quit()

    else:
    print ‘Invalid option please input a or b only’

  11. Ho un problema con Python, in particolare con serial
    Se lo importo nn mi da errori, se scrivi ser=serial.Serial() ancora ok ma quando scrivo ser = serial.Serial(0) mi genera errore C:\Python24\Lib\site-packages\serial\serialutil.py”, line 156, in __init__
    File “C:\Python24\Lib\site-packages\serial\serialwin32.py”, line 55, in open
    win32file.SetupComm(self.hComPort, 4096, 4096)
    SerialException: could not open port: (2, ‘CreateFile’, ‘Impossibile trovare il file specificato.’)

    Come devo fare???

  12. Hi,
    If i import serial, shell is generating a following error can u plz help me to get rid of this:
    Traceback (most recent call last):
    File “”, line 1, in -toplevel-
    import serial
    File “C:\Python24\lib\serial\__init__.py”, line 18, in -toplevel-
    from serialwin32 import *
    File “C:\Python24\lib\serial\serialwin32.py”, line 9, in -toplevel-
    import win32file # The base COM port and file IO functions.
    ImportError: No module named win32file

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s