I’m trying to use a LED as a light sensor(input) connected to a Arduino Nano. I connected the led with the Anode at digital pin 8 (PB0) with a resistance of 56 Ohm and the Cathode at an analog pin A0 (PC0). schematics_led_input The main idea is to measure the voltage across the parasite capacitance in the LED which was stored during a short 5V pulse(turning PC0 high and then low) in reverse bias. First example is very simple.

uint16_t sen_time = 0;    //Variable for counting
void setup() {
  // Setting pin 8 to OUTPUT and the rest to INPUT
  DDRB |= (1 << PB0);   // Setting OUTPUT PB0
  PORTB &=  ~(1 << PB0);   // Setting Anode LOW 

  TCCR1B |= (1 << CS10); // Setting timer, no prescaling(f = 16Mhz)

void loop() {
/* Reverse bias pulse */
  DDRC |= (1 << PC0);     //Setting A0 to OUTPUT
  PORTC |= (1 << PC0);    //Setting A0 to HIGH
 /* Setting Threestate Cathode */ 
  DDRC &=  ~(1 << PC0);    //Setting A0 to INPUT
  PORTC &=  ~(1 << PC0);   //Setting A0 to LOW

  TCNT1 = 0;  // Setting timer the moment we turn off 
  //Waiting for the led to discharge and counting
  while (analogRead(A0) != 0)
  Serial.println(sen_time);    //Print the value
  sen_time = 0;                //Setting the value to 0

The results are as follows. In normal conditions: normal_conditions_data In darkness: darkness_data In heavy light: heavy_light_data

The variable which is incremented sen_time is pretty much accurate, having high values for darkness and low values for heavy light. But I can’t understand why my timer has trash values all way around.

I’m trying to solve it with interrupts(Pin change interrupts) but getting the pin three-stated just triggers the interrupt all way around. Plus the TCNT got trush values whenever I read it. Getting pull-up resistors just keeps the pin high. Some advices about how to solve this problem preferably with interrupts (due to time restriction on future project). Thank you and I hope to solve it as soon as possible!

You need to read the value TCNT1 into a variable straight after your while loop and before you start printing stuff, then print the value of that variable.

Why? TCNT1 is counting at 16MHz. Your serial port baud rate is 9600. A single character (start bit, 8 data bits, stop bit) will therefore take ~10.4ms to transmit. In this amount of time, TCNT1 will increment 16,666 times. In the time 4 characters take to transmit, TCNT1 will wrap around and start counting up from zero again.

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.