Skip to content

Instantly share code, notes, and snippets.

@peeranatkankham
Created May 23, 2023 15:30
Show Gist options
  • Save peeranatkankham/634eea4ae66929e13a8aa46ee1450431 to your computer and use it in GitHub Desktop.
Save peeranatkankham/634eea4ae66929e13a8aa46ee1450431 to your computer and use it in GitHub Desktop.
#define F_CPU 16000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
// Define the pin numbers for the sensors and the relay
#define LDR_PIN PB3
#define MOTION_PIN PB1
#define RELAY_PIN PB2
#define BUTTON_PIN PB4
// Define constants for the ADC readings
#define LDR_THRESHOLD 500
void initADC(){
// Select ADC03
ADMUX |= (1 << MUX0) | (1 << MUX1);
// Enable ADC with prescalar 128
ADCSRA |= (1 << ADEN) | (1<< ADPS2) | (1<< ADPS1) |(1 << ADPS0);
}
// Function to read the analog value from the LDR sensor
uint16_t read_ldr() {
// start conversion
ADCSRA |= (1 << ADSC);
//wait for ADIF
while (ADCSRA & (1 << ADSC));
// Return the ADC result
return ADC;
}
// Function to read the digital value from the MOTION sensor
uint8_t read_motion() {
// Read the digital value from the MOTION pin
return PINB & (1 << MOTION_PIN);
}
uint8_t relay_state = 0; // Initially off
void initInterrupt() {
// Set BUTTON_PIN as input
DDRB &= ~(1 << BUTTON_PIN);
// Enable external interrupt on BUTTON_PIN
PCMSK |= (1 << PCINT4); // Enable interrupt for BUTTON_PIN
GIMSK |= (1 << PCIE); // Enable pin change interrupt for PCINT7..0
}
ISR(PCINT0_vect) {
// Debounce the button
_delay_ms(200);
// Check if the button is pressed
if (PINB & (1 << BUTTON_PIN)) {
// Toggle the relay state
relay_state = !relay_state;
if (relay_state) {
PORTB |= (1 << RELAY_PIN); // Turn on the relay
} else {
PORTB &= ~(1 << RELAY_PIN); // Turn off the relay
}
}
}
int main(void) {
// Initialize the ADC
initADC();
// Configure the pin directions
DDRB |= (1 << RELAY_PIN); // Relay pin as output
// Initialize the relay state
relay_state = 0; // Initially off
// Set PB2 as an input pin
DDRB &= ~(1 << MOTION_PIN);
// Enable the internal pull-up resistor for PB5
PORTB |= (1 << MOTION_PIN);
// Enable global interrupts
sei();
initInterrupt();
while (1) {
// Read the sensor values
uint16_t ldr_value = read_ldr();
uint8_t motion_value = read_motion();
// Check the LDR value and the MOTION value
if (ldr_value > LDR_THRESHOLD && motion_value) {
relay_state = 1;
// Turn on the relay for 2 minutes
PORTB |= (1 << RELAY_PIN);
_delay_ms(120000);
PORTB &= ~(1 << RELAY_PIN);
relay_state = 0;
}
_delay_ms(1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment