def __init__(self):
     super(Euglena_moto_port, self).__init__(0)
     moto_pwm = PWM(0, 5000)
     self.moto = {}
     self.S1.mode(Pin.OUT)
     self.S2.mode(Pin.OUT)
     self.S3.mode(Pin.OUT)
     self.S4.mode(Pin.OUT)
     self.moto['left_direction'] = self.S1
     self.moto['rigth_direction'] = self.S3
     self.moto['left_pwm'] = moto_pwm.channel(0,
                                              pin=self.S2.id(),
                                              duty_cycle=0)
     self.moto['right_pwm'] = moto_pwm.channel(1,
                                               pin=self.S4.id(),
                                               duty_cycle=0)
Beispiel #2
0
class ToolHead:
    def __init__(self):
        # create pwm channel on pin P12
        self.pwm = PWM(
            0, frequency=50)  # use PWM timer 0, with a frequency of 50Hz
        self.is_active = False
        self.button_up = Pin('G4', mode=Pin.IN, pull=Pin.PULL_UP)
        self.button_dwn = Pin('G5', mode=Pin.IN, pull=Pin.PULL_UP)

    def activate(self):
        # May not be switched on
        if not self.is_active:
            self.is_active = True
            self.pwm_c = self.pwm.channel(0, pin='P12', duty_cycle=0.15)

    def set_position(self, position):  # Converts to 1 -2 ms pulses
        self.activate()
        # speed in %
        dc = (position / 100.0) * (1 / 20) + (1 / 20)
        self.pwm_c.duty_cycle(dc)
        return dc

    def park(self):
        self.set_position(50)

    def grip(self):
        self.set_position(100)

    def release(self):
        self.set_position(0)

    def shutdown(self):
        # Ideally won't move servo
        self.pwm_off = Pin('P12', mode=Pin.IN, pull=Pin.PULL_UP)
        self.is_active = False
Beispiel #3
0
def buz(frequency=440):
    buz = Pin("P10")  # Buzzer
    tim = PWM(0, frequency=frequency)
    ch = tim.channel(2, duty_cycle=0.5, pin=buz)
    time.sleep(1)
    tim = PWM(0, frequency=0)
    ch.duty_cycle(0)
Beispiel #4
0
    def __init__motor(self, ENpin, PHpin, timer_id, channel_id, sensorApin,
                      sensorBpin):

        #Assign IO as Enable and Phase  output,pins
        EN = PWM(self.timer_id, frequency=5000)
        ENpin = EN.channel(self.channel_id, ENpin, duty_cycle=0)
        PHpin = Pin(self.PHpin, Pin.OUT_PP)

        #Preliminary Attributes
        self.isRunning = False
        self.currentDirection = None
        self.speed = self.duty_cycle

        #Assign hall effect sensor pins frrom encoder as input pins
        hallsensorA = Pin(self.sensorApin, mode=Pin.IN, pull=Pin.PULL_UP)
        hallsensorB = Pin(self.sensorBpin, mode=Pin.IN, pull=Pin.PULL_UP)

        #Assign Trigger for when sensor hits falling edge
        low_value_trigger_A = encoder_A.callback(
            Pin.IRQ_FALLING,
            rencoder)  #Trigger is the falling edge; handler is rencoder event
        low_value_trigger_B = encoder_B.callback(Pin.IRQ_FALLING, rencoder)

        #Prelimnary Attributes
        count = long(pulse=0)
Beispiel #5
0
def openDoor():
    motorGND = Pin(
        'P8', mode=Pin.OUT
    )  # Enable of LN298 is connected to 3V3 so we have to switch the input pins to turn the motor the other way
    motorGND.value(
        0
    )  # The DC motor needs GND on 1 pin and a PWM signal on the other pin (we use pin 8 as GND now)

    pwm = PWM(0, frequency=5000)  # use PWM timer 0, with a frequency of 5KHz
    pwm_c_motor = pwm.channel(
        0, pin='P9', duty_cycle=1.0
    )  # create pwm channel on pin P9 with a duty cycle of 100%
    time.sleep(
        DOOROPENTIME)  # Let the motor run until the door is completely open
    pwm_c_motor = pwm.channel(0, pin='P9',
                              duty_cycle=0.0)  # Stop the door when opened
Beispiel #6
0
 def __init__(self, pin, freq=50, min_us=600, max_us=2400, angle=180):
     self.min_us = min_us
     self.max_us = max_us
     self.us = 0
     self.freq = freq
     self.angle = angle
     print(freq)
     pwm = PWM(0, frequency=freq)
     self.pwm = pwm.channel(0, pin=pin, duty_cycle=0)
Beispiel #7
0
 def do(self, freq=2000, duty=0.1, duration=0.1, pause=0.1, repeat=1, color=0x0000ff):
     pycom.heartbeat(False)
     for i in range(repeat):
         pycom.rgbled(color)
         pwm = PWM(0, freq)
         pin = pwm.channel(0, pin='P10', duty_cycle=duty)
         time.sleep(duration)
         pycom.heartbeat(False)
         pin.duty_cycle(0)
         time.sleep(pause)
Beispiel #8
0
    def __init__(self, ENpin, PHpin, timer_id, channel_id):
        self.timer_id = timer_id
        self.channel_id = channel_id
        #Assign IO as Enable and Phase  output,pins
        EN = PWM(0, frequency=5000)
        self.ENpin = EN.channel(0, pin=ENpin, duty_cycle=0)
        self.PHpin = Pin(PHpin, mode=Pin.OUT)

        #Preliminary Attributes
        self.isRunning = False
        self.current_direction = None
        self.current_speed = 0
class PulseLED(object):
    """pulsing LED"""
    def __init__(self, pin, freq=1000, timer=0):
        #super(, self).__init__()
        self.pwm = PWM(timer, frequency=freq)
        self.led_c = self.pwm.channel(0, pin=pin, duty_cycle=0)

    # pulse function
    def pulse(self, t):
        """pulse led l with time interval t in ms"""
        for i in range(17):
            self.led_c.duty_cycle(math.sin(i / 10 * math.pi))
            time.sleep_ms(t)
Beispiel #10
0
def controlClimate(
):  # Read temperature and humidity from DHT 22 and activate fan if temp is to high.
    result = th.read()
    if result.is_valid():
        if result.temperature > MAXTEMP:
            fanGND = Pin('P10',
                         mode=Pin.OUT)  #Declaring pin as digital output.
            fanGND.value(0)  # Setting pin to zero/ GND for fan.
            pwm = PWM(
                0, frequency=5000)  # use PWM timer 0, with a frequency of 5KHz
            pwm_c_fan = pwm.channel(
                0, pin='P11', duty_cycle=1.0
            )  # create pwm channel on pin P11 with a duty cycle of 50%
Beispiel #11
0
class ToolHead:
    def __init__(self):
        # create pwm channel on pin P12
        self.pwm = PWM(
            0, frequency=50)  # use PWM timer 0, with a frequency of 50Hz
        self.pwm_c = self.pwm.channel(0, pin='P12', duty_cycle=0.15)
        self.state = 0

    def set_position(self, position):  # Converts to 1 -2 ms pulses
        # speed in %
        dc = (position / 100.0) * (1 / 20) + (1 / 20)
        self.pwm_c.duty_cycle(dc)
        return dc

    def park(self):
        self.set_position(50)

    def grip(self):
        self.set_position(100)

    def release(self):
        self.set_position(0)

    def run(self):
        global running, btn
        if self.state == 0:
            pycom.rgbled(0x002000)
            self.state = 1
            self.park()
        elif self.state == 1:
            pycom.rgbled(0x008000)
            if btn.pushed:
                self.state = 2
                self.release()
        elif self.state == 2:
            pycom.rgbled(0x000080)
            if btn.pushed:
                self.state = 3
                self.grip()
        elif self.state == 3:
            pycom.rgbled(0x808000)
            if btn.pushed:
                self.state = 4
                self.release()
        else:
            self.state == 4
            pycom.rgbled(0x200000)
            if btn.pushed:
                running = False
                self.park()
                pycom.rgbled(0x800000)
Beispiel #12
0
def test_servo():
    pwm = PWM(0, frequency=50)  # create PWM, with a frequency of 50Hz
    pwm_c = pwm.channel(
        0, pin='P4',
        duty_cycle=0.05)  # .05 duty cycle starts servo all the way to the east
    d_cycle = 0.05  # initial duty cycle value
    while True:
        # 0.03 and 0.12-0.16 work, though 0.12 seems to give best results

        print("moving to d cycle 0.03")
        pwm_c.duty_cycle(0.03)
        time.sleep(2)
        print("moving to d cycle 0.12")
        pwm_c.duty_cycle(0.12)
        time.sleep(5)
Beispiel #13
0
class Servo:
    """
    WiPy servo object
    Sets up Timer and Channel and performs calculation so servo angle is automatically converted to duty cycle.
    """

    def __init__(self, gp_pin, channel, frequency, full_range100, pulse_min, pulse_max):
        """
        :param gp_pin: GPIO pin
        :channel: PWM unit
        :param frequency: in Hz
        :param full_range100: in deg
        :param pulse_min: in µs (WiPy3.0) in Duty (for ESP32, it should be - 30)
        :param pulse_max: in µs (WiPy3.0) in Duty (for ESP32, it should be - 30)
        :return:
        """

        # Store object properties
        self.PWM_frame = frequency  # in Hz
        self.full_range100 = full_range100
        self.pulse_min = pulse_min
        self.pulse_diff = pulse_max - pulse_min

    	self.min_position = 0
    	self.max_position = 180

        if (uname().sysname == 'WiPy'):
        	# Configure PWM timer to pin flow
        	self.pwm = PWM(0, frequency=self.PWM_frame)
        	self.servo = self.pwm.channel(channel, pin=gp_pin, duty_cycle=0.077)  # initial duty cycle of 7.5%
        else:
            self.pwm = PWM(gp_pin, freq=self.PWM_frame)

    def angle(self, angle100):
        """
        Set timer duty cycle to specified angle
        :param angle100: angle in deg * 100
        :return:
        """
        angle_fraction = float(angle100) / float(self.full_range100)
        pulse_width = float(self.pulse_min + angle_fraction * self.pulse_diff) # in µs
        if (uname().sysname == 'WiPy'):
            duty_cycle =  pulse_width * 100 / (1000 / self.PWM_frame) / 100
            self.servo.duty_cycle(duty_cycle)
        else:
            self.pwm.duty(int(pulse_width))
Beispiel #14
0
 def __configure_pwm_pin(self, pin_number):
     # TODO: Add a check for WiPy 1.0
     _PWMMap = {0: (0, 0),
                1: (0, 1),
                2: (0, 2),
                3: (0, 3),
                4: (0, 4),
                8: (0, 5),
                9: (0, 6),
                10: (0, 7),
                11: (1, 0),
                12: (1, 1),
                19: (1, 2),
                20: (1, 3),
                21: (1, 4),
                22: (1, 5),
                23: (1, 6)}
     pwm = PWM(_PWMMap[pin_number][0], frequency=5000)
     self.__pins[pin_number] = pwm.channel(_PWMMap[pin_number][1], pin="P" + str(pin_number),
                                           duty_cycle=0)
Beispiel #15
0
    def __init__(self,
                 p_pwm_id,
                 p_channel_enable_id,
                 channel_name,
                 pwm_timer_id=0,
                 pwm_channel_id=0):
        """
        p_pwm_id            -- the id of the pwm pin (e.g, connect pin to PWMA)
        p_channel_enable_id -- the id of the motor enable pin (e.g., connect pin to AIN2)
        channel_name        -- the name of the channel used for logging
        pwm_timer_id        -- [0], id of the timer, must be 0 to 3
        pwm_channel_id      -- [0], id of the pwm channel, must be 0 to 7
        """
        self.channel_name = channel_name
        pwm = PWM(
            pwm_timer_id,
            frequency=5000)  # use given pwm timer, with a frequency of 5KHz
        self.p_pwm = pwm.channel(pwm_channel_id, pin=p_pwm_id, duty_cycle=0.0)

        self.p_channel_enable = Pin(p_channel_enable_id, mode=Pin.OUT)
Beispiel #16
0
def start_servo():
    LDR1 = adc.channel(Pin='P16', attn=ADC.ATTN_11DB)
    LDR2 = adc.channel(Pin='P17', attn=ADC.ATTN_11DB)
    pwm = PWM(0, frequency=50)  # create PWM, with a frequency of 50Hz
    pwm_c = pwm.channel(
        0, pin='P4',
        duty_cycle=0.05)  # .05 duty cycle starts servo all the way to the east
    d_cycle = 0.05  # initial duty cycle value
    while True:  # run continuosly
        # read voltages (mV) at each node
        LDReast_v = LDR1.voltage()
        LDRwest_v = LDR2.voltage()
        # compare voltages at each LDR node
        v_diff = LDReast_v - LDRwest_v
        threshold = 100  # millivolts
        if v_diff > threshold:
            moveservo = 1
        elif v_diff < (-1) * threshold:
            moveservo = -1
        else:
            moveservo = 0

        # move servo in 1 degree increments every (interval) seconds
        increment = 10 * 1 / 180  # 1 ms divided by 180 degrees =.0055555 increment
        d_cycle += increment  # new duty cycle

        # check to make sure d_cycle is within allowable range
        if d_cycle < 0.05:
            d_cycle = 0.05

        if d_cycle > 0.1:
            d_cycle = 0.1

        # move servo to new location (incrementally)
        pwm_c.duty_cycle(d_cycle)

        print("servo moved")
        time.sleep(5)
Beispiel #17
0
        self.dutycycle = servo.min_dutycycle + servo.step * self.position
        self.dutycycle = min(max(self.dutycycle, servo.min_dutycycle),
                             servo.max_dutycycle)
        if self.pwm_channel:
            self.pwm_channel.duty_cycle(self.dutycycle)


if __name__ == "__main__":
    from machine import Pin, PWM
    import socket
    import url
    import gc

    # servo setup
    pwm = PWM(0, frequency=50)
    servo1 = servo(50, pwm.channel(0, pin=Pin.exp_board.G15))
    servo2 = servo(50, pwm.channel(1, pin=Pin.exp_board.G16))

    # for demonstration purpose limit servo2's position
    servo2.min_position = 20
    servo2.max_position = 80

    # webserver setup
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.bind(socket.getaddrinfo('0.0.0.0', 80)[0][-1])
    serversocket.listen(1)

    while True:
        gc.collect()

        conn, addr = serversocket.accept()
Beispiel #18
0
class LEDStrip:
    DISABLED = const(-1)

    def __init__(self, *args):
        self.pin_r = args[0]
        self.pin_g = args[1]
        self.pin_b = args[2]

        self.pin_r.mode(Pin.OUT)
        self.pin_g.mode(Pin.OUT)
        self.pin_b.mode(Pin.OUT)

        self.pwm = PWM(0, frequency=5000)

        self.pwm_r = self.pwm.channel(0, pin=self.pin_r, duty_cycle=0)
        self.pwm_g = self.pwm.channel(1, pin=self.pin_g, duty_cycle=0)
        self.pwm_b = self.pwm.channel(2, pin=self.pin_b, duty_cycle=0)
        self.fader = Fader(self.pwm_r, self.pwm_g, self.pwm_b)

        self._r = pycom.nvs_get('red') or 0
        self._g = pycom.nvs_get('green') or 20
        self._b = pycom.nvs_get('blue') or 40
        self._fading = pycom.nvs_get('fading') or False
        self._schedule_start = pycom.nvs_get('schedule_start') or self.DISABLED
        self._schedule_stop = pycom.nvs_get('schedule_stop') or self.DISABLED


    @property
    def enabled(self):
        return self.r > 0 or self.g > 0 or self.b > 0


    # red
    @property
    def r(self):
        return self._r


    @r.setter
    def r(self, value):
        self._r = value
        self.pwm_r.duty_cycle(value/255)
        pycom.nvs_set('red', value)

    # green
    @property
    def g(self):
        return self._g


    @g.setter
    def g(self, value):
        self._g = value
        self.pwm_g.duty_cycle(value/255)
        pycom.nvs_set('green', value)

    # blue
    @property
    def b(self):
        return self._b


    @b.setter
    def b(self, value):
        self._b = value
        self.pwm_b.duty_cycle(value/255)
        pycom.nvs_set('blue', value)

    # fading
    @property
    def fading(self):
        return self._fading


    @fading.setter
    def fading(self, value):
        self._fading = value
        pycom.nvs_set('fading', value)

    # schedule_stop (in minutes 0-1439)
    @property
    def schedule_stop(self):
        return self._schedule_stop


    @schedule_stop.setter
    def schedule_stop(self, value):
        self._schedule_stop = value
        pycom.nvs_set('schedule_stop', value)

    # schedule_start (in minutes 0-1439)
    @property
    def schedule_start(self):
        return self._schedule_start


    @schedule_start.setter
    def schedule_start(self, value):
        self._schedule_start = value
        pycom.nvs_set('schedule_start', value)


    def fade_in(self):
        self.fader.fade_in(self.r, self.g, self.b)

    def fade_out(self):
        self.fader.fade_out(self.r, self.g, self.b)
Beispiel #19
0
from machine import Pin
import pycom
import time
from machine import PWM
pwm = PWM(0, frequency=50)  # use PWM timer 0, with a frequency of 50Hz
# create pwm channel on pin P12 with a duty cycle of 50%
pwm_c = pwm.channel(0, pin='P12', duty_cycle=0.15)

# initialisation code
pycom.heartbeat(False)
pycom.rgbled(0xCC8080)  # pale pink

# initialize `P9` in gpio mode and make it an output
p_out = Pin('P9', mode=Pin.OUT)
p_out.value(1)
p_out.value(0)
p_out.toggle()
p_out(True)

# make `P10` an input with the pull-up enabled
p_in = Pin('P10', mode=Pin.IN, pull=Pin.PULL_UP)
p_in()  # get value, 0 or 1

time.sleep(2)

while p_in() == 1:
    pycom.rgbled(0x008000)  # Green
    time.sleep(1)
    pycom.rgbled(0x000080)  # Blue
    time.sleep(1)
    p_out.toggle()
Beispiel #20
0
from machine import PWM
import time

pwm = PWM(0, frequency=5000)  # use PWM timer 0, with a frequency of 5KHz
# create pwm channel on pin P11 with a duty cycle of 50%
pwm_c = pwm.channel(0, pin='P11', duty_cycle=0.5)
incVal = 0.5
valToSum = 0.05
# Faz o led alterar o brilho
i = 10000000000
while i > 0:
    pwm_c.duty_cycle(incVal)  # change the duty cycle to 50%
    time.sleep(.05)

    if incVal >= 1:
        valToSum = -valToSum
    elif incVal <= 0:
        valToSum = -valToSum

    incVal += valToSum
    i -= 1
Beispiel #21
0
"""

if __name__ == "__main__":
    from machine import Pin, PWM
    import socket
    import url
    import gc

    # setup for the servo
    position = 50
    dutycycle = 0.07
    min_dutycycle = 0.03
    max_dutycycle = 0.13

    pwm = PWM(0, frequency=50)
    servo = pwm.channel(0, pin=Pin.exp_board.G22, duty_cycle=dutycycle)

    # setup for the webserver
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.bind(socket.getaddrinfo('0.0.0.0', 80)[0][-1])
    serversocket.listen()

    while True:
        conn, addr = serversocket.accept()

        request = conn.readline()
        print("request:", request)

        conn.recv(2048)

        d = url.extract(request)
Beispiel #22
0
enable_gate = Pin(enableA, mode=Pin.OUT)
gate_open = Pin(in2, mode=Pin.OUT)
gate_close = Pin(in1, mode=Pin.OUT)

enable_fan = Pin(enableB, mode=Pin.OUT)
fan_1 = Pin(in3, mode=Pin.OUT)
fan_2 = Pin(in4, mode=Pin.OUT)

#schakelaar voor de poort open te doen
switch = Pin(switch_pin, mode=Pin.IN)

#maak een pwm aan met timer 0 & frequentie van 5KHz
pwm = PWM(0, frequency=5000)

#creer een pwm kaneel op pin enableA met een duty cycle van 0
gate_speed = pwm.channel(0, pin=enableA, duty_cycle=0)
fan_speed = pwm.channel(0, pin=enableB, duty_cycle=0)
#deze worden niet gebruikt want de motoren bewegen pas vanaf 90% duty cycle

#de load cell amplifier
load_amp = HX711(data_pin, clk_pin)

#wordt gebruikt om de load cell waarde op null te zetten
weight_offset = 969850


def main():
    #kijkt of de poort open of dicht is en sluit/opent deze als de schakelaar gebruikt wordt (zie video)
    gateIsOpen = False
    while True:
        if (switch.value() and gateIsOpen):
Beispiel #23
0
# off
MIN_VALUE = 0.0

# disable bright blue blink
# https://docs.pycom.io/chapter/tutorials/all/rgbled.html
pycom.heartbeat(False)

# setup two inputs
# https://docs.pycom.io/chapter/firmwareapi/pycom/machine/Pin.html
p_in_1 = Pin('P13', mode=Pin.IN, pull=Pin.PULL_UP)
p_in_2 = Pin('P14', mode=Pin.IN, pull=Pin.PULL_UP)

# create two pwm channels for the LEDs
# https://docs.pycom.io/chapter/firmwareapi/pycom/machine/PWM.html
pwm_1 = PWM(0, frequency=100)
pwm_c_1 = pwm_1.channel(0, pin='P10', duty_cycle=1.0)
# purely decorative
pwm_c_2 = pwm_1.channel(1, pin='P11', duty_cycle=1.0)

# piggyback buzzer to channel 0 (which drives the first led)
pwm_buz = pwm_1.channel(0, pin='P9', duty_cycle=0.5)

# initialize variables
c_1_cycle = MIN_VALUE
c_2_cycle = MIN_VALUE
cstep_1 = STEP_1
cstep_2 = STEP_2

# loop
while True:
    # button 1 effect
Beispiel #24
0
def nvs_get(key, default_value=0):
    """ Get value for key from NVRAM. Create the key if it does not exist.

    :param str key:
    :param int default_value: value to use when creating the key
    :return value int: (NVRAM can only store integers)
    """
    value = pycom.nvs_get(key)
    if value is None:
        pycom.nvs_set(key, int(default_value))
        value = int(default_value)
    return value


pwm = PWM(0, frequency=25000)
channel0 = pwm.channel(0, pin="P23", duty_cycle=1.0)
channel1 = pwm.channel(0, pin="P22", duty_cycle=1.0)

lock = _thread.allocate_lock()

temp0 = 0
temp1 = 0

dutycycle = 0  # unit %, where 0 if off and 100 is full speed

max_dutycycle = nvs_get("max_dutycycle", 100)  # unit = %
min_dutycycle = nvs_get("min_dutycycle", 20)  # unit = %

temp_fan_on = nvs_get("temp_fan_on", 40)  # unit = degrees celsius
temp_fan_max = nvs_get("temp_fan_max", 60)  # unit = degrees celsius
Beispiel #25
0
        if led_value:
            if led_value == False:
                pycom.rgbled(0x000000)

    elif events & LoRa.TX_PACKET_EVENT:
        print('LoRa packet sent')


lora.callback(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT, lora_callback)

print('creating the i2c component')

pwm = PWM(0, frequency=5000)  # use PWM timer 0, with a frequency of 5KHz
# create pwm channel on pin P12 with a duty cycle of 50%
pwm_c = pwm.channel(0, pin='P22', duty_cycle=1.0)

i2c = I2C(0, I2C.MASTER)  # create and init as a master
sensor0 = drivers.adafruit_sht31d.SHT31D(
    i2c, address=drivers.adafruit_sht31d._SHT31_ADDRESSES[0])
#sensor1 = drivers.adafruit_sht31d.SHT31D(i2c, address=drivers.adafruit_sht31d._SHT31_ADDRESSES[1])
print('i2c component created')
while True:
    print('i2c component reading')
    t0 = sensor0.temperature
    RH0 = sensor0.relative_humidity
    #t1 = sensor1.temperature
    #RH1 = sensor1.relative_humidity

    value_object = {
        'temperature': "{0:.2f}".format(t0),
Beispiel #26
0
"""
Ricezione lettura pressione di un bottone (0|1) in frequenza "locale" 
inviata da un'altra board LoPy con accensione di led e buzzer
--RICEZIONE
"""

from network import LoRa
import socket
import time
import pycom
from machine import PWM

# PWM per output buzzer
pwm = PWM(0, frequency=3000)
buzzer = pwm.channel(0, pin='G9', duty_cycle=0)

# Setup del socket
lora = LoRa(mode=LoRa.LORA, frequency=868000000)  # 868 MHz
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setblocking(False)

# Ferma la pulsazione del led e lo spegne
pycom.heartbeat(False)
pycom.rgbled(0x000000)

while True:
    if s.recv(64) == b'1':
        pycom.rgbled(0xffffff)  # Led acceso bianco
        buzzer.duty_cycle(0.5)
    elif s.recv(64) == b'0':
        pycom.rgbled(0x000000)  # Led spento
Beispiel #27
0
from machine import Pin, PWM
import time
#import random

#red = Pin('P12', mode = Pin.OUT)
#green = Pin('P11', mode = Pin.OUT)
#blue = Pin('P10', mode = Pin.OUT)

pwm_timer = PWM(0, frequency = 5000)

red_pwm = pwm_timer.channel(0, pin = 'P12', duty_cycle = 0)
green_pwm = pwm_timer.channel(1, pin = 'P11', duty_cycle = 0)
blue_pwm = pwm_timer.channel(2, pin = 'P10', duty_cycle = 0)

def flash(led):
    led.toggle()
    time.sleep(1)
    led.toggle()

def color_cycle():
    for i in range(100):
        j = randint(1, 100)
        red_pwm.duty_cycle((abs(j-i))/100)
        time.sleep(.300)
        green_pwm.duty_cycle((j)/100)
        time.sleep(.300)
        blue_pwm.duty_cycle((i)/100)
        time.sleep(.300)

def turn_off():
   red_pwm.duty_cycle(0)
# 1. Pycom documentatie: https://docs.pycom.io/firmwareapi/pycom/machine/pwm
# 2. frequency parameter and pulse LED:
# http://docs.micropython.org/en/latest/esp8266/esp8266/tutorial/pwm.html#control-a-hobby-servo

from time import sleep
from machine import PWM

# Servo configuration: GPIO6 / 'P19' Expansion board
# Vcc = 5V, signal=3V3 (GPIO)
# Servo type TG9e - assortimentsdoos
# trial-and-error values
duty_range = [0.025, 0.05]

pwm = PWM(0, frequency=50)  #servo: frequency = 50 Hz
duty_mean = (duty_range[0] + duty_range[1]) / 2
servo = pwm.channel(0, pin='P19', duty_cycle=duty_mean)


def sweep(min_duty, max_duty, dt=2):
    """ sweep servo between min_duty and max_duty and waittime dt. """
    while True:
        servo.duty_cycle(min_duty)  # one side
        sleep(dt)
        servo.duty_cycle(max_duty)  # other side
        sleep(dt)


# demo: sweep the servo...
def demo():
    """ demo sweep servo until Ctrl-C."""
    try:
# Function to caculate the pwm value for the angle given.
def setServoPwn(angle):
    servo.duty_cycle(
        ((angle / 180) * 0.05) +
        0.05)  # calculate the right value for PWM based on the angle given


bluetooth = Bluetooth()  # Get a bluetooth instance
bluetooth.set_advertisement(name='FyPi')  # Set the name
bluetooth.callback(
    trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED,
    handler=conn_cb)  # set up the callbacks for connect and disconnect events
bluetooth.advertise(True)  # advertise the device

print("Started BLE")

srv1 = bluetooth.service(
    uuid=0x1815, isprimary=True
)  # set up the service to display the current angle of the servo
chr1 = srv1.characteristic(
    uuid=0x2763,
    value=currentAngle)  # set up the characteristic to get the server angle
char1_cb = chr1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT,
                         handler=char1_cb_handler
                         )  # set up the callback when writen to characteristic

pwm = PWM(0, frequency=50)  # make a pwm provider
servo = pwm.channel(0, pin='P23',
                    duty_cycle=0.0)  # Setup the pwm for the servo
setServoPwn(currentAngle)  # Set the servo the the initial angle
Beispiel #30
0
class DRV8833_V2:
    def __init__(self, In1_pin, In2_pin, sleep_pin, timer_number, freq,
                 num_channel_pwm_In1, num_channel_pwm_In2, moteur_dg,
                 **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
        # moteur_dg : permet de différencier le moteur droit du moteur gauche

        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)
        self.consigne_rotation_roue = 0.0
        self.sens = SENS_HORAIRE
        self.moteur_dg = moteur_dg
        time.sleep(0.05)
#---------------------------------------------------------------------------
# Commande d'un moteur :
# paramètres :
#   sens  : sens de rotation
#   consigne_rotation_roue : en tours par seconde

    def Cmde_moteur(self, sens, consigne_rotation_roue):
        self.DRV883_Sleep_Pin.value(0)  # Désactive le driver DRV8833
        self.sens = sens
        if consigne_rotation_roue < 0.0:
            self.consigne_rotation_roue = 0.0
        elif consigne_rotation_roue > VITESSE_MAX:
            self.consigne_rotation_roue = VITESSE_MAX
        else:
            self.consigne_rotation_roue = consigne_rotation_roue
        consigne_pwm_moteur = self.ToursParSeconde_vers_PWM(
            self.consigne_rotation_roue)
        self.DRV883_Sleep_Pin.value(
            1
        )  # Activer le driver DRV8833.value(1) # Activer le driver DRV8833
        if self.sens == SENS_HORAIRE:  # forward
            self.DRV8833_Pwm_In1.duty_cycle(
                consigne_pwm_moteur)  # 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 self.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(
                consigne_pwm_moteur)  # 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_In2.duty_cycle(0.0)  # Rapport cyclique à 0.0 sur IN2
        self.DRV883_Sleep_Pin.value(0)  # Désactive le driver DRV8833
#---------------------------------------------------------------------------

    @staticmethod
    def ToursParSeconde_vers_PWM(consigne_rotation_roue):
        # Permet de calculer le rapport cyclique de la PWM de commande d'un moteur
        # en fonction de la vitesse de rotation de la roue
        # consigne_rotation_roue dans [0.0 ; 1.78] tours/s
        # Valeur retournée : rapport cyclique dans [0.0 ; 1.0]
        # Interpolation polynomiale : y = ax^6+bx^5+cx^4+dx^3+ex^2+fx+g avec :
        #    a = -0.2903
        #    b = 1.9281
        #    c = -4.6062
        #    d = 5.2432
        #    e = -2.8844
        #    f = 0.8839
        #    g = 0.0611
        # Validé le 06.03.2019
        coeff = (-0.2903, 1.9281, -4.6062, 5.2432, -2.8844, 0.8839, 0.0611)

        y = consigne_rotation_roue * coeff[0] + coeff[1]
        for i in range(1, 6):
            y = consigne_rotation_roue * y + coeff[i + 1]
        return y