利用蜂鸣器来控制温度传感器上下限
蜂鸣器可以用来警示温度传感器的上下限,以下是一个简单的代码示例:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <Tone.h>
#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10
#define MIN_TEMP 15 // 设定温度下限
#define MAX_TEMP 25 // 设定温度上限
Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK);
Tone buzzer; // 声明蜂鸣器对象
void setup() {
Serial.begin(9600);
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
pinMode(2, OUTPUT); // 设置蜂鸣器接口为输出模式
}
void loop() {
float temp = bme.readTemperature(); // 读取当前温度值
Serial.print("Temperature = ");
Serial.println(temp);
if (temp < MIN_TEMP || temp > MAX_TEMP) { // 如果温度超过设定范围
buzzer.play(500); // 播放蜂鸣器声音
delay(1000); // 延时1秒
}
}
在上面的代码中,我们在setup函数中初始化了蜂鸣器,并将其设置为输出模式。在loop函数中,我们读取当前温度值,并判断是否超出设定的范围。如果超出范围,就播放蜂鸣器声音,并延时1秒钟,以免声音过于频繁
原文地址: https://www.cveoy.top/t/topic/heJW 著作权归作者所有。请勿转载和采集!