嵌入式学习笔记003-裸奔篇之按键

  1. 有了前面关于led的讲解后,后续的相关裸奔就方便多了,当然,code就不会像led那样简单了~ 现在开始讲解关于按键key的相关code
  2. 首先先看原理图找到key相关的引脚,在我的tq2440板子中,有如下分布:
    key1 – INT1 – GPF1
    key2 – INT4 – GPF4
    key3 – INT2 – GPF2
    key4 – INT0 – GPF0
    从上面可以看出GPF0124除了正常的引脚输入输出IO功能外还有额外的作用 –> 中断,这个我们后面会讲到,到时再讲解,从原理图可以看出,引脚默认情况是高电平,当有按键按下时为低电平。
  3. 接下来就是写code了,可以将之前写的C语言led直接copy过来改个名就可以满足框架了,现先将code贴 出 来:
    crt0.S key_loop.c Makefile

    crt0.S

 1 .text                                                                                                                           
  2 .global _start
  3 _start:
  4     ldr r0, =0x53000000 @ close watch dog,or it will reboot again and again
  5     ldr r1, =0x0
  6     str r1, [r0]
  7 
  8     ldr sp, =4096       @ set stack for call C function
  9 
 10     bl  main            @ call C main,that's why the user code entry is main,and it will return
 11 loop:
 12     b loop              @ call but not return

key_loop.c

  1 #define GPBCON      (*(volatile unsigned long *)0x56000010)                                                                     
  2 #define GPBDAT      (*(volatile unsigned long *)0x56000014)
  3 #define GPFCON      (*(volatile unsigned long *)0x56000050)
  4 #define GPFDAT      (*(volatile unsigned long *)0x56000054)
  5 
  6 void delay_ms(int ms)
  7 { 8 int x,y; 9 for(x=ms; x>0; x--) 10 for(y=100; y>0; y--) 11 { 12 ; //do nothing 13 }
 14 }
 15 int main()
 16 { 17 unsigned char key_value=0; 18 GPBCON |= ((1<<10) | (1<<12) | (1<<14) | (1<<16)); // set led1~4 output 19 GPFCON = 0x0; //set GPF input 20 GPBDAT = ~0x0; //set led off default 21 22 while(1) 23 { 24 key_value = GPFDAT; 25 if( 0 == (key_value & (1<<0))) //INT0 key4 26 { 27 GPBDAT = ~(1<<8); //led4 on 28 }
 29 
 30         if( 0 == (key_value & (1<<1))) //INT1 key1
 31         { 32 GPBDAT = ~(1<<5); //led1 on 33 }
 34 
 35         if( 0 == (key_value & (1<<2))) //INT2 key3
 36         { 37 GPBDAT = ~(1<<7); //led3 on 38 }
 39 
 40         if( 0 == (key_value & (1<<4))) //INT4 key2
 41         { 42 GPBDAT = ~(1<<6); //led2 on 43 }
 44 
 45         delay_ms(20);
 46     }
 47 
 48     return 0;
 49 }

Makefile

 1 key.bin : crt0.S key_loop.c                                                                                                     
  2     arm-linux-gcc -c crt0.S -o crt0.o
  3     arm-linux-gcc -c key_loop.c -o key_loop.o
  4     arm-linux-ld -Ttext 0x0 crt0.o key_loop.o -o key.elf
  5     arm-linux-objcopy -O binary -S key.elf key.bin
  6     arm-linux-objdump -D -S key.elf > key.dis
  7 
  8 clean:
  9     rm -f *.o key.elf key.bin key.dis

crt0.S还是老样子,关闭看门狗,设置好栈,最后跳转到C的main函数,在key_loop.c中,设置key引脚为input,我们采用的是效率很低的轮询查询方式,每隔一段时间就读取值一次并做判断哪个key按下了,然后点亮相应的led。到时将到中断也会用这个例子,只不过不用轮询这方式。

你可能感兴趣的:(key,按键,s3c2440,TQ2440)