Created
July 18, 2022 15:59
-
-
Save lululombard/7663b61db89e63fc6202e1a8454e81b9 to your computer and use it in GitHub Desktop.
Pico solar tracker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from machine import Pin, ADC, PWM | |
import utime | |
MAX_DELTA_ALIGNED = 4000 | |
led = Pin(25, Pin.OUT) | |
servos = { | |
'pan': { | |
'min': 1000, | |
'max': 9000, | |
'current': 0, | |
'servo': PWM(Pin(19)), | |
}, | |
'tilt': { | |
'min': 1000, | |
'max': 5000, | |
'current': 0, | |
'servo': PWM(Pin(20)), | |
}, | |
} | |
sensors = { | |
'top': Pin(0, Pin.OUT), | |
'right': Pin(1, Pin.OUT), | |
'bottom': Pin(2, Pin.OUT), | |
'left': Pin(3, Pin.OUT), | |
} | |
adc = ADC(Pin(26)) | |
led.value(1) | |
for id, servo in servos.items(): | |
servo['servo'].freq(50) | |
max_light = 0 | |
for sensor, pin in sensors.items(): | |
pin.high() | |
for i in range(servo['max'], servo['min'], -10): | |
servo['servo'].duty_u16(i) | |
utime.sleep(0.01) | |
value = adc.read_u16() | |
if value > max_light: | |
max_light = value | |
servos[id]['current'] = i | |
servo['servo'].duty_u16(servos[id]['current']) | |
for sensor, pin in sensors.items(): | |
pin.low() | |
led.value(0) | |
def read_sensors(): | |
max_value = 0 | |
lowest_value = 65535 | |
max_sensor = None | |
readings = {} | |
for sensor, pin in sensors.items(): | |
pin.high() | |
utime.sleep(0.01) | |
value = adc.read_u16() | |
readings[sensor] = value | |
if value > max_value: | |
max_sensor = sensor | |
max_value = value | |
if value < lowest_value: | |
lowest_value = value | |
pin.low() | |
print(readings) | |
delta = max_value - lowest_value | |
if delta > MAX_DELTA_ALIGNED: | |
print(f'{max_sensor} {max_value} {lowest_value} {delta}') | |
servo_steps = delta // 100 | |
if servo_steps > 100: | |
servo_steps = 100 | |
updated = False | |
if max_sensor == 'top' and servos['tilt']['current'] > servos['tilt']['min']: | |
servos['tilt']['current'] -= servo_steps | |
updated = True | |
if max_sensor == 'bottom' and servos['tilt']['current'] < servos['tilt']['max']: | |
servos['tilt']['current'] += servo_steps | |
updated = True | |
if max_sensor == 'left' and servos['pan']['current'] > servos['pan']['min']: | |
servos['pan']['current'] -= servo_steps | |
updated = True | |
if max_sensor == 'right' and servos['pan']['current'] < servos['pan']['max']: | |
servos['pan']['current'] += servo_steps | |
updated = True | |
if updated: | |
led.value(1) | |
servos['pan']['servo'].duty_u16(servos['pan']['current']) | |
servos['tilt']['servo'].duty_u16(servos['tilt']['current']) | |
led.value(0) | |
print(servos) | |
while True: | |
print('----') | |
read_sensors() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment