User avatar
Z80 Refugee
Posts: 358
Joined: Sun Feb 09, 2014 1:53 pm

Accessing GPIO I/O Pins from Forth, and How to Use Them

Sun Mar 11, 2018 3:14 pm

. . . . .

NB: This article has been written and developed over a significant period of time, with a number of errors and incorrect assumptions corrected when discovered, and new content added. If you haven't looked at it for a while, but aim to try these things out, it would be as well to review the latest version.

Last significant update (not minor corrections or adjustments of presentation): 21/05/2018


. . . . .

Introduction

This article is for people familiar with the Forth programming language but unfamiliar with using a Raspberry Pi, or people familiar with using the RPi but who might like to explore Forth for the first time. It is probably not for people unfamiliar with either the RPi or Forth, who may be better off with another introduction to the RPi and programming, but nonetheless, by following the instructions exactly, even a complete novice should (hopefully) succeed.

Forth as a programming language is closely coupled to the computer hardware it runs on, and is therefore very useful for "physical computing" (the control of hardware mechanisms such as lights, motors, switches etc). Forth is interpreted rather than compiled, so anything you can do in a program file can also be done directly on the command line - and program development provides instant gratification because you test in small steps as you develop the program. But beware: Forth makes you think for yourself instead of relying on sophisticated compilers to do all the heavy lifting.

The Raspberry Pi (RPi) is a small, cheap, single-board computer highly suited to (and originally designed for) experimenting with physical computing. As well as providing sufficient processor power and system resources to run complete personal-computer desktop operating systems and office suites, it has connections that can be used for operating external circuits under program control.

The following provides step-by-step instructions for installing an operating system on a Raspberry Pi, accessing a text command line, installing a version of the Forth programming language, and (as a demonstration) using Forth to turn a LED connected to the RPi's input-output header (known as the GPIO - General Purpose Input/Output) on and off. The hobbyist can then extend that to controlling motors, getting sensor input, building robots...

Tips for simple hardware interfacing to the GPIO are included at the end of the article under "Hardware Interfacing", for those unfamiliar with hooking up external circuits to their RPi.

A video demonstrating the instructions in this article has been posted on YouTube here (credit Peter Forth): https://youtube.com/watch?v=UBJegHVCPQQ

I'm sure this is not the only way of getting a Forth environment, it may not be the best way, and there are definitely other languages and programming environments that can flash a LED - but it works as a proof of concept if you are interested in using Forth, particularly if this is your first experience of using a Raspberry Pi.


. . . . .

Preface

As a novice rpi-er but (in a past life) a dabbler in Forth on Win3.1/98 (Win98 was the last version that actually lets you get at the hardware so I could use the printer port pins for I/O), the sorts of things I want to do with an RPi are hardware related, and Forth is great for instant-gratification lighting LEDs and moving motors.

As a novice, though, I was dismayed how little information there was on-line about how to set up a Forth environment and get it controlling the GPIO. What there was seemed to assume a level of knowledge I didn't have, so here are detailed instructions, explained simply, for anyone who wants to follow my footsteps. Comments from more experienced users (or followers who could or couldn't make it work) welcome and if there's anything I could have done better let me know. I have developed the article over the passage of some time, and incorporated comments where appropriate - thanks to all who have contributed.

The RPi I am using is "Model B+ V1.2"* with an 8GB micro-SD card (only 2GB required for Raspbian Lite).

* These instructions have been verified to work on Raspberry Pi models: A+, B+, 2B+, 3B


Step 1 - Operating System

I wanted this to be headless* (ie no screen & keyboard required). It's not great to have an RPi controlling some hardware on a workbench but needing extra stuff in support! And neither did I want to be forced to connect a keyboard/monitor at any stage in the process. So, from raspberrypi.org I downloaded Raspbian Stretch** Lite to my Windows PC:

https://downloads.raspberrypi.org/raspbian_lite_latest ***

The product is a .zip containing a disk image that needs to be burned to the SD card. This does not just mean unzipping to the SD, a proper image writer is needed. My existing ISO burner wouldn't hack writing to an SD, so the solution was to download Etcher (available as both an installer and a no-install exe for Windows - I prefer the no-install, but run it with administrator privileges):

https://www.raspberrypi-spy.co.uk/2016/ ... linux-mac/

This is capable of reading the image source without unzipping the file first (excellent!). If your PC has an SD card slot you will need a micro-SD adapter, or if not you will need a USB-SD adapter.

The product is the micro-SD card with the necessary boot image to start up the RPi. However, by default this will not start headless, so it needs to be configured to enable a network terminal session.

The SD now has a 40MB FAT32 section and the remainder an Ext3/4 section, the (Windows) PC will not "see" the Ext3/4 section at all. However, in the section you can see on the PC, create an empty file called "ssh" (at the top directory level). This is a flag which tells the RPi boot process to configure for SSH login over the network (and once actioned the flag file is deleted, so don't be surprised if you can't find the ssh file afterwards).

Install the micro-SD in the RPi, connect power, and it should boot. Connect by Ethernet to your home network for headless access to the command line and for Internet access to continue the setting up.

As there is nothing to see and therefore give confidence that the RPi has booted properly for the first time, it is probably worth hooking up a TV by HDMI just to see the boot happening. Note that Raspbian Lite does not boot to a desktop, only a command prompt.

* There's no reason the below won't work if you choose to use a screen and keyboard instead of a remote terminal session.

** "Stretch" is simply the designation of the latest version of Raspbian available at the time of writing, and the version used to develop these instructions.

*** Alternatively, install the full-fat Raspbian (which boots to a full home-computer environment with on-screen desktop icons for word processing etc etc) instead of Raspbian Lite (which doesn't), but is a much larger download (1.7GB v 350MB) and much larger image on the SD card. For options see https://www.raspberrypi.org/downloads/raspbian/


Step 2 - Headless* Access to a Command Prompt

* You do not need to do this if you are using the keyboard+screen command line or a command terminal on the full-fat Raspbian desktop. "Headless Access" means accessing the command line using a remote terminal via a network connection.

For a Windows PC download the portable version of PuTTY:

Windows: https://portableapps.com/apps/internet/putty_portable

...or for iPad:

iOS: As the app I use - vSSH - seems not to be available any more, type "ssh terminal" in the App Store search and take your pick. Many of the free ones seem to be crippled by advertising, so you may want to just sample the free version and then upgrade to the paid one. If you find a good one, let me know!

Access your router settings to find out what IP address has been allocated to the RPi (most likely 192.168.?.?). Use that address as the address in your SSH client to connect to the RPi on your home network, and it should ask for a login. The default login is:

User ID: pi
Password: raspberry

(You will be pestered to change the password, as the default user name and password is well known and therefore insecure! Change the password to suit yourself.)

At this point you should have a command prompt.

(I realise that SSH is more secure, but for this kind of mucking about normal Telnet is perfectly OK and more accessible, with a built-in client in Windows etc. However, the above instructions set things up for SSH not Telnet, so one trades the inconvenience of downloading an SSH client to use on a PC or iPad (or whatever) for the convenience of not having to set up a Telnet server on the RPi.)


Step 3 - Installing gForth

These instructions are adapted from Kris Johnson's Blog.

If you are running from a Raspbian desktop: open a command terminal - probably Ctrl+Alt+T or Alt+F2, otherwise select Terminal from the menus.

Install gForth:

Code: Select all

sudo apt-get install gforth
We are now in a position to "play" with Forth (without access to I/O at this stage). Leo Brodie's useful Forth primer (with code examples) is available to view on-line or download as PDF (free for personal use) here:

https://www.forth.com/starting-forth/ (I bought the printed book decades ago - no Internet freebies in those days!)

However, just as a test: push two numbers onto the stack, add them (replacing the input values on the stack with the result), and output the value at the top of the stack. Note there is no Forth command line prompt - rather disconcertingly you will be presented with a blank line after the "gforth" command, and the response to a Forth command is on the same line:

Code: Select all

gforth
3 4 + .
...should yeild

Code: Select all

7 ok
Type "bye" to exit from gForth and return to the Raspbian command line.


Step 4 - Configuring gForth for GPIO Access

Install libraries:

Code: Select all

sudo apt-get install libtool-bin

sudo apt-get install wiringpi
(Some of these installs may not be necessary for the full-fat Raspbian - but they won't hurt.)

...and fetch Kris Johnson's Forth definitions:

Code: Select all

sudo apt-get install git-core

git clone https://github.com/kristopherjohnson/wiringPi_gforth.git

cp wiringPi_gforth/wiringPi.fs .
And that's it, you're all set and ready to go.

Steps 3 & 4 - installing and configuring gForth - can be streamlined as follows (compressing the instructions above into three lines), courtesy scruss:

Code: Select all

sudo apt install gforth libtool-bin wiringpi git-core
git clone https://github.com/kristopherjohnson/wiringPi_gforth.git
cp wiringPi_gforth/wiringPi.fs .

Step 5 - Testing

For my test, I wired a light emitting diode (LED) with a series resistor, positive lead to GPIO17 (connector pin 11) and negative lead to 0V (eg pin 6 or pin 9).

Getting the wiring wrong is the only way you might damage your RPi, so make sure you either know exactly what you are doing, or follow these instructions to the letter. It's not hard though, and even something as simple as making a LED flash from your own program for the first time is very satisfying! The ins and outs of wiring circuits to the GPIO are too long to discuss here, so for more information see the Hardware Interfacing section at the end of this article.

To initiate a Forth session with the GPIO control definitions pre-loaded:

Code: Select all

gforth wiringPi.fs
We need to initialise the GPIO, and then empty the returned status off the stack (note that gForth is not case sensitive, so the use of capitals is not critical except when referring to external resources such as calling in wiringPi.fs):

Code: Select all

wiringPiSetupGpio drop
Define GPIO17 as the pin the LED is connected to, and set it for output:

Code: Select all

17 constant ledPin

ledPin OUTPUT pinMode
Define a couple of verbs to turn the LED on and off (":" begins a definition, followed by the name of the definition and then the code itself, terminated by ";"):

Code: Select all

: ledOn ledPin HIGH digitalWrite ;

: ledOff ledPin LOW digitalWrite ;
Now you should be able to type "ledOn" to light it up, and "ledOff" to extinguish it again. If this does not work, and no other reason can be found (errors in following the above instructions, or the LED not wired properly), see notes about Using Root Privilege below.

It is also possible to read back the state of the GPIO pin:

Code: Select all

: ledRead ledPin digitalRead ;
So now by typing "ledRead" the digital state of GPIO17 is pushed onto the Forth stack, and then "." prints the value at the top of the stack to the screen (the following includes the responses from the system - only the first word on each line, plus the dot where applicable, is for you to type - followed by the "Return" key of course).

Code: Select all

ledOn  ok
readLed . 1  ok
readLed . 1  ok
ledOff  ok
readLed . 0  ok
Define a couple more convenient verbs:

Code: Select all

: pause 500 delay ;

: blink begin ledOn pause ledOff pause again ;
Now type "blink" to start an infinite loop that flashes the LED. Ctrl+C breaks out of the loop and dumps you back to the Forth command line.

And that is the essence of Forth coding! Create a verb, test it, build it into the next verb, etc. Note that if you leave the Forth session and come back another time, your definitions will have been lost - but I'll talk about that shortly.

Try this (flash the international distress signal "SOS" in Morse Code on the LED):

Code: Select all

: dit ledOn 200 delay ledOff 200 delay ;
: dah ledOn 600 delay ledOff 200 delay ;
: SOS dit dit dit dah dah dah dit dit dit ;

SOS
That's a very crude program - it would be better to define constants to govern the time the LED is on for a dit or a dah, and off between dits or dahs, off between letters, and off between words. Then, if the user wanted to fine-tune the intervals, it would only be necessary to tweak the constants and not change all the delay values throughout the program - which could be a lot more involved than the simple example above!

As an exercise to get to grips with Forth, you might like to write a verb "morse" to take a string as input, and output it in Morse Code to the LED (which could equally be a piezo buzzer). You will need to read up about string handling to fetch one character at a time, and array handling to be able to look up the Morse Code for any character in a predefined table. As above, the timings should be predefined constants rather than hard-coded. It would be elegant to have the look-up table convert (for example) "e" to "·" and "o" to "–––", which is then passed on to be interpreted into short and long LED flashes.

The specifications for International Morse Code are available on Wikipedia. Note that the international distress signal "SOS" is defined as ···–––··· and not the three individual letters S O S (which would have longer breaks separating the letters).

Writing something to read Morse on an input pin and convert it to on-screen text is do-able, but a much tougher programming challenge!



Saving

When you exit gForth, everything you did in Step 5 is forgotten and you will have to start again next time from "gforth...".

Well, that's not entirely true. gForth maintains a command history just like the normal Raspbian command prompt, and the history is preserved between sessions (in fact, the relevant history file just grows and grows). You can replay your previous sessions, or selected parts of them, simply by using the up-arrow and down-arrow keys (or Ctrl+P and Ctrl+N for "previous" and "next") to bring up the line you want, alter it if necessary, and press return to execute it.

The command history is also accessible outside the gForth session, in a hidden file ".gforth-history" (files starting with a dot don't show up in directory listings unless you specifically specify "ls .*"). This means that one can, for example, copy the history file to another file (thus saving it), and edit the new file into a definition file for gForth - which can then be loaded next time to reinstate your work. Of course, one can also create a definition file from scratch.

The following prepares to create a file "sos" containing the code used to define the Forth verb "SOS", as above:

Code: Select all

cp .gforth-history sos
nano sos
"nano" is an editor that runs in a terminal session. It uses Ctrl combinations to write (save to file), exit (which will remind you to save if necessary), etc - the options are displayed at the bottom of the terminal window.

The command history file just gets longer and longer as sessions accumulate. To erase it and start again:

Code: Select all

rm .gforth-history
You should now be able to edit the command list to look like the following, and save it as the file "sos":

Code: Select all

include wiringPi.fs
wiringPiSetupGpio drop
17 constant ledPin
ledPin OUTPUT pinMode
: ledOn   ledPin HIGH digitalWrite ;
: ledOff  ledPin LOW digitalWrite ;
: dit ledOn 200 delay ledOff 200 delay ;
: dah ledOn 600 delay ledOff 200 delay ;
: SOS dit dit dit dah dah dah dit dit dit ;
Using the command "gforth sos" will set everything up ready to type "SOS" on the gForth command line; alternatively start gForth without any parameters and then within the gForth session type "include sos".

It is much more convenient to do the text editing on the PC you are using to run the terminal session than in the terminal session itself. Files can be copied between the RPi and the PC using SFTP, which was enabled at the same time as SSH. To access the RPi file system from Windows via SFTP: use Filezilla and put in the same credentials as you use to log in to the SSH terminal session. FileZilla provides a dual-pane file manager you can use to copy files between systems.

Beware of differences in text file formats between Windows and Linux (in this case Raspbian). Windows won't show the Forth code file correctly in Notepad, because it doesn't have the expected end-of-line markers (for MS-DOS/Windows). Similarly, the markers used by Windows may confuse Linux. To ensure you can edit files and not make them incompatible: always start with a file originated on the RPi; and use Notepad++ to do the editing.


User Input

A program which just does the same thing every time is okay in some cases, but it is often useful to include some user control. Assuming the existing definitions etc listed previously are already loaded into gForth, add the following (or add it into the file "sos"):

Code: Select all

: oneBlink ledOn 200 delay ledOff 200 delay ;
: Blinks
    CR
    ." How many blinks (1-9)? " KEY DUP EMIT SPACE
    DUP DUP 48 > OVER 58 < AND
    IF 48 DO oneBlink LOOP THEN
;
...and execute using "Blinks". (To find out how this works, please see Starting Forth.)


Using Root Privilege

Everything done above is from a normal user perspective, in this case the user login being "pi". Raspbian (in its default configuration) restricts the access that a normal user has so as to protect critical operating system files and the hardware. The alternative is "root" privilege, also known as "super-user", which allows access to everything (at your own risk). wiringPi, in general, provides direct access to the GPIO functions without requiring root privilege, and the ability to control the LED from gForth via the wiringPi libraries has been demonstrated not to need root privilege.

However, there may be occasions when it is necessary to over-ride the user level restrictions and ensure nothing blocks access to the hardware, in which case the gforth command can be prefixed by the command "sudo", which elevates everything done within the gForth session to root privilege:

Code: Select all

sudo gforth wiringPi.fs
(or whatever).

"sudo" is a powerful but potentially dangerous command because it overrides protections that prevent accidental or deliberate attempts to corrupt the computer system - it elevates permissions to "Super User" for the duration of what the following command is DOing (in this case: gforth). It is not good practice to use "sudo" just anywhere, but as we are trying to interact with the RPi's hardware it may be needed on occasions.

Bear in mind however that this is your computer to do what you like with, even mess it up if you want - you are the super-user. Nothing's going to come to any harm if you do mess it up, so it doesn't matter. The worst that might happen is you have to start again from Step 1.

However, in super-user mode, gForth records its command history in a separate file, in a place inaccessible without root privilege. To append the "root" command history to the existing "user" command history (where the history lines can be easily accessed):

Code: Select all

sudo cat /root/.gforth-history >> ~/.gforth-history
To erase the "root" command history:

Code: Select all

sudo rm /root/.gforth-history


Running a Forth Program from the Raspbian Command Line

Taking the SOS code above as our example, if we add two lines to the end of the file "sos":

Code: Select all

SOS
bye
...then it can be invoked straight from the command line, and it flashes the Morse equivalent of "SOS" on the LED and then returns to the command prompt:

Code: Select all

gforth sos
It would be rather nice, though, if it could simply be run directly as "sos".

There are several ducks to be put in a row for this to happen:
  1. "sos" needs to invoke gForth so that the code it contains can be interpreted;
  2. "sos" needs to be marked as executable;
  3. "sos" needs to be on the command search path;
  4. Any files "sos" refers to need to be located when executed.
The first of these is solved by adding the line "#! /usr/bin/gforth" at the beginning of sos. The file should now look like:

Code: Select all

#! /usr/bin/gforth
include wiringPi.fs
wiringPiSetupGpio drop
17 constant ledPin
ledPin OUTPUT pinMode
: ledOn   ledPin HIGH digitalWrite ;
: ledOff  ledPin LOW digitalWrite ;
: dit ledOn 200 delay ledOff 200 delay ;
: dah ledOn 600 delay ledOff 200 delay ;
: SOS dit dit dit dah dah dah dit dit dit ;
SOS
bye
To mark the file as executable:

Code: Select all

chmod 755 sos
The third requirement is a little trickier. The current directory is not automatically on the command search path (unlike MS-DOS/Windows), and it is possible to make it so using "PATH=$PATH:$HOME" (presuming everything so far has been done in user pi's default directory), but that won't persist after you log out or close the session. However, Raspbian is configured to automatically add the user's /bin folder to the search path if it exists, so an easy solution is to create a bin folder and move sos into it:

Code: Select all

mkdir ~/bin
mv sos ~/bin
("~/" is the current user's default directory, equivalent to "$HOME". The ~/bin folder won't be on the command search path until you log out and log in again.)

Finally, sos expects to find wiringPi.fs in the same directory. If we were to simply copy wiringPi.fs into ~/bin, that would mean there were several versions of wiringPi.fs floating around and all needing to be updated if one was updated. If we were to move it into ~/bin, that would make it unavailable for instant use on the Forth command line (without also specifying where to look for it). A solution is to move wiringPi.fs and create a symbolic link to it from the home directory:

Code: Select all

mv wiringPi.fs ~/bin
ln -s ~/bin/wiringPi.fs wiringPi.fs
Close the terminal session and start a new one, and the action of logging in registers the ~/bin folder into the command search path. Now type "sos" on the command line - "dit dit dit dah dah dah dit dit dit" flashes on the LED, and then the next command prompt pops up.


Still to come...

Fetching parameters from the Raspbian command line;
More info about the GPIO commands provided by wiringPi.fs;
Calling Forth programs from other scripts.


Hardware Interfacing

I have now split this out to a separate post. See here: viewtopic.php?p=1330183#p1330183
Last edited by Z80 Refugee on Sat Jul 07, 2018 7:16 am, edited 160 times in total.
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

User avatar
DougieLawson
Posts: 34166
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website

Re: Accessing GPIO I/O Pins from gForth

Sun Mar 11, 2018 3:28 pm

You shouldn't need to purge Wiringpi. The Stretch version is 2.44 2.46 which is current and works with all models of Raspberry.

Code: Select all

[email protected]:~/c$ apt show wiringpi
Package: wiringpi
Version: 2.44+1
Priority: optional
Section: libraries
Maintainer: Gordon Henderson <[email protected]>
Installed-Size: unknown
Depends: libc6
Download-Size: 53.1 kB
APT-Manual-Installed: yes
APT-Sources: http://archive.raspberrypi.org/debian stretch/main armhf Packages
Description: The wiringPi libraries, headers and gpio command
  Libraries to allow GPIO access on a Raspberry Pi from C and C++
  and BASIC programs as well as from the command-line

[email protected]:~/c$
Edit: there's a new version for RPi3B+
Download the *.deb to install it.
http://wiringpi.com/wiringpi-updated-for-the-pi-v3plus/
Last edited by DougieLawson on Thu Mar 15, 2018 6:56 pm, edited 1 time in total.
Microprocessor, Raspberry Pi & Arduino Hacker
Mainframe database troubleshooter
MQTT Evangelist
Twitter: @DougieLawson

2012-18: 1B*5, 2B*2, B+, A+, Z, ZW, 3Bs*3, 3B+

Any DMs sent on Twitter will be answered next month.

User avatar
Z80 Refugee
Posts: 358
Joined: Sun Feb 09, 2014 1:53 pm

Re: Accessing GPIO I/O Pins from gForth

Sun Mar 11, 2018 5:01 pm

DougieLawson wrote:
Sun Mar 11, 2018 3:28 pm
You shouldn't need to purge Wiringpi. The Stretch version is 2.44 which is current and works with all models of Raspberry.
Thanks, appreciated. I'll try it from scratch without.
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

User avatar
Z80 Refugee
Posts: 358
Joined: Sun Feb 09, 2014 1:53 pm

Re: Accessing GPIO I/O Pins from gForth

Mon Mar 12, 2018 12:54 am

Does that mean
Z80 Refugee wrote:
Sun Mar 11, 2018 3:14 pm
As I understand it, we need a special version of the wiringpi libraries, so need to get rid of any existing (if they exist):

Code: Select all

sudo apt-get purge wiringpi

hash -r
(I don't know what the "hash -r" command is for.)

Now install the right version of the wiringpi libraries:

Code: Select all

sudo apt-get install git-core

cd

git clone git://git.drogon.net/wiringPi

cd ~/wiringPi

./build

cd
...is not needed and all I actually need is

Code: Select all

sudo apt-get install wiringpi
?
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

User avatar
DougieLawson
Posts: 34166
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website

Re: Accessing GPIO I/O Pins from gForth

Mon Mar 12, 2018 12:56 am

Since it's already installed on stock standard full fat Raspbian you don't even need the install command.
Microprocessor, Raspberry Pi & Arduino Hacker
Mainframe database troubleshooter
MQTT Evangelist
Twitter: @DougieLawson

2012-18: 1B*5, 2B*2, B+, A+, Z, ZW, 3Bs*3, 3B+

Any DMs sent on Twitter will be answered next month.

User avatar
scruss
Posts: 1863
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: Accessing GPIO I/O Pins from gForth

Mon Mar 12, 2018 12:58 am

but they were running from Lite, Dougie. So they need the ‘apt get’
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.

User avatar
Z80 Refugee
Posts: 358
Joined: Sun Feb 09, 2014 1:53 pm

Re: Accessing GPIO I/O Pins from gForth

Mon Mar 12, 2018 7:49 am

Thank you both. Yes, there's no need for desktops and office apps for the kind of usage I have in mind. Good to know though, and I will make a note of it in the primary post when I have had a chance to test (not that I doubt you, but I do like to confirm everything if possible).
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

User avatar
scruss
Posts: 1863
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: Accessing GPIO I/O Pins from gForth

Mon Mar 12, 2018 1:01 pm

Then again, if you've got the disk space (and disk/card space is cheap), why not use the full Raspbian? Your tutorial can be made much simpler and appeal to many more people. Also, your queries here will be easier: everyone assumes you're running latest Raspbian, and if not, you're somewhat on your own.
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.

User avatar
Z80 Refugee
Posts: 358
Joined: Sun Feb 09, 2014 1:53 pm

Re: Accessing GPIO I/O Pins from gForth

Mon Mar 12, 2018 5:21 pm

Hardly a problem though, is it? I was proposing to say something like "if you are using the full version of Raspbian you don't need to do (whatever)". Covers all bases.
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

User avatar
Z80 Refugee
Posts: 358
Joined: Sun Feb 09, 2014 1:53 pm

Re: Accessing GPIO I/O Pins from gForth

Wed Mar 14, 2018 8:55 pm

The procedures in Post 1 have been refined in the light of the above comments and further experimentation.
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

User avatar
scruss
Posts: 1863
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: Accessing GPIO I/O Pins from Forth

Thu Mar 15, 2018 2:43 pm

Nice - thank you!

Does wiringPi need sudo access? I know it used to, but there was this update in 2015:
http://wiringpi.com/wiringpi-update-to-2-29/
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.

User avatar
Z80 Refugee
Posts: 358
Joined: Sun Feb 09, 2014 1:53 pm

Re: Accessing GPIO I/O Pins from Forth

Thu Mar 15, 2018 3:01 pm

The way I see it: something like the RPi really shouldn't need protecting from users (cos it's meant for users to get at). However, if we insist on also having them connected to Internet threats, protections become necessary - which can be circumvented by "sudo" (whether it happens to be needed or not), so it might as well be in the instructions.
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

User avatar
DougieLawson
Posts: 34166
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website

Re: Accessing GPIO I/O Pins from Forth

Thu Mar 15, 2018 6:57 pm

scruss wrote:
Thu Mar 15, 2018 2:43 pm
Nice - thank you!

Does wiringPi need sudo access? I know it used to, but there was this update in 2015:
http://wiringpi.com/wiringpi-update-to-2-29/
V2.46 was release yesterday. It doesn't need sudo unless you're doing strange pwm things.
Microprocessor, Raspberry Pi & Arduino Hacker
Mainframe database troubleshooter
MQTT Evangelist
Twitter: @DougieLawson

2012-18: 1B*5, 2B*2, B+, A+, Z, ZW, 3Bs*3, 3B+

Any DMs sent on Twitter will be answered next month.

User avatar
Z80 Refugee
Posts: 358
Joined: Sun Feb 09, 2014 1:53 pm

Re: Accessing GPIO I/O Pins from Forth

Thu Mar 15, 2018 7:37 pm

Is there no "like" on this forum?
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

User avatar
DougieLawson
Posts: 34166
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website

Re: Accessing GPIO I/O Pins from Forth

Thu Mar 15, 2018 8:32 pm

Z80 Refugee wrote:
Thu Mar 15, 2018 7:37 pm
Is there no "like" on this forum?
Correct, because - thankfully - it's not Faceborg.
Microprocessor, Raspberry Pi & Arduino Hacker
Mainframe database troubleshooter
MQTT Evangelist
Twitter: @DougieLawson

2012-18: 1B*5, 2B*2, B+, A+, Z, ZW, 3Bs*3, 3B+

Any DMs sent on Twitter will be answered next month.

User avatar
Z80 Refugee
Posts: 358
Joined: Sun Feb 09, 2014 1:53 pm

Re: Accessing GPIO I/O Pins from Forth

Thu Mar 15, 2018 8:42 pm

It's useful on other forums for expressing thanks without having to post to say so!
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

User avatar
scruss
Posts: 1863
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: Accessing GPIO I/O Pins from Forth

Fri Mar 16, 2018 1:05 am

Z80 Refugee wrote:
Thu Mar 15, 2018 3:01 pm
The way I see it: something like the RPi really shouldn't need protecting from users (cos it's meant for users to get at).
But, apart from "don't do it again", there's no learning from a sudo snafu. Not using sudo protects everyone from carelessness.

I can confirm that the installation works with just:

Code: Select all

sudo apt install gforth libtool-bin wiringpi git
git clone https://github.com/kristopherjohnson/wiringPi_gforth.git
cp wiringPi_gforth/wiringPi.fs .
gforth wiringPi.fs
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.

User avatar
Z80 Refugee
Posts: 358
Joined: Sun Feb 09, 2014 1:53 pm

Re: Accessing GPIO I/O Pins from Forth

Fri Mar 16, 2018 8:51 am

I am in two minds about this, only because eliminating "sudo" to launch gforth reduces the typing and risk of transcription error. I hear what you ware saying, but my intention is a process which will definitely work (nothing worse than trying something for the first time, possibly with no experience at all, finding it didn't work and not knowing why). Frankly I would prefer to log in as root - I just haven't explored that yet, and as a set of "getting started" instructions root login seems like overkill.

The other thing is PWM (which I wouldn't have known about unless you pointed it out, thanks). If any of GPIO control needs root access, then root access should be the experimenter's default.

In summary, given what I am trying to do, I don't see anything wrong with launching gforth with the sudo prefix as an insurance. It's hardly a snafu because it does not stop anything working and could make something work that otherwise wouldn't. The only risk I can think of is that you might execute something within gforth that screws up the system - not very likely unless it was deliberate, but if you do you just start again from the top.

Unless someone can identify a specific reason not to use sudo to launch gforth, it stays in. RPi is for experimenters, not system administrators!
scruss wrote:
Fri Mar 16, 2018 1:05 am
I can confirm that the installation works with just:
OK, but that only provides the code to set up and access GPIO functions - you don't know it works until you actually waggle some bits.
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

User avatar
Z80 Refugee
Posts: 358
Joined: Sun Feb 09, 2014 1:53 pm

Re: Accessing GPIO I/O Pins from Forth

Fri Mar 16, 2018 9:18 am

I hope I have resolved this by adding a note about the use of sudo.

Thanks for this:
scruss wrote:
Fri Mar 16, 2018 1:05 am

Code: Select all

sudo apt install gforth libtool-bin wiringpi git
git clone https://github.com/kristopherjohnson/wiringPi_gforth.git
cp wiringPi_gforth/wiringPi.fs .
gforth wiringPi.fs
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

User avatar
DougieLawson
Posts: 34166
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website

Re: Accessing GPIO I/O Pins from Forth

Fri Mar 16, 2018 9:34 am

scruss wrote:
Fri Mar 16, 2018 1:05 am
Z80 Refugee wrote:
Thu Mar 15, 2018 3:01 pm
The way I see it: something like the RPi really shouldn't need protecting from users (cos it's meant for users to get at).
But, apart from "don't do it again", there's no learning from a sudo snafu. Not using sudo protects everyone from carelessness.

Too much sudoitis on this forum. My program doesn't work fix it with sudo is not the right answer. Fix the program so it doesn't need sudo.
Microprocessor, Raspberry Pi & Arduino Hacker
Mainframe database troubleshooter
MQTT Evangelist
Twitter: @DougieLawson

2012-18: 1B*5, 2B*2, B+, A+, Z, ZW, 3Bs*3, 3B+

Any DMs sent on Twitter will be answered next month.

jahboater
Posts: 3263
Joined: Wed Feb 04, 2015 6:38 pm

Re: Accessing GPIO I/O Pins from Forth

Fri Mar 16, 2018 9:38 am

DougieLawson wrote:
Fri Mar 16, 2018 9:34 am
Too much sudoitis on this forum. My program doesn't work fix it with sudo is not the right answer. Fix the program so it doesn't need sudo.
+1
Understand Linux file permissions and the reasons why some parts of the disk are protected from casual error, or in the case of other users, simply for privacy.
Its not rocket science.

User avatar
Z80 Refugee
Posts: 358
Joined: Sun Feb 09, 2014 1:53 pm

Re: Accessing GPIO I/O Pins from Forth

Fri Mar 16, 2018 10:32 am

Can I just remind everybody what the RPi is for? If you want to use it as a central computing resource where users are locked out of doing anything the system admins don't want them to do, that's up to you, but you are dumping it right back into Windows territory (and before that, multi-user mainframes).

RPi is for experimenting and mucking about without risk of killing the main get-work-done computer. If you make a mistake and kill it, you simply rebuild and start again (and learn how not to kill it next time). As far as I am concerned, having a full-blown desktop OS on it (with all the restrictions thus imposed) is killing the goose that laid the golden egg. It just happens that a full-blown desktop OS in the form of Linux is available and can be ported to the RPi hardware, and saves an awful lot of reinventing the wheel when it comes to file management, peripheral driving, communications...

Short of getting down and dirty with the OS, drivers, whatever, there is nothing an ordinary user can do to fix something that causes sudo (or root privilege) to be necessary. The restriction is imposed on what you're legitimately trying to do with one's own hobby compute module, and the only reasonable way forward is root privilege.

Using sudo from a user login does not expose the environment to external threats (unless you import them yourself), nor does logging in as root. If the system does get compromised, you just rip it up and rebuild.

Sudo-itis on a compute hardware hobbyist forum? I would put it the other way around: sudo-phobia.

Is this the right place to be debating the philosophical points of using or not using sudo? I reckon it deserves a separate thread in an appropriate section of the forum.
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

jahboater
Posts: 3263
Joined: Wed Feb 04, 2015 6:38 pm

Re: Accessing GPIO I/O Pins from Forth

Fri Mar 16, 2018 10:39 am

Use "sudo su" or change the user-id entry in /etc/passwd to zero if you want permanent root privilege, good luck.

You yourself are the sys-admin on your own computer. There is no big-brother to worry about.

I have seen people using sudo to access files in their home directory!
Of course the files then become owned by root, and sudo is required to do anything.
Such users get in a right pickle, because of they were not clear what sudo does.

Its best to understand why the system configuration files, such as /etc/fstab say, need extra privilege to alter.

User avatar
scruss
Posts: 1863
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: Accessing GPIO I/O Pins from Forth

Sat Mar 17, 2018 1:08 am

Z80 Refugee wrote:
Fri Mar 16, 2018 8:51 am
Unless someone can identify a specific reason not to use sudo to launch gforth, it stays in. RPi is for experimenters, not system administrators!
sez you; I don't think the Foundation goes to the bother of packaging a decent user distro to expect the user to have to re-image it every couple of hours.

And let's face it: re-imaging is a pain. It's a couple of hours out your life that could be spent doing something else. If you have any packages you like to use, the download and setup takes time. If I'm wanting a machine I can just pull the plug on and mess with the hardware, I use ESP8266s or Circuit Playground Express boards.
OK, but that only provides the code to set up and access GPIO functions - you don't know it works until you actually waggle some bits.
I did; got the blink thing working. But since my LED is on a different pin, I didn't think it ideal to impose my changes on what you've done.
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.

8thdev
Posts: 24
Joined: Fri Jul 31, 2015 2:23 pm

Re: Accessing GPIO I/O Pins from Forth, and How to Use Them

Sun Apr 15, 2018 3:43 am

Just thought I'd mention that 8th (a Forth-derivative) lets you easily access GPIO pins on RPI:

Code: Select all

pin# write? hw:gpio
That returns a HW item which you then use to write or read the specified pin:

Code: Select all

hw 1 hw:gpio!
( to write a '1' on that pin)

Return to “Other programming languages”