pySerial provides a access to serial port using python. It works in malti-platform such as Windows, Linux, Mac OS X and so on without converting source code.
The module supporting write and read apis is following;
serial_port_controller.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
serial_port_controller.py
AProjectName
Created by Norio Saito on 7/2/11.
Copyright 2011 Tokyo Institute of Technology. All rights reserved.
"""
import sys
import serial
class SerialPortController(object):
"""
Encapsulate the settings and handles of the serial port.
It provides simple APIs with read and write.
"""
port = None
def __init__(self, port_name):
""" Open a serial connection using port_name. """
#self.port = serial.Serial(port_name)
self.port = mockups.Serial(port_name)
if not self.port.isOpen():
print "Port name: %s is invalid." % (port_name)
sys.exit()
def close(self):
""" Return the result of closing a serial connection. """
if not self.port:
print "The serial connection is not opened. "
return False
if self.port.isOpen():
self.port.close()
return True
return False
def write_command(self, command):
""" Write comamnd to equipment. """
self.port.write(command)
def read_buffer(self, size):
""" Read the buffer of equipment until a size. """
return self.port.read(size)
if __name__ == "__main__":
port_controller = SerialPortController("COM1")
port_controller.write_command("This is command.")
port_controller.read_buffer(11)
port_controller.close()
最終更新:2011年07月03日 20:47