Well I've already done UDP send/receive many times. But now I'm stucked.
Maybe I'm missing some dumb mistake that's in the code or maybe there's problem in the libraries that I'm using. Anyway if there's someone who could help please take a look.
Code of the receiver
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char* ssid = "M3-L7";
const char* password = "mySmartChoice";
unsigned int localPort = 2390;
char packetBuffer[255];
WiFiUDP Udp;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}
Udp.begin(localPort);
}
void loop() {
delay(10);
if (Udp.parsePacket()) {
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
Serial.println(packetBuffer);
}
}
}
The code of the sender/accesss point
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char *ssid = "M3-L7";
const char *password = "mySmartChoice";
unsigned int localPort = 2390;
WiFiUDP Udp;
void setup() {
delay(1000);
Serial.begin(115200);
WiFi.softAP(ssid, password);
Udp.begin(localPort);
}
void loop() {
Udp.beginPacket("192.168.4.1", localPort);
Udp.write("Hello");
Udp.endPacket();
delay(10);
}
Well I'd expect "Hello" to be printed repeatedly :D.. they reach the point where they connect but that's over.
You might want to try adding the following to your receiver just before Wifi.begin:
WiFi.mode(WIFI_STA);
This sets the Wifi up as a station (client) rather than an access point. Your code isn't doing this so it's difficult to be certain what is going on, especially if you are re-using a device that was previously programmed to run in AP mode.
Related
I'm working on getting my ESP32 board (also Arduino R3 & Nano) to connect to a HiveMQ broker, but it will not connect. I've tried various ports, different brokers, disabling ad blocking on my network, etc., but nothing seems to make a difference.
#include <Arduino.h>
#include <ArduinoJson.h>
#include <WiFi.h>
#include <PubSubClient.h>
void MQTT_callback(char* topic, byte* message, unsigned int length);
void setup() {
Serial.begin(115200);
while (!Serial);
delay(250);
Serial.println("setup beginning");
Serial.print("Connecting to WiFi...");
WiFi.begin("...", "...");
for (int i=0; i<30 && WiFi.status() != WL_CONNECTED; ++i) {
Serial.print(".");
delay(250);
}
if (WiFi.status() != WL_CONNECTED) {
Serial.println(" failed");
Serial.println("Oh no, no Wifi!? You're back in 1980! That's horrible...");
return;
} else {
Serial.println(" connected!");
}
WiFiClient espClient;
PubSubClient client(espClient);
const char* MQTT_URL = "somereallylongstring.s2.eu.hivemq.cloud";
const int MQTT_PORT = 8883;
const char* MQTT_uid = "...";
const char* MQTT_pwd = "...";
const String MQTT_client = "esp32-client-" + WiFi.macAddress();
client.setServer(MQTT_URL, MQTT_PORT);
client.setCallback(MQTT_callback);
if (!client.connected()) {
Serial.println("Connecting to MQTT broker with client '" + MQTT_client + "'...");
for (int i=0; i<10 && !client.connected(); ++i) {
if (client.connect(MQTT_client.c_str(), MQTT_uid, MQTT_pwd)) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Connection to MQTT broker failed: ");
#define C(x) case (x): Serial.println(#x); break;
switch (client.state()) {
C(MQTT_CONNECTION_TIMEOUT)
C(MQTT_CONNECTION_LOST)
C(MQTT_CONNECT_FAILED)
C(MQTT_DISCONNECTED)
C(MQTT_CONNECTED)
C(MQTT_CONNECT_BAD_PROTOCOL)
C(MQTT_CONNECT_BAD_CLIENT_ID)
C(MQTT_CONNECT_UNAVAILABLE)
C(MQTT_CONNECT_BAD_CREDENTIALS)
C(MQTT_CONNECT_UNAUTHORIZED)
}
#undef C
}
}
}
if (client.connected()) {
const char* topic = "/sensors/sean/salt_tank";
StaticJsonDocument<MQTT_MAX_PACKET_SIZE> doc;
doc["ts"] = "2023-01-15 20:24:00";
doc["temp"] = 82.1;
doc["tds"] = 821;
doc["ph"] = 7.6;
String output;
serializeJson(doc, output);
Serial.println("Publishing message to " + String(topic) + output);
client.publish(topic, output.c_str());
}
Serial.println("setup complete!");
}
void loop() {
}
void MQTT_callback(char* topic, byte* message, unsigned int length) {
String msg = "";
for (int i=0; i<length; ++i)
msg += (char)message[i];
Serial.println("Message arrived on topic " + String(topic) + ":");
Serial.println(msg);
}
Here's the output:
22:11:00.629 > setup beginning
22:11:00.631 > Connecting to WiFi........ connected!
22:11:02.001 > Connecting to MQTT broker with client 'esp32-client-08:3A:F2:B8:8B:CC'...
22:11:17.512 > Connection to MQTT broker failed: MQTT_CONNECTION_TIMEOUT
22:11:32.670 > Connection to MQTT broker failed: MQTT_CONNECTION_TIMEOUT
I don't know if this makes a difference, but I'm using an ARM MacBook. I don't know if the difference in libraries could be causing an issue or not. Thanks!
I have been trying to learn how to get a subscribed message to respond to the message content but information is sparse for the arduino framework.
Many attempts have failed,,no clue how to debug this without a decoder board.
using mosquito broker on windows 10 as local server. Sketch will log on to wifi and mqtt and pub and sub OK. callback does not parse "PAYLOAD". I am having trouble understanding callback syntax, please advise.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <string.h>
#include <stdio.h>
// WiFi
const char *ssid = ""; // Enter your WiFi name
const char *password = ""; // Enter WiFi password
// MQTT Broker
const char *mqtt_broker = "192.168.1.2";
const char *topic = "alert";
const char *mqtt_username = "";
const char *mqtt_password = ";
const int mqtt_port = "";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
pinMode(2, OUTPUT);
// Set software serial baud to 115200;
Serial.begin(9600);
// connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
//connecting to a mqtt broker
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp8266-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the local mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Local mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// publish and subscribe
client.publish(topic, "Hello World");
client.subscribe(topic);
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
if (payload[0] == 49) // Message "1" in ASCII (turn outputs ON)
{
digitalWrite(2, LOW); // LED is active-low, so this turns it on
} else if (payload[0] == 48) // Message "0" in ASCII (turn outputs OFF)
{
digitalWrite(2, HIGH); // LED is active-low, so this turns it off
} else {
Serial.println("no input");
}
}
void loop() {
client.loop();
}
Output--
Connecting to WiFi..
8:46:46.600 -> Connected to the WiFi network
8:46:46.632 -> The client esp8266-58:BF:25:D9:B9:40 connects to the local mqtt broker
8:46:46.696 -> Local mqtt broker connected
I’m trying to build a feeder machine on a pig farm by using the Infrared photoelectric switch Sensor E18-D80NK to control relay then send notifications to line and mqtt broker when it’s working. I have been testing for 2 days, it’s working normal, but third day, it’s not responding then I just press reset so it’s working again.
I’m wondering it may cause by board cause it happen only one of four boards that I tasted or may be my code cause I was confused why output to line send “connected” so many times it’s should sent only one time when connected to wifi, so I’m not sure pls help.
Question
Why board not responding after working normal for a while.
Why out output to line send "connected" more than one cause I put in void setup()
Pictures
Last line output since working
All code
extra library line notification library
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <TridentTD_LineNotify.h>
const char* ssid = "Artnaseaw-2.4G";
const char* password = "0812667120";
const char* mqttUser = "****";
const char* mqttPassword = "****";
const char* mqttServer = "******";
const int mqttPort = *****;
const char* linetoken = "********";
long lastMsg = 0;
String DataString;
int lastL=0;
WiFiClient espClient;
PubSubClient client(espClient);
const int ACTION = D8;
const int SENSOR = D2;
const char* host = "maker.ifttt.com";
const char *privateKey = "******";
const char *event = "*****";
String value1, value2;
String postData = "";
String MachineID="A01";
void setup() {
Serial.begin(115200);
pinMode(SENSOR, INPUT_PULLUP);
pinMode(ACTION, OUTPUT);
digitalWrite(SENSOR, LOW);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("test", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.subscribe("command");
LINE.setToken(linetoken);
LINE.notify("Connected");
Serial.println("line send connected");
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void loop() {
client.loop();
delay(5000);
int sensorValue = digitalRead(SENSOR);
long now = millis();
if (now - lastMsg > 60000)
{
lastMsg = now;
int sensorValue = digitalRead(SENSOR);
if (sensorValue == LOW){
Serial.println(" === Obstacle detected");
Serial.print(" realy OFF ");
digitalWrite(ACTION,LOW);
} else {
LINE.notify("send data to line ---working");
Serial.println(" === All Clear");
Serial.println(" relay ON ");
digitalWrite(ACTION,HIGH);
sendMessageToIFTTT();
sendSensorToMQTT();
}
}
}
void sendSensorToMQTT(){
char msg[100];
int count = 1;
DataString = "e18,location=test detest="+String(count);
DataString.toCharArray(msg, 100);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("e18", msg);
}
void sendMessageToIFTTT(){
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
String url = "/trigger/";
url += event;
url += "/with/key/";
url += privateKey;
value1 = "Worked";
value2 = "1";
genJSonObject();
Serial.print("Requesting URL: ");
Serial.println(url);
Serial.println(postData);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n");
client.println("Content-Type: application/json");
client.print("Content-Length: ");
client.println(postData.length());
client.println();
client.println(postData);
client.println("Connection: close\r\n\r\n");
while (client.connected())
{
if (client.available())
{
String line = client.readStringUntil('\r');
Serial.print(line);
} else {
// No data yet, wait a bit
delay(50);
};
}
}
void genJSonObject()
{
postData = "{";
postData.concat("\"value1\":\"");
postData.concat(value1);
postData.concat("\",");
postData.concat("\"value2\":\"");
postData.concat(value2);
postData.concat("\"}");
}
Try to connect to another mqtt broker and see if it connects more than once in there too. If it happens the problem might be in the sketch. Otherwise, the cause may be with the IFTTT service.
I'm trying to send text over the serial monitor using RadioHead ASK. Text input from the serial monitor is not sent to the receiver. I have read up on C++ theory with char arrays and pointers... it's not computing in my head :). How can *msg exist without first declaring char msg? Please see the sample below. It would be great if you could explain the theory with any sample solution. Thank you for your help!
void setup() {
Serial.begin(9600); // Debugging only
if (!driver.init())
Serial.println("init failed");
else
Serial.println("TX");
}
void loop() {
const char *msg = Serial.read();
driver.send((uint8_t *)msg, strlen(msg));
driver.waitPacketSent();
delay(200);
}
This seems to work. strMsg.toCharArray(msg, i); Can you please comment on the efficiency of the code? Is there a better way? Thanks!
void setup() {
Serial.begin(9600); // Debugging only
if (!driver.init())
Serial.println("init failed");
else
Serial.println("TX");
}
void loop() {
if (Serial.available() > 0)
{
String strMsg = "";
int i;
strMsg = Serial.readString();
i = (strMsg.length() + 1);
char msg[i] = {};
Serial.print("Sent: ");
Serial.println(strMsg);
Serial.print("Size: ");
Serial.println(i);
strMsg.toCharArray(msg, i);
driver.send((uint8_t *)msg, strlen(msg));
driver.waitPacketSent();
delay(200);
}
}
I'm trying to send a UDP packet when an interrupt is triggered using the mbed platform.
However, when i try to call udp_send from the interrupt function key_pressed, i get sys_arch_protect error.
Could this be because some portion of UDPsocket is not being passed to the interrupt function?
For the sake of brevity i have omitted most of the code
Thanks in advance,
Greg
/*--INCLUDES----------------------------------------------------------------------------*/
#include "mbed.h"
#include "EthernetInterface.h"
/*--CONSTANTS---------------------------------------------------------------------------*/
const int BROADCAST_PORT = 58083;
char pin_status[1] = {0};
InterruptIn push_button(SW3);
/*--FUNCTION DEFINITIONS----------------------------------------------------------------*/
void udp_send(void);
void keyPressed(void);
void keyReleased(void);
/*--------------------------------------------------------------------------------------*/
void keyPressed(void)
{
printf("Key Pressed\r\n"); //debug
udp_send(); //calling the function to send UDP packet, this casuses errors
}
/*--------------------------------------------------------------------------------------*/
void keyReleased( void )
{
printf("Key Released\r\n"); //debug
}
/*--------------------------------------------------------------------------------------*/
void udp_send(void) //sends UDP broadcast packet
{
UDPSocket sock;
sock.init();
sock.set_broadcasting();
Endpoint broadcast;
broadcast.set_address("255.255.255.255", BROADCAST_PORT); //broadcast UDP to all
sock.sendTo(broadcast, pin_status, sizeof(pin_status)); //pin_status changed elsewhere
}
/*--------------------------------------------------------------------------------------*/
int main() {
EthernetInterface eth;
eth.init();
eth.connect();
printf("IP Address is %s\r\n", eth.getIPAddress());
udp_send(); //test call to confirm UDP_send function is working (with Wireshark)
while( 1 )
{
push_button.rise(keyPressed); //debounce omitted, calls interupt
push_button.fall(keyReleased);
//other stuff
}
}
Many thanks #Tony d, i guess its not good practice to include big function calls within the interrupt routine anyway.
For future reference, code is attached;
#include "mbed.h"
#include "EthernetInterface.h"
#include "rtos.h"
#include <string>
#include "PinDetect.h"
/*--CONSTANTS---------------------------------------------------------------------------*/
const int BROADCAST_PORT = 58083;
char pin_status[1] = {0};
int global_flag;
InterruptIn push_button(SW3);
/*--FUNCTION DEFINITIONS----------------------------------------------------------------*/
void udp_send(void);
void keyPressed(void);
void keyReleased(void);
EthernetInterface eth;
Endpoint broadcast;
UDPSocket sock;
/*--------------------------------------------------------------------------------------*/
void keyPressed(void)
{
printf("Key Pressed\r\n"); //debug
udp_send();
}
/*--------------------------------------------------------------------------------------*/
void keyReleased( void )
{
printf("Key Released\r\n"); //debug
}
/*--------------------------------------------------------------------------------------*/
void udp_send(void)
{
global_flag = 1; //sends UDP broadcast packet
//pin_status changed elsewhere
}
/*--------------------------------------------------------------------------------------*/
int main() {
eth.init();
eth.connect();
sock.init();
sock.set_broadcasting();
broadcast.set_address("255.255.255.255", BROADCAST_PORT); //broadcast UDP to all
printf("IP Address is %s\r\n", eth.getIPAddress());
udp_send(); //test call to confirm UDP_send function is working
while( 1 )
{
push_button.rise(keyPressed); //debounce omitted, calls interupt
push_button.fall(keyReleased);
if (global_flag)
{
global_flag = 0;
sock.sendTo(broadcast, pin_status, sizeof(pin_status));
}
}
}