carduinodetectionarduino-unoatmega

How do I detect a button release?


I am new to arduino and its programming. For my project I use the voltage detection of the pressed button. When a button is pressed, the variable "keypressed" is assigned the value of the pressed button. After releasing the button, the variable "keyreleased" must be assigned to the value of the released button.

  int analogVal = analogRead(A0);              //read analog voltage value from pin A0
  if (analogVal < 325) keypressed = instrkey;
  if (analogVal < 300) keypressed  = keyB4;
  if (analogVal < 275) keypressed  = keyA4s;
  if (analogVal < 250) keypressed  = keyA4;
  if (analogVal < 225) keypressed  = keyG4s;
  if (analogVal < 200) keypressed  = keyG4;
  if (analogVal < 175) keypressed  = keyF4s;
  if (analogVal < 150) keypressed  = keyF4;
  if (analogVal < 125) keypressed  = keyE4;
  if (analogVal < 100) keypressed  = keyD4s;
  if (analogVal < 75) keypressed  = keyD4;
  if (analogVal < 50) keypressed  = keyC4s;
  if (analogVal < 25) keypressed  = keyC4;
  if (analogVal > 1000) keyreleased = nokey;

In this code we need to build the function of button release detection.

I tried using the if construction, but it didn't work. Because the first condition breaks before the next one is fulfilled.

if (analogVal < 325) keypressed = instrkey; {
    if (keypressed != instrkey) keyreleased = instrkey;
  }

And when I decided to use loops, all the code stopped and did not respond to button signals. This happened with both "for" and "while".


Solution

  • try this code to get keypressed and keyreleased :

    int lastKey=nokey; //assume keys are integer
    void loop() {
      int analogVal = analogRead(A0);              //read analog voltage value from pin A0
      if (analogVal < 325) keypressed = instrkey;
      if (analogVal < 300) keypressed  = keyB4;
      if (analogVal < 275) keypressed  = keyA4s;
      if (analogVal < 250) keypressed  = keyA4;
      if (analogVal < 225) keypressed  = keyG4s;
      if (analogVal < 200) keypressed  = keyG4;
      if (analogVal < 175) keypressed  = keyF4s;
      if (analogVal < 150) keypressed  = keyF4;
      if (analogVal < 125) keypressed  = keyE4;
      if (analogVal < 100) keypressed  = keyD4s;
      if (analogVal < 75) keypressed  = keyD4;
      if (analogVal < 50) keypressed  = keyC4s;
      if (analogVal < 25) keypressed  = keyC4;
      if (analogVal > 1000) keypressed  = nokey;
      //if (analogVal > 1000) keyreleased = nokey;
    
      if (lastKey != keypressed) {
        keyreleased=lastKey;
        lastKey=keypressed;
      }
    }
    

    example :

    at prog start, lastkey=nokey and keypressed=nokey.

    1- press keyG4 : keypressed change from nokey to keyG4, keyreleased stay equal to nokey and lastkey become equal to keyG4

    2- release keyG4 : keypressed change from keyG4 to nokey, keyreleased become keyG4 and lastkey become nokey.

    etc....