Monday 26 September 2022

31 - Arduino, the everyman computer

In the old days if you wanted to work with microprocessors (tiny computers designed to be embedded inside other products) you had quite a lot to learn, a complete subject to master. Because people just wanted to use the things and not get a university degree, modules were designed to make life easy. The Arduino team took a microprocessor made by Atmel - the ATMega328P and put it on a board that had convenient connectors, and an LED as a training aid as well as serial communication to a host computer. 

The Arduino Foundation also took the software development toolset and drastically simplified the view of it that the users saw, the Arduino programming environment is a nice snug and cosy minimalist screen of text that is easy for non programmers to use. The key users were artists who just wanted a gadget to do something but the simplicity of the software and hardware, the convenience of assembling both code and hardware was so good that many groups of people adopted it. Makers and amateur radio homebrewers to name a few.

I used the phrases Arduino Team and Arduino Foundation in the text above, the exact status of these is not easy to determine and things have changed over the years. There is a "for-profit" company that manufactures hardware;- Arduino AG and the intention is to have the software tools produced by the Foundation. There is an extensive list of people involved and it all began in Italy with Massimo Banzi and four others.

As usual Dr Google helps with research and Wikipedia is a useful resource which usually carries the "truth", take a look at  https://en.wikipedia.org/wiki/Arduino for more background. The full story is listed there, with all the main people, sinners and saints listed.

What is important is that the Arduino hardware is open sourced and anyone can download the details and copy, and even sell boards. You can buy an "official" Arduino from the Arduino shop (http://arduino.cc ) or a clone from Ebay, either a cheap Chinese version or from more reputable company  like Seedstudio, Adafruit or Sparkfun. Seedstudio is actually a Chinese company but makes high quality products. If you buy official Arduino boards from Arduino you are contributing to the ecosystem. See the Arduino.cc site for more details. The word Arduino comes from the name of a local pub near where the first board was designed!

The first board was the "Arduino Serial" but the first one to really catch on was the Arduino UNO. (Most names are Italian, because that is where Arduinos began). It is not my intention to make you an Arduino expert as there is now a plethora of boards and some have moved on to more powerful processors and include Wifi and other goodies. The original UNO is still very popular but a lower cost smaller version called the Nano was produced and a more powerful bigger board with more memory and I/O called the Mega. These three will take you a long way. I have Megas in my 3D printers and CNC machine controllers and nanos in some home made testgear. If you buy an arduino board study carefully how to power it. Some are 3.3v and some are 5V and they allow several ways to supply power, some with voltage regulators and some without. Caveat Emptor.

So, the Nano;

 
As you can see there are two lines of convenient pins. A couple of other features include a small 6 pin (3x2) connector used for a hardware programmer (not needed as supplied Nanos have a software programmer built-in to them - called a bootloader this allows programming using the mini-USB connector) The mini-USB can also provide serial communications to a connected PC - handy for sending and receiving text messages from within the Arduino programming environment using  a simple two way serial terminal window and keyboard on your PC. There are also 4 LEDs and a pushbutton. One of the LEDs is simply connected to an I/O pin (you configure the pin to be an output of course). A standard procedure, a rite of passage, is to get that LED to blink - traditionally this is the first program you upload and run, the "BLINK" program is included in the examples supplied with the Arduino Software. The other LEDs indicate power and serial communications.

The standard "pinout" of the Nano looks complicated; it is complicated! but focus on one thing at a time, we need to apply power and connect a couple of wires for most projects.

In fact to prove you have a working system all you have to do is plug in the mini USB lead as it can supply power and allow programming your first program. Called "Blink".

You install the Arduino software from the Arduino.cc site - there are two current versions, either version1.8.19 or version 2.0. I refer to version 1.8.19 below, it is slightly simpler.

Before looking at the software and the Blink program in more detail, here are some photos of the other common Arduino boards. The Uno and the Mega.


This is actually a modern "version" of the UNO called a Leonardo. Its basic size and input/ output capability is the same but it has better USB communications (and a different type of USB connector). All UNO boards and their variants look much like this. The main chip may have more internal memory, either more program space or more space to store data. (or both)

The Leonardo provides 32 connection points on the two rows of pins. Some can be used for applyng power, or use the USB connector, or the 2.1mm barrel DC connector. As with the Nano you can (MUST) configure a pin to the correct function, this might be a simple output that can he "high" or "low" - a digital output for lighting LEDs or switching relays on or off for example. Or you might configure it as a simple input that can detect "high" or "low" - a signal from a switch or thermostat sensor for example. Or you can configure some (but not all) pins to receive a actual voltage which must be within zero to the power supply voltage, either 3.3V or 5V depending on the Arduino. The voltage can be read to within 0.1%. You can also configure some pins to output square waves that can vary in frequency or in the percentage that they are "high" or "low" (called the mark to space ratio, a term that relates to ancient telegraphy!). 

The next board in the Arduino family is the Mega, again they have several versions depending on internal memory size, set by the actual microprocessor chip that is on the board. 



I will not list all the input/output capabilities of the Mega, it is a long list!

I did come across a poster with the history of the Arduino at a very good Australian site, click https://core-electronics.com.au/guides/history-of-arduino/ for the original; thanks Sam. It is best printed as an A3 sheet so I do not reproduce it here.

Modern hardware does little without software (configuring the hardware to do something) and traditionally the configuration begins with a text editor to produce a simple text file that is input to a program that reads the text and works out what to tell the hardware. This is what a compiler does, the combination of the text editor and compiler is a basic integrated development environment, an IDE. The Arduino IDE now has two versions; version 2.0 looks prettier and has extra features to make your life easier. More complex IDEs in general have built in help and extra tools that are even more useful but take longer to learn. Invest the time if you are going to use Arduinos a lot. Version 1.8 looks like this;


Just 5 buttons on the toolbar (and you will only probably use 2 of them!) The first button (the black tick inside a blue circle) converts the text in the white box into machine readable code that configures the machine and runs commands in sequence i.e a "compiled program" the second button (the right arrow inside a blue circle) moves the compiled program into an attached Arduino and allows it to start running. This is called "Download and execute". The black window and the bottom line give progress and status messages as the software operates. There is a separate window used for serial communications. 

I have simplified this a bit, but that is the essence. If you are only using other peoples programs you load their text into the text editor  (the white area above) and click two buttons (you can even get away with clicking one button as the download button will also compile if you have forgotten. (the IDE tries to look after you!).

There are two other steps needed to setup the IDE before you begin, you need to attach your Arduino board using a USB cable and you must tell the IDE which board you are using. what COMM port the USB has decided to use and possibly what processor is on your particular board. There may be a need to specify any libraries that a particular program might use but if you download someone else's program they should tell you if you need to do this.

Note the white box above has some initial lines of text, you overwrite these with your own program but they are useful to look at now; you should realise that compilers (and computers) are actually very stupid and have an annoying need to be told absolutely explicitly what to do, you cannot be imprecise and expect them to know what you meant, as opposed to what you typed or said.

When I began programming (in a language called FORTRAN) I used to misspell the keyword EQUIVALENCE wrongly all the time, the computer always barfed and I always said "Sh1t". You will get an error message but sometimes with cryptic text if you make a mistake and you have to check everything carefully. If you think a program is not working then you are wrong, it is the human typing the program in that is not working! computers always work - they always do what you ask them to do.

Anyway, the text in the white box is a useful example of what is needed, it is not complete. In the Arduino world a program has two sections, a setup section and loop section. In a more conventional computer program there is just a single program and it is up to you to do what is needed, but the Arduino ecosystem makes it easy for you. The IDE uses the name sketch instead of calling the text a program and they describe the language as "wiring" as it connects up hardware in sequence over time as the program runs. I suppose that is less scary for beginners but I do not like these terms.

In fact the "wiring" language is 99.99% the same as one of the standard programming languages, well, it is really a blend of the C programming language and an improved version called C++. A traditional C programmer (like me) has no problem just treating it as standard C with good library support.

Before presenting the first real program I will point out a few things in the text. You do not need to know this if you only ever program other peoples programs but they are worth knowing.

Once the compiler sees two slashes together // it will ignore the rest of that line.

Why is this useful? because you can add notes and explanatory text to help you (or other people) understand what a line or section of code does. I find I am commenting more as I get older as my memory forgets code I wrote a week ago, adding comments helps. You can also write comments by prefixing and suffixing text with the delimiters  /*  and */ but the double slash is handier.

The essence of C, or most languages, is that you need actions, a bit like a verb, we call each action a "function" (in other languages sometimes called a "subprogram" or "subroutine"). Most programs do a function, then another function, then another function, a sequence of functions are executed to get the hardware to do something. It is good to have a lot of small functions rather than one big one. Good style is important, when teaching programming I used to insist a function must be shorter than an A4 page.  Sometimes you do one thing or another, so you have to test some input or condition and do one function if the condition is one value or a different function if it has a different value. 

That is how I describe a program to people who have never programmed before, I also point out that if you have made a pot of tea you have executed a series of functions (you do warm the pot before adding the tea don't you?) The modern term for what a program does is an algorithm.

Functions in C are named, hopefully sensibly! they are sometimes preceded by a special word, have a couple of round brackets that might or might not have some words between them and then have a curly bracket '{' followed by the body text of the function and then a final curly bracket '}'. 

C was originally meant to be a programming language for programmers, not an initial learning language, hence it is a bit terse. I much preferred the Algol, Pascal or Modula languages where you use the actual world "begin" and "end" instead of '{' and '}' although it did mean more typing.

So the template above should make more sense now, the special word void means the function just does something, if you were writing a function to work out the temperature of something then the function needs to return a number and then the void word be replaced with a word indicating what type of number the function creates - a whole number or one with a decimal point (don't worry about this for now, the secret to learning a lot is to learn a little, over and over again) The real secret to being a programmer is "the management of complexity"

A real program is included in the examples folders installed when you install the IDE. In fact there are dozens of examples given, do not sit and read them all or your brain will fill up. Under the folder "BASIC I/O" you will find the BLINK program (more correctly called the blink sketch); here it is

# define LED_PIN 13                  // Pin number attached to LED.

void setup() {
    pinMode(LED_PIN, OUTPUT);       // Configure pin 13 to be a digital output.
}

void loop() {
    digitalWrite(LED_PIN, HIGH);    // Turn on the LED.
    delay(1000);                    // Wait 1 second (1000 milliseconds).
    digitalWrite(LED_PIN, LOW);     // Turn off the LED.
    delay(1000);                    // Wait 1 second.
}

Of course, we must examine this one line at a time; do not be too disheartened at the amount you need to learn, the C programming language only has 35 odd keywords, much less than most languages, (although there are a lot of libraries)

# define LED_PIN 13                  // Pin number attached to LED.

Any line beginning with a '#' is telling the compiler to do something, there are only a couple of valid '#' commands, the # define tells the compiler to do a text substitution, anytime the word LED_PIN is seen from now on the compiler is to substitute the number 13 for it. Why do we do this? so we can use the more understandable word LED_PIN in our text and humans will understand it better than 13. In a large program we lump all the # defines together and if we move the program to a different board which has its LED on pin 15, we need only edit the single # define line in our program rather than searching and replacing every time the number 13 appears (in the right context) and changing it to 15. My 3D printer arduino code is 15,000 lines long and making a change in it would be tedious if hardware specific things were not isolated to one section (or one file) of the program. 

void setup() {
    pinMode(LED_PIN, OUTPUT);       // Configure pin 13 to be a digital output.
}

The setup function of the blink program simply calls the pinMode function and passes it two pieces of information, a pin number and what mode we want that pin to be configured as, in this case pin 13 is configured as an output. We need to know the pinMode function exists and what its options are, look up https://www.arduino.cc/reference/en/ to see the other things PinMode can do. 

By the way, every time you use a function you must put a semicolon after the final round bracket. When you write a function you put a '{' after the final round bracket. This is so the stupid compiler can figure out if you are giving it details about the function - its guts (usually called the "body" of the function) or whether you are using it. You only need to give the body of a function once but you can "call" or use a function as often as you like. (e.g we call the delay function twice in the blink program)

Nearly there; only two more functions to understand!, the second of these is the delay function. Guess what? it does what it says and simply waits for 1000 somethings, the program documentation says the delay function takes a number of millisecs so delay(1000); means wait a second.

I will leave it to you to figure out what the digitalWrite function does, you must pass it two things and it is documented in the help system https://www.arduino.cc/reference/en/ or click the Help top right menu item in the IDE.

To use the board, connect it to your PC via a USB lead. your PC should install drivers and allocate a virtual serial port. Some clones need you to manually change drivers but proper Arduino hardware shouldn't. In my case the default drivers loaded and I started up the IDE. The menu line at the top of the Version 1.8.19 IDE has File, Tool and Help entries as well as two others. 

Click on File->Examples->01.Basics->Blink A new IDE window should appear, close the first one and click on the new one.

Click on Tools->Board:->Nano

Click on Tools->Port:-> "whatever port your NANO got installed on" COM8: in my case, yours will be different. If I have difficulty finding the right port I hit Ctrl-ESC and enter dev on the keyboard to run the device manager control panel, expanding the Ports(COM & LPT) arrow will list all the com ports, mine lists "USB Serial Device  (COM8) but yours may list others. In any case the bottom line of the IDE should now list the board type and port in very small writing.

You are ready to compile and download the contents of the white window.  You can just hit the two buttons in round blue near the top left, but I usually alter one of the time delays in the Blink program from 1000 to 250 or smaller - I can then tell I am executing new code as my Arduinos might have an old blink program within them, so if you want to check out your system by actually compiling and downloading a new program then this is better. This is called "Verifying the toolchain" and means you have a working development environment to use your board. A good start.

Clicking the first button (with the tick in it) should bring up the word "Compiling" and a progress bar on the blue bar at the bottom of the white window. After a few tens of seconds this changes to "Done Compiling" and the black window has a few messages about how much memory the program uses. Unless of course you made a typing mistake. Even a trivial mistake stops compilation, an extraneous comma or a missing semicolon will break things. You must be absolutely precise. OCD even. You can type "white space" as C mostly does not care about indenting or new lines (some languages such as Python do).

Clicking the second button, the right arrow in the blue circle brings up another "compiling" message followed by "Downloading" and the black window shows a lot of messages, finally the LED Blinks!

note some Arduinos require you to press a button on the Arduino board a split second before hitting the download button. 

Hopefully this is a useful very basic overview of how to use an Arduino, a helicopter view. for sure you will probably need to follow more detailed tutorials and/or YouTube videos (or even a book!) but I have shown how it is not actually that complicated. Next month I will describe my experiments with a Nano connected to a Si5351 chip to make a VFO - similar to the system used in the uBitX.