def test(): import machine, display, time, math, network, utime print("Testing Display") tft = display.TFT() tft.init(tft.ST7789,bgr=True,rot=tft.LANDSCAPE, miso=17,backl_pin=4,backl_on=1, mosi=19, clk=18, cs=5, dc=16) tft.setwin(40,52,320,240) tft.set_bg(tft.WHITE) tft.clear() text="Welcome to ODF-Nanoleaf" tft.text(120-int(tft.textWidth(text)/2),10,text,tft.BLACK) from machine import TouchPad, Pin tIn2 = TouchPad(Pin(2)) tIn2.config(1000) while True: tIn2Touch = tIn2.read() if (tIn2Touch < 1007): tIn2TouchYN = True else: tIn2TouchYN = False print(tIn2TouchYN) if tIn2TouchYN: text="Touch Detected - Start LEDs" tft.text(120-int(tft.textWidth(text)/2),67-int(tft.fontSize()[1]/2+tft.fontSize()[1]+10),text,tft.BLACK) break time.sleep(1)
def __init__(self, pin, on_pressed, threshold=400, debounce_ms=50): self._touchpad = TouchPad(pin) self._on_pressed = on_pressed self._threshold = threshold self._debounce_ms = debounce_ms self._down_ms = None self._pressed = False
class Plugin(plugin.PluginProto): PLUGIN_ID = 97 PLUGIN_NAME = "Input - ESP32 Touch" PLUGIN_VALUENAME1 = "Touch" def __init__(self, taskindex): # general init plugin.PluginProto.__init__(self, taskindex) self.dtype = pglobals.DEVICE_TYPE_SINGLE self.vtype = pglobals.SENSOR_TYPE_SWITCH self.pinfilter[0] = 4 self.valuecount = 1 self.senddataoption = True self.timeroption = True self.timeroptional = True self.inverselogicoption = True self.recdataoption = False self._pin = None self.refvalue = 1500 def plugin_init(self, enableplugin=None): plugin.PluginProto.plugin_init(self, enableplugin) self.decimals[0] = 0 self.initialized = False self.timer100ms = False if int(self.taskdevicepin[0]) >= 0 and self.enabled: try: self._pin = TouchPad(Pin(int(self.taskdevicepin[0]))) self.refvalue = int( self._pin.read() / 2 ) # get value at startup, hope that it is in non-touched state, for reference self._pin.config(200) self.timer100ms = True self.initialized = True misc.addLog(pglobals.LOG_LEVEL_DEBUG, "Touch init, ref: " + str(self.refvalue)) except Exception as e: misc.addLog(pglobals.LOG_LEVEL_ERROR, "Touch config failed " + str(e)) def plugin_read(self): result = False if self.initialized: self.set_value(1, int(float(self.uservar[0])), True) # return with saved value self._lastdataservetime = utime.ticks_ms() # compat result = True return result def timer_ten_per_second(self): if self.initialized and self.enabled: prevval = int(float(self.uservar[0])) if ( self._pin.read() < self.refvalue ): # touch value read by 10 times per sec, report if change occures aval = 1 else: aval = 0 if prevval != aval: self.set_value(1, int(aval), True) self._lastdataservetime = utime.ticks_ms() # compat
def __init__(self): freq(160000000) self._i2c = I2C(scl=Pin(22), sda=Pin(21), freq=100000) self._bme = bme280_float.BME280(i2c=self._i2c) self._adc = ADC(Pin(37)) self._lis3dh = LIS3DH_I2C(self._i2c, address=0x19, int1=Pin(15)) self._lis3dh.set_tap(tap=1, threshold=10, time_limit=10, time_latency=20, time_window=255) self._touchPad = TouchPad(Pin(32)) self._blueled = Pin(4, Pin.OUT) self._blueled.off() self._mqttClient = None self._nb_leds = 4 self._clock_pin = 14 self._data_pin = 13 self._empty_pin = 12 self._spi = SPI(1, baudrate=10000000, sck=Pin(self._clock_pin), mosi=Pin(self._data_pin), miso=Pin(self._empty_pin)) self._leds = DotStar(self._spi, self._nb_leds) for i in range(0, self._nb_leds): self._leds[i] = (0, 0, 0) try: self._oled = ssd1306.SSD1306_I2C(128, 64, self._i2c, 0x3c) except Exception as e: self._oled = None print("Exception occurred when initializing OLED.") print("Exception: " + str(e))
def __init__(self, pin): self.__touch_pad = TouchPad(pin) self.__touch_pad.irq(self.__irq_handler) self.event_pressed = None self.event_released = None self.__pressed_count = 0 self.__was_pressed = False self.__value = 0
def __init__(self): self.wifi = None self.mqtt = None self.config = ujson.load(open("settings.json")) self.lighting = False self.pin = Pin(2, Pin.OUT) self.touchpad = TouchPad(Pin(13))
def read_touch(pins=(13, 12, 14, 27, 33, 32, 15, 4), sensitivity=600): r = {} for p in pins: t = TouchPad(Pin(p)) t.config(sensitivity) v = t.read() r[p] = v return r
def read(self): r = {} for p in self.pins: t = TouchPad(Pin(p)) t.config(self.sensitivity) v = t.read() r[p] = v return r
def touch(triglvl=300): """ triglvl - trigger level, value < triglvl decide touched """ from machine import TouchPad, Pin from LogicalPins import get_pin_on_platform_by_key t = TouchPad(Pin(get_pin_on_platform_by_key('touch_0'))) value = t.read() # Returns a smaller number when touched return {'isTouched': True if value < triglvl else False, 'value': value}
def run(): touch = TouchPad(Pin(TPIN)) np = neopixel.NeoPixel(Pin(13), 20, timing=1) #sw1 = Pin(23,Pin.IN,Pin.PULL_UP) #sw2 = Pin(22,Pin.IN,Pin.PULL_UP) while True: if touch.read() <= 800: light(np, 255, 255, 0) else: light(np, 0, 255, 0) #np.fill((0,0,0)) np.write()
def __init__(self, tpin): self.tpin = tpin self.touch5 = TouchPad(Pin(self.tpin)) self.threshold5 = [] # Scan each TouchPad 12 times for calibration for x in range(12): self.threshold5.append(self.touch5.read()) sleep(.1) # Store average threshold values self.threshold5 = sum(self.threshold5) / len(self.threshold5) print('Threshold5: {0}'.format(self.threshold5))
class TouchKey(Key): def __init__(self, pinNum, pinMode, name): super(TouchKey, self).__init__(pinNum, pinMode, name) self.touchPad = TouchPad(self.pin) def keyDown(self): threshold = 550 if self.touchPad.read() > threshold: self.pressed = False elif not self.pressed: time.sleep(0.02) if self.touchPad.read() <= threshold: self.pressed = True return True return False
def __init__(self, pin, press_cmd=None, hold_cmd=None, release_cmd=None, threshold=400, hold_time=2, hold_repeat_time=None, freq=10): if isinstance(pin, int): pin = Pin(pin) else: pin.init() self.tp = TouchPadBase(pin) self.press_cmd = press_cmd self.hold_cmd = hold_cmd self.release_cmd = release_cmd self.hold_time = int(hold_time * 1000) if hold_repeat_time is not None: self.hold_repeat_time_diff = int((hold_repeat_time * 1000) - self.hold_time) else: self.hold_repeat_time_diff = None self.threshold = threshold self.freq = freq self.is_active = self.tp.read() < self.threshold if self.is_active: self.pressed_timestamp = time.ticks_ms() else: self.pressed_timestamp = None loop = asyncio.get_event_loop() loop.create_task(self._handle_touch())
def is_touched(self): id = int(str(self)[4:-1]) if id in (0, 2, 4, 12, 13, 14, 15, 27, 32, 33): return (TouchPad(Pin(id)).read() - 150 < 0) else: self.init(Pin.IN) return self.value() == 1
class Touch: def __init__(self, pin): self.__touch_pad = TouchPad(pin) self.__touch_pad.irq(self.__irq_handler) self.event_pressed = None self.event_released = None self.__pressed_count = 0 self.__was_pressed = False self.__value = 0 def __irq_handler(self, value): # when pressed if value == 1: if self.event_pressed is not None: self.event_pressed(value) self.__was_pressed = True self.__value = 1 if (self.__pressed_count < 100): self.__pressed_count = self.__pressed_count + 1 # when released else: self.__value = 0 if self.event_released is not None: self.event_released(value) def config(self, threshold): self.__touch_pad.config(threshold) def is_pressed(self): if self.__value: return True else: return False def was_pressed(self): r = self.__was_pressed self.__was_pressed = False return r def get_presses(self): r = self.__pressed_count self.__pressed_count = 0 return r def read(self): return self.__touch_pad.read()
def __init__(self, touch_pins, threshold=400): self.touchpads = [TouchPad(Pin(pin)) for pin in touch_pins] self.threshold = threshold # self.cur_time = time.ticks_ms self.debounce_ms = 75 # cur_time = self.cur_time() self.was_touched = bytearray(len(touch_pins))
def __init__(self, ios=[0], thr=0.05): self.ts = [TouchPad(Pin(p)) for p in ios] # values without touching cals = [t.read() for t in self.ts] # thresholds (considered as touched when below that value) self.thrs = [int(c * (1 - thr)) for c in cals] self.states = [False] * len(ios) self.states_ = [False] * len(ios) self.cbs = [None] * len(ios)
def plugin_init(self, enableplugin=None): plugin.PluginProto.plugin_init(self, enableplugin) self.decimals[0] = 0 self.initialized = False self.timer100ms = False if int(self.taskdevicepin[0]) >= 0 and self.enabled: try: self._pin = TouchPad(Pin(int(self.taskdevicepin[0]))) self.refvalue = int( self._pin.read() / 2 ) # get value at startup, hope that it is in non-touched state, for reference self._pin.config(200) self.timer100ms = True self.initialized = True misc.addLog(pglobals.LOG_LEVEL_DEBUG, "Touch init, ref: " + str(self.refvalue)) except Exception as e: misc.addLog(pglobals.LOG_LEVEL_ERROR, "Touch config failed " + str(e))
def touch_pins_check(touch_pins): global touch_okay if touch_pins and touch_okay: touched_pins = 0 try: for touch_pin in touch_pins: try: TouchPad(Pin(touch_pin)).read() except Exception: print("### Main: Touch calibration issue on GPIO: " + str(touch_pin)) if TouchPad(Pin( touch_pin)).read() < 200: # TODO: Fix literal "200" touched_pins += 1 except Exception: touch_okay = False if touched_pins == len(touch_pins): return True return False
class ESPTOUCHSW(): def __init__(self, tpin): self.tpin = tpin self.touch5 = TouchPad(Pin(self.tpin)) self.threshold5 = [] # Scan each TouchPad 12 times for calibration for x in range(12): self.threshold5.append(self.touch5.read()) sleep(.1) # Store average threshold values self.threshold5 = sum(self.threshold5) / len(self.threshold5) print('Threshold5: {0}'.format(self.threshold5)) def wait_touchvalue(self): while True: self.capacitance5 = self.touch5.read() self.cap_ratio5 = self.capacitance5 / self.threshold5 # Check if a TouchPad is pressed if .40 < self.cap_ratio5 < .95: #player.next() print('Touch5: {0}, Diff: {1}, Ratio: {2}%.'.format( self.capacitance5, self.threshold5 - self.capacitance5, self.cap_ratio5 * 100)) sleep(.2) # Debounce press return self.threshold5 - self.capacitance5 break def one_touchvalue(self): self.capacitance5 = self.touch5.read() self.cap_ratio5 = self.capacitance5 / self.threshold5 print('Touch5: {0}, Diff: {1}, Ratio: {2}%.'.format( self.capacitance5, self.threshold5 - self.capacitance5, self.cap_ratio5 * 100)) sleep(.2) # Debounce press return self.cap_ratio5
def create_touch_button(pin_number, continuous=False): if pin_number in pin_numbers: button = buttons[pin_numbers.index(pin_number)] # if not isinstance(button, TouchPad): # raise Exception("Existing button {} isn't TouchPad".format(pin_number)) else: touch_pad = TouchPad(Pin(pin_number)) button = create_button(touch_pad, pin_number) touch_buttons.append(button) button.continuous = continuous return button
async def pulse_lightbar(self): pwm2 = PWM(Pin(2), freq=1000, duty=1) t = TouchPad(Pin(14)) # a = [i for i in range(-50, 51)] # seq = [math.ceil(1023/math.cosh(i/20)) for i in a] # seq= [710, 719, 728, 738, 747, 756, 765, 775, 784, 793, 802, 811, # 820, 829, 838, 846, 855, 863, 872, 880, 888, 896, 904, 912, 919, # 926, 933, 940, 947, 953, 959, 965, 971, 977, 982, 987, 991, 996, # 1000, 1003, 1007, 1010, 1013, 1015, 1017, 1019, 1021, 1022, 1023, # 1023, 1023, 1023, 1023, 1022, 1021, 1019, 1017, 1015, 1013, 1010, # 1007, 1003, 1000, 996, 991, 987, 982, 977, 971, 965, 959, 953, 947, # 940, 933, 926, 919, 912, 904, 896, 888, 880, 872, 863, 855, 846, 838, # 829, 820, 811, 802, 793, 784, 775, 765, 756, 747, 738, 728, 719, 710] # seq = [math.ceil(1024/math.cosh(i/20)) for i in a] seq = range(1000,1124) while True: # Returns a smaller number when touched pwm2.duty(self.duty_led) await sleep_ms(50)
class TouchButton(object): def __init__(self, pin, on_pressed, threshold=400, debounce_ms=50): self._touchpad = TouchPad(pin) self._on_pressed = on_pressed self._threshold = threshold self._debounce_ms = debounce_ms self._down_ms = None self._pressed = False def read(self): if self._touchpad.read() < self._threshold: if not self._pressed: if not self._down_ms: self._down_ms = time.ticks_ms() else: if time.ticks_diff(time.ticks_ms(), self._down_ms) > self._debounce_ms: self._on_pressed() self._pressed = True else: self._pressed = False self._down_ms = None
def start(): if not 'provisioned' in os.listdir(): print("First Boot REPL") #15 27 39 51 63 75 87 99 epd.set_rotate(gxgde0213b1.ROTATE_270) epd.clear_frame(fb) epd.display_string_at(fb, 0, 0, "First Boot!", font16, gxgde0213b1.COLORED) epd.display_string_at(fb, 4, 15, "Badge will drop to REPL", font12, gxgde0213b1.COLORED) epd.display_string_at(fb, 4, 39, "Configure Via REPL", font12, gxgde0213b1.COLORED) #hw stats adc = machine.ADC(machine.Pin(35)) adc.atten(adc.ATTN_11DB) Voltage = (adc.read() / 4096) * 3.3 epd.display_string_at(fb, 4, 63, "Bat V:", font12, gxgde0213b1.COLORED) epd.display_string_at(fb, 60, 63, str(Voltage), font12, gxgde0213b1.COLORED) i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21)) devl = i2c.scan() epd.display_string_at(fb, 4, 75, "i2c:", font12, gxgde0213b1.COLORED) epd.display_string_at(fb, 60, 75, str(devl), font12, gxgde0213b1.COLORED) epd.display_frame(fb) f = open("provisioned", "w") f.write("") f.close() return # i2c bus address of the Kionix KX122-1037 Accelerometer addr = 30 i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21)) devl = i2c.scan() print("detected i2c addresses: {0}".format(str(devl))) if addr in devl: print("accelerometer detected: {0}".format(addr)) i2c.writeto_mem(addr, 0x18, b'\x80') # read X-axis accelerometer output least significant byte acclx = struct.unpack("h", i2c.readfrom_mem(addr, 0x6, 2)) # use only the first element of tuple acclx = acclx[0] print("accelerometer: x={0}".format(acclx)) # only enter menu if badge is held horizontal or inverted # this will prevent errant cap touch press from taking the # badge out of name display mode while being worn # acclx < 0: badge is hanging from lanyard # acclx = 0: badge is hortizontal # acclx > 0: badge is being held by user if machine.wake_reason() == machine.TOUCHPAD_WAKE and acclx >= 0: print(machine.TouchPad.wake_reason()) #if machine.TouchPad.wake_reason() == 9: # #go into AP mode # #TODO add support for detecting which button cause the wakeup # start_ap_mode() # start_web_server() if machine.TouchPad.wake_reason() == 8: m = buildMenu() app = TouchPad(Pin(32)) card = TouchPad(Pin(33)) right = TouchPad(Pin(13)) left = TouchPad(Pin(14)) down = TouchPad(Pin(27)) up = TouchPad(Pin(12)) m.menuloop(up, down, left, right, app, card) machine.reset() else: epd.clear_frame(fb) epd.display_string_at(fb, 0, 0, "OHS 2018", font24, gxgde0213b1.COLORED) epd.display_string_at(fb, 0, 24, "Serial REPL Mode", font16, gxgde0213b1.COLORED) epd.display_frame(fb) else: try: import d_name print("Printing Name") namestr = d_name.first + "\n" + d_name.last epd.clear_frame(fb) epd.G_display_string_at(fb, 0, 0, namestr, G_FreeSans24pt7b, 1, gxgde0213b1.COLORED) epd.display_frame(fb) except: print("No Name, Showing Logo") epd.display_frame(imagedata.ohslogo) goto_deepsleep()
accelerometer = Accelerometer() # bm280 try: bme280=BME280() except: pass # 3 rgb leds rgb = NeoPixel(Pin(17, Pin.OUT), 3, 3, 1) rgb.write() # light sensor light = ADC(Pin(39)) # sound sensor sound = ADC(Pin(36)) # buttons button_a = Pin(0, Pin.IN, Pin.PULL_UP) button_b = Pin(2, Pin.IN, Pin.PULL_UP) # touchpad touchPad_P = TouchPad(Pin(27)) touchPad_Y = TouchPad(Pin(14)) touchPad_T = TouchPad(Pin(12)) touchPad_H = TouchPad(Pin(13)) touchPad_O = TouchPad(Pin(15)) touchPad_N = TouchPad(Pin(4))
from machine import TouchPad, Pin touch = TouchPad(Pin(14)) touch.read() # Returns a smaller number when touched
import machine from machine import Pin, Timer, RTC, TouchPad import network from time import sleep import sys import esp32 import ntptime import ubinascii led_red = Pin(14, Pin.OUT) led_green = Pin(33, Pin.OUT) greenTouch = TouchPad(Pin(4)) redTouch = TouchPad(Pin(12)) button1 = Pin(32, Pin.IN, Pin.PULL_DOWN) button2 = Pin(15, Pin.IN, Pin.PULL_DOWN) wlan = network.WLAN(network.STA_IF) wlan.active(True) nets = wlan.scan() wlan.connect("David", "zyx74082L11") while not wlan.isconnected(): pass if machine.wake_reason() == machine.EXT1_WAKE: print("\n") print("Woke up due to push button") print("\n") elif machine.wake_reason() == machine.TIMER_WAKE: print("\n") print("Woke up due to timer") print("\n")
def start_pump(duration=3): RELAY(0) # on sleep(duration) RELAY(1) # off if __name__ == "__main__": # setup RELAY = Pin(15, Pin.OUT) # turn RELAY off at startup RELAY(1) WATERING_TIME = '2:51' surface = TouchPad(Pin(12)) threshold = [] # scan surface to calibrate for x in range(12): threshold.append(surface.read()) sleep(0.2) threshold = sum(threshold)/len(threshold) while True: capacitance = surface.read() capacitance_ratio = capacitance / threshold if 0.40 < capacitance_ratio < 0.90: print('Capacitance: {0}, Diff: {1}, Ratio: {2}'.format(
def start_ftp_server_app(f): start_ap_mode() startFTPServer() wait_for_button(TouchPad(Pin(32)))
def __init__(self, pinNum, pinMode, name): super(TouchKey, self).__init__(pinNum, pinMode, name) self.touchPad = TouchPad(self.pin)