Webről irányítható servo motor

A projekthez elég egy Raspberry Pi Pico W is.

A netre így tud csatlakozni (wifi.py):

import network

wifi_ssid = 'ssid'
wifi_password = 'password'
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(wifi_ssid, wifi_password)

A motort így tudod vezérelni (servomotor.py):

from machine import Pin, PWM
 
class Servo:
    def __init__(self, pin: int or Pin or PWM, minVal=1700, maxVal=8300):
        if isinstance(pin, int):
            pin = Pin(pin, Pin.OUT)
        if isinstance(pin, Pin):
            self.__pwm = PWM(pin)
        if isinstance(pin, PWM):
            self.__pwm = pin
        self.__pwm.freq(50)
        self.minVal = minVal
        self.maxVal = maxVal

    def deinit(self):
        self.__pwm.deinit()

    def goto(self, value: int):
        if value < 0:
            value = 0
        if value > 1024:
            value = 1024
        delta = self.maxVal - self.minVal
        target = int(self.minVal + ((value / 1024) * delta))
        self.__pwm.duty_u16(target)

    def middle(self):
        self.goto(512)

    def free(self):
        self.__pwm.duty_u16(0)
    
    def servo_Map(self,x, in_min, in_max, out_min, out_max):
        return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

    def servo_Angle(self,angle):
        if angle < 0:
            angle = 0
        if angle > 180:
            angle = 180
        self.goto(round(self.servo_Map(angle, 0, 180, 0, 1024)))   

És végül a program így néz ki (main.py):

import socket
import network
import ure as re
import servomotor
import wifi

motor = servomotor.Servo(0)
motor.servo_Angle(90)

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('', 8080))
server.listen(5)
print("Server listening on port 8080")

while True:
    client, addr = server.accept()
    request = client.recv(1024)
    request = str(request)

    match = re.search("GET /api\?angle=(\d+)", request)
    if match:
        value = match.group(1)
        motor.servo_Angle(int(value))
        print("Received value:", value)

    client.send("HTTP/1.1 200 OK\n\n")
    client.close()

Comments are closed.