Arduino void loop() stopped working after HttpClient request - arduino

I have an access control system that retrieves data from the database, the problem is if the RFID is not registered on the database, it gets stuck there and it does not scan for the RFID card anymore.
The same scenario when both the RFID and PIN Code matches with the database.
The loop stopped working after I have used Ethernet and HttpClient libraries.
Here's is my program code:
#include <SPI.h>
#include <Ethernet.h>
#include <ArduinoHttpClient.h>
#include <Keypad.h>
#include <MFRC522.h>
#include <Servo.h>
/////// RFID Settings ///////
#define SS_PIN 53
#define RST_PIN 10
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
/////// Ethernet Settings ///////
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 222);
char serverAddress[] = "192.168.1.51"; // server address
int port = 80;
/////// HttpClient Settings ///////
EthernetClient ethr;
HttpClient client = HttpClient(ethr, serverAddress, port);
int statusCode = 0;
/////// Keypad Settings ///////
char key[4];
int i = 0;
String pass;
const byte ROWS = 4; // Four rows
const byte COLS = 4; // columnsffff
// Define the Keymap
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = {29, 28, 27, 26}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {25, 24, 23, 22}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
/////// Servo Settings ///////
Servo lock; //declares servo
/////// Status Variables & Strings ///////
int rStatus = 0; // RFID Status
int pStatus = 0; // PIN Status
String getReq, tag, rfid, pincode;
void setup() {
/////// Starting Serial ///////
Serial.begin(9600);
delay(1000);
/////// Ethernet Setup ///////
Serial.println("Initializing Ethernet.");
Ethernet.begin(mac, ip);
Serial.println("Connection Success.");
Serial.println("");
delay(1000);
/////// RFID Setup ///////
Serial.println("Initializing RFID Module.");
mfrc522.PCD_Init(); // Initiate MFRC522
Serial.println("RFID Ready.");
Serial.println("");
delay(1000);
/////// Keypad Setup ///////
Serial.println("Initializing Keypad Module...");
keypad.addEventListener(keypadEvent); //add an event listener for this keypad
Serial.println("Keypad Ready.");
Serial.println("");
delay(1000);
/////// Servo Setup ///////
Serial.println("Setting up servo motor...");
lock.attach(13);
Serial.println("Servo Motor Ready.");
Serial.println("");
delay(1000);
/////// R E A D Y ///////
Serial.println("Please tap RFID Card.");
}
void loop() {
if (rStatus == 0)
{
readRFID();
}
else if (rStatus == 1)
{
keypad.getKey();
}
if (rStatus == 1 && pStatus == 1)
{
Serial.println("Door Unlocked.");
lock.write(5);
delay(5000);
lock.write(0);
rStatus = 0;
pStatus = 0;
delay(1000);
loop();
}
}
/////// Module Methods - RFID ///////
void readRFID()
{
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
//Show UID on serial monitor
Serial.print("RFID UID : ");
String content = "";
for (byte i = 0; i < mfrc522.uid.size; i++)
{
content.concat(String(mfrc522.uid.uidByte[i]));
}
Serial.println(content);
tag = String(content);
getTagRequest();
Serial.print("DB UID : ");
Serial.println(rfid);
if (tag == rfid) //change here the UID of the card/cards that you want to give access
{
Serial.print("Message : ");
Serial.println("UID Found.");
Serial.println();
delay(3000);
rStatus = 1;
Serial.println("Please enter 4 digit PIN.");
}
else {
Serial.println(" Access denied");
delay(3000);
rStatus = 0;
}
}
/////// Module Methods - Keypad ///////
void keypadEvent(KeypadEvent eKey)
{
switch (keypad.getState())
{
case PRESSED:
key[i] = eKey;
Serial.print("Enter: ");
Serial.println(eKey);
delay(10);
i++;
switch (eKey)
{
case '#': checkPassword(); delay(1); break;
case '*': i = 0; delay(1); break;
default: delay(1);
}
}
}
void checkPassword()
{
pass = "";
pass.concat(key[0]);
pass.concat(key[1]);
pass.concat(key[2]);
pass.concat(key[3]);
delay(1000);
getPinRequest();
Serial.print("Input PIN: ");
Serial.println(pass);
Serial.print("DB PIN: ");
Serial.println(pincode);
if (pass == pincode)
{
Serial.println("Message: PIN Accepted");
Serial.println("");
i = 0;
pStatus = 1;
delay(10);
} else
{
Serial.println("Message: PIN Denied"); //if passwords wrong keep box locked
i = 0;
pStatus = 0;
delay(10);
}
}
/////// Database Transactions via PHP ///////
void getTagRequest() {
//Making GET Request
getReq = "";
getReq.concat("/getTag.php?tag=");
getReq.concat(tag);
client.get(getReq);
rfid = client.responseBody();
client.stop();
delay(1000);
}
void getPinRequest() {
//Making GET Request
getReq = "";
getReq.concat("/getPin.php?tag=");
getReq.concat(tag);
getReq.concat("&pin=");
getReq.concat(pass);
client.get(getReq);
pincode = client.responseBody();
client.stop();
delay(1000);
}
So how do I fix this? I want the system to ask again for an RFID Card after having matched results from the db.

I figured this one out by not using any pins on my ethernet shield except for the 5v/3.3v and the GND only. It now works again and loops the whole program

Related

Unable to establish connection to mosquitto broker from Arduino+ESP8266

I am using Arduino Uno and ESP8266 for WIFI connectivity. My Laptop on which mosquitto broker is running and Arduino(through ESP8266) is are both connected to wifi network. But I am unable to establish a connection to mqtt server.
I am using the follwing code.
#define FASTLED_INTERNAL
#include <SoftwareSerial.h>
#include <DHT.h>
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
#include <PubSubClient.h>
#include <FastLED.h>
#define DHTPIN 2
#define DHTTYPE DHT11
#define ESP_RX 9
#define ESP_TX 8
#define WIFI_AP "Anurag"
#define WIFI_PASSWORD "qwerty12345"
#define NUM_LED 64
#define DATA_PIN 5
#define CLOCK_PIN 13
static const int RXPin = 4, TXPin = 3;
static const uint32_t baudRate = 9600;
static const int rainSensorMin = 0;
static const int rainSensorMax = 1024;
WiFiEspClient espClient;
PubSubClient mqttClient(espClient);
IPAddress broker(192,168,43,235);
SoftwareSerial ESP8266(ESP_RX, ESP_TX);
DHT dht(DHTPIN, DHTTYPE);
int status = WL_IDLE_STATUS;
char *ID = "uno";
char *TOPIC = "weatherStats";
int AT_cmd_time;
boolean AT_cmd_result = false;
CRGB leds[NUM_LED];
void setup() {
//pinMode(13, OUTPUT);
//FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LED);
Serial.begin(9600);
//ss.begin(baudRate);
initWiFi();
dht.begin();
mqttClient.setServer(broker,1883);
Serial.println("GPS, DHT11, and, Raindrop detector started.");
}
void loop() {
status = WiFi.status();
if ( status != WL_CONNECTED) {
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(WIFI_AP);
// Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(500);
}
Serial.println("Connected to AP");
}
delay(3000);
float h = dht.readHumidity();
float t = dht.readTemperature();
int rainReading = analogRead(A0);
int range = map(rainReading, rainSensorMin, rainSensorMax, 0, 2);
if(!mqttClient.connected()){
reconnect_mqtt();
}
mqttClient.loop();
mqttClient.publish(TOPIC,"one step forward");
//Serial.println("Satellites: " + String(gps.satellites.value()));
if (!isnan(h) || !isnan(t))
Serial.print("Temparture: " + String(t) + "°C | " + " Humidity: " + String(h) + " | ");
else {
Serial.println("Failed to obtain temparature and humidity data");
}
switch (range) {
case 0:
Serial.print("Rain Warning : 1");
break;
case 1:
Serial.print("Rain Warning : 0");
break;
}
Serial.println(" | Lat: 22.716191217468406 Lon: 72.44229199663788");
}
void initWiFi(){
ESP8266.begin(9600);
WiFi.init(&ESP8266);
// 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(WIFI_AP);
//Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
}
}
void reconnect_mqtt(){
while(!mqttClient.connected()){
Serial.println("Attempting MQTT Connection");
if(mqttClient.connect(ID)){
Serial.println("MQTT connection established.");
Serial.print("Publishing to: ");
Serial.println(TOPIC);
}
else{
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
Runnig this code I keep getting output "try again in 5 seconds". Please help.

Arduino returning wrong integer value

I have some code, that turns a LED on/off based on a value on a website (blank page containing a number. The number on the page indicate the number of times the LED should flash.
The problem is that the loop keep running.
I can fix the problem by setting the integer value manually (int c = 3).
Not sure what my problem is.
Maybe one of you can point me in the right direction.
Url: http://b2b.as/lan.php?pid=8855
Code:
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 104 };
char server[] = "b2b.as";
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println(Ethernet.localIP());
Serial.println();
// Set digital pin as output
// 5V
pinMode(8, OUTPUT);
}
void loop()
{
//
Serial.print("\n-----\n");
// Connect to the server
Serial.print("connecting to URL ...");
// Start LAN connection
EthernetClient client;
if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /lan.php?pid=8855");
client.println();
} else {
Serial.println("connection failed");
}
// Wait a moment for data to arrive
// Note: This is NOT a reliable way of doing this!
delay(1000);
if (client.available() > 0) {
char c = atoi(client.read());
Serial.print("page value (pick): ");
Serial.print(c, DEC);
Serial.print("\n");
for (int x = 1; x <= int(c); x++) {
Serial.print("picking: #");
Serial.println(x);
digitalWrite(8, HIGH);
Serial.println("8 HIGH ...");
delay(5000); // Add switch
digitalWrite(8, LOW);
Serial.println("8 LOW ...");
delay(1000);
}
Serial.print("end");
}
// Disconnect the client
if (client.connected()) {
//Serial.println();
Serial.print("disconnecting");
client.stop();
}
// Wait another 9s, which will give us a delay of roughly 10s
delay(9000);
}
I assume that the call to lan.php?pid=8855 will just return the value without any formatting, e.g., HTML, XML, JSON. Then your code basically converts the ASCII character 3 to an integer which gives you the integer value 33 (see ASCII Table). Therefore, your loop won't stop.
Solution
Just use the atoi function to convert it to an integer.
char c = atoi(client.read());
It seems that toInt() was the function I was looking for. It convert a string to integer and fixes the loop.
https://www.arduino.cc/en/Reference/StringToInt
Code has been updated and it seems to work:
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 104 };
char server[] = "b2b.as";
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println(Ethernet.localIP());
Serial.println();
// Set digital pin as output
// 5V
pinMode(8, OUTPUT);
}
void loop()
{
//
Serial.print("\n-----\n");
// Connect to the server
Serial.print("connecting to URL ...");
// Start LAN connection
EthernetClient client;
if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /lan.php?pid=8855");
client.println();
} else {
Serial.println("connection failed");
}
// Wait a moment for data to arrive
// Note: This is NOT a reliable way of doing this!
delay(1000);
if (client.available() > 0) {
String pickNum;
while (client.available()) {
char c = client.read(); // gets one byte from serial buffer
pickNum += c; // count
delay(2); // delay for buffer
}
Serial.print("page value (pick): ");
Serial.println(pickNum);
for (int x = 1; x <= pickNum.toInt(); x++) {
Serial.print("picking: #");
Serial.println(x);
digitalWrite(8, HIGH);
Serial.println("8 HIGH ...");
delay(1000); // Add switch
digitalWrite(8, LOW);
Serial.println("8 LOW ...");
delay(1000);
}
Serial.print("end");
}
// Disconnect the client
if (client.connected()) {
//Serial.println();
Serial.print("disconnecting");
client.stop();
}
// Wait another 9s, which will give us a delay of roughly 10s
delay(9000);
}

integrating the AdafruitFona GSM shield with tiny gps library

i need help in integrating the two libraries so that i can send the GPS data via GSM . Information regarding the use of two special Serial is needed and also a help with the code is needed .
The below segmnet containts the code for the GPS shield this has to be used to generate the location and this data has to be sent via gsm to a mobile number.
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
It requires the use of SoftwareSerial, and assumes that you have a
4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 4, TXPin = 3;//was 4 and 3;
static const uint32_t GPSBaud = 9600;
// The TinyGPS++ object
TinyGPSPlus gps;
// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);
void setup()
{
Serial.begin(115200);
ss.begin(GPSBaud);
Serial.println(F("GPS GSM tracking system"));
Serial.println(F("Sabdadon Presents"));
Serial.print(F("Search and Rescue")); Serial.println(TinyGPSPlus::libraryVersion());
Serial.println(F("Sabarish"));
Serial.println();
}
void loop()
{
// This sketch displays information every time a new sentence is correctly encoded.
while (ss.available() > 0)
if (gps.encode(ss.read()))
displayInfo();
if (millis() > 500000 && gps.charsProcessed() < 10)
{
Serial.println(F("No GPS detected: check wiring."));
while(true);
}
}
void displayInfo()
{
delay(10000);
Serial.print(F("Location: "));
if (gps.location.isValid())
{
Serial.print(gps.location.lat(), 5);
Serial.print(F(","));
Serial.print(gps.location.lng(), 5);
// latitude=gps.location.lat();
//longitude=gps.location.lng();
//if(latitude && longitude)
}
else
{
Serial.print(F("INVALID"));
}
Serial.print(F(" Date/Time: "));
if (gps.date.isValid())
{
Serial.print(gps.date.month());
Serial.print(F("/"));
Serial.print(gps.date.day());
Serial.print(F("/"));
Serial.print(gps.date.year());
}
else
{
Serial.print(F("INVALID"));
}
Serial.print(F(" "));
if (gps.time.isValid())
{
if (gps.time.hour() < 10) Serial.print(F("0"));
Serial.print(gps.time.hour());
Serial.print(F(":"));
if (gps.time.minute() < 10) Serial.print(F("0"));
Serial.print(gps.time.minute());
Serial.print(F(":"));
if (gps.time.second() < 10) Serial.print(F("0"));
Serial.print(gps.time.second());
Serial.print(F("."));
if (gps.time.centisecond() < 10) Serial.print(F("0"));
Serial.print(gps.time.centisecond());
}
else
{
ss.read();
Serial.print(F("INVALID"));
}
Serial.println();
}
FOR GSM
#include "Adafruit_FONA.h"
#define FONA_RX 2//2
#define FONA_TX 3//3
#define FONA_RST 4//4
char replybuffer[255];
#include <SoftwareSerial.h>
#include <AltSoftSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);
uint8_t type;
void setup()
{
while (!Serial);
Serial.begin(115200);
Serial.println(F("FONA basic test"));
Serial.println(F("Initializing....(May take 3 seconds)"));
fonaSerial->begin(4800);
if (! fona.begin(*fonaSerial)) {
Serial.println(F("Couldn't find FONA"));
while (1);
}
type = fona.type();
Serial.println(F("FONA is OK"));
Serial.print(F("Found "));
switch (type) {
case FONA800L:
Serial.println(F("FONA 800L")); break;
case FONA800H:
Serial.println(F("FONA 800H")); break;
case FONA808_V1:
Serial.println(F("FONA 808 (v1)")); break;
case FONA808_V2:
Serial.println(F("FONA 808 (v2)")); break;
case FONA3G_A:
Serial.println(F("FONA 3G (American)")); break;
case FONA3G_E:
Serial.println(F("FONA 3G (European)")); break;
default:
Serial.println(F("???")); break;
}
// Print module IMEI number.
char imei[15] = {0}; // MUST use a 16 character buffer for IMEI!
uint8_t imeiLen = fona.getIMEI(imei);
if (imeiLen > 0) {
Serial.print("Module IMEI: "); Serial.println(imei);
}
}
void loop()
{ Serial.print(F("FONA> "));
while (! Serial.available() ) {
if (fona.available()) {
Serial.write(fona.read());
}
}
// send an SMS!
char sendto[21], message[141];
flushSerial();
Serial.print(F("Send to #"));
readline(sendto, 20);
Serial.println(sendto);
Serial.print(F("Type out one-line message (140 char): "));
readline(message, 140);
Serial.println(message);
if (!fona.sendSMS(sendto, message)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("Sent!"));
}
}
void flushSerial() {
while (Serial.available())
Serial.read();
}
char readBlocking() {
while (!Serial.available());
return Serial.read();
}
uint16_t readnumber() {
uint16_t x = 0;
char c;
while (! isdigit(c = readBlocking())) {
//Serial.print(c);
}
Serial.print(c);
x = c - '0';
while (isdigit(c = readBlocking())) {
Serial.print(c);
x *= 10;
x += c - '0';
}
return x;
}
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) {
uint16_t buffidx = 0;
boolean timeoutvalid = true;
if (timeout == 0) timeoutvalid = false;
while (true) {
if (buffidx > maxbuff) {
//Serial.println(F("SPACE"));
break;
}
while (Serial.available()) {
char c = Serial.read();
//Serial.print(c, HEX); Serial.print("#"); Serial.println(c);
if (c == '\r') continue;
if (c == 0xA) {
if (buffidx == 0) // the first 0x0A is ignored
continue;
timeout = 0; // the second 0x0A is the end of the line
timeoutvalid = true;
break;
}
buff[buffidx] = c;
buffidx++;
}
if (timeoutvalid && timeout == 0) {
//Serial.println(F("TIMEOUT"));
break;
}
delay(1);
}
buff[buffidx] = 0; // null term
return buffidx;
}
Here is a step-by-step to mix your GPS input device and your GSM output device.
Remainder for Arduino principles:
The void setup() function is performed one time after startup.
The void loop() function is performed periodically after the
setup().
Step1 - declaration of GPS device and Serial link
// GPS and Serial link
static const int RXPin = 4, TXPin = 3;//was 4 and 3;
static const uint32_t GPSBaud = 9600;
// The TinyGPS++ object
TinyGPSPlus DeviceGPS;
// The serial connection to the GPS device
SoftwareSerial SerialGPS(RXPin, TXPin);
Step2 - declaration of GSM/FONA device and Serial link
Including the SendTo SMS number !!!
#define FONA_RX 2//2
#define FONA_TX 3//3
#define FONA_RST 4//4
// The serial connection to the GSM device
SoftwareSerial SerialFONA = SoftwareSerial(FONA_TX, FONA_RX);
// The FONA/GSM Cellular Module device
Adafruit_FONA DeviceFONA = Adafruit_FONA(FONA_RST);
// The destination SMS number
static const char *sSendTo = "<NUMBER>";
Step3 - setup() function for (Console, GPS and GSM)
It is possible to add some extra Init.
// only execute once
void setup()
{
// Wait and Init Console
while (!Serial); // Serial over USB
Serial.begin(115200);
// Init GPS link
SerialGPS.begin(GPSBaud);
Serial.print(F("TinyGPSPlus ver: "));
Serial.println(TinyGPSPlus::libraryVersion());
// Init GSM link
SerialFONA.begin(4800);
if (! DeviceFONA.begin(SerialFONA)) {
Serial.println(F("Couldn't find FONA"));
while (1); // Stop working
}
// Add some extra Init
}
Step4 - loop() function to wait GPS location and send SMS
It is possible to use String() to create the SMS based on the
acquired DeviceGPS.location.lng() and DeviceGPS.location.lat().
// executed periodicaly
void loop()
{
// check until GPS message
while (SerialGPS.available() > 0) {
// get for a complete GPS message
DeviceGPS.encode(SerialGPS.read());
}
// flush GSM serial link
while (SerialFONA.available() > 0) {
if (DeviceFONA.available()) {
DeviceFONA.flush();
}
}
// send an SMS!
char sendto[21], message[141];
// Wait for location (lng, lat, alt) is OK
if (DeviceGPS.location.isValid()) {
// ==> create SMS with longitude & latitude
}
}

Openhab doesn't change the status of switch from manual overide

I have just made an account because of this particular problem I'm having with OpenHAB. I was following a tutorial from this https://openhardwarecoza.wordpress.com/2015/03/29/openhab-mqtt-arduino-and-esp8266-part-3-hardware-arduino-with-ethernet-shield/ site but since the reply there didn't help me. I decided to go to this site.
I have successfully installed OpenHAB and use it. When I turn the switch off and on from both the HTTP page and android device, It works just fine. But when I tried to manual override using a push button on an Arduino. It didn't update the state of the switch in both of them. I'm using windows with OpenHAB version 1.71
The Openhab server notices that there is an update of the state from the push button, but the button in the HTTP page and android device didn't change at all.
I have tested the connection using MQTTlens and it works just fine.
Below is my code
items configuration
Group All
Switch mqttsw1 "Switch 1" (all) {mqtt=">[mymosquitto:/arduino/l1/com:command:off:0],>[mymosquitto:/arduino/l1/com:command:on:1],<[mymosquitto:/arduino/l1/state:state:default]"}
Switch mqttsw2 "Switch 2" (all) {mqtt=">[mymosquitto:/arduino/l2/com:command:off:0],>[mymosquitto:/arduino/l2/com:command:on:1],<[mymosquitto:/arduino/l2/state:state:default]"}
Number temp "Temperature [%.1f °C]" <temperature> {mqtt="<[mymosquitto:/arduino/temp/state:state:default]"}
Number hum "Humidity [%.1f &#37]" <temperature> {mqtt="<[mymosquitto:/arduino/hum/state:state:default]"}
Sitemap configuration
sitemap dolphin label="Main Menu"
{
Frame label="Switch" {
Switch item=mqttsw1 label="Switch 1"
Switch item=mqttsw2 label="Switch 2"
}
Frame label="Weather" {
Text item=temp
Text item=hum
}
The Arduino Code
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <DHT.h>
const int butt1 = 3;// the pin that the pushbutton is attached to
const int butt2 = 2;
const int ledPin1 = 5;
const int ledPin2 = 4;
int ledState1 = HIGH;
int buttonState1;
int lastButtonState1 = LOW;
int ledState2 = HIGH;
int buttonState2;
int lastButtonState2 = LOW;
long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 60000; // READING INTERVAL
int t = 0; // TEMPERATURE VAR
int h = 0; // HUMIDITY VAR
#define DHTPIN 24 // SENSOR PIN
#define DHTTYPE DHT11 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xEF };
IPAddress ip(192, 168, 1, 103);
IPAddress server(192, 168, 1, 100);
void callback(char* topic, byte* payload, unsigned int length);
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println();
Serial.println("Callback");
Serial.print("Topic = ");
Serial.println(topic);
Serial.print("Payload = ");
for (int i=0;i<length;i++){
Serial.print((char)payload[i]);
}
Serial.println();
if (strcmp(topic,"/esp1/l1/com")==0) {
if (payload[0] == '0')
{
digitalWrite(ledPin1, LOW);
delay(100);
client.publish("/esp1/l1/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(ledPin1, HIGH);
delay(100);
client.publish("/esp1/l1/state","1");
}
}
if (strcmp(topic,"/esp1/l2/com")==0) {
if (payload[0] == '0')
{
digitalWrite(ledPin2, LOW);
delay(100);
client.publish("/esp1/l2/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(ledPin2, HIGH);
delay(100);
client.publish("/esp1/l2/state","1");
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
client.subscribe("/esp1/#");
client.publish("conn","Connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void push1() {
int reading1 = digitalRead(butt1);
buttonState1 = reading1;
if (buttonState1 == HIGH) {
ledState1 = !ledState1;
if (ledState1 < 1)
{
digitalWrite(ledPin1, LOW);
delay(100);
client.publish("/esp1/l1/com","0");
client.publish("/esp1/l1/state","0");
}
else
{
digitalWrite(ledPin1, HIGH);
delay(100);
client.publish("/esp1/l1/com","1");
client.publish("/esp1/l1/state","1");
}
}
}
void push2() {
int reading2 = digitalRead(butt2);
buttonState2 = reading2;
if (buttonState2 == HIGH) {
ledState2 = !ledState2;
if (ledState2 < 1)
{
digitalWrite(ledPin2, LOW);
delay(100);
client.publish("/esp1/l2/com","0");
client.publish("/esp1/l2/state","0");
}
else
{
digitalWrite(ledPin2, HIGH);
delay(100);
client.publish("/esp1/l2/com","1");
client.publish("/esp1/l2/state","1");
}
}
}
void temp() {
h = (int)dht.readHumidity();
t = (int)dht.readTemperature();
char temp[2];
char hum[3];
sprintf(hum, "%d", h);
sprintf(temp, "%d", t);
client.publish("/esp1/temp/state", temp);
client.publish("/esp1/hum/state", hum);
}
void setup() {
// put your setup code here, to run once:
pinMode(butt1, INPUT);
pinMode(butt2, INPUT);
// initialize the LED as an output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
Serial.begin(9600);
Ethernet.begin(mac, ip);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
pinMode(26, OUTPUT); // sets the digital pin as output
pinMode(22, OUTPUT); // sets the digital pin as output
digitalWrite(26, HIGH); // sets +5v for the sensor
digitalWrite(22, LOW); // sets gnd for the sensor
h = (int)dht.readHumidity();
t = (int) dht.readTemperature();
if (client.connect("arduinoClient")) {
client.publish("conn","Connected");
client.subscribe("/esp1/#");
}
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect();
}
currentMillis = millis();
if (currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
previousMillis = currentMillis;
temp();
}
int reading1 = digitalRead(butt1);
int reading2 = digitalRead(butt2);
if (reading1 != buttonState1) {
push1();
}
if (reading2 != buttonState2){
push2();
}
client.loop();
}
If there are anybody who can help me I would be very grateful. Thank you for your attention !
Best Regards,
Aldi
If I remember correctly you should post back a status of ON or OFF instead of 1 or 0.
Could you change your arduino code to publish back ON and OFF and test that?
e.g.
client.publish("/esp1/l1/state","ON");

Xbee communication in api mode between two arduinos

I have two Arduino Unos, two lcds and Xbee s2.
I connected two xbee s2 module to each arduino uno.
I searched this implementation hard and tried it.
but, it didn't work. I appreciate your help.
Configuration: AP=2
Coordinator API and Router API
Sender: Router
#include <XBee.h>
#include <SoftwareSerial.h
#include <LiquidCrystal.h>
#define LED 13
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
SoftwareSerial xSerial(3,4);
XBee xbee=XBee();
ZBTxStatusResponse txStatus = ZBTxStatusResponse();
void setup(){
//Serial.begin(9600);
xSerial.begin(9600);
xbee.setSerial(xSerial);
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, Gang!");
//Serial.println("xbee start");
pinMode(LED, OUTPUT);
digitalWrite(LED, HIGH);
delay(3000);
}
void loop(){
ZBTxRequest zbTx;
uint8_t payload[]={'H', 'E', 'Y', '\0'};
XBeeAddress64 address=XBeeAddress64(0x13a200, 0x40b450f4);
zbTx=ZBTxRequest(address, payload, sizeof(payload));
xbee.send(zbTx);
if (xbee.readPacket(500)) {
if (xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE) {
xbee.getResponse().getZBTxStatusResponse(txStatus);
// get the delivery status, the fifth byte
if (txStatus.getDeliveryStatus() == SUCCESS) {
lcd.setCursor(0,1);
lcd.print("Success");
} else {
// the remote XBee did not receive our packet. is it powered on?
}
}
} else if (xbee.getResponse().isError()) {
//nss.print("Error reading packet. Error code: ");
//nss.println(xbee.getResponse().getErrorCode());
} else {
// local XBee did not provide a timely TX Status Response -- should not happen
}
delay(1000);
}
Receiver: Coordinator
#include <SoftwareSerial.h>
#include <XBee.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
SoftwareSerial xSerial(3,4);
XBee xbee=XBee();
XBeeResponse response = XBeeResponse();
// create reusable response objects for responses we expect to handle
ZBRxResponse rx = ZBRxResponse();
void setup(){
xSerial.begin(9600);
xbee.setSerial(xSerial);
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, tang!");
delay(3000);
}
void loop(){
xbee.readPacket();
if (xbee.getResponse().isAvailable()) {
// got something
lcd.setCursor(0, 1);
lcd.print( "MSG");
if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE) {
// got a zb rx packet
// now fill our zb rx class
xbee.getResponse().getZBRxResponse(rx);
lcd.setCursor(0, 1);
lcd.print(rx.getData(1));
if (rx.getOption() == ZB_PACKET_ACKNOWLEDGED) {
// the sender got an ACK
lcd.setCursor(0,1);
lcd.print( "ACK");
} else {
lcd.setCursor(0,1);
lcd.print("ERROR");
}
} else {
// not something we were expecting
//flashLed(errorLed, 1, 25);
lcd.print("7 print");
}
} else if (xbee.getResponse().isError()) {
lcd.print("error");
}
delay(3000);
}
Ah, I connect xbee s2 to xbee pro shield on arduino. There are no dline/uart switch on xbee shield. so, I use softwareserial library...But it didn't work.
I have done the communication between two XBee with Arduino, you can take a look at my coding and try to change your coding a little bit.
Sender =
#include <SoftwareSerial.h>
#define Dout 2
#define Din 3
#define LED 9
SoftwareSerial XBeeSerial (Dout, Din);
void setup() {
XBeeSerial.begin(9600);
pinMode(LED, OUTPUT);
}
void loop() {
delay(500);
XBeeSerial.write("+");
analogWrite(LED,13);
delay(3000);
XBeeSerial.write("-");
analogWrite(LED,0);
delay(500);
}
Receiver =
#include<SoftwareSerial.h>
#define LED 9
#define Dout 2
#define Din 3
SoftwareSerial XBeeSerial( Dout, Din);
char XBee_message;
void setup() {
Serial.begin(9600);
XBeeSerial.begin(9600);
pinMode(LED, OUTPUT);
}
void loop() {
while(XBeeSerial.available()) {
XBee_message = XBeeSerial.read();
Serial.print(XBee_message);
switch (XBee_message){
case '+':
analogWrite(LED, 13);
break;
case '-':
analogWrite(LED, 0);
break;
default:
analogWrite(LED, 0);
}
}
}

Resources