Skip to content

Instantly share code, notes, and snippets.

@kongmunist
Last active December 23, 2020 08:10
Show Gist options
  • Save kongmunist/29587107f436bfc7253c585457831631 to your computer and use it in GitHub Desktop.
Save kongmunist/29587107f436bfc7253c585457831631 to your computer and use it in GitHub Desktop.
Arduino Variable Duty-Cycle Square Wave Generator
#define LED_pin 9
// Track LED state
bool LED_state = false;
// Set frequency of LED
float blinkrate = 1; // In Hz
float delay_between_switch = 500.0/blinkrate; // Blink at N Hz means you switch every 1s/(N/2)
// Track blinking cycle times of LED
long lastBlinkedTime;
void setup() {
pinMode(LED_pin, OUTPUT);
lastBlinkedTime = millis();
}
void loop() {
long now = millis();
if (now - lastBlinkedTime > delay_between_switch){
digitalWrite(LED_pin, LED_state);
LED_state = !LED_state;
lastBlinkedTime = now;
}
}
#define LED_pin 9
// Track LED state
bool LED_state = false;
// Set frequency and duty cycle of LED
float blinkrate = 20; // In Hz
int dutyCycle = 80; // in percent (%)
// Since time slices are much smaller, use microseconds
float granularity = 100.0;
float delay_between_check = 1000000.0/blinkrate/granularity; // 1 sec/rate, divided into 100 segments
int cyclePosition = 0; // out of 100
// Track blinking cycle times of LED
long lastCheckedTime;
void setup() {
pinMode(LED_pin, OUTPUT);
lastCheckedTime = micros();
Serial.begin(9600);
Serial.println(delay_between_check);
}
void loop() {
long now = micros();
if (now - lastCheckedTime > delay_between_check){
// Only turn LED on if current cycle position is less than the duty cycle
if (cyclePosition < dutyCycle){
digitalWrite(LED_pin, HIGH);
} else {
digitalWrite(LED_pin, LOW);
}
// Increment cycle position, zero it out if it's too big
cyclePosition++;
cyclePosition %= granularity;
lastCheckedTime = now;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment