AnalogWrite

From Pinguino
Jump to: navigation, search

Name

analogWrite - Send a Pulse Width Modulated signal to a pin

Description

Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightness or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite(), or a call to digitalRead(), or digitalWrite() on the same pin. Only the duty cycle can be varied, if the frequency needs to be adjusted, use the PWM Library calls.

You do not need to call pinMode() to set the pin as an output before calling analogWrite().
The analogWrite function has nothing to do with the analog pins (AD converter) or the analogRead function.
The frequency of the PWM signal is fixed and may not be adjusted.

Output Pins
PIC18F2550 - pin 11 and 12 can be both or individually used.
PIC18F47J53 - can be used with pin 4, 5, 6, 7, 17, 22 or 23.
PIC18F4550 - can be used with pin 11, 12
PIC32 OlimexMicro - IDE pin 10, 11, 12
Measured Frequency
PIC32 OlimexMicro - 170khz


Pulse Width Modulation 8bit 0-255, 16bit 0-1023

Syntax

analogWrite(pin, ratio)
pin
PIC18F2550 - type u8 pin 11, 12
PIC32 OlimexMicro - IDE pin 10, 11, 12
ratio
type u16, value 0-1023
Output
none

Example 1

Also see this PWM Example

/* +---------------------------------------------------------------------+
   | analogWrite_test.pde         by Jan Zumwalt      rev 2015.12.17     |
   +---------------------------------------------------------------------+
   | Copyright: COPYRIGHT by Jan Zumwalt                                 |
   |            Licensed under the GNU public license.                   |
   | Build    : Olimex Pic32 Micro dev brd w/Pinguino.cc IDE (V11)       |
   | Purpose  : This fades the yellow LED using pulse width modulation.  |
   +---------------------------------------------------------------------+  */


u8 ledPin = 10;    // LED connected to IDE pin 10 
u16 fadeValue;

void setup()  { 
    // nothing to do 
    // pinMode is not needed
} 

void loop() {

    for (fadeValue = 1 ; fadeValue < 1023; fadeValue++) { // slowly turn led on
        analogWrite(ledPin, fadeValue);           
        delay(1);                            
    }

    for (fadeValue = 1023; fadeValue > 1; fadeValue--) { // slowly turn led off
        analogWrite(ledPin, fadeValue);            
        delay(1);                            
    }
}

Bugs

See Also

analogWrite
analogRead

digitalWrite
digitalRead

PWM.setPercentDutyCycle
PWM.setDutyCycle
PWM.setFrequency

Comments

ratio type has been changed from 10 bit u16 to 8 bits u8 on x.4 release

PinMode() does not have to be set to use analaogWrite