赞
踩
有了前面的经验,我们现在用esp32实现http服务器
我们要实现通过网页控制四个舵机
esp32开发板一个
esp32拓展板一个
舵机四个
简单组装
注意接口(线头颜色千万别插反了!!!)
在MicroPython设备 新建目录结构
lib 存放一些库文件
common
public 存放网页内容
main.py (程序主入口)
# 导入PWM库 from machine import PWM # 数学库 import math # 构造函数 class Servo: def __init__(self,pin,freq=50,min_us=600,max_us=2400,angle=180): self.min_us = min_us self.max_us = max_us self.us = 0 self.freq = freq self.angle = angle self.pwm =PWM(pin,freq=freq,duty=0) def write_us(self,us): if us == 0: self.pwm.duty(0) return us = min(self.max_us,max(self.min_us,us)) duty = us *1024 * self.freq // 1000000 self.pwm.duty(duty) def write_angle(self,degrees=None,redians=None): if degrees is None: degrees = math.degrees(radians) degrees = degrees % 360 total_range = self.max_us - self.min_us us = self.min_us + total_range * degrees // self.angle self.write_us(us)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>滑动</title> </head> <body> <h1>滑动四个电机</h1> <input type="range" min="0" max="180" value="1" step="1" name="" id=""> <div class="content"> </div> <script> let ipt = document.querySelector("input") let content = document.querySelector(".content") // 防抖函数 防止服务器接受大量请求 const throttle = (func,interval)=>{ let last = 0; return function(){ let args = arguments let now = Date.now(); if(now - last > interval){ func.apply(this,args) last = now } } } ipt.addEventListener("input",throttle((e)=>{ let value = ipt.value fetch("/move/"+value,{ }).then(e=>{ content.innerHTML = e.status }).catch(err=>{ content.innerHTML = "error"+err }) },500)) </script> </body> </html>
# 导入Microdot from lib.microdot import Microdot,send_file # 连接wifi from common.connect_wifi import do_connect from common.servo import Servo # 导入引脚 from machine import Pin # 对应四个电机 从左上角顺时针排序 s1 = Servo(Pin(15)) s2 = Servo(Pin(17)) s3 = Servo(Pin(25)) s4 = Servo(Pin(27)) # 复位 s1.write_angle(0) s2.write_angle(180-0) s3.write_angle(180-0) s4.write_angle(0) # esp32 引脚2是一颗自带的 led的灯 light = Pin(2,Pin.OUT) # 开始连接wifi do_connect() # 实例化这个类 app = Microdot() # get请求返回一个网页 @app.route('/') def index(request): return send_file('public/index.html') # 设置一个get请求 如果收到信息就操作舵机 @app.get('/move/<int:angle>') def index(request,angle): print("angle",angle) # angle为前端发过来的舵机旋转角度 s1.write_angle(angle) # 这里用180-angle因为2,3舵机在右侧 s2.write_angle(180-angle) s3.write_angle(180-angle) s4.write_angle(angle) return "移动到:"+angle # 端口号为5000 app.run(host='0.0.0.0', port=5000, debug=False, ssl=None)
完成了哈哈哈哈项目视频展示
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。