sumorobot-firmware/main.py
2024-11-03 17:56:36 +02:00

102 lines
2.4 KiB
Python

import ubinascii
import _thread
import os
import network
from utime import sleep_ms
from machine import Timer, Pin, PWM
print("Press Ctrl-C to stop boot script...")
sleep_ms(200)
led_power = Pin(25, Pin.OUT)
led_power.value(1)
pwm_left = PWM(Pin(15), freq=50, duty=0)
pwm_right = PWM(Pin(13), freq=50, duty=0)
HOSTNAME = "sumo-%s" % \
ubinascii.hexlify(network.WLAN().config('mac'),':').decode().replace(":","")[6:]
url = "ws://sumo.koodur.com:80/p2p/%s/browser/" % HOSTNAME
ap_if = network.WLAN(network.AP_IF)
ap_if.active(False)
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.config(dhcp_hostname=HOSTNAME)
wlan.connect("sumo", "salakala")
#wlan.connect("k-space.ee legacy","")
while not wlan.isconnected():
print("Connecting to wifi...")
sleep_ms(100)
print("Connected to wifi!", wlan.ifconfig())
print("Hi my name is:")
print(HOSTNAME)
def map_vals(value, leftMin, leftMax, rightMin, rightMax):
#http://stackoverflow.com/questions/1969240/mapping-a-range-of-values-to-another
# Figure out how 'wide' each range is
leftSpan = leftMax - leftMin
rightSpan = rightMax - rightMin
# Convert the left range into a 0-1 range (float)
valueScaled = float(value - leftMin) / float(leftSpan)
# Convert the 0-1 range into a value in the right range.
return int(rightMin + (valueScaled * rightSpan))
import socket
import time
from time import sleep_ms
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.settimeout(0.3)
sock.bind(("", 44444))
while True:
try:
buf = sock.recv(20)
except OSError: # timed out
pwm_left.duty(0)
pwm_right.duty(0)
continue
try:
value, forward, backward = buf.decode("ascii").split(":")
except ValueError:
continue
forward, backward = int(forward), int(backward)
if forward:
left, right = 10, -10
elif backward:
left, right = -10, 10
else:
left, right = 0, 0
mapped = map_vals(int(value),-400,400,-10,10)
if abs(mapped) > 5:
left -= mapped
right -= mapped
if left < -10:
left = -10
if left > 10:
left = 10
if right < -10:
right = -10
if right > 10:
right = 10
if abs(left) > 2:
pwm_left.duty(78 + left)
else:
pwm_left.duty(0)
if abs(right) > 2:
pwm_right.duty(78 + right)
else:
pwm_right.duty(0)
sleep_ms(20)