2. Goose for Arduino and MicroPython programmers¶
Goose looks like C, Rust or Go. If you have written an Arduino sketch or a MicroPython script, most of it will look familiar. This tutorial goes through what you need for firmware, one small program at a time.
How to run each program¶
Make a folder for this tutorial:
microgoose new basics
For each program below, replace everything in basics/main.goose with
it, save, and run it.
Open the folder in VS Code, and press Ctrl+Shift+B for each program:
code basics
The folder's tasks build for the ESP32-S3. For an ESP32 DevKit V1, make
the folder with microgoose new basics --target esp32 instead. In a
terminal, the same is:
microgoose run basics/main.goose --target esp32 # ESP32 DevKit V1
microgoose run basics/main.goose --target s3 # ESP32-S3-DevKitC-1
These programs only print, so an emulator of the chip runs them too, in VS Code's terminal. Install Espressif's QEMU, then choose Terminal > Run Task... > MicroGoose: run in the emulator in VS Code, or in a terminal:
microgoose run basics/main.goose --target esp32 --emulate
Build it:
microgoose velxio basics/main.goose
In Velxio, keep the circuit from tutorial 1: any ESP32
board runs any program. Press Stop, choose File > Upload
firmware, pick velxio/basics-esp32.bin, and press Run. The
output is in the Serial monitor.
The outputs below are from an ESP32. Times in milliseconds will differ a little on yours.
The shape of a program¶
import mcu;
fn main() {
// Like Arduino's setup(): this runs once.
print("hello at ", millis(), " ms");
// Like Arduino's loop(): a loop that you end, or that never ends.
for i in 3 {
print("loop ", i, " at ", millis(), " ms");
delay_ms(1000);
}
print("main() returns, and the program is over");
}
hello at 285 ms
loop 0 at 289 ms
loop 1 at 1291 ms
loop 2 at 2298 ms
main() returns, and the program is over
[microgoose] program exited with code 0 (free heap 256036)
- A program starts at
fn main(). There is nosetup()andloop(): the top ofmainis your setup, and a loop of your own is your loop. Writewhile true { … }for one that never ends. - When
mainreturns, the program is over. MicroGoose prints that it exited, and the board waits until it is reset. import mcu;brings in the functions for the board's hardware:millis(),delay_ms(), the pins and the rest of the Hardware API. A program that doesn't touch the hardware doesn't need it.printtakes any number of values, of any type, and writes them on one line. Comments start with//, and every statement ends with;.
Values and types¶
import mcu;
fn main() {
let mhz = cpu_mhz(); // let: set once
var count: i32 = 0; // var: can change; i32 is a 32-bit integer
count += 3;
count++;
let volts = 3.3; // a float
let half = volts / 2; // the 2 becomes a float too
let ms: i64 = millis(); // millis() is an i64
let seconds = (ms / 1000) as i32; // narrowing is never silent: say `as`
print("cpu ", mhz, " MHz, count ", count, ", half of ", volts, " V is ", half);
print("up for ", seconds, " s");
print("-7 % 3 is ", -7 % 3, ", -7 / 3 is ", -7 / 3);
}
cpu 240 MHz, count 4, half of 3.3 V is 1.65
up for 0 s
-7 % 3 is 2, -7 / 3 is -2
letnames a value that never changes;varnames one that can. Preferlet.-
A type follows the name after a
:. Leave it out and Goose works it out from the value. The types you will use most:Goose Arduino C++ What it holds i32int(on an ESP32),int32_twhole numbers, ±2 billion i64int64_twhole numbers, ±9 × 10¹⁸; what millis()returnsu8,u16,u32uint8_t,uint16_t,uint32_twhole numbers from 0 f32floatnumbers with a fraction f64doublethe same, more precise boolbooltrueorfalse -
A smaller type turns into a bigger one by itself, but never the other way: to fit an
i64into ani32, writeas i32. That way you see every place where a value could be cut short. %never gives a negative result:-7 % 3is 2, where C and Arduino give −1. That makesi % nalways a valid index into an array ofnitems.
Decisions and loops¶
import mcu;
fn main() {
let temp = 31;
let label = if temp > 30 { "hot" } else { "fine" }; // an if gives a value
print(temp, " C is ", label);
let level = match temp {
0..10 => "cold",
10..25 => "mild",
_ => "warm",
};
print("match says ", level);
for i in 3 { print("for i in 3: ", i); }
for i in 10..13 { print("for i in 10..13: ", i); }
var n = 0;
while n < 3 { n++; }
print("while counted to ", n);
var tries = 0;
loop {
tries++;
guard tries < 5 else { break; } // leave the loop when tries reaches 5
}
print("loop stopped after ", tries, " tries");
}
31 C is hot
match says warm
for i in 3: 0
for i in 3: 1
for i in 3: 2
for i in 10..13: 10
for i in 10..13: 11
for i in 10..13: 12
while counted to 3
loop stopped after 5 tries
- Conditions need no parentheses, and the braces are always there.
- An
ifgives a value, so it does the job of C'scond ? a : b. matchis aswitchthat gives a value.10..25matches 10 up to 24: the end of a range is never in it._matches anything else.for i in 3counts 0, 1, 2, likefor (int i = 0; i < 3; i++)and MicroPython'sfor i in range(3):.for i in 10..13counts 10, 11, 12.looprepeats until abreak.guardsays what must be true for the rest of the block to run, and what to do when it isn't.
Functions¶
import mcu;
fn average(a: f32, b: f32) -> f32 {
return (a + b) / 2;
}
// Two results: the reading, and whether it is valid.
fn read_sensor(pin: i32) -> i32, bool {
if pin < 0 { return 0, false; }
return 1234, true;
}
fn blink_count(times: i32 = 3) -> i32 { // a default for the last parameter
return times * 2;
}
fn main() {
print("average ", average(20.5, 22.5));
let value, ok = read_sensor(4);
if ok { print("sensor says ", value); }
let _, ok2 = read_sensor(-1);
print("pin -1 valid: ", ok2);
print("edges for 3 blinks: ", blink_count(), ", for 5: ", blink_count(5));
}
average 21.5
sensor says 1234
pin -1 valid: false
edges for 3 blinks: 6, for 5: 10
fn name(parameter: type, …) -> result type. A function that returns nothing leaves out the->part.- A function can return several values. A last
boolthat says whether the others are good is the custom, where C would return −1 or use a pointer._drops a value you don't need. - Functions can come in any order in the file:
maincan call one that is written below it.
Structs, arrays and text¶
import mcu;
struct Reading { at_ms: i64, celsius: f32 }
fn main() {
let first = Reading { at_ms: millis(), celsius: 21.5 };
print("first reading at ", first.at_ms, " ms: ", first.celsius, " C");
let pins: i32[3] = [25, 26, 27]; // a fixed array: always 3
print("pins ", pins, ", the middle one ", pins[1]);
var log: Reading[>..] = []; // an array that grows
for i in 4 {
log.push(Reading { at_ms: millis(), celsius: 21.5 + i });
delay_ms(100);
}
print("log holds ", log.len, " readings; the last is ", log[log.len - 1].celsius, " C");
var text: u8[>..] = []; // text is an array of bytes
text.append("log:");
for r in log { format(text, " ", r.celsius); }
print(text);
}
first reading at 249 ms: 21.5 C
pins [25, 26, 27], the middle one 26
log holds 4 readings; the last is 24.5 C
log: 21.5 22.5 23.5 24.5
- A
structgroups named values, as in C. Build one withName { field: value, … }, and read a field with a.. i32[3]is an array of exactly three.Reading[>..]is one that grows with.push(), like a C++std::vectoror a Python list..lenis how many it holds, and the first is at[0].- An index past the end stops the program with an error that says where, instead of reading whatever memory is there.
- Text is an array of bytes,
u8.u8[>..]is one you can add to:.append()adds text, andformat()adds the text of any values, asprintwould write them. - There is no
new,mallocor garbage collector. Each value lives in the block that made it, and its memory is free again when the block ends. MicroGoose sets that memory aside when it builds the program, and prints how much.
Put it together: dice¶
A program that rolls two dice 3600 times, counts each total, and draws the counts as bars:
import mcu;
// One roll of a six-sided die: 1 to 6.
fn roll() -> i32 {
return (hw_random() % 6) as i32 + 1;
}
fn main() {
var counts: i32[13] = [0; 13]; // counts[total] for totals 2 to 12
let rolls = 3600;
for i in rolls {
counts[roll() + roll()]++;
}
var most = 2;
for total in 2..13 {
if counts[total] > counts[most] { most = total; }
var bar: u8[>..] = [];
for j in counts[total] / 20 { bar.push('#'); }
print(if total < 10 { " " } else { "" }, total, " ", bar, " ", counts[total]);
}
print("the most common total of ", rolls, " rolls: ", most);
}
2 #### 97
3 ######### 189
4 ############## 297
5 ##################### 431
6 ######################### 515
7 ########################### 557
8 ######################## 499
9 ##################### 431
10 ############# 268
11 ########## 203
12 ##### 113
the most common total of 3600 rolls: 7
hw_random() is the chip's random number generator, so your counts will
differ, but 7 should come out on top. [0; 13] makes an array of thirteen
0s.
Try changing it: roll three dice instead of two. The totals then run from
3 to 18, so counts needs 19 places.
Arduino and MicroPython, side by side¶
| Arduino C++ | MicroPython | Goose |
|---|---|---|
void setup() { … } and void loop() { … } |
code at the top level, while True: |
fn main() { … while true { … } } |
int n = 0; |
n = 0 |
var n: i32 = 0; |
const int LED = 25; |
LED = 25 |
let LED = 25; |
Serial.println(x); |
print(x) |
print(x); |
for (int i = 0; i < 10; i++) |
for i in range(10): |
for i in 10 { } |
delay(500); |
time.sleep_ms(500) |
delay_ms(500); |
millis() |
time.ticks_ms() |
millis() |
pinMode(25, OUTPUT); digitalWrite(25, HIGH); |
Pin(25, Pin.OUT).value(1) |
pin_output(25); pin_write(25, 1); |
pinMode(14, INPUT_PULLUP); digitalRead(14) |
Pin(14, Pin.IN, Pin.PULL_UP).value() |
pin_input(14, PULL_UP); pin_read(14) |
analogRead(34) |
ADC(Pin(34)).read() |
adc_read_raw(34) |
Where to learn more¶
- The Goose tutorial, by Goose's authors, covers the whole language: enums, slices, generics, errors, threads.
- Hardware API lists every function of
import mcu;.
Next, tutorial 3 uses the pins: LEDs, a button, and events.