使用手機上動作感測器控制藍芽小車
電路圖
程式列表
Thunkable程式
https://x.thunkable.com/copy/481e3e70e4ef7c5119d38bc83e974433
Python程式
|
from machine import Switch #Get button KEY library from machine import Pin, LED, UART, PWM from machine import delay
class Motor:
def __init__(self): self.motorR_pwmA = PWM(Pin.epy.PWM2, freq = 10000, duty = 0) self.motorR_pwmB = PWM(Pin.epy.PWM3, freq = 10000, duty = 0) self.motorL_pwmA = PWM(Pin.epy.PWM0, freq = 10000, duty = 0) self.motorL_pwmB = PWM(Pin.epy.PWM1, freq = 10000, duty = 0)
def forward(self): self.motorR_pwmA.duty(100) self.motorR_pwmB.duty(0) self.motorL_pwmA.duty(100) self.motorL_pwmB.duty(0)
def turnLeft(self): self.motorR_pwmA.duty(100) self.motorR_pwmB.duty(0) self.motorL_pwmA.duty(50) self.motorL_pwmB.duty(0)
def turnRight(self): self.motorR_pwmA.duty(50) self.motorR_pwmB.duty(0) self.motorL_pwmA.duty(100) self.motorL_pwmB.duty(0)
def backward(self): self.motorR_pwmA.duty(0) self.motorR_pwmB.duty(100) self.motorL_pwmA.duty(0) self.motorL_pwmB.duty(100)
def backLeft(self): self.motorR_pwmA.duty(0) self.motorR_pwmB.duty(100) self.motorL_pwmA.duty(0) self.motorL_pwmB.duty(50)
def backRight(self): self.motorR_pwmA.duty(0) self.motorR_pwmB.duty(50) self.motorL_pwmA.duty(0) self.motorL_pwmB.duty(100)
def stop(self): self.motorR_pwmA.duty(0) self.motorR_pwmB.duty(0) self.motorL_pwmA.duty(0) self.motorL_pwmB.duty(0)
def XY2LR(X, Y): if Y < -20: if X > 20: Car.turnRight() elif X < -20: Car.turnLeft() else: Car.forward() elif Y > 20: if X > 20: Car.backRight() elif X < -20: Car.backLeft() else: Car.backward() else : Car.stop()
def key_int(): global KeyADone KeyADone = True
def tick3(timer): global TimerDone TimerDone = True
# Start Function if __name__ == '__main__': ledy = LED('ledy') ledr = LED('ledr') ledg = LED('ledg')
KeyA = Switch('keya') #Create button A KeyA.callback(key_int) KeyADone = False
Car = Motor()
# Lite BLE on UART port 1, baudrate is 115200) ble = UART(1, 115200,timeout=200) #確保 BLE 回到 CMD mode ble.write('!CCMD@') delay(150) ble.write('!CCMD@') delay(150) # enable BLE System MSG ble.write('AT+EN_SYSMSG=1\r\n') delay(50)
while True: msg = ble.readline() recv_data = str(msg,'utf-8') #return a data string = recv_data.strip('\n') string = string.split(',') num=len(string)
print (msg,num) if(num == 2) : print (string[0],string[1]) XY2LR(int(string[1]), int(string[0])) #x,y
if recv_data == 'A' : ledy.toggle() if recv_data == 'B' : ledr.toggle() if recv_data == 'C' : ledg.toggle()
if KeyADone == True: #Press A Key break
ble.deinit() KeyA.callback(None) ledY.off() ledr.off() ledg.off()
|
執行畫面
沒有留言:
張貼留言