Exemplo n.º 1
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()
Exemplo n.º 2
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)
Exemplo n.º 3
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)
Exemplo n.º 4
0
def stop(pin=27):
    from machine import Pin, PWM
    try:
        pwm = PWM(Pin(pin))
        pwm.duty(0)
        pwm.freq(1)
    finally:
        pwm.deinit()
Exemplo n.º 5
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()
Exemplo n.º 6
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()
Exemplo n.º 7
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)
Exemplo n.º 8
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()
Exemplo n.º 9
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)))
Exemplo n.º 10
0
          miso=Pin(12))
oled = SH1106_SPI(128, 64, spi, dc=Pin(25), res=Pin(16), cs=Pin(15))

#显示中文
#oled.draw_chinese('我',0,0)
#oled.draw_chinese('我',4,2)
wlan = network.WLAN(network.STA_IF)

is_heating = 0  # State heating in oled,io output,when heating set to 1
is_setpoint_flag = 0
is_countdown_flag = 0
# PWM Control,设定输出引脚,频率,占空比
heater = PWM(Pin(27))  #GPIO 27
heater.freq(1)
#默认占空比0
heater.duty(0)
#PID Setup

#下面是自由变量,由于没定义系统会报错,所以要先定义并赋值
#参数初始化,p、i、d分别是pid参数
p = '0.00'
i = '0.00'
d = '0.00'
#duty占空比,大部分情况下drive=duty
#drive是计算出来,考虑了最大值和最小值后的值
drive = '0.0'
duty = '0'
duty_min = str('0')
duty_max = str('1023')
#控制周期,经过测试,15.5秒上升1摄氏度,1.5秒上升0.1摄氏度,如果允许误差0.2度,应该设置3秒
sleep_time = str('1.0')  #Control loop interval (seconds)
Exemplo n.º 11
0
class led_pwm():
    # led_pwm is a basic constructor for

    def __init__(self, config={}):
        pin = config.get("pin", 0)
        if pin not in (
                0,
                2,
                4,
                5,
                12,
                13,
                14,
                15,
        ):
            raise ValueError("pin must be 0, 2, 4, 5, 12, 13, 14, or 15")
        self._pwm_device = PWM(Pin(pin, Pin.OUT), freq=500, duty=0)
        self.inverted = config.get("inverted", False)
        self.is_on = False
        self.val = 0
        self.state = 'OFF'
        self.old_state = None
        self.type = config.get("type", "led")
        self.topic = config.get("state_topic", None)
        self.set_topic = config.get("command_topic", None)

        self.value(0)

    def __str__(self):
        variables = (self.is_on, self.inverted, self.val,
                     self._pwm_device.duty())
        log_str = 'is_on: {}, inverted: {}, value: {}, duty: {}'
        return log_str.format(*variables)

    def value(self, value=None):
        if value == None:
            return self.val
        elif 0 > value > 255:
            raise ValueError('value must be between 0 and 255')
        self.val = value
        if value == 0:
            self.is_on = False
            self.state = 'OFF'
        else:
            self.is_on = True
            self.state = 'ON'
        if self.inverted:
            pin_val = 1023 - int(round(value * 4.012))
        else:
            pin_val = int(round(value * 4.012))
        self._pwm_device.duty(pin_val)
        return self.val

    def update(self, state):
        if isinstance(state, str):
            state = state.lower()  # convert value to lower case
        on_states = ('true', 'on', True, 1, '1')
        off_states = ('false', 'off', False, 0, '0')
        if state in on_states:
            self.on()
        elif state in off_states:
            self.off()

    def check_state(self):
        pass

    def on(self):
        self.value(255)

    def off(self):
        self.value(0)

    def toggle(self):
        if self.is_on:
            self.value(0)
        else:
            self.value(255)
Exemplo n.º 12
0
from machine import Timer, PWM
import time
from board import board_info
from fpioa_manager import *

board_info = board_info()

tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM)
ch = PWM(tim, freq=500000, duty=50, pin=board_info.LED_G)
duty = 0
dir = True
while True:
    if dir:
        duty += 10
    else:
        duty -= 10
    if duty > 100:
        duty = 100
        dir = False
    elif duty < 0:
        duty = 0
        dir = True
    time.sleep(0.05)
    ch.duty(duty)
Exemplo n.º 13
0
from machine import PWM
# frequency ranges upto 1Hz and Duty scycle of 512
led = PWM(4, freq=1000, duty=512)
# Connect your LED to D2 or GPIO4 of NodeMCU
# First it starts from 0 duty cycle and ends to 510
try:
    for i in range(0, 511, 5):
        led.duty(i)
        print(i)
    # then it recides from 510 to 0 and then deinitlises the process
    for i in range(510, -5, -5):
        led.duty(i)
        print(i)

    led.deinit()  # Deinitialises the process
except KeyboardInterrupt:
    print("User ended the Program, bye...!!!!")
Exemplo n.º 14
0
import common
from machine import Pin, PWM
from encoder import Encoder

MAX_STEPS_ENCODER = 32
CLIENT_ID = 'LIGHTS'
SUBTOPIC = b"%s/set/#" % CLIENT_ID
PUBTOPIC_ON = b"%s/state/power" % CLIENT_ID
PUBTOPIC_VALUE = b"%s/state/intensity" % CLIENT_ID

light_pin = Pin(14)  # D5
light_pwm = PWM(light_pin, freq=1000)
light_pwm.duty(512)  # 0 = 0%, 1023 = 100%
sw = Pin(5, Pin.IN, Pin.PULL_UP)  # d1

light_intensity = 1
light_on = True


def set_light(on, value):
    light_pwm.duty(on * value)
    common.publish(PUBTOPIC_ON, str(on))
    common.publish(PUBTOPIC_VALUE, str(value))


def update_light():
    value = light_intensity * int(1024 / MAX_STEPS_ENCODER)
    set_light(int(light_on), value)


@common.debounce(250)
Exemplo n.º 15
0
class RgbLightDriver:
    def __init__(self, r_pin_num, g_pin_num, b_pin_num):
        self.r_pwm = PWM(Pin(r_pin_num))
        self.g_pwm = PWM(Pin(g_pin_num))
        self.b_pwm = PWM(Pin(b_pin_num))

        self.b = 0
        self.c = {'r': 0, 'g': 0, 'b': 0}

    def on(self):
        self.__update()

    def off(self):
        self.r_pwm.duty(1023)
        self.g_pwm.duty(1023)
        self.b_pwm.duty(1023)

    def color(self, value):
        self.c = value
        self.__update()

    def brightness(self, value):
        self.b = value
        self.__update()

    def __update(self):
        self.r_pwm.duty(
            int(1023 * (1.0 - self.b * self.c['r'] / 255.0 / 255.0)))
        self.g_pwm.duty(
            int(1023 * (1.0 - self.b * self.c['g'] / 255.0 / 255.0)))
        self.b_pwm.duty(
            int(1023 * (1.0 - self.b * self.c['b'] / 255.0 / 255.0)))
Exemplo n.º 16
0
from machine import PWM, Pin
import time

PWM_PORT = 2
PWM_FREQ = 1000
DUTY_DEFAULT = 1023
DUTY_MIN = 0
DUTY_MAX = 1023

pwm = PWM(Pin(PWM_PORT), freq=PWM_FREQ, duty=DUTY_DEFAULT)

for i in range(1023):
    pwm.duty(1023 - i)
    print("duty: {}".format(1023 - i))
    time.sleep_ms(10)
Exemplo n.º 17
0
from machine import Pin,PWM
import time
p14=Pin(14)   # the buzzer runs from this pin
pwm14=PWM(p14)

pwm14.freq(500)
pwm14.duty(512)

time.sleep(1)
pwm14.deinit()
Exemplo n.º 18
0
class Main(HeatControl):
    def __init__(self):
        super().__init__()
        self.wifi_led = Pin(2, Pin.OUT,
                            value=1)  # Pin2, светодиод на плате контроллера
        self.heat = PWM(Pin(13), freq=1000,
                        duty=0)  # Pin12, управление нагревом пола
        self.default_on = Pin(
            14, Pin.IN)  # Pin14, кнопка для сброса настроек в дефолт
        self.i2c = I2C(scl=Pin(5), sda=Pin(4),
                       freq=400000)  # Настройка шины i2c
        self.ds = DS18X20(OneWire(Pin(12)))  # Set Temperature sensors
        # Дефолтные настройки, если файла config.txt не будет обнаружено в системе
        self.default = {}
        self.default['MODE'] = 'AP'  # Включаем точку доступа
        self.default[
            'ssid'] = 'HEAT_CONTROL'  # Устанавливаем имя точки доступа
        self.default['pass'] = '******'  # Пароль для точки доступа
        self.default['timezone'] = 3  # Временная зона
        self.default[
            'DST'] = True  # Разрешаем переход с летнего на зимнее время
        self.default[
            'SET'] = 20.0  # Установка поддерживаемой температуры в помещении
        self.default['DAY'] = 50  # Уменьшение мощности в дневное время в %
        self.default['ON'] = (0, 0, 0, 22, 0, 0, 0, 0
                              )  # Время включения обогрева 20:00
        self.default['OFF'] = (0, 0, 0, 8, 0, 0, 0, 0
                               )  # Время выключения обогрева 08:00
        self.default['WORK'] = 'ON'  # Постоянный обогрев включен
        self.default['DS_K'] = -5.0  # Поправочный коэффициент для DS18B20
        # Дефолтный хещ логин, пароль для web admin (root:root)
        self.default_web = str(
            b'0242c0436daa4c241ca8a793764b7dfb50c223121bb844cf49be670a3af4dd18'
        )
        # Основные настройки системы
        self.config[
            'DEBUG'] = False  # Режим отладки, делаем программу разговорчивой
        self.config['RTC_DS3231'] = 0x68  # Адрес DS3231 RTC
        self.config['WIFI_AP'] = ('192.168.4.1', '255.255.255.0',
                                  '192.168.4.1', '208.67.222.222')
        self.config['TARIFF_ZONE'] = (
            (7, 0, 0), (22, 59, 59))  # Тарифнаф зона день с 7 до 22:59
        self.config['DAY_ZONE'] = (
            (7, 0, 0), (22, 59, 59))  # Дефолтное значение тарифной зоны день
        self.config['TEMP'] = 18.00  # Начальное значение темратуры в помещении
        self.config[
            'DUTY_MIN'] = 0  # Режим работы ПИД регулятора, минимальный предел
        self.config[
            'DUTY_MAX'] = 90  # Режим работы ПИД регулятора, максимальный предел, установлен в 90%
        # для исключения перегрева нагревателя
        self.config['RTC_TIME'] = (0, 1, 1, 0, 0, 0, 0, 0)  # Дефолтное время
        self.config['PID_KP'] = 5
        self.config['PID_KI'] = 0.1
        self.config['PID_KD'] = 0.01
        self.config['SETPOWER'] = 0  # Заданное значение мощности нагревателя
        self.config['POWER'] = 0  # Начальное значение мощности нагревателя
        self.config['NTP_UPDATE'] = True  # Разрешаем обновление по NTP
        self.config['IP'] = None  # Дефолтный IP адрес
        self.config['no_wifi'] = True  # Интернет отключен(значение True)
        # Eсли файла config.txt не обнаружено в системе создаем его
        if self.exists('config.txt') == False or not self.default_on():
            read_write_config(cfg=self.default)
        # Eсли файла root.txt нет создаем его
        if self.exists('root.txt') == False or not self.default_on():
            read_write_root(passwd=self.default_web)
        # Читаем настройки из файла config.txt
        update_config()
        # Начальные настройки сети AP или ST
        if self.config['MODE'] == 'AP':
            self._ap_if = WLAN(AP_IF)
            self.config['WIFI'] = self._ap_if
        elif self.config['MODE'] == 'ST':
            self._sta_if = WLAN(STA_IF)
            self.config['WIFI'] = self._sta_if
        # Настройка для работы с RTC
        self.config['RTC']= DS3231(self.i2c, \
                    self.config['RTC_DS3231'], self.config['timezone'], ) #В ключаем работу с модулем RTC DS3231
        self.rtc = self.config['RTC']
        self.config['NOW'] = mktime(self.rtc.datetime())
        # Включаем поддержку TIME ZONE
        self.tzone = TZONE(self.config['timezone'])

        loop = asyncio.get_event_loop()
        loop.create_task(self._heartbeat())  # Индикация подключения WiFi
        loop.create_task(
            self._collection_temp()
        )  # Сбор информации с температурных датчиков DS18D20 и Вычисление тарифных зон
        loop.create_task(self._dataupdate())  # Обновление информации и часы
        loop.create_task(self._start_web_app())  # Включаем WEB приложение
        collect()  #Очищаем RAM

    async def _dataupdate(self):
        while True:
            # RTC Update
            self.config['RTC_TIME'] = self.rtc.datetime()
            rtc = self.config['RTC_TIME']
            self.config['NOW'] = mktime(rtc)
            # Проверка летнего или зименего времени каждую минуту в 30с
            if rtc[5] == 30:
                self.rtc.settime('dht')
            # Если у нас режим подключения к точке доступа и если есть соединение, подводим часы по NTP
            if self.config['MODE'] == 'ST' and not self.config['no_wifi']:
                # Подводка часов по NTP каждые сутки в 22:00:00
                if rtc[3] == 22 and rtc[4] == 5 and rtc[5] < 3 and self.config[
                        'NTP_UPDATE']:
                    self.config['NTP_UPDATE'] = False
                    self.rtc.settime('ntp')
                    await asyncio.sleep(1)
                    self.config['NTP_UPDATE'] = True
            collect()  #Очищаем RAM
            await asyncio.sleep(1)

    #Индикация подключения WiFi
    async def _heartbeat(self):
        while True:
            if self.config['no_wifi'] == True:
                self.wifi_led(not self.wifi_led()
                              )  #Быстрое мигание, если соединение отсутствует
                await asyncio.sleep_ms(200)
            elif self.config['no_wifi'] == False:
                self.wifi_led(0)  #Редкое мигание при подключении
                await asyncio.sleep_ms(50)
                self.wifi_led(1)
                await asyncio.sleep_ms(5000)
            else:
                self.wifi_led(0)  #Два быстрых миганиения при AP Mode
                await asyncio.sleep_ms(50)
                self.wifi_led(1)
                await asyncio.sleep_ms(50)
                self.wifi_led(0)
                await asyncio.sleep_ms(50)
                self.wifi_led(1)
                await asyncio.sleep_ms(5000)

    # Сбор данных с DS18D20, Вычисление тарифной зоны день, Управление отоплением и логикой работы отопления
    async def _collection_temp(self):
        roms = self.ds.scan()
        #Создаем ПИД регулятор
        pid = PID(self.config['PID_KP'],
                  self.config['PID_KI'],
                  self.config['PID_KD'],
                  setpoint=self.config['SET'])
        #Устанавливаем минимальный и максимальный предел работы регулятора
        pid.output_limits = (self.config['DUTY_MIN'], self.config['DUTY_MAX'])
        #Устанавливаем поддерживаемую температуру
        t_room = self.config['SET']
        heat = False
        while True:
            rtc = self.config['RTC_TIME']
            # Вычисление тарифной зоны день, если минуты обнулились, прошел 1 час делаем проверку тарифной зоны
            if self.config['RTC_TIME'][
                    4] == 0 and self.config['RTC_TIME'][5] < 10:
                delta = self.config['timezone'] - self.tzone.adj_tzone(
                    self.config['RTC_TIME'])
                if delta == 1:  #Если Зимняя тарифная зона вычитаем из часов delta
                    self.config['DAY_ZONE'] = ((self.config['TARIFF_ZONE'][0][0]-delta,)\
                    +self.config['TARIFF_ZONE'][0][1:]),\
                    (self.config['TARIFF_ZONE'][1][0]-delta,)+self.config['TARIFF_ZONE'][1][1:]
                else:  #Если Летняя тарифная зона, 'DAY_ZONE' = 'TARIFF_ZONE'
                    self.config['DAY_ZONE'] = self.config['TARIFF_ZONE']
    # Считываем показания с датчика температуры
            self.ds.convert_temp()
            await asyncio.sleep(2)
            self.config['TEMP'] = round(
                self.ds.read_temp(roms[0]) + self.default['DS_K'], 2)
            #Логика управления отоплением
            st = self.config['DAY_ZONE'][0]
            end = self.config['DAY_ZONE'][1]
            st = mktime((rtc[0], rtc[1], rtc[2], st[0], 0, 0, 0, 0))
            end = mktime(
                (rtc[0], rtc[1], rtc[2], end[0], end[1], end[2], 0, 0))
            # Если тариф дневной зоны, ограничиваем мощность нагрева на self.config['DAY']%
            if st < self.config['NOW'] and self.config['NOW'] < end:
                pid.output_limits = (self.config['DUTY_MIN'],
                                     self.config['DAY'])
                self.config['SETPOWER'] = self.config['DAY']
            else:  # Если тариф ночной зоны, разрешаем нагрев до self.config['DUTY_MAX']%
                pid.output_limits = (self.config['DUTY_MIN'],
                                     self.config['DUTY_MAX'])
                self.config['SETPOWER'] = self.config['DUTY_MAX']
            if t_room != self.config['SET']:
                pid.set_setpoint = self.config['SET']
                t_room = self.config['SET']
    # Вычисляем мощность нагрева
            if heat:
                self.config['POWER'] = round(
                    pid(self.config['TEMP']) * 10
                )  # Для ШИМ необходим диапазон от 0 до 1000, умножаем мощность на 10
            else:
                self.config['POWER'] = 0
            self.heat.duty(self.config['POWER'])
            # Обрабатываем режимы работы контроллера
            if self.config['WORK'] == 'ON':  # Режим поддержания температуры
                heat = True
            elif self.config['WORK'] == 'TAB':  # Режим работы по рассписанию
                on = self.config['ON']
                off = self.config['OFF']
                d = rtc[2] + 1 if int(on[3]) > int(off[3]) else rtc[2]
                on = mktime((rtc[0], rtc[1], rtc[2], on[3], on[4], 0, 0, 0))
                off = mktime((rtc[0], rtc[1], d, off[3], off[4], 0, 0, 0))
                if self.config['NOW'] > on and self.config['NOW'] < off:
                    heat = True
                else:
                    heat = False
            elif self.config['WORK'] == 'OFF':  # Обогрев выключен
                heat = False
            else:
                heat = False
            collect()  #Очищаем RAM
            await asyncio.sleep(10)

    #Запуск WEB приложения

    async def _start_web_app(self):
        while True:
            await asyncio.sleep(5)
            if not self.config['no_wifi'] or self.config['MODE'] == 'AP':
                self.ip = self.config['WIFI'].ifconfig()[0]
                self.dprint('Run WebAPP...')
                app.run(debug=self.config['DEBUG'], host=self.ip, port=80)

    async def _run_main_loop(self):  # Бесконечный цикл
        while True:
            #lt = self.config['RTC_TIME']
            #try:
            #    self.dprint('IP:', self.config['IP'])
            #    self.dprint('Local Time:', '{:0>2d}-{:0>2d}-{:0>2d} {:0>2d}:{:0>2d}:{:0>2d}'\
            #                          .format(lt[0], lt[1], lt[2], lt[3], lt[4], lt[5]))
            #    self.dprint('MemFree:', '{}Kb'.format(str(round(mem_free()/1024, 2))))
            #    self.dprint('MemAvailab:', '{}Kb'.format(str(round(mem_alloc()/1024, 2))))
            #except Exception as e:
            #    self.dprint('Exception occurred: ', e)
            collect()  # Очищаем RAM
            await asyncio.sleep(30)

    async def main(self):
        while True:
            try:
                await self.connect()  #Включение WiFi и контроль соединения
                await self._run_main_loop()
            except Exception as e:
                self.dprint('Global communication failure: ', e)
                await asyncio.sleep(20)
Exemplo n.º 19
0
from time import sleep
from machine import Pin, PWM
pwm = PWM(Pin(17, Pin.OUT), freq=50, duty=75)

pwm.duty(50)  # left
sleep(1)
pwm.duty(75)  # middle
sleep(1)
pwm.duty(100)  # right
sleep(1)
pwm.deinit()
Exemplo n.º 20
0
from machine import Pin, PWM
import time

buzzer = PWM(Pin(13))

pitches = {
    'C5': 523,
    'D5': 587,
    'E5': 659,
    'F5': 698,
    'G5': 784,
    'A5': 880,
    'B5': 988,
    'S': 0
}

melody = (('E5', 100), ('S', 100), ('E5', 100), ('S', 300), ('E5', 100),
          ('S', 300), ('C5', 100), ('S', 100), ('E5', 100), ('S', 300), ('G5',
                                                                         100))

for tone, tempo in melody:

    if tone == 'S':
        buzzer.duty(0)
    else:
        buzzer.duty(900)
        buzzer.freq(pitches[tone])

    time.sleep_ms(tempo)

buzzer.deinit()
Exemplo n.º 21
0
    while True:
        if run_flag:
            for pos in pos_list:
                servo.duty(pos)
                await asyncio.sleep_ms(interval_ms)
                dist_cm = await async_measure_range()
                pos_actual = pos
        elif not run_flag:
            await asyncio.sleep(0) # do nothing
    
#stop all motors first
stop_all_sync()

# move servo to initial position
print('Move sensor to initial position...')
servo.duty(75)
sleep(1) #wait 1s for servo reaching initial position
print('Waiting for start button...')

#enable gc
gc.enable()

# create callback fo button:
button.irq(trigger=Pin.IRQ_FALLING, handler=callback)

# define loop
loop = asyncio.get_event_loop()

#create looped tasks
loop.create_task(blink_led(syst_led, interval_ms=250))
loop.create_task(radar_scan(interval_ms=250))
Exemplo n.º 22
0
from machine import Pin, PWM, ADC
import time

led = PWM(Pin(32), freq=5000)  # create and configure

adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB)

delay = 0.02

while True:
    value = int(adc.read() * 0.25)  # convert range 0-4095 to 0-1023
    led.duty(value)
    print(value)
    time.sleep(delay)
Exemplo n.º 23
0
class Feeder(object):
    def __init__(
        self,
        pin_servo=None,
        trigger=None,
        echo=None,
    ):
        """
        servo's minimum duty 27
        """
        self._open_position = None
        self._open_position_max = 38
        self._pause_open = None
        self._pause_open_max = 0.8
        self._close_position = 77
        self._trigger = trigger
        self._remaining_quantity = None
        self._full_quantity = 1
        self._empty_quantity = 25
        self._distance_cm = None

        self._servo = PWM(Pin(pin_servo, Pin.OUT),
                          freq=50,
                          duty=self._close_position)

        if self._trigger:
            self._distance_trigger = Pin(trigger, Pin.OUT)
            self._distance_echo = Pin(echo, Pin.IN)

    @property
    def open_position(self):
        return float(self._open_position)

    @open_position.setter
    def open_position(self, value):
        self._open_position = float(value)

    @property
    def pause_open(self):
        return float(self._pause_open)

    @pause_open.setter
    def pause_open(self, value):
        self._pause_open = float(value)

    @property
    def remaining_quantity(self):
        """"""
        if not self._trigger:
            return str(-1)

        if self._distance_cm is None:
            return str(-1)

        result = self.map_range(self.distance_cm,
                                (self._empty_quantity, self._full_quantity),
                                (0, 100))

        print('Full at %s%s.' % (result, "%"))
        return str(result)

    @remaining_quantity.setter
    def remaining_quantity(self, value):
        self._remaining_quantity = value

    @property
    def distance_cm(self):
        return self._distance_cm

    @distance_cm.setter
    def distance_cm(self, value):
        self._distance_cm = value

    def distance_in_cm(self):
        start = 0
        end = 0

        self._distance_trigger.on()
        time.sleep_us(10)
        self._distance_trigger.off()

        while self._distance_echo.value() == 0:
            start = time.ticks_us()

        while self._distance_echo.value() == 1:
            end = time.ticks_us()

        diff = time.ticks_diff(start, end)

        # Calc the duration of the recieved pulse, divide the result by
        # 2 (round-trip) and divide it by 29 (the speed of sound is
        # 340 m/s and that is 29 us/cm).
        dist_in_cm = (diff / 2) / 29

        self._distance_cm = -dist_in_cm
        print("Distance: %s cm." % self._distance_cm)
        if self._distance_cm > self._empty_quantity:
            self._distance_cm = self._empty_quantity
        return self._distance_cm

    def get_opening_ratio(self):
        """"""
        if not self._trigger:
            return self._open_position, self._pause_open

        dist = self.distance_in_cm()

        opening_ratio = self.map_range(
            dist, (self._empty_quantity, self._full_quantity),
            (self._open_position_max, self._open_position))
        pause_ratio = self.map_range(
            dist, (self._empty_quantity, self._full_quantity),
            (self._pause_open, self._pause_open_max))

        if pause_ratio > 2:
            pause_ratio = 2

        return opening_ratio, pause_ratio

    @staticmethod
    def map_range(value, old_range, new_range):
        """"""
        old_range_max, old_range_min = old_range
        old_range = old_range[0] - old_range[1]
        new_range_max, new_range_min = new_range
        new_range = new_range[0] - new_range[1]

        new_value = (
            (value - old_range_min) * new_range / old_range) + new_range_min

        return round(new_value, 2)

    def feed(self):
        """"""
        # open_ratio, pause_ratio = self.get_opening_ratio()
        open_ratio = self.open_position
        pause_ratio = self.pause_open
        print('Opening to: %i degrees.' % open_ratio)
        print('Pausing for: %f sec.\n' % pause_ratio)

        self._servo.duty(int(round(open_ratio)))
        time.sleep(pause_ratio)
        self._servo.duty(self._close_position)

        # print('Done feeding: %s' % self._servo.__name__)
        return
Exemplo n.º 24
0
            ie = request.find(
                ' ', ib)  #init address of the index with ib,then find ' '
            Val = request[ib +
                          4:ie]  #get the string of ib+4 to ie in the request
            print("Val =", Val)
            led.duty(int(Val) * 100)  #set the duty of led
            conn.send(Val)  #send data
        else:
            with open('Ajax_webCtrl.html',
                      'r') as html:  #open file 'webCtrl.htm' with readonly
                conn.sendall(html.read(
                ))  #read data from 'webCtrl.htm',and send all of the data
        conn.sendall('\r\n')
        conn.close()  #close file
        #print("Connection wth %s closed" % str(addr))


#Catch exceptions,stop program if interrupted accidentally in the 'try'
try:
    led = PWM(Pin(2), freq=100)  #create led object
    led.init()
    led.duty(0)
    connectWifi(SSID, PASSWORD)
    ajaxWebserv()
except:
    if (s):
        s.close()
    led.deinit()
    wlan.disconnect()
    wlan.active(False)
Exemplo n.º 25
0
import network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("itcollege")

import sys
import uwebsockets
from machine import Pin, PWM
led = PWM(Pin(14, mode=Pin.OUT), freq=400)  # SCK LED on WeMos D1
uri = "ws://iot.koodur.com:80/ws/mllnd-xyz"
print("Connecting to:", uri)
conn = uwebsockets.connect(uri)
conn.send("alive")
while True:
    print("Reading message...")
    try:
        fin, opcode, data = conn.read_frame()
    except OSError:  # Connection timeout or reset
        sys.exit()  # Soft reset
    if data.startswith(b"duty:"):
        led.duty(int(data[5:]))
    else:
        print("Got unknown command:", data)
Exemplo n.º 26
0
# -*- coding: utf-8 -*-
"""
   程式說明請參閱9-22頁
"""

from machine import Pin, PWM

motorPin = Pin(13, Pin.OUT)
MOTOR = PWM(motorPin, 1000)
CLK = Pin(14, Pin.IN)
DT = Pin(12, Pin.IN)
power = 0
step = 10
prev = CLK.value()

while True:
    now = CLK.value()

    if now != prev:
        if DT.value() != now:
            power = min(1023, power + step)
        else:
            power = max(0, power - step)

        print("power: " + str(power))
        MOTOR.duty(power)

    prev = now
Exemplo n.º 27
0
#
# this is workaround for using L298N as 3.3V PWM
# wemos d1 mini 13 : D7
# wemos d1 mini 15 : D8
# wemos d1 mini 2 : D4
# fixed on: (D7 = HIGH, D8 = LOW)
# fixed off: (D7 = LOW, D8 = LOW)
# duty range : 0 ~ 1023

p13 = Pin(13, Pin.OUT)
p15 = Pin(15, Pin.OUT)
p13.off()  # on
p15.off()  # off

pwm0 = PWM(Pin(2))
pwm0.duty(0)
######################################################

targetT = 195
p = Pid.Pid(targetT, {"P": 22.2, "I": 1.09, "D": 114}, 0)

if __name__ == 'builtins':
    while 1:
        temperature = thermistor.getTemperature()

        if (temperature is None):
            continue

        targetPwm = p.update(temperature)

        print("[fixed : %d] Target: %.1f C | Current: %.1f C | PWM: %s %%" %
Exemplo n.º 28
0
class WifiManager:

    AUTH_MODES = {
        0: "open",
        1: "WEP",
        2: "WPA-PSK",
        3: "WPA2-PSK",
        4: "WPA/WPA2-PSK"
    }

    def __init__(self,
                 ap_name='',
                 ap_password='',
                 filepath='profiles.txt',
                 connection_max_retries=10,
                 led_pin=2):
        self._filepath = filepath
        self._ap_name = ap_name
        self._ap_password = ap_password
        self._connection_max_retries = connection_max_retries
        self.wlan = network.WLAN(network.STA_IF)
        self.ap = network.WLAN(network.AP_IF)
        self._profiles = self._read_profiles()
        self.led = PWM(Pin(led_pin))
        self._led_off()

    def is_access_point_mode(self):
        return self.ap.active()

    def is_wifi_connected(self):
        return self.wlan.active()

    def auto_connect(self, include_open=False):
        self._led_flash_slow()
        print('Attempting auto connect')
        if not self._profiles:
            print('No stored profiles, exposing AP')
            self.start_ap()
            return
        connected = False
        # start by scanning all available access points
        print('Scanning for networks')
        networks = self.access_point_scan()
        for ssid, bssid, channel, rssi, authmode, hidden in sorted(
                networks, key=lambda x: x[3], reverse=True):
            ssid = ssid.decode('utf-8')
            encrypted = authmode > 0
            print("\t Found ssid: %s chan: %d rssi: %d authmode: %s" %
                  (ssid, channel, rssi, self.AUTH_MODES.get(authmode, '?')))
            if not encrypted and include_open:
                # it's not secured so let's try to connect
                connected = self.connect(ssid)
            else:
                if ssid not in self._profiles:
                    # we don't have any profiles for this network so skipping
                    continue
                connected = self.connect(ssid, self._profiles[ssid])
            if connected:
                break
        if not connected:
            print('Failed to detect any previous networks, exposing AP')
            self.start_ap()

    def start_ap(self):
        self._led_off()
        print('Starting AP {}'.format(self._ap_name))
        self.stop_wlan()
        # activate the interface
        self.ap.active(True)
        # configure the params
        self.ap.config(essid=self._ap_name, password=self._ap_password)

    def stop_ap(self):
        # deactivate the interface
        self.ap.active(False)

    def start_wlan(self):
        # activate the interface
        self.wlan.active(True)

    def stop_wlan(self):
        if self.wlan.isconnected():
            self.wlan.disconnect()
        # deactivate the interface
        self.wlan.active(False)

    def connect(self, essid='', password=''):
        if self.wlan.isconnected():
            self.disconnect()
        self._led_flash_fast()
        print('connecting to {} . . .'.format(essid))
        # switch from ap to wlan mode
        self.start_wlan()
        self.wlan.connect(essid, password)
        # wait a few seconds to see if the connection was successful
        for _ in range(self._connection_max_retries * 2):
            if self.wlan.isconnected():
                break
            time.sleep(0.5)
            print('. . .')
        # set the led to be on
        if not self.wlan.isconnected():
            print('error connecting to {}'.format(essid))
            # enable ap again
            self.start_ap()
            # set the led to be dim
            self._led_off()
            return False
        self._led_on()
        print('connected')
        self._add_new_profile(essid, password)
        return True

    def disconnect(self):
        print('disconnecting . . .')
        self.wlan.disconnect()

    def access_point_scan(self):
        self.start_wlan()
        # scan and return all available access points
        return self.wlan.scan()

    def _read_profiles(self):
        profiles = {}
        try:
            with open(self._filepath) as f:
                line = f.readline()
                if not line:
                    # EOF
                    return profiles
                ssid, password = line.strip('\n').split(";")
                profiles[ssid] = password
        except OSError:
            pass
        finally:
            return profiles

    def _add_new_profile(self, ssid, password):
        try:
            self._profiles = self._read_profiles()
            self._profiles[ssid] = password
            self._write_profiles(self._profiles)
        except Exception as exc:
            print('Error adding new profile {}'.format(exc))

    def _write_profiles(self, profiles):
        try:
            print('Writing profiles')
            with open(self._filepath, "w") as f:
                for ssid, password in profiles.items():
                    f.write("{};{}\n".format(ssid, password))
            print('Profile writing completed')
        except Exception as exc:
            print('Error writing profiles {}'.format(exc))

    def _led_off(self):
        self.led.duty(0)
        self.led.freq(2000)

    def _led_on(self):
        self.led.duty(512)
        self.led.freq(2000)

    def _led_flash_slow(self):
        self.led.duty(512)
        self.led.freq(1)

    def _led_flash_fast(self):
        self.led.duty(512)
        self.led.freq(5)
Exemplo n.º 29
0
from machine import Pin, PWM
import time

# externe LED zit op pin D1 (GPIO5)
PinNum = 5

# pwm initialisatie
pwm1 = PWM(Pin(PinNum))
pwm1.freq(60)
pwm1.duty(0)

step = 100
for i in range(10):
    # oplichten
    while step < 1000:
        pwm1.duty(step)
        time.sleep_ms(500)
        step+=100
    # uitdoven    
    while step > 0:
        pwm1.duty(step)
        time.sleep_ms(500)
        step-=200

# pwm resetten        
pwm1.deinit()
Exemplo n.º 30
0
class Buzzer():

    B0 = 31
    C1 = 33
    CS1 = 35
    D1 = 37
    DS1 = 39
    E1 = 41
    F1 = 44
    FS1 = 46
    G1 = 49
    GS1 = 52
    A1 = 55
    AS1 = 58
    B1 = 62
    C2 = 65
    CS2 = 69
    D2 = 73
    DS2 = 78
    E2 = 82
    F2 = 87
    FS2 = 93
    G2 = 98
    GS2 = 104
    A2 = 110
    AS2 = 117
    B2 = 123
    C3 = 131
    CS3 = 139
    D3 = 147
    DS3 = 156
    E3 = 165
    F3 = 175
    FS3 = 185
    G3 = 196
    GS3 = 208
    A3 = 220
    AS3 = 233
    B3 = 247
    C4 = 262
    CS4 = 277
    D4 = 294
    DS4 = 311
    E4 = 330
    F4 = 349
    FS4 = 370
    G4 = 392
    GS4 = 415
    A4 = 440
    AS4 = 466
    B4 = 494
    C5 = 523
    CS5 = 554
    D5 = 587
    DS5 = 622
    E5 = 659
    F5 = 698
    FS5 = 740
    G5 = 784
    GS5 = 831
    A5 = 880
    AS5 = 932
    B5 = 988
    C6 = 1047
    CS6 = 1109
    D6 = 1175
    DS6 = 1245
    E6 = 1319
    F6 = 1397
    FS6 = 1480
    G6 = 1568
    GS6 = 1661
    A6 = 1760
    AS6 = 1865
    B6 = 1976
    C7 = 2093
    CS7 = 2217
    D7 = 2349
    DS7 = 2489
    E7 = 2637
    F7 = 2794
    FS7 = 2960
    G7 = 3136
    GS7 = 3322
    A7 = 3520
    AS7 = 3729
    B7 = 3951
    C8 = 4186
    CS8 = 4435
    D8 = 4699
    DS8 = 4978

    def __init__(self):
        self.notes = {
            'cdef': [
                self.C6, self.D6, self.E6, self.F6, self.G6, self.A6, self.B6,
                self.C7, self.D7, self.E7, self.F7, self.G7, self.A7, self.B7,
                self.C8, 0
            ],
            'mario': [
                self.E7, self.E7, 0, self.E7, 0, self.C7, self.E7, 0, self.G7,
                0, 0, 0, self.G6, 0, 0, 0, self.C7, 0, 0, self.G6, 0, 0,
                self.E6, 0, 0, self.A6, 0, self.B6, 0, self.AS6, self.A6, 0,
                self.G6, self.E7, 0, self.G7, self.A7, 0, self.F7, self.G7, 0,
                self.E7, 0, self.C7, self.D7, self.B6, 0, 0, self.C7, 0, 0,
                self.G6, 0, 0, self.E6, 0, 0, self.A6, 0, self.B6, 0, self.AS6,
                self.A6, 0, self.G6, self.E7, 0, self.G7, self.A7, 0, self.F7,
                self.G7, 0, self.E7, 0, self.C7, self.D7, self.B6, 0, 0
            ],
            'starwars': [
                self.A4,
                0,
                0,
                0,
                self.A4,
                0,
                0,
                0,
                self.A4,
                0,
                0,
                0,
                self.F4,
                0,
                0,
                self.C5,
                self.A4,
                0,
                0,
                0,
                self.F4,
                0,
                0,
                self.C5,
                self.A4,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                self.E5,
                0,
                0,
                0,
                self.E5,
                0,
                0,
                0,
                self.E5,
                0,
                0,
                0,
                self.F5,
                0,
                0,
                self.C5,
                self.GS4,
                0,
                0,
                0,
                self.F4,
                0,
                0,
                self.C5,
                self.A4,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
            ],
        }

    def playnotes(self, title, length=150, duty=64):
        # Init
        p = Pin(27, Pin.OUT)
        self.pwm = PWM(p)
        self.pwm.duty(0)

        if title not in self.notes:
            print('unknown title: {}'.format(title))
            return

        melody = self.notes[title]
        print('Play', title)
        for i in melody:
            if i == 0:
                self.pwm.duty(0)
            else:
                self.pwm.freq(i)
                self.pwm.duty(duty)
            time.sleep_ms(length)

        # deinit
        self.pwm.deinit()
Exemplo n.º 31
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')
        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)
Exemplo n.º 32
0
# POT:        ESP32:
# GND -->     GND
# Signal -->  GPIO34
# VCC -->     3V3

# LED:                ESP32:
# GND add 330 Ohm --> GND
# VCC -->             GPIO5

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

frequency = 5000
led = PWM(Pin(5), frequency)
pot = ADC(Pin(34))
pot.width(ADC.WIDTH_10BIT)
pot.atten(ADC.ATTN_11DB)

while True:
    pot_value = pot.read()
    print(pot_value)

    if pot_value < 15:
        led.duty(0)
    else:
        led.duty(pot_value)

    sleep(0.1)
Exemplo n.º 33
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')
Exemplo n.º 34
0
class PWMOut(object):
    """PWM output."""
    def __init__(self, pin, freq=50, duty=0, verbose=False, channel=-1):
        if channel in [i for i in range(RMT_MAX_CHAN)]:
            self._chanRMT = channel
            self._pin = RMT(channel, pin=Pin(pin), clock_div=RMT_CLOCK_DIV)
            self.__setRMTDuty(duty)
            self._pin.loop(True)
        else:
            self._chanRMT = -1
            self._pin = PWM(Pin(pin))
            self._pin.init(freq=freq, duty=duty)
        self._verbose = verbose
        if self._verbose:
            self.__logFrequency()

    def deinit(self):
        self._pin.deinit()

    @property
    def duty_percent(self):
        """ duty in percent
    """
        if self._chanRMT < 0:
            return self._pin.duty() / MAX_DUTY * 100
        else:
            return self._dutyRMT / RMT_DUTY_SCALER

    @duty_percent.setter
    def duty_percent(self, value):
        if self._chanRMT < 0:
            self._pin.duty(int(min(max(0, value / 100.0 * MAX_DUTY),
                                   MAX_DUTY)))
        else:
            self.__setRMTDuty(
                min(max(0, value / 100. * RMT_MAX_DUTY), RMT_MAX_DUTY))

    @property
    def duty(self):
        """ duty as raw value
    """
        if self._chanRMT < 0:
            return self._pin.duty()
        else:
            return self._dutyRMT

    @duty.setter
    def duty(self, value):
        if self._chanRMT < 0:
            self._pin.duty(int(value))
        else:
            self.__setRMTDuty(value)

    @property
    def freq_Hz(self):
        """ frequency in [Hz]
    """
        if self._chanRMT < 0:
            return self._pin.freq()
        else:
            return self._pin.source_freq() / RMT_CLOCK_DIV

    @freq_Hz.setter
    def freq_Hz(self, value):
        if self._chanRMT < 0:
            self._pin.freq(value)
        else:
            if value == 0:
                self._pin.loop(False)
            else:
                self._pin.loop(True)
                d2 = int(
                    (self._pin.source_freq() / RMT_CLOCK_DIV) / value // 2)
                self._pin.write_pulses((d2, d2))
        if self._verbose:
            self.__logFrequency()

    @property
    def max_duty(self):
        if self._chanRMT < 0:
            return MAX_DUTY
        else:
            return RMT_MAX_DUTY

    @property
    def uses_rmt(self):
        return self._chanRMT >= 0

    def __logFrequency(self):
        print("PWM frequency is {0:.1f} kHz".format(self.freq_Hz / 1000))

    def __setRMTDuty(self, value):
        self._dutyRMT = int(min(max(1, value), RMT_MAX_DUTY))
        self._pin.write_pulses((self._dutyRMT, RMT_MAX_DUTY - self._dutyRMT))
Exemplo n.º 35
0
import sys
import utime as time
import machine
from machine import Pin, PWM

import logging
logging.setGlobal(logging.DEBUG)

led = machine.Pin(5, mode=machine.Pin.OUT)
print("Switching off blue led")
led.value(0)

pwm0 = PWM(led)  # create PWM object from a pin with blue led
pwm0.freq()  # get current frequency
pwm0.freq(50)  # set frequency
duty = pwm0.duty()  # get current duty cycle

print("Current duty:", duty)
pwm0.duty()  # get current duty cycle
print("Setting duty to 200")
pwm0.duty(200)  # set duty cycle

for i in range(200):
    pwm0.duty(i)
    time.sleep_ms(2)

for i in range(200):
    pwm0.duty(200 - i)
    time.sleep_ms(2)

#pwm2 = PWM(Pin(6), freq=500, duty=512) # create and configure in one go
Exemplo n.º 36
0
 def stop(self, pin=27):
     from machine import Pin, PWM
     pwm = PWM(Pin(pin))
     pwm.duty(0)
     pwm.freq(1)
     pwm.deinit()
Exemplo n.º 37
0

pin4.irq(handler, trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING)

# initialize PWM
pwm1 = PWM(pin1, timer=0)
pwm2 = PWM(pin2, timer=0)
pwm3 = PWM(pin3, timer=0)

# set frequency
# Note pwm1.freq() == pwm2.freq() since they use the same timer
pwm1.freq(500)
pwm3.freq(500)

# set duty cycle (0 ... 1023)
pwm1.duty(500)
pwm2.duty(500)
pwm3.duty(500)

print("pwm1:", pwm1)
print("pwm2:", pwm2)
print("pwm3:", pwm3)

try:
    # go about other business (or just take a nap)
    sleep(1000)

finally:
    # release PWM circuitry for later reuse
    pwm1.deinit()
    pwm2.deinit()
# 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)
Exemplo n.º 39
0
from machine import Pin, PWM
led = PWM(Pin(5))
led.freq(10)
led.duty(100)  #0 es 0% 100% es 1023
Exemplo n.º 40
0
def servo_write_angle(pin,angle):
	pwm=PWM(Pin(pin))
	pwm.duty(int(40 + 75 * angle / 180))
	pwm.freq(50)
Exemplo n.º 41
0
OLED_HEIGHT = 64
OLED_CYAN_TOP = 16

sta_if = network.WLAN( network.STA_IF )
sta_if.active( True )
sta_if.connect( secrets['ssid'], secrets['wpa2'] )
while not sta_if.isconnected():
    pass

i2c = I2C( 0, scl=Pin( 18 ), sda=Pin( 19 ), freq=100000 )
oled = ssd1306.SSD1306_I2C( OLED_WIDTH, OLED_HEIGHT, i2c, addr=0x3c )

np = NeoPixel( Pin( 23 ), 1 )

dhts = DHT22( Pin( 16 ) )

rtc = RTC()
if machine.DEEPSLEEP != machine.reset_cause() and \
machine.SOFT_RESET != machine.reset_cause():
    update_time()

    np[0] = (0, 0, 0)
    np.write()

    buzz = PWM( Pin( 26 ) )
    buzz.freq( 800 )
    buzz.duty( 512 )
    time.sleep_ms( 200 )
    buzz.deinit()

Exemplo n.º 42
0

# sends a cycle of light intensities on a triangular curve
def intensityCycle(duration, resolution):
    for i in range(0, resolution - 1):
        brightness = 1023 / resolution * i
        #        print(brightness)
        pwmLED.duty(round(brightness))
        utime.sleep_ms(duration)

    for i in range(0, resolution - 1):
        brightness = 1023 - 1023 / resolution * i
        #        print(brightness)
        pwmLED.duty(round(brightness))
        utime.sleep_ms(duration)


print("Changing the light intensity on the built-in LED using PWM")
print("Program written for the workshop on IoT at the")
print("African Internet Summit 2019")
print("Copyright: U.Raich")
print("Released under the Gnu Public License")

led = Pin(2)
pwmLED = PWM(led)
pwmLED.freq(1000)  # PWM at 1 kHz

for i in range(0, 10):
    intensityCycle(20, 100)
pwmLED.duty(0)
Exemplo n.º 43
0
class Rodas:
    freqA = 900
    freqB = 900

    def __init__(self):
        ## Frequencia de trabalho do motor
        # O valor maximo e 1024

        ## 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()