Learn to write embedded software in Swift | Swift Safari

Learn about uSwift (pronounced micro swift) and the Swift4Arduino IDE

Ocean Paradise (they/them)
SwiftSafari
9 min readJun 10, 2023

--

Welcome to this comprehensive tutorial where we’re going to immerse ourselves in the fascinating world of hardware programming with Swift4Arduino. This guide aims to equip you with the tools, knowledge, and confidence to bring your microcontroller projects to life using the power and elegance of the Swift language. If you’re not already familiar with writing embedded software this might be a bit much, but depending on the interest I see in this article I may start doing more in depth articles that cover more complex Arduino projects in Swift. I’ve tried to keep it as simple as possible, and of course if you have any questions, drop them in the comments below!

Swift, a modern, type-safe and high-level programming language, has already taken the world of iOS development by storm. However, its utility is not restricted to developing apps for Apple devices. The *open-sourced* Swift4Arduino project has extended Swift’s reach into the realm of microcontrollers and Arduino, leading to the birth of an exciting new application for Swift in the world of hardware.

If you have ever been interested in the interplay of hardware and software or if you are a Swift enthusiast who wants to explore a new dimension of your favourite language, then you’ve come to the right place! In this guide, we will traverse through the uncharted territories of Swift4Arduino, understand its inner workings, and learn to craft programs for Arduino hardware using the Swift language.

Whether you’re an experienced Swift programmer eager to dive into hardware or a microcontroller hobbyist interested in new languages, we have you covered. With step-by-step project guides, easy-to-digest explanations, and comprehensive code blocks, we aim to make your Swift4Arduino journey an enlightening and enjoyable one. So without further ado, let’s dive right in!

An Overview of Swift for Arduino

Before we dive into the programming and project-building aspect, it’s crucial to understand what Swift for Arduino is, its purpose, and how it fits into the broader landscape of hardware programming.

What is Swift for Arduino?

Swift for Arduino is a groundbreaking innovation that brings the modern, safe, and powerful Swift language to the world of Arduino, a popular platform for building Internet of Things (IoT) applications and prototyping hardware projects. Swift for Arduino introduces a unique compiler that can translate Swift language into code that the Arduino UNO board, equipped with an Atmega328p microcontroller, can interpret and execute. This revolutionary approach opens up a world of possibilities for developers and hobbyists who can now leverage Swift’s robust features to build exciting hardware projects.

Why Swift for Arduino?

In a world where C/C++ has been the traditional choice for microcontroller programming, why should we turn to Swift? Here are some compelling reasons:

  • Safety: Swift is designed to be a safe language, eliminating a whole class of unsafe code by design. It means fewer crashes and unexpected behavior in our hardware projects.
  • Modern Language Features: Swift brings modern programming concepts, generics, and powerful protocol-oriented programming to the microcontroller realm.
  • Community: Swift has a vibrant, growing community, and the popularity of the language means it’s easier to find help and resources online.

Introducing Micro Swift (uSwift)

To adapt Swift for the resource-constrained environment of microcontrollers, the Swift for Arduino project introduces a variant of the Swift language, known as uSwift (Micro Swift). uSwift trims away memory-intensive features unsuitable for microcontroller programming while retaining the core language features that make Swift stand out.

The Swift4Arduino IDE

The Swift for Arduino project provides its own Integrated Development Environment (IDE), making it easy to write and compile Swift code for your Arduino UNO. It takes care of the intricacies of the compilation process, freeing you up to focus on your hardware project.

In the following sections, we will be using the Swift4Arduino IDE extensively to write, compile, and upload our Swift code onto the Arduino board.

Understanding the File Format

When you save a new document or open an existing one using the Swift4Arduino IDE, a .swift4a file is used. It’s essentially a folder containing the main .swift files and various related files. The built system outputs a .hex file, which is the finished program that can be uploaded to the Arduino board. The IDE takes care of the complexities behind the scenes, making the process smooth for you.

With this overview, we now have a broad understanding of what Swift for Arduino is and its potential. In the next section, we’ll start setting up our development environment and dive into writing our first Swift for Arduino project!

uSwift vs Swift: A Comparative Overview

Swift is a versatile, general-purpose programming language developed by Apple Inc. for iOS, macOS, watchOS, and tvOS app development. However, when it comes to microcontroller programming, a more tailored version is needed, one that prioritizes efficiency and performance on such constrained platforms. That’s where uSwift comes into play. Let’s delve deeper and understand how uSwift compares to mainstream Swift, the modifications it underwent to function efficiently on microcontrollers, and what it means for developers transitioning to uSwift.

Mainstream Swift vs uSwift

While uSwift and mainstream Swift share much of their syntax, type system, and programming model, there are notable differences due to the unique demands of microcontroller environments:

  1. Efficiency: uSwift was designed with an emphasis on efficiency, making it optimal for microcontrollers with their limited resources. On the other hand, mainstream Swift, being a high-level language, can afford to be more resource-intensive.
  2. Simplified Standard Library: In uSwift, many of the memory or CPU-intensive parts of the Swift standard library have been replaced with more efficient, simpler functions that fit on constrained programming platforms.
  3. Stripped Features: Some features from mainstream Swift, such as complex string processing, arrays, classes, and advanced data structures, have been removed or significantly simplified to keep uSwift lean and fit for microcontroller programming.

Changes Made for Efficiency

uSwift has been designed keeping in mind the resource constraints of microcontrollers. Here are some of the changes it underwent for efficient performance:

  • Simplified String Processing: Complex string processing from Swift has been removed in uSwift, replaced by memory-efficient small buffers for string synthesis and program memory stored constant strings for debugging and labels.
  • Removed Classes and Arrays: Classes and arrays, which lead to substantial runtime, have been disabled, reducing program size bloat significantly. This change also eliminates heap-managed RAM, which can pose a risk in constrained RAM devices.
  • Efficient Code Generation: uSwift emphasizes on generating optimal, fast, and efficient code, resulting in real-time performance and predictable timings, which are crucial for microcontroller functionality.

Learning Curve for uSwift

Transitioning from mainstream Swift to uSwift may present a learning curve, particularly for those not accustomed to programming on resource-constrained platforms. However, the core Swift concepts remain the same, allowing Swift developers to quickly adapt to uSwift’s nuances.

For developers with experience in microcontroller programming using languages like C or ASM, the uSwift programming style should feel familiar and straightforward. For those new to microcontroller programming, some aspects of uSwift might require some practice, particularly the emphasis on resource use and efficient timing. However, with a bit of dedication, no part of uSwift should be too challenging to learn.

In the next section, we will dive into setting up the Swift4Arduino IDE, which allows us to harness the power of uSwift to develop for Arduino boards.

Setting Up Your Development Environment

Now that we have a grasp on what Swift for Arduino is, let’s set up our development environment. This includes installing the Swift for Arduino IDE and getting familiar with its interface.

Installation

The first step towards working with Swift for Arduino is to install the IDE, which is available for both Windows and macOS platforms. Here are the steps for installation:

  1. Download the IDE: You can download the app on the Apple App Store. Alternatively, visit the Swift4Arduino website here and download the Swift4Arduino IDE suited to your operating system.
  2. Install the IDE: Run the installer and follow the on-screen instructions to complete the installation.
  3. (optional) License Activation: After the installation, launch the IDE. You will be prompted to enter your license key, which you should have received when purchasing the IDE. After entering the key, click ‘Activate’, and you’re all set! You have a trial period where you do not need to activate though, and downloading from the website does not require activation for personal use (double check terms for updated status on this).

Exploring the IDE

The Swift4Arduino IDE is a purpose-built platform designed specifically for Swift programming on Arduino. The layout is clean and minimalist, allowing you to focus on writing your code.

Here’s what you’ll see when you launch the IDE:

  • Code Editor: The central part of the IDE is the code editor, where you’ll spend most of your time writing your Swift code. The editor offers syntax highlighting for Swift, which helps make the code easier to read and understand.
  • Compiler Messages: At the bottom, you’ll find a space for compiler messages. If there’s an error in your code, this is where the IDE will let you know.
  • Toolbar: At the top, there’s a toolbar with several options. Here, you’ll find buttons to create a new project, open an existing one, save your current project, compile your code, and upload your program to the Arduino.
Swift 4 Arduino IDE

Your First Swift4Arduino Project

As we continue our journey into the realm of Swift4Arduino, we’ll start with a simple yet rewarding project — making an LED blink on the Arduino board. This project is often considered the ‘Hello, World!’ of the hardware programming world and will help you get hands-on with uSwift and the Swift4Arduino IDE. We will use the official Blink template from Swift4Arduino and explain everything inside of it in detail.

We have to start by importing AVR which provides the Swift interface for various AVR functionalities, such as reading and writing from/to the GPIO pins of an Arduino board.

import AVR

Next we define a typealias called IntegerLiteralType to be UInt8, which is an unsigned 8-bit integer type. This line is basically saying "Whenever you see 'IntegerLiteralType', think 'UInt8'." This is done to enforce an explicit type for the integer literals used in the program, as a precaution against the compiler using inappropriate types.

typealias IntegerLiteralType = UInt8

These lines declare and initialize three constants: ledPin is set to D13, which is the built-in LED on the Arduino board. ledOnTime and ledOffTime are set to 1000 and 500 milliseconds respectively, to control the duration for which the LED stays on and off.

let ledPin: Pin = D13
let ledOnTime: Milliseconds = 1000
let ledOffTime: Milliseconds = 500

Here, pinMode function is used to set the mode of ledPin to OUTPUT. This allows us to send voltage to the pin, and is necessary because we want to power the LED connected to D13.

pinMode(pin: ledPin, mode: OUTPUT)

SetupSerial() initializes the serial communication between the Arduino and the computer. Then, print is used to send a welcome message over the serial communication. This message can be read using the Serial Monitor tool in the Swift4Arduino IDE.

SetupSerial()
print("Hello, and welcome to Swift for Arduino!")

Finally, we have the main loop of the program. This loop runs indefinitely because its condition is always true. Inside this loop, we're turning the LED on by setting ledPin to HIGH with digitalWrite, then we're waiting for ledOnTime milliseconds. After that, we're turning the LED off by setting ledPin to LOW, and waiting for ledOffTime milliseconds. This sequence of operations creates a blinking effect with the LED.

while(true) {

// Turn LED on, wait
digitalWrite(pin: ledPin, value: HIGH)
delay(milliseconds: ledOnTime)

// Turn LED off, wait
digitalWrite(pin: ledPin, value: LOW)
delay(milliseconds: ledOffTime)
}

The template is well organized and modular. It first initializes the necessary properties, configures the LED pin, then enters an infinite loop that toggles the LED on and off. This structure makes it easy to modify the properties at the beginning of the program to control the behavior of the LED, for instance, to change the blinking rate of the LED.

Uploading the Program to the Arduino Board

Once you’ve written the code, it’s time to upload it to the Arduino board and see the results!

  1. Connect the Arduino Board: Connect your Arduino UNO board to your computer using a USB cable.
  2. Compile the Code: Click the ‘Compile’ button in the toolbar of the Swift4Arduino IDE. If there are no errors in your code, you should see a “Compilation Successful” message in the compiler messages area.
  3. Upload the Program: Click the ‘Upload’ button in the toolbar. The IDE will ask you to select the connected Arduino board from a list. Once you’ve selected the correct board, click ‘Upload’.

After the program uploads successfully, you should see the LED on your Arduino UNO board start to blink!

You’ve just completed your first Swift4Arduino project! If you like this, let me know and I may start tackling more projects utilizing uSwift and the S4A IDE!

Please, if you liked this project and the Swift Safari blog, please consider subscribing which really helps me justify taking my time to write these. It’s a lot of fun, but it also takes me away from life-sustaining paychecks, so clapping for the article and subscribing are ways that you can support me for free! Thank you!

--

--

Ocean Paradise (they/them)
SwiftSafari

amateur computational biologist & software engineer |sentient astrolotl | open-source enthusiast | let's tinker together!