2021-01-29 06:31:58 -05:00
|
|
|
//
|
|
|
|
// FILE: HeartBeat.cpp
|
|
|
|
// AUTHOR: Rob Tillaart
|
2021-12-19 06:08:01 -05:00
|
|
|
// VERSION: 0.2.1
|
2021-01-29 06:31:58 -05:00
|
|
|
// PURPOSE: Arduino library for HeartBeat with frequency and dutyCycle
|
|
|
|
// DATE: 2019-06-12
|
|
|
|
// URL: https://github.com/RobTillaart/HeartBeat
|
|
|
|
//
|
|
|
|
// HISTORY:
|
|
|
|
// 0.1.0 2019-06-12 initial version
|
|
|
|
// 0.1.1 2020-12-24 arduino-CI
|
|
|
|
// 0.1.2 2021-01-15 renamed all to HeartBeat
|
|
|
|
// added dutyCycle
|
2021-05-28 07:30:27 -04:00
|
|
|
// 0.1.3 2021-05-27 fix arduino-lint
|
2021-11-02 12:26:51 -04:00
|
|
|
// 0.2.0 2021-11-02 update Build-CI, add badges
|
|
|
|
// add getFrequency(), getDutyCycle();
|
|
|
|
// add getState().
|
|
|
|
// removed set()
|
2021-12-19 06:08:01 -05:00
|
|
|
// 0.2.1 2021-12-18 update library.json, license, minor edits
|
|
|
|
|
2021-01-29 06:31:58 -05:00
|
|
|
|
|
|
|
|
|
|
|
#include "HeartBeat.h"
|
|
|
|
|
|
|
|
|
|
|
|
HeartBeat::HeartBeat()
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void HeartBeat::begin(const uint8_t pin, float frequency)
|
|
|
|
{
|
|
|
|
_pin = pin;
|
|
|
|
pinMode(_pin, OUTPUT);
|
|
|
|
|
|
|
|
setFrequency(frequency);
|
|
|
|
enable();
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void HeartBeat::setFrequency(float frequency)
|
|
|
|
{
|
2021-11-02 12:26:51 -04:00
|
|
|
_frequency = frequency;
|
|
|
|
if (_frequency < 0) _frequency = -frequency;
|
|
|
|
if (_frequency < 0.001) _frequency = 0.001;
|
2021-01-29 06:31:58 -05:00
|
|
|
_setFreqDuty();
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void HeartBeat::setDutyCycle(float dutyCycle)
|
|
|
|
{
|
|
|
|
_dutyCycle = constrain(dutyCycle, 0, 100); // percentage
|
|
|
|
_setFreqDuty();
|
|
|
|
}
|
|
|
|
|
2021-05-28 07:30:27 -04:00
|
|
|
|
2021-01-29 06:31:58 -05:00
|
|
|
void HeartBeat::beat()
|
|
|
|
{
|
|
|
|
if (_running == false)
|
|
|
|
{
|
2021-11-02 12:26:51 -04:00
|
|
|
_state = LOW;
|
2021-01-29 06:31:58 -05:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
uint32_t now = micros();
|
2021-11-02 12:26:51 -04:00
|
|
|
if ((_state == LOW) && (now - _lastHeartBeat) < _dutyCycleLow) return;
|
|
|
|
if ((_state == HIGH) && (now - _lastHeartBeat) < _dutyCycleHigh) return;
|
2021-01-29 06:31:58 -05:00
|
|
|
_lastHeartBeat = now;
|
2021-11-02 12:26:51 -04:00
|
|
|
_state = !_state;
|
2021-01-29 06:31:58 -05:00
|
|
|
}
|
2021-11-02 12:26:51 -04:00
|
|
|
digitalWrite(_pin, _state);
|
2021-01-29 06:31:58 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/////////////////////////////////
|
2021-11-02 12:26:51 -04:00
|
|
|
//
|
|
|
|
// PRIVATE
|
|
|
|
//
|
2021-01-29 06:31:58 -05:00
|
|
|
void HeartBeat::_setFreqDuty()
|
|
|
|
{
|
|
|
|
float time = 10000.0/_frequency;
|
|
|
|
_dutyCycleHigh = round(_dutyCycle * time);
|
|
|
|
_dutyCycleLow = round((100 - _dutyCycle) * time);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// -- END OF FILE --
|
2021-11-02 12:26:51 -04:00
|
|
|
|