Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * MotionActivatedLightSwitch.c
- *
- * Created: 1/1/2013 3:57:11 PM
- * Author: grist.carrigafoyl
- * Target: ATtiny85
- Activate a pin when motion is detected via a PIR sensor on another pin. Checks
- ambient light level via a photoresistor on an analog input.
- Didn't implement TIMER_POT in this version.
- */
- #define F_CPU 8000000UL // 8Mhz
- #define ADMUX_BITS 0b0000 // All default (VCC ref, ADLAR unset)
- #define TIMER_POT 0b0001 // ADC1 PB2 (pin7)
- #define PHOTORESISTOR 0b0011 // ADC3 PB3 (pin2)
- #define PIR_PIN PB0 // PCINT0 (pin5)
- #define SWITCH_PIN PB1 // pin6
- // The light level below which the switch will trigger.
- #define LOW_LIGHT_LEVEL 300 // Based on experimentation.
- #include <avr/io.h>
- #include <util/delay.h>
- // Prototypes
- int main(void);
- int read_adc(char pin);
- int main(void)
- {
- char pir_state;
- int curr_light_level;
- // ADC settings. Check with data sheet that this is what you want
- ADCSRA |= _BV(ADEN) | // Enable ADC
- (_BV(ADPS1)) | // set pre-scaler to clock/128
- (_BV(ADPS0)) | // 8MHz/128 = 62.5Khz (aiming for 50 - 200)
- (_BV(ADPS2)); // so this is good.
- DDRB = _BV(SWITCH_PIN); // All input except the switch pin
- PORTB = _BV(PIR_PIN); // Internal pullup for the PIR pin
- // How long the light stays on for. Simple constant for now
- int delay_time = 5000;
- for (;;) {
- pir_state = ~PINB & _BV(PIR_PIN);
- if (pir_state != 0) { // Movement detected
- curr_light_level = read_adc(PHOTORESISTOR);
- if (curr_light_level < LOW_LIGHT_LEVEL) {
- PORTB |= _BV(SWITCH_PIN); // On
- _delay_ms(delay_time);
- }
- }
- PORTB &= ~_BV(SWITCH_PIN); // Off
- }
- return 0; // Never going to happen
- }
- 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 << 4) | pin;
- // Discard the first reading in case it had its settings changed mid-conversion
- 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