2016年9月20日 星期二

Pyserial 的使用


在這裡介紹 Pyserial這個python的套件,
它透過電腦 COM Port來跟周邊作通訊

程式碼如下,使用的版本為python3.4

# c:\python34\Scripts  --> pip3 install pyserial
# Linux:  pip3 install pyserial

# -*- coding: utf8

import serial

#----------  Environment Setting  ---------------

Serial_PORT = 9


#---------- Global Variables ---------------

ser = 0

 
#-----------init serial ------------

def init_serial():  

  global ser , Serial_PORT

ser=serial.Serial()

ser.baudrate = 115200

#ser.port = (Serial_PORT) - 1      <-- Windows
ser.port = '/dev/ttyUSB0'              <-- Linux

ser.timeout = 1


## 這樣就完成初始化了
##使用方式如下

init_serial()

ser.open()

ser.write("'command_string")

read_data ="not ready"

while (len(read_data)):
  read_data = ser.readline()
if(len(read_data)):
print ('Port xxx send: ' + str(read_data))

ser.close()  




沒有留言:

張貼留言