簡單WiFi控制小車系統(樹莓派+python+web控制界面)


~~ 如果有什么問題可以在我的Five-great的博客留言,我會及時回復。歡迎來訪交流 ~~


下面是小車 

 

 

好丑 對不對 ,不過反正可以蛇皮走位就行。

   蛇皮走位演示視頻: https://pan.baidu.com/s/1RHHr8bRHWzSEAkrpwu99aw

 只需要 一個 index.html  和Index.py 就可以實現 簡單WiFi 控制小車。

需要准備

  python 

   bottle 庫

 bottle 安裝

命令: pip install bottle

 

 

樹莓派控制界面(web客戶端)

  index.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>遙控樹莓派</title>
    <link href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <script src="http://code.jquery.com/jquery.js"></script>
    <style type="text/css">
        #front {
            margin-left: 55px;
            margin-bottom: 3px;
        }
        #rear{
            margin-top: 3px;
            margin-left: 55px;
        }
        .btn{
             background: #62559f;
            }
    </style>
    <script>
        $(function(){
            $("button").click(function(){
                $.post("/cmd",this.id,function(data,status){});
            });
        });

    </script>
</head>
<body>
<div id="container" class="container">
    
    <div>
        <button id="front" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-up"></button>
    </div>
    <div>

        <button id='leftFront' class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-left"></button>
        <button id='stop' class="btn btn-lg btn-primary glyphicon glyphicon-stop"></button>
        <button id='rightFront' class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-right"></button>
    </div>
    <div>
        <button id='rear' class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-down"></button>
    </div>
     <div>
        <button id='leftRear' class="btn btn-lg btn-primary glyphicon">左后轉</button>
        <button id='rightRear' class="btn btn-lg btn-primary glyphicon">右后轉</button>
    <div>
</div>

<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>

 

  js腳本解釋:

 <script>
        $(function(){
            $("button").click(function(){
                $.post("/cmd",this.id,function(data,status){});
     //表示 按鈕對應的id值 會被傳入樹莓派服務器中,就如同 你在樹莓派的命令行(cmd)中輸入 id 的值
            });
        });

</script>

 

樹莓派小車控制程序+we服務端

 Index.py

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from bottle import get,post,run,request,template

import RPi.GPIO as GPIO
import time
import sys 

 
####  定義Car類
class Car(object):
    def __init__(self):
        self.enab_pin = [5,6,13,19]
####  self.enab_pin是使能端的pin
        self.inx_pin = [21,22,23,24]
####  self.inx_pin是控制端in的pin
        self.RightAhead_pin = self.inx_pin[0]
        self.RightBack_pin = self.inx_pin[1]
        self.LeftAhead_pin = self.inx_pin[2]
        self.LeftBack_pin = self.inx_pin[3]
####  分別是右輪前進,右輪退后,左輪前進,左輪退后的pin
        self.setup()
 
####  setup函數初始化端口
    def setup(self):
        print ("begin setup ena enb pin")
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        for pin in self.enab_pin: 
            GPIO.setup(pin,GPIO.OUT)
            GPIO.output(pin,GPIO.HIGH)
####  初始化使能端pin,設置成高電平
        pin = None
        for pin in self.inx_pin:
            GPIO.setup(pin,GPIO.OUT)
            GPIO.output(pin,GPIO.LOW)
####  初始化控制端pin,設置成低電平
        print ("setup ena enb pin over")
 
####  fornt函數,小車前進
    def front(self):
        self.setup()
        GPIO.output(self.RightAhead_pin,GPIO.HIGH)
        GPIO.output(self.LeftAhead_pin,GPIO.HIGH)
 
####  leftFront函數,小車左拐彎
    def leftFront(self):
        self.setup()
        GPIO.output(self.RightAhead_pin,GPIO.HIGH)
 
####  rightFront函數,小車右拐彎
    def rightFront(self):
        self.setup()
        GPIO.output(self.LeftAhead_pin,GPIO.HIGH)
 
####  rear函數,小車后退
    def rear(self):
        self.setup()
        GPIO.output(self.RightBack_pin,GPIO.HIGH)
        GPIO.output(self.LeftBack_pin,GPIO.HIGH)
 
####  leftRear函數,小車左退
    def leftRear(self):
        self.setup()
        GPIO.output(self.RightBack_pin,GPIO.HIGH)
 
####  rightRear函數,小車右退
    def rightRear(self):
        self.setup()
        GPIO.output(self.LeftBack_pin,GPIO.HIGH)
 
####  定義main主函數
def main(status):
    
    car = Car()

    if status == "front":
        car.front()
    elif status == "leftFront":
        car.leftFront()
    elif status == "rightFront":
        car.rightFront()
    elif status == "rear":
        car.rear()
    elif status == "leftRear":
        car.leftRear()
    elif status == "rightRear":
        car.rightRear()
    elif status == "stop":
        car.setup()      
             



@get("/")
def index():
    return template("index")
@post("/cmd")
def cmd():
    adss=request.body.read().decode()
    print("按下了按鈕:"+adss)
    main(adss)
    return "OK"
run(host="0.0.0.0")

 

web服務端 實際就這點代碼, 主要是 bottle 庫的強大,(實際控制的小車的代碼 根據自己的需求改就行了)

from bottle import get,post,run,request,template


@get("/")
def index():
    return template("index") 
#### 這個是 客戶端請求 服務端就發給一個 index.html 控制界面給客戶端
@post("/cmd")
def cmd():
    adss=request.body.read().decode()#### 接收到 客戶端 發過來的數據
    print("按下了按鈕:"+adss)
    main(adss)  #### 傳值到主函數 實現對應功能
    return "OK"
run(host="0.0.0.0")  #### 開啟服務端 

 

運行 index.py 開啟服務器:

然后打開瀏覽器(手機瀏覽器也可以但必須在同一個局域網內) 輸入 樹莓派的ip 我的是 192.168.191.4:8080

有可能 打開比較慢  10分鍾內吧 哈哈哈(我第一次打開 就用了好久 都以為沒有成功)

手機端輸入ip

登錄成功!!!

 

 

輸入之后  服務器會給你拋出一個 index.html 控制文件。

然后就可以點擊按鍵 控制小車了  下面是 服務端中反饋

 

框架搭好后,根據自己需求更改 。

 

補充說明一下啊 因為我改過系統的語言和編碼設置 (支持utf-8)

  詳情 :  樹莓派 設置系統中文 並安裝中文輸入法

當很多人遇到

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 的錯誤,原因是python的str默認是ascii編碼,和unicode編碼沖突,就會報這個標題錯誤,解決辦法是

1. 開頭添加

                          import sys

                           reload(sys)

                           sys.setdefaultencoding('utf8') 

 

2.暴力一點,把所有中文字符 漢字什么的 包括注釋了的 都統統刪掉 也可以解決

 

 還有遇到 bottle 下載安裝后 ,運行說 沒有 安裝 bottle  可能是 你把 bottle 安裝到 python 2.7 環境下,而在python3 環境下找不到。

解決辦法:

1 在命令行中 用對應pythonX  環境下運行

2.在執行腳本代碼前 手動引包(得找到bottle 安裝路徑


如果你想了解更多樹莓派相關知識或則其他控制小車的手段

(如 自寫網頁,數據庫,語音控制等)

可以此處留言或前往Five-great的博客留言板進行交流討論 歡迎您的來訪

能幫助您 ,留點個贊 ,關注一波 …^_^…

 

最后 奉上 采用 websocket 的實現的代碼

先運行服務端代碼 car.py,然后再 運行 car.html

  car.py 代碼

#coding=utf8

import struct, socket, sys
import hashlib
import threading, random
import time
from base64 import b64encode, b64decode
import RPi.GPIO as GPIO
import sys 

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(17,GPIO.OUT)
p=GPIO.PWM(17,600)
p_pin =35
p.start(p_pin)
####  定義Car類
class Car(object):
    def __init__(self):

        self.inx_pin = [19,26,5,6]
####  self.inx_pin是控制端in的pin
        self.RightAhead_pin = self.inx_pin[0]
        self.LeftAhead_pin = self.inx_pin[1]
        self.RightBack_pin = self.inx_pin[2]
        self.LeftBack_pin = self.inx_pin[3]
####  分別是右輪前進,左輪前進,右輪退后,左輪退后的pin
        self.RightP_pin=17
        self.LeftP_pin =27 
        self.setup()
       
 
####  setup函數初始化端口
    def setup(self):
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
####  初始化使能端pin,設置成高電平
        pin = None
        for pin in self.inx_pin:
            GPIO.setup(pin,GPIO.OUT)
            GPIO.output(pin,GPIO.LOW)
####  初始化控制端pin,設置成低電平
        print ("setup ena enb pin over")
          
 
####  fornt函數,小車前進
    def front(self):
        self.setup()
        GPIO.output(self.RightAhead_pin,GPIO.HIGH)
        GPIO.output(self.LeftAhead_pin,GPIO.HIGH)
 
####  leftFront函數,小車左拐彎
    def leftFront(self):
        self.setup()
        GPIO.output(self.RightAhead_pin,GPIO.HIGH)
 
####  rightFront函數,小車右拐彎
    def rightFront(self):
        self.setup()
        GPIO.output(self.LeftAhead_pin,GPIO.HIGH)
 
####  rear函數,小車后退
    def rear(self):
        self.setup()
        GPIO.output(self.RightBack_pin,GPIO.HIGH)
        GPIO.output(self.LeftBack_pin,GPIO.HIGH)
 
####  leftRear函數,小車左退
    def leftRear(self):
        self.setup()
        GPIO.output(self.RightBack_pin,GPIO.HIGH)
 
####  rightRear函數,小車右退
    def rightRear(self):
        self.setup()
        GPIO.output(self.LeftBack_pin,GPIO.HIGH)

       
        
####  定義main主函數
def main(status):
    
    car = Car()

    if status == "front":
        car.front()
    elif status == "leftFront":
        car.leftFront()
    elif status == "rightFront":
        car.rightFront()
    elif status == "rear":
        car.rear()
    elif status == "leftRear":
        car.leftRear()
    elif status == "rightRear":
        car.rightRear()
    elif status == "stop":
        car.setup()      
        #p.stop()
    elif status == "q1":
        p.ChangeDutyCycle(35)
    elif status == "q2":
        p.ChangeDutyCycle(50)
    elif status == "q3":
        p.ChangeDutyCycle(75)
    elif status == "q4":
        p.ChangeDutyCycle(90)
    elif status == "q5":
        p.ChangeDutyCycle(100)



##socket
connectionlist = {}

def decode(data):
    if not len(data):
        return False

    # 用數據包的第二個字節,與127作與位運算,拿到前七位。
    length = data[1] & 127

    # 這七位在數據頭部分成為payload,如果payload等於126,就要再擴展2個字節。
    # 如果等於127,就要再擴展8個字節。
    # 如果小於等於125,那它就占這一個字節。
    if length == 126:
        extend_payload_len = data[2:4]
        mask = data[4:8]
        decoded = data[8:]
    elif length == 127:
        extend_payload_len = data[2:10]
        mask = data[10:14]
        decoded = data[14:]
    else:
        extend_payload_len = None
        mask = data[2:6]
        decoded = data[6:]
    
    byte_list = bytearray()

    print(mask)
    print(decoded)

    # 當payload確定之后,再往后數4個字節,這4個字節成為masking key,再之后的內容就是接收到的數據部分。
    # 數據部分的每一字節都要和masking key作異或位運算,得出來的結果就是真實的數據內容。
    for i in range(len(decoded)):
        chunk = decoded[i] ^ mask[i % 4]
        byte_list.append(chunk)
    
    new_str = str(byte_list, encoding="utf-8")
    print(new_str)
    return new_str

def encode(data):  
    data=str.encode(data)
    head = b'\x81'

    if len(data) < 126:
        head += struct.pack('B', len(data))
    elif len(data) <= 0xFFFF:
        head += struct.pack('!BH', 126, len(data))
    else:
        head += struct.pack('!BQ', 127, len(data))
    return head+data
                
def sendMessage(message):
    global connectionlist
    for connection in connectionlist.values():
        connection.send(encode(message))
 
def deleteconnection(item):
    global connectionlist
    del connectionlist['connection'+item]

class WebSocket(threading.Thread):

    GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

    def __init__(self,conn,index,name,remote, path="/"):
        threading.Thread.__init__(self)
        self.conn = conn
        self.index = index
        self.name = name
        self.remote = remote
        self.path = path
        self.buffer = ""     
    def run(self):
        print('Socket%s Start!' % self.index)
        headers = {}
        self.handshaken = False

        while True:
          try: 
            if self.handshaken == False:
                print ('Socket%s Start Handshaken with %s!' % (self.index,self.remote))
                self.buffer += bytes.decode(self.conn.recv(1024))

                if self.buffer.find('\r\n\r\n') != -1:
                    header, data = self.buffer.split('\r\n\r\n', 1)
                    for line in header.split("\r\n")[1:]:
                        key, value = line.split(": ", 1)
                        headers[key] = value

                    headers["Location"] = ("ws://%s%s" %(headers["Host"], self.path))
                    key = headers['Sec-WebSocket-Key']
                    token = b64encode(hashlib.sha1(str.encode(str(key + self.GUID))).digest())

                    handshake="HTTP/1.1 101 Switching Protocols\r\n"\
                        "Upgrade: websocket\r\n"\
                        "Connection: Upgrade\r\n"\
                        "Sec-WebSocket-Accept: "+bytes.decode(token)+"\r\n"\
                        "WebSocket-Origin: "+str(headers["Origin"])+"\r\n"\
                        "WebSocket-Location: "+str(headers["Location"])+"\r\n\r\n"
                    
                    self.conn.send(str.encode(str(handshake)))
                    self.handshaken = True  
                    print('Socket%s Handshaken with %s success!' %(self.index, self.remote))
                    sendMessage('Welcome, ' + self.name + ' !')

            else:
                msg = decode(self.conn.recv(1024))
                main(msg)
                if msg == 'quit':
                    print ('Socket%s Logout!' % (self.index))
                    nowTime = time.strftime('%H:%M:%S',time.localtime(time.time()))
                    sendMessage('%s %s say: %s' % (nowTime, self.remote, self.name+' Logout'))                  
                    deleteconnection(str(self.index))
                    self.conn.close()
                    break
                else:
                    #print('Socket%s Got msg:%s from %s!' % (self.index, msg, self.remote))
                    nowTime = time.strftime('%H:%M:%S',time.localtime(time.time()))
                    sendMessage('%s %s say: %s' % (nowTime, self.remote, msg))       
                
            self.buffer = ""
          except Exception as e:
            self.conn.close()

class WebSocketServer(object):
    def __init__(self):
        self.socket = None
    def begin(self):
        print( 'WebSocketServer Start!')
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind(("172.19.8.102", 8081))
        self.socket.listen(50)

        global connectionlist

        i = 0
        while True:
            connection, address = self.socket.accept()

            username=address[0]     
            newSocket = WebSocket(connection,i,username,address)
            newSocket.start()
            connectionlist['connection'+str(i)]=connection
            i = i + 1

if __name__ == "__main__":
    server = WebSocketServer()
    server.begin()

 

 car.html  代碼:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>遙控樹莓派</title>
    <link href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <script src="http://code.jquery.com/jquery.js"></script>
    <style type="text/css">
        #front {
            margin-left: 55px;
            margin-bottom: 3px;
        }
        #rear{
            margin-top: 3px;
            margin-left: 55px;
        }
        .btn{
             background: #62559f;
            }
    </style>
    <script>
  var socket;
        function init() {
            var host = "ws://192.168.1.111:8081/";
            try {
                socket = new WebSocket(host);
                socket.onopen = function () {
                 
                };
                socket.onmessage = function () {
                    
                };
                socket.onclose = function () {
                    
                };
            }
            catch (ex) {
                
            }
           
        }
        function send(msg) {
            try {
                socket.send(msg);
            } catch (ex) {
                
            }
        }
        window.onbeforeunload = function () {
            try {
                socket.send('quit');
                socket.close();
                socket = null;
            }
            catch (ex) {
                
            }
        };
     
       
 
 
    </script>
</head>
<body οnlοad="init()">
<div id="container" class="container">
    
    <div>
        <button id="front" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-up" οnclick="send('front')"></button>
    </div>
    <div>
 
        <button id='leftFront' class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-left" οnclick="send('leftFront')"></button>
        <button id='stop' class="btn btn-lg btn-primary glyphicon glyphicon-stop" οnclick="send('stop')"></button>
        <button id='rightFront' class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-right" οnclick="send('rightFront')"></button>
    </div>
    <div  style="height:50px;">
        <button id='rear' class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-down" οnclick="send('rear')"></button>
    </div>
    <div style="height:20px;"></div>
     <div style="height:50px;">
        <button id='leftRear' class="btn btn-lg btn-primary glyphicon" οnclick="send('leftRear')">左后轉</button>
        <button id='rightRear' class="btn btn-lg btn-primary glyphicon" οnclick="send('rightRear')">右后轉</button>
    </div>
     <div style="height:20px;"></div>
    <div  style="height:50px;">
        <button id='q1' class="btn btn-lg btn-primary glyphicon" οnclick="send('q1')">P1</button>
        <button id='q2' class="btn btn-lg btn-primary glyphicon" οnclick="send('q2')">P2</button>
        <button id='q3' class="btn btn-lg btn-primary glyphicon" οnclick="send('q3')">P3</button>
        <div style="height:20px;"></div>
        <button id='q4' class="btn btn-lg btn-primary glyphicon" οnclick="send('q4')">P4</button>
        <button id='q5' class="btn btn-lg btn-primary glyphicon" οnclick="send('q5')">P5</button>
    </div>
</div>
 
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>

注意: host 端口號要匹配哦 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM