Example #1
0
def temp_menu():
  r = RotaryIRQ(pin_num_clk=14, pin_num_dt=13, min_val=9, max_val=30, reverse=True, range_mode=RotaryIRQ.RANGE_BOUNDED)
  lastval = r.value()
  lcd.clear()
  lcd.putstr("Temperature:\n")
  while True:
    val = r.value() 
    if lastval != val:
      lastval = val
      lcd.move_to(0,1)
      lcd.putstr("")
      lcd.putchar(chr(62))
      if val == 9:
        lcd.putstr("         OFF")
      else: 
        lcd.putstr("        %d" %val)
        lcd.putchar(chr(223))
        lcd.putstr("C")
    if sw.value()==0:
      lcd.clear()
      if val == 9:
        lcd.putstr("Temp:  OFF")
      else: 
        lcd.putstr("Temp: %d"%val)
        lcd.putchar(chr(223))
        lcd.putstr("C")
      time.sleep_ms(5000)
      return val
Example #2
0
    def __init__(self, pin_clk, pin_dt, delay=100, cw=None, ccw=None):
        self._rotary = RotaryIRQ(pin_clk, pin_dt)
        self._delay = delay

        self._cb_cw = cw
        self._cb_ccw = ccw

        loop = asyncio.get_event_loop()
        loop.create_task(self.check())
async def main():
    r = RotaryIRQ(pin_num_clk=14, pin_num_dt=15)
    r.add_listener(callback)

    asyncio.create_task(heartbeat())
    while True:
        await event.wait()
        print('result =', r.value())
        event.clear()
Example #4
0
def set_mtime(check,max,x):
  if check==x: 
    r = RotaryIRQ(pin_num_clk=14, pin_num_dt=13, min_val=0, max_val=max, reverse=True, range_mode=RotaryIRQ.RANGE_BOUNDED)
  elif (check+1)==x: 
    r = RotaryIRQ(pin_num_clk=14, pin_num_dt=13, min_val=max, max_val=59, reverse=True, range_mode=RotaryIRQ.RANGE_BOUNDED)
  else:
    r = RotaryIRQ(pin_num_clk=14, pin_num_dt=13, min_val=0, max_val=59, reverse=True, range_mode=RotaryIRQ.RANGE_BOUNDED)
  lastval = r.value()
  while True:
    val = r.value() 
    if lastval != val:
      lastval = val
      lcd.move_to(0,1)
      lcd.putstr("")
      lcd.putchar(chr(62))
      if x<10 and val<10:
        lcd.putstr("        0%d:0%d " %(x,val))
      elif x<10 and val>9:
        lcd.putstr("        0%d:%d " %(x,val))   
      elif x>9 and val<10:
        lcd.putstr("        %d:0%d " %(x,val))           
      else:
        lcd.putstr("        %d:%d " %(x,val)) 
    if sw.value()==0:
      return val
Example #5
0
class RotaryEncoder(object):
    def __init__(self, pin_clk, pin_dt, delay=100, cw=None, ccw=None):
        self._rotary = RotaryIRQ(pin_clk, pin_dt)
        self._delay = delay

        self._cb_cw = cw
        self._cb_ccw = ccw

        loop = asyncio.get_event_loop()
        loop.create_task(self.check())

    async def check(self):
        old_value = 0

        while True:
            new_value = self._rotary.value()
            difference = abs(new_value - old_value)

            if new_value > old_value and callable(self._cb_ccw):
                self._cb_ccw(difference)
            elif old_value > new_value and callable(self._cb_cw):
                self._cb_cw(difference)

            old_value = new_value

            await asyncio.sleep_ms(self._delay)
def setup(temps, sm):
    i2c = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(21))

    lcd = I2cLcd(i2c, 39, 2, 16)
    lcd.clear()

    r = RotaryIRQ(18, 19, 0, 10, False)

    menu = ep_lcd_menu.menu_rot_enc(menu_config_file="menu.json",
                                    display_type="1602",
                                    display=lcd,
                                    rotary=r,
                                    button_pin=5)

    menu.display_funcs = {
        "print_T_Oven":
        lambda: "{:.2f} C".format(temps("T_Oven")),
        "print_T_TankU":
        lambda: "{:.2f} C".format(temps("T_TankU")),
        "print_T_TankL":
        lambda: "{:.2f} C".format(temps("T_TankL")),
        "print_state":
        lambda: "{}".format(sm.state),
        "print_cpu_temp":
        lambda: "{:.2f} C".format((esp32.raw_temperature() - 32) * 5 / 9),
        "print_ram":
        lambda: "{:.1f}/{:.1f}kB".format(gc.mem_free() / 1024, (gc.mem_alloc(
        ) + gc.mem_free()) / 1024),
    }

    menu.load()
    menu.render()
    return menu
Example #7
0
def set_htime():
  r = RotaryIRQ(pin_num_clk=14, pin_num_dt=13, min_val=0, max_val=23, reverse=True, range_mode=RotaryIRQ.RANGE_BOUNDED)
  lastval = r.value()
  while True:
    val = r.value() 
    if lastval != val:
      lastval = val
      lcd.move_to(0,1)
      lcd.putstr("")
      lcd.putchar(chr(62))
      if val<10:
        lcd.putstr("        0%d:00 " %val)
      else:
        lcd.putstr("        %d:00 " %val)
    if sw.value()==0:
      x=val
      return x
 def __init__(self):
     self.rotary_encoder = RotaryIRQ(pin_num_clk=0,
                                     pin_num_dt=4,
                                     min_val=-50,
                                     max_val=50,
                                     reverse=False,
                                     range_mode=RotaryIRQ.RANGE_BOUNDED)
     self.rotary_switch = Pin(32, Pin.IN, Pin.PULL_UP)
Example #9
0
 def __init__(self):
     """Init"""
     machine.WDT(True)
     self.tft = self.initDisplay()
     self.tft.clear()
     self.encoder_state_machine = RotaryIRQ(25,
                                            26,
                                            min_val=0,
                                            max_val=2,
                                            reverse=True,
                                            range_mode=Rotary.RANGE_WRAP)
     self.encoder_grinder_time = None
     self.run = True
     self.update_display = True
     self.print_s = 0.0
     self.encoder_value = 0
     self.state = 0
     self.state_old = 0
     self.edit_state = False
     self.cup = Cup()
     self.single_sec = machine.nvs_getint("single_sec")
     self.double_sec = machine.nvs_getint("double_sec")
     self.cps = machine.nvs_getint("cps")
     self.seconds = 0.1
     self.edit_cps = False
     self.pin_start = machine.Pin(33,
                                  mode=machine.Pin.IN,
                                  pull=machine.Pin.PULL_DOWN,
                                  handler=self.__startGrinding,
                                  trigger=machine.Pin.IRQ_HILEVEL,
                                  acttime=0,
                                  debounce=500000)
     self.pin_menu = machine.Pin(27,
                                 mode=machine.Pin.IN,
                                 pull=machine.Pin.PULL_DOWN,
                                 handler=self.setCPS,
                                 trigger=machine.Pin.IRQ_FALLING,
                                 acttime=0,
                                 debounce=500000)
     self.pin_out = machine.Pin(32, mode=machine.Pin.INOUT)
     self.pin_out.value(False)
Example #10
0
async def main():
    rotary_encoder_1 = RotaryIRQ(pin_num_clk=14,
                                 pin_num_dt=15,
                                 min_val=0,
                                 max_val=5,
                                 reverse=False,
                                 range_mode=RotaryIRQ.RANGE_WRAP)

    rotary_encoder_2 = RotaryIRQ(pin_num_clk=32,
                                 pin_num_dt=33,
                                 min_val=0,
                                 max_val=20,
                                 reverse=False,
                                 range_mode=RotaryIRQ.RANGE_WRAP)

    # create tasks that use the rotary encoders
    app1 = Application1(rotary_encoder_1)
    app2 = Application2(rotary_encoder_1, rotary_encoder_2)

    # keep the event loop active
    while True:
        await asyncio.sleep_ms(10)
Example #11
0
def setup():
    i2c = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(21))

    lcd = I2cLcd(i2c, 39, 2, 16)
    lcd.clear()

    r = RotaryIRQ(18, 19, 0, 10, False)

    menu = ep_lcd_menu.menu_rot_enc(menu_config_file="menu.json",
                                    display_type="1602",
                                    display=lcd,
                                    rotary=r,
                                    button_pin=5)

    menu.load()
    menu.render()
    return menu
Example #12
0
class Controller():
    _enc = RotaryIRQ(PIN_ENC1, PIN_ENC2)
    _but = Pin(PIN_BUTTON, Pin.IN)
    _pressed = False

    @classmethod
    def get_key(cls):

        # Next / previous
        count = cls._enc.value()
        if count != 0:
            cls._enc.reset()
            return KEY_NEXT if count > 0 else KEY_PREV, abs(count)

        # Enter
        if cls._but.value() == 0 and not cls._pressed:
            cls._pressed = True
            return KEY_ENTER, count
        if cls._but.value() and cls._pressed:
            cls._pressed = False

        return False, count
Example #13
0
sdist_i = [20, 31, 40, 52, 81, 96, 113, 123]
pxc = [20, 31, 52, 81, 96, 113, 123]
rad_i = [5, 7, 10, 13, 20, 24, 28, 30]

oled.fill(0)
display1.fill(0)
display2.fill(0)

oled.show()
display1.show()
display2.show()

# define rotary variables
r = RotaryIRQ(pin_num_clk=14,
              pin_num_dt=13,
              min_val=0,
              max_val=len(names) - 1,
              reverse=True,
              range_mode=RotaryIRQ.RANGE_WRAP)

lastval = r.value()

simple_cron.run()
# orbitTracker_all needs to be cached 1/day
simple_cron.add('Daily',
                lambda *a, **k: orbit_loc_all(),
                hours=12,
                minutes=0,
                seconds=0)

#define starfield screensaver variables
stars = 500
Example #14
0
from rotary_irq_esp import RotaryIRQ
import math

LED_OUT_GPIO = 2

pin = Pin(LED_OUT_GPIO, Pin.OUT)
#signal = Signal(LED_OUT_GPIO, Pin.OUT, invert=True)
pwm0 = PWM(Pin(LED_OUT_GPIO))  # create PWM object from a pin
pwm0.freq(100)  # set frequency
pwm0.duty(0)  # set duty cycle

r = RotaryIRQ(
    pin_num_clk=4,
    pin_num_dt=0,
    min_val=0,
    max_val=33,
    reverse=True,
    range_mode=RotaryIRQ.RANGE_BOUNDED
    #              range_mode=RotaryIRQ.RANGE_UNBOUNDED
    #              range_mode=RotaryIRQ.RANGE_WRAP
)


def start():
    val_old = r.value()

    while True:
        val_new = r.value()

        if val_old != val_new:
            val_old = val_new
Example #15
0
# from machine import Pin
# from neopixel import NeoPixel

import time
from rotary_irq_esp import RotaryIRQ

r = RotaryIRQ(pin_num_clk=2, 
              pin_num_dt=0, 
              min_val=0, 
              max_val=100, 
              reverse=True, 
              range_mode=RotaryIRQ.RANGE_BOUNDED)



val_old = r.value()
while True:
    val_new = r.value()
    
    if val_old != val_new:
        val_old = val_new
        print('result =', val_new)
        
    time.sleep_ms(50)





# NEOPIXEL
# pixelCount = 16
Example #16
0
d = dht.DHT22(Pin(13))
nuevo_sp = 0
ventilador = 0
histeresis = 2
rele = Pin(16, Pin.OUT, value=1)

f = open("setpoint.dat", "r")
setpoint = int(f.read())
f.close()

#gpio12 == D6 NodeMCU
#gpio14 == D5 NodeMCU
r = RotaryIRQ(pin_num_clk=12,
              pin_num_dt=14,
              min_val=0,
              max_val=50,
              reverse=False,
              range_mode=RotaryIRQ.RANGE_WRAP)
r.set(value=setpoint)

disp_SP = setpoint
y_SP = 28
y_vent = 39
y_wifi = 51
oled.text("Set Point:", 0, y_SP)
oled.text(str(setpoint), 112, y_SP)
oled.text("Ventilador:   NO", 0, y_vent)
if wlan.isconnected():
    oled.text("WiFi: " + wlan.config('essid'), 0, y_wifi)
    nic = wlan.config('mac')
    mac = ""
Example #17
0
# The MIT License (MIT)
# Copyright (c) 2019 Mike Teachman
# https://opensource.org/licenses/MIT

# example for MicroPython rotary encoder
#
# Documentation:
#   https://github.com/MikeTeachman/micropython-rotary

import time
from rotary_irq_esp import RotaryIRQ

r = RotaryIRQ(pin_num_clk=14,
              pin_num_dt=13,
              min_val=0,
              max_val=5,
              reverse=False,
              range_mode=RotaryIRQ.RANGE_WRAP)

lastval = r.value()
while True:
    val = r.value()

    if lastval != val:
        lastval = val
        print('result =', val)

    time.sleep_ms(50)
Example #18
0
async def rotary_change_timer():
    global rotary, rotary_sw, rotary_press_count, val_old, val_new, countdown_timer, arr_t
    rotary = RotaryIRQ(pin_num_clk=36,
                       pin_num_dt=39,
                       min_val=0,
                       max_val=9,
                       reverse=False,
                       range_mode=RotaryIRQ.RANGE_WRAP)

    val_old = rotary.value()
    rotary_press_count = 0
    oled.fill(0)  #清屏
    oled.draw_chinese('新定时间', 0, 0)
    #白色线,1
    oled.hline(0, 30, 128, 1)
    #每个占16高度,最大64/16=4
    oled.draw_chinese('原定时间', 0, 2)
    oled.text(str("{:.0f}".format(float(countdown_timer))), 70, 40)
    oled.text('min', 96, 40)
    oled.text(':', 78, 6)
    while True:
        val_new = rotary.value()
        #如果旋转编码器按钮被按下,计数器加1
        rotary_sw.close_func(count_add)
        if val_old != val_new:
            #arr用来存储setpoint的高位,低位,小数点后的位数
            #asyncio.run(sleep_time())
            #最高设置温度99.9.最低0.0
            #计数,如果按动次数被3除余数0,光标在十位数,修改该位数值,下同
            if rotary_press_count == 0:
                #把矩形区域充0,先用oled.fill(0) 代替
                #消除三角形
                oled.draw_all(0x03, 8, 8, 70, 16)
                oled.draw_all(0x03, 8, 8, 86, 16)
                oled.draw_all(0x03, 8, 8, 94, 16)
                oled.draw_all(0x03, 8, 8, 70, 6)
                oled.draw_all(0x02, 8, 8, 70, 16)
                #val_new旋转编码器读数
                arr_t[0] = val_new

            #计数,如果按动次数被3除余数1,光标在个位数
            elif rotary_press_count == 1:
                oled.draw_all(0x03, 8, 8, 70, 16)
                oled.draw_all(0x03, 8, 8, 86, 16)
                oled.draw_all(0x03, 8, 8, 94, 16)
                oled.draw_all(0x03, 8, 8, 86, 6)
                oled.draw_all(0x02, 8, 8, 86, 16)
                if val_new > 6:
                    val_new = 0
                arr_t[1] = val_new

            #计数,如果按动次数被3除余数2,光标在小数点后第一位
            elif rotary_press_count == 2:
                oled.draw_all(0x03, 8, 8, 70, 16)
                oled.draw_all(0x03, 8, 8, 86, 16)
                oled.draw_all(0x03, 8, 8, 94, 16)
                oled.draw_all(0x03, 8, 8, 94, 6)
                oled.draw_all(0x02, 8, 8, 94, 16)
                arr_t[2] = val_new
        if rotary_press_count == 3:
            #会执行两遍,不知道原因
            countdown_timer = arr_t[0] * 60 + arr_t[1] * 10 + arr_t[2]
            break
            val_old = val_new
        oled.text(str(arr_t[0]), 70, 6)
        oled.text(str(arr_t[1]), 86, 6)
        oled.text(str(arr_t[2]), 94, 6)
        oled.show()
        await asyncio.sleep_ms(60)
Example #19
0
#Credit:
#Forked from miketeachman/micropython-rotary
#https://github.com/miketeachman/micropython-rotary.git

import time
from rotary_irq_esp import RotaryIRQ

r = RotaryIRQ(pin_num_clk=12,
              pin_num_dt=13,
              min_val=0,
              max_val=99,
              reverse=True,
              range_mode=RotaryIRQ.RANGE_WRAP)

lastval = r.value()
while True:
    val = r.value()

    if lastval != val:
        lastval = val
        print('result =', val)

    time.sleep_ms(20)
if sys.platform == 'esp8266' or sys.platform == 'esp32':
    from rotary_irq_esp import RotaryIRQ
elif sys.platform == 'pyboard':
    from rotary_irq_pyb import RotaryIRQ
    print('found pyboard')
elif sys.platform == 'rp2':
    from rotary_irq_rp2 import RotaryIRQ
    print('found Raspberry Pico')
else:
    print('Warning:  The Rotary module has not been tested on this platform')

import time


r = RotaryIRQ(pin_num_clk=17,
              pin_num_dt=16,
              min_val=0,
              max_val=10,
              reverse=True,
              range_mode=RotaryIRQ.RANGE_WRAP)

val_old = r.value()
while True:
    val_new = r.value()

    if val_old != val_new:
        val_old = val_new
        print('result =', val_new)

    time.sleep_ms(50)
Example #21
0
start_sw = Switch(start_pin)
timer_pin = Pin(21, Pin.IN, Pin.PULL_UP)
timer_sw = Switch(timer_pin)
temp_pin = Pin(22, Pin.IN, Pin.PULL_UP)
temp_sw = Switch(temp_pin)
menu_pin = Pin(4, Pin.IN, Pin.PULL_UP)
menu_sw = Switch(menu_pin)
#旋转编码器按钮
rotary_btn_pin = Pin(34, Pin.IN, Pin.PULL_UP)
rotary_sw = Switch(rotary_btn_pin)
#旋转编码器按钮按动次数计数器
rotary_press_count = 0
#旋转编码器
rotary = RotaryIRQ(pin_num_clk=36,
                   pin_num_dt=39,
                   min_val=0,
                   max_val=9,
                   reverse=False,
                   range_mode=RotaryIRQ.RANGE_WRAP)

#initial spi oled,miso与字库共用,都写成gpio 19。 res没引出,设为3,否则oled实例化失败
spi = SPI(2,
          baudrate=8000000,
          polarity=0,
          phase=0,
          sck=Pin(14),
          mosi=Pin(13),
          miso=Pin(12))
oled = SH1106_SPI(128, 64, spi, dc=Pin(25), res=Pin(16), cs=Pin(15))

#显示中文
#oled.draw_chinese('我',0,0)
Example #22
0
async def rotary_change_temp():
    global rotary, rotary_sw, rotary_press_count, val_old, val_new, setpoint, arr, new_setpoint
    rotary = RotaryIRQ(pin_num_clk=36,
                       pin_num_dt=39,
                       min_val=0,
                       max_val=9,
                       reverse=False,
                       range_mode=RotaryIRQ.RANGE_WRAP)

    val_old = rotary.value()
    rotary_press_count = 0
    oled.fill(0)  #清屏
    oled.draw_chinese('新定温度', 0, 0)
    #白色线,1
    oled.hline(0, 30, 128, 1)
    #每个占16高度,最大64/16=4
    oled.draw_chinese('原定温度', 0, 2)
    oled.text(str("{:.2f}".format(float(setpoint))), 70, 40)
    #oled.text('.',86,6)
    #import framebuf
    #buffer = bytearray(34 * 22 // 8)        #开辟56*8像素空间
    #framebufnew = framebuf.FrameBuffer(buffer, 34, 22, framebuf.MVLSB) #创建新的framebuffer对象

    while True:
        val_new = rotary.value()
        #如果旋转编码器按钮被按下,计数器加1
        rotary_sw.close_func(count_add)
        if val_old != val_new:

            #清屏
            #arr用来存储setpoint的高位,低位,小数点后的位数
            #asyncio.run(sleep_time())
            #最高设置温度99.9.最低0.0
            #计数,如果按动次数被3除余数0,光标在十位数,修改该位数值,下同
            if rotary_press_count % 3 == 0:
                #把矩形区域充0,先用oled.fill(0) 代替
                #消除三角形
                '''
                oled.draw_all(0x03,8,8,70,16)
                oled.draw_all(0x03,8,8,78,16)
                oled.draw_all(0x03,8,8,94,16)
                '''
                #framebufnew.fill(0)  #清屏
                #oled.draw_all(0x04,32,18,70,16)
                oled.draw_all(0x02, 8, 8, 70, 16)
                #val_new旋转编码器读数
                arr[0] = val_new

            #计数,如果按动次数被3除余数1,光标在个位数
            elif rotary_press_count % 3 == 1:
                '''
                oled.draw_all(0x03,8,8,70,16)
                oled.draw_all(0x03,8,8,78,16)
                oled.draw_all(0x03,8,8,94,16)
                oled.draw_all(0x03,8,8,78,6)
                oled.draw_all(0x02,8,8,78,16)
                '''
                #framebufnew.fill(0)  #清屏
                oled.draw_all(0x04, 32, 18, 70, 16)
                oled.draw_all(0x02, 8, 8, 78, 16)
                arr[1] = val_new

            #计数,如果按动次数被3除余数2,光标在小数点后第一位
            elif rotary_press_count % 3 == 2:
                '''
                #清除
                oled.draw_all(0x03,8,8,70,16)
                oled.draw_all(0x03,8,8,78,16)
                oled.draw_all(0x03,8,8,94,16)
                oled.draw_all(0x03,8,8,94,6)
                oled.draw_all(0x02,8,8,94,16)
                '''
                #framebufnew.fill(0)  #清屏
                oled.draw_all(0x04, 32, 18, 70, 16)
                oled.draw_all(0x02, 8, 8, 94, 16)
                arr[2] = val_new
            val_old = val_new

        #setpoint=arr[0]*10+arr[1]+arr[2]*0.1
        '''
        framebufnew.text(str(arr[0]), 0, 0)      #新的framebuffer输入字符串
        framebufnew.text(str(arr[1]), 8, 0)
        framebufnew.text('.',16,0) 
        framebufnew.text(str(arr[2]), 24, 0)
        oled.blit(framebufnew, 70, 6)           #新的frambuffer起始坐标
        '''
        oled.text(str(arr[0]), 70, 6)
        oled.text(str(arr[1]), 78, 6)
        oled.text(str(arr[2]), 94, 6)
        oled.text('.', 86, 6)
        #'''
        oled.show()
        await asyncio.sleep_ms(800)
Example #23
0
class CoffeeGrinder:
    """CoffeeGrinder Class"""
    CPS_DEFAULT = 167

    def __init__(self):
        """Init"""
        machine.WDT(True)
        self.tft = self.initDisplay()
        self.tft.clear()
        self.encoder_state_machine = RotaryIRQ(25,
                                               26,
                                               min_val=0,
                                               max_val=2,
                                               reverse=True,
                                               range_mode=Rotary.RANGE_WRAP)
        self.encoder_grinder_time = None
        self.run = True
        self.update_display = True
        self.print_s = 0.0
        self.encoder_value = 0
        self.state = 0
        self.state_old = 0
        self.edit_state = False
        self.cup = Cup()
        self.single_sec = machine.nvs_getint("single_sec")
        self.double_sec = machine.nvs_getint("double_sec")
        self.cps = machine.nvs_getint("cps")
        self.seconds = 0.1
        self.edit_cps = False
        self.pin_start = machine.Pin(33,
                                     mode=machine.Pin.IN,
                                     pull=machine.Pin.PULL_DOWN,
                                     handler=self.__startGrinding,
                                     trigger=machine.Pin.IRQ_HILEVEL,
                                     acttime=0,
                                     debounce=500000)
        self.pin_menu = machine.Pin(27,
                                    mode=machine.Pin.IN,
                                    pull=machine.Pin.PULL_DOWN,
                                    handler=self.setCPS,
                                    trigger=machine.Pin.IRQ_FALLING,
                                    acttime=0,
                                    debounce=500000)
        self.pin_out = machine.Pin(32, mode=machine.Pin.INOUT)
        self.pin_out.value(False)

    @staticmethod
    def initDisplay():
        """initialize the display"""
        tft = display.TFT()
        tft.init(tft.ST7789,
                 rst_pin=23,
                 backl_pin=4,
                 miso=0,
                 mosi=19,
                 clk=18,
                 cs=5,
                 dc=16,
                 width=235,
                 height=340,
                 backl_on=1)

        tft.font(tft.FONT_DejaVu18)

        # invert colors
        tft.tft_writecmd(0x21)

        # set orientation (optional)
        tft.orient(tft.PORTRAIT_FLIP)

        # set window size
        tft.setwin(52, 40, 188, 280)
        # x, y -> x2, y2
        tft.rect(0, 0, 135, 240, 0xFFFFFF)
        return tft

    def __textWrapper(self, x, y, text, color=0xFFFFFF):
        """Function to warp text"""
        self.tft.text(x - self.__textCenterOffset(text),
                      y - self.__textFontSizeOffset(),
                      text,
                      color=color)

    def __initText(self):
        """Init Text"""
        text = "Initialize"
        self.__textWrapper(67, 110, text)
        text = "Coffegrinder"
        self.__textWrapper(67, 130, text)
        time.sleep(4)

    def __textCenterOffset(self, text):
        """Center offset"""
        return int(self.tft.textWidth(text) / 2)

    def __textFontSizeOffset(self):
        """Fontsize offset"""
        return int(self.tft.fontSize()[1] / 2)

    def __showCoffeData(self):
        """Show Display Data"""
        self.update_display = True
        color = 0xFFFFFF
        if self.edit_state:
            color = 0xFF0000
        text_s = "Timer: {} \r".format(round(self.print_s, 2))
        if self.print_s < 10:
            text_s = "Timer:   {} \r".format(round(self.print_s, 2))
        qty = round(self.print_s * self.cps, 1)
        text_g = "QTY: {} g\r".format(qty)
        if qty < 10:
            text_g = "QTY:   {} g\r".format(qty)
        self.tft.textClear(67, 200, text_s, color)
        if self.state != 2:
            self.__textWrapper(67, 200, text_s, color)
            self.__textWrapper(67, 225, text_g, color)

    def __stateSingeleShot(self):
        """Single shot"""
        self.pin_start = machine.Pin(33,
                                     mode=machine.Pin.IN,
                                     pull=machine.Pin.PULL_DOWN,
                                     handler=self.__startGrinding,
                                     trigger=machine.Pin.IRQ_HILEVEL,
                                     acttime=0,
                                     debounce=500000)
        self.update_display = True
        self.tft.clear()
        self.cup.oneCup(self.tft, 57, 90)
        text = "Single Shot!"
        self.__textWrapper(67, 30, text)
        self.print_s = self.single_sec
        self.run = False

    def __stateDoubleShot(self):
        """Double Shot"""
        self.pin_start = machine.Pin(33,
                                     mode=machine.Pin.IN,
                                     pull=machine.Pin.PULL_DOWN,
                                     handler=self.__startGrinding,
                                     trigger=machine.Pin.IRQ_HILEVEL,
                                     acttime=0,
                                     debounce=500000)
        self.update_display = True
        self.tft.clear()
        self.cup.oneCup(self.tft, 27, 90)
        self.cup.oneCup(self.tft, 87, 90)
        text = "Double Shot!"
        self.__textWrapper(67, 30, text)
        self.print_s = self.double_sec
        self.run = False

    def __stateEndlessShot(self):
        """Endless"""
        self.pin_start = machine.Pin(33,
                                     mode=machine.Pin.IN,
                                     pull=machine.Pin.PULL_DOWN,
                                     handler=self.__startGrinding,
                                     trigger=machine.Pin.IRQ_HILEVEL,
                                     acttime=0,
                                     debounce=500000)
        self.update_display = True
        self.tft.clear()
        self.cup.endLess(self.tft, 68, 110, 20)
        text = "Endless!"
        self.__textWrapper(67, 30, text)
        self.run = False

    def __startGrinding(self, pin):
        """Interrupt routine for grinder start"""
        if self.edit_state:
            return
        self.pin_start.init(trigger=machine.Pin.IRQ_DISABLE)
        self.pin_menu.init(trigger=machine.Pin.IRQ_DISABLE)
        time.sleep(0.1)
        if not self.pin_start.value():
            self.pin_menu.init(trigger=machine.Pin.IRQ_FALLING)
            self.pin_start.init(trigger=machine.Pin.IRQ_HILEVEL)
            return
        self.pin_out.value(True)
        if self.state != 2:
            sleep = self.print_s
            while sleep > 0:
                text = "Seconds: {}".format(round(sleep, 2))
                self.__textWrapper(67, 200, text, 0xec7d15)
                sleep -= 0.1
                time.sleep(0.1)
        else:
            text = "Grind!"
            self.__textWrapper(67, 200, text)
            count = 0.2
            time.sleep(0.2)
            while self.pin_start.value():
                qty = round(count * self.cps, 1)
                text_g = "QTY: {} g".format(qty)
                if qty < 10:
                    text_g = "QTY:   {} g\r".format(qty)
                self.__textWrapper(67, 225, text_g)
                count += 0.1
                time.sleep(0.1)
            self.__textWrapper(67, 200, "\r             ")
        self.pin_out.value(False)
        print(self.pin_out.value())
        self.update_display = True
        time.sleep(1)
        self.pin_menu.init(trigger=machine.Pin.IRQ_FALLING)
        self.pin_start.init(trigger=machine.Pin.IRQ_HILEVEL)

    def __setCoffeGrindTime(self, pin):
        """Interrupt routine for set timer"""
        self.update_display = True
        if self.state == 0:
            self.single_sec = self.seconds / 10
            self.print_s = self.single_sec
            machine.nvs_setint("single_sec", int(self.seconds))
        elif self.state == 1:
            self.double_sec = self.seconds / 10
            self.print_s = self.double_sec
            machine.nvs_setint("double_sec", int(self.seconds))

    def switchState(self, pin):
        """Switch state on button press"""
        self.pin_menu.init(trigger=machine.Pin.IRQ_DISABLE)
        self.update_display = True
        if self.state == 2:
            self.edit_state = False
            self.pin_menu.init(trigger=machine.Pin.IRQ_FALLING)
            return
        if self.edit_state:
            self.edit_state = False
        elif not self.edit_state:
            self.edit_state = True

        if self.edit_state:
            value = 0.1
            if self.state_old == 0:
                value = self.single_sec
            elif self.state_old == 1:
                value = self.double_sec
            value *= 10
            self.encoder_state_machine.set(value=value,
                                           min_val=1,
                                           max_val=120,
                                           range_mode=Rotary.RANGE_WRAP)
        else:
            self.encoder_state_machine.set(value=self.state_old,
                                           min_val=0,
                                           max_val=2,
                                           range_mode=Rotary.RANGE_WRAP)
        self.pin_menu.init(trigger=machine.Pin.IRQ_FALLING)

    def setCPS(self, pin):
        self.pin_menu.init(trigger=machine.Pin.IRQ_DISABLE)
        self.edit_cps = True

    def editCPS(self):
        self.encoder_state_machine.set(value=self.cps * 10,
                                       min_val=100,
                                       max_val=200,
                                       range_mode=Rotary.RANGE_WRAP)
        self.tft.clear()
        text = "Set CPS"
        self.__textWrapper(67, 110, text)
        time.sleep(1.0)
        while True:
            self.cps = self.encoder_value / 100
            text = "CPS:   {}\r".format(round(self.cps, 2))
            self.__textWrapper(67, 130, text, 0xec7d15)
            if not self.pin_menu.value():
                print(self.pin_menu.value())
                break
            time.sleep(0.1)
        machine.nvs_setint("cps", int(self.cps * 100))
        self.encoder_state_machine.set(value=0,
                                       min_val=0,
                                       max_val=2,
                                       range_mode=Rotary.RANGE_WRAP)
        self.tft.clear()
        self.edit_cps = False
        self.pin_menu.init(trigger=machine.Pin.IRQ_FALLING,
                           handler=self.switchState)

    def __getEncoderValue(self):
        """Thread for fast polling encoder value"""
        while True:
            ntf = _thread.wait(0)
            if ntf == _thread.EXIT:
                # Terminate the thread
                return
            self.encoder_value = self.encoder_state_machine.value()
            time.sleep(0.001)

    def __shotState(self):
        """Thread for checking states"""
        self.state_old = self.encoder_value
        while True:
            ntf = _thread.wait(50)
            if ntf == _thread.EXIT:
                # Terminate the thread
                return
            if not self.edit_state:
                self.state = self.encoder_value
                if self.state_old != self.state:
                    self.run = True
                    self.state_old = self.state
            else:
                self.seconds = self.encoder_value

    def runProgram(self):
        """Run Main Program"""

        if not self.single_sec:
            self.single_sec = 1
        self.single_sec /= 10

        if not self.double_sec:
            self.double_sec = 1
        self.double_sec /= 10

        if not self.cps:
            self.cps = self.CPS_DEFAULT
        self.cps /= 100

        self.tft.set_fg(0x000000)

        self.shot_state_th = _thread.start_new_thread("Shot_state",
                                                      self.__shotState, ())
        _thread.start_new_thread("t", self.__getEncoderValue, ())
        self.__initText()
        if self.edit_cps:
            self.editCPS()
        self.pin_menu.init(trigger=machine.Pin.IRQ_FALLING,
                           handler=self.switchState)
        # self.__stateSingeleShot()
        self.state = 0
        self.run = True
        while True:
            if self.state == 0 and self.run:
                self.__stateSingeleShot()
            elif self.state == 1 and self.run:
                self.__stateDoubleShot()
            elif self.state == 2 and self.run:
                self.__stateEndlessShot()
            if self.edit_state:
                self.__setCoffeGrindTime(1)
            if self.update_display:
                self.__showCoffeData()
                self.update_display = False
            time.sleep(0.1)
Example #24
0
# https://opensource.org/licenses/MIT

# example for MicroPython rotary encoder

import sys
if sys.platform == 'esp8266' or sys.platform == 'esp32':
    from rotary_irq_esp import RotaryIRQ
elif sys.platform == 'pyboard':
    from rotary_irq_pyb import RotaryIRQ
else:
    print('Warning:  The Rotary module has not been tested on this platform')

import time

r = RotaryIRQ(pin_num_clk=14,
              pin_num_dt=15,
              min_val=0,
              max_val=5,
              reverse=False,
              range_mode=RotaryIRQ.RANGE_WRAP)

val_old = r.value()
while True:
    val_new = r.value()

    if val_old != val_new:
        val_old = val_new
        print('result =', val_new)

    time.sleep_ms(50)
Example #25
0
import tm1637
from machine import Pin
import time

tm = tm1637.TM1637(clk=Pin(5), dio=Pin(4))

button = Pin(16, Pin.IN, Pin.PULL_UP)
led = Pin(17, Pin.OUT)


# Rotary encoder
from rotary_irq_esp import RotaryIRQ
r = RotaryIRQ(
    pin_num_clk=14,
    pin_num_dt=12,
    min_val=0,
    max_val=200,
    range_mode=RotaryIRQ.RANGE_BOUNDED
)

microwave_on = False

while True:
    if microwave_on == False:
        cur_val = r.value()
    minutes = int(cur_val/60)
    seconds = cur_val%60
    tm.numbers(minutes,seconds)
    time.sleep(.2)

    if button.value() == 0: