So I tried using packed structs for my bit fields, and I am a bit stuck on how to use them properly.
My example code:
pub const pin = packed struct(u8) {
p0: bool = false,
p1: bool = false,
p2: bool = false,
p3: bool = false,
p4: bool = false,
p5: bool = false,
p6: bool = false,
p7: bool = false,
pub fn val(self: pin) u8 {
return @bitCast(self);
}
};
const gpio_s = packed struct {
pin: u8,
dir: u8,
port: u8,
};
pub const gpio: *volatile gpio_s = @ptrFromInt(0x23);
export fn app_main() void {
var pp = pin.val(.{ .p5 = true });
gpio.dir |= pp;
while (true) {
gpio.port ^= pp;
// dump loop
for (0..1000) |_| {
for (0..200) |_| {
asm volatile ("nop");
}
}
}
}
What I want to do is basically what we do in C but nicer, e.g. either gpio.dir |= pin.p5 | pin.p6 | ... or (what I tried to do now) gpio.dir |= pin.val( .{ .p5 = true }); but that didn't work, instead I had to save struct as a temporary variable, pp in this case, and then do gpio.dir |= pp which is not as neat. Why do I have to save the value in a variable first?
Also, is there an even nicer/cleaner way of doing this?