Request timer interrupts in userspace program? - c

Is it possible (preferably in an OS-independent fashion, although I happen to be using Windows) to request a timer interrupt in a userspace program?
Here is some pseudo-code which may illustrate what kind of functionality I'm looking for:
#include <time_library_x.h> //For setHandler() and set_timer_for_ms()
void timerInterruptHandler() {
update_something();
set_timer_for_ms(50);
}
void main() {
setHandler(timerInterruptHandler);
set_timer_for_ms(50);
while(1) {
very_boring_data_collection();
}
}
Anyone know what "library x" is?

In Windows, there is Timers object to create Timer object and register callback function.
In Linux using SIGALRM and setitimer is common to implement timer things, but I have not seen such libraries which integrates those for mult-platform use.
Windows Timers Example : https://msdn.microsoft.com/en-us/library/windows/desktop/ms644901(v=vs.85).aspx

Related

FreeRTOS task not resuming

I'm using an ARM Cortex-M4 microcontroller to develop an application with FreeRTOS.
For exact timing, I want use an interrupt based timer. The interrupt has an appropriate priority so it should be able to call the FreeRTOS API. The ISR is called periodically and should wake up a task as in the given code:
/* This function is executed by the task I'd like to resume */
void hello_task() {
while (1) {
vTaskSuspend(task);
printf("Tick\n");
}
}
/* The ISR is called by an interrupt about 200 times per second */
void Timer_IRQHandler() {
CLEAR_INTERRUPT_FLAG();
xTaskResumeFromISR(task);
}
The ISR is executed correctly but the task doesn't resume afterwards.
Does anyone have an explaination for this behavior?
Thank you!
Read the documentation for xTaskResumeFromISR(). It tells you not to do what you are doing.
Direct to task notifications offer the best (most light weight and efficient) method of doing what you describe. There is a worked example on the following page: http://www.freertos.org/RTOS_Task_Notification_As_Counting_Semaphore.html

Integrating freeRTOS to an existing project

I'am attempting to integrate freeRTOS to my application that run on AT32UC3A0512. I downloaded a freeRTOS project example for EVK1100 (it Supports the AT32UC3A) and try to include the kernel source files, so my application hierarchy looks like :
src
|ASF
|main.c
|freertos
|freertos-7.0.0
|source
the main looks like
int main()
{
char str[5];
uint8_t num;
enable_Timer();
enable_Timer_Interrupt();
sprintf (str, %03d, num);
while(1)
{
// Wait the timer interrupt to happen
}
}
Now by just excluding the freertos folder from my project, the timer interrupt are fired and all works well,
However if i include the freertos folder (no inclusion nor call to freertos sources is done) the timer interrupt are not fired.
It seems crazy but i don't know how the behaviour of sprintf has changed this way and also i don't see the relation between sprintf and the interrupt controller
The RTOS and your application might be using the same timer interrupt. Check RTOS port.c file to find which timer is it using for timer tick. CHeck your interrupt function and port.c interrupt function definition.

Linux device driver that print periodically an information

I should write a linux device driver code that periodically print an information. This information should be printed until the module will be unloaded. I should write something like this
int boolean = 1;
static int hello_init(void)
{
while(boolean){
printk(KERN_ALERT "An information\n");
msleep(1000);
}
return 0;
}
static void hello_exit(void)
{
boolean=0;
printk(KERN_ALERT "Goodbye, cruel world\n");
}
module_init(hello_init);
module_exit(hello_exit);
Obviously, this code doesn't work (I suppose because __init and __exit can't work concurrently, so the boolean value cannot change). Can anyone help me to solve this problem?
If the task you are performing periodically needs to go to sleep, you may not be able to use timer functions. Delayed workqueues can be used in that situation -- they are not as precise as the hrtimer but if the timing requirements aren't too strict, they work just fine.
I recently posted a question about doing things periodically here:
Calling spi_write periodically in a linux driver
I posted a workqueue example in it that you may find useful.
I also found this documentation to be helpful:
http://www.makelinux.net/ldd3/chp-7-sect-6
However, some changes have been made to the API since it was published. This article outlines these changes:
http://lwn.net/Articles/211279/
You should set up a timer with hrtimer_start() at the hello_init().
The struct hrtimer *timer contains a function pointer what will be called at the time you set. That callback function should contains the printk(). You have to renew the timer each time the callback called.
Don't forget to call the hrtimer_cancel() at the hello_exit().
You can use the ktime_set() function to calculate the expire time you want. Have a look here, there are some related and useful functions: High-resolution timers

Loops/timers in C

How does one create a timer in C?
I want a piece of code to continuously fetch data from a gps parsers output.
Are there good libraries for this or should it be self written?
Simplest method available:
#include <pthread.h>
void *do_smth_periodically(void *data)
{
int interval = *(int *)data;
for (;;) {
do_smth();
usleep(interval);
}
}
int main()
{
pthread_t thread;
int interval = 5000;
pthread_create(&thread, NULL, do_smth_periodically, &interval)
...
}
On POSIX systems you can create (and catch) an alarm. Alarm is simple but set in seconds. If you need finer resolution than seconds then use setitimer.
struct itimerval tv;
tv.it_interval.tv_sec = 0;
tv.it_interval.tv_usec = 100000; // when timer expires, reset to 100ms
tv.it_value.tv_sec = 0;
tv.it_value.tv_usec = 100000; // 100 ms == 100000 us
setitimer(ITIMER_REAL, &tv, NULL);
And catch the timer on a regular interval by setting sigaction.
One doesn't "create a timer in C". There is nothing about timing or scheduling in the C standard, so how that is accomplished is left up to the Operating System.
This is probably a reasonable question for a C noob, as many languages do support things like this. Ada does, and I believe the next version of C++ will probably do so (Boost has support for it now). I'm pretty sure Java can do it too.
On linux, probably the best way would be to use pthreads. In particular, you need to call pthread_create() and pass it the address of your routine, which presumably contains a loop with a sleep() (or usleep()) call at the bottom.
Note that if you want to do something that approximates real-time scheduling, just doing a dumb usleep() isn't good enough because it won't account for the execution time of the loop itself. For those applications you will need to set up a periodic timer and wait on that.
SDL provides a cross platform timer in C.
http://www.libsdl.org/cgi/docwiki.cgi/SDL_AddTimer
If your using Windows, you can use SetTimer,else you can build a timer out of timeGetTime and _beginthreadex along with a queue of timers with callbacks
The question about a timer is quite unspecific, though there are two functions that come to my mind that will help you:
sleep() This function will cause execution to stop for a specified number of seconds. You can also use usleep and nanosleep if you want to specify the sleeptime more exactly
gettimeofday() Using this function you are able to stop between to timesteps.
See manpages for further explanation :)
If the gps data is coming from some hardware device, like over a serial port, then one thing that you may consider is changing the architecture around so that the parser kicks off the code that you are trying to run when more data is available.
It could do this through a callback function or it could send an event - the actual implementation would depend on what you have available.

Creating a simple timer application

gcc 4.4.3
vc++ 2008
I would like to make a timer application would be portable on windows and linux. However, would be suffice to start with.
My idea is to start a timer and set it for a specified number of seconds. When the time expires call a callback function.
Is that the best way to do this?
Many thanks,
There are many ways to do a timer. It is not hard but you need to think exactly what you want. If you want to call a callback, you usually use a thread that sleep until your delay is elapsed, before calling your callback. If you don't want to use a thread, you can call periodically a checker function that compute the time delta.
You api will be a function taking the delay and a function pointer plus the callback parameters. It will launch a thread that will sleep for the delay, then call the callback with the given parameters.
Check general purpose libraries, they usually have timers implemented (gtk+ glib, boost::timer I think).
my2c
Edit:
For the portability part, you have of course to write two versions of your timer function. If you use thread that means it is better to use a lib. As libs give you timers ... Use a lib :)
Windows and linux do timers differently. I suggest that you encapsulate the timing functionality into a class. You'll have to write the class twice (once for each platform) but then the rest of the program can be the same.
Alternatively you can use a toolkit where somebody else gas already done it for you. e.g. QT or Boost.
I have worked with several such timers in both C and C++. For C GTK example on the following url may be helpful http://zetcode.com/tutorials/gtktutorial/gtkevents/. In C++ I used glib timer https://developer.gnome.org/glibmm/2.34/classGlib_1_1SignalTimeout.html (although it is not precise). I also work with libev (which uses epoll() on Linux and select() on Windows) for better precision timer. For C, I present an example below
//This program is demo for using pthreads with libev.
//Try using Timeout values as large as 1.0 and as small as 0.000001
//and notice the difference in the output
//(c) 2013 enthusiasticgeek for stack overflow
//Free to distribute and improve the code. Leave credits intact
//On Ubuntu (assuming libev is installed) compile with the command - gcc -g test.c -o test -lev
#include <ev.h>
#include <stdio.h> // for printf
#include <stdlib.h>
double timeout = 1.0; //seconds
ev_timer timeout_watcher;
int timeout_count = 0;
static void timeout_cb (EV_P_ ev_timer *w, int revents) // Timer callback function
{
++timeout_count;
printf("%d\n", timeout_count);
w->repeat = timeout;
ev_timer_again(loop, &timeout_watcher); //Start the timer again.
}
int main (int argc, char** argv)
{
struct ev_loop *loop = EV_DEFAULT; //or ev_default_loop (0);
ev_timer_init (&timeout_watcher, timeout_cb, timeout, 0.); // Non repeating timer. The timer starts repeating in the timeout callback function
ev_timer_start (loop, &timeout_watcher);
// now wait for events to arrive
ev_loop(loop, 0);
return 0;
}
For more docs on libev view http://doc.dvgu.ru/devel/ev.html

Resources