來源 : https://blog.csdn.net/lizilpl/article/details/26695767

該程式運行在樹莓派上,主要功能是把收到的UDP消息通過樹莓派自帶串口發給下位機,同時把串口收到的資料通過UDP發送出去,使用threading模組啟動兩個執行緒,互不干涉,可以在此基礎上更改實現各種功能。

首先,樹莓派在使用串口之前是需要配置一些檔案

1.修改cmdline.txt

>>> sudo vi /boot/cmdline.txt

將原來的內容

dwc_otg.lpm_enable=0 console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait

修改成

dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait

2.修改 inittab

>>> sudo vi /etc/inittab

將下面這一行加#注釋掉,一般是最後一行

#T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

 

3.安裝python-serial

>>>sudo apt-get install python-serial

現在就可以用了,下面貼上原始程式碼:

 

#!/bin/env/python

import serial

import string

import time

import threading

import socket

host=''

port=10001

global addr  #UDP 用戶端的IP地址,必須設為全域變數,才能在執行緒間共用

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 檔案名.py 即可運行

    全站熱搜

    Mamason 發表在 痞客邦 留言(0) 人氣()