Secret Code

Hello World

[In Six Languages]

Oliver Higgins

Issue 1, July 2017

Have you ever wanted to be fluent in another language? We can't help you with your Mandarin, but here's an intro to a few coding languages you'll probably encounter soon!

Greetings programmers, and welcome to Secret Code! This is the first in a series of articles that will guide you through the niche aspects of programming, while giving the beginner to advanced user a peek inside the world of coding. Where possible, this article will use pseudo code and then give a real world example in C for Arduino, and in Python as a high level guide. The idea is to discuss how programming works and the concepts behind it. How these concepts are universal and how they translate across languages; except PERL, nobody likes PERL.

Structure & Entry points

All programs have to know where to start and depending on the language, this may be as simple as the first line being marked with “start” or “main”. From this point on, the program will execute a series of commands that you have instructed it to do, then complete and shut down. To explain the concept better you can use the below “Hello World” program.

To start, the lowest level of programming would be machine code. The reality of this is that it would just be a large sequence of ones and zeros. So instead we have prepared some assembly language.

What is programming?

Put simply, a program is a set of instructions that tells the computer to do various things. At its simplest core, programming any processor is about shifting bits from one part to another. Different bits to different addresses produce different functions, depending on what the processor designer has envisioned. At a very low programming level this would allow basic mathematics and functions, while in a system such as the Arduino, pushing a certain byte to a particular address register will cause the hardware pins to go high or low. Fortunately for us the world of programming has become much more user friendly, with English-like syntax becoming the norm. A compiler takes this code and converts it to the required byte code or similar, allowing us to focus on what we want to achieve.

If you’ve done any coding previously, then chances are you will have undertaken a “Hello World” project. This is coding in its purest and simplest form and often used as the ultimate introduction; it asks the question “how do I initiate this software and output a result?” Relativity speaking, this is a modern concept. First and second generation languages are direct coding, but procedural based languages (i.e. third generation languages (3GL) such as C, Basic, Python and Java) provide a way to gain insight into how a language is structured. 

Why “Hello World”?  

The tradition of using “Hello World” as a test case comes from a code example in The C Programming by Brian Kernighan. This book is considered to be the seminal work of modern C-based programming. While the Arduino Compiler is based around C/C++ I would recommend hunting down a copy for reference. However, the tradition of Hello World has now propagated into virtually all languages for test examples, regardless of how far from C they are.

A NOTE ABOUT DUMB LANGUAGES (HTML & CSS):Yes, I probably shouldn’t refer to these as “dumb”, but the context here is that these particular languages serve to perform a certain function. In this case, it’s the mark-up of text, and how the pages are displayed in a web browser. On their own they perform no computation process and are not considered a programming language. The caveat here is the introduction of technologies such as JavaScript, which is the most common client-side scripting language.

Assembly (Motorola 68K)

I had to include this, as I learned it at university but have never used assembly since! This is provided primarily to give you an understanding of what happens at a basic level. We need to move our instructions around to different registrars on the process, then evaluate and move to the next one. 

Running the following code on a Motorola 68K processor will produce a “Hello World” on the screen.

START   ORG     $1000 
        LEA     MESSAGE,A1 
        MOVE.B  #14,D0 
        TRAP    #15 
        MOVE.B  #9,D0 
        TRAP    #15 
MESSAGE DC.B    ‘HELLO WORLD’,0 
        END     START   

C

C is the cornerstone of most modern languages. It is fast, relativity lightweight, easily modifiable and will compile on almost every type of processor. Arduino code is based on this syntax, and is a powerful language to learn. It can be quite verbose at times, so if you are coming from a modern high level language you may find you have to break your ideas down into very small pieces, in order to get it to execute correctly. Objective-C (a slight variant) is used to develop apps for iPhone® / iPad® etc, so it’s a VERY useful language to be familiar with.

#include <stdio.h> 
#include <stdlib.h> 
int main(void) 

   printf("Hello worldn"); 
   return EXIT_SUCCESS; 
}

JAVA

Java is a cross-platform, general purpose, high-level programming language developed by Sun Microsystems. It was originally intended to be an embedded language and is written compiler independent, so you can write code and quickly port it from one platform to another. The drawback with this however, is that it tends to be slower then a natively complied language. But if you are looking to build a tool that will work across a wide space, it may well be the answer. Another key feature of Java is that it is designed to be a pure object oriented language. We'll cover this another time.

public class Hello{ 
    public static void main
       (String []args){ 
       System.out. 
          println("Hello world"); 
    } 

PHP

PHP is a server side scripting language and interpreter that is freely available and used to power most of the web. It stands for PHP: Hypertext Preprocessor, and yes that is a recursive acronym.

<?php
   echo "Hello World";
?>

PYTHON3

Python is an interpreted language with a focus on design and readability of code. One of the most prominent features is its lack of curly braces and line ends. In Python, whitespace matters and it uses tabs and spaces to delimit code blocks. The syntax is quite compact, often allowing the programmer to express concepts in fewer lines of code than is possible with Java or C++. 

print("Hello world")

VB.NET (Visual Basic)

VB.net is probably getting a little bit old now, but we have included it to give an idea of modern BASIC (Beginners All-purpose Symbolic Instruction Code). BASIC was often considered the entry point for many programmers, and through this iteration it evolved to the modern .net variant by Microsoft. It was designed to allow the beginner a rich high-level experience that was readable and easy to debug.

Private Sub Button1_Click()
    Msgbox("Hello world")
End Sub

PSUEDO CODE

Pseudo code is well, not real. It’s a way to sequence a program and is generally used to describe how a process will function. It ignores the nuances of languages and sundry things like line ends and operator syntax. It is often very similar in its content to BASIC or Python. Here at DIYODE, we use it when mapping out a project flow as it allows those of us with different programming skillsets to easily converse. We have included it here as an example of things that may be featured elsewhere in the magazine. 

Print "Hello world"

COMMENTING IN CODE

A quick note about comments: As a person who is hopeless at commenting their code, I urge you to please comment your code – you will thank me later. Comments are used to debug code, so if you quickly comment out a section, it will help you find out if there is a problem relating to that line, as well as provide a way of outputting information. They also help you follow logic which another person has created - an important consideration when sharing code! Following is an example of basic commenting in popular languages.

//C Comment 
//Java Comment 
#Python Comment 
'VB Comment

FUNDAMENTAL PYTHON FOR RASPBERRY PI

One of the simplest languages that will help you learn the art of programming is Python. It’s commonly used in Raspberry Pi programming among other things. It has its roots as a scripting language, but it does away with a lot of the curly braces and line ends (often semicolons), thus making the code much more simple. On the surface it is not heavily object orientated and provides a simple yet powerful tool. 

There are two major Python versions: Python 2 and Python 3; and each of them are quite different. This tutorial uses Python 3, because it is more semantically correct and supports newer features.

How to install Python

Please go to python.org and follow the instructions to install Python3. A quick note before we start, Monty Python References are not only encouraged, they are expected! So in that tradition you need to fire up IDLE, the Python interface. Python does allow us to write code in a text editor, save it and then run it like a normal program, but using the IDLE interface we can experiment in real-time [1].

1
Output in Python Interface
This is the basic output from the Python interface

The first time you open IDLE you will get the above prompt, which may look like you've done something wrong! Just type at the cursor and press enter.

Congratulations! You can now communicate with your users. 

Greetings, programs! (yes, Tron references are an inherit part of code and are virtually mandatory). Let's dive into this simple statement. We can break this down to three main sections:

print; the parentheses ( ) and the “Hello World”.

When we typed in “print”, we called the print function (which is a built-in function). Python understands that from this, you will want to output a command to the user and, as such, expects you to give it more information to do so. The information required for the function is placed between the parentheses. In many functions you will place more than one item. 

Finally there is the message you want it to deliver. In this case it is the string “Hello World”. The “ denote that this should be handled as a string of text. We could put anything in here, of any length, and Python will simply output it to the user.

FUNDAMENTAL C FOR ARDUINO 

To put this into the real world we will walk through two quick examples using Processing in Arduino. Processing is a C/C++ derivative and is used to program the Arduino. These programs are called sketches. Using processing, we have two “Hello World” options. I’m going to assume at this point you have the Arduino IDE installed and a working UNO or similar attached. 

The basic sketch needs a bare minimum of two code sections (called methods): setup and loop. These are the entry point and setup of your variables, then a main loop that repeats whenever the unit is on. 

Startup 
    // anything here that needs to happen first. 
    // think of this as "booting". 
Main
    // this is the bit that goes 
    // around and around. 

In reality, the bare bones sketch looks like this:

void setup () {
    // put your setup code here, to run once:
}
void loop () {
    // put your main code here,
    // to run repeatedly:     
}

The real world, “Hello World” and the flashing LED

The Uno and most Arduinos have a built-in LED on Pin 13. We are going to make this flash to indicate some communication with the outside world. In this code we define the pin mode of the built-in LED to be an output; so pin 13 of your Arduino will be set to only output (i.e. send it high or pull it low). 

Once this setup is complete, the main loop is started. Here we use digitalwrite to send pin 13 (LED_BUILTIN), high. We then use delay to make the Arduino stop for 1,000 milliseconds (one second). Then we do the opposite and digitalwrite pin 13 low, turning the LED off. Another delay of one second, it returns to the beginning of the loop.

// the setup function runs once on startup or reset void setup() {   
    // initialize digital pin LED_BUILTIN
    // as an output.   
    pinMode(LED_BUILTIN, OUTPUT);

// the loop function runs over and 
// over again forever 
void loop() {   
    // turn the LED on (HIGH is board voltage)   
    digitalWrite(LED_BUILTIN, HIGH);    
    // wait for a second   
    delay(1000);    
    // turn the LED off by making the pin LOW   
    digitalWrite(LED_BUILTIN, LOW);    
    // wait for a second   
    delay(1000);    
We can create the same basic "blink" circuit with a Raspberry Pi and a few components.

FOR COMPARISON

Now to compare to the basic blink sketch using Raspberry Pi’s Python, we take a slight variation on the code but you can quickly see the similarities in the programming constructs. In the Raspberry Pi context Python is not as rigid as Arduino’s code. We can actually get away with creating different names with the loops, but for the purpose of this comparison we will keep it as close as we can to the Arduino code. 

This is working code, however it is not best practice for using Raspberry Pi Python as the loop never ends and we do not cleanup after ourselves with the GPIO.CLEANUP() function;

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
  
def loop(): # runs over and over again forever 
    while True: 
       GPIO.output(11, GPIO.HIGH) 
       time.sleep(1) 
       GPIO.output(11, GPIO.LOW) 
       time.sleep(1) 
loop()

Learning to code isn’t difficult, but it can seem daunting at first. Next month we’ll explore variable and conditional statements.