PIC16F-ADC-Configuration&Control-Functions

by Marwen Maghrebi
// Function to configure the ADC module
void configure_ADC(void) {
    ADCON0 = 0x41;  // Turn ADC ON, select AN0 channel, ADC clock = Fosc/8
    ADCON1 = 0x80;  // All 8 channels are analog, result is "right-justified"
                    // ADC clock = Fosc/8
}

// Function to start ADC conversion
void start_ADC_conversion(void) {
    ADCON0bits.GO_DONE = 1; // Start A/D conversion
}

// Function to wait for ADC conversion to complete
void wait_for_conversion(void) {
    while (ADCON0bits.GO_DONE); // Polling GO_DONE = delay until conversion is complete
}

// Function to read ADC result and control LEDs
void read_ADC_result(void) {
    uint16_t ADC_result = ((uint16_t)ADRESH << 8) + ADRESL; // Read the right-justified 10-bit result
    
    // Turn off all LEDs initially
    PORTBbits.RB0 = 0;
    PORTBbits.RB1 = 0;
    PORTBbits.RB2 = 0;
    PORTBbits.RB3 = 0;
    
    // Check ADC result and control LEDs accordingly
    if (ADC_result > 250) {
        // ADC result is greater than 250, turn on LED1
        PORTBbits.RB0 = 1;
    }
    if (ADC_result > 500) {
        // ADC result is greater than 500, turn on LED2
        PORTBbits.RB1 = 1;
    }
    if (ADC_result > 750) {
        // ADC result is greater than 750, turn on LED3
        PORTBbits.RB2 = 1;
    }
    if (ADC_result > 1000) {
        // ADC result is greater than 1000, turn on LED4
        PORTBbits.RB3 = 1;
    }
}
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
-
00:00
00:00
Update Required Flash plugin
-
00:00
00:00