/////////////////////////////////////////////////////////////////////////////
// Registers' Address Setting
volatile unsigned char *ADMUX_ESP;
volatile unsigned char *ADCSRA_ESP;
volatile unsigned char *ADCSRB_ESP;
volatile unsigned char *ADCL_ESP;
volatile unsigned char *ADCH_ESP;
volatile uint8_t* portB = (uint8_t*)0x25; // Declare portB as a global pointer
#define ADC_PIN 0
ISR(ADC_vect) {
}
void setup() {
Serial.begin(9600);
ADMUX_ESP = (volatile unsigned char*) 0x7C;
ADCSRA_ESP = (volatile unsigned char*) 0x7A;
ADCSRB_ESP = (volatile unsigned char*) 0x7B;
ADCL_ESP = (volatile unsigned char*) 0x78;
ADCH_ESP = (volatile unsigned char*) 0x79;
// Set reference voltage to AVCC
*ADMUX_ESP = 0b01000000; // Binary: 01000000
// Set ADC prescaler to 128 for a reasonable conversion time
*ADCSRA_ESP = 0b10000111; // Binary: 10000111
// Set auto-trigger source for free-running mode (optional)
*ADCSRB_ESP &= ~(1 << 5);
// Set LED pin as an output PB5
unsigned char *portDDRB = (unsigned char *)0x24;
*portDDRB |= ( 1 << PB5 ); //PB5 on output mode
*portB &= ~( 1 << PORTB5 ); //turn off PB5 init
SREG |= ( 1 << 7 ); //global interrupts enabled
}
void loop() {
// Read ADC value
uint16_t adcValue = adc_read(ADC_PIN);
// Print ADC value to Serial Monitor
Serial.print("[email protected]: ");
Serial.println(adcValue);
// Check if ADC value is over 500
if (adcValue > 500) {
// Turn on the LED
*portB |= (1 << PORTB5);
MyDelay(500); // Adjust delay as needed
// Turn off the LED
*portB &= ~(1 << PORTB5);
MyDelay(500); // Adjust delay as needed
}
}
uint16_t adc_read(uint8_t adcx) {
// Select the ADC pin
*ADMUX_ESP &= 0xF0;
*ADMUX_ESP |= adcx;
// Start the conversion
*ADCSRA_ESP |= 0b01000000;
// Wait for the conversion to complete
while (!(*ADCSRA_ESP & (1 << 4))); // Wait for ADIF (conversion complete) flag
// Clear ADIF flag by writing 1 to it
*ADCSRA_ESP |= (1 << 4);
// Read the result
uint16_t result = *ADCL_ESP | (*ADCH_ESP << 8);
return result;
}
// Define MyDelay function
void MyDelay(unsigned long mSec){
volatile unsigned long i;
unsigned long endT = 1000 * mSec;
for (i = 0; i < endT; i++);
}