# Professor Cristiano Teixeira
# Sob Licença Apache 2.0
print("INICIO")
import machine, time
from machine import Pin, PWM
import math
import neopixel
frequency = 5000
#### Classe Servo ####
class Servo:
# these defaults work for the standard TowerPro SG90
__servo_pwm_freq = 50
__min_u10_duty = 26 - 0 # offset for correction
__max_u10_duty = 123- 0 # offset for correction
min_angle = 0
max_angle = 180
current_angle = 0.001
def __init__(self, pin):
self.__initialise(pin)
def update_settings(self, servo_pwm_freq, min_u10_duty, max_u10_duty, min_angle, max_angle, pin):
self.__servo_pwm_freq = servo_pwm_freq
self.__min_u10_duty = min_u10_duty
self.__max_u10_duty = max_u10_duty
self.min_angle = min_angle
self.max_angle = max_angle
self.__initialise(pin)
def move(self, angle):
# round to 2 decimal places, so we have a chance of reducing unwanted servo adjustments
angle = round(angle, 2)
# do we need to move?
if angle == self.current_angle:
return
self.current_angle = angle
# calculate the new duty cycle and move the motor
duty_u10 = self.__angle_to_u10_duty(angle)
self.__motor.duty(duty_u10)
def __angle_to_u10_duty(self, angle):
return int((angle - self.min_angle) * self.__angle_conversion_factor) + self.__min_u10_duty
def __initialise(self, pin):
self.current_angle = -0.001
self.__angle_conversion_factor = (self.__max_u10_duty - self.__min_u10_duty) / (self.max_angle - self.min_angle)
self.__motor = PWM(Pin(pin))
self.__motor.freq(self.__servo_pwm_freq)
##########################################
# from servo import Servo
# Criamos a instância para o servo no pino 14
servo1 = Servo(pin=14)
servo1.move(91) # Movimento inicial
# -------------------- Configuracao do hardware --------------------
PINO_DIN = 2 # GPIO D2 do ESP32 ligado ao DIN da matriz
LINHAS = 16
COLUNAS = 16
NUM_LEDS = LINHAS * COLUNAS # 64 LEDs
np = neopixel.NeoPixel(Pin(PINO_DIN), NUM_LEDS)
# Funções de exibição básicas:
def led(linha, coluna, cor):
"""Acende o LED na posicao (linha, coluna) com a cor (r, g, b)."""
if 0 <= linha < LINHAS and 0 <= coluna < COLUNAS:
idx = linha * COLUNAS + coluna
np[idx] = cor
def apagar():
"""Desliga todos os LEDs."""
np.fill((0, 0, 0))
np.write()
def mostrar():
"""Envia os dados do buffer para a matriz."""
np.write()
# Função Delay prá matar a saudade do Arduino
def delay(ms):
time.sleep_ms(ms)
#Função que calcula a distância com ultrassom
def distancia():
echo_timeout = echo_timeout=500*2*30
trigger = Pin(13, Pin.OUT, pull=None)
echo = Pin(12, Pin.IN, pull=None)
trigger.value(0)
# Aguarda 5 milisegundos.
time.sleep_us(5)
trigger.value(1)
# Aguarda 10 milisegundos.
time.sleep_us(10)
trigger.value(0)
try:
pulse_time = machine.time_pulse_us(echo, 1, echo_timeout)
except OSError as ex:
if ex.args[0] == 110: # 110 = ETIMEDOUT
raise OSError('Fora de Alcance')
raise ex
cms = (pulse_time / 2) / 29.1
print ("Distância: ",cms, "cms")
return cms
# Teste Preenche tudo de tres cores.
def cores_separadas():
"""Acende a matriz inteira de vermelho, depois verde, depois azul."""
cores = [
(255, 0, 0), # Vermelho
(0, 255, 0), # Verde
(0, 0, 255), # Azul
]
nomes = ["VERMELHO", "VERDE", "AZUL"]
for cor, nome in zip(cores, nomes):
print("Cor:", nome)
np.fill(cor)
np.write()
delay(800)
apagar()
cores_separadas()
while True:
distancia()
# Fazer movimento do Servo Motor da esquerda para a direita 10 150
# E voltando 150 a 10
# porque 10 a 150? Para na posição de 85 à 95 preencher as duas linhas centrais. Vamos ver se dá certo.
# Calcula a distância a cada 10 graus movidos registra a distância e guarda em uma matriz de 16 x 16 sendo o endereço 0 e 0 15 Zonas mortas
# A posiçaõ inicial do sensor é [16] [8] e [16] [9] ocupa 2 posições