Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gpio: improve the module and add support for PORTD #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 58 additions & 3 deletions src/gpio.zig
Original file line number Diff line number Diff line change
@@ -1,12 +1,67 @@
const regs = @import("atmega328p.zig").registers;

/// For now only supports PORTB
pub fn init(comptime pin: u8, comptime dir: enum { in, out }) void {
const MODE = enum { in, out };

// PORTB: pins D8 to D13
fn init_portb(pin: u3, comptime dir: MODE) void {
regs.PORTB.DDRB.* = @as(u8, @intFromEnum(dir)) << pin;
}

pub fn toggle(comptime pin: u8) void {
pub fn toggle_portb(comptime pin: u3) void {
var val = regs.PORTB.PORTB.*;
val ^= 1 << pin;
regs.PORTB.PORTB.* = val;
}

// PORTD: pins D0 TO D7
fn init_portd(pin: u3, comptime dir: MODE) void {
regs.PORTD.DDRD.* = @as(u8, @intFromEnum(dir)) << pin;
}

pub fn toggle_portd(comptime pin: u3) void {
var val = regs.PORTD.PORTD.*;
val ^= 1 << pin;
regs.PORTD.PORTD.* = val;
}

// TODO: PORTC: analog pins

pub const PIN = enum {
D0,
D1,
D2,
D3,
D4,
D5,
D6,
D7,
D8,
D9,
D10,
D11,
D12,
D13,
A0,
A1,
A3,
A4,
A5,
};

pub fn init(comptime pin: PIN, comptime dir: MODE) void {
const i = @intFromEnum(pin);
if (i <= 7) {
init_portd(@as(u3, @intCast(i)), dir);
} else if (i >= 8 and i <= 13) {
init_portb(@as(u3, @intCast(i - 8)), dir);
}
}

pub fn toggle(comptime pin: PIN) void {
const i = comptime @intFromEnum(pin);
if (i <= 7) {
toggle_portd(@as(u3, @intCast(i)));
} else if (i >= 8 and i <= 13) {
toggle_portb(@as(u3, @intCast(i - 8)));
}
}
6 changes: 4 additions & 2 deletions src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ pub fn main() void {
// var x: u8 = 255;
// x += 1;

gpio.init(5, .out);
gpio.init(.D13, .out);
gpio.init(.D5, .out);

while (true) {
uart.write_ch(ch);
Expand All @@ -41,7 +42,8 @@ pub fn main() void {
uart.write("\r\n");
}

gpio.toggle(5);
gpio.toggle(.D13);
gpio.toggle(.D5);
delay_cycles(50000);
}
}
Expand Down