Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int sensorValue;
- int sensorHigh = 0;
- int sensorLow = 1023;
- int curButState = 1;
- int lastButState = 1;
- const int button = 7;
- const int ledPin = 13;
- bool Switch = false;
- void setup() {
- // put your setup code here, to run once:
- pinMode(button, INPUT_PULLUP);
- pinMode(ledPin, OUTPUT);
- digitalWrite(ledPin, HIGH);
- while (millis() < 5000) {
- sensorValue = analogRead(A0);
- if (sensorValue > sensorHigh) {
- sensorHigh = sensorValue;
- } if (sensorValue < sensorLow) {
- sensorLow = sensorValue;
- }
- }
- digitalWrite(ledPin, LOW);
- Serial.begin(9600);
- Serial.println("running");
- }
- void loop() {
- // put your main code here, to run repeatedly:
- sensorValue = analogRead(A0);
- int pitch = map(sensorValue, sensorLow, sensorHigh, 50, 4000);
- //This line checks of the varable [switch] is TRUE or FALSE.
- //IF true then it runs the code inside the if statment.
- //IF false, then it runs the code in the else statment, just turning the speaker OFF.
- if (buttonReading()) {
- tone(8, pitch, 20);
- delay(10);
- } else {
- digitalWrite(8, LOW);
- }
- Serial.println(Switch);
- }
- //This is a new function I created just to handle the button operation:
- //I created it into a BOOL so it will just be true false.
- bool buttonReading() {
- //here I read the button, remember LOW means the button is pressed down, HIGH means its released.
- curButState = digitalRead(button);
- //Same as you had, bur I swaped the HIGH, LOW. So it not detects if the button WAS not pressed
- //And is now pressed.
- if (lastButState == HIGH && curButState == LOW) {
- Serial.println("button is pressed");
- //This switch statment changes state any time this code is active it changes to the opisit of what it was.
- Switch = !Switch;
- Serial.println(Switch);
- //Here we store nte new value of the button
- lastButState = curButState;
- //This line sends info to ANY code that calls this function, I am sending the varable SWITCH [true or fales only.]
- return (Switch);
- }
- lastButState = curButState;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement