---
title: "树莓派实现串口通信"
author: "徜徉の小溪"
date: "2015-11-06T15:57:44Z"
tags: []
categories: ["操作系统"]
slug: "untitled"
draft: false
lastmod: "2015-11-06T15:57:44Z"
id: 2254944
url: "https://minjiechenjava.iteye.com/blog/2254944"
---

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

**首先，安装pyserial：**

从[https://pypi.python.org/pypi/pyserial](https://pypi.python.org/pypi/pyserial)下载最新版本的安装包，再通过下面的命令完成安装：

**\[plain]** [view plain](http://blog.csdn.net/Burgess_Liu/article/details/41745159 "view plain")[copy](http://blog.csdn.net/Burgess_Liu/article/details/41745159 "copy")

 

1. tar zxvf pyserial-2.7.tar.gz
2. cd pyserial-2.7
3. python setup.py install

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

![](http://img.blog.csdn.net/20141205113059449?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvQnVyZ2Vzc19MaXU=%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast)

通过命令python -m serial.tools.list\_ports可以查看大可用的端口：

![](http://img.blog.csdn.net/20141205113241738?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvQnVyZ2Vzc19MaXU=%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast)

测试通信：

![](http://img.blog.csdn.net/20141205113645656?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvQnVyZ2Vzc19MaXU=%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast)

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

**\[python]** [view plain](http://blog.csdn.net/Burgess_Liu/article/details/41745159 "view plain")[copy](http://blog.csdn.net/Burgess_Liu/article/details/41745159 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/543153 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/543153/fork "派生到我的代码片")

 

01. import serial
02. from time import sleep
03. ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0.5)
04. def recv(serial):
05. data
06. while True:
07. data =serial.read(30)
08. if data == '':
09. continue
10. else:
11. break
12. sleep(0.02)
13. return data
14. while True:
15. data =recv(ser)
16. ser.write(data)

 

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

**\[python]** [view plain](http://blog.csdn.net/Burgess_Liu/article/details/41745159 "view plain")[copy](http://blog.csdn.net/Burgess_Liu/article/details/41745159 "copy")[![在CODE上查看代码片](https://code.csdn.net/assets/CODE_ico.png)](https://code.csdn.net/snippets/543153 "在CODE上查看代码片")[![派生到我的代码片](https://code.csdn.net/assets/ico_fork.svg)](https://code.csdn.net/snippets/543153/fork "派生到我的代码片")

 

001. #!/usr/bin/env python
002. # generated by wxGlade 0.3.1 on Fri Oct 03 23:23:45 2003
003. #from wxPython.wx import *
004. import wx
005. import wxSerialConfigDialog
006. import serial
007. import threading
008. #----------------------------------------------------------------------
009. # Create an own event type, so that GUI updates can be delegated
010. # this is required as on some platforms only the main thread can
011. # access the GUI without crashing. wxMutexGuiEnter/wxMutexGuiLeave
012. # could be used too, but an event is more elegant.
013. SERIALRX = wx.NewEventType()
014. # bind to serial data receive events
015. EVT\_SERIALRX = wx.PyEventBinder(SERIALRX, 0)
016. class SerialRxEvent(wx.PyCommandEvent):
017. eventType = SERIALRX
018. def \_\_init\_\_(self, windowID, data):
019. wx.PyCommandEvent.\_\_init\_\_(self, self.eventType, windowID)
020. self.data = data
021. def Clone(self):
022. self.\_\_class\_\_(self.GetId(), self.data)
023. #----------------------------------------------------------------------
024. ID\_CLEAR        = wx.NewId()
025. ID\_SAVEAS       = wx.NewId()
026. ID\_SETTINGS     = wx.NewId()
027. ID\_TERM         = wx.NewId()
028. ID\_EXIT         = wx.NewId()
029. NEWLINE\_CR      = 0
030. NEWLINE\_LF      = 1
031. NEWLINE\_CRLF    = 2
032. class TerminalSetup:
033. """Placeholder for various terminal settings. Used to pass the
034. options to the TerminalSettingsDialog."""
035. def \_\_init\_\_(self):
036. self.echo = False
037. self.unprintable = False
038. self.newline = NEWLINE\_CRLF
039. class TerminalSettingsDialog(wx.Dialog):
040. """Simple dialog with common terminal settings like echo, newline mode."""
041. def \_\_init\_\_(self, \*args, \*\*kwds):
042. self.settings = kwds\['settings']
043. del kwds\['settings']
044. # begin wxGlade: TerminalSettingsDialog.\_\_init\__
045. kwds\["style"] = wx.DEFAULT\_DIALOG\_STYLE
046. wx.Dialog.\_\_init\_\_(self, \*args, \*\*kwds)
047. self.checkbox\_echo = wx.CheckBox(self, -1, "Local Echo")
048. self.checkbox\_unprintable = wx.CheckBox(self, -1, "Show unprintable characters")
049. self.radio\_box\_newline = wx.RadioBox(self, -1, "Newline Handling", choices=\["CR only", "LF only", "CR+LF"], majorDimension=0, style=wx.RA\_SPECIFY\_ROWS)
050. self.button\_ok = wx.Button(self, -1, "OK")
051. self.button\_cancel = wx.Button(self, -1, "Cancel")
052. self.\_\_set\_properties()
053. self.\_\_do\_layout()
054. # end wxGlade
055. self.\_\_attach\_events()
056. self.checkbox\_echo.SetValue(self.settings.echo)
057. self.checkbox\_unprintable.SetValue(self.settings.unprintable)
058. self.radio\_box\_newline.SetSelection(self.settings.newline)
059. def \_\_set\_properties(self):
060. # begin wxGlade: TerminalSettingsDialog.\_\_set\_properties
061. self.SetTitle("Terminal Settings")
062. self.radio\_box\_newline.SetSelection(0)
063. self.button\_ok.SetDefault()
064. # end wxGlade
065. def \_\_do\_layout(self):
066. # begin wxGlade: TerminalSettingsDialog.\_\_do\_layout
067. sizer\_2 = wx.BoxSizer(wx.VERTICAL)
068. sizer\_3 = wx.BoxSizer(wx.HORIZONTAL)
069. sizer\_4 = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Input/Output"), wx.VERTICAL)
070. sizer\_4.Add(self.checkbox\_echo, 0, wx.ALL, 4)
071. sizer\_4.Add(self.checkbox\_unprintable, 0, wx.ALL, 4)
072. sizer\_4.Add(self.radio\_box\_newline, 0, 0, 0)
073. sizer\_2.Add(sizer\_4, 0, wx.EXPAND, 0)
074. sizer\_3.Add(self.button\_ok, 0, 0, 0)
075. sizer\_3.Add(self.button\_cancel, 0, 0, 0)
076. sizer\_2.Add(sizer\_3, 0, wx.ALL|wx.ALIGN\_RIGHT, 4)
077. self.SetAutoLayout(1)
078. self.SetSizer(sizer\_2)
079. sizer\_2.Fit(self)
080. sizer\_2.SetSizeHints(self)
081. self.Layout()
082. # end wxGlade
083. def \_\_attach\_events(self):
084. self.Bind(wx.EVT\_BUTTON, self.OnOK, id = self.button\_ok.GetId())
085. self.Bind(wx.EVT\_BUTTON, self.OnCancel, id = self.button\_cancel.GetId())
086. def OnOK(self, events):
087. """Update data wil new values and close dialog."""
088. self.settings.echo = self.checkbox\_echo.GetValue()
089. self.settings.unprintable = self.checkbox\_unprintable.GetValue()
090. self.settings.newline = self.radio\_box\_newline.GetSelection()
091. self.EndModal(wx.ID\_OK)
092. def OnCancel(self, events):
093. """Do not update data but close dialog."""
094. self.EndModal(wx.ID\_CANCEL)
095. # end of class TerminalSettingsDialog
096. class TerminalFrame(wx.Frame):
097. """Simple terminal program for wxPython"""
098. def \_\_init\_\_(self, \*args, \*\*kwds):
099. self.serial = serial.Serial()
100. self.serial.timeout = 0.5   #make sure that the alive event can be checked from time to time
101. self.settings = TerminalSetup() #placeholder for the settings
102. self.thread = None
103. self.alive = threading.Event()
104. # begin wxGlade: TerminalFrame.\_\_init\__
105. kwds\["style"] = wx.DEFAULT\_FRAME\_STYLE
106. wx.Frame.\_\_init\_\_(self, \*args, \*\*kwds)
107. self.text\_ctrl\_output = wx.TextCtrl(self, -1, "", style=wx.TE\_MULTILINE|wx.TE\_READONLY)
108. # Menu Bar
109. self.frame\_terminal\_menubar = wx.MenuBar()
110. self.SetMenuBar(self.frame\_terminal\_menubar)
111. wxglade\_tmp\_menu = wx.Menu()
112. wxglade\_tmp\_menu.Append(ID\_CLEAR, "&Clear", "", wx.ITEM\_NORMAL)
113. wxglade\_tmp\_menu.Append(ID\_SAVEAS, "&Save Text As...", "", wx.ITEM\_NORMAL)
114. wxglade\_tmp\_menu.AppendSeparator()
115. wxglade\_tmp\_menu.Append(ID\_SETTINGS, "&Port Settings...", "", wx.ITEM\_NORMAL)
116. wxglade\_tmp\_menu.Append(ID\_TERM, "&Terminal Settings...", "", wx.ITEM\_NORMAL)
117. wxglade\_tmp\_menu.AppendSeparator()
118. wxglade\_tmp\_menu.Append(ID\_EXIT, "&Exit", "", wx.ITEM\_NORMAL)
119. self.frame\_terminal\_menubar.Append(wxglade\_tmp\_menu, "&File")
120. # Menu Bar end
121. self.\_\_set\_properties()
122. self.\_\_do\_layout()
123. # end wxGlade
124. self.\_\_attach\_events()          #register events
125. self.OnPortSettings(None)       #call setup dialog on startup, opens port
126. if not self.alive.isSet():
127. self.Close()
128. def StartThread(self):
129. """Start the receiver thread"""
130. self.thread = threading.Thread(target=self.ComPortThread)
131. self.thread.setDaemon(1)
132. self.alive.set()
133. self.thread.start()
134. def StopThread(self):
135. """Stop the receiver thread, wait util it's finished."""
136. if self.thread is not None:
137. self.alive.clear()          #clear alive event for thread
138. self.thread.join()          #wait until thread has finished
139. self.thread = None
140. def \_\_set\_properties(self):
141. # begin wxGlade: TerminalFrame.\_\_set\_properties
142. self.SetTitle("Serial Terminal")
143. self.SetSize((546, 383))
144. # end wxGlade
145. def \_\_do\_layout(self):
146. # begin wxGlade: TerminalFrame.\_\_do\_layout
147. sizer\_1 = wx.BoxSizer(wx.VERTICAL)
148. sizer\_1.Add(self.text\_ctrl\_output, 1, wx.EXPAND, 0)
149. self.SetAutoLayout(1)
150. self.SetSizer(sizer\_1)
151. self.Layout()
152. # end wxGlade
153. def \_\_attach\_events(self):
154. #register events at the controls
155. self.Bind(wx.EVT\_MENU, self.OnClear, id = ID\_CLEAR)
156. self.Bind(wx.EVT\_MENU, self.OnSaveAs, id = ID\_SAVEAS)
157. self.Bind(wx.EVT\_MENU, self.OnExit, id = ID\_EXIT)
158. self.Bind(wx.EVT\_MENU, self.OnPortSettings, id = ID\_SETTINGS)
159. self.Bind(wx.EVT\_MENU, self.OnTermSettings, id = ID\_TERM)
160. self.text\_ctrl\_output.Bind(wx.EVT\_CHAR, self.OnKey)
161. self.Bind(EVT\_SERIALRX, self.OnSerialRead)
162. self.Bind(wx.EVT\_CLOSE, self.OnClose)
163. def OnExit(self, event):
164. """Menu point Exit"""
165. self.Close()
166. def OnClose(self, event):
167. """Called on application shutdown."""
168. self.StopThread()               #stop reader thread
169. self.serial.close()             #cleanup
170. self.Destroy()                  #close windows, exit app
171. def OnSaveAs(self, event):
172. """Save contents of output window."""
173. filename = None
174. dlg = wx.FileDialog(None, "Save Text As...", ".", "", "Text File|\*.txt|All Files|\*",  wx.SAVE)
175. if dlg.ShowModal() ==  wx.ID\_OK:
176. filename = dlg.GetPath()
177. dlg.Destroy()
178. if filename is not None:
179. f = file(filename, 'w')
180. text = self.text\_ctrl\_output.GetValue()
181. if type(text) == unicode:
182. text = text.encode("latin1")    #hm, is that a good asumption?
183. f.write(text)
184. f.close()
185. def OnClear(self, event):
186. """Clear contents of output window."""
187. self.text\_ctrl\_output.Clear()
188. def OnPortSettings(self, event=None):
189. """Show the portsettings dialog. The reader thread is stopped for the
190. settings change."""
191. if event is not None:           #will be none when called on startup
192. self.StopThread()
193. self.serial.close()
194. ok = False
195. while not ok:
196. dialog\_serial\_cfg = wxSerialConfigDialog.SerialConfigDialog(None, -1, "",
197. show=wxSerialConfigDialog.SHOW\_BAUDRATE|wxSerialConfigDialog.SHOW\_FORMAT|wxSerialConfigDialog.SHOW\_FLOW,
198. serial=self.serial
199. )
200. result = dialog\_serial\_cfg.ShowModal()
201. dialog\_serial\_cfg.Destroy()
202. #open port if not called on startup, open it on startup and OK too
203. if result == wx.ID\_OK or event is not None:
204. try:
205. self.serial.open()
206. except serial.SerialException, e:
207. dlg = wx.MessageDialog(None, str(e), "Serial Port Error", wx.OK | wx.ICON\_ERROR)
208. dlg.ShowModal()
209. dlg.Destroy()
210. else:
211. self.StartThread()
212. self.SetTitle("Serial Terminal on %s \[%s, %s%s%s%s%s]" % (
213. self.serial.portstr,
214. self.serial.baudrate,
215. self.serial.bytesize,
216. self.serial.parity,
217. self.serial.stopbits,
218. self.serial.rtscts and ' RTS/CTS' or '',
219. self.serial.xonxoff and ' Xon/Xoff' or '',
220. )
221. )
222. ok = True
223. else:
224. #on startup, dialog aborted
225. self.alive.clear()
226. ok = True
227. def OnTermSettings(self, event):
228. """Menu point Terminal Settings. Show the settings dialog
229. with the current terminal settings"""
230. dialog = TerminalSettingsDialog(None, -1, "", settings=self.settings)
231. result = dialog.ShowModal()
232. dialog.Destroy()
233. def OnKey(self, event):
234. """Key event handler. if the key is in the ASCII range, write it to the serial port.
235. Newline handling and local echo is also done here."""
236. code = event.GetKeyCode()
237. if code &lt; 256:                          #is it printable?
238. if code == 13:                      #is it a newline? (check for CR which is the RETURN key)
239. if self.settings.echo:          #do echo if needed
240. self.text\_ctrl\_output.AppendText('\\n')
241. if self.settings.newline == NEWLINE\_CR:
242. self.serial.write('\\r')     #send CR
243. elif self.settings.newline == NEWLINE\_LF:
244. self.serial.write('\\n')     #send LF
245. elif self.settings.newline == NEWLINE\_CRLF:
246. self.serial.write('\\r\\n')   #send CR+LF
247. else:
248. char = chr(code)
249. if self.settings.echo:          #do echo if needed
250. self.text\_ctrl\_output.WriteText(char)
251. self.serial.write(char)         #send the charcater
252. else:
253. print "Extra Key:", code
254. def OnSerialRead(self, event):
255. """Handle input from the serial port."""
256. text = event.data
257. if self.settings.unprintable:
258. text = ''.join(\[(c &gt;= ' ') and c or '&lt;%d&gt;' % ord(c)  for c in text])
259. self.text\_ctrl\_output.AppendText(text)
260. def ComPortThread(self):
261. """Thread that handles the incomming traffic. Does the basic input
262. transformation (newlines) and generates an SerialRxEvent"""
263. while self.alive.isSet():               #loop while alive event is true
264. text = self.serial.read(1)          #read one, with timout
265. if text:                            #check if not timeout
266. n = self.serial.inWaiting()     #look if there is more to read
267. if n:
268. text = text + self.serial.read(n) #get it
269. #newline transformation
270. if self.settings.newline == NEWLINE\_CR:
271. text = text.replace('\\r', '\\n')
272. elif self.settings.newline == NEWLINE\_LF:
273. pass
274. elif self.settings.newline == NEWLINE\_CRLF:
275. text = text.replace('\\r\\n', '\\n')
276. event = SerialRxEvent(self.GetId(), text)
277. self.GetEventHandler().AddPendingEvent(event)
278. #~ self.OnSerialRead(text)         #output text in window
279. # end of class TerminalFrame
280. class MyApp(wx.App):
281. def OnInit(self):
282. wx.InitAllImageHandlers()
283. frame\_terminal = TerminalFrame(None, -1, "")
284. self.SetTopWindow(frame\_terminal)
285. frame\_terminal.Show(1)
286. return 1
287. # end of class MyApp
288. if \_\_name\__ == "\_\_main\_\_":
289. app = MyApp(0)
290. app.MainLoop()