Thursday, August 23, 2012

Raspberry PI - Serial Port Output

The next thing that I wanted to do is get a Python program talking to the serial port TXD pin on the GPIO header (Pin 8) . Using the info in ref 1, here is what to do to get serial output:
 
To keep from spawning a terminal login session on the header serial port, in  the file

      /etc/inittab

 Comment out the line (using nano as discussed in previous posts)

     # 2:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

You can also stop boot up messages as per the reference, but I did not do this.

Then you need to re-boot (as the login process was spawned already, and will not be spawned until you boot with that line commented out)

    $ sudo shutdown -r now

I then found that you need to install this software package

    $ sudo apt-get install python-serial

When rebooted, log back in and nano up the following Python program as sertest.py (heavily based on ref 1, some neat tricks here, like the code to do a clean exit when you hit ^C on the controlling keyboard):

----------------------------------------------------------------
#!/usr/bin/env python
#
print ("Starting program")
import serial
import time
# import string
#
count = 1
test=serial.Serial("/dev/ttyAMA0",9600)
test.open()
teststring = "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz"
#
try:
    while True:
                print count, teststring
                test.write(teststring)
                print "Waiting 1 second"
                time.sleep(1)
                count = count + 1
#
except KeyboardInterrupt:
    pass # do cleanup here
#
test.close()
----------------------------------------------------------------

Now run it as root (to get access to the metal):

  $ sudo python sertest.py

Observing the serial TXD (header pin 8) with the logic probe, you can see a data stream while the program is running. It works!


References:



Eric Pierce VA3EP - See the Disclaimer in the Introduction

© Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", 1952-2099. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", with appropriate and specific direction to the original content.



No comments:

Post a Comment