Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * SimplePotPlay.c
- *
- * Created: 1/1/2013 3:57:11 PM
- * Author: grist.carrigafoyl
- Testing reading analog pins. This one works properly.
- Using the readings to alter the flashing pattern on an LED.
- Using 10 bit resolution.
- */
- #define F_CPU 8000000UL // 8Mhz
- #define admux_bits 0b00000000 // All default (VCC ref, ADLAR unset)
- #define timer_pot 0b00000001 // ADC1 PB2 (pin7)
- #define photoresistor 0b00000011 // ADC3 PB3 (pin2)
- #include <avr/io.h>
- #include <util/delay.h>
- // Prototypes
- int main(void);
- int read_adc(char pin);
- int main(void)
- {
- int timer_val,ambient_light, i;
- DDRB = _BV(PB1); // All input except PB1 (will drive the SSR, is LED for now)
- PORTB = _BV(PB0); // Turn on the internal pullup resistor on the IR detector pin
- // ADC settings. Check with datasheet that this is what you want
- ADCSRA |= _BV(ADEN) | // Enable ADC
- (_BV(ADPS1)) | // set prescaler to 128 (clock/128)
- (_BV(ADPS0)) | // 8MHz/128 = 62.5Khz (aiming for 50 - 200)
- (_BV(ADPS2));
- // How long the light stays on or off for. Simple constant multiplied by the pot reading
- int delay_time = 2; // ms
- while(1) {
- timer_val = read_adc(timer_pot);
- PORTB |= _BV(PB1); // On
- // _delay_ms will only take a constant as its argument or the code won't compile. So
- // I'm using a constant time with a for loop around it as a simple multiplier. It's
- // not very accurate, but good enough for this purpose.
- for (i=0;i<timer_val;i++) {
- _delay_ms(delay_time);
- }
- ambient_light = read_adc(photoresistor);
- PORTB &= ~_BV(PB1); // Off
- for (i=0;i<ambient_light;i++) {
- _delay_ms(delay_time);
- }
- }
- return 0;
- }
- int read_adc(char pin)
- { // Read the analog value from the ADC input pin.
- // Code based on samples from http://avrbasiccode.wikispaces.com/
- int ret_val;
- // Assumes ADCSRA enabled and prescalars are set already
- // Set the input channel and other ADMUX bits
- ADMUX = admux_bits | pin;
- // Discard the first reading as it could
- ADCSRA |= _BV(ADSC); // start a single conversion
- while (ADCSRA & _BV(ADSC)){} // wait until conversion is done
- ADCSRA |= _BV(ADSC); // start a single conversion
- while (ADCSRA & _BV(ADSC)){} // wait until conversion is done
- ret_val = ADCL; // Get ADCL first for 10bit and combine with ADCH
- return((ADCH << 8) | ret_val);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement