我正在编写代码以使一组五个 LED 看起来像“Knight Rider”风格来回“反弹”。写入 PORTB 寄存器时,我注意到插入 LED 的方式不同,分别是 1、2、4、8、16。这些会打开相应的 LED。所以我想通过使用pow
函数将寄存器设置为 2 的值循环到 LED 编号(0、1、2、3、4)。但它不能正常工作。
#include <avr/io.h>
#include <inttypes.h>
#include <math.h>
void delay(uint16_t x);
//void buttons(int b1, int b2);
int led = 0;
int inc = 1;
unsigned int ledpow = 0;
int main(void)
{
DDRB |= (1<<PORTB0); //Set PORTB0 (pin 8) as an output
DDRB |= (1<<PORTB1); //Set PORTB1 (pin 9) as an output
DDRB |= (1<<PORTB2); //Set PORTB2 (pin 10) as an output
DDRB |= (1<<PORTB3); //Set PORTB3 (pin 11) as an output
DDRB |= (1<<PORTB4); //Set PORTB4 (pin 12) as an output
DDRD &= ~(1<<PORTD3); //Set PORTD3 (pin 3) as an input
DDRD &= ~(1<<PORTD4); //Set PORTD4 (pin 4) as an input
PORTB = 0; //Disable Pull-up resistors for PORTB
PORTD = 0; //Disable Pull-up resistors for PORTD
while(1)
{
while((PIND & (1<<PORTD3)) != 0) {
//Do nothing, just pause the program
}
ledpow = pow(2,led);
PORTB = ledpow;
led = led + inc;
if ((led == 4) || (led==0)) {
inc = -inc;
}
if((PIND & (1<<PORTD4)) != 0) {
delay(50);
}
else {
delay(100);
}
}
}
void delay(uint16_t x)
{
uint16_t i,j;
for(i=0;i<x;i++)
for(j=0;j<1000;j++)
;
return;
}
为什么这不起作用?我让它使用 switch/case 语句。我测试了该pow
函数通过做PORTB = pow(2,0);
以及变量“led”的其他权力来工作。那工作正常。