I am attempting to use radio modules to receive a value from a sensor, either 1 or 0, and complete an action. The only problem is that I would like the action to only complete once per state change, instead of every time (if it activates when the variable is 0, only activate again when the variable changes to 1.) Despite the != sign, the code inside the if statement will not activate even if the variables are reading 0 and 1.
// Keyboard - Version: Latest
#include <Keyboard.h>
#include <KeyboardLayout.h>
#include <Keyboard_da_DK.h>
#include <Keyboard_de_DE.h>
#include <Keyboard_es_ES.h>
#include <Keyboard_fr_FR.h>
#include <Keyboard_it_IT.h>
#include <Keyboard_sv_SE.h>
#include <SPI.h>
#include "RF24.h"
RF24 myRadio (7, 8);
int mag = 2;
int prevState = 1; // 0=open, 1=closed
byte addresses[][6] = {"0"};
void setup()
{
Serial.begin(9600);
Keyboard.begin();
delay(1000);
myRadio.begin();
myRadio.setChannel(115);
myRadio.setPALevel(RF24_PA_MAX);
myRadio.setDataRate( RF24_250KBPS ) ;
myRadio.openReadingPipe(1, addresses[0]);
myRadio.startListening();
}
struct package
{
int val;
};
typedef struct package Package;
Package data;
void loop()
{
if ( myRadio.available())
{
while (myRadio.available())
{
myRadio.read( &data, sizeof(data) );
}
// Serial.print("state: ");
Serial.println(data.val);
int state = digitalRead(data.val);
// Serial.print("prevState: ");
// Serial.println(prevState);
// Serial.print("\n");
if (state != prevState) {
Keyboard.press(' ');
delay(50);
Keyboard.press(KEY_LEFT_GUI);
delay(50);
Keyboard.press('D');
delay(50);
Keyboard.releaseAll();
Serial.println("Executed successfully.");
prevState = state;
}
}
delay(1000);
}
int prevState = -1; //-1= not initialized, 0=open, 1=closed
int state = digitalRead(data.val);
Is that what you intend?enum
forprevState
instead of values 0, -1, 1; it makes the program easier to read/maintain.