0

I need to analogread every 4ms, but I tested my code reading the execution time and it printed this:

enter image description here

it's not 4ms, my code:

#include <time.h>

clock_t start,end;
double tempo;

     for(i=1; i <= 20; i++) {
           start=clock();
           x = analogRead (BASE + chan);
           printf("%d\n", x);
           delay(4);
           end=clock();
    tempo=((double)(end-start))/CLOCKS_PER_SEC;
    printf("%f \n", tempo);
    } 
Emperon
  • 91
  • 8
  • Where is the question ? – Tony Tannous Aug 05 '17 at 15:35
  • every value I put inside delay the time printed is always the same. It's not 4ms – Emperon Aug 05 '17 at 15:36
  • I need to be sure I'm sampling at 256hz – Emperon Aug 05 '17 at 15:37
  • 1
    What does the documentation say about the argument to the `delay` function? – user3386109 Aug 05 '17 at 15:46
  • the documentation says delay(1000) is 1 second, so for 4ms I put delay(4). But I used also sleep() function, same problem. – Emperon Aug 05 '17 at 15:51
  • 4
    I just tried a simple experiment: `for(int i=0;i<10;i++){printf("%lu\n",clock()); sleep(1);}` I expected to see the values increase by 1 million since `CLOCKS_PER_SEC` is 1 million. That didn't happen. Then I checked the man page, which says, "The clock() function determines the amount of **processor time**..." The code doesn't use much **processor time** because it's sleeping most of the time. See [this post](https://stackoverflow.com/questions/3523442/difference-between-clock-realtime-and-clock-monotonic) for some useful hints. – user3386109 Aug 05 '17 at 16:03
  • so what function would you use to check if the 4ms is set right? – Emperon Aug 05 '17 at 16:15
  • No functions will help you. It is not achievable. @Emperon – 0___________ Aug 05 '17 at 17:09
  • the posted code does not compile. It is not even a complete function. The question is about a runtime problem, so the code needs to be complete – user3629249 Aug 07 '17 at 01:56
  • Suggest using an interrupt function, driven by one of the hardware timers – user3629249 Aug 07 '17 at 02:01
  • you might want to read [timers](https://www.raspberrypi.org/forums/viewtopic.php?f=33&t=50757)\ – user3629249 Aug 07 '17 at 02:03

1 Answers1

0

It does not matter what function you use as the Linux is not a RTOS, so you can actually forget about real time functionality unless you patch the kernel with PREEMPT_RT. There is a lots of information about this topic online.

This is to complex topic for a SO answer but I hope that I will point you into a right direction.

0___________
  • 60,014
  • 4
  • 34
  • 74