I've program the Accelerometer to detect vibrations by setting a reasonable min/max threshold along all 3-axis' raw data. I need it to only count how many times it detects vibration, however, due to the way it's programmed with the threshold, I used a delay of about 1 sec in order to prevent multiple miscounts, which works but interferes with the Ultrasonic Module (HC-SR04) when it needs to read distance values is synchronously with the Accelerometer. Would like to get some feedback on this.
As far as I understand, you are using Arduino's delay()
function. Bad idea as you block the all the rest of your application, well, you noticed already...
Better approach just checking if some time elapsed, e. g. using millis
function:
static bool isDelay = false;
static unsigned long timestamp;
if(detect())
{
isDelay = true;
timestamp = millis();
}
if(isDelay && millis() - timestamp > 1000)
{
isDelay = false;
}
if(!isDelay)
{
// actions to be taken...
}
Always use subtraction between the timestamp and the current time – the time counter might overflow, subtraction result is unaffected, though, and you are safe...
You can simply skip the isDelay
variable if you are sure enough that the relevant event always occurs at least once in between overflow period (around 50 days):
static unsigned long timestamp = millis() - 1000;
if(detect())
{
timestamp = millis();
}
if(millis() - timestamp > 1000)
{
// actions to be taken...
}
Both variants: static variables as assuming you have this code in Arduino's loop
function (or one being called from loop
). Yet prefer replacing the magic number 1000 with a macro and you're fine...