#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
// Constants
const int relayPin = 7;
const int lcdAddress = 0x27;
const int motorPin = 9; // PWM pin connected to the L298 driver
const int bulbStateOff = 0;
const int bulbStateOn = 1;
// Global variables
int bulbState = bulbStateOff;
Servo motor; // Using Servo library for PWM control
// LCD initialization
LiquidCrystal_I2C lcd(lcdAddress, 16, 2);
void setup() {
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, HIGH); // Start with the relay off
Serial.begin(9600); // Initialize serial communication
lcd.init(); // Initialize the LCD
lcd.backlight();
lcd.print("Bulb is ON");
motor.attach(motorPin); // Attach the motor control pin
// Print lab and system readiness information on the serial monitor
Serial.println(F("SI 2024 FAF-212 Cristian Brinza lab4 full"));
Serial.println(F("System Ready. Enter Password."));
}
void loop() {
if (Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
handleSerialCommand(command);
}
}
void setBulbState(int state) {
if (state == bulbStateOn) {
digitalWrite(relayPin, LOW); // Turn on the bulb
bulbState = bulbStateOn;
lcd.clear();
lcd.print("Bulb is OFF");
Serial.println("Bulb is OFF");
} else {
digitalWrite(relayPin, HIGH); // Turn off the bulb
bulbState = bulbStateOff;
lcd.clear();
lcd.print("Bulb is ON");
Serial.println("Bulb is ON");
}
}
void setMotorPower(int power) {
// Map the power from -100...100 to 0...180 for the Servo library
int angle = map(power, -100, 100, 0, 180);
motor.write(angle); // Set the PWM via servo library
// Update LCD with motor power
lcd.clear();
lcd.print("Motor Power: ");
lcd.print(power);
Serial.println("Motor Power: " + String(power));
}
void handleSerialCommand(String command) {
if (command.equalsIgnoreCase("off")) {
setBulbState(bulbStateOn);
} else if (command.equalsIgnoreCase("on")) {
setBulbState(bulbStateOff);
} else if (command.startsWith("motor ")) {
int power = command.substring(6).toInt(); // Extract power level
if (power >= -100 && power <= 100) {
setMotorPower(power);
}
}
}