Mutila: Mouse's Utilities for Arduino
Oft-used utilities: debouncing buttons, averaging samples, and so on.
MultiThrowSwitch.cpp
1 #include <stdlib.h>
2 #include <MutilaDebug.h>
3 #include "MultiThrowSwitch.h"
4 
5 MultiThrowSwitch::MultiThrowSwitch(uint8_t throws, const uint8_t pins[], bool useOff, bool pullup) :
6  _throws(throws),
7  _useOff(useOff),
8  _pos(0)
9 {
10  // First allocate space for pointers to button objects
11  _buttons = new DebouncedButton*[throws];
12 
13  // Now create the button objects
14  for (int i=0; i<_throws; i++) {
15  _buttons[i] = new DebouncedButton(pins[i], pullup);
16  }
17 }
18 
19 MultiThrowSwitch::~MultiThrowSwitch()
20 {
21  // Protect from double delete
22  if (_buttons == NULL) {
23  return;
24  }
25 
26  // Delete the button objects
27  for (int i=0; i<_throws; i++) {
28  if (_buttons[i]) {
29  delete _buttons[i];
30  _buttons[i] = NULL;
31  }
32  }
33 
34  // Finally delete the array of pointers to them
35  delete _buttons;
36  _buttons = NULL;
37 
38 }
39 
40 void MultiThrowSwitch::begin(int startPosition, uint8_t threshold, uint8_t delay)
41 {
42  if (_buttons != NULL) {
43  for (int i=0; i<_throws && _buttons[i] != NULL; i++) {
44  _buttons[i]->begin(threshold, delay);
45  }
46  }
47  if (startPosition >= 1 && startPosition <= _throws) {
48  _pos = startPosition;
49  }
50  update();
51 }
52 
54 {
55  if (_buttons == NULL) {
56  return;
57  }
58 
59  for (int i=0; i<_throws && _buttons[i] != NULL; i++) {
60  _buttons[i]->update();
61  }
62 
63  if (_buttons != NULL) {
64  for (int i=0; i<_throws && _buttons[i] != NULL; i++) {
65  if (_buttons[i]->on()) {
66  _pos = i + 1;
67  return;
68  }
69  }
70  if (_useOff) {
71  _pos = 0;
72  }
73  }
74 }
75 
77 {
78  return _pos;
79 }
80 
81 
void begin(int startPosition=0, uint8_t threshold=AbstractDebouncedButton::DefaultThreshold, uint8_t delay=AbstractDebouncedButton::DefaultButtonDelay)
void begin(uint8_t threshold=AbstractDebouncedButton::DefaultThreshold, uint8_t delay=AbstractDebouncedButton::DefaultButtonDelay)
MultiThrowSwitch(uint8_t throws, const uint8_t pins[], bool sticky=false, bool pullup=true)