c - 读取输入引脚的状态并显示在 LED 上 - LPC1115

标签 c arm gpio lpc nxp-microcontroller

此代码应该通过按钮读取数字输入引脚的状态并将状态输出到 LED。 即当输入为高电平时,LED 亮起,反之亦然 由于按钮连接到上拉电阻,因此当按下按钮时,输入应该读取低电平,反之亦然。

我的代码:

    #include "board.h"
    #include <stdio.h>

    //setting pointers
    #define Port0 ((LPC_GPIO_T *) 0x50000000) //Port 0
    #define IOCON ((LPC_IOCON_T *) 0x40044000) //IO configuration

    int main(void)
    {

        /* Initialize pins */       
        Port0->DIR &= ~((1 << 1)); //PIO0_1 input - onboard switch (unpressed state is pulled-up)
        Port0->DIR |= (1<<7);      //PIO0_7 output - onboard LED

        //Pin configuration
        IOCON->REG[IOCON_PIO0_7] &= 0x0 << 3; //No addition pin function
        IOCON->REG[IOCON_PIO0_1] &= 0x0 << 3; // "

        Port0->DATA[1<<7] &= ~(1<<7); // output initially low 

        while (1) {

            if((Port0->DATA[1<<1]) & (1<<1)) //When input is high
            {
                Port0->DATA[1<<7] |= (1<<7); //drive PIO0_7 High

            }
            else
            {
                 Port0->DATA[1<<7] &= ~(1<<7); //Drive PIO0_7 Low
            }
        }

        return 0;
    }

当执行这部分代码时,除非按下按钮,否则 PIO0_7 保持低电平。但是,由于开关被上拉,这不是意味着以相反的方式工作吗?我还用电压表仔细检查了这一点。

我尝试改变

     if((Port0->DATA[1<<1]) & (1<<1)) //When input is high

     if(!(Port0->DATA[1<<1]) & (1<<1)) //When input is Low

即使按下按钮,LED 输出仍保持高电平。

最佳答案

假设您的Port0->DATA[0]指向基址0x5000 0000并定义为对齐的8位数组,那么您的引脚端口寻址/屏蔽是错误的.

参见LPC111x user manual UM10398 Rev. 12.4 p196 Chapter 12.4.1 write/read data operation :

In order for software to be able to set GPIO bits without affecting any other pins in a single write operation, bits [13:2] of a 14-bit wide address bus are used to create a 12-bit wide mask for write and read operations on the 12 GPIO pins for each port.

因此,地址中有 2 位偏移量,用于获取/设置所需引脚的值。 因此,您必须将寻址移动 2 位,以下应该可以解决问题:

Port0->DATA[1<<(7+2)] &= ~(1<<7); // output initially low 

while (1) {
    if((Port0->DATA[1<<(1+2)]) & (1<<1)) //When input is high
    {
        Port0->DATA[1<<(7+2)] |= (1<<7); //drive PIO0_7 High
    }
    else
    {
         Port0->DATA[1<<(7+2)] &= ~(1<<7); //Drive PIO0_7 Low
    }
}

关于c - 读取输入引脚的状态并显示在 LED 上 - LPC1115,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53567099/

相关文章:

c - 如何在 C 中读取由 { , , } 格式分隔的数字的整个文件?

c - 图书馆管理项目的数据结构

c - 使用时区在纯 C 中进行日期格式化

c - NEON 比较

android - 如何检测传感器连接到哪个引脚?

c - 解码二进制信号

c - 不同的数组大小

memory-management - Windows CE : Mapping Physical memory in user mode

android - 以编程方式检索 Android ARM 处理器版本

python - 使用Raspberry Pi 2 Model B上的GPIO引脚控制运行ROS的P3DX机器人