Application notes

Accessing GPIO on Raspberry Pi or Linux.

The problem

The GPIO or “General-purpose I/O” pins are a low-level hardware feature of some chipsets, and are often used to interface with external hardware.

The 8th solution

Depending on your system’s settings, you probably will need “root” access to manipulate the GPIO pins. So first, make sure you’ve got the correct access. You might choose to run as “root” using sudo or the like, or you may choose to adjust the access rights to the GPIO subsystem files.

The actual 8th code for the GPIO sample follows:

\ Toggle the GPIO pin #18 on an RPI twice a second for three seconds:

\ tell the system we want to use that pin to write.  Store the 'hw' returned in
\ the variable 'gp':

18 false hw:gpio var, gp

\ Sets the pin to the value, and then sleep a tenth of a second:

: set'n'sleep \ pin value --
  hw:gpio! 0.1 sleep ;

\ Toggles the pin on and off:

: toggle \ -- 
  "Toggle....\n" .
  gp @ 
  0 set'n'sleep
  1 set'n'sleep drop ;

\ see if we can run:
: ok?
  os 5 n:= not if 
    "Sorry, this only runs on Raspberry Pi" throw 
  then ;
\ do our thing: toggle on and off 10 times:
ok? ' toggle 10 times 

\ reset the pin to off, and quit:
gp @ 0 hw:gpio!  bye

This sample is very simple. All it does is toggle GPIO pin 18 and sleep for a tenth of a second. The relevant word to write to the GPIO pin is hw:gpio!, which is given the pin number and a 0 for ‘off’ nad a 1 for ‘on’.

Learn more

To find out more about 8th and how it can help meet your application development needs, please refer to the manual, browse this site or the 8th forum, or contact us.