I have a bicycle lamp I bought in Decathlon years ago:
Because the button batteries are dead, and I’m not going to buy new button batteries. So, I took it off. I then installed it on the Wemos D1.
Next, go to thonny.org/ to download Thonny IDE, go to micropython.org/ to find the MicroPython firmware for ESP8266, and burn it using Thonny.
After that, I used the D7 pin (GPIo13) as the button trigger.
btn = Pin(13, Pin.OUT) #d7
Copy the code
To call from a small program, you need to start a Web service. The first natural thing to do is to make an AP hotspot:
import network
ssid = 'led'
password = 'codetyphon'
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid=ssid, password=password)
while ap.active() == False:
pass
Copy the code
Then, set up a server:
try:
import usocket as socket
except:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
Copy the code
After that, set http://192.168.4.1/next to trigger:
conn, addr = s.accept()
request = conn.recv(1024)
request = str(request)
btn_click = request.find('/next')
if btn_click == 6:
btn.on()
sleep(1)
btn.off()
Copy the code
Why have a sleep(1)? It’s because the headlight was manually pressed, and when it was pressed, there was a certain touch time. Therefore, even if the D7 pin is used to simulate touch, there is a time.
That’s the end of the key code. Here’s all the microPython code:
try: import usocket as socket except: import socket from machine import Pin import network from time import sleep import gc gc.collect() ssid = 'led' password = 'codetyphon' ap = network.WLAN(network.AP_IF) ap.active(True) ap.config(essid=ssid, password=password) while ap.active() == False: pass print('Connection successful') print(ap.ifconfig()) btn = Pin(13, Pin.OUT) #d7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 80)) s.listen(5) while True: try: if gc.mem_free() < 102000: gc.collect() conn, Addr = s.acept () Conn.setTimeout (3.0) Request = Conn.recv (1024) Conn.setTimeout (None) Request = STR (request) print('Content = %s' % request) btn_click = request.find('/next') if btn_click == 6: btn.on() sleep(1) btn.off() conn.send('ok') conn.close() except OSError as e: conn.close()Copy the code
Next, develop small programs. The key code is simple, in fact, a single sentence calling the 192.168.4.1 (Web service written in MicroPython) service.
Async up() {const res = await app.wx.request({url: 'http://192.168.4.1/next'})},Copy the code
Finally, the effect is as follows:
Reference: 1, randomnerdtutorials.com/micropython… 2, randomnerdtutorials.com/micropython…