此代码应该通过按钮读取数字输入引脚的状态并将状态输出到 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/