樹莓派串列埠通訊編碼 樹莓派UDP通訊及串列埠通訊

2021-10-16 18:05:02 字數 1523 閱讀 1562

#!/bin/env/python

import serial

import string

import time

import threading

import socket

host=''

port=10001

s=socket.socket(socket.af_inet,socket.sock_dgram)

s.setsockopt(socket.sol_socket,socket.so_reuseaddr,1)

s.setsockopt(socket.sol_socket,socket.so_broadcast,1)

s.bind((host,port))

ser = serial.serial('/dev/ttyama0',9600,timeout =0.1) #串列埠設定

if ser.isopen() == false:

ser.open()

class timer(threading.thread): # timer class

def __init__(self, num, interval):

threading.thread.__init__(self)

self.thread_num = num

self.interval = interval

self.thread_stop = false

def run(self):

global addr

while 1:

if self.thread_num == 1:

try:

data,addr=s.recvfrom(1024) #接收到的udp訊息

print"got data from",addr

ser.write(data) #將udp內容通過串列埠傳送至下位機

except keyboardinterrupt:

raise

if self.thread_num == 2:

try:

re = ser.readlines() #收到的串列埠資料

print re

c=''.join(re)#sendto()第乙個引數是str,而readlins()返回值型別是list,故需要先將list轉換為str再傳送,之前 資料不斷丟包,一直不明白是這個原因。

s.sendto(c,addr) #將串列埠資料通過udp傳送出去

except:

pass

# time.sleep(self.interval)

def test():

thread1 = timer(1, 0.1) #udp recev and serial send

thread2 = timer(2, 0.1) #serial recev and udp send

thread1.start()

thread2.start()

return

if __name__ == '__main__':

test()

樹莓派串列埠通訊python 樹莓派串列埠通訊設定

實驗環境樹莓派 3b 開發板 2018 06 27 raspbian stretch 樹莓派作業系統 使用 windows 10 通過網線連線遠端登陸訪問方式控制樹莓派 實驗目的 為了將樹莓派構建成乙個智慧型家居的資料中心,我們需要在樹莓派上連線 zigbee 無線通訊模組,實現與感測器的一對多通訊...

樹莓派串列埠

串列埠使用例程及說明 pyserial api sudo apt get install python serial python m serial.tools.list ports 此命令可以檢視裝置的檔案節點。class serial.serial init port none,baudrate...

樹莓派串列埠通訊 python篇

修改 boot 目錄下的cmdline.txt 修改內容為 dwc otg.lpm enable 0 console tty1 root dev mmcblk0p2 rootfstype ext4 elevator deadline fsck.repair yes rootwait安裝python ...