108
110
static int saved_since = 0;
109
111
unsigned long now = millis();
110
112
unsigned long real_button_state = PIND & BUTTON;
113
bool button_state_changed = false;
111
114
if( saved_button_state != real_button_state ) {
112
115
saved_button_state = real_button_state;
113
116
saved_since = now;
116
119
now - saved_since > 25 )
118
121
button_state = saved_button_state;
121
// on rising edge of press, set toggle
122
static int last_button_state = 0;
124
if( last_button_state != button_state )
126
last_button_state = button_state;
127
if( !button_state ) toggle = true;
122
button_state_changed = true;
125
// read buffer from serial
126
static int buffer_pos = 0;
127
static char buffer[ BUFFERLEN ] = "";
128
int got = getc( &USBSerialStream );
129
bool got_command = false;
134
case '\n': got_command = true; break;
137
if( !buffer_pos ) break;
140
if( buffer_pos < ( BUFFERLEN - 1 ) )
141
buffer[ buffer_pos++ ] = got;
142
buffer[ buffer_pos ] = 0;
132
145
static bool relay_state = false;
146
bool toggle_relay = false;
151
// command: turn relay off
152
if( !strcmp( buffer, "0" ) ) {
153
if( relay_state ) toggle_relay = true;
156
// command: turn relay on
157
else if( !strcmp( buffer, "1" ) ) {
158
if( !relay_state ) toggle_relay = true;
161
// command: report relay state
162
else if( !strcmp( buffer, "?" ) ) {
163
fputs( relay_state? "1\r\n" : "0\r\n", &USBSerialStream );
166
// command: toggle relay state
167
else if( !strcmp( buffer, "." ) ) {
172
buffer_pos = buffer[ 0 ] = 0;
175
// handle button press?
176
if( button_state_changed && !button_state )
135
184
relay_state = !relay_state;
170
/* Must throw away unused bytes from the host, or it will lock up while
171
* waiting for the device */
172
CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
174
219
CDC_Device_USBTask(&VirtualSerial_CDC_Interface);