10 years ago.

Tickers: using variables for interval?

I'm using the LPC1768 and trying to write a program that will take any given time period and divide it up into equal steps of PwmOut. I want it to ramp up and then down again linearly. Is there a way to make the ticker take variables for an interval? Or do I need to do this some other way?

This is what I have, and it does not work!

Ticker Trouble

#include "mbed.h"


Serial pc(USBTX, USBRX); //tx rx debug

PwmOut pulse(p26);
Ticker u;
Ticker d;

int p, w;   //period, pulsewidth keep in micro seconds
int t;      //time pwm on in seconds
int x;      //number of steps one way (up or down)
int step;   //step size. micro seconds
int max;    //max pwidth desired


void up(){
    w = w + step;
    }
    
void down(){
    w = w - step;
    }
    
int step_size(int max, int x){
    step = max / x;  // step size
    return step;
    }
    
int step_time(int t, int x){
      t = (t * 1000000); // seconds to micro seconds
      t = t / 2;
      int times = (t / x);
      return times;     //time between steps
      }
    

int main(){
    
    
    t = 0.5;    // half a second on
    x = 10;      // steps each way
    max = 500;
    
    step = step_size(max, x);
    
    int time = step_time(t, x);
    p = 1000;
    w = 0;
    
    while(1){
        
        DigitalIn enable(p5);
        
        if (enable == 0){
            pulse = 0.5;
            
            while(w <= max){
                u.attach_us(&up, time);  
                pulse.period_us(p);
                pulse.pulsewidth_us(w);  
                u.detach();
            }
            while(w > 0){
                d.attach_us(&down, time);
                pulse.period_us(p);
                pulse.pulsewidth_us(w);
                d.detach();
                }
            
            if (enable == 1){
                pulse = 0;  //no pwm
                }
    
    }
}
    
       }

1 Answer

10 years ago.

It looks like you detach your ticker before it has a chance to activate. Put the attach before the while loop. Put the detach after the end of the loop not inside it. You can also put the period_us command before the loop.

And to stop it getting called several thousand times more than needed put the pulsewidth command inside the interrupt routine rather than in the loop. You end up with an empty while loop but that's ok.

Finally w should be declared as volatile e.g.

volatile int w;

Without that the main code may not notice that the value has changed in the interrupt code.

This is a general rule, any variable that is modified by an interrupt (including in a timer) and also used in the main code should be volatile, otherwise compiler optimizations could break things.

Accepted Answer