Events: add ON_SECOND_TICK event that fires once per second. Also finish moving event...
[clinton/Smoothieware.git] / src / libs / SlowTicker.cpp
1 /*
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.
5 You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
6 */
7
8 using namespace std;
9 #include <vector>
10 #include "libs/nuts_bolts.h"
11 #include "libs/Module.h"
12 #include "libs/Kernel.h"
13 #include "SlowTicker.h"
14 #include "libs/Hook.h"
15
16 #include <mri.h>
17
18 SlowTicker* global_slow_ticker;
19
20 SlowTicker::SlowTicker(){
21 this->max_frequency = 0;
22 global_slow_ticker = this;
23 LPC_SC->PCONP |= (1 << 22); // Power Ticker ON
24 LPC_TIM2->MR0 = 10000; // Initial dummy value for Match Register
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
28
29 ispbtn.from_string("2.10")->as_input()->pull_up();
30
31 flag_1s_flag = 0;
32 flag_1s_count = SystemCoreClock;
33 }
34
35 void SlowTicker::set_frequency( int frequency ){
36 this->interval = int(floor((SystemCoreClock >> 2)/frequency)); // SystemCoreClock/4 = Timer increments in a second
37 LPC_TIM2->MR0 = this->interval;
38 LPC_TIM2->TCR = 3; // Reset
39 LPC_TIM2->TCR = 1; // Reset
40 }
41
42 void SlowTicker::tick()
43 {
44 LPC_GPIO1->FIODIR |= 1<<20;
45 LPC_GPIO1->FIOSET = 1<<20;
46
47 for (unsigned int i=0; i<this->hooks.size(); i++){
48 Hook* hook = this->hooks.at(i);
49 hook->countdown -= this->interval;
50 if (hook->countdown < 0)
51 {
52 hook->countdown += hook->interval;
53 hook->call();
54 }
55 }
56
57 flag_1s_count -= this->interval;
58 if (flag_1s_count < 0)
59 {
60 flag_1s_count += SystemCoreClock >> 2;
61 flag_1s_flag++;
62 }
63
64 LPC_GPIO1->FIOCLR = 1<<20;
65
66 if (ispbtn.get() == 0)
67 __debugbreak();
68 }
69
70 bool SlowTicker::flag_1s(){
71 __disable_irq();
72 if (flag_1s_flag)
73 {
74 flag_1s_flag--;
75 __enable_irq();
76 return true;
77 }
78 __enable_irq();
79 return false;
80 }
81
82 extern "C" void TIMER2_IRQHandler (void){
83 if((LPC_TIM2->IR >> 0) & 1){ // If interrupt register set for MR0
84 LPC_TIM2->IR |= 1 << 0; // Reset it
85 }
86 global_slow_ticker->tick();
87 }
88