Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
This snippet is intended to be the hello world equivalent for working with the raspberry pi gpio with node.js. This simply flashes an LED connected to pin 7 based on the duration.
/*
Requires:
- pi-gpio
- gpio-admin
This snippet is intended to be the hello world equivalent for working
with the raspberry pi gpio with node.js. This simply flashes an LED
connected to pin 7 based on the duration.
*/
var gpio = require("pi-gpio");
function flashLED(pin, duration) {
return setInterval(function() {
gpio.open(pin, "output", function(err) {
gpio.write(pin, 1, function() {
setTimeout(function() {
gpio.write(pin, 0, function(err) {
gpio.close(pin);
});
}, duration/2);
});
});
}, duration);
}
var intervalID = flashLED(7, 500);
setTimeout(function() {
clearInterval(intervalID);
}, 60000);
# Requires: RPi.GPIO
import RPi.GPIO as GPIO
from threading import Event, Thread, Timer
class ImprovedThread(Thread):
def __init__(self, *args, **kwargs):
super(ImprovedThread, self).__init__(*args, **kwargs)
self._stopEvent = Event()
def stop(self):
self._stopEvent.set()
def is_stopped(self):
return self._stopEvent.isSet()
def wait(self, duration):
self._stopEvent.wait(duration);
class LEDFlasher(ImprovedThread):
def __init__(self, pin, duration):
super(LEDFlasher, self).__init__(target=self._flashLED)
self.setDaemon(True)
self._pin = pin
self._duration = duration
self._state = False
GPIO.setmode(GPIO.BOARD)
GPIO.setup(self._pin, GPIO.OUT)
self.start()
def _flashLED(self):
while not self.is_stopped():
GPIO.output(self._pin, self._state)
self._state = not self._state
self.wait(self._duration/2)
flasher = LEDFlasher(7, 0.5)
Timer(60, flasher.stop).start()
flasher.join()
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment