Landing : Athabascau University
  • Blogs
  • Circuit 1C: Photoresistor

Circuit 1C: Photoresistor

Building this circuit was straightforward. Instead of using the SIK Guide example program, I decided to modify my morse code program from Circuit 1B. My program makes the LED blink my name (Adam) in morse code when it is dark. Here is the code:

# define LED_PIN 12 // Pin number attached to LED.
int threshold = 400; //if the photoresistor reading is below this value the the light will turn on
void setup() {
// put your setup code here, to run once:
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
letterA();
longSpace();
letterD();
longSpace();
letterA();
longSpace();
letterM();
longerSpace();
}
boolean isDark(){
if (analogRead(A0) < threshold) {
return true;
}
else {
return false;
}
}
int ditDuration(){
return 100; //100 milliseconds
}
void letterA(){
dit();
space();
dah();
}
void letterD(){
dah();
space();
dit();
space();
dit();
}
void letterM(){
dah();
space();
dah();
}
void dit(){
if(isDark()){
digitalWrite(LED_PIN, HIGH); // Turn on the LED.
delay(ditDuration()); // The duration of a dit.
}
}
void dah(){
if(isDark()){
digitalWrite(LED_PIN, HIGH); // Turn on the LED.
delay(3*ditDuration()); // The duration of a dah is 3 times that of a dit.
}
}
void space(){
digitalWrite(LED_PIN, LOW); // Turn off the LED.
if(isDark()){
delay(ditDuration()); // The duration of a space is equal to that of a dit.
}
}
void longSpace(){
digitalWrite(LED_PIN, LOW); // Turn off the LED.
if(isDark()){
delay(3*ditDuration()); // The duration is 3 times that of a dit, used between characters.
}
}
void longerSpace(){
digitalWrite(LED_PIN, LOW); // Turn off the LED.
if(isDark()){
delay(7*ditDuration()); // The duration is 7 times that of a dit, used between words.
}
}

The main changes from the previous iteration of the morse code program are the addition of isDark() to check if the photoresistor value is below the threshold, calls to isDark() in dit(), dah(), space(), longSpace(), and longerSpace(), and the modification of ditDuration() to always return 100.

Here is a video of the program in action:  MorseCodePhotoresistor

There was one challenge that I had while writing the code. Initially, the if(isDark()) statements inside space(), longSpace(), and longerSpace() included the digitalWrite(LED_PIN, LOW) statement. This meant that if the LED happened to be turned on when isDark() returned true, then the LED would stay turned on until isDark returned false again. So if I happened to take my finger off of the photoresistor while the LED was on, then it would stay on until I covered the photoresistor again. I fixed this issue by taking the digitalWrite(LED_PIN, LOW) statements outside of the if(isDark) statements. Now isDark() can be true or false for the LED to turn off, but it has to be true for the LED to turn on.