Specialist › Make AVR firmware

Specialist

AVR firmware: Uno, Nano and Mega

An Arduino Uno or Nano has an ATmega328P. A Mega has an ATmega2560. A board whose processor says compute { hal avr; chip "atmega328p" } gets real firmware from archec gen --target c. It is bare-metal C on avr-libc. You build it with avr-gcc and flash it with avrdude through the board's bootloader.

This page makes a blink, a button and a servo on an Uno. Then it says what is generated, which pins and devices the C drives, and what it does not do.

Why C and avr-libc#

There were two ways to build for an AVR:

  • the C target with avr-libc: avr-gcc, a Makefile, avrdude;
  • Rust with avr-hal (the arduino-hal crate) on a nightly toolchain.

arche-lang uses the first. The reasons:

  • The C target already writes each component, its state machine and the wiring of a deployment as C99 with no heap. Only the platform under it is new: a small HAL and a runtime.
  • The Embassy target is built on embassy-executor and the embassy HALs. They have no AVR HAL, so the Rust route would be a second Rust generator.
  • avr-hal needs a nightly Rust, and it links with avr-gcc anyway. The C route needs avr-gcc alone.
  • Without avr-gcc, the tests compile the same C with the host's compiler against small stubs of avr-libc's headers, and run it.

What to wire on the Uno:

Device Pin Notes
the LED D13 the Uno's own LED is on it
a push button D2 and GND no resistor: the pin's pull-up holds it high
an SG90 servo D9 (signal), 5V, GND D9 is on Timer1, which gives the 50 Hz pulse

The model, in main.arche:

project Blink { version "0.1.0"; uses arche-hw-store "^0.1" }
include "arche-hw-store/boards/arduino-uno-r3/arduino-uno-r3.arche"
include "arche-hw-store/devices/led/led.arche"
include "arche-hw-store/devices/button/button.arche"
include "arche-hw-store/devices/sg90/sg90.arche"

/// Blinks the LED every 500 ms. Each press of the button swings the servo to its other end.
component Panel "Blink, button, servo" {
  out led:    requires Led
  out button: requires Button
  out arm:    requires Servo
  var ticks:  uint32   = 0
  var was:    bool     = false
  var up:     bool     = false

  fn step ```arche
    ticks += 1
    if ticks % 5 == 0 {
      led.toggle()
    }
    let pressed = button.pressed()
    if pressed && !was {
      up = !up
      if up {
        arm.move(3.14159)
      } else {
        arm.move(0.0)
      }
    }
    was = pressed
  ```
}

system Bench {
  part board:  ArduinoUnoR3
  part led:    GpioLed    { in pin { pins { pin D13 } } }
  part button: GpioButton { out pin { pins { pin D2 } } }
  part servo:  Sg90       { in pin { pins { pin D9 } } }
  part panel:  Panel
  panel.led    -> led.led
  panel.button -> button.button
  panel.arm    -> servo.servo
}

deployment OnUno {
  system Bench
  binary fw on board {
    thread main { runs panel; period 100ms; step step }
  }
}
Diagram: Bench
What archec draws from this code: Bench
Try it

The thread runs step every 100 ms. Every fifth step toggles the LED. A press is a change from released to pressed, so holding the button does nothing more.

Each device says its pin on its own port. You can also link it to a port of the board that says its pin, as board.d13 -> led.pin.

Run it in the simulator first: archec sim main.arche.

2. Generate#

archec gen main.arche --target c

The note says where each device is:

note: binary fw: 3 device(s) on the atmega328p (hw.c): led on D13; button on D2; servo on D9

3. Build and flash#

cd generated/c/fw
make                       # fw.elf, fw.hex and their size
make flash PORT=/dev/ttyACM0

make flash runs avrdude with the Uno's bootloader (-c arduino -b 115200).

  • A Mega uses -c wiring.
  • An old Nano has the old bootloader: make flash BAUD=57600.
  • On macOS the port is /dev/cu.usbmodem… or /dev/cu.usbserial….

archec gen --target flash writes flash/fw/flash.sh, which runs the same avrdude on c/fw/fw.elf. Set the port with ARCHE_PORT.

The log (log in a body) goes to the USB serial at 115200 baud. Read it with screen /dev/ttyACM0 115200 or the serial monitor of your choice.

What is generated#

File What it is Rewritten
c/arche_avr.h, c/arche_avr.c the HAL: GPIO, PWM, the servo pulse, the ADC, USART0, the TWI (I²C) master, the time yes
c/arche_rt_avr.c arche_rt.h on the HAL: the time, a busy wait, the log, the queues no: yours once written
c/fw/hw.h, c/fw/hw.c the devices of the platform, one C function per function of the device yes
c/fw/wiring.c the parts, the queues, the threads as turns, fw_start and fw_poll yes
c/fw/main.c fw_start(), then fw_poll() for ever no
c/fw/Makefile avr-gcc for the chip, make flash with avrdude yes

The parts' own C (c/panel.c here) is the same as on any other target.

Threads without an RTOS#

The AVR has no RTOS here. Each thread of the deployment becomes one turn that never waits:

  • a periodic thread returns until its period has come, then runs its step;
  • a thread that receives takes the messages that wait in its queue;
  • a part's timers (after, watchdogs) are checked at each turn.

fw_poll runs every thread's turn, highest priority first. main calls it in a loop. A long step delays the threads after it. A fn main that loops for ever runs once, at the first turn of its thread, and the threads after it never run.

The queues live in a static arena of 320 bytes on the ATmega328P and 1024 on the ATmega2560. Build with -DARCHE_QUEUE_ARENA=<bytes> for more. A queue that does not fit is logged and its messages are dropped.

Pins#

A pin is written in the datasheet's name or the Arduino's:

Written Is
PB5 port B, bit 5
D13, 13 the Arduino pin: PB5 on the Uno and the Nano, PB7 on the Mega
A0 the analog pin: PC0 (ADC0) on the Uno, PF0 (ADC0) on the Mega
A6, ADC6 an analog input only (the Nano's A6 and A7)

PWM and the servo pulse need a timer's pin:

Chip 8-bit timers (about 1 kHz PWM) 16-bit timers (50 Hz, servos)
ATmega328P D5, D6 (Timer0), D3, D11 (Timer2) D9, D10 (Timer1)
ATmega2560 D4, D13 (Timer0), D9, D10 (Timer2) D11, D12, D13 (Timer1), D2, D3, D5 (Timer3), D6, D7, D8 (Timer4), D44, D45, D46 (Timer5)

Timer0 also counts the time, so its PWM runs at about 976 Hz and you cannot change its clock.

Devices#

A device is driven when one of its ports provides one of these interfaces, or when it has an analog pin:

Interface Store devices In C
Led, Relay, Buzzer GpioLed, GpioRelay, GpioBuzzer an output: on, off, toggle, state; brightness dims on a PWM pin
Button GpioButton an input with its pull-up: pressed is true when the pin reads low
Servo Sg90, HobbyServo, Mg996r a pulse every 20 ms: move(angle) in rad, 0 to π; the pulse range is the store's driver's
an analog pin AnalogSensor, PotModule, a potentiometer of your own raw_value(), 0 to 1023 against AVcc; value(), 0 to 1; angle() when the device says its turn (hardware {range: {min: 0rad, max: 5.236rad}})

Any other device is left out with a note. A part with only power ports (a battery) or a level shifter needs no driver, and is left out silently. On a platform with two boards, a device wired to the other board is that board's binary's. Drive it yourself in drivers.c with the functions of arche_avr.h. For an I²C device, call arche_i2c_init(100000) once, then arche_i2c_write, arche_i2c_read and arche_i2c_write_read. Each waits a bounded time and gives false when the device does not answer.

A link routed over a uart bus sends its frames on USART0, the same line as the log.

ESP8266#

A board with compute { hal esp8266; chip "esp8266" } is for the model, the checks and the simulation. There is no firmware for it: the C target writes a host's C and says so, and the Embassy target leaves the binary out. The ESP8266 needs the ESP8266_RTOS_SDK, a toolchain and an SDK of its own. In Rust, esp-hal does not support it, and the older esp8266-hal crate is no longer maintained. Neither fits the C target cleanly.

Limits#

What it does not do yet:

  • No RTOS and no preemption: the threads take turns (see above).
  • --trace and --monitors are not generated for hal avr.
  • double is 32 bits in avr-gcc unless you build with -mdouble=64, so a float64 of the model has a float's precision on the chip.
  • The store's I²C and SPI devices (a BME280, an SSD1306) have no C driver. The TWI master is there for yours. There is no SPI in the HAL.
  • tone(frequency, duration) of a buzzer is not generated.
  • The chips are the ATmega328P and the ATmega2560. Another ATmega is built with its -mmcu, but on the ATmega328P's pins.
  • Nothing here has run on a board in arche-lang's tests. Without avr-gcc, the C is compiled and run on the host against stubs of avr-libc's registers.