75 lines
1.7 KiB
C
75 lines
1.7 KiB
C
|
|
/**
|
|
* Lab 4
|
|
*
|
|
* PWM Pin is configured to output a 20 Hz signal with a 50% duty cycle
|
|
* on GPIO 2.
|
|
*
|
|
* ADC is configured to read the value of the PWM from GPIO 2 on GPIO 26.
|
|
*
|
|
* An interrupt is setup to read the ADC value every 25 ms and print it.
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
#include "pico/stdlib.h"
|
|
#include "hardware/pwm.h"
|
|
#include "hardware/adc.h"
|
|
|
|
#define PWM_PIN 2
|
|
|
|
#define ADC_PIN 26
|
|
#define ADC_FREQ 25
|
|
|
|
/**
|
|
* Callback function for repeating timer to read ADC value
|
|
* @param t The timer that triggered the callback
|
|
* @return True to keep the timer running, false to stop it
|
|
*/
|
|
bool repeating_timer_callback (struct repeating_timer *t) {
|
|
// Read ADC value
|
|
uint16_t result = adc_read();
|
|
printf("ADC value: %d\n", result);
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Setup Function for PWM and ADC
|
|
* @param timer Repeating timer for ADC
|
|
*/
|
|
void setup (struct repeating_timer *timer) {
|
|
// PWM setup
|
|
gpio_set_function(PWM_PIN, GPIO_FUNC_PWM);
|
|
uint slice_num = pwm_gpio_to_slice_num(PWM_PIN);
|
|
uint channel = pwm_gpio_to_channel(PWM_PIN);
|
|
|
|
pwm_set_clkdiv(slice_num, 100); // 125 MHz / 100 = 1.25 MHz
|
|
pwm_set_wrap(slice_num, 62500); // 1.25 MHz / 62500 = 20 Hz
|
|
pwm_set_chan_level(slice_num, channel, 62500/2); // 50% duty cycle
|
|
|
|
pwm_set_enabled(slice_num, true);
|
|
|
|
// ADC setup
|
|
adc_init();
|
|
adc_gpio_init(ADC_PIN);
|
|
adc_select_input(0);
|
|
|
|
// Setup timer interrupt
|
|
add_repeating_timer_ms(ADC_FREQ,
|
|
repeating_timer_callback,
|
|
NULL,
|
|
timer
|
|
);
|
|
}
|
|
|
|
int main () {
|
|
stdio_init_all();
|
|
struct repeating_timer timer;
|
|
setup(&timer);
|
|
|
|
while (true)
|
|
{
|
|
tight_loop_contents();
|
|
}
|
|
}
|