#include <avr/io.h>
#include <util/delay.h>

#define F_CPU 8000000UL // 设置CPU时钟频率为8MHz

// 数码管显示的数字对应的编码
const uint8_t segCode[10] = {
    0b00111111, // 0
    0b00000110, // 1
    0b01011011, // 2
    0b01001111, // 3
    0b01100110, // 4
    0b01101101, // 5
    0b01111101, // 6
    0b00000111, // 7
    0b01111111, // 8
    0b01101111  // 9
};

// 读取八位拨码开关的状态
uint8_t readSwitches() {
    return PINA;
}

// 将二进制数转换为对应的十进制数
uint8_t binaryToDecimal(uint8_t binary) {
    uint8_t decimal = 0;
    uint8_t weight = 1;
    while (binary > 0) {
        decimal += (binary & 0x01) * weight;
        binary >>= 1;
        weight *= 2;
    }
    return decimal;
}

// 在数码管上显示十进制数
void displayDecimal(uint8_t decimal) {
    uint8_t thousands = decimal / 1000;
    uint8_t hundreds = (decimal / 100) % 10;
    uint8_t tens = (decimal / 10) % 10;
    uint8_t units = decimal % 10;

    // 显示千位
    PORTB = 0b00001111; // 关闭所有数码管
    PORTD = segCode[thousands]; // 设置千位数字的段码
    PORTB = 0b00001110; // 打开千位数码管
    _delay_ms(1);

    // 显示百位
    PORTB = 0b00001111; // 关闭所有数码管
    PORTD = segCode[hundreds]; // 设置百位数字的段码
    PORTB = 0b00001101; // 打开百位数码管
    _delay_ms(1);

    // 显示十位
    PORTB = 0b00001111; // 关闭所有数码管
    PORTD = segCode[tens]; // 设置十位数字的段码
    PORTB = 0b00001011; // 打开十位数码管
    _delay_ms(1);

    // 显示个位
    PORTB = 0b00001111; // 关闭所有数码管
    PORTD = segCode[units]; // 设置个位数字的段码
    PORTB = 0b00000111; // 打开个位数码管
    _delay_ms(1);
}

int main(void) {
    DDRA = 0x00; // 设置PA引脚为输入
    DDRB = 0x0F; // 设置PB0~PB3引脚为输出
    DDRD = 0xFF; // 设置PD0~PD7引脚为输出

    PORTB = 0b00001111; // 关闭所有数码管

    while (1) {
        uint8_t switches = readSwitches(); // 读取拨码开关状态
        uint8_t decimal = binaryToDecimal(switches); // 将二进制数转换为十进制数
        displayDecimal(decimal); // 在数码管上显示十进制数
    }

    return 0;
}

原文地址: https://www.cveoy.top/t/topic/fynj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录