80 Examples of Microcontroller Programming

80 Examples of Microcontroller Programming

▍Note: If you need the Word source file, please reply “Admin” in the public account backend to get the material.

*Example 70: Software Debounce Independent Keyboard Input Experiment

#include<reg51.h> // Include header file defining 51 microcontroller registers
sbit S1=P1^4; // Define S1 pin as P1.4
sbit LED0=P3^0; // Define LED0 pin as P3.0

/* Function: Delay for approximately 30ms */
void delay(void)
{
    unsigned char i,j;
    for(i=0;i<100;i++)
        for(j=0;j<100;j++);
}

/* Function: Main function */
void main(void) // Main function
{
    LED0=0; // Output low level to P3.0 pin
    while(1)
    {
        if(S1==0) // P1.4 pin outputs low level, button S1 is pressed {
            delay(); // Delay for a while before checking again
            if(S1==0) // Button S1 is indeed pressed
                LED0=!LED0; // Toggle P3.0 pin
        }
    }
}

*Example 71: CPU Controlled Independent Keyboard Scanning Experiment

#include<reg51.h> // Include header file defining 51 microcontroller registers
sbit S1=P1^4; // Define S1 pin as P1.4
sbit S2=P1^5; // Define S2 pin as P1.5
sbit S3=P1^6; // Define S3 pin as P1.6
sbit S4=P1^7; // Define S4 pin as P1.7
unsigned char keyval; // Store key value

/* Function: Delay for running lights */
void led_delay(void)
{
    unsigned char i,j;
    for(i=0;i<250;i++)
        for(j=0;j<250;j++);
}

/* Function: Software debounce delay */
void delay30ms(void)
{
    unsigned char i,j;
    for(i=0;i<100;i++)
        for(j=0;j<100;j++);
}

/* Function: Forward lighting of LEDs */
void forward(void)
{
    P3=0xfe; // First light on
    led_delay();
    P3=0xfd; // Second light on
    led_delay();
    P3=0xfb; // Third light on
    led_delay();
    P3=0xf7; // Fourth light on
    led_delay();
    P3=0xef; // Fifth light on
    led_delay();
    P3=0xdf; // Sixth light on
    led_delay();
    P3=0xbf; // Seventh light on
    led_delay();
    P3=0x7f; // Eighth light on
    led_delay();
    P3=0xff;
    P3=0xfe; // First light on
    led_delay();
}

*Example 72: Timer Interrupt Controlled Independent Keyboard Scanning Experiment

#include<reg51.h> // Include header file defining 51 microcontroller registers
sbit S1=P1^4; // Define S1 pin as P1.4
sbit S2=P1^5; // Define S2 pin as P1.5
sbit S3=P1^6; // Define S3 pin as P1.6
sbit S4=P1^7; // Define S4 pin as P1.7
unsigned char keyval; // Store key value

/* Function: Delay for running lights */
void led_delay(void)
{
    unsigned char i,j;
    for(i=0;i<250;i++)
        for(j=0;j<250;j++);
}

… (additional examples omitted for brevity) …

Leave a Comment