Hello everyone. I have currently started to work with the NRF5340 chipsets. One of the first tasks that were assigned to me is to implement a singlewire software protocol. To get I need precise timing to get the device working. In the range of nanoseconds. My current implementation looks like this:
#include "nrfx_timer.h"
#include <zephyr/drivers/gpio.h>
#include <zephyr/devicetree.h>
#include <zephyr/device.h>
void timer_init()
{
// Initialize HF Clock
NRF_CLOCK->TASKS_HFCLKSTART = 1;
// Initialize Timer
NRF_TIMER1->MODE = TIMER_MODE_MODE_Timer;
NRF_TIMER1->TASKS_CLEAR = 1;
NRF_TIMER1->PRESCALER = NRF_TIMER_FREQ_1MHz;
NRF_TIMER1->BITMODE = TIMER_BITMODE_BITMODE_32Bit;
NRF_TIMER1->INTENSET = (TIMER_INTEN_COMPARE0_Enabled << TIMER_INTENSET_COMPARE0_Pos);
}
//
// Delay function for constant 1-Wire timings
//
void OneWire_Delay(uint32_t us)
{
// Reset compare register
NRF_TIMER1->EVENTS_COMPARE[0] = 0;
// Reset capture compare
NRF_TIMER1->CC[0] = us;
// Reset timer
NRF_TIMER1->TASKS_CLEAR = 1;
NRF_TIMER1->TASKS_STOP = 0;
NRF_TIMER1->TASKS_START = 1;
while(!NRF_TIMER1->EVENTS_COMPARE[0])
{
__NOP();
// Busy wait
}
NRF_TIMER1->TASKS_STOP = 1;
NRF_TIMER1->TASKS_CLEAR = 1;
}
static const struct gpio_dt_spec gpio27 = GPIO_DT_SPEC_GET(GPIO0_NODE, gpios);
void main(void)
{
timer_init();
for(;;)
{
OneWire_Delay((uint32_t)1000);
gpio_pin_toggle_dt(gpio27);
}
}
The pin toggles on and off as expected within 1ms. Afterwards the system waits for 400ms untill it starts again. Is something wrong with my implementation? Is this a good approach to the problem?
Best regards Maikel