Programming for sensors

In my robotics class we are using an arduino uno to add sensors so LED1 on the board lights up whenever the sensor is on black paper and isnt when on white paper. My code compiles but the teacher did not explain it exactly to what the code should look like and mine isn’t working. Please help!

#include <avr/io.h>

//call this first to enable the analog-to-digital converter
void initialize_adc(void) {
ADCSRA |= (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0); //set prescalar
ADMUX |= (1<<REFS0); //set reference voltage
ADMUX |= (1<<ADLAR); //left align data
ADCSRA |= (1<<ADEN); //enable ADC
}
//call this to read one of the analog input pins
//example: readADC(0); --read input 0 and return the 8-bit digital number
unsigned char readADC(unsigned char num) {
unsigned char temp;
ADMUX = (ADMUX & 0xE0) | num; //set ADC input
ADCSRA = ADCSRA | 0x40; //start analog to digital conversion
while (ADCSRA & (1<<ADSC)); //wait for conversion to finish
temp = ADCH; //read upper 8bits
return temp;
}

int main (void)
{
DDRD |= (1 << PD7); //Sets PD7 to output
initialize_adc ();

unsigned int x; //Switch status indicator
unsigned char y; //Color variable

while (1) //Infinite loop
{
y = readADC (0); //reads the analog number
if (y > 200)
{

PORTD |= (1 << PD7);

} else
{

PORTD &= ~(1<<PD7);

}
}
return 0;
}

Thanks,

Austin

please use the # button when posting code. It provides [ code]

tags that improve radability.

Also good for readability is consequent indentation. In the Arduino IDE you just press CTRL-T (windows)

and mine isn’t working. Please help!

What did you expect for behavior? and what does it do? or not do?

YOu could rewrite the same code in Arduino language. HIgh level languages are made for a purpose :wink:

void setup()
{
  inputMode(7, OUTPUT);  
}

void loop()
{
  int y = analogRead(0);
  if (y < 200) 
  {
    digitalWrite(7, HIGH);
  }
  else
  {
    digitalWrite(7, LOW);
  }
}