2025年1月16日 星期四

WOKWI ESP32 模擬 READ RFID UID (AsyncMQTT_ESP32)

 WOKWI ESP32 模擬 READ RFID UID (AsyncMQTT_ESP32)


https://wokwi.com/projects/420235174679393281







WOKWI程式
#include <WiFi.h>
extern "C" {
  #include "freertos/FreeRTOS.h"
  #include "freertos/timers.h"
}
#include <AsyncMQTT_ESP32.h>

//#include <MFRC522.h>
#include <Arduino.h>
//=========================
//  RFID-RC522 wire pin
//  SDA = 5   SCK =18
//  MOSI=23   MISO=19
//  RST = 4  
//  GND , VCC
//=========================
#define LEDPIN    27
#define BuzzerPIN 14

//#define MQTT_HOST     "broker.mqtt-dashboard.com"
//#define MQTT_HOST     "broker.hivemq.com"
#define MQTT_HOST       "test.mosquitto.org"  
//#define MQTT_HOST     "broker.mqttgo.io"
#define MQTT_PORT       1883

#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""

AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;


const char *SubTopic1  = "alex9ufo/esp32/led";
const char *PubTopic2  = "alex9ufo/esp32/uid";
//const char *PubTopic3  = "alex9ufo/esp32/buzzer";  
//================================================================
//================================================================
void connectToWifi() {
  Serial.println("Connecting to Wi-Fi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
//================================================================
void connectToMqtt() {
  Serial.println("Connecting to MQTT...");
  mqttClient.connect();
}
//================================================================
void WiFiEvent(WiFiEvent_t event)
{
  switch (event)
  {
#if USING_CORE_ESP32_CORE_V200_PLUS

    case ARDUINO_EVENT_WIFI_READY:
      Serial.println("WiFi ready");
      break;

    case ARDUINO_EVENT_WIFI_STA_START:
      Serial.println("WiFi STA starting");
      break;

    case ARDUINO_EVENT_WIFI_STA_CONNECTED:
      Serial.println("WiFi STA connected");
      break;

    case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
    case ARDUINO_EVENT_WIFI_STA_GOT_IP:
      Serial.println("WiFi connected");
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());
      connectToMqtt();
      break;

    case ARDUINO_EVENT_WIFI_STA_LOST_IP:
      Serial.println("WiFi lost IP");
      break;

    case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
      Serial.println("WiFi lost connection");
      xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
      xTimerStart(wifiReconnectTimer, 0);
      break;
#else

    case SYSTEM_EVENT_STA_GOT_IP:
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      connectToMqtt();
      break;

    case SYSTEM_EVENT_STA_DISCONNECTED:
      Serial.println("WiFi lost connection");
      xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
      xTimerStart(wifiReconnectTimer, 0);
      break;
#endif

    default:
      break;
  }
}
//================================================================
void onMqttConnect(bool sessionPresent) {
  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);

  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);

  uint16_t packetIdSub1 = mqttClient.subscribe(SubTopic1 , 2);
  Serial.print("Subscribing at QoS 2, packetId: ");
  Serial.println(packetIdSub1);

  //uint16_t packetIdSub2 = mqttClient.subscribe(SubTopic2, 2);
  //Serial.print("Subscribing at QoS 2, packetId: ");
  //Serial.println(packetIdSub2);

}
//================================================================

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.println("Disconnected from MQTT.");
  if (WiFi.isConnected()) {
    xTimerStart(mqttReconnectTimer, 0);
  }
}
//================================================================
void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  Serial.println("Subscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
  Serial.print("  qos: ");
  Serial.println(qos);
}
//================================================================
void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println("Unsubscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}
//================================================================
void onMqttPublish(uint16_t packetId) {
  Serial.print("Publish acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}
//================================================================
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
 
  String messageTemp;
  for (int i = 0; i < len; i++) {
    Serial.print((char)payload[i]);
    messageTemp += (char)payload[i];
  }

  if (strcmp(topic, SubTopic1) == 0) {
    // If the relay is on turn it off (and vice-versa)
    Serial.println();

    Serial.println(messageTemp);  
    if (messageTemp == "on") {
      digitalWrite(LEDPIN,HIGH);
      Serial.println("LED ON");    
    }
    if (messageTemp == "off") {
      digitalWrite(LEDPIN,LOW);
      Serial.println("LED OFF");    
    }
     
  }
}
//================================================================
void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println("Hello, ESP32!");
  pinMode(LEDPIN, OUTPUT);
  pinMode(BuzzerPIN, OUTPUT);


  mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
  wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

  WiFi.onEvent(WiFiEvent);

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  mqttClient.onSubscribe(onMqttSubscribe);
  mqttClient.onUnsubscribe(onMqttUnsubscribe);
  mqttClient.onMessage(onMqttMessage); //callback
  mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  // If your broker requires authentication (username and password), set them below
  //mqttClient.setCredentials("REPlACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");
  connectToWifi();
}
//================================================================
void loop() {

  if (Serial.available()) {
    Serial.println("Enter MFRC522 UID (format: XX XX XX XX):");
    String input = Serial.readStringUntil('\n');
    input.trim(); // Remove any leading or trailing whitespace
    if (isValidFormat(input)) {
      Serial.println("Valid format.");
      String temp1=input;
      uint16_t packetIdPub1 = mqttClient.publish(PubTopic2, 1, true, temp1.c_str());                            
      Serial.printf("RFID UID Number Published", PubTopic2, packetIdPub1);                            
      digitalWrite(BuzzerPIN, HIGH);
      tone(BuzzerPIN, 750);
      delay(1000);
      digitalWrite(BuzzerPIN, LOW);
      noTone(BuzzerPIN);

    } else {
      Serial.println("Invalid format. Enter Enter MFRC522 UID (format: XX XX XX XX):");
    }
  }
}
//================================================================
bool isValidFormat(String input) {
  // Check if the input matches the format "XX XX XX XX"
  if (input.length() == 11 && input.charAt(2) == ' ' && input.charAt(5) == ' ' && input.charAt(8) == ' ') {
    for (int i = 0; i < input.length(); i++) {
      if (i != 2 && i != 5 && i != 8) {
        if (!isDigit(input.charAt(i))) {
          return false;
        }
      }
    }
    return true;
  }
  return false;
}
//================================================================


rfid-rc522.chip.c程式

#include "wokwi-api.h"
#include <stdint.h>
#include <stdio.h>
#include <unistd.h> // For sleep function

// Function to simulate SPI communication
void spi_transfer(uint8_t *data_out, uint8_t *data_in, uint8_t len) {
    // Simulate SPI transfer
    printf("MFRC522: Sending data: ");
    for (int i = 0; i < len; i++) {
        printf("0x%02X ", data_out[i]);
    }
    printf("\n");

    // Simulate receiving data
    for (int i = 0; i < len; i++) {
        data_in[i] = 0xAB; // Dummy data
    }
    printf("MFRC522: Received data: ");
    for (int i = 0; i < len; i++) {
        printf("0x%02X ", data_in[i]);
    }
    printf("\n");
}

// Function to send UID data to Arduino
void send_uid_to_arduino() {
    // Loop for sending 10 sets of UID data
    for (int i = 0; i < 10; i++) {
        // Simulate UID data
        uint8_t uid_data[4] = {0x12, 0x34, 0x56, 0x78};

        // Print UID data
        printf("UID %d: ", i + 1);
        for (int j = 0; j < 4; j++) {
            printf("%02X ", uid_data[j]);
        }
        printf("\n");

        // Send UID data to Arduino via SPI
        spi_transfer(uid_data, NULL, 4);

        // Wait for 1 second (for demonstration, reduce to 1 second)
        sleep(1);
    }
}


// Function to initialize the chip and SPI pins
void chip_init() {
    // Initialize MFRC522
    // Reset MFRC522
    // Additional initialization steps can be added here
     //mfrc522_write(0x0A, 0x0F); // Command register address and reset command
     
}

int main() {
    // Initialize chip
    chip_init();

    // Send UID data to Arduino
    // Send UID data to Arduino every 10 seconds
    while (1) {
        send_uid_to_arduino();
        // Wait for 10 seconds
        sleep(10);
    }

    return 0;
}

rfid-rc522.chip.json程式
{
  "name": "RFID-RC522",
  "author": "arducoding",
  "pins": [
    "SDA",
    "SCK",
    "MOSI",
    "MISO",
    "RST",
    "GND",
    "VCC",
    "",
    "",
    "",
    "",
    "",
    ""
  ],
  "controls": []
}

2025年1月14日 星期二

ESP32 DHT22 (Blynk)

 ESP32 DHT22 (Blynk)










































WOKWI程式


#define BLYNK_PRINT Serial

#define BLYNK_TEMPLATE_ID "TMPL6BrcHyG1i"
#define BLYNK_TEMPLATE_NAME "DHT22"
#define BLYNK_AUTH_TOKEN "ZHp5tlWYKk0Txynw5besSRULNcjT9UmE"

#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include "DHTesp.h"
const int DHT_PIN = 15;
#define LED 12

DHTesp dhtSensor;

int temp;
int humi;

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

BlynkTimer timer;

// This function sends Arduino's up time every second to Virtual Pin (5).
// In the app, Widget's reading frequency should be set to PUSH. This means
// that you define how often to send data to Blynk App.
void myTimerEvent()
{
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  temp=data.temperature;
  humi=data.humidity;
  Blynk.virtualWrite(V0, temp);
  Blynk.virtualWrite(V1, humi);

  Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  Serial.println("---");
 
}
BLYNK_WRITE(V2)
{
  int pinValue = param.asInt();
  Serial.print("V2 Switch value is: ");
  Serial.println(pinValue);

  if(pinValue == 1){
    digitalWrite(LED,HIGH);
    Serial.println("Led 亮");  
  }
  else{
    digitalWrite(LED,LOW);
    Serial.println("Led 滅");
  }
}
void setup() {
  Serial.begin(115200);

  pinMode(LED, OUTPUT);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
  timer.setInterval(1000L, myTimerEvent);

}

void loop() {
 
  Blynk.run();
  timer.run(); // Initiates BlynkTimer
 
}

ESP32 4 RELAY Control (Blynk)

 ESP32 4 RELAY Control  (Blynk)








Wokwi程式


#define BLYNK_PRINT Serial

#define BLYNK_TEMPLATE_ID         "TMPL6LesDW5_h"
#define BLYNK_TEMPLATE_NAME       "ESP32 4 Relay"
#define BLYNK_AUTH_TOKEN          "UehmJvhbd6YtPkMQHkxF2t6iYdWQm__d"
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#define BLYNK_PRINT Serial

char ssid[] = "Wokwi-GUEST";
char pass[] = "";

BlynkTimer timer;


// Define the pins for 4 relays
#define relay1 2
#define relay2 15
#define relay3 4
#define relay4 5
#define buttonPin 12 // Pin for the button to control all relays
int SW_relay1 = 0;
int SW_relay2 = 0;
int SW_relay3 = 0;
int SW_relay4 = 0;

BLYNK_WRITE(V1)
{
  SW_relay1 = param.asInt();
  controlRelay(relay1, SW_relay1, V1);
}

BLYNK_WRITE(V2)
{
  SW_relay2 = param.asInt();
  controlRelay(relay2, SW_relay2, V2);
}

BLYNK_WRITE(V3)
{
  SW_relay3 = param.asInt();
  controlRelay(relay3, SW_relay3, V3);
}

BLYNK_WRITE(V4)
{
  SW_relay4 = param.asInt();
  controlRelay(relay4, SW_relay4, V4);
}

BLYNK_WRITE(V5)
{
  int value = param.asInt();
  if (value == 1)
  {
    // Set all relays to ON
    digitalWrite(relay1, HIGH);
    digitalWrite(relay2, HIGH);
    digitalWrite(relay3, HIGH);
    digitalWrite(relay4, HIGH);
  }
  else
  {
    // Set all relays to OFF
    digitalWrite(relay1, LOW);
    digitalWrite(relay2, LOW);
    digitalWrite(relay3, LOW);
    digitalWrite(relay4, LOW);
  }
  Blynk.virtualWrite(V1, value);
  Blynk.virtualWrite(V2, value);
  Blynk.virtualWrite(V3, value);
  Blynk.virtualWrite(V4, value);
}

void controlRelay(int pin, int state, int virtualPin)
{
  if (state == 1)
  {
    digitalWrite(pin, HIGH);
    Serial.println("Relay terbuka");
    Blynk.virtualWrite(virtualPin, HIGH);
  }
  else
  {
    digitalWrite(pin, LOW);
    Serial.println("Relay tertutup");
    Blynk.virtualWrite(virtualPin, LOW);
  }
}

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("ESP32 Blynk");
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP); // Set buttonPin as input with internal pull-up resistor
  Blynk.begin(BLYNK_AUTH_TOKEN ,ssid, pass);
}

void loop()
{
  // put your main code here, to run repeatedly:
  Blynk.run();
  timer.run();
}

WOKWI ESP32 模擬 READ RFID UID (AsyncMQTT_ESP32)

 WOKWI ESP32 模擬 READ RFID UID (AsyncMQTT_ESP32) https://wokwi.com/projects/420235174679393281 WOKWI程式 #include < WiFi.h > extern ...