MicroPython是Python的精简版,但保留了python的基本特色。是学习python的工具之一。
烧录软件用的是uPyCraft。
本案例用了ESP32 和 L298N电机驱动。以及两个直流电机。
电源用一块废旧手机电池,加上Type-c的充放电保护模块。方便充电使用
放了个测速 霍尔传感器也没有写程序,惆怅找不上工作,以后陆续更新
esp32作为无线Ap,接收手机命令,并且控制电机驱动使小车前进、后退、左右、停止。
esp32启动时,运行boot.py 开启热点,手机连接热点 打开192.168.1.4 对小车进行控制
小车电机驱动&指令接收:
from machine import Pin, PWM
import socket
import time
from time import sleep
html='''
ESP32 LED on/offWebServer for turning LED on
.box{ font-size:14px}
.box .f20{ font-size:20px}
LED ON
LED OFF
UP
DOWN
LEFT
RIGHT
STOP
'''
LED0 = Pin(2,Pin.OUT)
LED0.value(0)
#in1 = 12
#in2 = 13
#in3 = 27
#in4 = 26
def forward(speed):
pin2 = PWM (Pin(13), freq=1000)
pin1 = Pin(12, Pin.OUT)
pin4 = PWM (Pin(26), freq=1000)
pin3 = Pin(27, Pin.OUT)
pin2.duty(speed)
pin1.value(0)
pin4.duty(speed)
pin3.value(0)
sleep(0.5)
pin2.deinit()
pin4.deinit()
print("backwards")
def backwards(speed):
pin1 = PWM (Pin(12), freq=1000)
pin2 = Pin(13, Pin.OUT)
pin3 = PWM (Pin(27), freq=1000)
pin4 = Pin(26, Pin.OUT)
pin1.duty(speed)
pin2.value(0)
pin3.duty(speed)
pin4.value(0)
sleep(0.5)
pin1.deinit()
pin3.deinit()
print("forward")
def leftright(speed):
pin2 = PWM (Pin(13), freq=1000)
pin1 = Pin(12, Pin.OUT)
pin3 = PWM (Pin(27), freq=1000)
pin4 = Pin(26, Pin.OUT)
pin2.duty(speed)
pin1.value(0)
pin3.duty(speed)
pin4.value(0)
sleep(0.2)
pin2.deinit()
pin3.deinit()
print("left")
def (speed):
pin1 = PWM (Pin(12), freq=1000)
pin2 = Pin(13, Pin.OUT)
pin4 = PWM (Pin(26), freq=1000)
pin3 = Pin(27, Pin.OUT)
pin1.duty(speed)
pin2.value(0)
pin4.duty(speed)
pin3.value(0)
sleep(0.2
)
pin1.deinit()
pin4.deinit()
print("right")
def stop():
pin1 = Pin(12, Pin.OUT)
pin2 = Pin(13, Pin.OUT)
pin3 = Pin(27, Pin.OUT)
pin4 = Pin(26, Pin.OUT)
pin1.value(0)
pin2.value(0)
pin3.value(0)
pin4.value(0)
print("stop")
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('',80))
s.listen(5)
while True:
conn,addr=s.accept()
print("GOT a connection from %s" % str(addr))
request=conn.recv(1024)
print("Content %s" % str(request))
request=str(request)
LEDON=request.find('/?LED=ON')
LEDOFF=request.find('/?LED=OFF')
carUP=request.find('/?car=UP')
carDOWN=request.find('/?car=DOWN')
carLEFT=request.find('/?car=LEFT')
carRIGHT=request.find('/?car=RIGHT')
carSTOP=request.find('/?car=STOP')
if(LEDON==6):
LED0.value(1)
if(LEDOFF==6):
LED0.value(0)
if(carUP==6):
forward(1023)
#sleep (0.1)
#stop()
if(carDOWN==6):
backwards(1023)
#sleep(0.1)
#stop()
if(carLEFT==6):
left(1023)
#sleep(0.1)
#stop()
if(carRIGHT==6):
right(1023)
#sleep(0.1)
#stop()
if(carSTOP==6):
stop()
response=html
conn.send(response)
conn.close()
esp32配置为Ap(boot.py):
import network
ap = network.WLAN(network.AP_IF) #设为AP模式
ap.active(True)
ap.config(essid='Node',password="12345678") #配置wifi接入点