Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Raspberry Pi Pico PWM example
- Scott Beasley (2021) No Copyright.
- Code used by Damien P. George Copyright (c) 2020
- From the RPI Pico MicroPython project. See below for copyright info.
- https://github.com/raspberrypi/micropython/blob/pico/ports/rp2/machine_pwm.c
- */
- #include "pico/stdlib.h"
- #include <stdio.h>
- #include "pico/time.h"
- #include "hardware/pwm.h"
- #include "hardware/clocks.h"
- #define LED_PIN 25
- #define PWM_PIN 16
- #define DUTY_50_PCT 32767
- #define PWM_1KHZ 62500 // Wrap val for 1khz at SYSCLK / 2
- // Not worring about less than 1k for now.
- int set_pwm_duty (uint slice, uint channel, uint32_t top, uint32_t duty);
- int main (void)
- {
- uint32_t div = 0, top = 0;
- uint slice_num, channel;
- // Use the LED for error notifications
- gpio_init (LED_PIN);
- gpio_set_dir (LED_PIN, GPIO_OUT);
- slice_num = pwm_gpio_to_slice_num (PWM_PIN);
- channel = pwm_gpio_to_channel (PWM_PIN);
- gpio_set_function (PWM_PIN, GPIO_FUNC_PWM);
- // Div the sys clock by 2
- pwm_set_clkdiv (slice_num, (float)2 * 1.0f);
- // Set the PWM counter wrap value to reset on
- top = PWM_1KHZ / 50; // Set for 50khz freq - Close to it anyway.
- pwm_set_wrap (slice_num, top);
- while (1) {
- tight_loop_contents ( );
- set_pwm_duty (slice_num, channel, top, (uint32_t)DUTY_50_PCT);
- sleep_ms(2000);
- set_pwm_duty (slice_num, channel, top, (uint32_t)DUTY_50_PCT / 2);
- sleep_ms(2000);
- set_pwm_duty (slice_num, channel, top, (uint32_t)DUTY_50_PCT / 4);
- sleep_ms(2000);
- set_pwm_duty (slice_num, channel, top, (uint32_t)DUTY_50_PCT / 6);
- sleep_ms(2000);
- }
- }
- // Code used from https://github.com/raspberrypi/micropython/blob/pico/ports/rp2/machine_pwm.c
- // Function - machine_pwm_duty_u16
- // Shaped for my needs (Scott Beasley) No Copyright.
- // MIT License (MIT) Damien P. George Copyright (c) 2020
- int set_pwm_duty (uint slice, uint channel, uint32_t top, uint32_t duty)
- {
- // Set duty cycle.
- uint32_t cc = duty * (top + 1) / 65535;
- pwm_set_chan_level (slice, channel, cc);
- pwm_set_enabled (slice, true);
- return 0;
- }
Add Comment
Please, Sign In to add comment