⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 button.txt

📁 linux下的按键中断程序
💻 TXT
字号:
系统配置:CPU+OnChipRam(4K)+LED_PIO+BUTTON_PIO

功能描述:按键实现中断,使led亮或灭
led配置成开发板上的led0,led1,led2,led3
按键采用简单按钮B17,B18,19,B20

不给过多注释了(其实注释够多了)
#include <stdlib.h>
#include <io.h>
#include "sys/alt_irq.h"
#include "altera_avalon_pio_regs.h"
#include "system.h"

/* A variable to hold the value of the button pio edge capture register. */
volatile int edge_capture;

#ifdef BUTTON_PIO_BASE
/* 按键中断服务程序*/
static void handle_button_interrupts(void* context, alt_u32 id)
{
    /* Cast context to edge_capture's type. It is important that this be
     * declared volatile to avoid unwanted compiler optimization.
     */  
    volatile int* edge_capture_ptr = (volatile int*) context;
    /* Store the value in the Button's edge capture register in *context. */
    *edge_capture_ptr = IORD_ALTERA_AVALON_PIO_EDGE_CAP(BUTTON_PIO_BASE);/*读取边沿捕获状态*/
    /* Reset the Button's edge capture register. */
    IOWR_ALTERA_AVALON_PIO_EDGE_CAP(BUTTON_PIO_BASE, 0);/*边沿捕获使能*/
}

/* Initialize the button_pio. */
static void init_button_pio()
{
    /* Recast the edge_capture pointer to match the alt_irq_register() function
     * prototype. */
    void* edge_capture_ptr = (void*) &edge_capture;
    /* Enable all 4 button interrupts. */
    IOWR_ALTERA_AVALON_PIO_IRQ_MASK(BUTTON_PIO_BASE, 0xf);/*中断使能*/
    /* Reset the edge capture register. */
    IOWR_ALTERA_AVALON_PIO_EDGE_CAP(BUTTON_PIO_BASE, 0x0);/*边沿捕获使能*/
    /* Register the interrupt handler. */
    alt_irq_register( BUTTON_PIO_IRQ, edge_capture_ptr,
                      handle_button_interrupts );/*注册中断服务子函数*/
}
#endif

int main (void) __attribute__ ((weak, alias ("alt_main")));/*重载alt_main函数*/

int alt_main(void)
{
    alt_irq_init(ALT_IRQ_BASE); //necessary,enable interrupts
    alt_sys_init();  //unnecessary//系统自动执行
    alt_io_redirect(ALT_STDOUT,ALT_STDIN,ALT_STDERR);//unnecessary
    init_button_pio();/*初始化BUTTON*/
    while(1)
    {
        switch(edge_capture)
        {
        case 0x01:
            IOWR_ALTERA_AVALON_PIO_DATA(LED_PIO_BASE,0xFF);
            break;
        case 0x02:
            IOWR_ALTERA_AVALON_PIO_DATA(LED_PIO_BASE,0x00);
            break;
        case 0x04:
            IOWR_ALTERA_AVALON_PIO_DATA(LED_PIO_BASE,0xFF);
            break;
        case 0x08:
            IOWR_ALTERA_AVALON_PIO_DATA(LED_PIO_BASE,0x00);
            break;
        default:
            IOWR_ALTERA_AVALON_PIO_DATA(LED_PIO_BASE,0x0A);
            break;
        }
    }
    return 0;
}

1 因为使用的是片上RAM,容量有限,故得重载alt_main(), 否则空间不够
2 系统默认的alt_main()是干了很多活的...比如系统中断,IO设备驱动等,改写的时候得注意,哪些用户程序用到了.比如本例用到中断,故 alt_irq_init(ALT_IRQ_BASE);函数是必须的.开始没有调试成功就是因为没有开总中断

中断的调试过程可以依次看以下:
   
    status:最低位PIE(使能),为0禁止,为1允许中断
  ienable:3232位,每位对应一个外部中断,为1则对应使能
  ipending:表示处理器正在处理的中断
 全局变量:alt_irq.若注册成功的话就会向向量表写入ISR和Context.注册完后返回0则成功,为负则失败

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -