/*----------------------------------------------------------------------------* * NAME * dutyCycleTask * * DESCRIPTION * This is the function called when the timer expires. * * Creates a timer for updating the duty cycle on the PWM1. The ramping * effect is produced on the PWM1 by updating its duty cycle periodically * while maintaining constant frequency. * * The PWM1 is configured for its duty cycle from this timer call-back. The * duty cycle is updated from 0% to 100% and then down to 0% and so on. * * PARAMETERS * tid Id of the timer that has just expired. It is not used. * * RETURNS/MODIFIES * None *----------------------------------------------------------------------------*/ static void dutyCycleTask( timer_id const tid ) { static uint8 on_ticks = 0U; static int8 increment_value = 1U; /* Hold the value by which ON time is incremented. When duty cycle is increasing it holds possitive value. When duty cycle is decreasing it holds negative value */ /* Configure the PWM1 to produce a fixed frequency signal, with the same * duty cycle for both the dullest and brightest parts. */ setPwmDutyCycle(on_ticks); if ( on_ticks >= NUMBER_OF_STEPS ) /* When ON time reaches its maximum (i.e. 100% duty cycle) * it should be decremented until it reaches minimum (i.e. 0%) */ { increment_value = -1; } else if ( on_ticks <= 0U ) /* When ON time reaches its minimum (i.e. 0% duty cycle) * it should be incremented until it reaches maximum (i.e. 100%) */ { increment_value = 1; } /* Update ON time for the next update */ on_ticks += increment_value; /* Re-start the timer */ TimerCreate(DUTY_CYCLE_STEP_TIME, TRUE, dutyCycleTask); }
void analogWrite(uint8_t pin, int16_t val) { uint8_t timer = 0xff; setPinMode(pin, OUTPUT); if ((val == 0) || (val <0)) { digitalWrite(pin, LOW); } else if ((val > 255) || (val == 255)) { digitalWrite(pin, HIGH); } else { timer = digitalPinToTimer(pin); initPwm(timer); setPwmDutyCycle((uint8_t)val, timer); } }