Merge branch 'edge' into onboot
[clinton/Smoothieware.git] / src / modules / tools / switch / Switch.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 #include "libs/Module.h"
9 #include "libs/Kernel.h"
10 #include <math.h>
11 #include "Switch.h"
12 #include "libs/Pin.h"
13
14 #include "MRI_Hooks.h"
15
16 Switch::Switch(){}
17
18 Switch::Switch(uint16_t name){
19 this->name_checksum = name;
20 }
21
22 void Switch::on_module_loaded(){
23 register_for_event(ON_CONFIG_RELOAD);
24 this->register_for_event(ON_GCODE_EXECUTE);
25
26 // Settings
27 this->on_config_reload(this);
28
29 // PWM
30 this->kernel->slow_ticker->attach(1000, &output_pin, &Pwm::on_tick);
31 }
32
33
34 // Get config
35 void Switch::on_config_reload(void* argument){
36 this->on_m_code = this->kernel->config->value(switch_checksum, this->name_checksum, on_m_code_checksum )->required()->as_number();
37 this->off_m_code = this->kernel->config->value(switch_checksum, this->name_checksum, off_m_code_checksum )->required()->as_number();
38 this->output_pin.from_string(this->kernel->config->value(switch_checksum, this->name_checksum, output_pin_checksum )->required()->as_string())->as_output();
39 this->output_pin.set(this->kernel->config->value(switch_checksum, this->name_checksum, startup_state_checksum )->by_default(0)->as_number() );
40
41 set_low_on_debug(output_pin.port_number, output_pin.pin);
42 }
43
44 // Turn pin on and off
45 void Switch::on_gcode_execute(void* argument){
46 Gcode* gcode = static_cast<Gcode*>(argument);
47 if( gcode->has_m){
48 int code = gcode->m;
49 if( code == this->on_m_code ){
50 if (gcode->has_letter('S'))
51 {
52 int v = gcode->get_value('S') * output_pin.max_pwm() / 256.0;
53 if (v)
54 this->output_pin.pwm(v);
55 else
56 this->output_pin.set(0);
57 }
58 else
59 {
60 // Turn pin on
61 this->output_pin.set(1);
62 }
63 }
64 if( code == this->off_m_code ){
65 // Turn pin off
66 this->output_pin.set(0);
67 }
68 }
69 }