### Build Microcontroller Blinky Example with TinyGo CLI Source: https://github.com/tinygo-org/tinygo/blob/release/README.md This shell command compiles and flashes the 'examples/blinky1' program to an Arduino Uno board using the TinyGo compiler. It requires the TinyGo toolchain to be installed and configured for the target board. ```shell tinygo flash -target arduino examples/blinky1 ``` -------------------------------- ### Load and Run WebAssembly in JavaScript Source: https://github.com/tinygo-org/tinygo/blob/release/src/examples/wasm/README.md Loads and instantiates a WebAssembly module in a web browser using JavaScript. It utilizes the `wasm_exec.js` helper file (provided by TinyGo) to manage the Go runtime and communication between JavaScript and Wasm. It supports both `instantiateStreaming` for modern browsers and a fallback using `fetch` and `instantiate` for compatibility. ```javascript const go = new Go(); // Defined in wasm_exec.js const WASM_URL = 'wasm.wasm'; var wasm; if ('instantiateStreaming' in WebAssembly) { WebAssembly.instantiateStreaming(fetch(WASM_URL), go.importObject).then(function (obj) { wasm = obj.instance; go.run(wasm); }) } else { fetch(WASM_URL).then(resp => resp.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes, go.importObject).then(function (obj) { wasm = obj.instance; go.run(wasm); }) ) } ``` -------------------------------- ### Build TinyGo WebAssembly Module Source: https://github.com/tinygo-org/tinygo/blob/release/src/examples/wasm/README.md Builds a WebAssembly module from a Go source file using the `tinygo` compiler. The output is a `.wasm` file, suitable for loading in JavaScript environments. This command specifies the output file name and the target platform as `wasm`. ```bash tinygo build -o ./wasm.wasm -target wasm ./main/main.go ``` -------------------------------- ### Target JSON Configuration Example Source: https://context7.com/tinygo-org/tinygo/llms.txt Defines hardware and compilation parameters for specific platforms through inheritable JSON specifications. This JSON structure specifies LLVM target, CPU, build tags, Go OS/Arch, linker, runtime libraries, garbage collector, scheduler, serial communication, stack size, C/Linker flags, linker scripts, extra source files, flash commands, and emulator configurations. ```json { "inherits": ["atmega328p"], "llvm-target": "avr-unknown-unknown", "cpu": "atmega328p", "features": "+avr6", "build-tags": ["arduino", "avr", "atmega328p"], "goos": "unknown", "goarch": "avr", "linker": "avr-gcc", "libc": "avr-libc", "rtlib": "compiler-rt", "gc": "conservative", "scheduler": "tasks", "serial": "uart", "automatic-stack-size": false, "default-stack-size": 512, "cflags": [ "-mmcu=atmega328p", "-DF_CPU=16000000UL" ], "ldflags": [ "-mmcu=atmega328p", "--defsym=_bootloader_size=512" ], "linkerscript": "targets/avr.ld", "extra-files": [ "src/runtime/runtime_atmega328p.go", "src/runtime/asm_avr.S" ], "flash-command": "avrdude -c arduino -p atmega328p -P {port} -b 57600 -U flash:w:{hex}:i", "flash-1200-bps-reset": "true", "serial-port": ["2341:0043", "1a86:7523"], "emulator": "simavr -m atmega328p -f 16000000 {}" } ``` -------------------------------- ### Go HTTP Server for Serving Wasm Source: https://github.com/tinygo-org/tinygo/blob/release/src/examples/wasm/README.md A simple Go HTTP server designed to serve static files, specifically configured to set the `Content-Type` header to `application/wasm` for files ending with `.wasm`. It also includes a development-specific `Cache-Control: no-cache` header to prevent browser caching during development, which should be removed in production. ```go package main import ( "log" "net/http" "strings" ) const dir = "./html" func main() { fs := http.FileServer(http.Dir(dir)) log.Print("Serving " + dir + " on http://localhost:8080") http.ListenAndServe(":8080", http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { resp.Header().Add("Cache-Control", "no-cache") if strings.HasSuffix(req.URL.Path, ".wasm") { resp.Header().Set("content-type", "application/wasm") } fs.ServeHTTP(resp, req) })) } ``` -------------------------------- ### Configure Garbage Collection and Scheduler in Go Source: https://context7.com/tinygo-org/tinygo/llms.txt This Go code demonstrates how to configure different garbage collection (GC) and scheduler options for various targets. It shows examples of using 'conservative' GC with a 'tasks' scheduler, 'precise' GC with 'threads', 'leaking' GC with 'asyncify' for WebAssembly, and a 'custom' GC with 'none' for embedded targets. The function returns a slice of compile-time configurations. ```go package main import ( "github.com/tinygo-org/tinygo/compileopts" ) func configureRuntime() ([]*compileopts.Config, error) { var configs []*compileopts.Config // Conservative GC with cooperative scheduler config1, _ := compileopts.NewConfig(&compileopts.Options{ Target: "cortex-m4", GC: "conservative", // Scans memory conservatively Scheduler: "tasks", // Cooperative multitasking }) configs = append(configs, config1) // Precise GC with preemptive threads config2, _ := compileopts.NewConfig(&compileopts.Options{ Target: "linux/amd64", GC: "precise", // Type-accurate garbage collection Scheduler: "threads", // OS-level threads }) configs = append(configs, config2) // No GC with asyncify for WebAssembly config3, _ := compileopts.NewConfig(&compileopts.Options{ Target: "wasm", GC: "leaking", // Never frees memory (for short-lived processes) Scheduler: "asyncify", // Transform to async/await style }) configs = append(configs, config3) // Custom GC for embedded config4, _ := compileopts.NewConfig(&compileopts.Options{ Target: "arduino-nano", GC: "custom", // User-provided GC implementation Scheduler: "none", // No concurrency support PanicStrategy: "trap", // Panic causes CPU trap }) configs = append(configs, config4) return configs, nil } ``` -------------------------------- ### Blink LED on Microcontroller with TinyGo Source: https://github.com/tinygo-org/tinygo/blob/release/README.md This Go program blinks the onboard LED of a microcontroller. It configures the LED pin as an output and toggles it in an infinite loop with a 1-second delay. This example works on various supported boards like Arduino Uno and Adafruit ItsyBitsy M0. ```go package main import ( "machine" "time" ) func main() { led := machine.LED led.Configure(machine.PinConfig{Mode: machine.PinOutput}) for { led.Low() time.Sleep(time.Millisecond * 1000) led.High() time.Sleep(time.Millisecond * 1000) } } ``` -------------------------------- ### Create WASM Library with Exported Functions using Go Source: https://context7.com/tinygo-org/tinygo/llms.txt This Go code demonstrates how to create a WebAssembly library with exported functions for seamless JavaScript interoperability. It includes functions for basic arithmetic, a Fibonacci sequence calculation, and JavaScript callback support for greeting and data processing. Ensure TinyGo is installed and use the provided build command to create the WASM module. ```go package main import ( "fmt" "syscall/js" ) //go:wasmexport add func add(x, y int32) int32 { return x + y } //go:wasmexport multiply func multiply(x, y int32) int32 { return x * y } //go:wasmexport fibonacci func fibonacci(n int32) int32 { if n <= 1 { return n } return fibonacci(n-1) + fibonacci(n-2) } // JavaScript callback support func registerCallbacks() { // Export function to JavaScript global scope js.Global().Set("goGreet", js.FuncOf(func(this js.Value, args []js.Value) interface{} { name := args[0].String() return fmt.Sprintf("Hello from Go, %s!", name) })) js.Global().Set("goProcess", js.FuncOf(func(this js.Value, args []js.Value) interface{} { data := args[0] length := data.Length() sum := 0 for i := 0; i < length; i++ { sum += data.Index(i).Int() } return sum })) } func main() { registerCallbacks() // Keep program running select {} } // Build as WASM component: // tinygo build -target=wasm -o math.wasm ./math.go // // Use in JavaScript: // const go = new Go(); // WebAssembly.instantiateStreaming(fetch("math.wasm"), go.importObject) // .then((result) => { // go.run(result.instance); // console.log(goGreet("World")); // "Hello from Go, World!" // console.log(goProcess([1,2,3,4,5])); // 15 // }); // // Or with direct exports: // const wasm = await WebAssembly.instantiateStreaming(fetch("math.wasm")); // console.log(wasm.instance.exports.add(5, 3)); // 8 // console.log(wasm.instance.exports.fibonacci(10)); // 55 ``` -------------------------------- ### Go Global Variable Initialization Source: https://github.com/tinygo-org/tinygo/blob/release/interp/README.md Demonstrates how Go typically initializes global variables with byte slices using an init function, which can be inefficient. ```go var foo = []byte{1, 2, 3, 4} ``` ```go var foo []byte func init() { foo = make([]byte, 4) foo[0] = 1 foo[1] = 2 foo[2] = 3 foo[3] = 4 } ``` -------------------------------- ### Automate Cross-Compilation for Multiple Targets using Go Source: https://context7.com/tinygo-org/tinygo/llms.txt This Go program demonstrates how to automate the cross-compilation of a project for various hardware targets and platforms, including Arduino, Raspberry Pi Pico, WebAssembly, and Linux ARM64. It defines a list of build targets with their specific configurations and uses the TinyGo builder package to compile the code for each. This is particularly useful for CI/CD pipelines. ```go package main import ( "fmt" "os" "path/filepath" "github.com/tinygo-org/tinygo/builder" "github.com/tinygo-org/tinygo/compileopts" ) type BuildTarget struct { Name string Target string OutputFile string Tags []string } func buildMultiTarget() error { targets := []BuildTarget{ { Name: "Arduino Nano", Target: "arduino-nano", OutputFile: "firmware-nano.hex", Tags: []string{"arduino", "avr"}, }, { Name: "Raspberry Pi Pico", Target: "pico", OutputFile: "firmware-pico.uf2", Tags: []string{"rp2040"}, }, { Name: "WebAssembly", Target: "wasm", OutputFile: "app.wasm", Tags: []string{"wasm", "web"}, }, { Name: "Linux ARM64", Target: "linux/arm64", OutputFile: "app-arm64", Tags: []string{"linux"}, }, } outputDir := "./dist" os.MkdirAll(outputDir, 0755) tmpDir := "./tmp" os.MkdirAll(tmpDir, 0755) defer os.RemoveAll(tmpDir) for _, target := range targets { fmt.Printf("Building for %s...\n", target.Name) options := &compileopts.Options{ Target: target.Target, Opt: "z", GC: "conservative", Tags: target.Tags, Debug: false, Semaphore: make(chan struct{}, 1), } config, err := builder.NewConfig(options) if err != nil { return fmt.Errorf("config error for %s: %w", target.Name, err) } outPath := filepath.Join(outputDir, target.OutputFile) result, err := builder.Build(".", "", tmpDir, config) if err != nil { return fmt.Errorf("build error for %s: %w", target.Name, err) } // Copy result to output directory err = os.Rename(result.Binary, outPath) if err != nil { return fmt.Errorf("output error for %s: %w", target.Name, err) } fmt.Printf("✓ Built %s: %s\n", target.Name, outPath) } return nil } // Run in CI/CD: // go run build-matrix.go // // Output: // Building for Arduino Nano... // ✓ Built Arduino Nano: dist/firmware-nano.hex // Building for Raspberry Pi Pico... // ✓ Built Raspberry Pi Pico: dist/firmware-pico.uf2 // Building for WebAssembly... // ✓ Built WebAssembly: dist/app.wasm // Building for Linux ARM64... // ✓ Built Linux ARM64: dist/app-arm64 ``` -------------------------------- ### Build Go Program to Binary Source: https://context7.com/tinygo-org/tinygo/llms.txt Orchestrates the entire build pipeline from source code to an executable binary. It takes a package import path, output file path, temporary directory, and build configuration as input. Dependencies include the builder and compileopts packages. The output is a build result containing paths to the binary, executable, main directory, and import path. ```go package main import ( "github.com/tinygo-org/tinygo/builder" "github.com/tinygo-org/tinygo/compileopts" ) func buildProgram() error { // Configure build options options := &compileopts.Options{ Target: "wasm", Opt: "z", // Optimize for size GC: "precise", // Precise garbage collector Scheduler: "asyncify", // Asyncify scheduler for WASM Debug: true, // Include debug information PrintSizes: "short", // Print size summary Tags: []string{"prod"}, // Custom build tags Semaphore: make(chan struct{}, 4), // Parallel build limit } // Create configuration from options config, err := builder.NewConfig(options) if err != nil { return err } // Execute full build pipeline: // 1. Load Go packages and dependencies // 2. Parse AST and type information // 3. Compile to LLVM IR // 4. Optimize IR (dead code elimination, inlining, etc.) // 5. Link with runtime libraries // 6. Generate target-specific binary result, err := builder.Build( "github.com/user/myapp", // Package import path "app.wasm", // Output file path "/tmp/tinygo-build", // Temporary directory config, // Build configuration ) if err != nil { return err } // Build result contains: // - result.Binary: Path to output binary // - result.Executable: Path to executable with debug symbols // - result.MainDir: Main package directory // - result.ImportPath: Full import path return nil } ``` -------------------------------- ### JavaScript Polyfill and Wasm Initialization for Go Source: https://github.com/tinygo-org/tinygo/blob/release/src/examples/wasm/main/index.html This snippet provides a polyfill for `WebAssembly.instantiateStreaming` for older browsers and demonstrates the standard method for instantiating a Go Wasm module. It fetches the 'wasm.wasm' file, integrates with the Go runtime, and enables a run button upon successful loading. ```javascript if (!WebAssembly.instantiateStreaming) { // polyfill WebAssembly.instantiateStreaming = async (resp, importObject) => { const source = await (await resp).arrayBuffer(); return await WebAssembly.instantiate(source, importObject); }; } const go = new Go(); let mod, inst; WebAssembly.instantiateStreaming(fetch("wasm.wasm"), go.importObject).then((result) => { mod = result.module; inst = result.instance; document.getElementById("runButton").disabled = false; }).catch((err) => { console.error(err); }); ``` -------------------------------- ### Microcontroller Blinky with Button Input (Go) Source: https://context7.com/tinygo-org/tinygo/llms.txt Demonstrates basic LED control and button input reading using TinyGo's machine package. It configures a built-in LED for output and a button pin for input with a pull-up resistor. The LED blinks at different rates based on button state and runs indefinitely. ```go package main import ( "machine" "time" ) func main() { // Configure built-in LED pin led := machine.LED led.Configure(machine.PinConfig{Mode: machine.PinOutput}) // Configure additional GPIO button := machine.D2 button.Configure(machine.PinConfig{Mode: machine.PinInputPullup}) for { if button.Get() { // Button pressed - fast blink led.High() time.Sleep(100 * time.Millisecond) led.Low() time.Sleep(100 * time.Millisecond) } else { // Normal blink led.Toggle() time.Sleep(500 * time.Millisecond) } } } // Build and flash: // tinygo flash -target=arduino-nano ./blinky.go // // Expected behavior: // - LED blinks at 1Hz when button not pressed // - LED blinks at 5Hz when button pressed // - Runs indefinitely on microcontroller ``` -------------------------------- ### Create Build Configuration from Compile Options Source: https://context7.com/tinygo-org/tinygo/llms.txt Creates a validated build configuration from compile options with target specification loading. It takes a compileopts.Options struct as input and returns a builder.Config. This function handles loading target specifications, resolving inheritance, validating options, and setting up compiler/linker flags. It depends on the compileopts package. ```go package main import ( "fmt" "github.com/tinygo-org/tinygo/compileopts" ) func configureTarget() error { options := &compileopts.Options{ GOOS: "linux", GOARCH: "arm", Target: "cortex-m4", Opt: "2", GC: "conservative", PanicStrategy: "trap", Scheduler: "tasks", StackSize: 8192, Work: false, // Clean temporary files Debug: true, PrintCommands: printCmd, } // NewConfig performs: // 1. Loads target specification from JSON // 2. Resolves inheritance chain for targets // 3. Validates option combinations // 4. Sets up compiler and linker flags // 5. Configures LLVM target triple config, err := compileopts.NewConfig(options) if err != nil { return fmt.Errorf("invalid config: %w", err) } // Access resolved configuration fmt.Printf("LLVM Triple: %s\n", config.Triple()) fmt.Printf("Target CPU: %s\n", config.CPU()) fmt.Printf("Build Tags: %v\n", config.BuildTags()) fmt.Printf("GC Strategy: %s\n", config.GC()) fmt.Printf("Scheduler: %s\n", config.Scheduler()) return nil } func printCmd(cmd string, args ...string) { fmt.Printf("Running: %s %v\n", cmd, args) } ``` -------------------------------- ### Build Go Packages with TinyGo Source: https://context7.com/tinygo-org/tinygo/llms.txt Compiles Go packages into various executable formats for different target platforms like microcontrollers and WebAssembly. Supports optimization, size reporting, and custom linker flags. Output formats include .hex, .elf, .wasm, .bin, and .uf2. ```bash # Build for microcontroller (Arduino Nano) tinygo build -target=arduino-nano -o firmware.hex ./examples/blinky # Build for WebAssembly tinygo build -target=wasm -o app.wasm ./cmd/webapp # Build with optimization and size reporting tinygo build -opt=z -size=short -o binary ./main.go # Build with custom linker flags tinygo build -ldflags="-X main.version=1.0.0" -o app ./cmd/app ``` -------------------------------- ### WASI Command-Line Tool for Word Count (Go) Source: https://context7.com/tinygo-org/tinygo/llms.txt Builds a standalone WebAssembly System Interface (WASI) application that counts lines and words from standard input and writes a summary to a file. It utilizes standard Go packages for input/output and file operations, designed to run in WASI-compatible runtimes. ```go package main import ( "bufio" "fmt" "os" "strings" ) func main() { // Read from stdin scanner := bufio.NewScanner(os.Stdin) fmt.Println("Enter lines of text (Ctrl+D to end):") lineCount := 0 wordCount := 0 for scanner.Scan() { line := scanner.Text() lineCount++ words := strings.Fields(line) wordCount += len(words) fmt.Printf("Line %d: %d words\n", lineCount, len(words)) } // Write summary to file summary := fmt.Sprintf("Total lines: %d\nTotal words: %d\n", lineCount, wordCount) err := os.WriteFile("summary.txt", []byte(summary), 0644) if err != nil { fmt.Fprintf(os.Stderr, "Error writing file: %v\n", err) os.Exit(1) } fmt.Println("Summary written to summary.txt") } // Build for WASI: // tinygo build -target=wasip1 -o wordcount.wasm ./wordcount.go // // Run with wasmtime: // echo -e "hello world\nfoo bar baz" | wasmtime run --dir=. wordcount.wasm // // Or with Node.js: // tinygo build -target=wasm -o tool.wasm ./wordcount.go // node wasm_exec.js tool.wasm ``` -------------------------------- ### Test Go Packages with TinyGo Source: https://context7.com/tinygo-org/tinygo/llms.txt Executes Go tests, including benchmarks, for specified packages. Supports various testing modes such as verbose output, short test mode, compiling test binaries without running, and running tests on microcontroller targets. Allows filtering tests by pattern and controlling execution with counts and shuffling. ```bash # Test current package tinygo test # Test specific packages with verbose output tinygo test -v ./pkg/driver ./pkg/sensor # Test with benchmarks tinygo test -bench=. -benchmem ./... # Test on microcontroller target tinygo test -target=arduino-nano ./hardware/gpio # Compile test binary without running tinygo test -c -o test.bin ./pkg/parser # Run specific tests matching pattern tinygo test -run=TestSerial -v ./pkg/uart # Short test mode for faster feedback tinygo test -short ./... # Skip tests matching pattern tinygo test -skip=TestSlow ./... # Test with custom count and shuffle tinygo test -count=3 -shuffle=on ./pkg/crypto ``` -------------------------------- ### Load and Manipulate Custom Target Specifications in Go Source: https://context7.com/tinygo-org/tinygo/llms.txt This Go code demonstrates how to programmatically load built-in target specifications, create a custom target by modifying an existing one (e.g., wasm), save it to a JSON file, and then use this custom target for building a project. It involves the 'encoding/json', 'fmt', 'os', and 'github.com/tinygo-org/tinygo/compileopts' packages. ```go package main import ( "encoding/json" "fmt" "os" "github.com/tinygo-org/tinygo/compileopts" ) func customTargetBuild() error { // Load built-in target specs, err := compileopts.GetTargetSpecs() if err != nil { return err } wasm := specs["wasm"] fmt.Printf("WASM LLVM Target: %s\n", wasm.Triple) fmt.Printf("WASM CPU: %s\n", wasm.CPU) fmt.Printf("WASM Scheduler: %s\n", wasm.Scheduler) // Create custom target by modifying existing customSpec := *wasm customSpec.GC = "conservative" customSpec.Scheduler = "none" customSpec.BuildTags = append(customSpec.BuildTags, "custom") customSpec.LDFlags = append(customSpec.LDFlags, "--initial-memory=1048576", "--max-memory=16777216", ) // Save custom target to file data, err := json.MarshalIndent(customSpec, "", " ") if err != nil { return err } err = os.WriteFile("custom-wasm.json", data, 0644) if err != nil { return err } // Use custom target in build options := &compileopts.Options{ Target: "custom-wasm.json", // Path to custom target file Opt: "z", } config, err := compileopts.NewConfig(options) if err != nil { return err } fmt.Printf("Custom target loaded: %s\n", config.Target.Triple) return nil } ``` -------------------------------- ### Run Go Programs Natively or in Emulators with TinyGo Source: https://context7.com/tinygo-org/tinygo/llms.txt Compiles and executes Go programs, either as native executables or within emulators tailored to the target platform (e.g., WebAssembly, Arduino simulators). Supports passing command-line arguments and using custom build tags. ```bash # Run native executable tinygo run ./main.go arg1 arg2 # Run WebAssembly in Node.js emulator tinygo run -target=wasm ./wasm-app.go # Run with WASI support tinygo run -target=wasip1 ./cli-tool.go --help # Run Arduino sketch in simavr emulator tinygo run -target=arduino-nano ./sketch.go # Run with custom build tags tinygo run -tags=debug,experimental ./main.go ``` -------------------------------- ### Flash Programs to Microcontrollers with TinyGo Source: https://context7.com/tinygo-org/tinygo/llms.txt Compiles and directly flashes Go programs to connected microcontroller devices. Supports automatic port detection, explicit port specification, serial monitoring, and timeout for device detection. Can also save the compiled binary to a file. ```bash # Flash to Arduino with automatic port detection tinygo flash -target=arduino-nano ./examples/blinky # Flash with explicit port specification tinygo flash -target=arduino-nano -port=/dev/ttyUSB0 ./main.go # Flash and immediately start serial monitor tinygo flash -target=arduino-nano -monitor ./main.go # Flash with timeout for mass storage device detection tinygo flash -target=circuitplay-express -timeout=30s ./game.go # Flash and save binary to file tinygo flash -target=arduino-nano -o firmware.hex ./main.go ``` -------------------------------- ### JavaScript Function to Run Go Wasm Instance Source: https://github.com/tinygo-org/tinygo/blob/release/src/examples/wasm/main/index.html This function, `run`, is designed to execute Go code compiled to WebAssembly. It clears the console, runs the Go program using `go.run(inst)`, and then re-instantiates the Wasm module to prepare for subsequent executions. This is crucial for interactive Wasm applications. ```javascript async function run() { console.clear(); await go.run(inst); inst = await WebAssembly.instantiate(mod, go.importObject); } ``` -------------------------------- ### Inject Global Variable Values in Go for Compilation Source: https://context7.com/tinygo-org/tinygo/llms.txt This Go code demonstrates how to inject compile-time values into a program, similar to Go's `-ldflags -X` mechanism. It utilizes the 'github.com/tinygo-org/tinygo/builder' and 'github.com/tinygo-org/tinygo/compileopts' packages to define global variables for different packages and then builds the project with these injected values. The injected values become string constants within the compiled binary. ```go package main import ( "github.com/tinygo-org/tinygo/builder" "github.com/tinygo-org/tinygo/compileopts" ) func buildWithGlobals() error { // Define global variable values to inject globalValues := map[string]map[string]string{ "main": { "version": "1.2.3", "buildTime": "2025-01-15T10:30:00Z", "gitCommit": "a1b2c3d4", }, "github.com/user/pkg/config": { "apiEndpoint": "https://api.prod.example.com", "apiKey": "prod-key-xyz", }, } options := &compileopts.Options{ Target: "wasm", GlobalValues: globalValues, // Inject at compile time Opt: "z", } config, err := builder.NewConfig(options) if err != nil { return err } // These values become string constants in the binary: // var version string // in main package = "1.2.3" // var apiEndpoint string // in config package = "https://..." return builder.Build(".", "app.wasm", "/tmp/build", config) } ``` -------------------------------- ### I2S Interface for Audio Communication in Go Source: https://github.com/tinygo-org/tinygo/wiki/Machine-API Facilitates audio data transfer between chips, implementing io.Reader, io.Writer, and io.Closer. Configuration options include pins for SCK, WS, SD, and various audio format settings. The interface supports reading and writing slices of uint32. ```go package machine import "io" // Pin represents a digital pin. type Pin interface { // Value returns the pin's value (0 or 1). Value() int // High sets the pin to high (1). High() // Low sets the pin to low (0). Low() // // Toggles the pin's value. // Toggle() // // Configure as input. // Configure(mode PinMode) } // I2SMode represents the operating mode for I2S. type I2SMode int // I2SStandard represents the I2S standard used. type I2SStandard int // I2SClockSource represents the clock source for I2S. type I2SClockSource int // I2SDataFormat represents the data format for I2S. type I2SDataFormat int // I2SConfig all fields are optional and may not be required or used on a particular platform. type I2SConfig struct { SCK Pin WS Pin SD Pin Mode I2SMode Standard I2SStandard ClockSource I2SClockSource DataFormat I2SDataFormat AudioFrequency uint32 MasterClockOutput bool } // I2SReadWriteCloser supports the io.ReadWriteCloser interface for I2S audio data. type I2SReadWriteCloser interface { Configure(I2SConfig) Read(p []uint32) (n int, err error) Write(p []uint32) (n int, err error) Close() error } // var I2S0 machine.I2SReadWriteCloser // implementation defined ``` -------------------------------- ### Build WASI Shared Library using Go Environment Variables Source: https://github.com/tinygo-org/tinygo/blob/release/README.md This shell command compiles a TinyGo program into a WebAssembly shared library (.wasm) using Go's environment variables for target specification. It achieves the same result as the previous command but utilizes GOARCH and GOOS for targeting WASI Preview 1. ```shell GOARCH=wasip1 GOOS=wasm tinygo build -buildmode=c-shared -o add.wasm add.go ``` -------------------------------- ### WASI Addition Function with TinyGo Source: https://github.com/tinygo-org/tinygo/blob/release/README.md This Go program defines an exported function 'add' for WebAssembly System Interface (WASI) environments. It takes two uint32 arguments and returns their sum. This allows the compiled WebAssembly module to be used by WASI-compatible runtimes. ```go package main //go:wasmexport add func add(x, y uint32) uint32 { return x + y } ``` -------------------------------- ### Build WASI Shared Library with TinyGo CLI Source: https://github.com/tinygo-org/tinygo/blob/release/README.md This shell command compiles a TinyGo program into a WebAssembly shared library (.wasm) suitable for WASI Preview 1 runtimes. It specifies the output file name and the target as 'wasip1'. ```shell tinygo build -buildmode=c-shared -o add.wasm -target=wasip1 add.go ``` -------------------------------- ### TinyGo Pin Configuration and Control Source: https://github.com/tinygo-org/tinygo/wiki/Machine-API Defines the structure and methods for configuring and controlling GPIO pins in TinyGo. It supports setting pin modes, reading/writing digital values, and configuring PWM and ADC functionalities. Platform-specific implementations are expected. ```go type Pin struct { // depends on the platform } type PinMode ... // type depends on the platform const ( // values depend on the platform PinOutput PinMode = ... PinInput PinMode = ... ) // Pin configuration. More fields may be added in the future, but the zero // value must do the expected thing - e.g. pull configuration must default to // 'no pull'. type PinConfig struct { Mode PinMode } // Initialize PWM on platforms that need such a thing. func InitPWM() // Configures pin mode and possibly other settings. func (p Pin) Configure(config PinConfig) // Sets the pin to high or low when configured as output. func (p Pin) Set(high bool) // Gets the current value of the pin. Pin must be configured as input pin. func (p Pin) Get() bool // Enables PWM with the given duty cycle. Pin must be configured as output pin. func (p Pin) SetPWM(dutycycle uint16) // Sets the frequency for this PWM. This may be a no-op on some platforms. func (p Pin) SetPWMFrequency(...) // Reads a number from the ADC. Pin must be configured as input pin. func (p Pin) ReadADC() uint16 ``` -------------------------------- ### UART Interface for Serial Communication in Go Source: https://github.com/tinygo-org/tinygo/wiki/Machine-API Implements io.Reader and io.Writer, supporting byte-level read/write operations similar to bufio. Configuration includes baud rate, RX, TX, RTS, and CTS pins. Not all configurations may be supported on all platforms. ```go package machine import "io" // Pin represents a digital pin. type Pin interface { // Value returns the pin's value (0 or 1). Value() int // High sets the pin to high (1). High() // Low sets the pin to low (0). Low() // // Toggles the pin's value. // Toggle() // // Configure as input. // Configure(mode PinMode) } // UARTConfig configuration. Some fields may be unavailable on some platforms. type UARTConfig struct { BaudRate uint32 RX Pin TX Pin RTS Pin CTS Pin } // UARTInterface defines the methods for a UART peripheral. type UARTInterface interface { Configure(UARTConfig) io.ReadWriter ReadByte() (byte, error) // like bufio.Reader WriteByte(c byte) error // like bufio.Writer } // Example of a minimal UARTConfig // type UARTConfig struct { // BaudRate uint32 // the only required field // } // var UART0 machine.UART // implementation defined ``` -------------------------------- ### TinyGo I2C Interface for Communication Source: https://github.com/tinygo-org/tinygo/wiki/Machine-API Provides an interface for interacting with I2C buses. It requires `Configure` and `Tx` methods, with optional convenience methods for register read/write operations. Platform-specific implementations define the actual I2C bus instance. ```go // All fields are optional and may be left out on a particular platform. type I2CConfig struct { Frequency uint32 SCL Pin SDA Pin } var I2C0 = ... // implementation defined // Not a real exported type, just here to serve as example. type I2C interface { Configure(I2CConfig) Tx(addr uint16, w, r []byte) error } // Convenience methods (added to the interface if supported by the implementation) // WriteRegister(address uint8, register uint8, data []byte) error // ReadRegister(address uint8, register uint8, data []byte) error ```