NodeMCU Arduino framework UDP Packet sending problem - arduino

I've been trying to send an UDP Packet from readed ADC Value via UDP to any terminal. Unfortunately, I can't get any input on UDP terminal from the ESP directly. Here's the code:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <string>
using namespace std;
//////////DEFINITIONS/////////////
#define ADC A0 //macrodef for reading the adc
///////////WiFi&UDP CONFIG///////////////////
WiFiUDP UdpPilot; // UDP Object for pilot
char udpSendingPacket[255] = "Hello there!"; //tab to send packet to board
unsigned int Port = 4210; // UDP port to send to
IPAddress destin_IP(192, 168, 0, 197); //IP Adress to send to
const char *softApName = "xxxxxxxx";
const char * pass = "xxxxxxxx";
/////////////////VARIABLES////////////////
int adcValueReaded = 0; //val to read from ADC
char adcToString[255];
void setup() {
WiFi.mode(WIFI_STA); //Station mode on WiFiUdp
Serial.begin(9600); //Begin serial
Serial.println(WiFi.begin( softApName, pass ) ? "WiFi Connection Ready!" : "WiFi Connection Failed!");
Serial.println(UdpPilot.begin(Port) ? "Port listening Ready!" : "Port listening Failed!");
}
void loop() {
adcValueReaded = analogRead(ADC);
if(adcValueReaded >= 500){
itoa(adcValueReaded, adcToString, 10);
UdpPilot.beginPacket(destin_IP, Port);
UdpPilot.write(adcToString);
UdpPilot.endPacket();
Serial.println(adcToString);
Serial.println(adcValueReaded);
}
yield();
}
Looking forward for your help.

Related

How to display the local IP of nodemcu esp8266 in Serial using arduino

This is the Serial of my arduino it doesn't show anything what am I doing wrong in my code?
Arduino Code
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char* host = "WiFi_Robot4_NodeMCU";
const char* ssid = "EarthQuakeBot";
ESP8266WebServer server(80);
void setup() {
IPAddress ip;
Serial.begin(115200);
ip = WiFi.localIP();
Serial.println(ip);
delay(100);
// Connecting WiFi
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid);
// Starting WEB-server
server.on ( "/", HTTP_handleRoot );
server.onNotFound ( HTTP_handleRoot );
server.begin();
}
void loop() {
}
How to display the localIP of nodemcu esp8266 in Serial using Arduino?
The code works without delay, just copy it (SoftwareSerial is commented out and a text line as print support is added, never use the delay with the Esps):
//#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char* host = "WiFi_Robot4_NodeMCU";
const char* ssid = "EarthQuakeBot";
ESP8266WebServer server(80);
void HTTP_handleRoot() {
// Some code here
}
void setup() {
IPAddress ip;
Serial.begin(115200);
ip = WiFi.localIP();
Serial.print("This is my ip: ");
Serial.println(ip);
// Connecting WiFi
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid);
// Starting WEB-server
server.on ( "/", HTTP_handleRoot );
server.onNotFound ( HTTP_handleRoot );
server.begin();
}
void loop() {
}
and displays (oh wonder) the following:
This is my ip: 0.0.0.0
If using the nodeMCU in AP_Mode (as an access point) you have to assign all the relevant data yourself.Thereis noself assign function, you do it like:
Serial.begin(115200);
.....
WiFi.softAPConfig(apIP, apGateway, apSubnet);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid);
.........
ip = WiFi.localIP();
Serial.print("This is my ip: ");
Serial.println(ip);
Work through the library examples and follow a good tutorial like:
https://tttapa.github.io/ESP8266/Chap01 - ESP8266.html
Hope this helps you and other beginners

two ESP8266 to communicate with udp using WiFiESP.h

guys, i'd like to use esp8266 module and wifiesp.h. I wanna make two esp8266 modules to communicate through udp protocol. To use it, i found udp communication example. But I wonder if the example consist receive codes and send codes. Can you help me to find receive code and send code??
Is there any other send and receive code for UDP protocol??
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif
char ssid[] = "Twim"; // your network SSID (name)
char pass[] = "12345678"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
unsigned int localPort = 10002; // local port to listen on
char packetBuffer[255]; // buffer to hold incoming packet
char ReplyBuffer[] = "ACK"; // a string to send back
WiFiEspUDP Udp;
void setup() {
// initialize serial for debugging
Serial.begin(115200);
// initialize serial for ESP module
Serial1.begin(9600);
// initialize ESP module
WiFi.init(&Serial1);
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}
// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network
status = WiFi.begin(ssid, pass);
}
Serial.println("Connected to wifi");
printWifiStatus();
Serial.println("\nStarting connection to server...");
// if you get a connection, report back via serial:
Udp.begin(localPort);
Serial.print("Listening on port ");
Serial.println(localPort);
}
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
Serial.println("Contents:");
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

Unintentional strange characters added to packets during udp communication in Arduino

Stackoverflow!
Unusual strange characters are added to packets during udp communication in Arduino.
Hi. Stack overflow. I encountered problems that I could not solve while using Udp with Arduino. I have looked up a lot of information to solve this problem. I also tested various cases. But I can not solve it.
The problem occurs from the 24th byte of the packet. The characters exceeding 23 characters are converted into strange characters and the subsequent sentences are not output. Is the packet transmission of udp communication limited to 24 bytes? If so, I am glad, but I want to know how to solve it. Please help me.
The test environment is as follows. Two Arduino are connected via a LAN cable. In addition, the following source code has been uploaded to Arduino. The serial monitor is as follows.
TX serial monitor
.
.
17:46:31.521 -> Sending UDP message
17:46:32.516 -> Sending UDP message
17:46:33.514 -> Sending UDP message
17:46:34.519 -> Sending UDP message
17:46:35.515 -> Sending UDP message
17:46:36.510 -> Sending UDP message
RX serial monitor
17:38:51.664 -> 010010010101001010101001K;⸮ <----------problem
17:38:52.662 -> Received packet of size 31
17:38:52.662 -> From 192.168.1.251, port 5678
17:38:52.662 -> Contents:
17:38:52.662 -> 01001001010100101010100j⸮ <------- problem
17:38:53.663 -> Received packet of size 31
17:38:53.663 -> From 192.168.1.251, port 5678
17:38:53.663 -> Contents:
17:38:53.663 -> 010010010101001010101001;ے <------------problem
17:38:56.770 -> Received packet of size 31
---------Source Code-------------
///////////TX
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#define MSG_INTERVAL 1000
// network parameters
byte mac[] = {
0x90, 0xA2, 0xDA, 0x0E, 0x05, 0x04}; // ethernet interface MAC address
IPAddress localIp(192, 168, 1, 251); // local ip address
IPAddress destIp(192, 168, 1, 15); // destination ip address
unsigned int port = 5678; // destination port
// EthernetUDP to send and receive messages.
EthernetUDP Udp;
// message string
char message[] = "0100100101010010101010010101010";
// timing
//unsigned long previousLedMillis;
//unsigned long ledInterval;
unsigned long previousSendMillis;
unsigned long sendInterval;
// setup the arduino and shields
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start ethernet and udp
Ethernet.begin(mac,localIp); // static ip version
// open UDP port
Udp.begin(port);
// show the local ip address (useful for dhcp)
Serial.print("Local IP: ");
Serial.println(Ethernet.localIP());
// initialize send interval
sendInterval = MSG_INTERVAL;
}
// do tasks
void loop() {
// check if udp string has to be sent
if(millis() - previousSendMillis >= sendInterval) {
sendMessage();
}
}
// send udp string
void sendMessage() {
Serial.println("Sending UDP message");
// store current millis
previousSendMillis = millis();
// send udp message
Udp.beginPacket(destIp, port);
Udp.write(message);
Udp.endPacket();
}
/////RX
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 15);
IPAddress remIp(92, 168, 1, 176);
unsigned int localPort = 5678; // local port to listen on
// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
void setup()
{
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);
pinMode(5, OUTPUT);
Serial.begin(115200);
Serial.print("Local IP: ");
Serial.println(Ethernet.localIP());
}
void loop()
{
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i =0; i < 4; i++)
{
Serial.print(remote[i], DEC);
if (i < 3)
{
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
//Udp.read(packetBuffer,1024);
Serial.println("Contents:");
Serial.println(packetBuffer);
//for (int i=0;i<packetSize;i++){
// Serial.print(packetBuffer[i]);
//}
//Serial.print('\n');
}
}
yes you have right, some problem with length 24!!
if you read inside the EthernetUDP.h file, you will see:
#define UDP_TX_PACKET_MAX_SIZE 24
so if you want use more characters, dont use this const, choose your personal size.
change
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
to
char packetBuffer[50];
or use another define:
#define UDP_MAX_BUFFER 50 //for example
char packetBuffer[UDP_MAX_BUFFER];

Sending sensor data via UDP

I'm trying to send sensor data via UDP. At the moment I'm struggling with the "packing" of the UDP packets. It says "incomingData" is not declared when I try to send it.
I would appreciate any kind of advice.
Code below.
Thank you :)
//Version 1.012
//necessary libraries
#include <SPI.h>
#include <Ethernet2.h>
#include <EthernetUdp2.h>
//Pin settings
#define CTD 19
//Network Settings
byte mac[] = { 0x90, 0xA2, 0xDA, 0x10, 0xEC, 0xAB }; //set MAC Address Ethernet Shield (Backside)
byte ip[] = { XXX, XXX, X, X }; //set IP-Address
byte gateway[] = { XXX, XXX, X, X }; //set Gateway
byte subnet[] = { 255, 255, 255, 1 }; //set Subnetmask
//local UDP port to listen on
unsigned int localPort = 4000;
//Recipient IP
IPAddress RecipientIP(127, 0, 0, 1);
//Recipient UDP port
unsigned int RecipientPort = 4444;
//Buffer for sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
//EthernetUDP instance
EthernetUDP Udp;
void setup()
{
//Start Ethernet
Ethernet.begin(mac, ip);
//Start UDP
Udp.begin(localPort);
//for debug only
Serial.begin(9600);
//Serial baud rate for CTD
Serial1.begin(1200);
//Version 1.012
Serial.print("Version 1.012");
//CTD
pinMode(CTD, INPUT);
}
void loop()
{
//If CTD is sending
if (Serial1.available())
{
//read incoming data
int incomingData = Serial1.read();
//for debug only
Serial.print("Data: ");
Serial.println(incomingData, BIN);
}
//Send UDP packets
int packetSize = Udp.parsePacket();
if (packetSize) {
// read the packet into packetBufffer
Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
// send to the IP address and port
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(incomingData);
Udp.endPacket();
}
}
In your code you have declared incomingData as int inside void loop () function inside if (Serial1.available()) .
But if the above if loop fails the incomingData will not be declared and say packetsize is greater than zero ( packet available) then if (packetSize) segment will be executed.Thus incomingData is not declared but it is used .That's why you get the error you stated.

Not able to Receive subscribed Message with PubSubClient.h in Arduino Uno R3

#include "SPI.h"
#include “WiFiEsp.h”
#include <WiFiEspClient.h>
#include “SoftwareSerial.h”
#include <PubSubClient.h>
#include <WiFiEspUdp.h>
float temp=0;
int tempPin = 0;
int isClientConnected = 0;
char data[80];
char ssid[] = “SSID”; // your network SSID (name)
char pass[] = “PASSWORD”; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio’s status
char deviceName = “ArduinoClient1”;
IPAddress server(xxx,xxx,xxx,xxx); //MQTT server IP
IPAddress ip(192,168,43,200);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(“Message arrived [“);
Serial.print(topic);
Serial.print(“] “);
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println("-");
}
// Emulate Serial1 on pins 6/7 if not present
WiFiEspClient espClient;
PubSubClient client(espClient);
SoftwareSerial Serial1(6,7); // RX, TX
void setup(){
Serial.begin(9600);
Serial1.begin(9600);
WiFi.init(&Serial1);
WiFi.config(ip);
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true);
}
while ( status != WL_CONNECTED) {
Serial.print("Attemptingonnect to WPA SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
Serial.print("WiFius : ");
Serial.println(status);
}
//connect to MQTT server
client.setServer(server, 1883);
client.setCallback(callback);
isClientConnected = client.connect(deviceName);
Serial.println("+++++++");
Serial.print("isClientConnected;
Serial.println(isClientConnected);
Serial.print("client.state");
Serial.println(client.state());
if (isClientConnected) {
Serial.println("Connected…..");
client.publish("status","Welcome to ISG");
client.subscribe("isg/demoPublish/rpi/ardTempWarn");
//Not able to recieve for this subscribed topic on Arduino Uno Only if I
//print it returns 1
}
}
void loop() {
temp = (5.0 * analogRead(tempPin) * 100.0) / 1024;
Serial.print(" temp : " );
Serial.println(temp);
Serial.print("client.connected);
Serial.println(client.connected());
if (!client.connected()) {
reconnect();
}
client.publish("isg/demoPublish/ard1/tempLM35",String(temp).c_str());
// able to receive data at other
// clients like RPI,Web using Mosquitto broker
client.loop();
delay(5000);
}
void reconnect() {
Serial.println("Device is trying to connect to server ");
while (!client.connected()) {
if (client.connect(deviceName)) {
} else {
delay(5000);
}
}
}
I am using Arduino Uno R3 and ESP8266-01 as wifi connector.
I have to read temperature data and send to Mosquitto ,MongoDB and Raspberry Pi and receive a data on specific condition for that i have subscribed a topic in Arduino.
I am able to receive data from Arduino to all other clients but I am not able to receive data on Subscribed topic in Arduino. But all other deviced like MongoDB able to receive data from Raspberry Pi.
I have used Arduino Uno R3, ESP8266-01 devices and liberary for to connect and send/receive data WiFiEsp.h, WiFiEspClient.h, WiFiEspUdp.h, SoftwareSerial.h, PubSubClient.h
client.subscribe("topic"); returns 1
Also callback function implemented but not able to get call.
So can any one help me why I am not getting subscribed topic message in Arduino?
I have follow https://sonyarouje.com/2016/03/15/mqtt-communication-with-arduino-using-esp8266-esp-01/#comment-111773
The library that you are using has bug in callback hence it would be better that you use other library my preference would be
https://github.com/vshymanskyy/TinyGSM
this library include almost all variants of SIM800(A,C,L,H,808), variants of SIM900(A,D,908,968), ESP8266 (mounted on arduino), Ethernet shield etc. It worked for me, as same issue bugged me for almost 1-2 weeks but latter was able to receive all subscribed message irrespective of mode of communication(GSM,Ethernet,WiFi)

Resources