Last active
April 22, 2020 16:47
-
-
Save ma2shita/2417df9221eb9aaa262f1fb7d7899f8c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* See: https://soracom.github.io/iot-recipes/iamhome-by-wio-lte-ultrasonic-sensor/ */ | |
/* | |
* Copyright (c) 2020 Kohei "Max" MATSUSHITA | |
* Released under the MIT license | |
* https://opensource.org/licenses/mit-license.php | |
*/ | |
#include <WioLTEforArduino.h> | |
#define console SerialUSB | |
WioLTE Wio; | |
#include <GroveDriverPack.h> | |
GroveBoard Board; | |
GroveUltrasonicRanger Ranger(&Board.D38); | |
float state_change_distance = 200.0; // mm | |
unsigned long state_entry_min = 120; // ms | |
unsigned long state_entry_max = 500; // ms | |
int required_as_event = 2; // times | |
unsigned long event_timeout = 1800; // ms | |
void setup() | |
{ | |
Wio.Init(); | |
console.println("--- START"); | |
Board.D38.Enable(); | |
Ranger.Init(); | |
} | |
#define MEASUREMENT_INTERVAL 80 // ms | |
boolean state = false; | |
boolean prev_state; | |
int state_change_counter = 0; | |
unsigned long state_entry_started_at_millis = 0; | |
unsigned long event_started_at_millis = 0; | |
void loop() | |
{ | |
Ranger.Read(); | |
float distance = Ranger.Distance; | |
console.print("distance:"); console.println(distance); | |
prev_state = state; /* keeping prev. loop value */ | |
state = (distance <= state_change_distance); /* update by new value */ | |
if (state && !prev_state) { /* entry */ | |
Wio.LedSetRGB(16, 0, 0); | |
state_entry_started_at_millis = millis(); | |
if (!state_change_counter) { /* begin of event */ | |
event_started_at_millis = state_entry_started_at_millis; | |
} | |
} | |
unsigned long millis_while_leave = 0; | |
if (!state && prev_state) { /* leaved */ | |
Wio.LedSetRGB(0, 0, 0); | |
millis_while_leave = millis() - state_entry_started_at_millis; | |
} | |
console.print("millis_while_leave:"); console.println(millis_while_leave); | |
if (state_entry_min <= millis_while_leave && millis_while_leave <= state_entry_max) { | |
state_change_counter++; | |
} | |
unsigned long millis_while_event = millis() - event_started_at_millis; | |
if (event_timeout < millis_while_event) { | |
state_change_counter = 0; /* Reset because it was not within the period */ | |
} | |
if (state_change_counter == required_as_event && millis_while_event <= event_timeout) { | |
/* Implementation block for user at event firing */ | |
Wio.LedSetRGB(16, 16, 16); | |
delay(1000); | |
Wio.LedSetRGB(0, 0, 0); | |
state_change_counter = 0; /* DONT REMOVE (reset for next tick) */ | |
} | |
delay(MEASUREMENT_INTERVAL); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment