ESP8266 has problems receiving udp packets - arduino

My WeMos D1 Mini is running a script that is supposed to perform certain actions if it receives certain strings in udp packets.
It works most of the time, but sometimes it just doesn't respond to anything.
Usually it's enough to just wait a few minutes or send the packet a couple of times. My guess is that it might go into some kind of deep sleep. Sometimes the only thing that helps is to restart it.
I tried implementing a watchdog but that didn't really work (but that's a separate issue) and i'm not sure if it would even solve the problem.
I'm sending the packets through Netcat and the WiFi strength is ok (but not great).
Everything is on the local network.
Please take a look at my code and check it for mistakes/improvements.
#include <ESP8266WiFi.h>
#include <WiFiUDP.h>
#define SSID "XXX"
#define PASSWORD "XXX"
#define PORT XXX
WiFiUDP udpServer;
char MESSAGE[] = "message";
void setup() {
Serial.begin(9600);
WiFi.mode(WIFI_STA);
WiFi.begin(SSID, PASSWORD);
wifiStrength();
udpServer.begin(PORT);
delay(100);
}
void wifiStrength(){
if (WiFi.status() != WL_CONNECTED) {
Serial.println("no wifi, reconnecting...");
delay(3000);
WiFi.begin(SSID, PASSWORD);
}
long rssi = WiFi.RSSI();
Serial.print("connected, RSSI:");
Serial.println(rssi);
}
void loop() {
if (udpServer.parsePacket()) {
char receiveBuffer[WIFICLIENT_MAX_PACKET_SIZE + 1];
udpServer.read(receiveBuffer, sizeof(receiveBuffer) - 1);
if (strstr(receiveBuffer, MESSAGE)) {
Serial.println("do stuff...");
}
}
}

Related

ESP32 was connecting earlier but is not connecting to WiFi now with the same code

I'm doing a project where I have to connect to a WiFi network. So, I've used this code for ESP32 to connect to a WiFi network -
#include <Arduino.h>
#include <WiFi.h>
void setup() {
Serial.begin(115200);
WiFi.begin("XYZXYZ", "asdfghjkl");
// Wait for WiFi to be connected
uint32_t notConnectedCounter = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.println("Wifi connecting...");
notConnectedCounter++;
if(notConnectedCounter > 50) { // Reset board if not connected after 5s
Serial.println("Resetting due to Wifi not connecting...");
ESP.restart();
}
}
Serial.print("Wifi connected, IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// put your main code here, to run repeatedly:
}
The code I mentioned above worked well but for some reason, it is not working now. Now when I power the ESP32, it gives out something like (or similar to) this-
}⸮~⸮}⸮n~⸮~ֶ⸮}⸮⸮⸮n⸮~n⸮⸮]⸮⸮⸮⸮⸮⸮D⸮b⸮⸮z⸮}⸮⸮⸮1]⸮⸮}⸮⸮~⸮⸮|⸮⸮~}⸮]⸮}⸮=~]⸮⸮]⸮⸮]⸮]⸮⸮n⸮⸮ ֎UvHX⸮.,⸮⸮a⸮⸮⸮]⸮⸮>]⸮>⸮]⸮]⸮n>⸮⸮⸮>>⸮]⸮⸮>]⸮]⸮⸮6⸮
What can I do to solve this?
Make sure your Serial.begin(11520) speed parameter is the same as Serial Monitor speed parameter value.

MQTT Mosquitto and two ESP8266

My problem:
I have a Raspberry Pi, and I have installed the Mosquitto MQTT broker on it. My objective is to make 2 MQTT clients communicate over the Mosquitto broker, so I have installed the code below on two ESP8266 (WeMos D1 mini)
and I have created this MQTT command: mosquitto_pub -h 192.168.1.20 -t /wassim/led -m "on".
So, when I connect only one ESP client, I see the message "on" in the serial monitor. But when I connect the second ESP client, I can't see any message on the serial monitor... (But if on the terminal of the Raspberry, then I can see everything. On the clients I can't see anything). The code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <MQTTClient.h>
float temp;
float lm;
String aw="";
const char* host = "192.168.1.20";
const char* ssid = "THOMSON1121";
const char* password = "Wassim";
WiFiClient net;
MQTTClient mqtt;
void connect();
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println("Booting...");
WiFi.mode(WIFI_AP_STA);
WiFi.begin(ssid, password);
mqtt.begin(host, net);
connect();
if(mqtt.subscribe("/wassim/led")) {
Serial.println("Subscription Valid !");
}
Serial.println("Setup completed...");
}
void loop() {
if (!mqtt.connected()) {
connect();
}
mqtt.loop();
delay(3000);
}
void connect() {
while(WiFi.waitForConnectResult() != WL_CONNECTED) {
WiFi.begin(ssid, password);
Serial.println("WiFi connection failed. Retry.");
}
Serial.print("Wifi connection successful - IP-Address: ");
Serial.println(WiFi.localIP());
while (!mqtt.connect(host)) {
Serial.print(".");
}
Serial.println("MQTT connected!");
}
void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
Serial.print("incoming: ");
Serial.print(topic);
Serial.print(" - ");
Serial.print(payload);
Serial.println();
}
The change from one client to another is if(mqtt.subscribe("/wassim/tmp")).
MQTT is a 'message bus' application....in order to have multiple 'subscribers' receive the same message that is being put on the bus by a 'publisher', they both have to subscribe to the same topic...or at least enough of the topic + wildcard...in order to get sent that published message. You only have one of your two clients listening to the topic that your 'mosquitto_pub' command is sending out. For it to receive, you either specify the full topic (mqtt.subscribe("/wassim/led")), or a wildcard to pick up all the 'wassim' messages sent out (mqtt.subscribe("/wassim/#")).

Set parameters of ESP8266 through Arduino

The problem is that I want to execute the code below, but when ESP8266 is shut down, then I start it again, everything is gone.
So, is there a solution that I can make this ESP8266 work the same controlled by my Arduino Uno.
My program blow is to control the GPIO2 through web browser.
Thanks a lot to all of you!!
My Codes:
#include <ESP8266WiFi.h>
#include <aREST.h>
// Create aREST instance
aREST rest = aREST();
// WiFi parameters
const char* ssid = "Protect Big Dragon 4";
const char* password = "18717772056";
// The port to listen for incoming TCP connections
#define LISTEN_PORT 80
// Create an instance of the server
WiFiServer server(LISTEN_PORT);
void setup(void)
{
// Start Serial
Serial.begin(115200);
// Give name and ID to device
rest.set_id("2");
rest.set_name("lamp_control");
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
// Handle REST calls
WiFiClient client = server.available();
if (!client) {
return;
}
while(!client.available()){
delay(1);
}
rest.handle(client);
}
So your ESP8266 loses your code when it is rebooted.
Sounds like the memory is faulty.
Try a different ESP8266 and let us know what occurs.

MQTT on Arduino not working

I'm using Arduino Uno and Wi-Fi shield. I'm trying to implement MQTT protocol for communication and I tried two libraries for Arduino. First one is Knolleary's PubSubClient: http://pubsubclient.knolleary.net/ . I modified original example a little bit to use WiFi module instead of ethernet. Sending works but not every time (sometimes, the message is sent and sometimes not). But receiving via callback function doesn't work at all.
Here is my code:
/*
Basic MQTT example with Authentication
- connects to an MQTT server, providing username
and password
- publishes "hello world" to the desired topic
- subscribes to the desired topic
*/
#include <WiFi.h>
#include <PubSubClient.h>
char ssid[] = "[DELETED]"; // your network SSID (name)
char pass[] = "[DELETED]"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
// Update these with values suitable for your network.
IPAddress server(85, 119, 83, 194);
WiFiClient WifiClient;
void callbackFunc(char* topic, byte* payload, unsigned int length) {
Serial.println("test message received");
/*Serial.println();
Serial.println("=============== MESSAGE RECEIVED ================================");
Serial.print("Topic: ");
Serial.print(topic);
Serial.println();
Serial.println((const char *) payload);*/
}
PubSubClient client(server, 1883, callbackFunc, WifiClient);
void setup()
{
delay(2000);
Serial.begin(9600);
Serial.println("Starting....");
Serial.println("Initializing Wifi...");
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
}
// attempt to connect using WPA2 encryption:
Serial.println("Attempting to connect to WPA network...");
status = WiFi.begin(ssid, pass);
// if you're not connected, stop here:
if (status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// If you are connected, print out success message
else
Serial.println("Connected to network");
if (client.connect("arduinoClient")) {
Serial.println("Connected to server! Sending message...");
client.publish("randy/test","hello world");
client.subscribe("randy/test");
Serial.println("Sent!");
}
else
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
}
void loop()
{
client.loop();
delay(1000);
if (!client.connected())
{
if(!client.connect("arduinoClient"))
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
else
{
client.subscribe("randy/test");
Serial.println("INFO: reconnected!");
}
}
}
As you can see, I'm using http://test.mosquitto.org/ for testing. I'm also using mosquitto on Ubuntu where I'm subscribed to the same topic and from where (another terminal window) I'm publishing to the same topic. Here is the picture of both windows:
As you can see, "hello world" message from Arduino is received successfully (but not every time), and when I publish "bla" message from another window, it's successfully received on mosquitto (on image) but NOT on Arduino. Is there something wrong with my code or? I found similar problem here: Arduino Knolleary PubSubClient will publish messages but can't receive them
It's worth noticing that it keeps getting reconnected all the time. As you can see, in loop() I put a part of code which will connect and subscribe again if connection is lost. On Serial Monitor I get "INFO: Reconnected!" message every 2-3 seconds.
Adafruit library
Then I tried the Adafruit library, but it won't connect at all! I tried with test.mosquitto.org and with io.adafruit.com from their example, but I just keep getting "Connection failed!" error. I tried making many changes and combinations but no luck so far. Once I managed to get "Failed to subscribe" instead of "Connection failed" but this was only once and next time with the same code I get "Connection failed" again.
Here's my code:
/*
Basic MQTT example with Authentication
- connects to an MQTT server, providing username
and password
- publishes "hello world" to the topic "outTopic"
- subscribes to the topic "inTopic"
*/
#include <WiFi.h>
#include <PubSubClient.h>
char ssid[] = "[DELETED]"; // your network SSID (name)
char pass[] = "[DELETED]"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
// Update these with values suitable for your network.
IPAddress server(85, 119, 83, 194);
WiFiClient WifiClient;
void callbackFunc(char* topic, byte* payload, unsigned int length) {
Serial.println("test message received");
/*Serial.println();
Serial.println("=============== MESSAGE RECEIVED ================================");
Serial.print("Topic: ");
Serial.print(topic);
Serial.println();
Serial.println((const char *) payload);*/
}
PubSubClient client(server, 1883, callbackFunc, WifiClient);
void setup()
{
delay(2000);
Serial.begin(9600);
Serial.println("Starting....");
Serial.println("Initializing Wifi...");
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
}
// attempt to connect using WPA2 encryption:
Serial.println("Attempting to connect to WPA network...");
status = WiFi.begin(ssid, pass);
// if you're not connected, stop here:
if (status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// Ff you are connected, print out success message
else
Serial.println("Connected to network");
if (client.connect("arduinoClient")) {
Serial.println("Connected to server! Sending message...");
client.publish("randy/test","hello world");
client.subscribe("randy/test");
Serial.println("Sent!");
}
else
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
}
void loop()
{
client.loop();
delay(1000);
if (!client.connected())
{
if(!client.connect("arduinoClient"))
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
else
{
client.subscribe("randy/test");
Serial.println("INFO: reconnected!");
}
}
}
Any idea what's wrong with those libraries or my code?
As mentioned in the comments
When using example code on public brokers make sure you change the client id to something random as the odds of clashing with somebody else are pretty high. Because client ids have to be unique else they will cause a reconnection storm

Arduino Wi-Fi shield - can't send a UDP packet

I'm trying to send information from the arduino board to my computer through the Wi-Fi network.
for my project's purposes it has to be a UDP connection
I use the "Send and Receive UDP String" example (http://arduino.cc/en/Tutorial/WiFiSendReceiveUDPString)
with a few changes:
#include <SPI.h>
#include <WiFi.h>
#include <WiFiUdp.h>
int status = WL_IDLE_STATUS;
char ssid[] = "itay_net"; // your network SSID (name)
char pass[] = "0527414540"; // your network password (use for WPA, or use as key for WEP)
unsigned int localPort = 50505; // local port to listen on
IPAddress remote_ip(192, 168, 1, 100);
unsigned int remote_port = 50505;
char ReplyBuffer[] = "acknowledged"; // a string to send back
WiFiUDP Udp;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// 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);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the data:
Serial.print("You're connected to the network");
delay(10000);
printWifiStatus();
Serial.println("\nStarting connection to server...");
// if you get a connection, report back via serial:
Udp.begin(localPort);
}
void loop() {
int bite_send;
Udp.beginPacket(remote_ip, remote_port);
bite_send = Udp.write("hello");
Udp.endPacket();
Serial.println("the packet was sent");
Serial.println(bite_send);
delay(1000);
}
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");
}
It compiles and connects to the network just fine.
the only problem is that I can't tell if the packet was sent because I see no trace of it on Wireshark.
I also wrote a socket on java that listens to the port (50505) and should display the message from the packet, but it didn't work either.
(I can copy the java code here but i can assure you that it is not the problem 'cause I tested it with a different java server and it worked, so the problem should be on the Arduino side)
a few details to narrow it down:
I believe the "remote ip" is correct but even if it isn't - I still should have seen it in the Wireshark, so it can't be the problem.
I should mention that the Wi-Fi shield works, I successfully sent pings and ran other examples (such as SimpleWebServerWifi).
I'm using an original Arduino Uno R3 board and an original Wi-Fi shield.
The arduino IDE is the newest version.
I updated the Wi-Fi shield with the newest update I found on GitHub.
I also ran the same "Send and Receive UDP String" code (with the necessary changes) on my Ethernet shield and it did work.
I don't know what else to try - please help.
any help will be appreciated.
Itay
I dont think you have a reply buffer packet. google arduino wifisendrecieve and you will see the example they have that has a reply packet labeled as 'acknowledged'. Hope this helps

Resources