手上有个CCD Camera(Barcode Reader/Scanner Module),它是通过RS232通信的,用RS232转USB的转接线连接树莓派,即可完成硬件连接。对于串口通信,可以通过pyserial实现。
首先,安装pyserial:
从https://pypi.python.org/pypi/pyserial下载最新版本的安装包,再通过下面的命令完成安装:
- tar zxvf pyserial-2.7.tar.gz
- cd pyserial-2.7
- python setup.py install
通过命令lsusb查看串口是否存在:
通过命令python -m serial.tools.list_ports可以查看大可用的端口:
测试通信:
通过以上的准备后,就可以写一个简单的Python程式来实现串口通信:
- import serial
- from time import sleep
- ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0.5)
- def recv(serial):
- data
- while True:
- data =serial.read(30)
- if data == '':
- continue
- else:
- break
- sleep(0.02)
- return data
- while True:
- data =recv(ser)
- ser.write(data)
来自官网的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 wx
- import wxSerialConfigDialog
- import serial
- import 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 events
- EVT_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 = data
- def Clone(self):
- self.__class__(self.GetId(), self.data)
- #----------------------------------------------------------------------
- ID_CLEAR = wx.NewId()
- ID_SAVEAS = wx.NewId()
- ID_SETTINGS = wx.NewId()
- ID_TERM = wx.NewId()
- ID_EXIT = wx.NewId()
- NEWLINE_CR = 0
- NEWLINE_LF = 1
- NEWLINE_CRLF = 2
- class TerminalSetup:
- """Placeholder for various terminal settings. Used to pass the
- options to the TerminalSettingsDialog."""
- def __init__(self):
- self.echo = False
- self.unprintable = False
- self.newline = NEWLINE_CRLF
- class TerminalSettingsDialog(wx.Dialog):
- """Simple dialog with common terminal settings like echo, newline mode."""
- def __init__(self, *args, **kwds):