将端口作为变量传递 - AVR

Dan*_*cci 5 c++ io avr

是否可以使用AVR端口作为可以传递的变量?

例如

LED myLed(PORTA,7);   //myLED hooked to PORTA, Pin 7
Run Code Online (Sandbox Code Playgroud)

我想让LED能够采用任何PORT/Pin组合,所以我宁愿不用硬编码.

请注意,PORT定义为:

#define PINA  _SFR_IO8(0x00)
#define DDRA  _SFR_IO8(0x01)
#define PORTA _SFR_IO8(0x02)    
Run Code Online (Sandbox Code Playgroud)

PORTA符号解析为(*(volatile uint8_t*)((0x02)+ 0x20))

我相信这将允许我做类似下面的事情,但我不确定我是否需要volatile关键字,也不确定它是否真的按预期工作

class LED{
public:
    LED(volatile uint8_t* port, uint8_t pin);
    {
        Port=port;
        Pin=pin;
    }
    void write(bool val)
    {
        if(val) (*Port) |= 1 << Pin;
        else    (*Port) &= ~(1 << Pin);
    }

private:
    uint8_t  Pin
    volatile uint8_t* Port;
}
Run Code Online (Sandbox Code Playgroud)

最后,有没有办法将端口/引脚设置为LED构造器的输出?这将涉及为给定端口#找到相对DDR#寄存器.我可以假设和DDR#将永远是&PORT#-1?

ava*_*kar 5

寄存器宏基本上是指向内存位置的指针,适当的寄存器所在的位置,所以是的,你可以使用uint8_t volatile *.但是,编译器不会以这种方式生成最有效的代码 - 它将使用间接寻址而不是直接写入.

这就是我使用avrlib做的事情.

#include <avrlib/porta.hpp>
#include <avrlib/pin.hpp>
using namespace avrlib;

typedef pin<porta, 4> led_pin;
Run Code Online (Sandbox Code Playgroud)

然后你可以使用led_pintypedef,例如

led_pin::set();
Run Code Online (Sandbox Code Playgroud)