//#define DEBUG
// timing in microseconds
uint32_t timerInterval = 2000;
//uint32_t onTime = 500;
uint8_t percentage = 25;
uint8_t refPin = 12;
uint8_t pwmPin = 13;
void setup()
{
Serial.begin(115200);
Serial.println(F("Software PWM"));
pinMode(refPin, OUTPUT);
pinMode(pwmPin, OUTPUT);
}
void loop()
{
// check serial data for PWM pulse width percentage
if (Serial.available())
{
char ch = Serial.read();
if (ch == '+' || ch == '-')
{
if (ch == '+' && percentage < 100)
{
percentage++;
}
if (ch == '-' && percentage > 0)
{
percentage--;
}
Serial.print(F("percentage = " ));
Serial.print(percentage);
Serial.print(F("%, onTime = "));
Serial.print(percentage * timerInterval / 100);
Serial.print(F(" us of "));
Serial.print(timerInterval);
Serial.println(F(" us"));
}
}
// run software PWM
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);
#ifdef DEBUG
Serial.print(micros());
Serial.print(F(" refStatus = "));
Serial.println(refStatus);
Serial.print(micros());
Serial.println(F(" Trigger set to true"));
#endif
}
// if new period started
if (trigger == true)
{
// create the pulse with the specified width
trigger = pulse(pulseWidth);
if (trigger == false)
{
#ifdef DEBUG
Serial.print(micros());
Serial.println(F(" Trigger set to false"));
#endif
}
}
}
/*
Creaste 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();
#ifdef DEBUG
Serial.print(micros());
Serial.print(F(" pwmPin = "));
Serial.println("HIGH");
#endif
return true;
}
if (micros() - startTime >= pulseWidth)
{
//startTime = micros();
digitalWrite(pwmPin, LOW);
isOn = false;
#ifdef DEBUG
Serial.print(micros());
Serial.print(F(" pwmPin = "));
Serial.println("LOW");
#endif
return false;
}
}