Blink Led using MQTT in arduino - arduino

I have to implement a prototyping scenario that blink LED in the arduino with MQTT protocol. I already tried with several MQTT libraries but non of them not work perfectly. Connection to the MQTT broker working successfully but when I publish the message with topic which I set in arduino not blink the LED. Arduno have to publish a message when it successfully connect but this publishing part also not working
this is my code
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Set the MAC address
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 100);
IPAddress server(192, 168, 1, 20);
// Set what PINs our Led's are connected to
int redPin = 13;
//int greenPin = 6;
//int bluePin = 7;
// Set a generic code that will trigger our Blue Led
// think of this as a set of codes for automation you might write
byte triggerRed[13] = "12345";
// handles messages that are returned from the broker on our subscribed channel
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("New message from broker on topic:");
Serial.println(topic);
Serial.print("Payload:");
Serial.write(payload, length);
// Check and see if our payload matches our simple trigger test
if ((length == 5) & (memcmp(payload, triggerRed, 5) == 0) )
{
//blink(redPin);
}
}
EthernetClient ethClient;
PubSubClient client(ethClient);
// Fire up our PubSub client
//PubSubClient client(server, 1883, callback);
void setup()
{
// Open serial communications
Serial.begin(9600);
client.setServer(server, 1883);
client.setCallback(callback);
// Setup our Leds
pinMode(redPin, OUTPUT);
// pinMode(greenPin, OUTPUT);
// pinMode(bluePin, OUTPUT);
// attempt a DHCP connection
Serial.println("Attempting to get an IP address using DHCP:");
if (!Ethernet.begin(mac))
{
// if DHCP fails, start with a hard-coded address:
Serial.println("failed to get an IP address using DHCP, trying manually");
Ethernet.begin(mac, ip);
}
Serial.print("My address:");
Serial.println(Ethernet.localIP());
// Connect to Broker, give it arduino as the name
if (client.connect("arduino")) {
// Good, we connected turn on the red led
digitalWrite(redPin, HIGH);
// Publish a message to the status topic
client.publish("status","Arduino is now online");
// Listen for messages on the control topic
client.subscribe("ultra");
}
}
void loop()
{
client.loop();
}
// Anything with flashing lights.
void blink(int targetLed)
{
digitalWrite(redPin, HIGH);
}
how can I fix this ?

Put connection routine in a loop and try with test.mosquitto.org first.
Here is code that works for me (Ethernet shield hardware):
definitions:
#define CLIENT_NAME "myclientname"
#define TOPIC "mytopic"
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 105);
IPAddress server(85, 119, 83, 194);// test.mosquitto.org
#define MQTT_PORT 1883
IPAddress myDns(8, 8, 8, 8);
EthernetClient ethClient;
PubSubClient client(ethClient);
setup:
client.setServer(server, MQTT_PORT);
client.setCallback(callback);
Ethernet.begin(mac);
loop:
if (!client.connected()) {
reconnect();
}
client.loop();
reconnect routine
void reconnect() {
if (millis() - reconnectionTimer >reconnection_period){// Loop until we're reconnected
reconnectionTimer = millis();
if (!client.connected()) {
// Attempt to connect
if (client.connect(CLIENT_NAME)) {
client.subscribe(TOPIC);
}
else {
Serial.print(client.state());
Serial3.print(client.state());
}
}
}
}
update for blink:
void blink(){
digitalWrite(led, LOW);
delay(500);
digitalWrite(led, HIGH);
}

I lost a lot of time because i had the problem with the mqtt server. ensure that your server is using mqtt protocol, because i was using ws protocol and any library that I tried doesn't works with this protocol

Related

Simple Arduino Client Server communication via Ethernet, IP

Simple Ethernet communication between two Arduino boards. I used two Arduino UNO boards, Two Arduino Ethernet Shields.
Here is my Server Code
//Server
#include <SPI.h>
#include <Ethernet.h>
// network configuration. gateway and subnet are optional.
// the media access control (ethernet hardware) address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
//the IP address for the shield:
byte ip[] = { 192,168,1,180 };
// the router's gateway address:
byte gateway[] = { 192, 168, 1, 1 };
// the subnet:
byte subnet[] = { 255, 255, 255, 0 };
EthernetServer server = EthernetServer(10001);
void setup()
{
// initialize the ethernet device
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();
}
void loop()
{
// if an incoming client connects, there will be bytes available to read:
EthernetClient client = server.available();
if (client == true) {
// read bytes from the incoming client and write them back
// to any clients connected to the server:
server.write(client.read());
}
}
Here is my Client Code
//Client
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xEC};
IPAddress ip(192,168,1,177);
IPAddress server(192,168,1,180);
EthernetClient client(10001);
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
if (client.connect(server, 10001)) {
Serial.println("connected");
client.println("GET /search?q=arduino HTTP/1.0");
client.println();
} else {
Serial.println("connection failed");
}
}
void loop()
{
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}
}
I input those two codes to two Arduino boards. Wiring and other connection are correct and reliable.
But I got this output from client serial monitor
connecting...
connection failed
disconnecting.
According to my view, error may happen in client code. Can you help me to find the error?

This code should upload a value to a database through a php file

I'm using an arduino and an Ethernet shield to upload data to a server.
Lately i changed from using a local database to use a web hosting service (000webhost) but i can't make it work, no errors are shown in the Arduino IDE but it just stops in the line where it says "MAKING INSERTION".
Everything was working fine when i had the database locally.
When i enter the url directly into the browser
mythesisinacap.000webhostapp.com/writemydata.php?value=0 it works fine inserting the apropriate value into the database...so that means that there's nothing wrong with the php file in the server.
Here's my code.
#include <Ethernet.h>
int isparked;
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
// Enter the IP address for Arduino
// Be careful to use , insetead of . when you enter the address here
IPAddress ip(192, 168, 0, 170);
int vcc = 5; //attach pin 2 to vcc
int trig = 6; // attach pin 3 to Trig
int echo = 7; //attach pin 4 to Echo
int gnd = 8; //attach pin 5 to GND
char server[] = "mythesisinacap.000webhostapp.com";
// Initialize the Ethernet server library
EthernetClient client(80);
void setup()
{
isparked=0;
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
}
void loop() {
if (client.connect(server, 80))
{
Serial.print("CONNECTED");
Serial.println();
Serial.print("MAKING INSERTION");
Serial.println();
client.print("GET /writemydata.php?value=");
client.print(isparked5);
client.println(" HTTP/1.1");
client.println("Host: mythesisinacap.000webhostapp.com");
client.println("Connection: close");
client.println();
client.println();
client.stop();
}
else
{
Serial.print("NO CONNECTION");
}
}
}
}
}
Serial.println();
Serial.print("FINNISH LOOPING");
Serial.println();
}
Ok i finally got it to work with my web hosted database, i used this example from github and adapted it to my case, now i'll have to add my sensor logic and calculation.
https://github.com/adafruit/Ethernet2/blob/master/examples/WebClient/WebClient.ino
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xDD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "mythesis2017.000webhostapp.com"; // name address for Google (using DNS)
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
void setup()
{
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
delay(10000);
insert();
}
}
void insert()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, 80))
{
Serial.println("connected");
// Make a HTTP request:
client.println("GET /writemydata.php?val=1 HTTP/1.1");
client.println("Host: mythesis2017.000webhostapp.com");
client.println("Connection: close");
client.println();
}
else
{
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
}

Arduino PubSubClient fail to connect to Mosquitto

I'm trying to complete my brewing system with Arduino, Raspberry, mqtt, MySql, Php.
I want to switch from sending data via serial port to ethernet+MQTT.
When I try to publish-subscribe with PubSubClient everything goes well. But whenever I try to put the DallasTemperature begin() function it can't connect anymore to the broker.
As soon as I remove the instruction sensors.begin(); it restarts and works perfectly.
Any of you knows why the hell is acting like this?
Here the code:
#include <OneWire.h>
#include <DallasTemperature.h>
#include <SPI.h>
#include <PubSubClient.h>
#include <Ethernet.h>
#define ONE_WIRE_BUS 10
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature Sensors(&oneWire);
// Pins
const int photocellPin = 1; // the cell and 10K pulldown are connected to a1
// Variables
String lightC;
unsigned long time;
char message_buffer[100];
// Network Settings
// MAC address of ethernet shield
// Look for it on a sticket at the bottom of the shield.
// Old Arduino Ethernet Shields or clones may not have a dedicated MAC address. Set any hex values here.
byte MAC_ADDRESS[] = { 0xFE, 0xED, 0xDE, 0xAD, 0xBE, 0xED };
// IP address of MQTT server
byte MQTT_SERVER[] = { 192, 168, 2, 46 }; // 10, 192, 191, 77 { 192, 168, 1, 115 };
// Handles messages arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Messaggio ricevuto [");
Serial.print(topic);
Serial.print("]");
for (int i = 0; i < length; i++) {
char receivedChar = (char)payload[i];
Serial.print(receivedChar);
}
Serial.println();
}
EthernetClient ethClient;
PubSubClient client(MQTT_SERVER, 1883, callback, ethClient);
IPAddress ip(192, 168, 2, 177);
void setup()
{
// Initilize serial link for debugging
Serial.begin(9600);
Ethernet.begin(MAC_ADDRESS, ip);
delay(2000);
// initialize the digital pin's as an output.
Serial.println("connected...");
Sensors.begin();
Serial.println("initialized..."); // Just for checking
}
void loop()
{
if (!client.connected()) {
reconnect();
}
lightC = dtostrf(analogRead(photocellPin), 5, 2, message_buffer); // TMP36 sensor calibration
Serial.println(lightC);
delay(2000);
// Publish sensor reading every X milliseconds
if (millis() > (time + 60000)) {
time = millis();
client.publish("fromarduino", (char*)lightC.c_str());
}
// MQTT client loop processing
client.loop();
}
void reconnect()
{
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("mb-arduino")) {
Serial.println("MQTT connected");
client.publish("fromarduino/alive", "I'm alive!");
client.subscribe("toarduino");
}
else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
It always returns error rc=-2.

mqtt between esp8266 and arduino with PubSubclient

I am using ESP8266 with arduino using WiFiEsp library.I want to make MQTT connection with arduino so I use PubSubclient library.i got error:
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
my code is:
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
#include "SoftwareSerial.h"
#include <PubSubClient.h>
IPAddress server(212, 72, 74, 21);
char ssid[] = "atmel"; // your network SSID (name)
char pass[] = "bets56789"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
// Initialize the Ethernet client object
WiFiEspClient espClient;
PubSubClient client(espClient);
SoftwareSerial soft(2,3); // RX, TX
void setup() {
// initialize serial for debugging
Serial.begin(9600);
// initialize serial for ESP module
soft.begin(115200);
// initialize ESP module
WiFi.init(&soft);
// 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);
}
// you're connected now, so print out the data
Serial.println("You're connected to the network");
//delay(2000);
//connect to MQTT server
client.setServer(server, 1883);
client.setCallback(callback);
}
//print any message received for subscribed topic
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();
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect();
}
client.loop();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect, just a name to identify the client
if (client.connect("arduinoClient")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outSHADAB","hello world");
// ... and resubscribe
client.subscribe("inShadab");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
I am using ESP8266 with arduino using WiFiEsp library.I want to make MQTT connection with arduino so I use PubSubclient library
I don't think the PubSubClient supports the WiFiEsp as a network layer from an arduino.
While the doc list the ESP8266 I believe this is running the PubSubClient directly on the ESP8266 hardware.

Arduino Knolleary PubSubClient will publish messages but can't receive them

I am using the Knolleary PubSubClient to make a connection to my MQTT server. I have been able to successfully authenticate and make a connection after not much work. I can even publish messages to topics. However, the issue I am having is that I can subscribe to topics and get no error, but when I publish to that topic (from mosquitto on my Mac) the callback does not get called and the message to the subscribe topic does not appear to be received. I have tried running a mosquitto subscription to the same topic at the same time, and that does receive the published message. Not sure if there is a problem in my callback code or what is going on here. Any help would be appreciated. Arduino code is below:
/*
Basic MQTT example
- connects to an MQTT server
- publishes "hello world" to the topic "outTopic"
- subscribes to the topic "inTopic"
*/
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte server[] = { 10, 2, 63, 123 };
byte ip[] = { 192, 168, 1, 10 };
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println(topic);
//convert byte to char
payload[length] = '\0';
String strPayload = String((char*)payload);
Serial.println(strPayload);
//int valoc = strPayload.lastIndexOf(',');
//String val = strPayload.substring(valoc+1);
//Serial.println(val);
}
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void setup()
{
Serial.begin(19200);
Serial.println("==STARTING==");
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
//delay(500);
boolean con = client.connect("1", "3snzzon5dyade:abc", "OBSCURED_FOR_SEC");
while(con != 1){
Serial.println("no con-while");
con = client.connect("1", "3snzzon5dyade:abc", "OBSCURED_FOR_SEC");
}
//Serial.println(con);
if(con){
Serial.println("got con");
client.publish("testq","hello world");
client.subscribe("testq");
}else Serial.println("no con");
}
void loop()
{
client.loop();
}
Like I said, I can see everything working properly with mosquitto. I have even tried matching up client_ids with no luck. Any help or ideas would be greatly appreciated.
your subscribe topic "testq" must be in an array like
char testq[] = {'t', 'e', 's', 't', 'q', '\0'};
be sure to finisht your array with an ,'\0'
Then you subscribe with:
client.subscribe(testq);

Resources