Raspberry Pi +python+pyserial 2.7 for serial communication

Source: Internet
Author: User

The hand has a CCD Camera (Barcode reader/scanner Module), it is through RS232 communication, with the RS232 to the USB adapter to connect the Raspberry Pi, you can complete the hardware connection. For serial communication, it can be realized by pyserial.

First, install Pyserial:

Download the latest version of the installation package from Https://pypi.python.org/pypi/pyserial and complete the installation with the following command:

Tar zxvf pyserial-2.7.tar.gzcd pyserial-2.7python setup.py Install

To see if the serial port exists by command LSUSB:

With the command python-m serial.tools.list_ports you can view the ports that are available:

Test communication:

After the preparation, you can write a simple Python program to achieve serial communication:

Import serialfrom time Import Sleepser = serial. Serial ('/dev/ttyusb0 ', 9600, timeout=0.5) def recv (Serial):      data while    True:          data =serial.read (+)          if data = = ':              continue        else:            break        Sleep (0.02)     return data while  True:      data =recv (Ser)      ser.write (data)

Sample (wxterminal.py) from the official website is also good, and the port can be selected and configured via the UI:

#!/usr/bin/env python# generated by Wxglade 0.3.1 on Fri Oct 23:23:45 2003#from wxpython.wx import *import wximport WxS Erialconfigdialogimport Serialimport threading#-----------------------------------------------------------------  -----# Create An own event type, so-GUI updates can delegated# this is required as on some platforms only the main Thread can# access the GUI without crashing. Wxmutexguienter/wxmutexguileave# could was used too, but an event was 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 = 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 = 0NEWLINE_LF = 1newline_crlf = 2class terminalsetup: "" "Placeholder for various Termina L settings.    Used to pass the options to the Terminalsettingsdialog. "" def __init__ (self): Self.echo = False self.unprintable = False Self.newline = Newline_crlfclass Termi Nalsettingsdialog (WX.        Dialog): "" "simple Dialog with common terminal settings like Echo, newline mode." def __init__ (self, *args, **kwds): self.settings = kwds[' Settings '] del kwds[' Settings '] # begin WXGL ade:terminalsettingsdialog.__init__ kwds["style"] = WX. Default_dialog_style WX. Dialog.__init__ (self, *args, **kwds) Self.checkbox_echo = wx. CheckBox (self,-1, "Local Echo") self.checkbox_unprintable = wx. CheckBox (self,-1, "Show unprintable characters") Self.radio_box_newline = wx. Radiobox (self,-1, "Newline handling", choices=["CR only", "LF only""," CR+LF "], majordimension=0, style=wx. ra_specify_rows) Self.button_ok = wx. button (self,-1, "OK") Self.button_cancel = wx. button (self,-1, "Cancel") Self.__set_properties () self.__do_layout () # End Wxglade Self.__att Ach_events () Self.checkbox_echo. SetValue (Self.settings.echo) self.checkbox_unprintable. SetValue (self.settings.unprintable) self.radio_box_newline. SetSelection (Self.settings.newline) def __set_properties (self): # begin WXGLADE:TERMINALSETTINGSDIALOG.__SET_PR Operties self. Settitle ("Terminal Settings") self.radio_box_newline. SetSelection (0) Self.button_ok.        SetDefault () # End Wxglade def __do_layout (self): # begin Wxglade:terminalsettingsdialog.__do_layout sizer_2 = wx. Boxsizer (WX. VERTICAL) sizer_3 = wx. Boxsizer (WX. Horizontal) Sizer_4 = wx. Staticboxsizer (WX. Staticbox (self,-1, "Input/output"), WX. VERTICAL) Sizer_4.add (Self.checkbox_echo,0, WX. All, 4) sizer_4.add (self.checkbox_unprintable, 0, WX. All, 4) sizer_4.add (self.radio_box_newline, 0, 0, 0) sizer_2.add (sizer_4, 0, WX. EXPAND, 0) sizer_3.add (SELF.BUTTON_OK, 0, 0, 0) sizer_3.add (self.button_cancel, 0, 0, 0) sizer_2.add ( Sizer_3, 0, WX. All|wx. Align_right, 4) self. Setautolayout (1) Self. Setsizer (sizer_2) sizer_2.fit (self), sizer_2.setsizehints (self) self. Layout () # End Wxglade def __attach_events (self): self. Bind (WX. Evt_button, self. OnOK, id = self.button_ok. GetId ()) self. Bind (WX. Evt_button, self. OnCancel, id = self.button_cancel.        GetId ()) def OnOK (self, events): "" "Update data wil new values and close dialog." " Self.settings.echo = Self.checkbox_echo. GetValue () self.settings.unprintable = self.checkbox_unprintable. GetValue () Self.settings.newline = Self.radio_box_newline. GetSelection () self. Endmodal (WX.ID_OK) def OnCancel(Self, events): "" "does not update data but close dialog." " Self. Endmodal (Wx.id_cancel) # End of Class Terminalsettingsdialogclass Terminalframe (WX. Frame): "" "Simple terminal-WxPython" "" Def __init__ (self, *args, **kwds): self.serial = Seria L.serial () Self.serial.timeout = 0.5 #make sure that the Alive event can is checked from time to time self . Settings = Terminalsetup () #placeholder for the settings self.thread = None self.alive = Threading. Event () # begin wxglade:terminalframe.__init__ kwds["style"] = WX. Default_frame_style WX. Frame.__init__ (self, *args, **kwds) self.text_ctrl_output = wx. Textctrl (self,-1, "", style=wx.te_multiline|wx.te_readonly) # menu Bar Self.frame_terminal_menubar = WX. MenuBar () self. Setmenubar (self.frame_terminal_menubar) Wxglade_tmp_menu = wx. Menu () Wxglade_tmp_menu. Append (Id_clear, "&clear", "", WX. Item_normal) Wxglade_tmp_menu. Append (Id_saveas, "&save Text as ...", "", WX. Item_normal) Wxglade_tmp_menu. Appendseparator () Wxglade_tmp_menu. Append (id_settings, "&port SETTINGS ...", "", WX. Item_normal) Wxglade_tmp_menu. Append (Id_term, "&terminal Settings ...", "", WX. Item_normal) Wxglade_tmp_menu. Appendseparator () Wxglade_tmp_menu. Append (Id_exit, "&exit", "", WX. Item_normal) Self.frame_terminal_menubar.        Append (Wxglade_tmp_menu, "&file") # menu Bar End self.__set_properties () self.__do_layout () # End Wxglade self.__attach_events () #register events self. Onportsettings (None) #call Setup dialog on startup, opens port if not Self.alive.isSet (): Self. Close () def startthread (self): "" Start the Receiver Thread "" "Self.thread = Threading.    Thread (Target=self.comportthread) Self.thread.setDaemon (1) self.alive.set ()    Self.thread.start () def stopthread (self): "" "Stop the receiver thread, wait util it ' s finished." "" If Self.thread is not None:self.alive.clear () #clear Alive event for thread Self.thread.jo        In () #wait until thread have finished self.thread = None def __set_properties (self): # Begin wxglade:terminalframe.__set_properties Self. Settitle ("Serial Terminal") self.        SetSize ((546, 383)) # End Wxglade def __do_layout (self): # begin Wxglade:terminalframe.__do_layout sizer_1 = wx. Boxsizer (WX. VERTICAL) Sizer_1.add (self.text_ctrl_output, 1, WX. EXPAND, 0) self. Setautolayout (1) Self. Setsizer (sizer_1) self. Layout () # End Wxglade def __attach_events (self): #register events on the controls self. Bind (WX. Evt_menu, self. OnClear, id = id_clear) self. Bind (WX. Evt_menu, self. Onsaveas, id = id_saveas) self. Bind (WX. Evt_menU, self. OnExit, id = id_exit) self. Bind (WX. Evt_menu, self. Onportsettings, id = id_settings) self. Bind (WX. Evt_menu, self. Ontermsettings, id = id_term) self.text_ctrl_output. Bind (WX. Evt_char, self. OnKey) self. Bind (Evt_serialrx, self. Onserialread) self. Bind (WX. Evt_close, self. OnClose) def OnExit (Self, event): "", "" "," "" ".        Close () def OnClose (Self, event): "" "called on application shutdown." "" Self. Stopthread () #stop reader Thread self.serial.close () #cleanup self. Destroy () #close windows, exit App Def onsaveas (Self, event): "" "Save contents of Output Window        .""" filename = None dlg = wx. FileDialog (None, "Save text as ...", ".", "", "text file|*.txt| All files|* ", WX. SAVE) if dlg. ShowModal () = = Wx.ID_OK:filename = dlg. GetPath () dlg. Destroy () If filename is not none:f =File (filename, ' w ') Text = Self.text_ctrl_output. GetValue () if type (text) = = Unicode:text = Text.encode ("Latin1") #hm, is a good asumpti            On?        F.write (text) f.close () def onclear (Self, event): "" "Clear contents of Output window." " Self.text_ctrl_output. Clear () def onportsettings (self, Event=none): "" "Show the Portsettings dialog.        The reader thread is stopped for the settings change. "" If event is not none: #will was none when called on startup self. Stopthread () self.serial.close () OK = False while not ok:dialog_serial_cfg = wxserial Configdialog.serialconfigdialog (None,-1, "", Show=wxserialconfigdialog.show_baudrate|wxserialconfigdialog. Show_format|wxserialconfigdialog.show_flow, serial=self.serial) result = Dialog_seri Al_cfg. ShowModal () Dialog_seriaL_cfg. Destroy () #open port if not called on startup, open it on startup and OK too if result = = Wx.id_ok O R event is not None:try:self.serial.open () except serial. Serialexception, E:dlg = wx. Messagedialog (None, str (e), "Serial Port Error", WX. OK | Wx. Icon_error) dlg. ShowModal () dlg. Destroy () else:self. Startthread () self. Settitle ("Serial Terminal on%s [%s,%s%s%s%s%s]"% (SELF.SERIAL.PORTSTR, S                        Elf.serial.baudrate, Self.serial.bytesize, Self.serial.parity, Self.serial.stopbits, self.serial.rtscts and ' rts/cts ' or ', sel            F.serial.xonxoff and ' xon/xoff ' or ',)) OK = True ELSE: #on Startup, Dialog aborted self.alive.clear () ok = True def ontermse Ttings (self, event): "" Menu point Terminal Settings. Show The settings dialog with the current terminal Settings "" "Dialog = Terminalsettingsdialog (None,-1, "", settings=self.settings) result = dialog. ShowModal () dialog. Destroy () def OnKey (Self, event): "" "Key event handler.           If the key is in the ASCII range, write it to the serial port.        Newline handling and local echo is also do here. "" Code = event.            getKeyCode () If code <: #is it printable? if code = =: #is it a newline?                    (Check for CR which is the RETURN key) if Self.settings.echo: #do echo if needed Self.text_ctrl_output. AppendText (' \ n ') if self.settings.newline = = NEWLINE_CR:SELF.SERIAL.WRIte (' \ R ') #send CR elif Self.settings.newline = = NEWLINE_LF:self.serial.write (' \ n ') #send LF elif Self.settings.newline = = NEWLINE_CRLF:self.serial.write (' \ r \ n ') #s End CR+LF Else:char = chr (code) if Self.settings.echo: #do echo if need Ed Self.text_ctrl_output. WRITETEXT (char) self.serial.write (char) #send the Charcater else:print "Extra Ke        Y: ", Code def onserialread (Self, event):" "" "" Handle input from the serial port. "" Text = Event.data If Self.settings.unprintable:text = '. Join ([(C >= ') and C or ' <%d> '% or D (c) for C in text]) Self.text_ctrl_output. AppendText (text) def comportthread (self): "" "Thread that handles the incomming traffic.        Does the basic Input Transformation (newlines) and generates an Serialrxevent "" "While Self.alive.isSet (): #loop while Alive event is true text = Self.serial.read (1) #re Ad one, with Timout if text: #check if not timeout n = self.serial.in Waiting () #look if there is more to read if N:text = text + self.serial.read (n) #ge  T it #newline transformation if self.settings.newline = = Newline_cr:text                = Text.replace (' \ r ', ' \ n ') elif self.settings.newline = = Newline_lf:pass elif Self.settings.newline = = Newline_crlf:text = Text.replace (' \ r \ n ', ' \ n ') event = Serialrxevent (self. GetId (), text) self. Geteventhandler (). Addpendingevent (event) #~ self. Onserialread (text) #output text in Window # End of Class Terminalframeclass MyApp (WX. APP): def OnInit (self): WX. InitallimAgehandlers () frame_terminal = Terminalframe (None,-1, "") self. Settopwindow (frame_terminal) frame_terminal. Show (1) Return # End of class myappif __name__ = = "__main__": App = MyApp (0) app. Mainloop ()


Raspberry Pi +python+pyserial 2.7 for serial communication

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.