Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const int buttonPin = 2; // the pin that the pushbutton is attached to
- // the pin that the LED is attached to
- const int led1Pin = 00;
- const int led2Pin = 00;
- const int led3Pin = 00;
- const int led4Pin = 00;
- // keep track if the led is high or low
- int led1State = LOW;
- int led2State = LOW;
- int led3State = LOW;
- int led4State = LOW;
- // Variables will change:
- int buttonPushCounter = 0; // counter for the number of button presses
- int buttonState = 0; // current state of the button
- int lastButtonState = 0; // previous state of the button
- int numToGuess = 1; // number to guess
- void setup() {
- // initialize the button pin as a input:
- pinMode(buttonPin, INPUT);
- // initialize the LED as an output:
- pinMode(led1Pin, OUTPUT);
- pinMode(led2Pin, OUTPUT);
- pinMode(led3Pin, OUTPUT);
- pinMode(led4Pin, OUTPUT);
- // initialize serial communication:
- Serial.begin(9600);
- decToBin();
- }
- void decToBin() {
- // Set every led to LOW
- digitalWrite(led1Pin, LOW);
- digitalWrite(led2Pin, LOW);
- digitalWrite(led3Pin, LOW);
- digitalWrite(led4Pin, LOW);
- // Make a copy of the number to guess.
- int copy = numToGuess;
- Serial.print("Number to guess: ");
- Serial.println(copy);
- if ((copy - 8) > -1) {
- copy = copy - 8;
- led1State = HIGH;
- digitalWrite(led1Pin, led1State);
- }
- if ((copy - 4) > -1) {
- copy = copy - 4;
- led2State = HIGH;
- digitalWrite(led2Pin, led2State);
- }
- if ((copy - 2) > -1) {
- copy = copy - 2;
- led3State = HIGH;
- digitalWrite(led3Pin, led3State);
- }
- if ((copy - 1) > -1) {
- copy = copy - 1;
- led4State = HIGH;
- digitalWrite(led4Pin, led4State);
- }
- }
- void loop() {
- // read the pushbutton input pin:
- buttonState = digitalRead(buttonPin);
- // compare the buttonState to its previous state
- if (buttonState != lastButtonState) {
- // if the state has changed, increment the counter
- if (buttonState == HIGH) {
- // if the current state is HIGH then the button
- // wend from off to on:
- buttonPushCounter++;
- Serial.println("on");
- Serial.print("number of button pushes: ");
- Serial.println(buttonPushCounter);
- checkIfNumIsGuessed();
- } else {
- // if the current state is LOW then the button
- // wend from on to off:
- Serial.println("off");
- }
- // Delay a little bit to avoid bouncing
- delay(50);
- }
- // save the current state as the last state,
- //for next time through the loop
- lastButtonState = buttonState;
- }
- void checkIfNumIsGuessed() {
- if (buttonPushCounter == numToGuess) {
- Serial.println("You guessed the number right! Next number...");
- buttonPushCounter = 0;
- numToGuess++;
- if (numToGuess > 15) {
- numToGuess = 1;
- }
- decToBin();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement