CodeBlanks Logo Icon CodeBlanks

Embedded Go

Learn Go's use in embedded systems.

Go on embedded Linux

On embedded Linux systems such as a Raspberry Pi, a router or an industrial device, Go is very handy: a single static binary, no dependencies, easy cross-compiling.

CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -ldflags="-s -w" -o sensor
scp sensor pi@cihaz:/usr/local/bin/

-ldflags="-s -w" shrinks the binary by dropping symbol and debug information.

Talking to hardware

On Linux hardware often looks like a file: GPIO, I²C and sensors are read under /sys or /dev. Pure-Go libraries such as periph.io wrap them. With limited memory, setting GOMEMLIMIT and avoiding needless goroutines matter.

b, _ := os.ReadFile("/sys/class/thermal/thermal_zone0/temp")
// "48312\n" → 48.3 °C

Practice Parse temperature

Convert the text "48312\n" read from a sensor file to a number with strings.TrimSpace and strconv.Atoi, divide by 1000 for Celsius and print it with %.1f.

Starter code

main.go
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
    ham := "48312\n"
    n, err := strconv.Atoi(strings.TrimSpace(ham))
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("%.1f\n", float64(n)/1000)
}

Expected output

48.3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which variable is added for 32-bit ARMv7?

  • GOARM=7 Correct answer
  • GOARCH=arm64
  • GOAMD64=v3
  • GOOS=arm

Explanation: GOARCH=arm selects 32-bit ARM; GOARM sets which ARM version to generate code for.

2 Shrink the binary

Question
go build -ldflags="____" -o sensor
Answer
go build -ldflags="-s -w" -o sensor

Explanation: -s drops the symbol table and -w drops DWARF debug information.

3 Setting and purpose

Term Meaning
GOARCH=arm 32-bit ARM
GOARM=7 ARMv7 code
-ldflags="-s -w" Smaller binary
/sys/class Hardware files

All lessons in Expert