SlowTicker: integer math only in interrupt context
[clinton/Smoothieware.git] / src / libs / SlowTicker.cpp
CommitLineData
df27a6a3 1/*
cd011f58
AW
2 This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
3 Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4 Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
df27a6a3 5 You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
cd011f58
AW
6*/
7
ded56b35
AW
8using namespace std;
9#include <vector>
ded56b35
AW
10#include "libs/nuts_bolts.h"
11#include "libs/Module.h"
12#include "libs/Kernel.h"
13#include "SlowTicker.h"
d9ebc974 14#include "libs/Hook.h"
ded56b35 15
65fe0408 16#include <mri.h>
ded56b35
AW
17
18SlowTicker* global_slow_ticker;
19
20SlowTicker::SlowTicker(){
50b9ac30 21 this->max_frequency = 0;
ded56b35 22 global_slow_ticker = this;
7dd8133c 23 LPC_SC->PCONP |= (1 << 22); // Power Ticker ON
d9ebc974 24 LPC_TIM2->MR0 = 10000; // Initial dummy value for Match Register
7dd8133c
AW
25 LPC_TIM2->MCR = 3; // Match on MR0, reset on MR0
26 LPC_TIM2->TCR = 1; // Enable interrupt
27 NVIC_EnableIRQ(TIMER2_IRQn); // Enable interrupt handler
65fe0408
MM
28
29 ispbtn.from_string("2.10")->as_input()->pull_up();
ded56b35
AW
30}
31
32void SlowTicker::set_frequency( int frequency ){
50b9ac30
MM
33 this->interval = int(floor((SystemCoreClock/4)/frequency)); // SystemCoreClock/4 = Timer increments in a second
34 LPC_TIM2->MR0 = this->interval;
7dd8133c
AW
35 LPC_TIM2->TCR = 3; // Reset
36 LPC_TIM2->TCR = 1; // Reset
ded56b35
AW
37}
38
39void SlowTicker::tick(){
2f7d3dba
AW
40
41 LPC_GPIO1->FIODIR |= 1<<20;
42 LPC_GPIO1->FIOSET = 1<<20;
43
df27a6a3 44 for (unsigned int i=0; i<this->hooks.size(); i++){
d9ebc974 45 Hook* hook = this->hooks.at(i);
50b9ac30
MM
46 hook->countdown -= this->interval;
47 if (hook->countdown < 0)
48 {
49 hook->countdown += hook->interval;
d9ebc974 50 hook->call();
df27a6a3 51 }
ded56b35 52 }
2f7d3dba
AW
53
54 LPC_GPIO1->FIOCLR = 1<<20;
55
65fe0408
MM
56 if (ispbtn.get() == 0)
57 __debugbreak();
ded56b35
AW
58}
59
60extern "C" void TIMER2_IRQHandler (void){
7dd8133c 61 if((LPC_TIM2->IR >> 0) & 1){ // If interrupt register set for MR0
df27a6a3 62 LPC_TIM2->IR |= 1 << 0; // Reset it
ded56b35 63 }
df27a6a3 64 global_slow_ticker->tick();
ded56b35
AW
65}
66