Ejemplo n.º 1
0
class Servo:
    def __init__(self, pin, freq=SERVO_FREQUENCY, timer=2):
        """
        Create a new Servo instance

        @param pin: 	    the machine.Pin on which the servo is connected
        @param freq:        the frequency at which the PWM signal should be generated
        """
        self.min_pct = SERVO_MIN_PCT
        self.max_pct = SERVO_MAX_PCT
        self.freq = freq

        self.pct_per_degree = (self.max_pct - self.min_pct) / float(180)

        self.pwm = PWM(pin, freq=freq, timer=timer)
        self.angle(90)

    def tune(self, min_pct, max_pct):
        self.min_pct = min_pct
        self.max_pct = max_pct

        self.pct_per_degree = (self.max_pct - self.min_pct) / float(180)

    def angle(self, angle=None):
        if angle is None:
            return (self.pwm.duty() - self.min_pct) / self.pct_per_degree
        else:
            if 0 <= angle <= 180:
                self.pwm.duty(angle * self.pct_per_degree + self.min_pct)
Ejemplo n.º 2
0
def pulse():
    for i in range(0, 101):
        p = PWM(0, Pin("P17", mode=Pin.OUT), freq=PWM.FREQ_16MHZ, duty=i, period=16000)
        p.init()
        time.sleep_ms(10)
        p.deinit()

    for i in range(0, 101):
        p = PWM(0, Pin("P17", mode=Pin.OUT), freq=PWM.FREQ_16MHZ, duty=100-i, period=16000)
        p.init()
        time.sleep_ms(10)
        p.deinit()
Ejemplo n.º 3
0
class MPythonPin(Pin):
    def __init__(self, pin, mode=PinMode.IN):
        if mode not in [PinMode.IN, PinMode.OUT, PinMode.PWM, PinMode.ANALOG]:
            raise TypeError("mode must be 'IN, OUT, PWM, ANALOG'")
        if pin == 3:
            raise TypeError("pin3 is used for resistance sensor")
        if pin == 4:
            raise TypeError("pin4 is used for light sensor")
        if pin == 10:
            raise TypeError("pin10 is used for sound sensor")
        self.id = pins_remap_esp32[pin]
        if mode == PinMode.IN:
            super().__init__(self.id, Pin.IN, Pin.PULL_UP)
        if mode == PinMode.OUT:
            if pin == 2:
                raise TypeError('pin2 only can be set "IN, ANALOG"')
            super().__init__(self.id, Pin.OUT)
        if mode == PinMode.PWM:
            if pin == 2:
                raise TypeError('pin2 only can be set "IN, ANALOG"')
            self.pwm = PWM(Pin(self.id), duty=0)
        if mode == PinMode.ANALOG:
            if pin not in [0, 1, 2, 3, 4, 10]:
                raise TypeError('the pin can~t be set as analog')
            self.adc = ADC(Pin(self.id))
            self.adc.atten(ADC.ATTN_11DB)
        self.mode = mode

    def read_digital(self):
        if not self.mode == PinMode.IN:
            raise TypeError('the pin is not in IN mode')
        return super().value()

    def write_digital(self, value):
        if not self.mode == PinMode.OUT:
            raise TypeError('the pin is not in OUT mode')
        super().value(value)

    def read_analog(self):
        if not self.mode == PinMode.ANALOG:
            raise TypeError('the pin is not in ANALOG mode')
        return self.adc.read()

    def write_analog(self, duty, freq=1000):
        if not self.mode == PinMode.PWM:
            raise TypeError('the pin is not in PWM mode')        
        self.pwm.freq(freq)
        self.pwm.duty(duty)
Ejemplo n.º 4
0
    def __init__(self, pin=Pin(33)):
        """
        Create a new Buzzer instance

        @param pin: 	the machine.Pin on which the servo is connected
        """
        self.pwm = PWM(pin, freq=3000)
Ejemplo n.º 5
0
 def play(self,tune,pin=27,duration=None):
  from machine import Pin,PWM
  from utime import sleep_ms
  pwm=PWM(Pin(pin))
  if duration is None:
   self.set_default(tune[0])
  else:
   self.set_duration(duration)
  for tone in tune:
   tone=tone.upper()
   if tone[0]not in Letter:
    continue
   midi=self.midi(tone)
   pwm.freq(midi[0])
   sleep_ms(midi[1])
  pwm.deinit()
Ejemplo n.º 6
0
 def __init__(self,pin,mode=PinMode.IN):
  if mode not in[PinMode.IN,PinMode.OUT,PinMode.PWM,PinMode.ANALOG]:
   raise TypeError("mode must be 'IN, OUT, PWM, ANALOG'")
  if pin==3:
   raise TypeError("pin3 is used for resistance sensor")
  if pin==4:
   raise TypeError("pin4 is used for light sensor")
  if pin==10:
   raise TypeError("pin10 is used for sound sensor")
  self.id=pins_remap_esp32[pin]
  if mode==PinMode.IN:
   super().__init__(self.id,Pin.IN,Pin.PULL_UP)
  if mode==PinMode.OUT:
   if pin==2:
    raise TypeError('pin2 only can be set "IN, ANALOG"')
   super().__init__(self.id,Pin.OUT)
  if mode==PinMode.PWM:
   if pin==2:
    raise TypeError('pin2 only can be set "IN, ANALOG"')
   self.pwm=PWM(Pin(self.id),duty=0)
  if mode==PinMode.ANALOG:
   if pin not in[0,1,2,3,4,10]:
    raise TypeError('the pin can~t be set as analog')
   self.adc=ADC(Pin(self.id))
   self.adc.atten(ADC.ATTN_11DB)
  self.mode=mode
Ejemplo n.º 7
0
def play_show(tune, pin=27, display=matrix.display, duration=None):
    from machine import Pin, PWM
    from utime import sleep_ms

    try:
        pwm = PWM(Pin(pin))
        if duration is None:
            set_default(tune[0])
        else:
            set_duration(duration)
        for tone in tune:
            tone = tone.upper()  # all to upper
            if tone[0] not in Letter:
                continue
            if len(tone)==4:
                display.showstatic(tone.replace(":",""))
            else:
                display.showstatic(tone)
            m = midi(tone)
            pwm.freq(m[0])  # set frequency
            pwm.duty(m[1])  # set duty cycle
            sleep_ms(m[1])
        display.clear()
    finally:
        pwm.deinit()
Ejemplo n.º 8
0
class Buzz(object):
 def __init__(self,pin=6):
  self.id=pins_remap_esp32[pin]
  self.io=Pin(self.id)
  self.io.value(1)
  self.isOn=False
 def on(self,freq=500):
  if self.isOn is False:
   self.pwm=PWM(self.io,freq,512)
   self.isOn=True
 def off(self):
  if self.isOn:
   self.pwm.deinit()
   self.io.init(self.id,Pin.OUT)
   self.io.value(1)
   self.isOn=False
 def freq(self,freq):
  self.pwm.freq(freq)
Ejemplo n.º 9
0
def stop(pin=27):
    from machine import Pin, PWM
    try:
        pwm = PWM(Pin(pin))
        pwm.duty(0)
        pwm.freq(1)
    finally:
        pwm.deinit()
Ejemplo n.º 10
0
 def play_show(self,tune,pin=27,display=matrix.display,duration=None):
  from machine import Pin,PWM
  from utime import sleep_ms
  pwm=PWM(Pin(pin))
  if duration is None:
   self.set_default(tune[0])
  else:
   self.set_duration(duration)
  for tone in tune:
   tone=tone.upper()
   if tone[0]not in Letter:
    continue
   if len(tone)==4:
    display.showstatic(tone.replace(":",""))
   else:
    display.showstatic(tone)
   midi=self.midi(tone)
   pwm.freq(midi[0])
   sleep_ms(midi[1])
  display.clear()
  pwm.deinit()
Ejemplo n.º 11
0
def pitch(freq,pin=27,tim=1000):
 from machine import Pin,PWM
 from utime import sleep_ms
 try:
  pwm=PWM(Pin(pin))
  pwm.freq(freq)
  pwm.duty(tim)
  sleep_ms(tim)
 finally:
  pwm.deinit()
Ejemplo n.º 12
0
class Buzzer:
    def __init__(self, pin=Pin(33)):
        """
        Create a new Buzzer instance

        @param pin: 	the machine.Pin on which the servo is connected
        """
        self.pwm = PWM(pin, freq=3000)

    def enable(self):
        """
        Enable the output of the buzzer
        """
        self.pwm.resume()

    def disable(self):
        """
        Disable the output of the buzzer
        """
        self.pwm.pause()

    def set(self, freq):
        """
        Set the frequency

        @param freq:     the frequency to set
        """
        self.pwm.duty(freq)
Ejemplo n.º 13
0
 def pitch(self,pin=27,freq=440,tim=0):
  from machine import Pin,PWM
  from utime import sleep_ms
  pwm=PWM(Pin(pin))
  if freq>0:
   pwm.freq(int(freq))
  else:
   pwm.duty(0)
  if tim>0:
   sleep_ms(tim)
   pwm.deinit()
Ejemplo n.º 14
0
    def __init__(self, pin, lower_duty=512, upper_duty=1953.5, freq=50):
        """
        Create a new Servo instance

        The lower and upper duty values may be tweaked depending on the servo model being used.

        @param pin: 	    the machine.Pin on which the servo is connected
        @param lower_duty: 	the lower duty value
        @param upper_duty:	the upper duty value
        @param freq:        the frequency at which the PWM signal should be generated
        """
        self.pwm = PWM(pin, freq=freq)
        self.lower_duty = (lower_duty * freq) / 10000
        self.upper_duty = (upper_duty * freq) / 10000
Ejemplo n.º 15
0
    def __init__(self, pin, freq=SERVO_FREQUENCY, timer=2):
        """
        Create a new Servo instance

        @param pin: 	    the machine.Pin on which the servo is connected
        @param freq:        the frequency at which the PWM signal should be generated
        """
        self.min_pct = SERVO_MIN_PCT
        self.max_pct = SERVO_MAX_PCT
        self.freq = freq

        self.pct_per_degree = (self.max_pct - self.min_pct) / float(180)

        self.pwm = PWM(pin, freq=freq, timer=timer)
        self.angle(90)
Ejemplo n.º 16
0
def play(tune,pin=27,duration=None):
 from machine import Pin,PWM
 from utime import sleep_ms
 try:
  pwm=PWM(Pin(pin))
  if duration is None:
   set_default(tune[0])
  else:
   set_duration(duration)
  for tone in tune:
   tone=tone.upper()
   if tone[0]not in Letter:
    continue
   m=midi(tone)
   pwm.freq(m[0])
   pwm.duty(m[1])
   sleep_ms(m[1])
 finally:
  pwm.deinit()
Ejemplo n.º 17
0
# D2,GPIO 4 Enable B
# D3,GPIO 0 Direction A
# D4,GPIO 2 Direction B

v = '0.8'

pwm_frequency = 750

speed_STOP = 0
speed_min = 400  # Depends on batteries state
speed_med = 600
speed_max = 1023

current_speed = speed_med

speedB = PWM(Pin(4, Pin.OUT), freq=pwm_frequency)
dirB = Pin(2, Pin.OUT)
dirA = Pin(0, Pin.OUT)
speedA = PWM(Pin(5, Pin.OUT), freq=750)


def stop():
    speedA.duty(speed_STOP)
    speedB.duty(speed_STOP)


def backward(speed=current_speed):
    speedA.duty(speed)
    speedB.duty(speed)
    dirA.off()
    dirB.off()
Ejemplo n.º 18
0
 def stop(self, pin=27):
     from machine import Pin, PWM
     pwm = PWM(Pin(pin))
     pwm.duty(0)
     pwm.freq(1)
     pwm.deinit()
Ejemplo n.º 19
0
 def lowBeep(self):
     if self.playSound:
         beeper = PWM(Pin(self.Buzzer, Pin.OUT), freq=440, duty=512)
         utime.sleep_ms(20)
         beeper.deinit()
Ejemplo n.º 20
0
from rtttl import RTTTL
from machine import Pin, PWM
import songs
import time

speaker_pin = Pin(19, Pin.OUT)  # Speaker is connected to this pin

# Initialize input/output pins
pwm = PWM(speaker_pin, freq=20000, duty=0) # create and configure in one go


def play_tone(freq, msec):
#    print('freq = {:6.1f} msec = {:6.1f}'.format(freq, msec))
    if freq > 0:
        pwm.freq(int(freq))     # Set frequency
        pwm.duty(512)           # 50% duty cycle
        time.sleep(msec*0.001)  # Play for a number of msec
        pwm.duty(0)             # Stop playing
        time.sleep(0.05)        # Delay 50 ms between notes

tune = RTTTL(Songs.find('Entertainer'))

for freq, msec in tune.notes():
    play_tone(freq, msec)
# Complete project details at https://RandomNerdTutorials.com
# Created by Rui Santos

from machine import Pin, ADC, PWM
from time import sleep

led = Pin(2, Pin.OUT)
button = Pin(15, Pin.IN)

#Configure ADC for ESP32
pot = ADC(Pin(34))
pot.width(ADC.WIDTH_10BIT)
pot.atten(ADC.ATTN_11DB)

#Configure ADC for ESP8266
#pot = ADC(0)

led_pwm = PWM(Pin(4),5000)

while True:
  button_state = button.value()
  led.value(button_state)

  pot_value = pot.read()
  led_pwm.duty(pot_value)

  sleep(0.1)
Ejemplo n.º 22
0
def buzzerSing(notes, tempo_ms):
    for note, delay in notes:
        buzzer = PWM(Pin(BUZZER_PIN), freq=note, duty=512)
        utime.sleep_ms(int(delay * tempo_ms))
        buzzer.deinit()
Ejemplo n.º 23
0
class Rodas:
    def __init__(self):
        ## Frequencia de trabalho do motor
        # O valor maximo e 1024
        self.freqA = 900
        self.freqB = 900
        ## Os pinos para o Shield ESP s鑼玱 fixos
        # Para o motor A, esquerdo, os pinos sao:
        # 5 para velocidade e 0 para dire鑾借尗o
        self.PwmA = PWM(Pin(5), freq=1000, duty=0)
        self.DirA = Pin(0, Pin.OUT)
        # Para o motor A, esquerdo, os pinos sao:
        # 5 para velocidade e 0 para dire閼剧禈o
        self.PwmB = PWM(Pin(4), freq=1000, duty=0)
        self.DirB = Pin(2, Pin.OUT)
        # Os pinos a seguir foram ocupados
        # para controlar a ponte H
        # D1 = GPIO 5
        # D2 = GPIO 4
        # D3 = GPIO 0
        # D4 = GPIO 2

    def frente(self):
        #print("frente")
        self.PwmA.duty(1000)
        self.PwmB.duty(1000)
        self.DirA.off()
        self.DirB.off()

    def re(self):
        #print("re")
        self.PwmA.duty(1000)
        self.PwmB.duty(1000)
        self.DirA.on()
        self.DirB.on()

    def esquerda(self):
        #print("esquerda")
        self.PwmA.duty(1000)
        self.PwmB.duty(1000)
        self.DirA.on()
        self.DirB.off()

    def direita(self):
        #print("direita")
        self.PwmA.duty(1000)
        self.PwmB.duty(1000)
        self.DirA.off()
        self.DirB.on()

    def parar(self):
        #print("parar")
        self.PwmA.duty(0)
        self.PwmB.duty(0)
        self.DirA.off()
        self.DirB.off()
Ejemplo n.º 24
0
ESC_IDLE = 40


def toggle(pwm):
    pwm.deinit()
    sleep_ms(50)
    pwm.init()


timer_motors = Timer(1)
timer_sensor = Timer(2)

motors_enable = Pin(16, mode=Pin.OUT)
motors_enable.value(0)

motor1_speed = PWM(Pin(2, mode=Pin.OUT), freq=6000, duty=ESCON_MIN)
motor2_speed = PWM(Pin(12, mode=Pin.OUT), freq=6000, duty=ESCON_MIN)
motor3_speed = PWM(Pin(15, mode=Pin.OUT), freq=6000, duty=ESCON_MIN)
motor1_reverse = Pin(0, mode=Pin.OUT)
motor2_reverse = Pin(14, mode=Pin.OUT)
motor3_reverse = Pin(13, mode=Pin.OUT)

toggle(motor1_speed)
toggle(motor2_speed)
toggle(motor3_speed)

# relay
p = Pin(5, mode=Pin.OUT, value=0)
p.value(0)

# # ball sensor
Ejemplo n.º 25
0
 def __init__(self,pin_vel,pin_dir):
     self.Pwm = PWM(Pin(pin_vel), freq=1000 ,duty = 0)
     self.Dir= Pin(pin_dir, Pin.OUT)
Ejemplo n.º 26
0
 def __init__(self, pin, angle):
     print(pin)
     self._servo = PWM(Pin(pin),
                       duty=self._angleToDuty(angle),
                       freq=JointServo.FREQ)
Ejemplo n.º 27
0
    time.sleep(.1)
dist.stop()  # saves power

# mpu
from mpu6050 import MPU6050
accel = MPU6050(i2c)
#print some values:
accel.val_test()
#read once:
accel_reading = accel.get_values()

#servo
#simple servo controll with PWM
#assuming servo is plugged in GPIO26 (last of the Vbat connectors)
from machine import PWM
servo = PWM(Pin(26), freq=50)
servo.duty(8)  # 8% of 50 Hz = 16 milliseconds ~ about center
time.sleep(1)
for i in range(5):
    np.set(0, 0xFF0000)  #red
    np.show()
    servo.duty(13)  # 26 milliseconds about max
    time.sleep(1)
    np.set(0, 0x0000FF)  #blue
    np.show()
    servo.duty(3)  #6 millisec about min
    time.sleep(1)

#motors
# if pwm sound is anoying, frequency can be changed
# motors run at high speed but low torque
Ejemplo n.º 28
0
so = Pin(A14, mode=Pin.IN)
cs = Pin(A15, mode=Pin.OUT)
sck = Pin(A6, mode=Pin.OUT)
thermo = MAX6675(sck, cs, so)

################################
# DC MOTOR                     #
################################
p20 = Pin(A20, mode=Pin.OUT)
p21 = Pin(A21, mode=Pin.OUT)

f = 100000
HI = 100
LO = 100  #MOTOR STARTS OFF NOT RUNNING

xIN1 = PWM(p20, freq=f, duty=HI)
xIN2 = PWM(p21, freq=f, duty=LO)

################################
# MAIN PROGRAM                 #
################################

mqtt.publish(topic, \
    "BoserBeater is now running." \
    "\r\r[INSTRUCTIONS]" \
    "\r -Input speed range: 0 - 100" \
    "\r -Starting speed = 0. Input a speed from 0 to 100." \
    "\r  Speeds 100 or greater will result in max speed." \
    "\r\r -Every 20 seconds, speed can be changed. " \
    "\r -Time elapsed and current temperature will also be displayed." \
    "\r\r -Input of '-1' will terminate the program!")
Ejemplo n.º 29
0
# analog_out.py
# 利用模拟输出(pwm)实现灯亮度调节

from machine import Pin, PWM
import time

# led引脚初始化,频率为1HZ,每秒闪烁一次
led_pin = PWM(Pin(16), freq = 1023, duty = 0)

while True:
  for i in range(0,1024):
    led_pin.duty(i)
    time.sleep_ms(10)


Ejemplo n.º 30
0
from machine import Pin, PWM
import time
 
led = PWM(Pin(2),freq=1000) # DPIO2對應到D4 

while True:
    for n in range(1023,-1,-1): #燈漸亮
        led.duty(n)
        time.sleep_ms(5)
    for n in range(1024):      #燈漸熄
        led.duty(n)
        time.sleep_ms(5)
    print("change")
Ejemplo n.º 31
0
 def buzzerBeep(self, note, delay):
     buzzer = PWM(Pin(self.buzzer_pin), freq=note, duty=512)
     utime.sleep_ms(delay)
     buzzer.deinit()
Ejemplo n.º 32
0
    elif len(lect)==3:
        lect='0'+lect
    return lect

def send_marker(flag):
    if(flag==True):
        mark='9999'
        uart.write(bytearray(mark))
    else:
        return None

#uos.dupterm(None,1)
uart=UART(0,115200)
uart.init(115200,bits=8,parity=None,stop=1)

led=PWM(Pin(5))
led.freq(90)
input_adc=ADC(0)
lect=0
i=0
flag=True
while True:
    if uart.any()>0:
        #uart.write(i)
        lect=input_adc.read()
        if(lect==b'ok'):
            flag=False
        #print(type(lect))
        led.duty(lect)# va desde 0 a 1023
        #print('ingrese valor de 0 a 1024')
        #a=input()
Ejemplo n.º 33
0
def beep(freq=440, duration=0.1):
    pwm = PWM(Pin(25, Pin.OUT))
    pwm.duty(512)
    pwm.freq(freq)
    sleep(duration)
    pwm.deinit()
Ejemplo n.º 34
0
# -*- coding: utf-8 -*-
"""
   程式說明請參閱9-11頁
"""

from machine import Pin, PWM
import time

swPin = Pin(0, Pin.IN)
buzzer = PWM(Pin(14))

print('Start!')

try:
    while True:
        if swPin.value() == 0:
            buzzer.duty(900)
            buzzer.freq(500)
            time.sleep(1.5)
            buzzer.duty(0)
except:
    buzzer.deinit()
    print('Game Over')
Ejemplo n.º 35
0
        return p, v, t
    if i == 3:
        return p, q, v
    if i == 4:
        return t, p, v
    if i == 5:
        return v, p, q


def pulse(led_red, led_green, led_blue, t):
    for i in range(0, 60):
        r, g, b = hsv_to_rgb(i/60.0, 1.0, 1.0)

        led_red.duty(int(r * DUTY))
        led_green.duty(int(g * DUTY))
        led_blue.duty(int(b * DUTY))
        
        time.sleep_ms(t)


led_red = PWM(Pin(23), freq=FREQ, duty=0)
led_green = PWM(Pin(22), freq=FREQ, duty=0)
led_blue = PWM(Pin(21), freq=FREQ, duty=0)

for i in range(CYCLES):
    pulse(led_red, led_green, led_blue, STEP_DELAY_MS)

led_red.deinit()
led_green.deinit()
led_blue.deinit()
import time
import machine
from machine import Pin, PWM, ADC

led = Pin(0, Pin.OUT)
piezo = Pin(12, Pin.OUT)

pwm1 = PWM(led)
pwm2 = PWM(piezo)

adc = machine.ADC(0)


def brightness(pwm1, a):
    pwm1.duty(a)


def pitch(pwm2, a):
    pwm2.duty(a)


button_edge = Pin(14, Pin.IN, Pin.PULL_UP)


def callback(p):
    while not button_edge.value():
        a = int((1 - (adc.read() / 1024)) * 1023)
        brightness(pwm1, a)
        pitch(pwm2, a)
        time.sleep_ms(100)
Ejemplo n.º 37
0
import utime
import sensor
import image
import lcd
import time
import random
from Maix import FPIOA
from Maix import GPIO

#button
Fpioa = FPIOA()
Fpioa.set_function(3, FPIOA.GPIO0)
button=GPIO(GPIO.GPIO0,GPIO.IN)

tim1 = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM)
blue_led = PWM(tim1,500000,0,0)

tim2 = Timer(Timer.TIMER0, Timer.CHANNEL1, mode=Timer.MODE_PWM)
green_led = PWM(tim2, 500000, 0, 1)

tim3 = Timer(Timer.TIMER0, Timer.CHANNEL2, mode=Timer.MODE_PWM)
red_led = PWM(tim3, 500000, 0, 2)

def led_control(r,g,b):
    b_value=b/255*100
    g_value=g/255*100
    r_value=r/255*100
    blue_led.duty(b_value)
    green_led.duty(g_value)
    red_led.duty(r_value)
    pass
Ejemplo n.º 38
0
 def __init__(self, pin_tone, pin_mallet):
     self._servo_tone = PWM(Pin(pin_tone), freq=self._pwm_freq)
     self._servo_mallet = PWM(Pin(pin_mallet), freq=self._pwm_freq)
Ejemplo n.º 39
0
        self.write_cmd(0x2B)
        self.write_data(0x00)
        self.write_data(0x35)
        self.write_data(0x00)
        self.write_data(0xBB)
        
        self.write_cmd(0x2C)
        
        self.cs(1)
        self.dc(1)
        self.cs(0)
        self.spi.write(self.buffer)
        self.cs(1)
  
if __name__=='__main__':
    pwm = PWM(Pin(BL))
    pwm.freq(1000)
    pwm.duty_u16(32768)#max 65535

    LCD = LCD_1inch14()
    #color BRG
    LCD.fill(LCD.white)
 
    LCD.show()
    LCD.text("DC540 Meetup",60,40,LCD.red)
    LCD.text("Stone Ridge",60,60,LCD.green)
    LCD.text("2021-05-17",60,80,LCD.blue)
    
    
    
    LCD.hline(10,10,220,LCD.blue)
Ejemplo n.º 40
0
class Servo:
    def __init__(self, pin, lower_duty=512, upper_duty=1953.5, freq=50):
        """
        Create a new Servo instance

        The lower and upper duty values may be tweaked depending on the servo model being used.

        @param pin: 	    the machine.Pin on which the servo is connected
        @param lower_duty: 	the lower duty value
        @param upper_duty:	the upper duty value
        @param freq:        the frequency at which the PWM signal should be generated
        """
        self.pwm = PWM(pin, freq=freq)
        self.lower_duty = (lower_duty * freq) / 10000
        self.upper_duty = (upper_duty * freq) / 10000

    def set(self, pos):
        """
        Set the position as a value between -1 and 1

        the position ranges from -1 to 1 where -1 equals 0 degrees and 1 equals 180 degrees

        @param pos: 	an float between -1 and 1, both inclusive
        """
        self.set_percentage((pos + 1) * 50)

    def set_angle(self, angle):
        """
        Set the position as an angle between 0 and 180 degrees

        @param angle: 	an integer between 0 and 180
        """
        self.set_percentage(angle / 180)

    def angle(self):
        """
        Get the servo's angle

        :return:    the angle expressed as degrees
        """
        return int(self.pos() * 180)

    def pos(self):
        """
        Get the servo's position

        :return:    the position of the servo as a float between 0 and 1
        """
        return int((self.pwm.duty() - self.lower_duty) / (self.upper_duty - self.lower_duty) * 100) / 100

    def center(self):
        """
        Set the servo to it's center position.
        """
        self.set_percentage(0.5)

    def min(self):
        """
        Set the servo to it's minimum position.
        """
        self.set_percentage(0)

    def max(self):
        """
        Set the servo to it's maximum position.
        """
        self.set_percentage(1)

    def set_percentage(self, pct):
        """
        Set the position as a percentage

        freq=50: cycle=1s/50=20ms=0.02: lower=0.001 upper=0.0025

        @param pct: 	a float between 0 and 1
        """
        self.pwm.duty(self.lower_duty + (pct * (self.upper_duty - self.lower_duty)))
Ejemplo n.º 41
0
 def right(self):
     p = PWM(0, self.pin, freq=PWM.FREQ_125KHZ, pulse_width=275, period=2500, mode=PWM.MODE_HIGH_LOW)
     p.init()
     time.sleep_ms(200)
     p.deinit()
Ejemplo n.º 42
0
from machine import Pin, PWM

pwm0 = PWM(Pin(0))  # create PWM object from a pin
pwm0.freq()  # get current frequency
pwm0.freq(1000)  # set frequency
pwm0.duty()  # get current duty cycle
pwm0.duty(200)  # set duty cycle
pwm0.deinit()  # turn off PWM on the pin

pwm2 = PWM(Pin(2), freq=20000, duty=512)  # create and configure in one go
Ejemplo n.º 43
0
 def on(self,freq=500):
  if self.isOn is False:
   self.pwm=PWM(self.io,freq,512)
   self.isOn=True
Ejemplo n.º 44
0
import ESP8266WebServer, network, time, scale
from machine import Pin, PWM
ESP8266WebServer.begin(80)

sound = PWM(Pin(5))
r = PWM(Pin(12))
g = PWM(Pin(13))
b = PWM(Pin(15))
r.duty(0)
g.duty(0)
b.duty(0)
light = 200


def setDuty(rl, gl, bl):
    r.duty(rl)
    g.duty(gl)
    b.duty(bl)


# note=(100, 200, 300, 400, 500)
duration = 4  #聲音長度


def tone(sound, note, duration):
    sound.freq(note)
    sound.duty(512)


#     time.sleep_ms(duration)
#     sound.deinit()
Ejemplo n.º 45
0
class ServoController:
    _pwm_freq = 200

    _tone_duty = {
        'l': 342,
        'm': 318,
        'h': 293}

    _mallet_duty = {
        'd': 265,
        'u': 350}

    _servo_tone = None
    _servo_mallet = None

    def __init__(self, pin_tone, pin_mallet):
        self._servo_tone = PWM(Pin(pin_tone), freq=self._pwm_freq)
        self._servo_mallet = PWM(Pin(pin_mallet), freq=self._pwm_freq)

    def ring(self, tone, move=True, raise_time=0.12):
        if move:
            self.rot_tone(tone)
        time.sleep(0.7)

        self.rot_mallet('d')
        time.sleep(raise_time)
        self.rot_mallet('u')
        time.sleep(0.3 - raise_time)

    def rot_tone(self, tone):
        self._servo_tone.duty(self._tone_duty[tone])
        time.sleep(0.05)
        self._servo_tone.deinit()

    def rot_mallet(self, state):
        self._servo_mallet.duty(self._mallet_duty[state])

    def init(self):
        self._servo_tone.init()
        self._servo_mallet.init()

    def deinit(self, servo=None):
        if servo is None:
            self._servo_tone.deinit()
            self._servo_mallet.deinit()
        elif servo == 'tone':
            self._servo_tone.deinit()
        elif servo == 'mallet':
            self._servo_mallet.deinit()

    def _use_servo(fn):
        def inner(self):
            self.init()
            self.rot_mallet('u')
            fn(self)
            self.deinit()
        return inner

    @_use_servo
    def morning(self):
        self.ring('m')
        self.ring('m', move=False)
        self.ring('m', move=False)
        self.ring('h')

    @_use_servo
    def finish1(self):
        self.ring('m')

    @_use_servo
    def finish2(self):
        self.ring('h')
class DRV8833:
    def __init__(self, In1_pin, In2_pin, sleep_pin, timer_number, freq,
                 num_channel_pwm_In1, num_channel_pwm_In2, **kwargs):
        # IN1_pin : entrée PWM 1 DRV8833
        # IN2_pin : entrée PWM 2 DRV8833
        # sleep_pin : SLP pin pour désactiver les ponts en H du DRV8833
        # timer_number : dans [0,1,2,3]. Choix du timer utilisé pour générer le signal pwm
        # freq : fréquence du signal pwm
        # num_channel_pwm_In1 : numéro de l'Id du canal PWM associé à la broche In1_pin
        # num_channel_pwm_In2 : numéro de l'Id du canal PWM associé à la broche In2_pin

        self.DRV883_Sleep_Pin = Pin(
            sleep_pin, mode=Pin.OUT
        )  # Initialiser la broche sleep_pin pour gérer le DRV8833
        self.DRV883_Sleep_Pin.value(0)  # Désactive le driver DRV8833
        if timer_number not in [0, 1, 2, 3]:
            raise ValueError(
                'Unexpected timer_number value {0}.'.format(timer_number))
        self.pwm = PWM(
            timer_number, frequency=freq
        )  # Utiliser le timer n° timer_number en PWM avec une fréquence de base de freq Hz
        self.DRV8833_Pwm_In1 = self.pwm.channel(num_channel_pwm_In1,
                                                pin=In1_pin,
                                                duty_cycle=0.0)
        self.DRV8833_Pwm_In2 = self.pwm.channel(num_channel_pwm_In2,
                                                pin=In2_pin,
                                                duty_cycle=0.0)
        time.sleep(0.05)
#---------------------------------------------------------------------------
# Commande d'un moteur : paramètres : sens de rotation et vitesse dans [0.0;1.0]

    def Cmde_moteur(self, sens, vitesse):
        self.DRV883_Sleep_Pin.value(0)  # Désactive le driver DRV8833
        if vitesse < 0.0:
            vitesse = 0.0
        elif vitesse > 1.0:
            vitesse = 1.0
        elif vitesse <= 0.3:
            v_init = 0.45
            Delta_v = (v_init - vitesse) / 10
            self.DRV883_Sleep_Pin.value(1)  # Activer le driver DRV8833
            for i in range(10):
                if sens == SENS_HORAIRE:  # forward
                    self.DRV8833_Pwm_In1.duty_cycle(
                        v_init - (i + 1) *
                        Delta_v)  # Rapport cyclique à vitesse % sur IN1
                    self.DRV8833_Pwm_In2.duty_cycle(
                        0.0)  # Rapport cyclique à 0.0 sur IN2 (soit 0%)
                    time.sleep(0.005)
                elif sens == SENS_ANTI_HORAIRE:  # reverse
                    self.DRV8833_Pwm_In1.duty_cycle(
                        0.0)  # Rapport cyclique à 0.0 sur IN1
                    self.DRV8833_Pwm_In2.duty_cycle(
                        v_init - (i + 1) *
                        Delta_v)  # Rapport cyclique à vitesse % sur IN2
                    time.sleep(0.005)
        else:
            self.DRV883_Sleep_Pin.value(
                1
            )  # Activer le driver DRV8833.value(1) # Activer le driver DRV8833
            if sens == SENS_HORAIRE:  # forward
                self.DRV8833_Pwm_In1.duty_cycle(
                    vitesse)  # Rapport cyclique à vitesse % sur IN1
                self.DRV8833_Pwm_In2.duty_cycle(
                    0.0)  # Rapport cyclique à 0.0 sur IN2 (soit 0%)
            elif sens == SENS_ANTI_HORAIRE:  # reverse
                self.DRV8833_Pwm_In1.duty_cycle(
                    0.0)  # Rapport cyclique à 0.0 sur IN1
                self.DRV8833_Pwm_In2.duty_cycle(
                    vitesse)  # Rapport cyclique à vitesse % sur IN2
                time.sleep(0.005)
#---------------------------------------------------------------------------
# Définitions des mouvements de base de la plateforme robotique

    def Arret_moteur(self):
        self.DRV883_Sleep_Pin.value(1)  # Activer le driver DRV8833
        self.DRV8833_Pwm_In1.duty_cycle(0.0)  # Rapport cyclique à 0.0 sur IN1
        self.DRV8833_Pwm_In1.duty_cycle(0.0)  # Rapport cyclique à 0.0 sur IN1
        self.DRV883_Sleep_Pin.value(0)  # Désactive le driver DRV8833
Ejemplo n.º 47
0
def servo_write_angle(pin,angle):
	pwm=PWM(Pin(pin))
	pwm.duty(int(40 + 75 * angle / 180))
	pwm.freq(50)
    mosi=Pin(23),
    sck=Pin(18))

display = ILI9341(
    spi,
    cs=Pin(27),
    dc=Pin(32),
    rst=Pin(5),
    w=320,
    h=240,
    r=3)

display.erase()
display.set_pos(0,0)

bg_led = PWM(Pin(4))
bg_led.freq(1000)
bg_led.duty(750)

for ff,col in zip(fonts,colors):
    display.set_color(col,0)
    display.set_font(ff)
    display.print(text)

while True:
    lum = 0
    for _ in range(5):
        lum += 200
        bg_led.duty(lum)
        sleep(2)
Ejemplo n.º 49
0
class MPythonPin():
    def __init__(self, pin, mode=PinMode.IN, pull=None):
        if mode not in [PinMode.IN, PinMode.OUT, PinMode.PWM, PinMode.ANALOG, PinMode.OUT_DRAIN]:
            raise TypeError("mode must be 'IN, OUT, PWM, ANALOG,OUT_DRAIN'")
        if pin == 4:
            raise TypeError("P4 is used for light sensor")
        if pin == 10:
            raise TypeError("P10 is used for sound sensor")
        try:
            self.id = pins_remap_esp32[pin]
        except IndexError:
            raise IndexError("Out of Pin range")
        if mode == PinMode.IN:
            if pin in [3]:
                raise TypeError('IN not supported on P%d' % pin)
            self.Pin = Pin(self.id, Pin.IN, pull)
        if mode == PinMode.OUT:
            if pin in [2, 3]:
                raise TypeError('OUT not supported on P%d' % pin)
            self.Pin = Pin(self.id, Pin.OUT, pull)
        if mode == PinMode.OUT_DRAIN:
            if pin in [2, 3]:
                raise TypeError('OUT_DRAIN not supported on P%d' % pin)
            self.Pin = Pin(self.id, Pin.OPEN_DRAIN, pull)
        if mode == PinMode.PWM:
            if pin not in [0, 1, 5, 6, 7, 8, 9, 11, 13, 14, 15, 16, 19, 20, 23, 24, 25, 26, 27, 28]:
                raise TypeError('PWM not supported on P%d' % pin)
            self.pwm = PWM(Pin(self.id), duty=0)
        if mode == PinMode.ANALOG:
            if pin not in [0, 1, 2, 3, 4, 10]:
                raise TypeError('ANALOG not supported on P%d' % pin)
            self.adc = ADC(Pin(self.id))
            self.adc.atten(ADC.ATTN_11DB)
        self.mode = mode

    def irq(self, handler=None, trigger=Pin.IRQ_RISING):
        if not self.mode == PinMode.IN:
            raise TypeError('the pin is not in IN mode')
        return self.Pin.irq(handler, trigger)

    def read_digital(self):
        if not self.mode == PinMode.IN:
            raise TypeError('the pin is not in IN mode')
        return self.Pin.value()

    def write_digital(self, value):
        if self.mode not in [PinMode.OUT, PinMode.OUT_DRAIN]:
            raise TypeError('the pin is not in OUT or OUT_DRAIN mode')
        self.Pin.value(value)

    def read_analog(self):
        if not self.mode == PinMode.ANALOG:
            raise TypeError('the pin is not in ANALOG mode')
        # calibration esp32 ADC 
        calibration_val = 0
        val = int(sum([self.adc.read() for i in range(50)]) / 50)
        if 0 < val <= 2855:
            calibration_val = 1.023 * val + 183.6
        if 2855 < val <= 3720:
            calibration_val = 0.9769 * val + 181
        if 3720 < val <= 4095:
            calibration_val = 4095 - (4095 - val) * 0.2
        return calibration_val

    def write_analog(self, duty, freq=1000):
        if not self.mode == PinMode.PWM:
            raise TypeError('the pin is not in PWM mode')
        self.pwm.freq(freq)
        self.pwm.duty(duty)
Ejemplo n.º 50
0
import array, time
from machine import Pin, PWM
import rp2
from rp2 import PIO, StateMachine, asm_pio

# Configure the number of WS2812 LEDs.
NUM_LEDS = 8
buzzer = PWM(Pin(19))


@asm_pio(sideset_init=PIO.OUT_LOW,
         out_shiftdir=PIO.SHIFT_LEFT,
         autopull=True,
         pull_thresh=24)
def ws2812():
    T1 = 2
    T2 = 5
    T3 = 3
    label("bitloop")
    out(x, 1).side(0)[T3 - 1]
    jmp(not_x, "do_zero").side(1)[T1 - 1]
    jmp("bitloop").side(1)[T2 - 1]
    label("do_zero")
    nop().side(0)[T2 - 1]


# Create the StateMachine with the ws2812 program, outputting on Pin(0).
sm = StateMachine(0, ws2812, freq=8000000, sideset_base=Pin(0))
# Start the StateMachine, it will wait for data on its FIFO.
sm.active(1)
Ejemplo n.º 51
0
import time
from machine import Pin, PWM
# piny odpowiadające segmentom wyświetlacza
a = 14
b = 13
c = 18
d = 17
e = 16
f = 15

segs = [
    PWM(Pin(a)),
    PWM(Pin(b)),
    PWM(Pin(c)),
    PWM(Pin(d)),
    PWM(Pin(e)),
    PWM(Pin(f))
]

i = 0
while True:
    p = (i + 5) % 6  # poprzedni segment
    n = (i + 1) % 6  # nastepny segment
    for q in range(0, len(segs)):
        if q not in [p, i, n]:
            segs[q].duty_u16(2**8)  # wygaszanie pozostałych

    segs[n].duty_u16((2**16) - 2)
    segs[i].duty_u16(2**14)
    segs[p].duty_u16(2**12)
Ejemplo n.º 52
0
dj1 = Pin(
    21, Pin.OUT
)  # Assigns the 4 digital pins to the GPIOs they are related to. These pins can be found in the 'Pin Values' file on GitHub, and the 'djx' terms match with the PCB labeling
dj2 = Pin(22, Pin.OUT)
dj3 = Pin(19, Pin.OUT)
dj4 = Pin(20, Pin.OUT)

digital_pins = [
    dj1,
    dj2,
    dj3,
    dj4,
]  # Creates an array so that the digital pins can be iterated through (allows them to all work in unison/related to each other)

aj1 = PWM(
    Pin(14, Pin.OUT)
)  # Assigns the 4 analogue pins to the GPIOs they are related to. These pins can be found in the 'Pin Values' file on GitHub, and the 'ajx' terms match with the PCB labeling
aj2 = PWM(Pin(11, Pin.OUT))
aj3 = PWM(Pin(10, Pin.OUT))
aj4 = PWM(Pin(7, Pin.OUT))

analogue_pins = [
    aj1,
    aj2,
    aj3,
    aj4,
]  # Creates an array so that the analogue pins can be iterated through (allows them to all work in unison/related to each other)


def trigger(
    pin,
Ejemplo n.º 53
0
        ["Teach yourself 3D\nmodeling, it is \nworth the effort!"],
        ["The Internet of\nThings is great\nthe way forward!"],
        ["We use Arduinos\nand Raspberries\nand ESP32 WROOM"],
        ["Welcome to the\n3D and Robo Lab\nof Haaga-Helia"],
        ["Why not learn to do\n3D and robotics, it\nis so much fun!"],
        ["You have no idea\nhow much fun 3D is\nso come and learn!"],
        ["Come on in and see\na 3D printer make\nsomething useful"],
        ["Every business\nneeds to see how\n3D affects it"],
        ["Teach yourself\nrobotics for a\ngood investment"],
        ["Come and see how we\nmake robots and do\ninteresting stuff!"],
        ["This Morse Moai is\nconnected to the\nInternet, really!"],
        ["My message can be\nchanged wirelessly\nover the Internet!"],
        ["I can make Morse\ncode out of anything\nyou want to say!"]
    ]
    p5 = Pin(5)  #create music object from pin5
    pwm5 = PWM(p5)
    pwm5.deinit()
    myRawNetMsg = ""  #this is the return string before converting to byte array
    myFinalMsg = ""  #this is the return string in UTF-8 format
    myNetMsg = ""  #this is the string passed on to be morse coded
    SSID = "insert_your_SSID_here"
    PASSWORD = "******"
    url = "insert_your_message_file_URL_here"  #this is the URL to get the message from
    host = "192.168.3.147"  #the IP address given to the ESP32 at connection time
    port = 100
    wlan = None
    s = None

    def connectWifi(ssid, passwd):  #function to connect to the Web
        global wlan  #declare a WLAN object
        lcd.move_to(0, 0)  #move LCD cursor to top left corner
Ejemplo n.º 54
0
bach = [
C4 , E4 , G4 , C5 , E5 , G4 , C5 , E5 , C4 , E4 , G4 , C5 , E5 , G4 , C5 , E5 ,
C4 , D4 , G4 , D5 , F5 , G4 , D5 , F5 , C4 , D4 , G4 , D5 , F5 , G4 , D5 , F5 ,
B3 , D4 , G4 , D5 , F5 , G4 , D5 , F5 , B3 , D4 , G4 , D5 , F5 , G4 , D5 , F5 ,
C4 , E4 , G4 , C5 , E5 , G4 , C5 , E5 , C4 , E4 , G4 , C5 , E5 , G4 , C5 , E5 ,
C4 , E4 , A4 , E5 , A5_ , A4 , E5 , A4 , C4 , E4 , A4 , E5 , A5_ , A4 , E5 , A4 ,
C4 , D4 , FS4 , A4 , D5 , FS4 , A4 , D5 , C4 , D4 , FS4 , A4 , D5 , FS4 , A4 , D5 ,
B3 , D4 , G4 , D5 , G5 , G4 , D5 , G5 , B3 , D4 , G4 , D5 , G5 , G4 , D5 , G5 ,
B3 , C4 , E4 , G4 , C5 , E4 , G4 , C5 , B3 , C4 , E4 , G4 , C5 , E4 , G4 , C5 ,
B3 , C4 , E4 , G4 , C5 , E4 , G4 , C5 , B3 , C4 , E4 , G4 , C5 , E4 , G4 , C5 ,
A3 , C4 , E4 , G4 , C5 , E4 , G4 , C5 , A3 , C4 , E4 , G4 , C5 , E4 , G4 , C5 ,
D3 , A3 , D4 , FS4 , C5 , D4 , FS4 , C5 , D3 , A3 , D4 , FS4 , C5 , D4 , FS4 , C5 ,
G3 , B3 , D4 , G4 , B4 , D4 , G4 , B4 , G3 , B3 , D4 , G4 , B4 , D4 , G4 , B4
]

pwm = PWM(pin, freq=FREQUENCY, duty = 10, timer = 1)
i = 0
xadc = ADC(Pin(ADC6))
yadc = ADC(Pin(ADC3))
xadc.atten(ADC.ATTN_11DB)
yadc.atten(ADC.ATTN_11DB)
def tune_cb(timer):
	global State
	global FREQUENCY
	global fight
	global i
	if State == False:
		FREQUENCY = fight[i]
		i+=1
	else: 
		FREQUENCY = int(4000*(yadc.read()/5000))