【麦昆试用】迟来的第四帖——试用Arduino IDE开发环境&定时器中断
[复制链接]
这个标题的因果关系应该反过来说,因为我想调通microbit主控板的定时器中断,在网上寻求答案,最终得知最便捷的方式是通过Arduino IDE开发环境实现,因为这个开发环境可以从开源社区下载安装一切纳入Arduino家族的开发板的资源并获得充足支持,在观看完代码之后,我发现Arduino IDE开源库里面对于microbit主控板的定时器中断例程实际上也是通过控制板上主控单片机nrf51822的寄存器实现的,将寄存器操作封装成类和对象的操作,正是Arduino开发的最常见操作。
首先下载Arduino IDE开发环境,这个不用多赘述,直接在arduino.cc官网下载即可,下载安装Arduino IDE这步很简单,安装Demo例程也很简单,难点在于安装器件支持包,这里先简单介绍下怎么安装micro:bit的DEMO例程。
打开ArduinoIDE,打开项目->库,搜索micro:bit,即可找到micro:bit所对应的Demo例程:
这个例程下有齐了micro:bit板子的大部分BSP(板级)Demo,如blink闪灯,定时器,按键,蓝牙控制器等,我选择这期主题——定时器,打开timerdemo:
然后到了最麻烦的一步(这步难度不高,就是很麻烦),那就是ArduinoIDE软件内部安装器件支持包了,这个跟电脑所在的网络环境息息相关,稍微有点差错都会下载失败,我被这个折腾了很久,最终是用公司的网络艰难完成的器件支持包安装,这里推荐大家使用离线安装的方式,离线安装方式繁琐但可以绕开ArduinoIDE内部蛋疼的联网机制:
timerdemo定时器例程写法与普通的KEIL程序如出一辙,使用寄存器方式配置定时器,然后在中断服务函数里面触发,例程使用的是NRF52832主控的定时器2,有两个比较事件,在同一个中断服务函数里面触发:
// This is a 'low level' demo showing how to use timer 2 (the only available timer really)
// to blink an LED. This code turned into the matrix handler, so you cant use it and the
// Adafruit_Microbit library at the same time but maybe its useful!
const int COL1 = 3; // Column #1 control
const int LED = 26; // 'row 1' led
void start_timer(void)
{
NRF_TIMER2->MODE = TIMER_MODE_MODE_Timer; // Set the timer in Counter Mode
NRF_TIMER2->TASKS_CLEAR = 1; // clear the task first to be usable for later
NRF_TIMER2->PRESCALER = 8;
NRF_TIMER2->BITMODE = TIMER_BITMODE_BITMODE_16Bit; //Set counter to 16 bit resolution
NRF_TIMER2->CC[0] = 32000; //Set value for TIMER2 compare register 0
NRF_TIMER2->CC[1] = 5; //Set value for TIMER2 compare register 1
// Enable interrupt on Timer 2, both for CC[0] and CC[1] compare match events
NRF_TIMER2->INTENSET = (TIMER_INTENSET_COMPARE0_Enabled << TIMER_INTENSET_COMPARE0_Pos) | (TIMER_INTENSET_COMPARE1_Enabled << TIMER_INTENSET_COMPARE1_Pos);
NVIC_EnableIRQ(TIMER2_IRQn);
NRF_TIMER2->TASKS_START = 1; // Start TIMER2
}
/** TIMTER2 peripheral interrupt handler. This interrupt handler is called whenever there it a TIMER2 interrupt
* Don't mess with this line. really.
*/
extern "C" { void TIMER2_IRQHandler(void) { timer_pal(); } }
void timer_pal(void) {
if ((NRF_TIMER2->EVENTS_COMPARE[0] != 0) && ((NRF_TIMER2->INTENSET & TIMER_INTENSET_COMPARE0_Msk) != 0))
{
NRF_TIMER2->EVENTS_COMPARE[0] = 0; //Clear compare register 0 event
Serial.println("TIMER2 Event C0");
}
if ((NRF_TIMER2->EVENTS_COMPARE[1] != 0) && ((NRF_TIMER2->INTENSET & TIMER_INTENSET_COMPARE1_Msk) != 0))
{
NRF_TIMER2->EVENTS_COMPARE[1] = 0; //Clear compare register 1 event
Serial.println("TIMER2 Event C1");
}
}
void setup() {
Serial.begin(115200);
Serial.println("microbit is ready!");
// because the LEDs are multiplexed, we must ground the opposite side of the LED
pinMode(COL1, OUTPUT);
digitalWrite(COL1, LOW);
pinMode(LED, OUTPUT);
start_timer();
}
void loop(){
Serial.println("blink!");
delay(500);
}
这里小改了一下,波特率改成115200,定时器中断触发里面改成串口打印,看看运行效果:
|