Skip to content

Instantly share code, notes, and snippets.

@erdeszt
Last active March 8, 2021 15:28
Show Gist options
  • Save erdeszt/f380b3dd0696180daec9bebf2c7cc146 to your computer and use it in GitHub Desktop.
Save erdeszt/f380b3dd0696180daec9bebf2c7cc146 to your computer and use it in GitHub Desktop.
Zig on AVR demo
const Direction = packed enum (u1) {
Output = 0,
Input = 1,
};
const Level = packed enum(u1) {
Low = 0,
High = 1,
};
const Bit = packed enum(u8) {
_0 = 1,
_1 = 1 << 1,
_2 = 1 << 2,
_3 = 1 << 3,
_4 = 1 << 4,
_5 = 1 << 5,
_6 = 1 << 6,
_7 = 1 << 7,
};
const GPIO = packed struct {
input: u8,
direction: u8,
output: u8,
pub fn setDirection(self: *volatile GPIO, bit: Bit, comptime direction: Direction) void {
switch (direction) {
Direction.Input => self.direction &= ~@enumToInt(bit), // TODO: Fix
Direction.Output => self.direction |= @enumToInt(bit),
}
}
pub fn write(self: *volatile GPIO, bit: Bit, level: Level) void {
switch (level) {
Level.Low => self.output &= ~@enumToInt(bit), // TODO: Fix
Level.High => self.output |= @enumToInt(bit), // TODO: Fix
}
}
pub fn read(self: *volatile GPIO, bit: Bit) Level {
return @intToEnum(Level, @boolToInt((self.input & @enumToInt(bit)) != 0));
}
};
const GPIOB = @intToPtr(*volatile GPIO, 0x23); // TODO: Volatile
export fn main() noreturn {
GPIOB.setDirection(Bit._1, Direction.Input);
GPIOB.setDirection(Bit._2, Direction.Output);
GPIOB.write(Bit._2, Level.High);
const input = GPIOB.read(Bit._1);
GPIOB.write(Bit._2, input);
while (true) {}
}
gpio.o: file format elf32-avr
Disassembly of section .text:
00000000 <main>:
0: 21 98 cbi 0x04, 1 ; 4
2: 22 9a sbi 0x04, 2 ; 4
4: 2a 9a sbi 0x05, 2 ; 5
6: 83 b1 in r24, 0x03 ; 3
8: 88 0f add r24, r24
a: 84 70 andi r24, 0x04 ; 4
c: 95 b1 in r25, 0x05 ; 5
e: 9b 7f andi r25, 0xFB ; 251
10: 98 2b or r25, r24
12: 95 b9 out 0x05, r25 ; 5
14: 00 c0 rjmp .+0 ; 0x16 <main+0x16>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment