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
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 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 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()
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
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()
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
from machine import TouchPad, Pin from time import sleep tp1 = TouchPad(Pin(4)) led_bleue = Pin(2, Pin.OUT) compt = 0 seuil = 100 ancien_etat = tp1.read() for boucle in range(500): # duree de la boucle : 10 s while not tp1.read() < seuil: # on attend l'appui sur le touch pad pass # on ne fait rien, mais il faut le dire compt = compt + 1 print("Compteur :", compt) led_bleue.value(not led_bleue.value()) # basculement de led_bleue while tp1.read() < seuil: # on attend l'appui sur le bp pass # on ne fait rien, mais il faut le dire
def output_touch_values(oled, touch_pin): touchpad = TouchPad(Pin(touch_pin)) oled.text(str(touchpad.read()), 1, 0)
from machine import TouchPad, Pin from time import sleep touch_pin = TouchPad(Pin(4)) while True: touch_value = touch_pin.read() print("Touch value : ", touch_value) sleep(0.5)
elif t == 4: fre = round(((2093 - 65) * p / 100) + 65) return (fre) neo_pixel = NeoPixel(Pin(12, Pin.OUT), 24) musica_1 = PWM(Pin(25)) Naranja1 = TouchPad(Pin(4)) Naranja2 = TouchPad(Pin(2)) Naranja1.config(1000) Naranja2.config(1000) i2c = I2C(scl=Pin(22), sda=Pin(21)) MPU = mpu6050.accel(i2c) U_Sonico = HCSR04(trigger_pin=32, echo_pin=35) while True: if 300 > (Naranja1.read()): for i in range(3): neo_pixel[i - 1] = hex_to_rgb('#ff0000') neo_pixel.write() musica_1.freq(784) musica_1.duty(512) time.sleep_us(1968750) musica_1.freq(0) time.sleep_us(31250) if 300 > (Naranja2.read()): for i in range(3, 6): neo_pixel[i - 1] = hex_to_rgb('#ff9900') neo_pixel.write() musica_1.freq(587) musica_1.duty(512) time.sleep_us(1968750)
# mqtt initialisatie mqtt_cl = MQTTClient('esp_frank_16', BROKER) mqtt_cl.connect() # touchpin initialisatie tpLinks = TouchPad(Pin(PIN_TOUCH5)) tpRechts = TouchPad(Pin(PIN_TOUCH0)) # touchpin calibratie drempelLinks = int(calibTouchPin(tpLinks) * FACTOR) drempelRechts = int(calibTouchPin(tpRechts) * FACTOR) while True: # touchpin uitlezen vLinks = tpLinks.read() vRechts = tpRechts.read() # move code if (vLinks <= drempelLinks and vRechts <= drempelRechts) or (vLinks > drempelLinks and vRechts > drempelRechts): Dx = 0 elif vLinks <= drempelLinks: Dx = -1 else: Dx = 1 print(Dx) # move code doorsturen naar mqtt broker mqtt_cl.publish(TOPIC, str(Dx))
from machine import TouchPad, Pin touch = TouchPad(Pin(14)) touch.read() # Returns a smaller number when touched
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( capacitance, threshold - capacitance, capacitance_ratio)) start_pump() sleep(0.2)
def do_both(): half(green, red) def do_night(): half(red, black) brightness(10) list_bedfunctions = [rainbow, do_both, do_papa, do_sundown, do_night] list_index = 0 while (True): if (t1.read() < threshold): if not on: stop_task() list_bedfunctions[list_index]() on = True else: stop_task() set_color(black) on = False while t1.read() < threshold: time.sleep_ms(500) if (t2.read() < threshold): if not on: pass
08.30 - Internal touch sensor (Capacitive touch) This sketch shows how to use the ESP32 integrated capacitive touch sensor. Components ---------- - ESP32 - Connect a jumper wire to GPIO 15 (leave the other end unconnected) - Wires - Breadboard Documentation: Timers: https://micropython-docs-esp32.readthedocs.io/en/esp32_doc/esp32/quickref.html#timers Pins and GPIO: https://micropython-docs-esp32.readthedocs.io/en/esp32_doc/esp32/quickref.html#pins-and-gpio Touch: http://docs.micropython.org/en/latest/esp32/quickref.html#capacitive-touch Course: MicroPython with the ESP32 https://techexplorations.com ''' from machine import TouchPad, Pin from time import sleep_ms t = TouchPad(Pin(15)) while True: print(t.read()) # Returns a smaller number when touched sleep_ms(50)
class TouchPad(): 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()) async def _handle_touch(self): current_hold_repead_time_diff = 0 while True: val = self.tp.read() if val < self.threshold: if not self.is_active: #print(val) self.pressed_timestamp = time.ticks_ms() self.is_active = True if self.press_cmd is not None: self.press_cmd(self) elif self.hold_cmd is not None and self.pressed_timestamp is not None: if time.ticks_diff( time.ticks_ms(), self.pressed_timestamp ) > self.hold_time + current_hold_repead_time_diff: if self.hold_repeat_time_diff is not None: current_hold_repead_time_diff = self.hold_repeat_time_diff self.pressed_timestamp = time.ticks_ms() else: current_hold_repead_time_diff = 0 self.pressed_timestamp = None self.hold_cmd(self) elif self.is_active: #release self.is_active = False self.pressed_timestamp = None current_hold_repead_time_diff = 0 if self.release_cmd is not None: self.release_cmd(self) await asyncio.sleep(1 / self.freq)
# pixles timer tim1.init(period=1000, mode=Timer.PERIODIC, callback=lambda t: Rgb_Neopixel()) #oled full pixel test testdrawline() display.fill(0) display.show() while True: if ext.read() == 0: time.sleep_ms(1000) if ext.read() == 0: Print_Serial_num() print('Y:%d, T:%d, H:%d, O:%d, N:%d' % (touchPad_Y.read(), touchPad_T.read(), touchPad_H.read(), touchPad_O.read(), touchPad_N.read())) print('P0:%d, P1:%d ,P2:%d, P3/ext:%d' % (P0.read(), P1.read(), P2.read(), ext.read())) print('light:%d,Sound:%d' % (light.read(), sound.read())) print( 'x = %.2f, y = %0.2f, z = %.2f ' % (accelerometer.get_x(), accelerometer.get_y(), accelerometer.get_z())) display.rect(0, 0, 128, 64, 1) display.DispChar('声音:%d,光线:%d' % (sound.read(), light.read()), 3, 3) display.DispChar( '加速度:%.1f,%.1f,%.1f' % (accelerometer.get_x(), accelerometer.get_y(), accelerometer.get_z()), 3, 16) display.DispChar('id:%s' % machine_id, 3, 42) display.show()
import utime # variabelen calib_touch = [] PIN_TOUCH0 = 4 PIN_LED = 21 bTouch = False # touch & LED initialiseren tp = TouchPad(Pin(PIN_TOUCH0)) led = Pin(PIN_LED, Pin.OUT) # los calibreren print('Calibratie los - 10 metingen') for i in range(0, 10): waarde = tp.read() print('Waarde %d : %d' % (i, waarde)) calib_touch.append(waarde) # gemiddelde waarde calib_val = sum(calib_touch) // len(calib_touch) # lus while True: # lees waarde waarde = tp.read() twaarde = waarde / calib_val # toon waarde print('Touchwaarde %.1f' % (twaarde)) # led aan of uit if not bTouch and twaarde < 0.4:
from machine import Pin, TouchPad import time keys = [] for pin in range(40): try: touchPad = TouchPad(Pin(pin)) except ValueError: continue keys.append((pin, touchPad)) while True: for pin, touchPad in keys: print("[{}]: {}".format(pin, touchPad.read()), end=" ") print() time.sleep(0.5)
# author: h.serimer 03.2021 https://github.com/eproje/uPy_Course # Board: Lolin32 Lite # simple touch # There are ten capacitive touch-enabled pins that can be used on the ESP32: 0, 2, 4, 12, 13 14, 15, 27, 32, 33. # Trying to assign to any other pins will result in a ValueError. # REF: https://docs.micropython.org/en/latest/esp32/quickref.html from machine import TouchPad, Pin from time import sleep touch_pin1 = TouchPad(Pin(12)) touch_pin2 = TouchPad(Pin(14)) while True: touch_value1 = touch_pin1.read() touch_value2 = touch_pin2.read() print(touch_value1, "-", touch_value2) sleep(0.5)
from machine import TouchPad, Pin from time import sleep tp1 = TouchPad(Pin(4)) tp2 = TouchPad(Pin(15)) for boucle in range(400): # duree de la boucle : 4 s etat1 = tp1.read() # lecture du TouchPad 1 etat2 = tp2.read() print("Touche 1 : {0:3d} Touche 2 : {1:3d}".format(etat1, etat2)) sleep(.01)
print('Sending response') client.sendall(b'HTTP/1.1 200 OK\n\n') client.sendall(html) client.close() print('Response sent') else: print("Sending 2") client.sendall(b'HTTP/1.1 200 OK\n\n') client.sendall(touchme) client.close() while True: try: if tp.read() < 200: led_val = 1 else: led_val = 0 except ValueError as e: led_val = led_val try: client, addr = server.accept() send_response(client, addr) except OSError as e: pass if HAVE_LED: led.value(led_val) time.sleep_ms(100)
from machine import Pin, PWM, I2C, TouchPad import mpu6050 en = Pin(32, Pin.OUT) pm = Pin(33, Pin.OUT) touch1 = TouchPad(Pin(12)) touch2 = TouchPad(Pin(13)) i2c = I2C(scl=Pin(22), sda=Pin(21)) accel = mpu6050.accel(i2c, 104) print("WHILE") while 1: t1 = touch1.read() < 300 t2 = touch2.read() < 300 if t1 == t2: en.off() else: en.on() if t1: pm.on() else: pm.off() while 0: a = accel.get_values() if a['GyZ'] > 1000: en.on() pm.on()
import ssd1306 from time import sleep from machine import Pin, I2C, TouchPad from common import * initialise_OLED() oled = create_oled() oled.fill(0) touchpad = TouchPad(Pin(13)) while True: #oled.text(str(touchpad.read()), 1, 0) if touchpad.read() < 500: oled.fill(1) else: oled.fill(0) oled.show()
''' Touch Sensor Pin Layout T0 = GPIO4 T1 = GPIO0 T2 = GPIO2 T3 = GPIO15 T4 = GPIO13 T5 = GPIO12 T6 = GPIO14 T7 = GPIO27 T8 = GPIO33 T9 = GPIO32''' from machine import TouchPad, Pin from time import sleep touch = TouchPad(Pin(15)) led = Pin(17, Pin.OUT) while True: data = touch.read() print(data) if (data > 2): led.value(0) else: led.value(1)
from fusion import Fusion i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(19)) i2c.scan() imu = MPU6050(i2c) fuse = Fusion() print(imu.accel.xyz) while (True): time.sleep_ms(500) print(imu.accel.xyz) while True: fuse.update_nomag(imu.accel.xyz, imu.gyro.xyz) # Note blocking mag read if count % 50 == 0: print("Heading, Pitch, Roll: {:7.3f} {:7.3f} {:7.3f}".format( fuse.heading, fuse.pitch, fuse.roll)) time.sleep_ms(20) count += 1 from machine import TouchPad, Pin t = TouchPad(Pin(4)) t.config(500) t.read() def touch(): if t.read() < 300: return True else: return False