Blinking Lights With GPIO

In my last post we looked at a basic query of the GPIO bus just to show that we could read it. This time I want to actually control something. Blinking a light is the IoT equivalent of Hello World, so we’ll try that. In this setup, the anode (short lead) of the LED is connected to pin 19 by a smaller resistor, and the cathode (long lead) is connected to the 3v ground bar.

Design

libgpio has two new functions we haven’t seen so far: ‘‘gpio_pin_high’’ and ‘‘gpio_pin_low’’ which alternately set the pin to high voltage (on) and low voltage (off). If you aren’t familiar with logic circuits, high and low are used instead of on or off, because there is in fact always a little bit of voltage even in the nominally off condition.

We’re also using a bit of argument processing to control the length of time the light circuit spends in the high position and the low position. There’s nothing magical about this, but if you want to learn more you should look at getopt man page.

The Code

#include <inttypes.h>
#include <libgpio.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

gpio_handle_t handle = -1;
int pin = 19;

int main(int argc, char **argv)
{
	int low_time = 1;
	int high_time = 1;
	int ch;

	while((ch = getopt(argc, argv, "h:l:")) != -1) {
		switch(ch) {
		case 'h':
			high_time = strtol(optarg, NULL, 10);
			break;
		case 'l':
			low_time = strtol(optarg, NULL, 10);
			break;
		case '?':
		default:
			fprintf(stderr, "%s [-l low_time -h high_time]\n",
				argv[0]);
			return EXIT_FAILURE;
		}
	}

	handle = gpio_open(0);
	if (-1 == handle) {
		perror("gpio");
		return EXIT_FAILURE;
	}
	gpio_pin_output(handle, pin);
	while(1) {
		gpio_pin_high(handle, pin);
		sleep(high_time);
		gpio_pin_low(handle, pin);
		sleep(low_time);
	}

	return EXIT_SUCCESS;
}

There are a few items worth noting:

Comments

comments powered by Disqus