Creative DIY Microcontroller Projects with TinyGo and WebAssembly - Tobias Theel - E-Book

Creative DIY Microcontroller Projects with TinyGo and WebAssembly E-Book

Tobias Theel

0,0
27,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

While often considered a fast and compact programming language, Go usually creates large executables that are difficult to run on low-memory or low-powered devices such as microcontrollers or IoT. TinyGo is a new compiler that allows developers to compile their programs for such low-powered devices. As TinyGo supports all the standard features of the Go programming language, you won't have to tweak the code to fit on the microcontroller.
This book is a hands-on guide packed full of interesting DIY projects that will show you how to build embedded applications. You will learn how to program sensors and work with microcontrollers such as Arduino UNO and Arduino Nano IoT 33. The chapters that follow will show you how to develop multiple real-world embedded projects using a variety of popular devices such as LEDs, 7-segment displays, and timers. Next, you will progress to build interactive prototypes such as a traffic lights system, touchless hand wash timer, and more. As you advance, you'll create an IoT prototype of a weather alert system and display those alerts on the TinyGo WASM dashboard. Finally, you will build a home automation project that displays stats on the TinyGo WASM dashboard.
By the end of this microcontroller book, you will be equipped with the skills you need to build real-world embedded projects using the power of TinyGo.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 287

Veröffentlichungsjahr: 2021

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Creative DIY Microcontroller Projects with TinyGo and WebAssembly

A practical guide to building embedded applications for low-powered devices, IoT, and home automation

Tobias Theel

BIRMINGHAM—MUMBAI

Creative DIY Microcontroller Projects with TinyGo and WebAssembly

Copyright © 2021 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Aaron Lazar

Publishing Product Manager: Alok Dhuri

Senior Editor: Nitee Shetty

Content Development Editor: Tiksha Lad

Technical Editor: Karan Solanki

Copy Editor: Safis Editing

Project Coordinator: Deeksha Thakkar

Proofreader: Safis Editing

Indexer: Manju Arasan

Production Designer: Vijay Kamble

First published: April 2021

Production reference: 1160421

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80056-020-8

www.packt.com

To Sir Patrick Stewart, for being a shining light of humanity even in the darkest days. And to my beloved dog, Luca, for silently accepting that some walks have been shorter than usual while writing this book.

– Tobias Theel

Contributors

About the author

Tobias Theel works as the Technical Lead and DevOps for a German FinTech startup fino and since 2020 he has also started working for RegTech startup, ClariLab, as Lead Software Engineer. Being a software architect and an expert for Go and TinyGo alongside C# and Java, he is also iSAQB certified. Theel is a highly enthusiastic community contributor and is among the top 10% responders in C# and Unity3D as well as top 20% responders in .NET, Go, and Visual Studio on StackOverflow.

When not programming for fino or ClariLab, he can be found developing games, mainly at game jams such as the Ludum Dare Jam, where he develops games from scratch within 72 hours. As an active speaker at tech talks and a participant for numerous hackathons, Theel loves to share his knowledge of software development with fellow enthusiasts.

I want to thank my Team at ClariLab for granting me so many days off in order to finish this book. Also special thanks to Johannes Kolata, for giving so much valuable input for the book.

About the reviewers

Enrico von Otte started to learn programming as an 11-year-old child on the good old Commodore C64. Later he coded on an Amiga 2000 and in the mid 90s finally on PC. He is working in professional software development from 2005. After developing hardware close to software in C and C++, he moved to the C# world in 2008.

He developed GIS systems and document management systems until 2015. Now he is a professional software architect with a strong affinity to self-made code and the motto "Assembling is not developing".

Johannes Kolata started coding 8 years ago, working on document management systems. Since 2018, Kolata works as a Software Backend Engineer for German FinTech fino, which is best known for building the first digital bank account switch. Along the way, he has become an expert in developing in C#, Java, and Golang. He also became adept in C++ and has gained insights in multiple other programming languages. Besides working in FinTech industry, he is a passionate open source and 3D-printing enthusiast and has been building home automation systems from scratch that feature CAN communication, go API, and an Angular dashboard. When not working on projects, Kolata participates in game jams and hackathons.

Table of Contents

Preface

Chapter 1: Getting Started with TinyGo

Technical requirements

Understanding what TinyGo is

How TinyGo works

Comparing TinyGo to Go

Setting up TinyGo

Installing on Linux

Installing on Windows

Installing on macOS

Installing on Docker

Understanding IDE integration

VS Code integration

General IDE integration

Setting up Goland

Integrating any editor

The Arduino UNO

Getting to know the technical specifications

Exploring pinout

Checking out the Hello World of Things

Getting the requirements ready

Preparing the project

Programming the microcontroller

Flashing the program

Using TinyGo Playground

Summary

Questions

Chapter 2: Building a Traffic Lights Control System

Technical requirements

Lighting an external LED

Lighting an LED when a button is pressed

Building the circuit

Programming the logic

Building traffic lights

Building the circuit

Creating a folder structure

Writing the logic

Building traffic lights with pedestrian lights

Assembling the circuit

Setting up the project structure

Writing the logic

Summary

Questions

Further reading

Chapter 3: Building a Safety Lock Using a Keypad

Technical requirements

Writing to the serial port

Monitoring the serial port

Monitoring input from a keypad

Building the circuit

Understanding the workings of a 4x4 keypad

Writing the driver

Driver variables

Configure

GetIndices

GetKey

main

Finding drivers for TinyGo

Contributing drivers to TinyGo

Controlling a servomotor

Understanding SG90 servomotors

Building the circuit

Writing the servo control logic

Building a safety lock using a keypad

Building the circuit

Writing the logic

Summary

Questions

Chapter 4: Building a Plant Watering System

Technical requirements

Reading soil moisture sensor data

Assembling the circuit

Finding thresholds

Understanding ADC in TinyGo

Writing a library for the sensor

Testing the library

Reading water level sensor data

Writing a water level sensor library

Controlling a buzzer

Writing a buzzer library

Controlling a pump

Working with relays

Writing a pump library

Watering your plants

Summary

Questions

References

Chapter 5: Building a Touchless Handwash Timer

Technical requirements

Introducing the Arduino Nano 33 IoT

Installing Bossa

Learning to measure distances

Understanding the HC-SR04 sensor

Assembling the circuit

Writing a library

Unit testing in TinyGo

Writing an example program for the library

Using 4-digit 7-segment displays

Using a MAX7219

Writing a library to control the MAX7219

Writing a library to control the hs42561k display

Putting it all together

Summary

Questions

Chapter 6: Building Displays for Communication using I2C and SPI Interfaces

Technical requirements

Exploring the TinyGo drivers

Displaying text on an HD44780 16x2 LCD display

Building the circuit

Understanding I2C

Writing the code

Displaying user input on the display

Building a CLI

Understanding SPI

Displaying a simple game

Building the circuit

Using an ST7735 display

Developing a game

Summary

Questions

Chapter 7: Displaying Weather Alerts on the TinyGo Wasm Dashboard

Technical requirements

Building a weather station

Assembling the circuit

Programming the weather station

Sending MQTT messages to a broker

Implementing the Wi-Fi package

Implementing an MQTT client abstraction layer

Implementing the weather station

Introducing Wasm

Displaying sensor data and weather alerts on a Wasm page

Serving the application

Implementing the weather app

Summary

Questions

Chapter 8: Automating and Monitoring Your Home through the TinyGo Wasm Dashboard

Technical requirements

Building a home automation dashboard

Creating a reusable MQTT component

Setting up the Wasm instantiation code

Creating the HTML template

Implementing the login view logic

Implementing the dashboard component

Implementing the main logic

Serving the app

Building the home automation client

Setting up the circuit

Implementing the logic

Requesting data from the microcontroller

Checking other implementation ideas

Summary

Questions

Appendix – "Go"ing Ahead

Blocking a goroutine

Reading from a channel

A select statement

Sleeping is a blocking call

Finding heap allocations

Assessments

Chapter 1

Chapter 2

Chapter 3

Chapter 4

Chapter 5

Chapter 6

Chapter 7

Chapter 8

Afterword

Why subscribe?

Other Books You May Enjoy

Preface

If JavaScript or C# can run on microcontrollers, then Go can do it even better. While standard Go produces huge binaries, TinyGo produces binaries that fit on the smallest devices. Why should you choose Go for microcontroller and Wasm (short for WebAssembly) programming? My favorite reasons are that Go is easy to learn, easy to read, and easy to write. Also, Go comes with a powerful standard library that is loosely coupled and has strong concurrency capabilities included.

If you love Go as a language, then this book is for you. After working through this book, you'll have all the tools and knowledge you need to build all the microcontroller projects that you have ever dreamed of. Plus, as a further benefit, you will be able to build dashboards and home control apps using Wasm for your home automation projects. All of this can be achieved using TinyGo.

If you have never worked with microcontrollers before, here are some reasons why you should try it out:

If you already are a programmer, it is a cool thing to see code affecting real-world appliances. It really is a great feeling to complete a project and finally see the motor turning, the LED blink, the buzzer beep, and so on.You will be constantly learning new things and gaining a deeper understanding of how computers work in general, as you will become familiar with different types of bus systems, protocols, hardware interfaces, and much more.The possibilities are virtually limitless when you're playing with microcontrollers. You are not bound to what is available on the market, as you can simply build everything on your own.You can learn how to write small, efficient programs to tell a microcontroller what you want from it. This will also help you become a better developer in general.You can contribute to cool projects and get in touch with great communities of like-minded people.

Who this book is for

If you are a Go developer who wants to program low-powered devices and hardware such as Arduino UNO and Arduino Nano IoT 33, or if you are a Go developer who wants to extend your knowledge of using Go with WebAssembly while programming Go in the browser, then this book is for you. Go hobbyist programmers who are interested in learning more about TinyGo by working through DIY projects will also find this hands-on guide useful.

What this book covers

Chapter 1, Getting Started with TinyGo, sees you set up TinyGo and compile your first program!

Chapter 2, Building a Traffic Lights Control System, has you build a traffic lights control system, including pedestrian lights and a button; you will learn how to make use of Goroutines in TinyGo.

Chapter 3, Building a Safety Lock Using a Keypad, looks at making use of a 4x4 keypad and a servomotor to build a lock that opens when the correct passcode has been entered.

Chapter 4, Building a Plant Watering System, explains how to use different types of sensors to build an automatic plant watering system, so you do not have to water your plants manually anymore!

Chapter 5, Building a Touchless Handwash Timer, explores using a four-digit, seven-segment display and an ultrasonic distance sensor to recognize the movement of a nearby object to start a timer that will tell us when we have washed our hands for long enough.

Chapter 6, Building Displays for Communication Using I2C and SPI Interfaces, explains the concepts of Inter-Integrated Circuit (I2C) and Serial Peripheral Interface (SPI) by having you use displays that communicate using I2C and SPI buses. By the end of the chapter, you will know how to use different types of displays in TinyGo.

Chapter 7, Displaying Weather Alerts on the TinyGo Wasm Dashboard, is where you will build and serve a Wasm application that displays sensor data sent from an Arduino Nano 33 IoT over Wi-Fi.

Chapter 8, Automating and Monitoring Your Home through a TinyGo Wasm Dashboard, explains how to control and monitor devices in your home using a Wasm dashboard.

Chapter 9, Appendix–"Go"ing Ahead, covers some concepts that did not find their way into the previous chapters.

To get the most out of this book

All code examples have been tested with Go 1.16.2 on Ubuntu, but they will also work with future releases of Go and other operating systems. Visual Studio Code has been used as the editor throughout the book, but any other editor can be used.

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

I would love to see the projects that you build after reading this book on social media. Feel free to tag me on Twitter using the following tag: @Nooby_Games.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Creative-DIY-Microcontroller-Projects-with-TinyGo-and-WebAssembly. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Code in Action

Code in Action videos for this book can be viewed at https://bit.ly/3cYZOh4.

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781800560208_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "When we receive the start of the command, we append all subsequent characters to commandBuffer."

A block of code is set as follows:

data, err := uart.ReadByte()

if err != nil {

      println(err.Error())

}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

func main() {

      blocker := make(chan bool, 1)

     <-blocker

     println("this gets never printed")

}

Any command-line input or output is written as follows:

tinygo flash –target=arduino-nano33 Chapter06/tinygame/main.go

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "The value is pretty stable at 37888."

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Chapter 1: Getting Started with TinyGo

In my opinion, Go is easy to learn, easy to read, and easy to write. The language is not overloaded with fancy features but rather focuses on being concise. The built-in concurrency, fast compile times, high execution performance, and rich standard libraries make a great mix for an awesome language. This is why I want to take you on a journey from very basic high-level Go programs to the depths of microcontrollers utilizing the full power of TinyGo.

In this chapter, we are going to set up TinyGo and learn how to get code completion to work in VS Code and different editors. After this is done, we will have a look at the Arduino UNO and its technical specifications. We are going to compare TinyGo with Go and talk about what makes TinyGo special compared to other languages on microcontrollers. At the end of this chapter, we will write, compile, deploy, and run our first TinyGo program on a real microcontroller. Having all these topics covered, you will have learned how to write, build, and run programs on microcontrollers.

In this chapter, we're going to cover the following main topics:

Understanding what TinyGo isSetting up TinyGoUnderstanding the IDE integrationThe Arduino UNOChecking out the Hello World of things

Technical requirements

In order to continue, you need to have the following:

Go must be installedGOPATH must be set upGit must be installedAn Arduino Uno, preferably the Rev3 Edition but you can also use other Arduino Uno boards

You can find all code examples from this chapter in the following GitHub repository: https://github.com/PacktPublishing/Creative-DIY-Microcontroller-Projects-with-TinyGo-and-WebAssembly/tree/master/Chapter01

The Code in Action video for the chapter can be found here: https://bit.ly/3mLFCCJ

Understanding what TinyGo is

TinyGo is an independently written compiler, with its own runtime implementation. It is intended to be used for microcontroller programming, WebAssembly (WASM), and CLI tools. TinyGo heavily makes use of the LLVM infrastructure to optimize and compile code to binaries that a microcontroller can understand.

The first release of TinyGo (v0.1) was published on February 1, 2019 on GitHub. Since then, the project has quickly implemented lots of features and never stopped adding support for more microcontrollers, sensors, displays, and other devices.

On February 2, 2020, TinyGo announced that it is now officially a Google-sponsored project. This was a big step for the complete project.

How TinyGo works

The TinyGo compiler uses a different set of steps than other languages to transform Go source code to machine code. We will not be going into the details though, but let's take a look at an overview of the compiler pipeline:

We write the Go source code.This source code gets translated to Go SSA (Static Single Assignment).The Go SSA is transformed to LLVM IR by the TinyGo compiler package.The initialization code in the LLVRM IR is interpreted by the TinyGo interp packages. This step optimizes globals, constants, and more.The result is then optimized by some LLVM optimization passes (such as string to []byte optimization).The result is then again optimized by the LLVM optimizer.Next, some fixes are done by the compiler package.And as the last step, LLVM creates the machine code.

If this sounds complicated right now, don't worry – we don't have to take care of this process. TinyGo does all this for us. Now let's have a look at what makes TinyGo special compared to Go.

Comparing TinyGo to Go

TinyGo can compile some, but not all Go programs. Let's have a look at an example that can be compiled by both. Let's write a small Hello World program in Go—build it and check its size:

This is the most minimal Hello World program I can currently think of:

package main

func main() {

    print("Hello World\n")

}

It does not need an external package such as fmt to print the line.

I will be using Go 1.15.2 on an Ubuntu 20.01 operating system. To check your currently installed Go version, use the go version command:

$ go version

go version go1.15.2 linux/amd64

We build the program using the go build command:

$ go build ./ch1/hello-world/

Now we check the size using the ls –l command:

$ ls -l

-rwxrwxr-x 1 tobias tobias 1231780 Okt  4 19:31 hello-world

So, the program has 1,231,780 bytes, which is 1.23178 megabytes. That is pretty big for a program that consists of just 4 lines of code.

Note

The ls command is not available on all operating systems. If you want to check the sizes for yourself, you need to use tools that are available on your operating system.

The size of the binary file may differ when you try it out, as the Go team continues to optimize the compiler.

Furthermore, the size of the binary file could differ when building for other operating systems.

Now let's check what the size of the same program is, but this time compiled using TinyGo. As TinyGo does not support building binaries for Windows, I take care of the compiling, so we can just compare the sizes here:

I used the following command to build the binary:

$ tinygo build -o hello-world-tiny ch1/hello-world/main.go

The tinygo build command has a syntax that is similar to the Go build command.

Then I checked the size using the ls –l command, as we did before:

$ ls -l

-rwxrwxr-x 1 tobias tobias 1231780 Okt  4 19:31 hello-world

-rwxrwxr-x 1 tobias tobias   21152 Okt  4 19:39 hello-world-tiny

We see that the TinyGo version of our Hello World program is only a fraction of the size that the Go compiler emitted. The TinyGo version is only 21,152 bytes, which is about 0.021152 megabytes. The TinyGo program is 58 times smaller as compared to the Go program. This is a huge difference. If you still want to test it out yourself, you can do this after setting up TinyGo.

We have now learned that TinyGo can compile some, but not all Go programs. Also, we learned that programs that are compiled with TinyGo are very small. In the next sections, we'll get to know why TinyGo cannot compile all Go programs and what features TinyGo offers that Go does not offer.

Supported language features

TinyGo supports a part of the Go language features, but not everything is supported right now. Goroutines and channels work on most microcontrollers. Reflection is supported for most types. While slices are supported, you may encounter some problems when working with maps. Only certain types of strings, integers, pointers, and structs or arrays that contain the previous types are supported. So, all in all, a good portion of Go is supported in TinyGo.

Supported standard packages

The biggest part of the standard library is also supported in TinyGo. As of the time of writing, however, most of the net and crypto packages still do not compile. That means, if you import them, you will get compile errors.

You can look up a list of currently supported standard packages here: https://tinygo.org/lang-support/stdlib/.

Note

A yes in the support table does not mean that every function in a package is actually usable in TinyGo. Some functions still could cause compile errors.

Volatile operations

Volatile operations can be used to read to and write from memory-mapped registers. The values inside these registers can change between several reads without the knowledge of the compiler. The compiler has no knowledge about the effects of these operations, hence they are called volatile.

Go does not have a volatile operator, which is why TinyGo provides a volatile package. For most cases, we will not need volatile operations, as these are abstracted away by the machine package.

Inline assembly

Assembly Language (ASM) is a language that is specifically designed for a certain processor architecture. This happens because assembly depends on the machine code instruction set. The device-specific packages of TinyGo provide assembly packages.

This enables us to use inline assembly code in our Go programs, which is not possible in standard Go.

Heap allocations

The Heap is the part of the memory where dynamic allocations and deallocations take place during runtime. So, when our application wants to reserve a part of the memory, it talks with the Heap to reserve the memory. That part of the memory will then be marked as being in use. As this space is rather limited on microcontrollers and garbage collection is expensive and slow, TinyGo tries to optimize away Heap allocations. The result is that, often, objects can be statically allocated instead of dynamically.

Garbage collection

Garbage collection is the process of freeing memory. So, when your application no longer needs a part of the memory it earlier requested, this memory is marked as unused (free) again.

For that purpose, TinyGo has implemented its own variant of garbage collection. TinyGo uses a conservative mark/sweep garbage collection, where conservative means that the Garbage Collector (GC) has no knowledge of what is a pointer and what it is not. The GC process is split into two parts:

Mark: In the marking phase, the gc marks objects as reachable. Sweep: In the sweeping phase, the gc frees memory by marking the areas of unreachable objects as free. These freed areas can then be reused to allocate new objects.

We do now know what TinyGo is and what differences exist between TinyGo and Go. We have also learned what the Heap, the GC, and volatile packages are. The next logical step is to go on and set up TinyGo, which we will be doing in the next section.

Setting up TinyGo

The easiest way to install TinyGo and all its dependencies is to follow the Quick Start Guides for Linux, macOS, Windows, and Docker at the following link: https://tinygo.org/getting-started/.

As these guides cover important parts, I will only cover the Quick Start part for x64-based architectures and only for Debian-based operating systems such as Ubuntu for Linux.

The first thing to do before we start the setup is to check the latest version of TinyGo. To do so, go to https://github.com/tinygo-org/tinygo/releases and check for the newest release. Now, keep this information written down somewhere or memorize it as we'll be using it later.

Installing on Linux

The following steps cover installing TinyGo on a Linux derivate, which is based on Debian:

We use the following command to download the deb package from GitHub and install it using dpkg:

wget https://github.com/tinygo-org/tinygo/releases/download/v0.15.0/tinygo_0.15.0_amd64.deb

sudo dpkg -i tinygo_0.15.0_amd64.deb

You can exchange the version in the path and filename with the newest release version you found before.

Now we must add TinyGo to GOPATH. You can use the following command:

export PATH=$PATH:/usr/local/tinygo/bin

You can also extend GOPATH by editing your .profile or .netrc file.

The next step is to verify the installation. Use the tinygo version command to verify that TinyGo has been successfully installed:

$ tinygo version

tinygo version 0.15.0 linux/amd64 (using go version go1.15.2 and LLVM version 10.0.1)

AVR dependencies: As we are going to work with an Arduino UNO in the first chapters, we need to install some additional dependencies. We do so by using the following commands:

sudo apt-get install gcc-avr

sudo apt-get install avr-libc

sudo apt-get install avrdude

After installing these dependencies, we can now compile on AVR-based boards such as the Arduino UNO.

If you are using Fedora, Arch Linux, or other distributions, please follow the installation guide: https://tinygo.org/getting-started/linux/.

Installing on Windows

In this section, we are going to learn how to install TinyGo on Windows. After this section, we will have also learned how to install dependencies, which are needed to flash the Arduino UNO.

Very important note

You cannot create Windows binary programs using TinyGo. You can still compile and flash programs for microcontroller and WebAssembly targets.

You may want to directly install and use TinyGo inside the Windows Subsystem for Linux (WSL). The WSL is the way I recommend for Windows users.

To install TinyGo on Windows without using the WSL, I recommend using Scoop, a command-line installer for Windows. Make sure that you have PowerShell 5 (or later) and .NET Framework 4.5 (or later) installed. To do so, please follow these steps:

Enable PowerShell for your current user account using the following command:

Set-ExecutionPolicy RemoteSigned -scope CurrentUser

Now run the following command to download Scoop:

iwr -useb get.scoop.sh | iex

You can install TinyGo by using the following command:

scoop install tinygo

Now to verify the installation was successful, use the following command:

tinygo version

The output should look like the following:

tinygo version 0.15.0 windows/amd64 (using go version go1.15.3 and LLVM version 10.0.1)

The actual TinyGo and Go version might differ.

AVR dependencies: In order to be able to compile and flash programs for the Arduino UNO, we need to have an AVR 8-bit toolchain installed. You can find a download here: https://www.microchip.com/mplab/avr-support/avr-and-arm-toolchains-c-compilers.

Extend your %PATH% and make sure that the bin folder is included:

Next, download and install GNU Make for Windows. You can find GNU Make here: http://gnuwin32.sourceforge.net/packages/make.htm.As the last step, you need to download and install avrdude. The avrdude EXE also must be inside your %PATH%. You can download AVR Dude here: http://download.savannah.gnu.org/releases/avrdude/. The file you are looking for is called avrdude-6.3-mingw32.zip.

If you encounter any problems regarding the avr setup or don't know how to configure environment variables, you may want to check out the following guide: https://fab.cba.mit.edu/classes/863.16/doc/projects/ftsmin/windows_avr.html.

WSL installation

It is also possible to install TinyGo directly on the Windows Subsystem for Linux (WSL). Just follow the Linux section to do that.

Installing on macOS

Installation on macOS is straightforward. Let's take a quick look at the steps:

We are going to use Homebrew to install tinygo. Just use the following two commands:

brew tap tinygo-org/tools

brew install tinygo

Simply run the tinygo version command to verify the installation:

$ tinygo version

tinygo version 0.15.0 darwin/amd64 (using go version go1.15 and LLVM version 10.0.1)

Run the following commands to install the additional requirements needed to compile programs for AVR-based microcontrollers such as the Arduino UNO, which we are going to use in the first few chapters of the book:

brew tap osx-cross/avr

brew install avr-gcc

brew install avrdude

Installing on Docker

It is possible to directly use a Docker image to compile our programs. However, it is not possible to flash the programs using the Docker image.

Simply download the image using the following:

docker pull tinygo/tinygo:0.15.0

Note

The actual TinyGo version might differ. Use the newest TinyGo version from the check we did when we started the section.

Here is an example call to build a program:

docker run -v $GOPATH:/go -e "GOPATH=/go" tinygo/tinygo:0.15.0 tinygo build -o /go/src/github.com/myuser/myrepo/wasm.wasm -target wasm --no-debug /go/src/github.com/myuser/myrepo/wasm-main.go

We have now successfully set up TinyGo and installed all additional requirements to compile and flash programs to the Arduino UNO microcontroller. Also, everything we need for WebAssembly is now set up. The next step is to set up IDE integration before we start writing our first program for a microcontroller.

Understanding IDE integration

Having a properly set up IDE is truly a blessing as we benefit from its features of code completion, functional linting, and so on. This way, we do not have to investigate the source code or documentation for every function we want to call.

In this section, we will look at the process of integrating TinyGo into VS Code, Goland, and other editors. This enables us to choose whatever editor we prefer to use.

VS Code integration

VS Code offers an extension system, which makes it easy to integrate the Go and TinyGo toolset into the IDE. We are going to install the Go Extension, which offers support for the Go programming language. Afterward, we are going to install the TinyGo extension, which brings TinyGo support.

The Go extension

We install the Go extension using the Extensions view using the following steps:

Open the Extensions view either by clicking on the Extensions icon or pressing Ctrl + Shift + X.Search for Go.Select the first entry in the list, which is called Go and is from the Go team at Google.Click on the Install button, as seen in the following screenshot:

Figure 1.1 – Installation from the Extensions view

After installing the extension for the first time, you might get prompted to install more dependencies. Do so by clicking on the Install button. If you do not get prompt, you can also install all dependencies by hitting Ctrl + Shift + P and entering the following command:

Go: install

Select the Go: Install/Update Tools command and hit Enter:

Figure 1.2 – Go: Install/Update Tools command to execute

Now select all dependencies by checking the box on the left side and click OK:

Figure 1.3 – Selection of all dependencies

VS Code will now install all dependencies, and it should print the following message when done:

All tools successfully installed. You are ready to Go :).

Next, we'll see the TinyGo integration in VS Code.

The TinyGo extension

TinyGo integration in VS Code is straightforward as there is a TinyGo extension that we simply need to install. Let's quickly go through the steps:

Open the Extensions view either by clicking on the Extensions icon or pressing Ctrl + Shift + X.Search for TinyGo.Select the first entry in the list, which is called TinyGo and is from the TinyGo team.Click on the Install button, as seen in the following screenshot:

Figure 1.4 – Extensions view showing the TinyGo extension

We are not done with installing the extension. We need to use another command to configure the target we want to build for. Hit Ctrl + Shift + P, type TinyGo target, and hit Enter. Now search for arduino and hit Enter, as we see in the following screenshot:

Figure 1.5 – The target selection popup

VS Code will open a popup telling you that it needs to reload the window. Do so by clicking on Reload:

Figure 1.6 – Popup asking to reload the window

Okay, we now have the extension installed and have selected a target. But what does it do internally? The only function of this extension is to set the go.toolsEnvVars variable in vs code settings.json of your current project.

This could look like the following example:

{

   "go.toolsEnvVars": {

     "GOROOT": "/home/user/.cache/tinygo/goroot-go1.14-f930d5b

         5f36579e8cbf1f-syscall",

     "GOFLAGS": "-tags=cortexm,baremetal,linux,arm,nrf51822,

         nrf51,nrf,microbit,tinygo,gc.conservative,scheduler.

         tasks"

}

}

Sometimes a popup similar to the one in the following screenshot will appear. Do not click on Update tools; just close it.

Figure 1.7 – Popup asking to update tools

If you are using VS Code, congratulations, you are done with the setup and are ready to go! The next sections are going to explain how to set up the IDE integration in other editors.

General IDE integration

You may wonder, how does IDE integration work with TinyGo? Well, we simply have to configure the standard Go tooling, especially the gopls language server.