Skip to content

Latest commit

 

History

History
167 lines (112 loc) · 3.29 KB

1.1.3_led_bar_graph_js.rst

File metadata and controls

167 lines (112 loc) · 3.29 KB

1.1.3 LED Bar Graph

Introduction

In this project, we sequentially illuminate the lights on the LED Bar Graph.

Components

image

Schematic Diagram

image

Experimental Procedures

Step 1: Build the circuit.

Note

Pay attention to the direction when connecting. If you connect it backwards, it will not light up.

image

Step 2: Go to the folder of the code.

cd ~/davinci-kit-for-raspberry-pi/nodejs/ 

Step 3: Compile the code.

sudo node led_bar_graph.js

After the code runs, you will see the LEDs on the LED bar turn on and off regularly.

Code

const Gpio = require('pigpio').Gpio;

var pins = [17, 18, 27, 22, 23, 24, 25, 2, 3, 8];
var leds = [];
for (let i = 0; i < pins.length; i++) {
    leds[i] = new Gpio(pins[i], { mode: Gpio.OUTPUT });
}

function oddLedBarGraph() {
    for (let i = 0; i < leds.length; i++) {
        if (i % 2 == 1) {
            leds[i].digitalWrite(1);
        } else {
            leds[i].digitalWrite(0);
        }
    }
}

function evenLedBarGraph() {
    for (let i = 0; i < leds.length; i++) {
        if (i % 2 == 0) {
            leds[i].digitalWrite(1);
        } else {
            leds[i].digitalWrite(0);
        }
    };
}

var odd_even = 0;

setInterval(() => {
    odd_even = (odd_even + 1) % 2;
    if (odd_even == 1) {
        oddLedBarGraph();
    } else {
        evenLedBarGraph();
    }
}, 500);

Code Explanation

var pins = [17,18,27,22,23,24,25,2,3,8];

Because the led bar graph will use multiple pins, we create a constant array pins to store them in batches.

var leds = [];
for (let i = 0; i < pins.length; i++) {
    leds[i] = new Gpio(pins[i], { mode: Gpio.OUTPUT });
}

Instantiate these pins as leds objects with a for loop.

function oddLedBarGraph() {
    for (let i = 0; i < leds.length; i++) {
        if (i % 2 == 1) {
            leds[i].digitalWrite(1);
        } else {
            leds[i].digitalWrite(0);
        }
    }
}

Implement an oddLedBarGraph() function to make the LEDs on the odd digits of the LED bar graph light up.

function evenLedBarGraph() {
    for (let i = 0; i < leds.length; i++) {
        if (i % 2 == 0) {
            leds[i].digitalWrite(1);
        } else {
            leds[i].digitalWrite(0);
        }
    };
}

Implement an evenLedBarGraph() function to make the LEDs on the even digits of the LED bar graph light up.

var odd_even = 0;

setInterval(() => {
    odd_even = (odd_even + 1) % 2;
    if (odd_even == 1) {
        oddLedBarGraph();
    } else {
        evenLedBarGraph();
    }
}, 500);

The working state of the LED is switched every 500ms.

Phenomenon Picture

image