AVR单片机数码管显示拨码开关值 - 基于ATmega328P
#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; // 全部数码管熄灭
_delay_ms(1);
PORTD = segCode[thousands]; // 在千位数码管上显示千位数字
PORTB = 0b00001110; // 打开千位数码管
_delay_ms(1);
PORTB = 0b00001111; // 全部数码管熄灭
_delay_ms(1);
PORTD = segCode[hundreds]; // 在百位数码管上显示百位数字
PORTB = 0b00001101; // 打开百位数码管
_delay_ms(1);
PORTB = 0b00001111; // 全部数码管熄灭
_delay_ms(1);
PORTD = segCode[tens]; // 在十位数码管上显示十位数字
PORTB = 0b00001011; // 打开十位数码管
_delay_ms(1);
PORTB = 0b00001111; // 全部数码管熄灭
_delay_ms(1);
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 binary = switches; // 将拨码开关状态转换为二进制数
uint8_t decimal = binaryToDecimal(binary); // 将二进制数转换为十进制数
displayDecimal(decimal); // 在数码管上显示十进制数
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/fynU 著作权归作者所有。请勿转载和采集!