This post is for the lucky owners of the BerryClip 6 LED add on board and is the first of a series of posts to get you started with an alternative to Python.
This article covers using C, but there will be future posts for using the BerryClip directly from Scratch and also using the node.js javascript language.
The easiest way to do this in C, is to use the very popular wiringPi C library developed by Gordon Henderson, aka drogon.
The code is available from BitBucket or by cutting and pasting the text below into a file called test1.c :
#include <wiringPi.h> #include <stdlib.h> int leds[6] = { 7, 0, 3, 12, 13, 14 }; int BUZZER = 10; int BUTTON = 11; void all_leds_off(); void init_pins(); int main (void) { //Check we have wiringPi if (wiringPiSetup () == -1 ) exit (1); init_pins(); all_leds_off(); for (;;) { if (digitalRead (BUTTON) == 1 ) { for (int i = 0; i < 6; i++) { digitalWrite (BUZZER,1); digitalWrite (leds[i],1); delay (50); digitalWrite (BUZZER,0); delay (450); } delay (1000); all_leds_off(); } delay(50); } exit(0); } void init_pins() { //set leds as outputs... for (int i = 0; i < 6; i++) { pinMode(leds[i], OUTPUT); } // set buzzer as output... pinMode(BUZZER, OUTPUT); // set button as an input... pinMode(BUTTON, INPUT); } void all_leds_off() { for (int i = 0; i < 6; i++) { digitalWrite (leds[i],0); } }
You will need wiringPi, so please pop over to Gordon’s site to learn how to install wiringPi.
You may notice the pin numbers used in the above example are different to those used in the Python examples. This is due to wiringPi having it’s own pin numbering system. See Gordon’s pin page for clarification.
To compile test1.c please create a file called Makefile in the same directory as test1.c with the following contents:
DEBUG = -O3 CC = gcc INCLUDE = -I/usr/local/include CFLAGS = $(DEBUG) -Wall -std=c99 $(INCLUDE) -Winline -pipe LDFLAGS = -L/usr/local/lib LIBS = -lwiringPi OBJ = test1.o BINS = test1 test1: test1.o @echo [link] $(CC) -o $@ test1.o $(LDFLAGS) $(LIBS) .c.o: @echo [CC] $< @$(CC) -c $(CFLAGS) $< -o $@ clean: rm -f $(OBJ) *~ test1
In the same directory type
make
To run the program, type
sudo ./test1
Enjoy C, or watch for my next post – if I get a language request in the comments, then I’ll be happy to get the Berry Clip to learn another language in a subsequent post.
2 Comments
The #include statements look a bit strange!
Leo
Should be corrected now!