安装 Tinygo

在 Ubuntu 上安装开发环境,其他环境见参考

# x86_64
wget https://github.com/tinygo-org/tinygo/releases/download/v0.17.0/tinygo_0.17.0_amd64.deb
sudo dpkg -i tinygo_0.17.0_amd64.deb
# arm
wget https://github.com/tinygo-org/tinygo/releases/download/v0.17.0/tinygo_0.17.0_arm.deb
sudo dpkg -i tinygo_0.17.0_arm.deb

配置环境变量

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

验证安装成功

tinygo version

安装 esp32 环境

# install dep
sudo apt-get install git wget make libncurses-dev flex bison gperf
pip3 install pyserial

# install esp32 toolchain
wget https://dl.espressif.com/dl/xtensa-esp32-elf-linux64-1.22.0-80-g6c4433a-5.2.0.tar.gz -P ~/
mkdir -p ~/esp
cd ~/esp
tar -xzf ~/xtensa-esp32-elf-linux64-1.22.0-80-g6c4433a-5.2.0.tar.gz

# add env path
export PATH="$PATH:$HOME/esp/xtensa-esp32-elf/bin"

# install esptool
pip3 install esptool

烧录 esp32 程序

可以用 usb 连接 esp32,也可以 ttl 转 usb 线,我用的是 ttl-usb,将连接 esp 对应的 RX 和 TX 串口,自己使用串口线烧录时需要同时按住两个板载按键。

烧录完成后,按 en 使能键,程序开始运行。

# chmod /dev/ttyUSB0
sudo chmod  666 /dev/ttyUSB0

# flash example program
tinygo flash -target=esp32-mini32 -port=/dev/ttyUSB0 examples/blinky1

example/blinky1 代码在/usr/local/lib/tinygo/src 目录下

也可以编写自己的程序进行烧录,将下面程序保存在/tmp/blink/blink.go

 package main

 // This is the most minimal blinky example and should run almost everywhere.

 import (
     "machine"
     "time"
 )

 func main() {
     led := machine.LED
     led.Configure(machine.PinConfig{Mode: machine.PinOutput})
     for {
         led.Low()
         time.Sleep(time.Millisecond * 300)

         led.High()
         time.Sleep(time.Millisecond * 2000)
     }
 }

编译并烧录

tinygo flash -target=esp32-mini32 -port=/dev/ttyUSB0 /tmp/blink/blink.go

Tinygo 对 esp32 支持情况

当前 tinygo 对 esp32 的支持还很不完善,比较鸡肋,不支持 goroutine,不支持网络和蓝牙等。相比 arduino 和 micropython,实用性不强。

InterfaceHardware SupportedTinyGo Support
GPIOYESYES
UARTYESYES
SPIYESYES
I2CYESNot Yet
ADCYESNot Yet
PWMYESNot Yet
WiFiYESNot Yet
BluetoothYESNot Yet

参考

https://tinygo.org/getting-started/linux/

https://docs.espressif.com/projects/esp-idf/en/release-v3.0/get-started/linux-setup.html#standard-setup-of-toolchain-for-linux