玩转Arduino(2)-按钮控制小灯

思路 按钮按下输出为低电平,按钮抬起时为高电平。 萌叔希望达到的效果是按一下按钮,小灯亮起,再按一次,小灯熄灭 需要捕获电位从 低电位 -> 高电位 的这个变化 代码 #define legPinIn 10 #define legPinOut 5 bool isLightOn = false; int preMode = HIGH; int currMode = HIGH; void setup() { Serial.begin(9600); pinMode(legPinIn, INPUT); pinMode(legPinOut, OUTPUT); } void loop() { isLightOn = getLightState(); if (isLightOn) { digitalWrite(legPinOut, HIGH); } else { digitalWrite(legPinOut, LOW); } delay(100); } bool getLightState() { if (digitalRead(legPinIn) != currMode) { preMode = currMode; currMode = digitalRead(legPinIn); if (preMode == LOW && currMode == HIGH) { isLightOn = !isLightOn; Serial.print("isLightOn: "); Serial.println(isLightOn); } } return isLightOn; } 演示视频 B站 ...

October 20, 2024 · 1 min

玩转Arduino(1)-自制温度湿度计

思路 从温湿度传感器读取温度和湿度信息,然后在LCD显示器上展示 代码 #include <DHT11.h> #include <Bonezegei_LCD1602_I2C.h> DHT11 dht11(2); Bonezegei_LCD1602_I2C lcd(0x27); void setup() { // Initialize serial communication to allow debugging and data readout. // Using a baud rate of 9600 bps. Serial.begin(9600); lcd.begin(); } void loop() { int temperature = 0; int humidity = 0; // Attempt to read the temperature and humidity values from the DHT11 sensor. int result = dht11.readTemperatureHumidity(temperature, humidity); // Check the results of the readings. // If the reading is successful, print the temperature and humidity values. // If there are errors, print the appropriate error messages. if (result == 0) { Serial.print("Temperature: "); Serial.print(temperature); Serial.print(" °C\tHumidity: "); Serial.print(humidity); Serial.println(" %"); String str = String("Temperat: ") + temperature + String(" C"); lcd.setPosition(0, 0); lcd.print(str.c_str()); lcd.setPosition(0, 1); str = str = String("Humidity: ") + humidity + String(" %"); lcd.print(str.c_str()); } else { // Print error message based on the error code. Serial.println(DHT11::getErrorString(result)); } delay(10000); } 参考资料 1.DHT11驱动 2.LCD1602驱动 ...

October 20, 2024 · 1 min