I am programming with the nRF52840DK. [Toolchain Manager: v1.3.0, IDE: Visual Studio Code (VSCode), SDK: ncs v2.6.0, window11 pro]
I'd like to inquire about methods for PWM on/off control. I'm wondering if the approach I'm currently using is common. If not, could you suggest more efficient methods?
while (1) {
if(pwm_on_off == 0){
ret = pwm_set_dt(&pwm, PWM_PERIOD, PWM_PERIOD); // PWM off
pwm_on_off = 1;
}else if(pwm_on_off == 1){
ret = pwm_set_dt(&pwm, PWM_PERIOD, PWM_PULSE_WIDTH); // PWM on
pwm_on_off = 0;
}
k_msleep(SLEEP_TIME_MS);
}
I plan to integrate this PWM control function into another application. Therefore, I'm looking for the optimal way to control PWM on/off while minimizing CPU load.
below is main.c
#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>
#include <zephyr/device.h>
#include <zephyr/drivers/pwm.h>
#define SLEEP_TIME_MS 1000
#define GPIO_PIN6 31
#define PWM0_NODE DT_NODELABEL(pwm0)
#define PWM_PERIOD 1000000 // period = On_time + Off_time [ns]
#define PWM_PULSE_WIDTH 700000 // Off_time [ns]
static const struct pwm_dt_spec pwm= PWM_DT_SPEC_GET(DT_ALIAS(pwm_led0));
int pwm_on_off=0;
int main(void)
{
int ret;
ret = device_is_ready(pwm.dev);
printk("device_is_ready: %d \n", ret); //t: 1
ret = pwm_set_dt(&pwm, PWM_PERIOD, PWM_PULSE_WIDTH);
printk("pwm_set_dt: %d \n", ret); //t: 1
while (1) {
if(pwm_on_off == 0){
ret = pwm_set_dt(&pwm, PWM_PERIOD, PWM_PERIOD); // PWM off
pwm_on_off = 1;
}else if(pwm_on_off == 1){
ret = pwm_set_dt(&pwm, PWM_PERIOD, PWM_PULSE_WIDTH); // PWM on
pwm_on_off = 0;
}
k_msleep(SLEEP_TIME_MS);
}
return 0;
}
below is code of .overlay
&gpio0 {
status = "okay";
};
/* &pwm0 {
status = "okay";
};
*/
&pinctrl {
pwm0_default_custom: pwm0_default_custom {
group1 {
psels = <NRF_PSEL(PWM_OUT0, 0, 31)>;
nordic,invert;
};
};
pwm0_sleep_custom: pwm0_sleep_custom {
group1 {
psels = <NRF_PSEL(PWM_OUT0, 0, 31)>;
low-power-enable;
};
};
};
&pwm0 {
pinctrl-0 = <&pwm0_default_custom>;
pinctrl-1 = <&pwm0_sleep_custom>;
pinctrl-names = "default", "sleep";
status = "okay";
};
/ {
pwmleds {
compatible = "pwm-leds";
pwm_led0: pwm_led_0 {
pwms = <&pwm0 0 PWM_MSEC(20) PWM_POLARITY_INVERTED>;
};
};
};