继续上一篇的工程,这次增加一个PL端的按键输入,实现按键与LED的联动
还是上次的框图,我们关注PB3
配置成输入,位数为1位
搜索按键SW3,可以查到对应的管脚为A8。
从原理图可以看出,SW3有上拉电阻,没按的时候为1,按下后才为0
主菜单,Layout-> I/O Planning,把管脚配成A8
检查一下是否一致
set_property IOSTANDARD LVCMOS18 [get_ports {pl_pb*}]
set_property PACKAGE_PIN A8 [get_ports pl_pb_tri_i ]; # HD_GPIO_PB1
PB1对应的地址为0x00A0020000
对应的C代码的宏定义在xparameters.h里面
读取GPIO的值
u32 XGpio_DiscreteRead(XGpio * InstancePtr, unsigned Channel)
注意这个程序只是为了演示了如何读取PL的IO,实际应用中检测按键需要在软件上做消抖处理,不然很容易误触发。
#include <stdio.h>
#include "platform.h"
#include "xil_printf.h"
#include "sleep.h"
#include "xgpio.h"
//RGB三色灯的颜色值,有红绿黄3种单色,还有紫色、黄色、青色、白色4种组合色。总共可以显示7种颜色
#define LED 0x07
#define LED_RED 0x01
#define LED_GREEN 0x02
#define LED_BLUE 0x04
#define LED_PURPLE (LED_RED | LED_BLUE)
#define LED_YELLOW (LED_RED | LED_GREEN)
#define LED_CYAN (LED_GREEN | LED_BLUE)
#define LED_WHITE (LED_RED | LED_GREEN | LED_BLUE)
//Gpio信息
XGpio Gpio[2];
//两路LED对应的设置ID
int Gpio_led_rgb_device_id[2] = {
XPAR_GPIO_0_DEVICE_ID,
XPAR_GPIO_1_DEVICE_ID
};
//两路LED对应的通道ID,前面有提过,单通道填1,如果是GPIO2则填2
int led_rgb_channel[2] = {1, 1};
XGpio GpioInput;
void delay_ms(int ms)
{
usleep(ms * 1000L);
}
int main()
{
int Status;
int led_out;
int i;
int j;
int count = 0;
u32 button;
init_platform();
//初始化按键对应的GPIO
Status = XGpio_Initialize(&GpioInput, XPAR_GPIO_2_DEVICE_ID);
if (Status != XST_SUCCESS) {
xil_printf("Gpio Input Initialization Failed\r\n");
return XST_FAILURE;
}
//bit 0为输出,1为输入。这里把bit0设置为输入
XGpio_SetDataDirection(&GpioInput, 1, 0x0001);
for(i = 0; i < 2; i++){
//初始化GPIO
Status = XGpio_Initialize(&Gpio[i], Gpio_led_rgb_device_id[i]);
if (Status != XST_SUCCESS) {
xil_printf("Gpio Initialization Failed\r\n");
return XST_FAILURE;
}
//bit 0为输出,1为输入。这里把除LED外的其他IO设置为输入
XGpio_SetDataDirection(&Gpio[i], led_rgb_channel[i], ~LED);
}
while (1) {
//两个3色LED灯,每个灯有3种颜色,每种颜色点亮一次。灯1红绿蓝,灯2红绿蓝,共6次
for(i = 0; i < 2; i++) {
led_out = 1;
for(j = 0; j < 3; j++) {
//PB1默认有上拉,没按的时候为1,按下后为0
button = XGpio_DiscreteRead(&GpioInput, 1);
xil_printf("count=%d LED%d led=0x%.2X button=0x%.4x\n\r", ++count, i, led_out);//打印日志,用来判断是否在运行
//按键没按下时正常执行,按下时暂停
if((button & 0x0001) == 1){
XGpio_DiscreteWrite(&Gpio[i], led_rgb_channel[i], led_out);//点亮
delay_ms(250);
XGpio_DiscreteClear(&Gpio[i], led_rgb_channel[i], led_out);//熄灭
delay_ms(250);
led_out <<= 1;
}
else{
delay_ms(20);//延时20ms再读
}
}
}
}
//实际并不会执行到这里
print("Successfully ran Hello World application");
cleanup_platform();
return 0;
}
SW3没按下: LED正常闪烁
按住SW3不放:LED熄灭
松开SW3: LED恢复闪烁