﻿ width Property

# width Property

Top  Previous  Next

An array that gets or sets the pulse width for each PWM channel.

## Syntax

Cell.PWM[n].width[channel]

## Property Value

A pulse width value that sets duty cycle/pulse width of the PWM channel.

## Remarks

The pulse width value ranges from zero to the value of the max property. A duty cycle of 100% is achieved when the width element is assigned the value max. The value to use for pulse width for any duty cycle in the range 0 - 100% can be computed as follows:

Cell.PWM[n].width[channel] = duty / 100 * Cell.PWM[n].max;

where duty has been assigned the duty cycle, channel is in the range 0 - 3, and n is 0 or 1.

In some applications it is useful to set the PWM pulse width to a specific duration instead of using duty cycle. The value to use for pulse width given a duration in fractional seconds can be computed as follows:

Cell.PWM[n].width[channel] = duration * Cell.PWM[n].resolution;

where duration has been assigned the pulse width in fractional seconds, channel is in the range 0 - 3, and n is 0 or 1.

## Examples

There are two examples below. Both read the analog value on pin A0 to set the pulse width of a PWM channel. The Cell Development Kit has a potentiometer on pin A0, so these examples allow that potentiometer to control the PWM output.

This example controls power level to a light or motor. The duty cycle is allowed to vary over the entire 0 - 100% range.

var val;

Cell.PWM.frequency = 4000;

for (;;)

{

val = Cell.ADC.convert(0) / Cell.ADC.max;  // 0 - 1 range

Cell.PWM.width = val * Cell.PWM.max;

}

This example controls an R/C servo. Servos require a pulse width of 1 ms to 2 ms repeated at 30 Hz - 60 Hz. The servo position is proportional to the where the pulse width falls within the 1 - 2 ms range.

var val, ms;

Cell.PWM.frequency = 60;

ms = Cell.PWM.resolution * 0.001;  // one millisecond

for (;;)

{

val = Cell.ADC.convert(0) / Cell.ADC.max;  // 0 - 1 range

Cell.PWM.width = (val + 1) * ms;

}