I have made a project that checks the code entered by user , if it is correct it displays "correct" else "try again". When the code is entered correct I want the servo to move 90 degrees , which it is not moving. Any idea what did I do wrong.
COMPONENTS: Servo, Push buttons. Arduino Uno, Oled (128 by 64) .
CODE:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Servo.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define BUTTON_1 2
#define BUTTON_2 3
#define BUTTON_3 4
#define SERVO_PIN 9
const int sequence[] = {1, 2, 3}; // Desired sequence of button presses
int userInput[3]; // Array to store user input
int inputIndex = 0; // Index for user input
unsigned long lastButtonPressTime = 0; // Timestamp of last button press
unsigned long debounceDelay = 50; // Debounce delay time in milliseconds
unsigned long buttonDelay = 1000; // Delay after button press in milliseconds
Servo servo;
void setup() {
pinMode(BUTTON_1, INPUT_PULLUP);
pinMode(BUTTON_2, INPUT_PULLUP);
pinMode(BUTTON_3, INPUT_PULLUP);
Wire.begin();
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Address 0x3C for 128x64
servo.attach(SERVO_PIN);
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(1);
display.setCursor(0, 0);
display.println("Push buttons:");
display.println("1 - 2 - 3");
display.display();
}
void loop() {
int buttonPressed = checkButtons();
if (buttonPressed != 0 && millis() - lastButtonPressTime > buttonDelay) {
userInput[inputIndex] = buttonPressed;
inputIndex++;
displayInput();
lastButtonPressTime = millis();
}
if (inputIndex == 3) {
checkSequence();
}
}
int checkButtons() {
if (digitalRead(BUTTON_1) == LOW) {
delay(debounceDelay); // Debounce delay
if (digitalRead(BUTTON_1) == LOW) {
return 1;
}
}
if (digitalRead(BUTTON_2) == LOW) {
delay(debounceDelay); // Debounce delay
if (digitalRead(BUTTON_2) == LOW) {
return 2;
}
}
if (digitalRead(BUTTON_3) == LOW) {
delay(debounceDelay); // Debounce delay
if (digitalRead(BUTTON_3) == LOW) {
return 3;
}
}
return 0;
}
void displayInput() {
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
display.println("Push buttons:");
for (int i = 0; i < inputIndex; i++) {
display.print(userInput[i]);
display.print(" ");
}
display.display();
}
void checkSequence() {
bool correct = true;
for (int i = 0; i < 3; i++) {
if (userInput[i] != sequence[i]) {
correct = false;
break;
}
}
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
if (correct) {
display.println("Code is correct!");
servo.write(90); // Move servo to 90 degrees
} else {
display.println("Try again!");
}
display.display();
delay(2000); // Delay to allow user to see the result
resetInput();
}
void resetInput() {
inputIndex = 0;
for (int i = 0; i < 3; i++) {
userInput[i] = 0;
}
}