Advertisement
Maderdash

The button Works

Sep 20th, 2021
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int sensorValue;
  2. int sensorHigh        = 0;
  3. int sensorLow         = 1023;
  4. int curButState       = 1;
  5. int lastButState      = 1;
  6.  
  7. const int button      = 7;
  8. const int ledPin      = 13;
  9.  
  10. bool Switch           = false;
  11.  
  12. void setup() {
  13.   // put your setup code here, to run once:
  14.   pinMode(button, INPUT_PULLUP);
  15.   pinMode(ledPin, OUTPUT);
  16.   digitalWrite(ledPin, HIGH);
  17.   while (millis() < 5000) {
  18.     sensorValue = analogRead(A0);
  19.     if (sensorValue > sensorHigh) {
  20.       sensorHigh = sensorValue;
  21.     } if (sensorValue < sensorLow) {
  22.       sensorLow = sensorValue;
  23.     }
  24.   }
  25.   digitalWrite(ledPin, LOW);
  26.   Serial.begin(9600);
  27.   Serial.println("running");
  28.  
  29. }
  30.  
  31. void loop() {
  32.   // put your main code here, to run repeatedly:
  33.   sensorValue = analogRead(A0);
  34.   int pitch = map(sensorValue, sensorLow, sensorHigh, 50, 4000);
  35.   //This line checks of the varable [switch] is TRUE or FALSE.
  36.   //IF true then it runs the code inside the if statment.
  37.   //IF false, then it runs the code in the else statment, just turning the speaker OFF.
  38.   if (buttonReading()) {
  39.     tone(8, pitch, 20);
  40.     delay(10);
  41.   } else {
  42.     digitalWrite(8, LOW);
  43.   }
  44.  
  45.   Serial.println(Switch);
  46. }
  47. //This is a new function I created just to handle the button operation:
  48. //I created it into a BOOL so it will just be true false.
  49. bool buttonReading() {
  50.   //here I read the button, remember LOW means the button is pressed down, HIGH means its released.
  51.   curButState = digitalRead(button);
  52.   //Same as you had, bur I swaped the HIGH, LOW. So it not detects if the button WAS not pressed
  53.   //And is now pressed.
  54.   if (lastButState == HIGH && curButState == LOW) {
  55.     Serial.println("button is pressed");
  56.     //This switch statment changes state any time this code is active it changes to the opisit of what it was.
  57.     Switch = !Switch;
  58.     Serial.println(Switch);
  59.     //Here we store nte new value of the button
  60.     lastButState = curButState;
  61.     //This line sends info to ANY code that calls this function, I am sending the varable SWITCH [true or fales only.]
  62.     return (Switch);
  63.   }
  64.   lastButState = curButState;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement