Reverse the Response

Perhaps you would like the opposite response. Don't worry we can easily reverse this response just change:

analogWrite(ledPin, lightLevel); -> analogWrite(ledPin, 255 - lightLevel);

Upload your modified sketch and watch the response change.

Night Light

Rather than controlling the brightness of the LED in response to light, lets instead turn it on or off based on a threshold value. Change the loop() code with:

void loop(){ 
  int threshold = 300; 
  if(analogRead(lightPin) > threshold){ 
    digitalWrite(ledPin, HIGH); 
    digitalWrite(ledPin, LOW); 

Light Controlled Servo

This circuit uses the same wiring for both the Metro and the Metro Express. Make sure your power rail is plugged into 3V instead of 5V.

Lets use our newly found light sensing skills to control a servo (and at the same time engage in a little bit of Arduino code hacking). Wire up a servo connected to pin 9 (like in CIRC-04). Then open the Knob example program (the same one we used in CIRC-08) File > Examples > Library-Servo > Knob. Upload the code to your board and watch as it works unmodified.

Using the full range of your servo

You'll notice that the servo will only operate over a limited portion of its range. This is because with the voltage dividing circuit we use the voltage on analog pin 0 will not range from 0 to 5 volts but instead between two lesser values (these values will change based on your setup). To fix this play with the line: val = map(val, 0, 1023, 0, 179);  (For hints on what to do, click here)

Learn More!

This guide was first published on Aug 18, 2017. It was last updated on Jun 12, 2017.

This page (Make It Better) was last updated on Jun 27, 2017.

Text editor powered by tinymce.