1
\$\begingroup\$

I have added a photoresistor to ATMEGA328P-PU. I'm trying to read the value from the analog input, but I don't understand how to assign the value from analog input to integer value (photoResistorValue in while loop), so I can work with it later.

#define F_CPU     800000UL
#define BAUD      14400
#define BRC       ((F_CPU/8/BAUD) - 1)

#include <stdlib.h>

#include <avr/io.h>
#include <avr/interrupt.h>

#include <util/delay.h>
#include <util/setbaud.h> 
#include <avr/io.h>
#include <avr/interrupt.h>

double dutyCycle = 0;

int main(void)
{
    DDRD = (1 << PORTD6);

    TCCR0A = (1 << COM0A1) | (1 << WGM00) | (1 << WGM01);
    TIMSK0 = (1 << TOIE0);

    setupADC();

    sei();

    TCCR0B = (1 << CS00) | (1 << CS02);

    while(1)
    {
        // int photoResistorValue = ..;
    }
}

void setupADC()
{
    ADMUX = (1 << REFS0) | (1 << MUX0) | (1 << MUX2);
    ADCSRA = (1 << ADEN) | (1 << ADIE) | (1 << ADPS0) | (1 << ADPS1) | (1 << ADPS2);
    DIDR0 = (1 << ADC5D);

    startConversion();
}

void startConversion()
{
    ADCSRA |= (1 << ADSC);
}

ISR(TIMER0_OVF_vect)
{
    OCR0A = dutyCycle;
}

ISR(ADC_vect)
{
    dutyCycle = ADC;
    startConversion();
}
\$\endgroup\$
1
\$\begingroup\$

First define INT photoresistorvalue outside of the while loop, as you don't want it to initialize it every loop.

Then inside of the while loop, it would be as simple as

 photoresistorvalue = ADCW;

ADCW should be the ADC result register for AVR microcontrollers, but could vary by family or ADC type.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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