用藍芽指令操控小車

這是python Pipico 小車操控的第一篇 – 用藍芽指令操控。

完正整的程式碼在gitHub

https://github.com/Chen11111112/Pico-1.git

下載檔案解壓縮後將小車透過usb線連接電腦。

Thoony

  1. 官網下載thoony
  2. 在上方Tools選取Options,進入Interpreter頁面修改Interpreter為Pipico。
  3. 下方Prot選擇COM3 (車子的port)
  4. thoony不能直接打開資料夾,要透過路徑一步步去找到。(找到moto.py)
  5. 按上方綠色的”執行”。
  6. 會輸出” Pico 小車測試(最終校正版)”在終端機,此時就可以根據指令操控小車了!!

修改藍芽對外名稱

  1. 將blue.py這個檔案另存為(Save as)blue在Raspberry Pi Pico。
  2. 執行change_ble_name_uuid.py這個檔案。

執行藍芽

  1. 將bot.py這個檔案另存為(Save as)bot在Raspberry Pi Pico。
  2. 執行rcbot.py這個檔案。
  3. 此時在終端機輸入任何指令都是無效的,因為現在要透過藍芽來輸入了!!

nRF Connect

藍芽測試的開發工具。

  1. 在行動裝置上下載nRF Connect
  2. 可參考以下文件輸入藍芽指令
  3. 此時傳入wsad等指令就可以跑起來了!!!!!!!!!
  4. 不過你會發現方向是錯的OwO

本檔案係經台北商業大學李文毅老師授權提供,作為其自走車自主學習練習教材使用。裡面有一些些老師故意留的bug,我已經幫忙修掉一些了。但還是留了一些給要下載的各位

/

須修錯誤

在bot.py中:

from machine import Pin, UART
import time

# ===== 馬達控制腳位 =====
M1_A = Pin(12, Pin.OUT)   # 左輪
M1_B = Pin(13, Pin.OUT)

M2_A = Pin(10, Pin.OUT)   # 右輪(實體方向相反)
M2_B = Pin(11, Pin.OUT)

# ===== 單顆馬達方向控制 =====
def _set_motor(a, b, v):
    if v > 0:          # 正轉
        a.value(1)
        b.value(0)
    elif v < 0:        # 反轉
        a.value(0)
        b.value(1)
    else:              # 停止
        a.value(0)
        b.value(0)

# 左輪:正常
def left(v):
    _set_motor(M1_A, M1_B, v)

# 右輪:補償實體反向(關鍵在這)
def right(v):
    _set_motor(M2_A, M2_B, -v)

# ===== 動作定義(現在全部都會正確) =====
def stop():
    left(0)
    right(0)

def back():
    left(1)
    right(1)

def forward():
    left(-1)
    right(-1)

def left_t():
    left(-1)
    right(1)

def right_t():
    left(1)
    right(-1)

# ===== BLE UART =====
ble = UART(0, 115200, tx=Pin(0), rx=Pin(1))

print("BLE 車子啟動完成(方向已校正)")

stop()

# ===== 主迴圈 =====
while True:
    if ble.any():
        ch = ble.read(1)
        if not ch:
            continue

        cmd = ch.decode().lower()

        if cmd == 'w':
            forward()
        elif cmd == 's':
            back()
        elif cmd == 'a':
            left_t()
        elif cmd == 'd':
            right_t()
        elif cmd == 'x':
            stop()

    time.sleep(0.05)

Leave a Reply

Your email address will not be published. Required fields are marked *