【问题标题】:What is wrong with this code for glowing LEDs using IR sensor for AVR?使用 AVR 的红外传感器发光 LED 的代码有什么问题?
【发布时间】:2015-07-05 03:58:04
【问题描述】:
/*This code takes in inputs from IR sensors connected on PA0 and PA1 
and glows LEDs connected on PB0 and PB1*/

#include <avr/io.h>

int main()
{
        DDRA=0x00; // PORTA (PA0 and PA1) will act as input

        DDRB=0x03; //The last two pins PBO and PB1 will act as output.

        int x=0x03 & PINA; //Initially when PINA=0, x=0

        if (x==0x00)
        {
            PORTB=0x00;
        }

        else if (x==0x01) 
// If input is given to PA0 then PINA=0x01 and x=0x01
        {
            PORTB=0x01;
        }

        else if (x==0x02) 
// If input is given to PA1 then PINA=0x02 and x=0x02
        {
            PORTB=0x02;
        }

        else if(x==0x03) 
// If input is given to PA0 and PA1 then PINA=0x03 and x=0x03
        {
            PORTB=0x03;
        }

        return 0;
    }

【问题讨论】:

  • 在 AVR 平台的嵌入式代码中从 main 返回几乎总是一个坏主意。它会跳回到代码中的其他地方,检查生成的程序集输出以找出确切的位置,如果你想要一个循环,你应该使用适当的主循环,而不是依赖返回的副作用来执行主循环.
  • 另外,在这样的帖子中解释会发生什么与您预期会发生什么会很有帮助。这里到底出了什么问题?
  • 如果你不使用循环,main 只会执行一次。 if 应该更好为if ( x&amp;3 == valore )
  • 它将返回到重置的 ISR,然后程序将从那里崩溃并烧毁。

标签: c embedded


【解决方案1】:

让程序连续运行的解决方案如下。此解决方案包含对您的代码的一些逻辑调整。逻辑调整允许代码不修改端口 B 的所有位,这样代码只修改端口的位 0 和 1。这允许将其他位用于其他目的。

#include <avr/io.h>

void main()
{
    DDRA=0x00; // PORTA (PA0 and PA1) will act as input
    DDRB=0x03; //The last two pins PBO and PB1 will act as output.

    int x;

    PORTB=0;
    PORTA=0;

    for( ;; ) {
        x=0x03 & PINA; //Initially when PINA=0, x=0

        if (x==0x00)
        {
            PORTB&=(~3);
        }

        else if (x==0x01) 
    // If input is given to PA0 then PINA=0x01 and x=0x01
        {
            PORTB&=(~2);
            PORTB|=0x01;
        }

        else if (x==0x02) 
    // If input is given to PA1 then PINA=0x02 and x=0x02
        {
            PORTB&=(~1);
            PORTB|=0x02;
        }

        else`enter code here` if(x==0x03) 
    // If input is given to PA0 and PA1 then PINA=0x03 and x=0x03
        {
            PORTB|=0x03;
        }

    // Here you may insert a delay
    //delay(50);
    }
}

我认为一个好的解决方案可能是以下代码:

#include <avr/io.h>

void main()
{
    DDRA=0x00; // PORTA (PA0 and PA1) will act as input
    DDRB=0x03; //The last two pins PBO and PB1 will act as output.

    PORTB=0;
    PORTA=0;

    for( ;; ) {
        PORTB &=(~3);
        PORTB |= (PORTA & 3);   

    // Here you may insert a delay
    //  delay(50);
    }
}

【讨论】:

    猜你喜欢
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多