How can I count pwm pulse's number when it is running ?

Hello.

     I am just do one project with Zephyr and nrf52840 to control one step motor,  the one task is to get pulse number of pwm pulse when motor is running ,  I think PPI May be userful and have write the below code ,   

....

//pwm0 init and start

//time0(work as counter) init and start 

.....

uint8_t ppi_ch;
int err;
uint32_t evt,task;

evt = nrf_pwm_event_address_get(NRF_PWM0,
NRF_PWM_EVENT_PWMPERIODEND);

task = nrfx_timer_task_address_get(NRF_TIMER0, NRF_TIMER_TASK_COUNT);

err = ppi_alloc(&ppi_ch, evt);
if (err != NRFX_SUCCESS) {
printk("Failed to allocate PPI channel.");
return NULL;
}

ppi_assign(ppi_ch, evt, task);

ppi_enable(ppi_ch);

.......

note : ppi functions are defined in ppi_trace.c, these functions can work well.

but it have not worked, it means the Time0 cannot trigger the interrupt of counter.

So, what wrong is the code? can you give me some suggestion?

Thanks.

  • Hi,

    Could I see how you setup the PWM and timer? And your prj.conf

  • OK, the code for pwm and timer (work as counter mode) is below:

    pwm = pwm_init();
    pwm_start(pwm, 10* 1000);

    printk("Counter alarm sample\n\n");
    counter_dev = device_get_binding(TIMER);
    if (counter_dev == NULL) {
    printk("Device not found\n");
    return;
    }

    counter_start(counter_dev);

    alarm_cfg.flags = 0;
    alarm_cfg.ticks = 10 * 1000;//counter_us_to_ticks(counter_dev, DELAY);
    alarm_cfg.callback = test_counter_interrupt_fn;
    alarm_cfg.user_data = &alarm_cfg;

    err = counter_set_channel_alarm(counter_dev, ALARM_CHANNEL_ID,
    &alarm_cfg);
    printk("Set alarm in %u sec (%u ticks)\n",
    (uint32_t)(counter_ticks_to_us(counter_dev,
    alarm_cfg.ticks) / USEC_PER_SEC),
    alarm_cfg.ticks);

    if (-EINVAL == err) {
    printk("Alarm settings invalid\n");
    } else if (-ENOTSUP == err) {
    printk("Alarm setting request not supported\n");
    } else if (err != 0) {
    printk("Error\n");
    }

     the pwm 's  work frequency is 10k, and I can test it with  oscilloscope,  it work well.

    the timer  works as counter , I have modify the timer's driver code (.mode = NRF_TIMER_MODE_COUNTER, ) in I:\nRF\ncs\zephyr\drivers\counter\counter_nrfx_timer.c temporarily.

     my prj.conf content is below:

    CONFIG_PRINTK=y
    CONFIG_COUNTER=y
    CONFIG_GPIO=y
    CONFIG_COUNTER_TIMER0=y
    CONFIG_NRFX_PPI=y
    CONFIG_PWM=y

    thanks.

      to add,   pwm_start is a wrapper of pwm_pin_set_usec(....).

  •  I think the method is not the best, or the PPI with pwm can't work well.  can somebody  give me suggestion to implement the function?

    Thanks.

Related