I’m having some problem with a home automation project of mine. I bought a nodeMCU v3 from aliexpress that i want to control my blinds with.
This is the code I’m using on it. I use the Arduino IDE to push this code in to the nodeMCU.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SimpleTimer.h>
// MQTT Server
const char* ssid = "****";
const char* password = "****";
const char* mqtt_server = "****";
char message_buff[100];
int photoValue = 0;
int rainValue = 0;
int photo = A0;
int rain = D6;
int relayUp = D7;
int relayDown= D8;
long interval = 10000;
long previousMillis = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void setup() {
pinMode(photo, INPUT);
pinMode(rain, INPUT);
pinMode(relayUp, OUTPUT);
pinMode(relayDown, OUTPUT);
digitalWrite(relayUp ,LOW);
digitalWrite(relayDown, LOW);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
if (client.connect("ESP8266Client")) {
client.subscribe("home/relayBlinds");
} else {
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
// Connect (or reconnect) to mqtt broker on the openhab server
reconnect();
}
// Read Photo- and Rain-sensors
photoValue = analogRead(photo);
rainValue = analogRead(rain);
// publish Temperature reading every 10 seconds
unsigned long currentMillis = millis();
if (currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
// publish Photo
String pubStringPhoto = String(photoValue);
pubStringPhoto.toCharArray(message_buff, pubStringPhoto.length()+1);
client.publish("home/photo", message_buff);
// publish Rain
String pubStringRain = String(rainValue);
pubStringRain.toCharArray(message_buff, pubStringRain.length()+1);
client.publish("home/rain", message_buff);
}
client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
// MQTT inbound Messaging
int i = 0;
// create character buffer with ending null terminator (string)
for(i=0; i<length; i++) {
message_buff[i] = payload[i];
}
message_buff[i] = '\0';
String msgString = String(message_buff);
if (msgString == "BLINDSUP") {
digitalWrite(relayUp ,HIGH);
delay(5000);
digitalWrite(relayUp ,LOW);
} else if (msgString == "BLINDSDOWN") {
digitalWrite(relayDown ,HIGH);
delay(5000);
digitalWrite(relayDown ,LOW);
}
}
The plan was to have a Raspberry Pi with openHAB as a controller. I have used several guides to setup mosquitto and openHAB and i always get the same result.
So this is what happens: the nodeMCU connects to my Wifi and publishes both the rain and photo values. I can read them in the openHAB GUI without problems.
When i press the activation button in openHAB to publish BLINDSUP or BLINDSDOWN the messages arrives without any problems and i can see the message on my mosquitto terminal. Now is when the unexpected result starts happening. The same message gets delivered multiple times to my nodeMCU without it showing up in the mosquitto terminal.
I have been trying to find out why it would act this way and I think it is because the line:
if (!client.connected()) {
is false and the nodeMCU reconnects and gets the same message somehow. But it is always the first message. If I send BLINDSUP and then BLINDSDOWN it will only register BLINDSUP forever.
I'm really out of ideas how to fix this and would appreciate any help, thanks.
URL to the nodeMCU if that helps anyhow: nodeMCU
Try connecting to MQTT broker with a clean session. Probably you published the topic with the retain flag set to true.
If you do like this, the broker will deliver the last retained message when the nodeMCU connects to the broker and subscribes to the retained topic.
Related
I am doing program on Arduino IDE with goal to blink LED on breadboard with NodeMCU whenever it receives ON message from MQTT topic.I have done the program but the LED is not blinking. If I do the program removing MQTT portion, things are fine. Might be I am doing something wrong in loop().
I created MQTT topic using Node-Red.When I tested publish-subscription on Node Red, the flow is working as expected. But when I am trying to read the message from arduino, I dont see LED changing it's state.
Copying relevant portion of the code-
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "NET";
const char* password = "xx";
const char* mqtt_server = "192.x.x.x";
const int lamp = 4;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
messageTemp += (char)payload[i];
}
Serial.println();
Serial.println("messageTemp-"+messageTemp);
if (topic=="room/lamp") {
Serial.print("Changing Room lamp to ");
if (messageTemp == "on") {
digitalWrite(lamp, LOW);
Serial.print("On");
}
else if (messageTemp == "off") {
digitalWrite(lamp, HIGH);
Serial.print("Off");
}
}
Serial.println();
}
void setup() {
pinMode(lamp, OUTPUT);
Serial.begin(9600);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
I expect whenever I am pushing ON and OFF messages on the topic 'room/lamp' from nodered, the LED should get turned on and off.But it is not happening now.I am new to Arduino.Please advise.
Currently I am attempting to figure out how to control my Adafruit NeoPixels strip using OSC. More specifically, I am using TouchOSC to send/receive messages over WiFi from my NodeMCU ESP8266 microcontroller, which is connected to my NeoPixels.
I have downloaded some test code that somebody else made that listens for OSC messages to toggle the tiny LED on the NodeMCU board on/off. When the controller receives the message, it sends the message back to the TouchOSC client to tell whether or not the light is on (it's a toggle button). This all works perfectly fine.
I've written a simple function that animates the NeoPixel LED strip connected to the NodeMCU board. On its own, this also works perfectly fine.
What I've been struggling with is to figure out a way to get my function [the one called gwBlink()] to run in a loop when the LED is toggled on.
I've attached the code. Could somebody tell me what I'm doing wrong?? I would be eternally grateful for any help!! :)
The TouchOSC interface:
/**
* Send and receive OSC messages between NodeMCU and another OSC speaking device.
* Send Case: Press a physical button (connected to NodeMCU) and get informed about it on your smartphone screen
* Receive Case: Switch an LED (connected to NodeMCU) on or off via Smartphone
* Created by Fabian Fiess in November 2016
* Inspired by Oscuino Library Examples, Make Magazine 12/2015
*/
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <OSCMessage.h> // for sending OSC messages
#include <OSCBundle.h> // for receiving OSC messages
#include <Adafruit_NeoPixel.h>
#define PIN 3
Adafruit_NeoPixel strip = Adafruit_NeoPixel(58, 3, NEO_GRB + NEO_KHZ800);
char ssid[] = "XXX"; // your network SSID (name)
char pass[] = "XXX"; // your network password
// Button Input + LED Output
const int btnPin = 12; // D6 pin at NodeMCU
const int ledPin = 14; // D5 pin at NodeMCU
const int boardLed = LED_BUILTIN; // Builtin LED
boolean btnChanged = false;
int btnVal = 1;
WiFiUDP Udp; // A UDP instance to let us send and receive packets over UDP
const IPAddress destIp(192,168,0,10); // remote IP of the target device (i.e. THE PHONE)
const unsigned int destPort = 12000; // remote port of the target device where the NodeMCU sends OSC to
const unsigned int localPort = 10000; // local port to listen for UDP packets at the NodeMCU (another device must send OSC messages to this port)
unsigned int ledState = 1; // LOW means led is *on*
void setup() {
strip.begin();
strip.show();
Serial.begin(115200);
// Specify a static IP address for NodeMCU - only needeed for receiving messages)
// If you erase this line, your ESP8266 will get a dynamic IP address
WiFi.config(IPAddress(192,168,0,13),IPAddress(192,168,0,1), IPAddress(255,255,255,0));
// Connect to WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Starting UDP");
Udp.begin(localPort);
Serial.print("Local port: ");
Serial.println(Udp.localPort());
// btnInput + LED Output
pinMode(btnPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(boardLed, OUTPUT);
}
void loop() {
receiveOSC();
sendOSC();
}
void sendOSC(){
// read btnInput and send OSC
OSCMessage msgOut("/1/buttonListener");
if(digitalRead(btnPin) != btnVal) {
btnChanged = true;
btnVal = digitalRead(btnPin);
}
if(btnChanged == true){
btnChanged = false;
digitalWrite(ledPin, btnVal);
digitalWrite(boardLed, (btnVal + 1) % 2); // strange, but for the builtin LED 0 means on, 1 means off
Serial.print("Button: ");
Serial.println(btnVal);
msgOut.add(btnVal);
}
Udp.beginPacket(destIp, destPort);
msgOut.send(Udp);
Udp.endPacket();
msgOut.empty();
delay(100);
}
void receiveOSC(){
OSCMessage msgIN;
int size;
if((size = Udp.parsePacket())>0){
while(size--)
msgIN.fill(Udp.read());
if(!msgIN.hasError()){
msgIN.route("/1/toggleLED",toggleOnOff);
}
}
}
void gwBlink() {
// LED strip animation
uint16_t i, j;
for(i = 0; i < strip.numPixels(); i = i + 2) {
strip.setPixelColor(i, 0, 182, 90);
}
for(j = 1; j < strip.numPixels(); j = j + 2) {
strip.setPixelColor(j, 128, 128, 128);
}
strip.show();
delay(100);
for(i = 0; i < strip.numPixels(); i = i + 2) {
strip.setPixelColor(i, 128, 128, 128);
}
for(j = 1; j < strip.numPixels(); j = j + 2) {
strip.setPixelColor(j, 0, 182, 90);
}
strip.show();
delay(100);
}
void toggleOnOff(OSCMessage &msg, int addrOffset){
ledState = (boolean) msg.getFloat(0);
digitalWrite(boardLed, (ledState + 1) % 2); // Onboard LED works the wrong direction (1 = 0 bzw. 0 = 1)
digitalWrite(ledPin, ledState); // External LED
if (ledState) {
Serial.println("LED on");
gwBlink();
}
else {
Serial.println("LED off");
strip.clear();
}
ledState = !ledState; // toggle the state from HIGH to LOW to HIGH to LOW ...
}
This code actually works fine as far as switching the little LED on the board on/off, but my animation function isn't triggered.
I have only been working with NeoPixels for a short time, but I had problems when trying to use them & serial monitor simultaneously. Once I disabled the serial command (//Serial.begin(115200);), they worked fine. The documentation doesn't plainly state this, I discovered it in a thread where an Adafruit Admin referred to using serial while trying to also update the NeoPixels as a "pain".
If commenting out Serial.begin fixes your problem, then I guess you can experiment with:
*if (Serial.available()) {
int inByte = Serial.read();
Serial1.print(inByte, DEC);
}*
...idk, but it's worth trying.
I am using PubSubClient library to subscribe to a server using a nodemcu. I tested the code using cloudMQTT and MQTTlens and it worked fine. In addition to that, I used MQTTlens to check mqtt connection with my pc. In there, I did not specify username and password (I kept blank) and it worked just fine. When I want to connect for a public server (ex: "tcp://11.111.111.111"), does not connect.
code for nodemcu
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "*****";
const char* password = "****";
const char* mqttServer = "****";
const int mqttPort = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
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("ESP8266Client")) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.publish("topic1", "Hello from ESP8266_tester1");
client.subscribe("topic1");
}
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();
}
the result from the serial monitor
Any suggestion is welcome
If you genuinely don't require a username and password then don't use the connect function that expects them:
...
if (client.connect("ESP8266Client")) {
...
I see you are using a fairly generic client id - ESP8266Client. Remember that all clients connecting to a broker must have a unique client id. If you depoyed this sketch to two different devices they would not both be able to connect at the same time.
The problem was with the ip I have provided. IP does not require "tcp://" part. After removing that, the code worked well.
I'm attempting to connect my Feather Huzzah to a local MQTT server but the program keeps blowing up and throwing a stack trace. When I attempt to decode the stack trace it's just empty, more frequently I only get part of the stack trace. Here's the code that I'm running, most of it is pretty similar to the pub/sub client example code for Arduino. I've tried erasing the flash on the device, that didn't seem to help.
Even stranger is that it worked once, but as soon as I tried it again adding the callback the code stopped working and blows up. If I try removing the callback nothing changes. I've tried stripping out a lot of the code just to see if I can get a consistent connection to MQTT, but that doesn't seem to be working either. The MQTT server is the latest Mosquitto from Ubuntu 18.04.
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
const char* ssid = "xxxxxxxx";
const char* password = "xxxxxxxxx";
const int hallPin = 14;
const int ledPin = 0;
const char* mqtt_server = "mosquitto.localdomain";
long lastMsg = 0;
char msg[100];
int value = 0;
int hallState = 0;
WiFiClient espClient;
PubSubClient client(espClient);
WiFiUDP ntpUDP;
// By default 'time.nist.gov' is used with 60 seconds update interval and
// no offset
NTPClient timeClient(ntpUDP);
// Setup and connect to the wifi
void setup_wifi() {
delay(100);
Serial.print("Connecting to: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Wifi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Gateway: ");
Serial.println(WiFi.gatewayIP());
}
//Reconnect to the MQTT broker
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("/homeassistant/devices/doorbell", "hello world");
// ... and resubscribe
client.subscribe("/homeassistant/doorbell/receiver");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//Process messages incoming from the broker
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]);
}
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(hallPin, INPUT);
Serial.begin(115200);
setup_wifi();
timeClient.begin();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
setup_wifi();
}
if (!client.connected()) {
reconnect();
}
hallState = digitalRead(hallPin);
if (hallState == LOW) {
digitalWrite(ledPin, HIGH);
generateAndSendMessage();
delay(1000); //Add in a delay so it doesn't send messages extremely rapidly
} else {
digitalWrite(ledPin, LOW);
}
}
void generateAndSendMessage() {
timeClient.update();
StaticJsonBuffer<100> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["sensor"] = "doorbell";
root["time"] = timeClient.getEpochTime();
root["value"] = 1;
root.printTo(msg);
Serial.println(msg);
client.publish("/homeassistant/devices/doorbell", msg);
}
Looking at the generateAndSendMessage function, I believe you are having an issue due to the size of the MQTT buffer.
The MQTT buffer is by default set to 128 bytes. This includes the length of the channel name along with the message.
The length of you channel is 32 bytes, and the json buffer you used to make the message is 100 bytes long. So you might just be exceeding the 128 byte mark.
Just declare this before including the PubSubClient.h
#define MQTT_MAX_PACKET_SIZE 200
This macro defines the buffer size of the PubSubClient to 200. You can change it to whatever you believe is required.
I hope this helps.
I have programmed to my ESP8266 and subscribed one topic to keep listening messages. This is my graphical view of injecting message to IBM Iot node.
This is my settings of inject view
This is my settings of IBM Iot node.
Here are my logs at Serial Monitor, it is connected and subscribed to cmd channel
So far so good, When I am trying to inject a message to my IBM Iot node then it is not publishing a message, as it is not reaching on serial monitor and no log on debug view. here you can see
Here is source code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3
const char* ssid = "shiv";
const char* password = "manmohan#12345";
#define ORG "2kafk4"
#define DEVICE_TYPE "ESP8266"
#define DEVICE_ID "5CCF7FEED6F0"
#define TOKEN "opKF7v3#8jRM*mGkb_"
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/cmd/test/fmt/String";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int payloadLength) {
Serial.print("callback invoked for topic: "); Serial.println(topic);
for (int i = 0; i < payloadLength; i++) {
Serial.print((char)payload[i]);
}
}
PubSubClient client(server, 1883, callback, wifiClient);
void setup() {
Serial.begin(115200);
Serial.println();
wifiConnect();
mqttConnect();
}
void loop() {
if (!client.loop()) {
mqttConnect();
}
}
void wifiConnect() {
Serial.print("Connecting to "); Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("nWiFi connected, IP address: "); Serial.println(WiFi.localIP());
}
void mqttConnect() {
if (!client.connected()) {
Serial.print("Reconnecting MQTT client to "); Serial.println(server);
while (!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
initManagedDevice();
Serial.println();
}
}
void initManagedDevice() {
if (client.subscribe(topic)) {
Serial.println("subscribe to cmd OK");
} else {
Serial.println("subscribe to cmd FAILED");
}
}
I tried to check cloud foundry logs using cf command, here it is https://pastebin.com/dfMaS1Gd
Can anyone hint me what I am doing wrong ? Thanks in advance.
Confirm the device type is correctly specified in your node configuration. Currently the screenshot show 0.16.2 which doesn't seem to match the device type you registered and what is specified in your code.