digitalWrite vs. analogWrite

The digital pins have only two modes – ON (1) or OFF (0). We use the constants HIGH (on) and LOW (off) since this makes it easier to read code. Digital pin always gives the output power of 5V when HIGH and 0V when LOW. The pin need to be configured with pinMode( ).

digitalWrite(pin,value)  //  sets ‘pin’ to value (LOW or HIGH)

Example: blinking LED

int led = 13;

void setup() {         
pinMode(led, OUTPUT);       // digital pin as an output

void loop() {
digitalWrite(led, HIGH);        // turn the LED on 
delay(1000);                           // wait for a second
digitalWrite(led, LOW);        // turn the LED off by making the voltage LOW
delay(1000);                           // wait for a second

The pigital pins 3, 5, 6, 9, 10 and 11 have a special function called PWM (). For these pins we are using the command analogWrite( ). With the PWM mode we can transform the 5V output into a range of 255 possible levels. Instead of going from 0V to 5V in one instance it goes from 0V to 5V in 255 steps.

analogWrite(pin,value);        //   writes ‘value’ to analog ‘pin’                                     //    value = between 0 (off) and 255 (on)

A value of 0 generates a steady 0 volts output at the specified pin; a value of 255 generates a steady 5 volts output at the specified pin. For values in between 0 and 255, the pin rapidly alternates between 0 and 5 volts – the higher the value, the more often the pin is HIGH (5 volts). For example, a value of 64 will be 0 volts three-quarters of the time, and 5 volts one quarter of the time; a value of 128 will be at 0 half the time; and a value of 192 will be 0 volts one quarter of the time and 5 volts three-quarters of the time.


Example: changing colour on RGB led with potentiometer

const int sensorPin = A0;          // select the input pin for the potentiometer
const int REDPin = 11;             // select the pin for the LED
const int BLUEPin = 10;
const int GREENPin = 9;

int sensorValue = 0;       
int outputValue = 0;

void setup() {
pinMode(REDPin, OUTPUT);
pinMode(BLUEPin, OUTPUT);
pinMode(GREENPin, OUTPUT);


void loop() {
int sensorValue = analogRead(A0);

outputValue = map(sensorValue, 0, 1023, 0, 255);

outputValue = map(sensorValue, 1023, 0, 0, 255);

outputValue = map(sensorValue, 0, 1023, 0, 255);

Serial.println(sensorValue);          // print out the value you read:
delay(1);                                         // delay in between reads for stability



Leave a Reply