Search code examples
linuxbashkeypress

how to wrap readkey in bash in a variable


I build a Lego remote using lirc and an raspberrypi.

All works fine but now i have a problem. The train needs the ir-signal constantly. I have written this script:

#!/bin/bash

while : 
do
  if [ -t 0 ]; then stty -echo -icanon -icrnl time 0 min 0; fi

  keypress=''
  clear;
  echo "Dies ist das Lego

  1 = vorwärts
  2 = rückwärts
  3 = stop
  "
  read -n 1 text
  if [ "$text" = "1" ];
  then
    while [ "x$keypress" = "x" ]; do
      irsend SEND_ONCE LEGO_Combo_Direct  FORWARD_FLOAT
      keypress="`cat -v`"
    done
  fi

  if [ "$text" = "2" ];
  then
    while [ "x$keypress" = "x" ]; do
      irsend SEND_ONCE LEGO_Combo_Direct  BACKWARD_FLOAT
      keypress="`cat -v`"
    done
  fi

  if [ "$text" = "3" ];
  then
    while [ "x$keypress" = "x" ]; do
      irsend SEND_ONCE LEGO_Combo_Direct  BRAKE_BRAKE
      keypress="`cat -v`"
    done
  fi

done

My problem is that the script stoppes on the read -n 1 text. If sombody could help me to use the keypress for the $text the script wont stop anymore.

Thanks in advance :)


Solution

  • Looks a bit overly complex. How about:

    #!/bin/bash
    #
    if [ -t 0 ]; then stty -echo -icanon -icrnl time 0 min 0; fi
        clear;
        echo "Dies ist das Lego
    
       1 = vorwärts
       2 = rückwärts
       3 = stop
    "
    keypress=''
    command='BRAKE_BRAKE'
    while true;
    do
        keypress="`cat -v`"
        case "$keypress" in
            "") ;;
            1) command="FORWARD_FLOAT";;
            2) command="BACKWARD_FLOAT";;
            3) command="BRAKE_BRAKE";;
            x) echo "Terminating..."; break;;
        esac
        irsend SEND_ONCE LEGO_Combo_Direct $command
    done
    

    And for sure you want to add some cleanup code to restore the terminal back to icanon mode....