Exploring STC 8051 Microcontrollers – Coding

Analogue Comparator

Analogue comparator is not typically found in many microcontrollers but STC8A8K64S4A12 packs one analogue comparator. Though this comparator has limited options, it is still very useful and very easy to use. It can be used for low battery/voltage detection, for comparing voltage levels, etc. The comparator can also be used to build simple switch mode power supplies and achieve feedback for various tasks.

The comparator block shows that P3.6 and P3.7 GPIO pins can be used as positive and negative inputs to the comparator unit. Alternatively, we can also use internal 1.344V voltage reference source or ADC input. The comparator output can be optionally filtered both using analogue and digital techniques. Lastly, we can retrieve comparator output via GPIO pins, flag and interrupts.

Code

 #include "STC8xxx.h"
#include "BSP.h"
 
void setup(void);
 
void main(void)
{
    setup();
    
    while(1)
    {
        if(CMP_get_comp_status != 0x00)
        {
            P55_low;
        }
        else
        {
            P55_high;
        }
    };
}
 
void setup(void)
{
    CLK_set_sys_clk(IRC_24M, \ 
                    2, \
                    MCLK_SYSCLK_no_output, \
                    MCLK_out_P54);
    
    P55_open_drain_mode;
    
    CMP_setup(CMP_positive_input_P37, \
              CMP_negative_input_P36, \
              CMP_output_disable, \
              CMP_result_positive_output, \
              CMP_enable_analog_filtering, \
              0x04);
    
    CMP_enable;
}

Schematic

Explanation

Analogue comparator is set up very easily by choosing the positive and negative input sources, output state, result state and filtering values. After setting all these, the comparator needs to be enabled.

CMP_setup(CMP_positive_input_P37, \
         CMP_negative_input_P36, \
         CMP_output_disable, \
         CMP_result_positive_output, \
         CMP_enable_analog_filtering, \
         0x04);
   
CMP_enable;

Here, we used the GPIO pins P3.6 and P3.7 as physical inputs to the comparator unit. We disabled the physical comparator output. The comparator will give output when positive input is larger than negative input. Lastly, 0.1µs analogue filtering is used along with some digital filtering by the addition of some latency. These filtering ensure that short-lived false signals are ignored.

Inside the main loop, comparator’s result flag status is continuously monitored. P5.5 onboard LED is turned on or off according to this flag’s status.

 if(CMP_get_comp_status != 0x00)
{
     P55_low;
}
else
{
     P55_high;
}

Demo

Pages: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

Related Posts

13 comments

Leave a Reply

Your email address will not be published. Required fields are marked *