Which timer library should i use?

Hi,
I am working on a robot project. Therefor i need different timed actions, eg. reading sensor values periodically, controlling stepper motors, but also some long-time-timings like starting a screensaver after 2h with no interaction. Which library do you recommend? For example i read in the comments at his blog that the timer library of simon monk is not capable of doing longer delays. What also would be great is a possibility of micros()-timing.
could you recommend one for my job?

My personal preference is to use timers as described in the Blink without delay demo sketch or in numerous other threads (Blink Two LEDs, independent, no delay - Programming Questions - Arduino Forum Class to simplify "blink without delay" - Programming Questions - Arduino Forum ... )

The libraries do not do any more magic than that. Oh, maybe some of them use interrupts. Let me put it this way - I've written a number of sketches that control steppers, read temperature, handle switches and lights, do Serial input, decoding of commands ... (yes, the equivalent of running an 3D printer) - all "at the same time" using no more than these timer contructs. Interrupts are only needed for very timecritical reaction on state changes. A reasonable written sketch will execute loop every 50-100 microseconds even when doing all of the above.

The classical timer library for using timed interrupts is MStimer2
http://playground.arduino.cc/Main/MsTimer2
I've used MStimer2 to set the basic scanning rate for a 5X5X5 LED cube and it worked great.

But there seems to be an updated version that allow sub-millisecond resolution while maintaining 'compatiblity' for just
replacement of MStimer2:

http://playground.arduino.cc/Main/FlexiTimer2

Don't use delayMicros( hugenumber ) because that delay is said to be rubbish for delays longer than about 16ms.
Don't use only delay( bignumber ) because the millisecond delay function ony goes up to 31 seconds.
I'd think that you want to write something using nested loops and some calls to micros() or millis() often enough to calculate the necessary delay after the measurement of the second has completed. That way your two hours does not depend on how busy the robot was with checking sensors and dodging axewielding antirobot maniacs.

I've just been testing an lcd by making a basic arduino clock, and that drifts by at least a minute per day because the 16MHz master clock is not temperature compensated. So you can't program the robot to swim up the sewers of 10 downing street and explode at 08:10:12 am next month when the VIP is expected to be sitting on the khazi. It would miss by a lot of minutes.

ad2049q:
Don't use delayMicros( hugenumber ) because that delay is said to be rubbish for delays longer than about 16ms.
Don't use only delay( bignumber ) because the millisecond delay function ony goes up to 31 seconds.
I'd think that you want to write something using nested loops and some calls to micros() or millis() often enough to calculate the necessary delay after the measurement of the second has completed. That way your two hours does not depend on how busy the robot was with checking sensors and dodging axewielding antirobot maniacs.

I've just been testing an lcd by making a basic arduino clock, and that drifts by at least a minute per day because the 16MHz master clock is not temperature compensated. So you can't program the robot to swim up the sewers of 10 downing street and explode at 08:10:12 am next month when the VIP is expected to be sitting on the khazi. It would miss by a lot of minutes.

He would have already flushed! :smiley: :smiley: :smiley:

Msquare:
My personal preference is to use timers as described in the Blink without delay demo sketch or in numerous other threads

Mine too.

If you use a library and it doesn't do what you want you just waste valuable time trying to figure out or modify the library. And some libraries conflict with other libraries because they both want to use the same Arduino resources.

I wrote an extended demo of the Blink Without Delay technique in the first post in this Thread.

...R

Hi,
I read through the Wohle thread you mentioned below and I am quite impressed;-)
Because of my poor programming knowledge and my middle-class English it's a little hard for me to figure out if there is a stable solution without time-slipping with your approach? I am using a stepper motor driver which needs one step signal for every 32th part of a step. So we are in a range of e.g 30 microseconds between every step signal. This stepping signal should stay stable, while some other things with heavy code are happening in between. Is this possible with this timing approach, or should I better use an interrupt-timer?

Mine too.

If you use a library and it doesn't do what you want you just waste valuable time trying to figure out or modify the library. And some libraries conflict with other libraries because they both want to use the same Arduino resources.

I wrote an extended demo of the Blink Without Delay technique in the first post in this Thread.

...R
[/quote]

The BWoD system in my sketch will be as good as the accuracy of the Arduino clock. (I presume you realize the technique works just as well with micros() as with millis() ).

The problem you mention of causing a step every 30 microseconds is a slightly different issue - whether other activities within the Arduino code might delay the generation of a step pulse at the correct time.

Using one of the Atmel timers to generate an interrupt may or may not solve the problem because the interrupt process itself takes some time.

A lot depends on what else the Arduino is expected to do in addition to generating the step pulses and how that other code is organized. At one extreme the Arduino might be incapable of doing everything and a faster MCU would be needed. At the other extreme there is nothing else to do and the BWoD would work just as well as using a timer to generate interrupts.

If you can get by without using interrupts your code will be much simpler and more flexible as between short and long step intervals.

Note that I am referring to the use of the Atmel on-board hardware timers - not some external Timer library. I would not expect any library to be any better than the BWoD system.

...R

thanks,

here is a sample code of my program.

void loop() {
  
 
     
 // ------------  Motor1 ------------------
  if (time1.intervalUs () > 20)
    {   
    toggleM1 = !toggleM1;
    digitalWrite(StepPinM1, toggleM1);   
    time1.reset ();
    }

... some time-consuming code here...
}

as you can see i try to use 20 Us as interval for my stepper motor. if i have time consuming code, the motor slows down extremely. can you tell me if you think it makes sense to use the interrupts of the board instead? there are different timers on the mega. can i use an other one so that it is dissolved from the rest of the code or do i come to the limits of the Mega board anyway?
i don't know a lot about these timers. when the code slows down the motor, is it a question of the whole capability of the board or just the timer which is used to execute the code?

Robin2:
The BWoD system in my sketch will be as good as the accuracy of the Arduino clock. (I presume you realize the technique works just as well with micros() as with millis() ).

The problem you mention of causing a step every 30 microseconds is a slightly different issue - whether other activities within the Arduino code might delay the generation of a step pulse at the correct time.

Using one of the Atmel timers to generate an interrupt may or may not solve the problem because the interrupt process itself takes some time.

A lot depends on what else the Arduino is expected to do in addition to generating the step pulses and how that other code is organized. At one extreme the Arduino might be incapable of doing everything and a faster MCU would be needed. At the other extreme there is nothing else to do and the BWoD would work just as well as using a timer to generate interrupts.

If you can get by without using interrupts your code will be much simpler and more flexible as between short and long step intervals.

Note that I am referring to the use of the Atmel on-board hardware timers - not some external Timer library. I would not expect any library to be any better than the BWoD system.

...R

If you think about it, if( time1.intervalUs() > 20) is likely to take longer than if(micros - prevMicros >20) if only because the code has to jump to the time1.intervalUs function.

Personally I believe your code will be faster if you use the BWoD technique.

And, if you want to cut out time wasting you need to replace digitalWrite() (and ...Read() ) with direct port manipulation using PORTx and PINx where x is the relevant Atmega I/O port. However this will mean that your code is specific to a particular Arduino board.

Note that the Atmel system has a neat trick whereby writing a bit using PINx (which is normally an input instruction) will toggle the bit with a single instruction. For example, on the Uno PIND |= B00001000; will toggle I/O pin 3.

...R

Ok, I see there are possibilities to reduce the runtime of a script;-)

It would be a great help if you could explain some basics for me so that I can decide which way would be the right for me. It seems that my motor's speed is influenced by the runtime of the code even if I take 1/2 stepping instead of 1/32 stepping, which should give 16 times more time for my code.
So I am not sure if it really helps saving a few Microseconds, if the code itself needs perhaps some millis?

So could you explain, how the processing in general works relating the timing?

E.g.:

Board Arduino Mega 2560
Pseudo code:

Program Start

Stepper 1 with Us -stepping

Stepper 2 with ms-stepping

Some millis-consuming code

Program End

Which hardware part is normally used for executing the code?
Does all limited by the processing clock of the Main Processor or is it possible to things like:

Program Start [executed as common]

Stepper 1 [executed by Timer2]

Stepper 2 [executed by Timer 3]

Program End

I didn't understand so far, how the additional timers wrk. What is the real advantage of these? Are they completely standalone or do the depend on the main processor in a way that they are also slowed down by the code?

Starting at the end of your Reply #10.

The Mega2560 has 6 hardware timers referred to as Timer0 - Timer5. If libraries uses similar names it is just coincidence.
Those timers operate from the same 16MHz clock that drives the CPU but they operate independently so they can be counting while other things are happening. There are various ways to get the output from the timers; the most common is for the timer to cause an interrupt when the value in its counter reaches some preset value. That way you can get the counter to produce an interrupt every few microseconds or at much longer intervals.

This is the process that the Arduino system uses to update the value of micros() every 4 microseconds. It is probably not practical to produce count interrupts more frequently than every 4 usecs - it would use up too much CPU time responding to them.

Consequently, as far as driving stepper motors at high step rates is concerned, there doesn't seem any advantage using any of the other 5 hardware Timers because it can only worsen the overall performance.

It is possible to get a Timer to cause an I/O pin to change directly - but this is probably not much use for stepper motors because you would still need time consuming code to keep track of the number of steps.

Producing interrupts at particular intervals is only part of the process of driving a stepper motor. Your code needs to decide what it should be doing.

One way to approach your problem may be to calculate the minimum interval (in usecs) you need between motor steps and then to think about how much code could be executed between steps.

It is an easy matter to write a short Arduino sketch to identify how long a piece of code takes. Just record the value of millis() at the start. Run the code for 1000 or 10000 iterations. Record the value of millis() at the end and work out the time for each iteration.

Short pieces of code tend to take a few microseconds, rather than milliseconds. But I think you will get the best understanding if you try out a few things for yourself. Just watch for the possibility that the compiler realizes the code in the test loop does nothing useful and just omits it - makes the performance appear very good :slight_smile: Probably best to have the code update a global variable or change the value of an I/O pin.

You describe the motors as having usec and msec timing. I wonder if this is causing confusion in your mind. In both cases the action of getting the motor to move one step is equally short. The only difference is how often they need to do that. Of course if you need to issue the step commands for the faster motor very frequently there may be no time for the Arduino to do anything else. Which brings me back to my above suggestion to calculate the minimum interval you require. Without doing any calculations my hunch is that an interval below 50usecs is going to be a challenge.

...R

Aso at a run-through speed of 50 useconds i would say that the mega board is not a good recommendation as a platform for controlling a stepper motor with microstepping, because at that speed it is not possible to get rpms more than e.g 100 rpm, and that is not SO much?

What about the time consumption of code inside an if-statetment, when its condition is not true? Is this code block also time-consuming or has it no prolonging influence on the run-through time

Hahi:
What about the time consumption of code inside an if-statetment, when its condition is not true? Is this code block also time-consuming or has it no prolonging influence on the run-through time

I don't know what was in your mind when you asked that question. It seems to lack context.

If you study the Atmega instruction set you will see that one branch of an IF takes an extra instruction (I can't remember which is which). One extra instruction (taking 0.0625 usecs) will probably be insignificant compared to the time it takes to execute the code that follows the decision.

Until you have a concrete example of the code you want to run it is impossible to know what impact it will have on timing.

My very crude guess of 50usecs was allowing for some "useful" code, but not a lot.

Perhaps your question is wondering whether the code in the unused side of an IF statement (the code for false when the condition is true, for example) uses up time. It doesn't, any more than the code on the true side takes time if the condition is false. But that leads me to wonder if there is some other unspoken idea in your mind that made you think the unused code might take time.

I suggest you write a short sketch that causes a motor to move 10 or 20 revolution and then use that as a concrete basis for further discussion.

...R

[ Message deleted – see next post. ]

Darkwing:
While this dicussion about such a topic is on,

Yours may be an interesting and useful addition to the Arduino stock of code but this is not the place to introduce it.

In this Thread the @Hahi is looking for a solution that allows very short loops to get a high step frequency for an stepper motor. Your code does not assist with that problem. And your very long post disrupts the reading of the real issues in the Thread.

I suggest you delete your post here and start a new Thread in the section Other Software Development Just leave a short post with a link to your new idea here so that @Hahi can read it separately if he is interested.

…R

Hahi:
It seems that my motor's speed is influenced by the runtime of the code even if I take 1/2 stepping instead of 1/32 stepping, which should give 16 times more time for my code.

Microstepping is fine if you want very precise positioning control or really smooth slow movement, but is not needed at high speed and will limit the speed that you can achieve. Since you seem to be running into speed issues, I suggest the very first thing you should do is stop microstepping.

Its interesting that you mentioned that. I also thought that microstepping is just for smoothiness of slow speeds. But i came to the point where i realized that the loudness of the sinus-tone that ths stepper produces is much less at microstepping and increases the volume at lower step-rates. Can you confirm that with your experience?

A stepper motor takes sharp steps a 200th-of-a-circle (for a typical motor). That's why it is called a stepper motor. :slight_smile:

Anything that makes regular vibrating motion (which is what your machine will do when the stepper steps) has a few frequencies where the machine (or parts of it) resonate and amplify the noise and the vibrations. That is the way mechanics and physics works. The frequency at which this happens varies with the mechanical construction it drives.

One engineering trickery is to make the steps less abrupt. The average steppermotor controller has therefore Microstepping which uses in-between values of the coils (which in full mode are fully on one way or the other). It also enables stopping "halfway" (or 32nd of a step) between the normal step positions. Like all trickery it comes at a price - in this case the microcontroller needs to geenerate step-pulses at 32 times the rate.

You can also mount the stepper motor with various rubber/vibration isolation mounts, and how the turning motion is connected to your machinery.

Msquare:
A stepper motor takes sharp steps a 200th-of-a-circle (for a typical motor). That's why it is called a stepper motor. :slight_smile:

Anything that makes regular vibrating motion (which is what your machine will do when the stepper steps) has a few frequencies where the machine (or parts of it) resonate and amplify the noise and the vibrations. That is the way mechanics and physics works. The frequency at which this happens varies with the mechanical construction it drives.

One engineering trickery is to make the steps less abrupt. The average steppermotor controller has therefore Microstepping which uses in-between values of the coils (which in full mode are fully on one way or the other). It also enables stopping "halfway" (or 32nd of a step) between the normal step positions. Like all trickery it comes at a price - in this case the microcontroller needs to geenerate step-pulses at 32 times the rate.

You can also mount the stepper motor with various rubber/vibration isolation mounts, and how the turning motion is connected to your machinery.

Increasing the frequency of the 'steps' would also increase the frequency of any vibration, sometimes taking it above the normal range of human hearing. It's still vibrating, but now you can't hear it! :slight_smile: