ESP8266(Lolin D1 mini)运行MicroPython无法读取I2C按键
Hey there! Let's figure out why your I2C button is stuck returning \x02 no matter what. The main issue I spot right away is a byte encoding mistake in how you're sending the GET_KEY_VALUE command. Let's break this down step by step:
1. The Critical Command Error
You mentioned the GET_KEY_VALUE instruction is 0x04 (1 byte), but your code uses b'4' to send it. Here's the problem:
b'4'is the ASCII character '4', which translates to the hex value 0x34—not the 0x04 the button module expects.- That's why the module is returning an unexpected (and unchanging) response: it's getting an invalid command, so it's either ignoring it or returning a default error state.
2. Fixed Code Example
Replace the command byte with the correct hex value using bytes([0x04]). Here's the corrected code:
from machine import Pin, I2C # Initialize I2C (same as your setup) i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000) # Send the correct GET_KEY_VALUE command (0x04) i2c.writeto(49, bytes([0x04])) # Read 1 byte of response and convert to integer for clarity key_state = i2c.readfrom(49, 1)[0] print(f"Key state (hex): 0x{key_state:02X} | Integer: {key_state}")
3. Expected Key State Values
Based on Wemos' I2C button library docs, you should see these values:
0x00: No button pressed0x01: Button 1 pressed0x02: Button 2 pressed0x03: Button 3 pressed0x04: Button 4 pressed
If you now see values change when pressing buttons, you're all set!
4. Additional Troubleshooting (If the Issue Persists)
If you still get unchanging values after fixing the command:
- Check I2C Frequency: Try lowering the I2C frequency to 100000 (100kHz) instead of 400000—some modules are more stable at the standard speed.
- Verify Hardware Connections: Double-check that the button module's SDA/SCL pins are properly connected to D1 (Pin 5) and D2 (Pin 4) on your Lolin D1 Mini.
- Test with a Simple Loop: Add a loop to continuously read the state, so you can test in real-time:
import time while True: i2c.writeto(49, bytes([0x04])) key_state = i2c.readfrom(49, 1)[0] print(f"Current key state: {key_state}") time.sleep(0.2)
内容的提问来源于stack exchange,提问作者dvilela
相关产品推荐
相关产品推荐

