That is significantly faster! So, this code below is where it was used. That thread was closed so I can’t ask there. I wanted to understand the what and how first so I could understand how to modify it for another board. The issues, are: The pwm signal for the device I’m trying to drive has a a built in circuit that uses a fixed 100hz frequency with varying duty cycle from 10%-90%. The pot referenced below adjusts the duty cycle which is interpreted by the device to adjust position.” Analogwrite support PWM is 490hz and 900hz.” So, I need the100hz signal but I’d rather not use an UNO since I have other stuff to combine running on another board. Obviously, PINB won’t compile on another board so I was looking for alternative ways to handle it.
It’s not straightforward PWM.
byte pin8 = 8;
unsigned long currentMicros;
unsigned long previousMicros;
unsigned long elapsedMicros;
unsigned long period = 10000UL; // microseconds, 0.01S 1/.01 = 100 Hz
unsigned long highTime = 1000UL; // microseconds
unsigned long lowTime; // microseconds
byte highLow = 0; // flag to show which state output is in
int potValue;
void setup()
{
pinMode (pin8, OUTPUT);
digitalWrite (pin8, LOW);
lowTime = period - highTime; // with numbers above, 10000 - 1000 = 9000
currentMicros = micros();
previousMicros = currentMicros;
}
void loop()
{
elapsedMicros = micros() - previousMicros;
if ((elapsedMicros >= lowTime) && (highLow == 0))
{
previousMicros = previousMicros + lowTime;
PINB = 0b00000001;
highLow = 1; // started high period
}
else if ((elapsedMicros >= highTime) && (highLow == 1))
{
previousMicros = previousMicros + highTime;
PINB = 0b00000001;
highLow = 0; // started low period
}
// "most of the time" (processor-wise) the above do nothing as the proper time hasn't elapsed
// use that downtime to adjust the duty cycle
potValue = analogRead(A0);
highTime = potValue * 10; // 1023 * 10 = 10230
// cap the range by limiting to 10-90%
if (highTime > 9000)
{
highTime = 9000;
}
if (highTime < 1000)
{
highTime = 1000;
}
lowTime = period - highTime;
}