1

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);
}
5
  • Try int prevState = -1; //-1= not initialized, 0=open, 1=closed
    – Abel
    Jun 14, 2022 at 0:54
  • 2
    The payload of the radio packet appears to be the number of the digital pin on which the sensor is attached: int state = digitalRead(data.val); Is that what you intend?
    – 6v6gt
    Jun 14, 2022 at 2:38
  • please copy and paste the content of the serial console to your question above ... please no screenshots
    – jsotola
    Jun 14, 2022 at 4:14
  • 1
    Just out of curiosity, why are you including key definitions for the Danish, German, Spanish, French, Italian and Swedish keyboard layouts? Jun 14, 2022 at 9:37
  • Consider using an enum for prevState instead of values 0, -1, 1; it makes the program easier to read/maintain. Jun 14, 2022 at 11:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.