Send data from NodeMcu(ESP266) to ESP32 using esp now? - esp8266

I am trying to send some data from a Nodemcu(esp8266) to ESP32. I am trying to use espnow for that purpose, but I am really stuck, I cant merge the Master and Slave for both the boards, I find the codes to be far different I tried some modifications and I can send data from the Nodemcu but can't receive it on the ESP32. I am trying to send two analog values for a Gesture control car.
The master code or the controller code running on the Nodemcu is given below
#include <ESP8266WiFi.h>
#include <espnow.h>
#define MUX_A D4
#define MUX_B D3
#define MUX_C D2
#define ANALOG_INPUT A0
#define CHANNEL 4
extern "C" {
}
uint8_t remoteMac[] = {0x24, 0x6F, 0x28, 0xB6, 0x24, 0x49};
struct __attribute__((packed)) DataStruct {
//char text[32];
int x;
int y;
unsigned long time;
};
DataStruct myData;
unsigned long lastSentMillis;
unsigned long sendIntervalMillis = 1000;
unsigned long sentMicros;
unsigned long ackMicros;
int xAxis;
int yAxis;
int zAxis;
void InitESPNow() {
WiFi.disconnect();
if (esp_now_init()==0) {
Serial.println("ESPNow Init Success");
}
else {
Serial.println("ESPNow Init Failed");
// Retry InitESPNow, add a counte and then restart?
// InitESPNow();
// or Simply Restart
ESP.restart();
}
}
void sendData() {
if (millis() - lastSentMillis >= sendIntervalMillis) {
lastSentMillis += sendIntervalMillis;
myData.time = millis();
uint8_t bs[sizeof(myData)];
memcpy(bs, &myData, sizeof(myData));
sentMicros = micros();
esp_now_send(NULL, bs, sizeof(myData)); // NULL means send to all peers
Serial.println("sent data");
Serial.println(myData.x);
Serial.println(myData.y);
}
}
void sendCallBackFunction(uint8_t* mac, uint8_t sendStatus) {
ackMicros = micros();
Serial.print("Trip micros "); Serial.println(ackMicros - sentMicros);
Serial.printf("Send status = %i", sendStatus);
Serial.println();
Serial.println();
}
void setup() {
Serial.begin(115200); Serial.println();
Serial.println("Starting EspnowController.ino");
WiFi.mode(WIFI_STA); // Station mode for esp-now controller
WiFi.disconnect();
Serial.printf("This mac: %s, ", WiFi.macAddress().c_str());
Serial.printf("slave mac: %02x%02x%02x%02x%02x%02x", remoteMac[0], remoteMac[1], remoteMac[2], remoteMac[3], remoteMac[4], remoteMac[5]);
Serial.printf(", channel: %i\n",CHANNEL);
InitESPNow();
esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER);
esp_now_add_peer(remoteMac, ESP_NOW_ROLE_SLAVE, CHANNEL, NULL, 0);
esp_now_register_send_cb(sendCallBackFunction);
Serial.print("Message ");
pinMode(MUX_A, OUTPUT);
pinMode(MUX_B, OUTPUT);
pinMode(MUX_C, OUTPUT);
Serial.println("Setup finished");
}
void changeMux(int c, int b, int a) {
digitalWrite(MUX_A, a);
digitalWrite(MUX_B, b);
digitalWrite(MUX_C, c);
}
void loop() {
changeMux(LOW, LOW, LOW);
xAxis = analogRead(ANALOG_INPUT); //Value of the sensor connected to pin 0 of IC
changeMux(LOW, LOW, HIGH);
yAxis = analogRead(ANALOG_INPUT); //Value of the sensor connected to pin 1 of IC
changeMux(LOW, HIGH, LOW);
zAxis = analogRead(ANALOG_INPUT); //Value of the sensor connected to pin 2 of IC
changeMux(LOW, HIGH, LOW);
myData.x= xAxis;
myData.y= yAxis;
sendData();
delay(500);
}
The slave code running on the ESP32 is given below
#include <esp_now.h>
#include <WiFi.h>
#include <esp_wifi.h>
#define CHANNEL 4
uint8_t mac[] = {0x36, 0x33, 0x33, 0x33, 0x33, 0x33};
struct __attribute__((packed)) DataStruct {
//char text[32];
int x;
int y;
unsigned long time;
};
DataStruct myData;
// Init ESP Now with fallback
void setup() {
Serial.begin(115200);
Serial.println("ESPNow/Basic/Slave Example");
//Set device in AP mode to begin with
WiFi.mode(WIFI_AP);
// configure device AP mode
// This is the mac address of the Slave in AP Mode
esp_wifi_set_mac(ESP_IF_WIFI_STA, &mac[0]);
Serial.print("AP MAC: "); Serial.println(WiFi.softAPmacAddress());
// Init ESPNow with a fallback logic
if (esp_now_init()!=0) {
Serial.println("*** ESP_Now init failed");
while(true) {};
}
// Once ESPNow is successfully Init, we will register for recv CB to
// get recv packer info.
esp_now_register_recv_cb(OnDataRecv);
Serial.print("Aheloiioi");
}
// callback when data is recv from Master
void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len) {
memcpy(&myData, data, sizeof(myData));
char macStr[18];
snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
Serial.print("Last Packet Recv from: "); Serial.println(macStr);
Serial.print("Last Packet Recv Data: "); Serial.println(myData.x); Serial.println(myData.y);
Serial.println("");
}
void loop() {
// Chill
}
This is the only output I get on the ESP32
ESPNow/Basic/Slave Example
AP MAC: 24:6F:28:B6:24:49
Aheloiioi
While this is the output on Nodemcu
Starting EspnowController.ino
This mac: BC:DD:C2:B5:E3:2B, slave mac: 246f28b62449, channel: 4
ESPNow Init Success
Message Setup finished
sent data
10
8
Trip micros 7320
Send status = 1
sent data
9
8
Trip micros 6817
Send status = 1
sent data
10
9
Trip micros 6731
Send status = 1
and it continues
If there are any other methods to send data, please do mention

I never use esp_now before so I didn't test it myself, but I think this has nothing to do with the library or esp32, it is just a minor mistake of c++ usage.
On your sendData() function of your esp8266, you did this:
uint8_t bs[sizeof(myData)];
memcpy(bs, &myData, sizeof(myData));
sentMicros = micros();
esp_now_send(NULL, bs, sizeof(myData));
The bs has a type of uint8_t and is an array, and you try to copy the data that has a type of struct myData into the array. And you then try to pass the array into the esp_now_send(). I quickly took a look at the esp_now_send() function prototype definition, the esp_now_send() need to pass in the address (which has a type of uint8_t) of your data structure myData.
I don't know know why you need to do the memcpy, but I think it will easier and simply to just directly pass in the pointer of myData into the function call.
void sendData() {
if (millis() - lastSentMillis >= sendIntervalMillis) {
lastSentMillis += sendIntervalMillis;
myData.time = millis();
esp_now_send(NULL, (uint8_t *)&myData, sizeof(myData)); // NULL means send to all peers
Serial.println("sent data");
Serial.println(myData.x);
Serial.println(myData.y);
}
}
Please let me know if this work?

Related

Issue with writing InfluxDB code to ESP32 chip using OTA

I'm trying to write a program for my ESP32 that writes to InfluxDB but also maintains an OTA access server and it appears that the two functions are having some impact on each other that's causing the OTA server to not work (i.e. the OTA page does not appear when I enter the IP address into the browser). I've narrowed the problem down to the
client.writePoint(sensor)
function that InfluxDB uses to write data to buffer and I'm unsure of how to remedy that. The OTA functionality works when I comment out the line that references the above function. I've included this code below.
//PASTE THIS IN ABOVE EXISTING HEADERS
//#include <WiFi.h> //if file already has these libraries, remove it from one of the places
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
const char* host = "esp32";
const char* ssid = "ssid";
const char* password = "pwd";
WebServer server(80);
// end OTA header file
//BEGIN HEADER FILE
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "TEST"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
/* Self inclusions -> Not from InfluxDB */
#define Vdd 3.3
#define Aout 35
#define LINEAR LOW
#define SQ_ROOT HIGH
const int R_0 = -1812; //Change this to your own R0 measurements
#include "max6675.h"
#include <WiFi.h>
#include <WiFiUdp.h>
/* End Self Inclusions */
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
#define INFLUXDB_URL "url"
// InfluxDB v2 server or cloud API authentication token ( Data -> Tokens -> MQ Sensors)
#define INFLUXDB_TOKEN "token"
// InfluxDB v2 organization id (Use: InfluxDB UI -> User -> About -> Common Ids )
#define INFLUXDB_ORG "org"
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Data -> Buckets)
#define INFLUXDB_BUCKET "bucket"
// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
// Examples:
// Pacific Time: "PST8PDT"
// Eastern: "EST5EDT"
// Japanesse: "JST-9"
// Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3"
#define TZ_INFO "EST5EDT"
// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
// Data Point
Point sensor("VOC_data"); // Data point
// END HEADER FILE
void setup() { //make sure this line appears one time only
Serial.begin(115200); //make sure there are not two serial/begin functions in setup
Serial.println("started"); //TS COMMENT
// Connect to WiFi network
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("\n\nACCESS UPDATES AT: http://");
Serial.print(WiFi.localIP());
Serial.println("\n\n");
pinMode(Aout, INPUT);
// Add tags
sensor.addTag("device", DEVICE);
// Accurate time is necessary for certificate validation and writing in batches
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
// Syncing progress and the time will be printed to Serial.
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");
// Check server connection
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
/*use mdns for host name resolution*/
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
/*return index page which is stored in serverIndex */
server.on("/", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", loginIndex);
Serial.println("init1 complete"); //TS COMMENT
});
server.on("/serverIndex", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", serverIndex);
Serial.println("init2 complete"); //TS COMMENT
});
/*handling uploading firmware file */
server.on("/update", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
Serial.println("init3 complete"); //TS COMMENT
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %s\n", upload.filename.c_str());
Serial.println("init4 complete"); //TS COMMENT
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Serial.println("Check at line 201");
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Serial.println("Check at line 207");
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Serial.println("Check at line 214");
Update.printError(Serial);
}
}
});
server.begin();
} //delete if void setup() line is deleted
void loop() { //make sure this line does not appear twice
server.handleClient();
float a0 = analogRead(Aout); // get raw reading from sensor
float v_o = a0 * 4.6 / 1023; // convert reading to volts
float R_S = (4.6-v_o) * 1000 / v_o; // apply formula for getting RS
float R_a = R_S/R_0; // formula for the ratio
float PPM = pow(R_a,-2.95) * 1000; //apply formula for getting PPM
float PPM_ALCOHOL = pow(-13.17*log(R_S/R_0) + 10.35 ,1);
//double PPM = pow(static_cast<double>(R_S/R_0),-2.95) * 1000;
//float PPMnew = a0*0.065156122+0.746160521;
sensor.clearFields();
// Store measured value into point
sensor.addField("VOC_Sensor", a0);
sensor.addField("VOC_PPM", PPM);
//sensor.addField("VOC_RS", R_S);
//sensor.addField("VOC_ALCOHOL", PPM_ALCOHOL);
/****************************** Self inclusions -> Not from InfluxDB ******************************/
Serial.print("Sensor Voltage: ");
Serial.print(v_o); //VOC concentration
Serial.println(" V"); //units
Serial.print("VOC Concentration calculation in arduino: ");
Serial.print(PPM); //VOC concentration
Serial.println(" PPM"); //units
Serial.print("Raw signal: ");
Serial.print(a0); //VOC concentration
Serial.println(" "); //units
delay(1000);
/***************************************************************************************************/
// Print what are we exactly writing
Serial.println(WiFi.localIP());
Serial.println("Line 286");
Serial.println(sensor.toLineProtocol());
// Write point
if (client.writePoint(sensor)) {
Serial.println("InfluxDB write successful");
} else {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}
Serial.println("Wait 200ms");
delay(200);
} //delete if void loop() line is deleted
The serial output displays
Connected to ssid
ACCESS UPDATES AT: ESP32_IP_ADDRESS
and then continues to display the "InfluxDB write successful" message with each data point.

Blue ESP8266-12e tx light staying on

I have some code I have been putting on an ESP8266-12e board. Until recently it always worked fine. Now though when I finish uploading the code the blue light on the ESP8266-12e is staying on. I have tried it on two different board and the blue light stay on on both. I can't figure out what I changed in the code.
I have decided to put it up and have everyone look at it and let me know what I may be missing.
I hope someone can find something.
My code:
//NodeMCU 1.0 (ESP-12E Module constant connect)
#include <ESP8266WiFi.h>
#include <FS.h> //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
//MQTT stuff
#define AIO_SERVER "go,here"
#define AIO_SERVERPORT SSSS // 8883 for MQTTS
#define AIO_USERNAME "FFFFFF"
#define AIO_KEY "XXXXXXXXXXXXXXXXXXXXXXX"
int tripper = 1;
#define MQTT_CONN_KEEPALIVE 18000000
#define LED3 16
//NEW AUTOCONNECT
const byte numChars = 32;
char receivedChars[numChars];
char Password[36]="";
char apiKey[16]="";
char apiKey2[32]="";
char channelKey[16];
char channelKey2[16];
String channelKey21= "&";
byte pinState = LOW;
char ssid[] = "";
char pass[] = "";
String Label = "";
String TOTAL = "";
uint32_t m=0;
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe trip2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/trip");
Adafruit_MQTT_Publish move1 = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/motion");
/*************************** Error Reporting *********************************/
Adafruit_MQTT_Subscribe errors = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/errors");
Adafruit_MQTT_Subscribe throttle = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/throttle");
//NEW AUTOCONNECT
int LED2 = 13;
int MOVEMENT = 5;
//send ssid/pass
String f;
//mqtt
char temperature[]="000";
String level;
String battery;
String trip;
String date;
int addr = 0;
//END NEW AUTOCONNECT
void MQTT_connect();
void setup() {
Serial.begin(115200);
pinMode(MOVEMENT,OUTPUT);
digitalWrite(MOVEMENT,LOW);
pinMode(D5,OUTPUT);
digitalWrite(D5,LOW);
pinMode(LED3,OUTPUT);
digitalWrite(LED3,LOW);
pinMode(LED2,INPUT);
Serial.println(F("Adafruit MQTT demo"));
//NEW AUTOCONNECT
WiFiManager wifiManager;
// put your setup code here, to run once:
WiFiManagerParameter customAPIKey("apiKey", "Time Zone #", apiKey, 16);
wifiManager.addParameter(&customAPIKey);
wifiManager.autoConnect("FloWT2");
Serial.println("Connected");
strcpy(apiKey,customAPIKey.getValue());
EEPROM.begin(512); //Initialize EEPROM
EEPROM.write(addr, 'A'); //Write character A
addr++; //Increment address
EEPROM.write(addr, 'B'); //Write character A
String www = apiKey;
Serial.print("www");
Serial.print (www);
for(int i=0;i<www.length();i++) //loop upto string lenght www.length() returns length of string
{
EEPROM.write(0x0F+i,www[i]); //Write one by one with starting address of 0x0F
}
EEPROM.commit();
delay (2000);
if (WiFi.status() == WL_DISCONNECTED) {
wifiManager.autoConnect("FloWT2");
delay(60000);}
if (WiFi.status() == WL_CONNECTED) { Serial.println("Connected");
delay(1000);
//get time zone
EEPROM.begin(512);
Serial.println(""); //Goto next line, as ESP sends some garbage when you reset it
Serial.print(char(EEPROM.read(addr))); //Read from address 0x00
addr++; //Increment address
Serial.print(char(EEPROM.read(addr))); //Read from address 0x01
addr++; //Increment address
Serial.println(char(EEPROM.read(addr))); //Read from address 0x02
//Read string from eeprom
String www;
//Here we dont know how many bytes to read it is better practice to use some terminating character
//Lets do it manually www.circuits4you.com total length is 20 characters
for(int i=0;i<16;i++)
{
www = www + char(EEPROM.read(0x0F+i)); //Read one by one with starting address of 0x0F
}
Serial.println("this");
Serial.print(www);
Serial.println("IP address: "); Serial.println(WiFi.localIP());
// Setup MQTT subscription for onoff feed
mqtt.subscribe(&trip2);
// Setup MQTT subscriptions for throttle & error messages
mqtt.subscribe(&throttle);
mqtt.subscribe(&errors);
WiFiClient client;
delay(2000);
Serial.printf("SSID: %s\n", WiFi.SSID().c_str());
Serial.printf("SSID: %s\n", WiFi.psk().c_str());
String ssidString = WiFi.SSID().c_str();
String pskString = WiFi.psk().c_str();
f = String('<')+String("Hi")+String(',')+String(ssidString)+String(',')+String(pskString)+String(',')+String(www)+String('>');
delay (1000);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
}
client.stop();
}
void loop() {
MQTT_connect();
uint32_t m=0;
Serial.print(F("\nSending motion val "));
Serial.print(m);
Serial.print("...");
if (! move1.publish(m)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
long state = digitalRead(LED2);
if(state == HIGH) {
m = 1;
Serial.print(F("\nSending motion val "));
Serial.print(m);
Serial.print("...");
digitalWrite(MOVEMENT,HIGH);
delay(1000);
digitalWrite(MOVEMENT,LOW);
if (! move1.publish(m)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
}
else{
}
// this is our 'wait for incoming subscription packets' busy subloop
// try to spend your time here
//12e
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(5000))) {
if (subscription == &trip2) {
Serial.print(F("Got onoff: "));
Serial.println((char *)trip2.lastread);
uint16_t sliderval = atoi((char *)trip2.lastread);
//THIS IS FOR LATCHING RELAY TURN ON D5 HIGH THEN OFF AFTER 1 SECOND
//NEXt TURN D6 HIGH THEN OFF AFTER A SECONDS
if((sliderval ==0)&&(tripper == 1)){
digitalWrite(D5,HIGH);
delay(1000);
digitalWrite(D5,LOW);
tripper = 2;
Serial.print(tripper);
Serial.print("tripped");
}
else if(sliderval == 50){
}
else if((sliderval == 100)&&(tripper == 2)){
digitalWrite(LED3,HIGH);
delay(1000);
digitalWrite(LED3,LOW);
tripper = 1;
Serial.print(tripper);
Serial.print("tripped2");
}
} else if(subscription == &errors) {
Serial.print(F("ERROR: "));
Serial.println((char *)errors.lastread);
} else if(subscription == &throttle) {
Serial.println((char *)throttle.lastread);
}
}
}
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}
I hope it is not toooo long.
Anyway I hope someone can find my problem. Everything works ok with the blue light on it is just know supposed to be that I can tell.
When I upload another code it doesn't stay on so it has to be in the code.
I will keep looking.
THANKS
So I got the blue light to go off. Instead of pinMode(D4,INPUT); and digitalWrite(D4,LOW); D4 is pin 16 which is the wake pin. So I had to define it thus #define LED3 16 and then pinMode(LED3,INPUT); and digitalWrite(LED3,LOW); I will change my original code to reflect these changes.

MQTT subscription

Can someone help me with this code?
The goal is to trigger a Led when the value of the payload is > 1000.
It is a MQTT subscribtion code based on the esp8266mqtt PubSub client example. I will use it for a subscribyion of a topic from a CO2sensor
I've tried to modify a part of it but I think it has yo do something with the kind of datatype or a wrong condition?
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char *ssid = "xxx";
const char *password = "xxx";
const char *mqtt_server = "xxxx";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
int led = D4;
void setup_wifi()
{
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
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();
// Switch on the LED if value of C02 is above 1000
i = atoi (payload); //convert string to integer
if ( i > 1000) // comparison
{
digitalWrite(led, HIGH); // Turn the LED on
}
else
{
digitalWrite(led, LOW); // Turn the LED off
}
}
void reconnect()
{
// Loop until we're reconnected
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str()))
{
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("outTopic", "Test");
// ... and resubscribe
client.subscribe("my/sensors/co2");
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
pinMode(led, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
}
Kind regards
Hi, This is what I publish:
void pubMessage() {
char message[16];
snprintf(message, sizeof(message), "%d", co2);
client.publish("my/sensors/co2", message);
delay(30000);
First you are casting the first byte of payload to a char.
Since it's just the first byte, it has a max value of 256.
Second you are comparing that 1 bytes value to the string '1000'
Without knowing exactly what you are publishing it is very hard to tell you how to fix it.
If you are publishing a string representing the number then you will need to parse it first with atoi() then do the comparison to the integer 1000 not the string.
If it is a byte value then you will need to read the correct value from the incoming byte array before doing the comparison.

MQTT NodeMCU servo can react only on decimal array payload

I'm creating a fish feeder with SG90 servo and NodeMCU
I used this sketch:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Servo.h>
// Update these with values suitable for your network.
const char* ssid = "your_wifi_hotspot";
const char* password = "your_wifi_password";
const char* mqtt_server = "broker.mqttdashboard.com";
//const char* mqtt_server = "iot.eclipse.org";
Servo myservo; // create servo object to control a servo
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(100);
// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Command from MQTT broker is : [");
Serial.print(topic);
for(int i=0;i<length;i++)
{
if((int)payload[i]>194||(int)payload[i]<0)
break;
myservo.write((int)payload[i]); // tell servo to go to position in variable '(int)payload[i]'
}
}//end callback
void reconnect() {
// Loop until we're reconnected
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
//if you MQTT broker has clientID,username and password
//please change following line to if (client.connect(clientId,userName,passWord))
if (client.connect(clientId.c_str()))
{
Serial.println("connected");
//once connected to MQTT broker, subscribe command if any
client.subscribe("OsoyooCommand");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 6 seconds before retrying
delay(6000);
}
}
} //end reconnect()
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
myservo.attach(D1); // attaches the servo on pin D1 to the servo object
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
The servo is working when I use MQTTBox in order to send a payload as "Decimal Array", it is however is giving me a hard time when I send payload as JSON string.
If I send "Decimal Array" 1 it does turn Servo to position 1, however if I simply send 1 as a payload as a string it moves Servo to position 49.
If I send payload as 2 it moves to position 50.
If I send payload as 10 then position is 4948
looks like position of 1 and position of 0 at the same time.
My ultimate goal is to send those payloads via HomeAssistant which are sent as string or JSON, however I don't find a correct solution at the moment.
I would highly appreciate any help or solution.
MQTT payloads are UTF-8 encoded so the Arduino PubSubClient library treats the payload as an array of uint8_t.
If you want to send and receive JSON then you can use the ArduinoJson library to parse a JSON payload. So assuming a JSON payload like:
{
"position": 123
}
Then you can implement a callback such as:
#include <ArduinoJson.h>
// Assuming a fixed sized JSON buffer
StaticJsonBuffer<200> jsonBuffer;
void callback(char* topic, byte* payload, unsigned int length)
{
JsonObject& root = jsonBuffer.parseObject(payload);
if (root.success() && root.is<JsonObject>())
{
int position = root.as<JsonObject>().get<int>("position");
myservo.write(position);
}
}
Looks like the motor is taking the position of the ASCII equivalent of the number when you send it as a string.
i.e.
ASCII equivalent of the character '1' in 49 in decimal
ASCII equivalent of the character '2' in 50 in decimal
Try sending the character 'a', the motor will go to 97.
If you want to send a string, you will have to change the following code:
for(int i=0;i<length;i++)
{
if((int)payload[i]>194||(int)payload[i]<0)
break;
myservo.write((int)payload[i]); // tell servo to go to position in variable '(int)payload[i]'
}
to:
int location=String((char*)payload).toInt()
if((location>194)||(location<0))
return;
myservo.write(location);

arduino uno + wifishield cannot connect bluemix using token

I have arduino uno + wifishield and if fails to connect to Bluemix. It gives this error:
"Closed connection from 194.228.11.222. The operation is not authorized."
Any idea why the connection gets kicked out? What operation is not authorized?
Thanks for any idea ;)
======
Here is the code:
#include <SPI.h>
#include <Ethernet.h>
#include <WiFi.h>
#include <WifiIPStack.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>
#define MQTT_MAX_PACKET_SIZE 100
#define SIZE 100
#define MQTT_PORT 1883
#define PUBLISH_TOPIC "iot-2/evt/status/fmt/json"
#define SUBSCRIBE_TOPIC "iot-2/cmd/+/fmt/json"
#define USERID "use-token-auth"
#define CLIENT_ID "d:6735ra:hlinoponie:petasek"
#define MS_PROXY "6735ra.messaging.internetofthings.ibmcloud.com"
#define AUTHTOKEN “xxxxx”
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0xD6, 0x8F };
WiFiClient c;
IPStack ipstack(c);
MQTT::Client<IPStack, Countdown, 100, 1> client = MQTT::Client<IPStack, Countdown, 100, 1>(ipstack);
String deviceEvent;
char ssid[] = “XXXXX”; // your network SSID (name)
char pass[] = “XXXXX”; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if ( fv != "1.1.0" )
Serial.println("Please upgrade the firmware");
// 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 5 seconds for connection:
delay(5000);
}
// you're connected now, so print out the data:
Serial.print("Hooray!!! You're connected to the network\n");
}
void loop() {
float tep = mojeDHT.readTemperature();
float vlh = mojeDHT.readHumidity();
int rc = -1;
if (!client.isConnected()) {
Serial.println("Connecting to Watson IoT Foundation ...");
rc = ipstack.connect((char*)MS_PROXY, MQTT_PORT);
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.MQTTVersion = 3;
data.clientID.cstring = (char*)CLIENT_ID;
data.username.cstring = (char*)USERID;
data.password.cstring = (char*)AUTHTOKEN;
data.keepAliveInterval = 60;
rc = -1;
while ((rc = client.connect(data)) != 0) {
Serial.println("rc=");
Serial.println(rc);
delay(2000);
}
Serial.println("Connected successfully\n");
// Serial.println("Temperature(in C)\tDevice Event (JSON)");
Serial.println("____________________________________________________________________________");
}
Serial.println("\n");
MQTT::Message message;
message.qos = MQTT::QOS0;
message.retained = false;
deviceEvent = String("{\"d\":{\"myName\":\"Arduino Uno\",\"temperature\":");
char buffer[60];
// convert double to string
dtostrf(getTemp(),1,2, buffer);
deviceEvent += buffer;
deviceEvent += "}}";
Serial.print("\t");
Serial.print(buffer);
Serial.print("\t\t");
deviceEvent.toCharArray(buffer, 60);
Serial.println(buffer);
message.payload = buffer;
message.payloadlen = strlen(buffer);
rc = client.publish(PUBLISH_TOPIC, message);
if (rc != 0) {
Serial.print("return code from publish was ");
Serial.println(rc);
}
client.yield(5000);
}
/*
This function is reproduced as is from Arduino site => http://playground.arduino.cc/Main/InternalTemperatureSensor
*/
double getTemp(void) {
unsigned int wADC;
double t;
ADMUX = (_BV(REFS1) | _BV(REFS0) | _BV(MUX3));
ADCSRA |= _BV(ADEN); // enable the ADC
delay(20); // wait for voltages to become stable.
ADCSRA |= _BV(ADSC); // Start the ADC
// Detect end-of-conversion
while (bit_is_set(ADCSRA,ADSC));
// Reading register "ADCW" takes care of how to read ADCL and ADCH.
wADC = ADCW;
// The offset of 324.31 could be wrong. It is just an indication.
t = (wADC - 324.31 ) / 1.22;
// The returned temperature is in degrees Celcius.
return (t);
}
It might be the case your organizations is configured to block non-secure connections (since you are using port 1883). Check the step 5 on this recipe
https://developer.ibm.com/recipes/tutorials/connect-an-arduino-uno-device-to-the-ibm-internet-of-things-foundation/
I noticed this error in the log: The topic is not valid: Topic="lwt" ClientID="d:6735ra:hlinoponie:petasek" Reason="The topic does not match an allowed rule".
I didn't see that topic listed in your code, but you may want to check to see how that may be getting set as topic.

Resources