Key detect raspberry pi4

53 Views Asked by At

I am trying to do a project that prints something on an LCD and if I press a key on the remote control will stop printing that text and print something else. I am searching for something similar with the 'keyboard' package but I need it to work with external devices like IR remote or something similar not only with the keyboard.

Eg.: LCD prints: Hello StackOverflow!

and after 5 seconds LCD print: HI!

If I press any key on the remote: LCD prints: Hello StackOverflow!

key detected LCD prints: See you soon! without the last part.

I want to find a module/package or a command that can help me do this.

2

There are 2 best solutions below

2
Elerium115 On

Just create a state machine and use it to decide whether running the code or not.

I implemented the code in C for an Arduino, but you can get the same in python for a raspberry pi. The concept of a state machine is the same.

enum State{
  RUNNING,
  STOPPED,
};

enum State currentState = RUNNING;

void setup() {
  // configure your IR device
}

void onButton1Pressed() {
  // call this function when button 1 from IR is pressed.
  // This function changes the state to RUNNING

  currentState = RUNNING;
}

void onButton2Pressed() {
  // call this function when button 2 from IR is pressed.
  // This function changes the state to STOPPED

  currentState = STOPPED;
}

void program_state_stopped() {
    // this function executes when the state is STOPPED
    // in the example, it prints I'm waiting every second
    print("I'm waiting...");
    delay(1000);
}

void program_state_running() {
    // this function executes when the state is RUNNING
    // in the example, it prints I'm running every second
    print("I'm running...");
    delay(1000);
}

void loop() {
  // Here you need to read the IR buttons and call the onButtonPressed functions if  button is pressed
  // Or even better use interruptions to read buttons and change states

  // once the button has been processed, check the current state and call the appropiate function
  if (currentState == STOPPED) {
    // state is STOPPED so we call its corresponding function
    program_state_stopped();
  }
  else if (currentState == RUNNING) {
    // state is RUNNINGso we call its corresponding function
    program_state_running();
  }
}
0
AnonimF On

I added an additional button and checked for it if it's state is high or low. Checking the button from the ir will just stop the whole program until a button is pressed