#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define INTERRUPT_PIN_0 4
#define INTERRUPT_PIN_1 A2
#define INTERRUPT_PIN_2 8 // New pin for 180-degree rotation button
volatile bool interrupt_0_triggered = false;
volatile bool interrupt_1_triggered = false;
volatile bool interrupt_2_triggered = false; // Flag for new button
LiquidCrystal_I2C lcd(0x27, 16, 2); // Display address and resolution
unsigned long previousMillis = 0;
const long interval = 2000; // 2 seconds
int initialAngle = 0; // Store initial servo motor position
void setup() {
pinMode(INTERRUPT_PIN_0, INPUT_PULLUP);
pinMode(INTERRUPT_PIN_1, INPUT_PULLUP);
pinMode(INTERRUPT_PIN_2, INPUT_PULLUP); // Set new pin as input with pull-up resistor
attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN_0), ISR_INT0, FALLING);
attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN_1), ISR_INT1, FALLING);
attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN_2), ISR_INT2, FALLING); // Attach new interrupt function for 180-degree button
lcd.begin(16, 2);
lcd.backlight();
// Configure Timer 1 for PWM for servo motor
TCCR1A = _BV(COM1A1) | _BV(WGM11); // PWM, non-inverted mode
TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS11); // Fast PWM, prescaler 8
ICR1 = 19999; // Set timer period (20ms at 16MHz)
// Connect servo motor to pin 9
pinMode(9, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
if (interrupt_0_triggered) {
setServoPosition(45);
displayAngle("Uhol: 45 stupnov");
delay(interval);
}
if (interrupt_1_triggered) {
setServoPosition(90);
displayAngle("Uhol: 90 stupnov");
delay(interval);
}
if (interrupt_2_triggered) {
setServoPosition(180);
displayAngle("Uhol: 180 stupnov");
delay(interval);
}
}
void ISR_INT0() {
interrupt_0_triggered = true;
}
void ISR_INT1() {
interrupt_1_triggered = true;
}
void ISR_INT2() {
interrupt_2_triggered = true;
}
void setServoPosition(int angle) {
// Map angle (0-180 degrees) to PWM duty cycle range (0-100%)
int dutyCycle = map(angle, 0, 180, 0, 100);
// Set PWM duty cycle for servo motor in percentage
OCR1A = (dutyCycle * 19999) / 100;
}
void displayAngle(const char* message) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(message);
}