Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define CLK 6
- #define DT 7
- #define SW 5
- #define BLUE 11
- #define GREEN 10
- #define YELLOW 9
- #define RED 8
- int counter = 0;
- int aState;
- int aLastState;
- int randNumber;
- int scoreCounter = 4;
- int scoreHolder = 0;
- void setup()
- {
- pinMode (CLK,INPUT);
- pinMode (DT,INPUT);
- pinMode (SW,INPUT);
- pinMode (BLUE,OUTPUT);
- pinMode (GREEN,OUTPUT);
- pinMode (YELLOW,OUTPUT);
- pinMode (RED,OUTPUT);
- Serial.begin (9600);
- // Reads the initial state of the outputA
- aLastState = digitalRead(CLK);
- randomSeed(analogRead(A0));
- randNumber = random(100);
- Serial.println(randNumber);
- digitalWrite(BLUE, LOW);
- digitalWrite(GREEN, LOW);
- digitalWrite(YELLOW, LOW);
- digitalWrite(RED, HIGH);
- }
- void loop()
- {
- if (digitalRead(SW) == LOW)
- {
- GetScore(counter);
- randNumber = random(100);
- CalculateDiff(counter);
- if (scoreHolder == scoreCounter)
- {
- Serial.println("Congratulations! You unlocked the safe");
- scoreHolder = 0;
- }
- }
- aState = digitalRead(CLK); // Reads the "current" state of the outputA
- // If the previous and the current state of the outputA are different, that means a Pulse has occured
- if (aState != aLastState)
- {
- // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
- if (digitalRead(DT) != aState)
- {
- counter ++;
- }
- else
- {
- counter --;
- }
- if (counter > 100)
- {
- counter = 0;
- }
- else if (counter < 0)
- {
- counter = 100;
- }
- CalculateDiff(counter);
- Serial.println(counter);
- Serial.println(randNumber);
- }
- aLastState = aState; // Updates the previous state of the outputA with the current state
- }
- int CalculateDiff(int count)
- {
- int Diff = randNumber - count;
- Serial.println(Diff);
- if (Diff < 10 || Diff > -10)
- {
- digitalWrite(YELLOW, HIGH);
- digitalWrite(RED, LOW);
- digitalWrite(GREEN, LOW);
- }
- if(Diff > 10 || Diff < -10)
- {
- digitalWrite(YELLOW, LOW);
- digitalWrite(GREEN, LOW);
- digitalWrite(RED, HIGH);
- }
- if (Diff == 0)
- {
- digitalWrite(GREEN, HIGH);
- digitalWrite(RED, LOW);
- digitalWrite(YELLOW, LOW);
- }
- return Diff;
- }
- void GetScore(int counterValue)
- {
- if (CalculateDiff(counterValue) == 0)
- {
- digitalWrite(BLUE, HIGH);
- digitalWrite(GREEN, LOW);
- delay (500);
- digitalWrite(BLUE, LOW);
- scoreHolder = scoreHolder + 1;
- Serial.print("Score:");
- Serial.println(scoreHolder);
- }
- else
- {
- digitalWrite(BLUE, HIGH);
- digitalWrite(GREEN, HIGH);
- digitalWrite(YELLOW, HIGH);
- digitalWrite(RED, HIGH);
- delay (500);
- digitalWrite(BLUE, LOW);
- digitalWrite(GREEN, LOW);
- digitalWrite(YELLOW, LOW);
- digitalWrite(RED, LOW);
- scoreHolder = 0;
- Serial.print("Score:");
- Serial.println(scoreHolder);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement