AttachIntrerrupt stops NRF24L01+ from working - ARDUINO - arduino

If I remove attachInterrupt(digitalPinToInterrupt(encoder1),readEncoder,RISING); The code works. But once its added, the radio.available doesnt let anything under it run.
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
struct InputData // define stuct
{
int x;
int y;
};
InputData data;
// Motor A connections
int motor_enA = 9;
int motor_in1 = 10;
int motor_in2 = 6;
int encoder1 = 2;
int encoder2 = 3;
int counter = 0;
int angle = 0;
void setup() {
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1, address);
radio.setPALevel(RF24_PA_MIN);
radio.startListening();
// Set all the motor control pins to outputs
pinMode(motor_enA, OUTPUT);
pinMode(motor_in1, OUTPUT);
pinMode(motor_in2, OUTPUT);
// Turn off motors - Initial state
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, LOW);
analogWrite(motor_enA, 255);
pinMode (encoder1, INPUT);
pinMode (encoder2, INPUT);
attachInterrupt(digitalPinToInterrupt(encoder1),readEncoder,RISING);
}
void loop() {
readEncoder();
if (radio.available()) {
radio.read(&data, sizeof(data));
// Serial.println(data.y);
if (data.y > 5) {
digitalWrite(motor_in1, HIGH);
digitalWrite(motor_in2, LOW);
}
else if (data.y < -5) {
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, HIGH);
}
else {
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, LOW);
}
}
if(counter>1){
counter=0;
angle+=2;
}else if(counter<-1){
counter=0;
angle-=2;
}
Serial.print("Position: ");
Serial.println(angle);
}
void readEncoder()
{
if(digitalRead(encoder1)==HIGH){
int b = digitalRead(encoder2);
if(b>0){
counter++;
}
else{
counter--;
}
}
}
I have tried removing and adding the line, as described above^^

as mentioned by Hcheung, make counter volatile and remove readEncoder(); from loop.
I simplify a bit ISR readEncoder();
volatile int counter = 0;
[....]
void readEncoder() {
//if(digitalRead(encoder1)==HIGH){ //we are precisely here because digitalRead(encoder1) = HIGH !
if(digitalRead(encoder2)) counter++;
else counter--;
}

Related

How to lower power consumption ARDUINO and RFID mfrc522

Im making a project that i scan rfid cards to gain access to a door. I have made the code the way i want it to function but currently its drawing 22mA. I want this project to be powered by an 4Ah Lead acid battery.
I have removed the leds from the reader and from the arduino to lower consumption. Also i run arduino at 1Mhz and that looks that lowered the consumption a lot. Also i disabled Analog converter of arduino.
IM using arduino nano and RFID-RC522 reader
the output is an 5 volt relay.
Here is the code:
#include <SPI.h>
#include <MFRC522.h>
#include <EEPROM.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);
#define relay 4
#define led 2
#define button 5
byte readCard[4];
byte storeCard[4];
byte lastCard[4] = {1,2,3,4};
uint8_t successread = 0;
int flag=0;
void setup() {
CLKPR = 0x80;
CLKPR = 0x04;
ADCSRA = 0;
pinMode(relay, OUTPUT);
pinMode(button, INPUT_PULLUP);
pinMode(led, OUTPUT);
digitalWrite(relay, LOW);
digitalWrite(led, LOW);
SPI.begin();
mfrc522.PCD_Init();
}
void loop() {
do {
successread = getID();
}
while(!successread);
digitalWrite(led, HIGH);
delayMicroseconds(100);
digitalWrite(led, LOW);
lastcard();
if(digitalRead(button)==LOW){
save_delCard();
}
if(checkID(readCard) && !(digitalRead(button)==LOW)){
if(flag==0){
digitalWrite(relay, HIGH);
flag = !flag;
}
else{
digitalWrite(relay, LOW);
flag = !flag;
}
}
}
/////////READ CARD FROM READER/////////////////
uint8_t getID(){
if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID
reader continue
return 0;
}
if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get
Serial and continue
return 0;
}
for (uint8_t i=0; i<4; i++){
readCard[i] = mfrc522.uid.uidByte[i];
}
mfrc522.PICC_HaltA(); // stop reading
return 1;
}
///////////////////SAVE OR DELETE CARD/////////////////////////
uint8_t save_delCard(){
uint8_t count = EEPROM.read(0);
int start = (count*4) + 1;
int num = count*4 +1;
if(checkID(readCard)){
uint8_t slot = slotcheck(readCard);
for(uint8_t m=0;m<4;m++){
EEPROM.write((num-m-1),0);
}
for(uint8_t k=0;k<4;k++){
EEPROM.write((((slot-1)*4)+1+k),lastCard[k]);
}
count--;
}
else{
count++;
}
for(uint8_t j=0; j<4;j++){
EEPROM.write(j + start, readCard[j]);
}
EEPROM.write(0,count);
return 0;
}
////////////////////READ FROM MEMORY//////////////////////////////////
uint8_t readID(uint8_t number){
uint8_t start = (number*4) + 1;
for(uint8_t j=0;j<4;j++){
storeCard[j] = EEPROM.read(start + j);
}
}
///////////////////COMPARE IDS///////////////////////////////
bool compare(byte arraya[],byte arrayb[]){
for(uint8_t i=0;i<4;i++){
if(arraya[i]!=arrayb[i]){
return false;
}
else{
return true;
}
}
}
/////////CHECK IF CARD IS IN MEMORY/////////////////////////////////////
bool checkID(byte arraya[]){
uint8_t count = EEPROM.read(0);
for(int i=0;i<count;i++){
readID(i);
if(compare(arraya, storeCard)){
return true;
}
else {
}
}
return false;
}
////////////////FINDS WHERE CARD IS IN MEMORY//////////////////
uint8_t slotcheck(byte arraya[]){
uint8_t count = EEPROM.read(0);
uint8_t slot=0;
for(int i=0;i<count;i++){
readID(i);
slot = i+1;
if(compare(arraya, storeCard)){
return slot;
}
else {
}
}
return NULL;
}
///////////////SAVES LAST CARD/////////////////////
void lastcard(){
uint8_t count = EEPROM.read(0);
for(uint8_t p=0;p<4;p++){
lastCard[p] = EEPROM.read((count*4)-3+p);
}
}
//////////////////////////////////////////////////////////////////

LED pins on Arduino aren't being initialized when using classes

I'm trying to implement classes in my traffic lights program. The issues I'm facing are that the lights do not blink and the inherited class does not seem to work. How can I fix them?
class Sensors {
public:
Sensors(int echopin, int trigpin);
Sensors();
void init();
double light();
double sensor();
// protected:
int ECHOPIN;
int TRIGPIN;
};
class Mode: public Sensors
//Add the VARIABLES into the CLASSES from the FUNCTIONS
{
public: Mode(int gled, int yled, int rled, int Delay1);
void init();
void mode1();
void mode2();
void mode3();
double sensor() {
Sensors::sensor();
}
private: int Gled;
int Yled;
int Rled;
int Delay;
};
Sensors sense(3, 2);
Mode mode(13, 12, 11, 2000);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
sense.init();
mode.init();
}
void loop() {
double measure;
double lightValue;
double MAXDISTANCE = 10;
double MAXLIGHT = 140;
measure = sense.sensor();
lightValue = sense.light();
if (measure < MAXDISTANCE) {
mode.mode2();
} else if (lightValue < MAXLIGHT) {
while (lightValue < MAXLIGHT) {
mode.mode3();
lightValue = sense.light();
}
} else {
mode.mode1();
}
}
Sensors::Sensors(int echopin, int trigpin) {
ECHOPIN = echopin;
TRIGPIN = trigpin;
}
Sensors::Sensors() {
ECHOPIN;
TRIGPIN;
}
double Sensors::light() {
//LIGHT SENSOR
int sensorPin = A0;
unsigned int value = 0;
value = analogRead(sensorPin);
Serial.print("Light value is: ");
Serial.println(value);
return value;
}
double Sensors::sensor() {
//Measure the distance for the RANGE FINDER
double distance;
double Time;
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
Time = pulseIn(ECHOPIN, HIGH);
distance = (Time * 340) / 20000;
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm \n");
return distance;
}
void Sensors::init() {
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
}
Mode::Mode(int gled, int yled, int rled, int Delay1) {
int Gled = gled;
int Yled = yled;
int Rled = rled;
int Delay = Delay1;
}
void Mode::init() {
pinMode(Gled, OUTPUT);
pinMode(Yled, OUTPUT);
pinMode(Rled, OUTPUT);
}
void Mode::mode1() {
//First Mode
digitalWrite(Gled, LOW);
digitalWrite(Rled, HIGH); //RED ON
delay(Delay);
digitalWrite(Rled, LOW);
digitalWrite(Yled, HIGH); //YELLOW ON
Delay -= 1000;
delay(Delay);
digitalWrite(Yled, LOW);
digitalWrite(Gled, HIGH); //GREEN ON
Delay += 1000;
delay(Delay);
digitalWrite(Yled, HIGH); //YELLOW ON
digitalWrite(Gled, LOW);
Delay -= 1000;
delay(Delay);
}
void Mode::mode2() {
int DELAY = 100;
int Y_LOOP = 10;
int buzz = 4;
pinMode(buzz, OUTPUT);
for (int i = 0; i < Y_LOOP; i++) {
tone(buzz, 20);
digitalWrite(Yled, HIGH);
delay(DELAY);
digitalWrite(Yled, LOW);
delay(DELAY);
}
noTone(buzz);
}
void Mode::mode3() {
double measure;
delay(1000);
measure = sensor();
if (measure < 10) {
digitalWrite(Rled, LOW);
digitalWrite(Gled, HIGH);
} else {
digitalWrite(Rled, HIGH);
digitalWrite(Gled, LOW);
}
delay(1000);
}
I expect the sensor method to return a distance, but it only does so the first time. When it is called as an inherited method it returns 0.
This code can be simplified to
struct foo
{
int myX;
foo(int x)
{
int myX = x;
}
};
int main()
{
foo f(42);
// f.myX is still garbage because in constuctor you initialize
// a local variable myX instead of object field
return 0;
}
So you should initialize class field in member initializer list instead:
foo(int x): myX{x}
{
// empty
}

Arduino | Everything on the X-axis works but not on the Y-axis

I want to make a simple memory game for the Arduino. But instead of buttons I want to use a joystick to select the blinking LEDs.
I am in the early stage of the project but my Y-axis won't read and I can't figure the problem out.
//Joystick
const int X_pin = A4;
const int Y_pin = A5;
int Joy_Waarde;
//leds
const int led_Rood = 13;
const int led_Groen = 12;
const int led_Blauw = 11;
const int led_Geel = 10;
//componenten
const int buzzer = 4;
int X_Value = 0;
int Y_Value = 0;
void setup() {
pinMode (led_Rood, OUTPUT);
pinMode (led_Groen, OUTPUT);
pinMode (led_Blauw, OUTPUT);
pinMode (led_Geel, OUTPUT);
pinMode(buzzer, OUTPUT);
Serial.begin(9600);
randomSeed(analogRead(A0));
Serial.println("Het spel is begonnen!");
}
void loop() {
X_Value = analogRead(X_pin);
Y_Value = analogRead(Y_pin);
if (X_Value == 1023) {
digitalWrite(led_Groen, HIGH);
} else {
digitalWrite(led_Groen, LOW);
}
if (X_Value == 0) {
digitalWrite(led_Blauw, HIGH);
} else {
digitalWrite(led_Blauw, LOW);
}
if (Y_Value == 1023) {
digitalWrite(led_Geel, HIGH);
} else {
digitalWrite(led_Geel, LOW);
}
if (Y_Value == 0) {
digitalWrite(led_Rood, HIGH);
} else {
digitalWrite(led_Rood, LOW);
}
}
Hopefully you guys now something about it! Thanks in advance!
It worked, It was something with the wiring!
Thank you!

Input from serial monitor and push button

So I am doing a project. My task is to create a traffic light system that contains three modes that I can select from, by inputting the numbers 1,2 or 3 to the serial monitor. Everything was alright until I decided to add three push-buttons to the breadboard so I am also able to select any mode via the buttons. So far I have been unable to make the Arduino accept input from the serial monitor and the push buttons at the same time, I don't know if i'm in the right path or not to achieving my objective. I just need a small guidance to this, pls. Here is my current code:
//----------------------- Variables
#define ECHOPIN 3
#define TRIGPIN 2
char inVal;
String inString = "";
const int red_led = 11;
const int yellow_led = 12;
const int green_led = 13;
const int on_delay= 2000, off_delay= 1000; //led delays
const int min_distance = 10; // Distance sensor min distance
const int The_buzzer = 4;
float real_distance; // Distance obtained from function
int ldrPin = A0; // LDR pin
unsigned int sensorValue = 0;
float voltage;
float light_amount;
int brightness = 600; // amount of light treshhold
int button_one = 5;
String ButtonOne;
void setup() {
pinMode(red_led, OUTPUT);
pinMode(yellow_led, OUTPUT);
pinMode(green_led, OUTPUT);
pinMode(The_buzzer, OUTPUT);
Serial.begin(9600);
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
pinMode(button_one, INPUT);
}
void loop() {
if (Serial.available()>0)
distanceSensor(0); // distance sensor function
{
inVal=Serial.read();
switch((inVal) | (ButtonOne == "HIGH"))
{
case '1': // ------------------------- Regular Mode
while (true)
{
red_light();
yellow_light();
green_light();
yellow_light();
}
break;
case '2': // ------------------------ Pedestrian Mode
while (true)
{
real_distance = distanceSensor(0);
if (real_distance < min_distance)
{
for (int a= 0; a < 10; a++)
{
tone(The_buzzer,1000);
delay(1000);
noTone(The_buzzer);
delay(1000);
digitalWrite(yellow_led, HIGH);
delay(100);
digitalWrite(yellow_led,LOW);
}
}
real_distance = distanceSensor(0);
if (real_distance > min_distance)
{
red_light();
yellow_light();
green_light();
yellow_light();
}
}
break;
case '3': // --------------------------- NIGHT MODE
while (true)
{
light_amount = LDRSensor(0);
real_distance = distanceSensor(0);
if (light_amount > brightness)
{
red_light();
yellow_light();
green_light();
yellow_light();
red_light();
delay(100);
}
if (light_amount < brightness || real_distance < min_distance)
{
real_distance = distanceSensor(0); // distance sensor reading
if (real_distance > min_distance)
{
digitalWrite(green_led, LOW);
digitalWrite(red_led, HIGH);
}
if (real_distance < min_distance )
{
while(real_distance < min_distance && light_amount < brightness)
{ //maybe change this
digitalWrite(red_led, LOW);
digitalWrite(green_led, HIGH);
real_distance = distanceSensor(0);
}
digitalWrite(green_led, LOW);
}
}
}
break;
default:
standby_mode(); // blinks all leds until 1,2 or 3 is selected
}
}
}
//--------------------------------------- FUNCTIONS -----------------------
//----------------------------------- Red light function
void red_light()
{
digitalWrite(red_led, HIGH);
delay(on_delay);
digitalWrite(red_led,LOW);
}
//---------------------------------- Yellow light function
void yellow_light()
{
digitalWrite(yellow_led, HIGH);
delay(off_delay);
digitalWrite(yellow_led,LOW);
}
//--------------------------------- Green light function
void green_light()
{
digitalWrite(green_led, HIGH);
delay(on_delay);
digitalWrite(green_led,LOW);
}
//------------------------------ --- Distance sensor function
float distanceSensor(int x)
{
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN,HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN,LOW);
float distance = pulseIn(ECHOPIN, HIGH);
distance = distance/58;
Serial.print(distance);
Serial.println("cm");
delay(200);
float distance_reading = distance;
return distance_reading;
}
//------------------------------------- LDR sensor function
float LDRSensor(int h)
{
sensorValue = analogRead(ldrPin);
voltage = sensorValue * (5000.0 / 1024.0);
Serial.print("Sensor Output: ");
Serial.println(sensorValue);
Serial.print("Voltage (mv): ");
Serial.println(voltage);
Serial.println();
delay(5000);
return sensorValue;
}
//------------------------------------- Buzzer Function
void buzzer(unsigned char delayms)
{
analogWrite(The_buzzer, 20);
delay(delayms);
analogWrite(The_buzzer, 0);
delay(delayms);
}
// ------------------------------------- Standby Mode
void standby_mode()
{
for ( int a= 10; a < 14; a++)
{
digitalWrite(a,HIGH);
}
delay(off_delay);
for (int b=10; b < 14; b++)
{
digitalWrite(b,LOW);
}
delay(off_delay);
}
As I mentioned in my top comments, once you enter a given case, you never leave it (i.e. things get "stuck")
So, as I said, have a single outer loop, and each case just does one iteration.
Also, note that, below, inVal only gets changed if the serial port has input data available. So, the single loop approach mimics the multiple loops but still responds to changes in input.
Here is something that I think gets you closer to your intent [please pardon the gratuitous style cleanup]:
//----------------------- Variables
#define ECHOPIN 3
#define TRIGPIN 2
char inVal;
String inString = "";
const int red_led = 11;
const int yellow_led = 12;
const int green_led = 13;
const int on_delay = 2000,
off_delay = 1000; // led delays
const int min_distance = 10; // Distance sensor min distance
const int The_buzzer = 4;
float real_distance; // Distance obtained from function
int ldrPin = A0; // LDR pin
unsigned int sensorValue = 0;
float voltage;
float light_amount;
int brightness = 600; // amount of light treshhold
int button_one = 5;
String ButtonOne;
void
setup()
{
pinMode(red_led, OUTPUT);
pinMode(yellow_led, OUTPUT);
pinMode(green_led, OUTPUT);
pinMode(The_buzzer, OUTPUT);
Serial.begin(9600);
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
pinMode(button_one, INPUT);
}
void
loop()
{
// distance sensor function
if (Serial.available() > 0)
distanceSensor(0);
while (1) {
if (Serial.available() > 0)
inVal = Serial.read();
switch ((inVal) | (ButtonOne == "HIGH")) {
case '1': // Regular Mode
red_light();
yellow_light();
green_light();
yellow_light();
break;
case '2': // Pedestrian Mode
real_distance = distanceSensor(0);
if (real_distance < min_distance) {
for (int a = 0; a < 10; a++) {
tone(The_buzzer, 1000);
delay(1000);
noTone(The_buzzer);
delay(1000);
digitalWrite(yellow_led, HIGH);
delay(100);
digitalWrite(yellow_led, LOW);
}
}
real_distance = distanceSensor(0);
if (real_distance > min_distance) {
red_light();
yellow_light();
green_light();
yellow_light();
}
break;
case '3': // NIGHT MODE
light_amount = LDRSensor(0);
real_distance = distanceSensor(0);
if (light_amount > brightness) {
red_light();
yellow_light();
green_light();
yellow_light();
red_light();
delay(100);
}
if (light_amount < brightness || real_distance < min_distance) {
real_distance = distanceSensor(0); // distance sensor reading
if (real_distance > min_distance) {
digitalWrite(green_led, LOW);
digitalWrite(red_led, HIGH);
}
if (real_distance < min_distance) {
while (real_distance < min_distance && light_amount < brightness) { // maybe change this
digitalWrite(red_led, LOW);
digitalWrite(green_led, HIGH);
real_distance = distanceSensor(0);
}
digitalWrite(green_led, LOW);
}
}
break;
default: // blinks all leds until 1,2 or 3 is selected
standby_mode();
break;
}
}
}
//--------------------------------------- FUNCTIONS -----------------------
//----------------------------------- Red light function
void
red_light()
{
digitalWrite(red_led, HIGH);
delay(on_delay);
digitalWrite(red_led, LOW);
}
//---------------------------------- Yellow light function
void
yellow_light()
{
digitalWrite(yellow_led, HIGH);
delay(off_delay);
digitalWrite(yellow_led, LOW);
}
//--------------------------------- Green light function
void
green_light()
{
digitalWrite(green_led, HIGH);
delay(on_delay);
digitalWrite(green_led, LOW);
}
//------------------------------ --- Distance sensor function
float
distanceSensor(int x)
{
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
float distance = pulseIn(ECHOPIN, HIGH);
distance = distance / 58;
Serial.print(distance);
Serial.println("cm");
delay(200);
float distance_reading = distance;
return distance_reading;
}
//------------------------------------- LDR sensor function
float
LDRSensor(int h)
{
sensorValue = analogRead(ldrPin);
voltage = sensorValue * (5000.0 / 1024.0);
Serial.print("Sensor Output: ");
Serial.println(sensorValue);
Serial.print("Voltage (mv): ");
Serial.println(voltage);
Serial.println();
delay(5000);
return sensorValue;
}
//------------------------------------- Buzzer Function
void
buzzer(unsigned char delayms)
{
analogWrite(The_buzzer, 20);
delay(delayms);
analogWrite(The_buzzer, 0);
delay(delayms);
}
// ------------------------------------- Standby Mode
void
standby_mode()
{
for (int a = 10; a < 14; a++) {
digitalWrite(a, HIGH);
}
delay(off_delay);
for (int b = 10; b < 14; b++) {
digitalWrite(b, LOW);
}
delay(off_delay);
}
I think you didn't get the way arduino sketches works. The loop() function is called every time in a continuous loop (like a while(true)), so you should make your logic take advantage of this fact.
You use infinite loops inside the loop() function (which is already an infinite loop) so your code gets stuck in one of these loops and never get out, so it will never read the serial buffer or the GPIO pins.

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");

Resources