#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/pwm.h"
// Definition of LED pins
const uint LED_RED = 13; // Pin for the red LED
const uint LED_BLUE = 12; // Pin for the blue LED
// PWM settings
const uint16_t PERIOD_RED = 1000; // PWM period for the red LED (1 kHz)
const uint16_t PERIOD_BLUE = 100; // PWM period for the blue LED (10 kHz)
const float DIVIDER_PWM = 16.0; // Fractional clock divider for PWM
const uint16_t MAX_DUTY_CYCLE = 100; // Maximum duty cycle (100%)
// Global variables
uint16_t red_duty_cycle = 5; // Initial duty cycle for the red LED (5%)
uint16_t blue_duty_cycle = 5; // Initial duty cycle for the blue LED (5%)
bool up_down = true; // Variable to control the direction of the duty cycle
// Function to configure PWM for an LED
void setup_pwm(uint pin, uint16_t period) {
uint slice = pwm_gpio_to_slice_num(pin); // Get the PWM slice associated with the pin
gpio_set_function(pin, GPIO_FUNC_PWM); // Configure the pin for PWM function
pwm_set_clkdiv(slice, DIVIDER_PWM); // Set the clock divider for PWM
pwm_set_wrap(slice, period); // Set the maximum counter value (PWM period)
pwm_set_enabled(slice, true); // Enable PWM on the corresponding slice
}
// Function to update the duty cycle of an LED
void update_duty_cycle(uint pin, uint16_t duty_cycle, uint16_t period) {
uint16_t level = (duty_cycle * period) / 100; // Calculate the PWM level
pwm_set_gpio_level(pin, level); // Set the PWM level
}
// Main function
int main() {
stdio_init_all(); // Initialize standard I/O
// Configure PWM for the LEDs
setup_pwm(LED_RED, PERIOD_RED); // Configure PWM for the red LED (1 kHz)
setup_pwm(LED_BLUE, PERIOD_BLUE); // Configure PWM for the blue LED (10 kHz)
while (true) {
// Update the duty cycle for the red LED
update_duty_cycle(LED_RED, red_duty_cycle, PERIOD_RED);
// Update the duty cycle for the blue LED
update_duty_cycle(LED_BLUE, blue_duty_cycle, PERIOD_BLUE);
// Wait for 2 seconds
sleep_ms(2000);
// Update the duty cycle (increment or decrement)
if (up_down) {
red_duty_cycle += 5; // Increment the duty cycle for the red LED
blue_duty_cycle += 5; // Increment the duty cycle for the blue LED
if (red_duty_cycle >= MAX_DUTY_CYCLE || blue_duty_cycle >= MAX_DUTY_CYCLE) {
up_down = false; // Change direction to decrement
}
} else {
red_duty_cycle -= 5; // Decrement the duty cycle for the red LED
blue_duty_cycle -= 5; // Decrement the duty cycle for the blue LED
if (red_duty_cycle <= 5 || blue_duty_cycle <= 5) {
up_down = true; // Change direction to increment
}
}
}
}