C和AVR pow功能点亮LED
我正在编写代码,使一组五个LED显示为“反弹”来回“骑士”风格。在写入PORTB寄存器时,我注意到我插入LED的方式,不同的东西是1、2、4、8、16。这将使相应的LED灯亮起。因此,我计算出循环使用C和AVR pow功能点亮LED,c,arduino,avr,pow,C,Arduino,Avr,Pow,我正在编写代码,使一组五个LED显示为“反弹”来回“骑士”风格。在写入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);
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;
}
#包括
#包括
#包括
无效延迟(uint16_t x);
//无效按钮(int b1、int b2);
int-led=0;
int inc=1;
无符号整数ledpow=0;
内部主(空)
{
DDRB |=(1因为pow函数返回的浮点数不是它应该表示的值的精确表示(而且,数学函数使用近似值)。所以可能pow(2,3)
不返回8,而是返回7.99856或8.0000261等。在前一种情况下,您被拧紧了,因为当您将其分配给端口时,它会被截断为整数(端口包含整数,对吗?),并丢失其小数部分,形成7以点亮所有前3个LED
对于整数运算,pow函数也是过期的,这是在浪费时间。我想知道为什么不使用PORTB=1您不应该使用pow()
。您可以找到有关的信息
但是,本质上,整数没有pow()
签名:
这意味着在运行时,它可能不起作用,因为它会对结果进行取整。它需要浮点库(完全在AVR上的软件中实现)——它速度慢且占用空间
PORTB=pow(2,0);
可能有效,因为它是一个constepr
,因此可以在编译时进行计算
相反,请尝试使用左移位运算符,例如:
PORTB = 1 << led;
PORTB=1您最好的方法是完全避免pow。与其操纵端口,不如使用digitalWrite函数
void setup() {
for (uint8_t pin=0; pin<20; ++pin) {
pinMode(pin, OUTPUT);
}
}
void blink(const uint8_t pos) {
digitalWrite(pos, HIGH);
delay(200);
digitalWrite(pos, LOW);
}
void loop() {
for (uint8_t pos=0; pos<19; ++pos) {
blink(pos);
}
for (uint8_t pos=19; pos>0; --pos) {
blink(pos);
}
}
void setup(){
对于(uint8_t pin=0;pin
void setup() {
for (uint8_t pin=0; pin<20; ++pin) {
pinMode(pin, OUTPUT);
}
}
void blink(const uint8_t pos) {
digitalWrite(pos, HIGH);
delay(200);
digitalWrite(pos, LOW);
}
void loop() {
for (uint8_t pos=0; pos<19; ++pos) {
blink(pos);
}
for (uint8_t pos=19; pos>0; --pos) {
blink(pos);
}
}