#include <WiFi.h>
#include <HTTPClient.h> //
#include <UrlEncode.h>
// Buzzer
const int Buzzer_Pin = 35;
// 超声波
const int TrigPin = 5;
const int EchoPin = 18;
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
float DistanceCm;
// WiFi Credentials
const char* ssid = "Wokwi-GUEST"; //定义WiFi网络
const char* password = ""; //需要输入密码,没有东西则不用
// WhatsApp API配置
String phoneNumber = "85259828641"; // WhatsApp手机号码
String apiKey = "8508860"; // API密钥
// 发送WhatsApp信息的函数
void sendMessage(String message) {
// 拼接URL
String url = "https://api.callmebot.com/whatsapp.php?phone=" + phoneNumber + "&apikey=" + apiKey + "&text=" + urlEncode(message);
HTTPClient http;
http.begin(url);
// 指定内容类型
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// 发送HTTP POST请求
int httpResponseCode = http.POST(url);
if (httpResponseCode == 200) {
Serial.print("Message sent successfully");
} else {
Serial.println("Error sending the message");
Serial.print("HTTP response code: ");
Serial.println(httpResponseCode);
}
// 释放HTTPClient资源
http.end();
}
void setup() {
Serial.begin(115200);
// 初始化超声波传感器引脚
pinMode(TrigPin, OUTPUT);
pinMode(EchoPin, INPUT);
// 连接WiFi
WiFi.begin(ssid, password);
Serial.println("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// 超声波检测距离
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
// 计算距离
duration = pulseIn(EchoPin, HIGH);
DistanceCm = duration * SOUND_SPEED / 2;
// 如果距离大于15cm,发送更换厕纸信息
if (DistanceCm > 15) {
sendMessage("厕所需要更换厕纸");
delay(5000); // 防止重复发送,延迟5秒
}
}