在很多情况下,按钮是比较方便的输入设备,在一般的开发板子上面都会有设计按钮,笔者所用的cc2538板子板载了几个按键用于输入测试,在contiki已经预先直接定义了按钮事件(并且已经设计了软件除颤)为传感事件其一,我们可以通过书写代码来捕捉传感事件发生并进行再一步的判别。
在这里,按钮事件均为高电平触发。线程在随开机启动后会监听事件,当事件发生后再执行代码,代码判断事件是否为传感事件,再继而判断触发的数据是否对应按钮的传感值,从而判断某个按钮按下。
所包含的头文件:
#include "contiki.h"
#include "dev/leds.h"
#include "dev/cc2538-sensors.h"
#include "dev/serial-line.h"
#include "dev/button-sensor.h"
#include "stdio.h"
1.建立线程并设置为自动启动
PROCESS(ButtonEvent, "Serial port output");
AUTOSTART_PROCESSES(&ButtonEvent);
2.等待事件发生
PROCESS_YIELD();//Wait for any event
3.发生事件处理代码
写在while循环内,当事件发生后,YIELD结束,对事件类型进行判断,这里用if()来进行
//如果event为sensors_event,判断数据是否为select按键按下
if(ev == sensors_event) {
if(data == &button_select_sensor) {
leds_off(0x0F);//关闭所有的LED灯
printf("All LED off");
}
完整代码:
#include "contiki.h"
#include "dev/leds.h"
#include "dev/cc2538-sensors.h"
#include "dev/serial-line.h"
#include "dev/button-sensor.h"
#include
PROCESS(ButtonEvent, "Serial port output");
AUTOSTART_PROCESSES(&ButtonEvent);
PROCESS_THREAD(ButtonEvent,ev,data)
{
PROCESS_BEGIN();
while(1){
PROCESS_YIELD();//Wait for any event
if(ev == sensors_event) {
if(data == &button_select_sensor)
{
leds_off(0x0F);
printf("All LED off");
}
else if(data == &button_left_sensor || data == &button_right_sensor) {
leds_toggle(8);
printf("Left or Right button pressed\n");
}
else if(data == &button_down_sensor)
{
leds_toggle(4);
printf("down button pressed\n");
}
else if(data == &button_up_sensor)
{
leds_toggle(2);
printf("up button pressed\n");
}
}
if(ev == serial_line_event_message)
{
printf("\nYour Send is :%s\n",(char*)data );
if((char*)data == "on")
leds_toggle(0x0F);
}
}
PROCESS_END();
}
转载请注明原文地址: https://ju.6miu.com/read-685.html