Arduino Software PWM without library

Sometimes you want your code to be as independent as possible. Arduinos have a hardware PWM-function, but not on every pin. For instance, on the (awesome!) Seeedstudio Grove Beginner Kit, both onboard LEDs (pin 13 and 4) are on pins that don’t have hardware PWM. There is a library to do software PWM, but sometimes you don’t want to use a library (e.g. extra overhead).

Here is an example that simulates PWM using only Arduino native functions:

/*
Analog Input

Demonstrates analog input by reading an analog sensor on analog pin 0 and
turning on and off a light emitting diode(LED) connected to digital pin 13.
The amount of time the LED will be on and off depends on the value obtained
by analogRead().

The circuit:

  • potentiometer
    center pin of the potentiometer to the analog input 0
    one side pin (either one) to ground
    the other side pin to +5V
  • LED
    anode (long leg) attached to digital output 13
    cathode (short leg) attached to ground
  • Note: because most Arduinos have a built-in LED attached to pin 13 on the
    board, the LED is optional. created by David Cuartielles
    modified 30 Aug 2011
    By Tom Igoe This example code is in the public domain. http://www.arduino.cc/en/Tutorial/AnalogInput
    */

int sensorPin = A0; // select the input pin for the potentiometer
int ledPin = 4; // select the pin for the LED
float sensorValue = 0; // variable to store the value coming from the sensor

void setup() {
// declare the ledPin as an OUTPUT:
pinMode(ledPin, OUTPUT);

}

void loop() {
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
// turn the ledPin on
digitalWrite(ledPin, HIGH);
// stop the program for microseconds:
delayMicroseconds(sensorValue);
// turn the ledPin off:
digitalWrite(ledPin, LOW);
// stop the program for for microseconds:
delayMicroseconds(1024-sensorValue);
}

Leave a Reply

Your email address will not be published. Required fields are marked *