// EME3153 Ex6 Q2
// Student: Alan Lee
// Student ID: 250258181
// Class: 1B (EG114403)
// Wokwi: https://wokwi.com/projects/447285956035118081
#define LED_Out_Pin 25
#define SW_In_Pin 15
#define VR_In_Pin 36
int VRvalue;
int pastVRvalue;
int timea = 0;
int timeb = 0;
int textat = 0;
int textbt = 0;
int textct = 0;
int lighta = 0;
int lightperiod = 200; // first ms
float lighttype = 0.5; // Range : 0 - 1
int textperiod = 10000;
int maxperiod = 1000;
int minperiod = 200;
void setup()
{
Serial.begin(115200);
pinMode(LED_Out_Pin, OUTPUT);
pinMode(SW_In_Pin, INPUT_PULLUP);
}
void loop()
{
VRvalue = analogRead(VR_In_Pin);
if (pastVRvalue != VRvalue) {
textbt = 1;
timeb = 0;
}
pastVRvalue = VRvalue;
VRvalue = map(VRvalue, 0, 4095, maxperiod, minperiod);
lightperiod = VRvalue;
if (digitalRead(SW_In_Pin))
{
if (lighta == 1) {
digitalWrite(LED_Out_Pin, HIGH);
} else if (lighta == 0) {
digitalWrite(LED_Out_Pin, LOW);
}
if ( lighta == 1 && timea >= (lightperiod * lighttype)) {
lighta = 0;
timea = 0;
} else if ( lighta == 0 && timea >= (lightperiod * (1 - lighttype))) {
lighta = 1;
timea = 0;
}
textct = 0;
}
else
{
digitalWrite(LED_Out_Pin, LOW);
if (textct == 0) {
texta();
Serial.print("Minimum period: ");
Serial.print(minperiod);
Serial.print(" ms");
Serial.print("\tMaximum period: ");
Serial.print(maxperiod);
Serial.println(" ms");
textct = 1;
}
timea = 0;
timeb = 0;
lighta = 1;
}
if (textbt == 1 && timeb >= 500) {
texta();
textbt = 0;
timeb = 0;
} else if (textbt == 0 && timeb >= textperiod) {
texta();
textbt = 0;
timeb = 0;
}
timea++;
timeb++;
delay(1);
}
void texta() {
Serial.println("=======================================================");
Serial.print("Raw Sensor reading: ");
Serial.print(pastVRvalue);
Serial.print("\tLED light period: ");
Serial.print(lightperiod);
Serial.println(" ms");
}