// EME3153 Ex6 Q3
// Student: Alan Lee
// Student ID: 250258181
// Class: 1B (EG114403)
// Wokwi: https://wokwi.com/projects/447287130872783873
#define LED_Out_Pin 25
#define SW_In_Pin 15
#define VR_In_Pin 36
int VRvalue;
int fadevalue;
int LightIntensity = 0;
int timeb = 0;
int textbt = 0;
int textct = 0;
int textperiod = 10000;
void setup()
{
// Initialize serial port
Serial.begin(115200);
// Set pins
pinMode(SW_In_Pin, INPUT_PULLUP);
// Initialize PWM channel
// channel 0-15, resolution 1-16 bits, freq limits depend on resolution
ledcAttach(LED_Out_Pin, 12000, 12); // 12 kHz PWM, 12-bit resolution
}
void loop()
{
VRvalue = analogRead(VR_In_Pin);
if (fadevalue != VRvalue) {
textbt = 1;
timeb = 0;
}
fadevalue = VRvalue;
ledcWrite(LED_Out_Pin, fadevalue);
LightIntensity = map(VRvalue, 0, 4095, 0, 100);
if (digitalRead(SW_In_Pin))
{
ledcWrite(LED_Out_Pin, fadevalue);
textct = 0;
}
else
{
digitalWrite(LED_Out_Pin, LOW);
if (textct == 0) {
texta();
int tempa = LightIntensity / 5;
int tempb = LightIntensity % 5;
Serial.println("LED light intensity bar: ");
Serial.print(" 0 ");
for (int i = tempa; i > 0; i--){
Serial.print("■");
}
if (tempb > 0){
Serial.print("#");
for (int i = (20 - tempa - 1); i > 0; i--){
Serial.print("□");
}
} else {
for (int i = (20 - tempa); i > 0; i--){
Serial.print("□");
}
}
Serial.println(" 100 ");
Serial.println("* Each block occupies 5%.");
textct = 1;
}
timeb = 0;
}
if (textbt == 1 && timeb >= 500) {
texta();
textbt = 0;
timeb = 0;
} else if (textbt == 0 && timeb >= textperiod) {
texta();
textbt = 0;
timeb = 0;
}
timeb++;
delay(1);
}
void texta() {
Serial.println("=======================================================");
Serial.print("Raw Sensor reading: ");
Serial.print(fadevalue);
Serial.print("\tLED light intensity: ");
Serial.print(LightIntensity);
Serial.println("% ");
}