// timing in microseconds
uint32_t timerInterval = 2000;
uint32_t onTime = 1500;
uint8_t percentage = 0;
// pins for the 74hc595 chip
byte dataPin = 2;
byte clockPin = 3;
byte latchPin = 4;
int outputEnablePin = 6;
// struct pulse to make things work
struct Pulse
{
uint32_t startTime;
uint16_t pulseWidth;
bool isOn;
};
Pulse Pulses [7] {
{0, 35, false},
{0, 70, false},
{0, 105, false},
{0, 140, false},
{0, 175 , false},
{0, 210, false},
{0, 245, false}
}
void setup() {
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(latchPin, OUTPUT);
pinMode(outputEnablePin, OUTPUT);
}
void loop() {
softPWM(percentage * timerInterval / 100);
}
/*
softPWM
Create the timebase
In:
pulse width
*/
void softPWM(uint16_t pulseWidth)
{
static uint32_t startTime;
static boolean refStatus = false;
static bool trigger = false;
if (micros() - startTime >= timerInterval)
{
startTime = micros();
refStatus = !refStatus;
trigger = true;
digitalWrite(refPin, refStatus == true ? HIGH : LOW);
}
// if new period started
if (trigger == true)
{
// create the pulse with the specified width
trigger = pulse(pulseWidth);
}
}
/*
Create a pulse
In:
width of the pulse in microseconds
*/
bool pulse(uint16_t pulseWidth)
{
static uint32_t startTime;
static boolean isOn = false;
if (pulseWidth == 0)
{
digitalWrite(pwmPin, LOW);
return false;
}
if (isOn == false)
{
digitalWrite(pwmPin, HIGH);
isOn = true;
startTime = micros();
return true;
}
if (micros() - startTime >= pulseWidth)
{
//startTime = micros();
digitalWrite(pwmPin, LOW);
isOn = false;
return false;
}
}