RSS Feed

RSS
Comments RSS

Serial Communications using Python

#k2test1.py  by Bill Allen – WA5PB
#This is an experiment in communicating with an Amateur Radio transceiver
#via Python through RS232 serial communications.  Similar code could be used
#to communicate with any device supporting serial communications.

#This was written using Python 2.6.5, but I like using the new
#Python 3.x print function so we pull it in for use here.
from __future__ import print_function

#We will be using the PySerial library to provide RS232 serial communications.
#PySerial is a third party library module that can be found here:
#http://pyserial.sourceforge.net/
import serial

#Configure the serial port to communicate with the Elecraft K2 xcvr.
#I am coding this on a Linux system, so the device string /dev/ttyS0
#works for the first serial port.  Your system my use a different serial
#port device.  For a Windows system, try COM1 for the first serial port.
ser = serial.Serial(‘/dev/ttyS0’, 4800, timeout=1)

#Sanity check for the K2 AutoInfo mode, turn it off.
ser.write(“AI0;”)

#Now set the K2 AutoInfo mode to mode 1 and get some initial data.
ser.write(“AI1;”)

#Read up to 150 bytes of returned data from the K2 and print it out.
K2_data = ser.read(150)
print(K2_data)

#Now set the K2 AutoInfo mode to return the most data while it is being polled.
#Ctrl-C will be used to end the program.  End the program gracefully by trapping
#the Ctrl-C, turning off the K2 AutoInfo mode and closing the serial port prior
#to exiting.
ser.write(“AI3;”)
while True:
    try:
        K2_data = ser.read(150)
        if K2_data != “”:
            print(K2_data)
    except KeyboardInterrupt:
        print(“\nOK, exiting…”)
        print(“Reseting K2 AutoInfo mode OFF”)
        ser.write(“AI0;”)
        print(“Closing Serial Port”)
        ser.close()
        raise SystemExit(0)

One Response to “Serial Communications using Python”









*