控制 GPIO 的首选替代方法是通过 BSP。因为这个 BSP(板级支持包)为您完成所有工作,将所有外设设置为良好的默认值并允许您调用函数。您选择的 BSP 可能具有将字节写入 8 位 GPIO 端口的功能;您的 LED 将只有一位。在这种情况下,您的 C 代码可能如下所示:(至少:它将在 Luminary Micro 套件上像这样工作)。 (示例代码;需要一些额外的工作才能使其编译,尤其是在您的工具包上)。
/* each LED is addressed by an address (byte) and a bit-within-this-byte */
struct {
address, // address of IO register for LED port
bit // bit of LED
} LEDConfigPair;
struct LEDConfigPair LEDConfig[NUMBER_OF_LEDS] = {
{GPIO_PORTB_BASE,0}, // LED_0 is at port B0
{GPIO_PORTB_BASE,1} // LED_1 is at port B1
} ;
/* function LED_init configures the GPIOs where LEDs are connected as output */
led_init(void)
{
U32 i;
for(i=0;i<NUMBER_OF_LEDS;i++)
{
GPIODirModeSet( LEDConfig[i][0], LEDConfig[i][1], GPIO_DIR_MODE_OUT );
}
}
/* my LED function
set_led_state makes use of the BSP of Luminary Micro to access a GPIO function
Implementation: this BSP requires setting 8 port wide IO, so the function will calculate a mask (
*/
set_led_state(U8 led,bool state)
{
U8 andmask;
U8 setmask;
andmask = ~(1 << LEDConfig[led].bit);// a bitmask with all 1's except bit of LED
if (true == state)
{
setmask = (1 << LEDConfig[led].bit); // set bit for LED
} else
{
setmask = 0;
}
GPIOPinWrite(LEDConfig[led].address, andmask, setmask);
}
当然,这一切都说明了;它可以像这样在一行中完成:
#DEFINE SETLEDSTATE(led,state) GPIOPinWrite(LEDConfig[led].address, ~(1<<LEDConfig[led].bit),(state<<LEDConfig[led].bit))
这也是一样的,但只有当你可以梦想位掩码并且你只想切换一些 LED 来调试真正的程序时才有意义......
替代方案:裸机。
在这种情况下,您需要自己设置所有内容。对于嵌入式系统,您需要了解引脚复用和电源管理(假设内存控制器和 cpu 时钟已经设置好!)
- 初始化:设置引脚复用,使您想要控制的功能实际映射到封装上。
- 外围设备的初始化(在这种情况下是 UART 或同一引脚上的 GPIO 功能)