Nios® II Software Developer Handbook

ID 683525
Date 8/28/2023
Public
Document Table of Contents

7.9.2. Alarms

You can register functions to be executed at a specified time using the HAL alarm facility. A software program registers an alarm by calling the function alt_alarm_start():
int alt_alarm_start(alt_alarm* alarm, 
   alt_u32 nticks,
   alt_u32 (*callback) (void* context), 
   void* context); 

The function callback() is called after nticks have elapsed. The input argument context is passed as the input argument to callback() when the call occurs. The HAL does not use the context parameter. It is only used as a parameter to the callback() function.

Your code must allocate the alt_alarm structure, pointed to by the input argument alarm. This data structure must have a lifetime that is at least as long as that of the alarm. The best way to allocate this structure is to declare it as a static or global. alt_alarm_start() initializes *alarm.

The callback function can reset the alarm. The return value of the registered callback function is the number of ticks until the next call to callback. A return value of zero indicates that the alarm should be stopped. You can manually cancel an alarm by calling alt_alarm_stop().

One alarm is created for each call to alt_alarm_start(). Multiple alarms can run simultaneously.

Alarm callback functions execute in an exception context. This imposes functional restrictions which you must observe when writing an alarm callback.

For more information about the use of these functions, refer to the "Exception Handling" chapter.

Example 6–8. Using a Periodic Alarm Callback Function

#include <stddef.h>
#include <stdio.h>
#include "sys/alt_alarm.h"
#include "alt_types.h"
/*
* The callback function.
*/
alt_u32 my_alarm_callback (void* context)
{
/* This function is called once per second */
return alt_ticks_per_second();
}
...
/* The alt_alarm must persist for the duration of the alarm. */
static alt_alarm alarm;
...
if (alt_alarm_start (&alarm,
alt_ticks_per_second(),
my_alarm_callback,
NULL) < 0)
{
printf ("No system clock available\n");
}