首页 > 代码库 > 树莓派+Python+pyserial 2.7实现串口通信

树莓派+Python+pyserial 2.7实现串口通信

手上有个CCD Camera(Barcode Reader/Scanner Module),它是通过RS232通信的,用RS232转USB的转接线连接树莓派,即可完成硬件连接。对于串口通信,可以通过pyserial实现。

首先,安装pyserial:

从https://pypi.python.org/pypi/pyserial下载最新版本的安装包,再通过下面的命令完成安装:

tar zxvf pyserial-2.7.tar.gzcd pyserial-2.7python setup.py install

通过命令lsusb查看串口是否存在:

通过命令python -m serial.tools.list_ports可以查看大可用的端口:

测试通信:

通过以上的准备后,就可以写一个简单的Python程式来实现串口通信:

import serialfrom time import sleepser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0.5) def recv(serial):      data    while True:          data =http://www.mamicode.com/serial.read(30)  >

 

来自官网的Sample(wxTerminal.py)也很不错,可以通过UI选择和配置端口:

#!/usr/bin/env python# generated by wxGlade 0.3.1 on Fri Oct 03 23:23:45 2003#from wxPython.wx import *import wximport wxSerialConfigDialogimport serialimport threading#----------------------------------------------------------------------# Create an own event type, so that GUI updates can be delegated# this is required as on some platforms only the main thread can# access the GUI without crashing. wxMutexGuiEnter/wxMutexGuiLeave# could be used too, but an event is more elegant.SERIALRX = wx.NewEventType()# bind to serial data receive eventsEVT_SERIALRX = wx.PyEventBinder(SERIALRX, 0)class SerialRxEvent(wx.PyCommandEvent):    eventType = SERIALRX    def __init__(self, windowID, data):        wx.PyCommandEvent.__init__(self, self.eventType, windowID)        self.data = http://www.mamicode.com/data>


 

树莓派+Python+pyserial 2.7实现串口通信