Hello
I connected two Arduinos with udp connection. Communicated and there is no problem. Because the temperature and humidity sensor is installed on the transmitter side. I want the data receiver to reach me separately and be sent to the server. For example, between the values that are sent, if the word "Temperature" is sent before the temperature data, Ardino realizes that the value sent is related to the temperature and sends it to the mqtt server.
Thank you for your help.
This is the sender's code:
/* AHT10 Sensor Active
Scheduler Active
Wifi Connectivity Active
HTTP UDP Stack Active
UID Active
Software Watchdog Active
Masoud
January 05, 2022
*/
#include <Arduino.h>
#include <Wire.h>
#include <AHT10.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoOTA.h>
#include <WiFiUdp.h>
//Prototyping
void tempSense(); // Prototype so PlatformIO doesn't complain
// Set WiFi credentials
#define WIFI_SSID "Ang-Sim"
#define WIFI_PASS "qwerty2580"
// UDP
WiFiUDP UDP;
IPAddress remote_IP(192,168,1,1);
#define UDP_PORT 4210
// UDP Buffer
char packet[255];
char reply[] = "Packet received!";
const String prefix = "/angizeh/toossab/1/4";
const char* clientID = "AirHumidityNode06";
String topic = "";
String message = "";
// AHT Sensor
AHT10 myAHT10(AHT10_ADDRESS_0X38);
//Timer Variables
long Day = 0;
int Hour = 0;
int Minute = 0;
int Second = 0;
int SecondStamp = 0;
int Once = 0;
int cnt=10;
int powerFlag;
//Variables
int strobe = 0;
float airTemperature = 0, airHumidity = 0;
WiFiClient wclient;
PubSubClient client(wclient);
void setup() {
// Setup serial port
Serial.begin(115200);
Serial.println();
// Begin WiFi
WiFi.begin(WIFI_SSID, WIFI_PASS);
WiFi.mode(WIFI_AP_STA);
while (myAHT10.begin() != true)
{
Serial.println(F("AHT10 not connected or fail to load calibration coefficient")); //(F()) save string to flash & keeps dynamic memory free
delay(5000);
}
Serial.println(F("AHT10 OK"));
// Connecting to WiFi...
Serial.print("Connecting to ");
Serial.print(WIFI_SSID);
// Loop continuously while WiFi is not connected
ArduinoOTA.setHostname("AirHumidityNode");
ArduinoOTA.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH) {
type = "sketch";
} else { // U_FS
type = "filesystem";
}
// NOTE: if updating FS this would be the place to unmount FS using FS.end()
Serial.println("Start updating " + type);
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) {
Serial.println("Auth Failed");
} else if (error == OTA_BEGIN_ERROR) {
Serial.println("Begin Failed");
} else if (error == OTA_CONNECT_ERROR) {
Serial.println("Connect Failed");
} else if (error == OTA_RECEIVE_ERROR) {
Serial.println("Receive Failed");
} else if (error == OTA_END_ERROR) {
Serial.println("End Failed");
}
});
ArduinoOTA.begin();
Serial.print("\n");
Serial.println("OTA Ready");
while (WiFi.status() != WL_CONNECTED){
// ESP.wdtFeed();
// ESP.wdtDisable();
// delay(500);
Serial.print(".");
delay(500);
// cnt--;
// if(cnt==0){
// ESP.wdtDisable();
// #ifdef SOFT_WATCHDOG
// ESP.wdtEnable(0);
// #endif
// while(1);
delay(1000);
}
// Connected to WiFi
Serial.println();
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqttServerName, mqttport);
client.setCallback(onMessageArrived);
//
// while (!client.connected()){
// delay(1000);
// Serial.println("Connecting To Server ...");
//
// if (client.connect(clientID, mqttuser, mqttpass, toCharArray(prefix + "/Will"), 1, true, toCharArray("Bye"), true))
// {
// Serial.println("Connected To Server");
// }
// else
// {
// Serial.print("failed with state ");
// Serial.print(client.state());
// delay(2000);
// }
// }
// Begin UDP port
UDP.begin(UDP_PORT);
Serial.print("Opening UDP port ");
Serial.println(UDP_PORT);
}
void loop() {
ESP.wdtFeed();
ArduinoOTA.handle();
tempSense();
int a=analogRead(A0);
int b=map(a,0,1023,0,255);
Serial.println(b);
if(b<=250){
Serial.println("AC Power Disconnected");
client.publish(toCharArray("/angizeh/toossab/1/4/ACPower:"), toCharArray("Disconnected"));
//Serial.print(b);
powerFlag = 0;
delay(500);
}
if(b>250){
Serial.println("AC Power Connected");
client.publish(toCharArray("/angizeh/toossab/1/4/ACPower:"), toCharArray("Connected"));
//Serial.print(b);
powerFlag = 1;
delay(500);
}
rtUDP();
delay(2000);
}
//Functions
//=======================================================================
void tempSense(){
// if (!client.connected()) {
// ESP.wdtFeed();
// Serial.print("reconnect");
// reconnect();
// } else {
**airTemperature = myAHT10.readTemperature(); airHumidity = myAHT10.readHumidity();**
** Serial.print("Timestamp; ");Serial.print(Minute);Serial.print(":");Serial.println(Second);**
** Serial.print("Device; ");Serial.print("Chip ID: ");Serial.print(ESP.getChipId());Serial.print(" MAC Address: ");Serial.println(WiFi.macAddress());**
** Serial.print("Temperature: ");Serial.print(airTemperature);Serial.println(" degrees C");**
** client.publish(toCharArray("/angizeh/toossab/1/4/Temperature"), toCharArray(String(airTemperature)));**
** Serial.println("Published");**
** Serial.print("Pressure: ");Serial.print(airHumidity);Serial.println(" RH %");**
** client.publish(toCharArray("/angizeh/toossab/1/4/Humidity"), toCharArray(String(airHumidity)));**
** UDP.print("Crestron connect");**
** UDP.endPacket();**
** UDP.write(toCharArray(String(airHumidity)));**
** UDP.endPacket();**
** Serial.println("Published");**
** //}**
**}**
boolean reconnect() {
while (WiFi.status() != WL_CONNECTED){
ESP.wdtFeed();
ESP.wdtDisable();
delay(500);
Serial.print(".");
delay(500);
cnt--;
if(cnt==0){
ESP.wdtDisable();
#ifdef SOFT_WATCHDOG
ESP.wdtEnable(0);
#endif
while(1);
}
}
delay(1000);
if (client.connect(clientID, mqttuser, mqttpass, toCharArray(prefix + "/Will"), 1, true, toCharArray("Disconnected"), true)) {
client.setCallback(onMessageArrived);
Serial.print("***Disconnected***");
return client.connected();
}
}
char* toCharArray(String str) {
return &str[0];
}
void onMessageArrived(char* t, byte* m, unsigned int length) {
topic = String(t);
message = String((char*)m);
message = message.substring(0, length);
if (message == "HELLO") {
Serial.println("Hello client");
client.publish(toCharArray(prefix + "/server"), toCharArray("HELLO"));
Serial.println("Hello server");
}
}
void rtUDP(){
// Send Packet
ESP.wdtFeed();
UDP.beginPacket(remote_IP, UDP_PORT);
if(powerFlag == 0){
int data = 0;
UDP.write(data);
UDP.endPacket();
Serial.println(data + "Sent");
}
if(powerFlag == 1){
int data = 1;
UDP.write(data);
UDP.endPacket();
Serial.println(data + "Sent");
}
Serial.print("UDP transmitted ");
//Serial.println(data++);
delay(5000);
}// END
//=======================================================================
This is the recipient side code:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <SoftwareSerial.h>
#include<ESP8266WebServer.h>
#include <PubSubClient.h>
#define rxPin D6
#define txPin D5
SoftwareSerial mySerial(rxPin,txPin);
#define ssid "Ang-Sim"
#define pass "qwerty2580"
//// UDP
WiFiUDP UDP;
IPAddress local_ip(192, 168, 1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
#define UDP_PORT 4210
ESP8266WebServer server(80);
const char* wifi = "Ang-IoT";
const char* password = "qwerty2580";
const String prefix = "/angizeh/toossab/1/4";
const char* clientID = "AirHumidityNode06";
const char* mqttServerName = "";
const int mqttport = ;
const char* mqttuser = "";
const char* mqttpass = "";
WiFiClient wclient;
PubSubClient client(wclient);
String topic = "";
String message = "";
// UDP Buffer
char packet[255];
char reply[] = "Packet received!";
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
int ACState = 3;
int newACState = 3;
int cnt=10;
void setup()
{
// Setup serial port
Serial.begin(115200);
Serial.println();
// Begin Access Point
Serial.println("UDP server\nStarting access point...");
WiFi.mode(WIFI_AP_STA);
WiFi.softAPConfig(local_ip, gateway, subnet);
WiFi.softAP(ssid, pass);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
// Begin listening to UDP port
UDP.begin(UDP_PORT);
Serial.print("Listening on UDP port ");
Serial.println(UDP_PORT);
STA();
mySerial.begin(9600);
Serial.println("Initializing...");
delay(1000);
mySerial.println("AT");
updateSerial();
delay(500);
mySerial.println("AT+CSQ");
updateSerial();
delay(500);
mySerial.println("AT+CSCS?");
updateSerial();
delay(500);
mySerial.println("AT+CREG=1");
updateSerial();
delay(500);
mySerial.println("AT+CMGF=1");
updateSerial();
delay(500);
mySerial.println("AT+CMGF?");
updateSerial();
delay(500);
mySerial.println("AT+CMGS=\"+989390726967\"");
updateSerial();
delay(500);
delay(3000);
}
void loop()
{
server.handleClient();
if(UDP.parsePacket()) {
UDP.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
if(strcmp(packetBuffer,"Crestron connect")==0){
UDP.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
Serial.println(packetBuffer);
client.publish(toCharArray("/angizeh/toossab/1/4/Humidity"), toCharArray(String(packetBuffer)));
Serial.println("Published");
}else{
//Serial.println((int) packetBuffer[0]);
newACState = (int) packetBuffer[0];
// Serial.print(ACState);
// Serial.print(newACState);
if (ACState != newACState){
ACState = newACState;
Serial.println("UDP packet received ");
if (ACState == 1){
client.publish(toCharArray("/angizeh/toossab/1/4/ACPower"), toCharArray("Connected"));
Serial.println("Published");
Serial.println ("AC Connected");
mySerial.println("AT+CMGS=\"+989390726967\"");
updateSerial();
delay(500);
mySerial.print("AC Connected");
updateSerial();
mySerial.write(26);
delay(500);
}
if (ACState == 0) {
client.publish(toCharArray("/angizeh/toossab/1/4/ACPower"), toCharArray("Disconnected"));
Serial.println("Published");
Serial.println ("AC Disconnected");
mySerial.println("AT+CMGS=\"+989390726967\"");
updateSerial();
delay(500);
mySerial.print("AC Disconnected");
updateSerial();
mySerial.write(26);
delay(500);
}
}
}
updateSerial();
}
}
void updateSerial()
{
delay(500);
while (Serial.available())
{
mySerial.write(Serial.read());
}
while(mySerial.available())
{
Serial.write(mySerial.read());
}
}
void STA()
{
WiFi.begin(wifi, password);
while(WiFi.status()!= WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
Serial.println();
Serial.print(".....Connect to the WiFi and open the IP address given below.....");
Serial.println("IP address:-");
Serial.println(WiFi.localIP());
server.on ("/", [] () {server.send(200, "text/plain", "HELLO THERE");});
server.begin();
client.setServer(mqttServerName, mqttport);
client.setCallback(onMessageArrived);
//
while (!client.connected()){
delay(1000);
Serial.println("Connecting To Server ...");
if (client.connect(clientID, mqttuser, mqttpass, toCharArray(prefix + "/Will"), 1, true, toCharArray("Bye"), true))
{
Serial.println("Connected To Server");
}
else
{
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.publish(toCharArray("/angizeh/toossab/1/4/Temperature"), toCharArray("Hellooo"));
Serial.println("Published");
}
char* toCharArray(String str) {
return &str[0];
}
void onMessageArrived(char* t, byte* m, unsigned int length) {
topic = String(t);
message = String((char*)m);
message = message.substring(0, length);
if (message == "HELLO") {
Serial.println("Hello client");
client.publish(toCharArray(prefix + "/server"), toCharArray("HELLO"));
Serial.println("Hello server");
}
}
boolean reconnect() {
while (WiFi.status() != WL_CONNECTED){
ESP.wdtFeed();
ESP.wdtDisable();
delay(500);
Serial.print(".");
delay(500);
cnt--;
if(cnt==0){
ESP.wdtDisable();
#ifdef SOFT_WATCHDOG
ESP.wdtEnable(0);
#endif
while(1);
}
}
delay(1000);
if (client.connect(clientID, mqttuser, mqttpass, toCharArray(prefix + "/Will"), 1, true, toCharArray("Disconnected"), true)) {
client.setCallback(onMessageArrived);
Serial.print("***Disconnected***");
return client.connected();
}
}