项目简介

设计一个板子,当按下按键时对微信发送通知,带有屏幕显示和灯光显示

项目详情

ESP8266部分

硬件连接

  1. TFT屏幕连线
TFT引脚8266引脚
VCC3.3V
GNDGND
LED3.3V
CLKD5
SDID7
RSD3
RSTD2
CSD1
  1. 其余元件连线
元件引脚8266引脚
绿色LED一极D8
红色LED一极D6
蓝色LED一极TX
开关一极RX

注:以上所示元件的另一极都接地,其中LED最好连接下拉电阻接地

软件代码

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SPI.h>

// TFT屏幕引脚定义
#define TFT_CS     D1
#define TFT_RST    D2
#define TFT_DC     D3

// 创建Adafruit_ST7735对象
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
 
// WiFi网络配置
const char* ssid = "902_WiFi";
const char* password = "jy666666";

// 引脚定义
const int successPin = 15;           // 发送成功信号的GPIO
const int failurePin = 12;           // 发送失败信号的GPIO
const int buttonPin = 3;             // 连接外部按钮的GPIO
const int wifiPin = 1;               // 监控WiFi连接状态的GPIO

// 通知持续时间,毫秒
const unsigned long notificationDuration = 3000;

// 按钮状态标志
volatile bool buttonPressed = false;

// 记录通知开始时间
unsigned long notificationStartTime = 0;

// 按钮中断处理函数
ICACHE_RAM_ATTR void handleButtonInterrupt() {
  buttonPressed = true;
}

// 在屏幕上打印文本,指定文本颜色
void tft_print(String text, uint16_t textColor) {
  tft.fillScreen(ST7735_BLACK);   // 用黑色填充屏幕
  tft.setCursor(0, 54);
  tft.setTextColor(textColor);    // 设置文本颜色
  tft.print(text);
  Serial.println(text);
}

// 初始化函数
void setup() {
  Serial.begin(115200);

  // 初始化TFT显示屏
  tft.initR(INITR_144GREENTAB);
  tft_print("Initialized", ST7735_WHITE);

  tft.fillScreen(ST7735_BLACK);   // 用黑色填充屏幕

  // 设置文本属性
  tft.setCursor(0, 0);
  tft.setTextColor(ST7735_WHITE);
  tft.setTextSize(1); // 调整文本大小

  // 设置引脚模式
  pinMode(successPin, OUTPUT);
  pinMode(wifiPin, OUTPUT);
  pinMode(failurePin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);

  // 连接到WiFi
  WiFi.begin(ssid, password);
  tft_print("Connecting to WiFi...", ST7735_WHITE);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  tft_print("Connected to WiFi", ST7735_BLUE);
  digitalWrite(wifiPin, HIGH);

  // 配置按钮中断
  attachInterrupt(digitalPinToInterrupt(buttonPin), handleButtonInterrupt, FALLING);
}

// 发送HTTP POST请求
bool sendHttpPostRequest(String url, String formData, String checkField, String successValue) {
  tft_print("Sending HTTP POST request...", ST7735_WHITE);

  WiFiClient client;  // 创建WiFiClient对象
  HTTPClient http;
  http.begin(client, url);
  http.setTimeout(10000);  // 设置连接超时时间,单位为毫秒
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  int httpResponseCode = http.POST(formData);

  if (httpResponseCode == 200) {
    // 解析JSON数据
    DynamicJsonDocument jsonDoc(512);  // 根据JSON数据大小调整大小
    DeserializationError jsonError = deserializeJson(jsonDoc, http.getString());

    // 检查解析是否成功
    if (jsonError) {
      tft_print("JSON parsing failed! Error code: ", ST7735_RED);
      tft_print(jsonError.c_str(), ST7735_RED);
      http.end();
      return false;
    }

    // 检查指定checkField的值
    String responseValue = jsonDoc[checkField].as<String>();

    // 检查响应值是否与指定的successValue匹配
    if (responseValue == successValue) {
      http.end();
      tft_print("Success", ST7735_GREEN);
      return true;
    }
  }

  http.end();
  tft_print("Failed", ST7735_RED);
  return false;
}

// 主循环函数
void loop() {
  if (buttonPressed) {
    // 检查HTTP POST请求是否成功
    bool postRequestSuccess = sendHttpPostRequest("http://192.168.31.248:2319/sendmessage", "token=CQACAgUAAxkBAAECJY&title=esp8266&message=post请求完成", "code", "1");

    // 根据请求结果设置输出引脚
    if (postRequestSuccess) {
      digitalWrite(successPin, HIGH);
      digitalWrite(failurePin, LOW);
    } else {
      digitalWrite(successPin, LOW);
      digitalWrite(failurePin, HIGH);
    }

    // 记录通知的开始时间
    notificationStartTime = millis();

    buttonPressed = false; // 重置按钮状态
  }

  // 检查是否应关闭通知
  if (millis() - notificationStartTime >= notificationDuration) {
    digitalWrite(successPin, LOW);
    digitalWrite(failurePin, LOW);
  }

  // 其他的循环代码...
}

个人API部分

个人api使用Flask开发,代码如下:

from flask import Flask, request, jsonify

import requests

app = Flask(__name__)
TOKEN='CQACAgUAAxkBAAECJY'

def send_notification(title, content):
    url = "https://sctapi.ftqq.com/SCT236695T1psARqmwT6dhUxVljhB4L1Pk.send"

    # 构造请求参数
    params = {
        'title': title,
        'desp': content
    }

    # 发送 POST 请求
    try:
        response = requests.post(url, data=params)
        response.raise_for_status()  # 检查请求是否成功
        return True
    except requests.exceptions.RequestException as e:
        print(f"Error: {e}")
        return False


@app.route('/sendmessage', methods=['POST'])
def process_request():
    # 获取 POST 请求中的数据
    data = request.form

    # 检查是否包含必要的字段
    if 'token' not in data or 'message' not in data:
        return jsonify({'message': 'failed'})

    # 进行身份验证,你可以根据实际需求修改这部分
    token = data['token']
    title = data['title']
    message = data['message']
    # 验证token是否正确并返回code和message
    if token != TOKEN:
        return jsonify({'code':0,'message': 'token error'})
    else:
        # 发送通知
        if send_notification(title, message):
            return jsonify({'code':1,'message': 'success'})
        else:
            return jsonify({'code':0,'message': 'send failed'})
    

if __name__ == '__main__':
    app.run(debug=True,port=2319,host='0.0.0.0')

项目验证

  1. 启动flask程序
  2. 连通硬件电路电源
  3. 等待蓝色LED亮起,屏幕显示"Connected to WiFi"
  4. 按下开关并松开,等待屏幕通知结果
  5. 红灯亮起表示失败,绿灯亮起表示成功

成功演示

演示视频

闲来无事,记录琐事