Skip to content

I2C support #99

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

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
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
3 changes: 3 additions & 0 deletions docgen/prj.conf
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,6 @@ CONFIG_GPIO=y
CONFIG_GPIO_ENABLE_DISABLE_INTERRUPT=y
CONFIG_PRINTK=y
CONFIG_POLL=y
CONFIG_I2C=y
CONFIG_I2C_RTIO=y
CONFIG_RTIO=y
26 changes: 26 additions & 0 deletions dt-rust.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@
raw: !Phandle gpios
device: crate::device::gpio::GpioPin

# Hook up the gpio-keys as gpio pins as well
- name: gpio-keys
rules:
- !Compatible
names:
- gpio-keys
level: 1
actions:
- !Instance
raw: !Phandle gpios
device: crate::device::gpio::GpioPin

# Flash controllers don't have any particular property to identify them, so we need a list of
# compatible values that should match.
- name: flash-controller
Expand All @@ -36,6 +48,8 @@
- "nordic,nrf52-flash-controller"
- "nordic,nrf51-flash-controller"
- "raspberrypi,pico-flash-controller"
- "st,stm32g4-flash-controller"
- "st,stm32l5-flash-controller"
- "zephyr,sim-flash"
level: 0
actions:
Expand Down Expand Up @@ -64,6 +78,18 @@
- !Reg
device: "crate::device::flash::FlashPartition"

# I2C.
- name: i2c
rules:
- !Compatible
names:
- "snps,designware-i2c"
level: 0
actions:
- !Instance
raw: !Myself
device: crate::device::i2c::I2C

# Generate a pseudo node that matches all of the labels across the tree with their nodes.
- name: labels
rules: !Root
Expand Down
6 changes: 5 additions & 1 deletion tests/drivers/gpio-async/prj.conf
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,8 @@ CONFIG_RUST_ALLOC=y
CONFIG_GPIO=y
CONFIG_GPIO_ENABLE_DISABLE_INTERRUPT=y

CONFIG_LOG_BACKEND_RTT=n
# CONFIG_LOG_BACKEND_RTT=n

CONFIG_UART_CONSOLE=n
CONFIG_RTT_CONSOLE=y
CONFIG_USE_SEGGER_RTT=y
5 changes: 5 additions & 0 deletions tests/drivers/gpio-async/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,18 @@ async fn main(spawner: Spawner) {
info!("Hello world");
let _ = spawner;

/*
let mut col0 = zephyr::devicetree::labels::col0::get_instance().unwrap();
let mut row0 = zephyr::devicetree::labels::row0::get_instance().unwrap();
*/
let mut row0 = zephyr::devicetree::aliases::sw0::get_instance().unwrap();
let mut gpio_token = unsafe { zephyr::device::gpio::GpioToken::get_instance().unwrap() };

unsafe {
/*
col0.configure(&mut gpio_token, GPIO_OUTPUT_ACTIVE);
col0.set(&mut gpio_token, true);
*/
row0.configure(&mut gpio_token, GPIO_INPUT | GPIO_PULL_DOWN);
}

Expand Down
4 changes: 4 additions & 0 deletions zephyr-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,13 @@ fn main() -> Result<()> {
.derive_copy(false)
.allowlist_function("k_.*")
.allowlist_function("gpio_.*")
.allowlist_function("i2c_.*")
.allowlist_function("flash_.*")
.allowlist_function("zr_.*")
.allowlist_function("mpsc_.*")
.allowlist_function("rtio.*")
.allowlist_item("GPIO_.*")
.allowlist_item("I2C_.*")
.allowlist_item("FLASH_.*")
.allowlist_item("Z_.*")
.allowlist_item("ZR_.*")
Expand Down
9 changes: 9 additions & 0 deletions zephyr-sys/wrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ extern int errno;
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/drivers/flash.h>
#include <zephyr/irq.h>
#include <zephyr/drivers/i2c.h>
#include <zephyr/rtio/rtio.h>
#include <zephyr/sys/mpsc_lockfree.h>

/*
* bindgen will only output #defined constants that resolve to simple numbers. These are some
Expand All @@ -63,6 +66,12 @@ const uint32_t ZR_GPIO_INT_MODE_DISABLE_ONLY = GPIO_INT_MODE_DISABLE_ONLY;
const uint32_t ZR_GPIO_INT_MODE_ENABLE_ONLY = GPIO_INT_MODE_ENABLE_ONLY;
#endif

const uint8_t ZR_I2C_MSG_WRITE = I2C_MSG_WRITE;
const uint8_t ZR_I2C_MSG_READ = I2C_MSG_READ;
const uint8_t ZR_I2C_MSG_STOP = I2C_MSG_STOP;

const uint16_t ZR_RTIO_SQE_NO_RESPONSE = RTIO_SQE_NO_RESPONSE;

/*
* Zephyr's irq_lock() and irq_unlock() are macros not inline functions, so we need some inlines to
* access them.
Expand Down
1 change: 1 addition & 0 deletions zephyr/src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::sync::atomic::{AtomicBool, Ordering};

pub mod flash;
pub mod gpio;
pub mod i2c;

// Allow dead code, because it isn't required for a given build to have any devices.
/// Device uniqueness.
Expand Down
6 changes: 5 additions & 1 deletion zephyr/src/device/gpio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ mod async_io {
ZR_GPIO_INT_MODE_DISABLE_ONLY,
};

use crate::sync::atomic::{AtomicBool, AtomicU32};
use crate::{
printkln,
sync::atomic::{AtomicBool, AtomicU32},
};

use super::{GpioPin, GpioToken};

Expand Down Expand Up @@ -112,6 +115,7 @@ mod async_io {
cb: *mut gpio_callback,
mut pins: gpio_port_pins_t,
) {
printkln!("GPIO callback: {}", pins);
let data = unsafe {
cb.cast::<u8>()
.sub(mem::offset_of!(Self, callback))
Expand Down
100 changes: 100 additions & 0 deletions zephyr/src/device/i2c.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
//! Zpehyr I2C interface

use core::{ffi::c_int, marker::PhantomData};

use crate::{error::to_result, printkln, raw};

use super::{NoStatic, Unique};

/// A single I2C controller.
pub struct I2C {
/// The underlying device itself.
#[allow(dead_code)]
pub(crate) device: *const raw::device,
}

unsafe impl Send for I2C {}

impl I2C {
/// Constructor, used by the devicetree generated code.
#[allow(dead_code)]
pub(crate) unsafe fn new(
unique: &Unique,
_data: &'static NoStatic,
device: *const raw::device,
) -> Option<Self> {
if !unique.once() {
return None;
}
Some(I2C { device })
}

/// Do a write/read.
pub fn write_read(&mut self, write: &[u8], read: &mut [u8]) -> crate::Result<c_int> {
let mut msg = [
raw::i2c_msg {
buf: write.as_ptr() as *mut _,
len: write.len() as u32,
flags: raw::ZR_I2C_MSG_WRITE,
},
raw::i2c_msg {
buf: read.as_mut_ptr(),
len: read.len() as u32,
flags: raw::ZR_I2C_MSG_READ | raw::ZR_I2C_MSG_STOP,
},
];
let res = unsafe { to_result(raw::i2c_transfer(self.device, msg.as_mut_ptr(), 2, 0x42)) };

printkln!("res: {} {}", msg[1].len, msg[1].flags);

res
}

/// Add an i2c operation to the RTIO.
///
/// TODO: Unclear how to indicate that the buffers must live long enough for the submittion.
/// As it is, this is actually completely unsound.
pub fn rtio_write_read(&mut self, write: &[u8], read: &mut [u8]) -> crate::Result<()> {
let _msg = [
raw::i2c_msg {
buf: write.as_ptr() as *mut _,
len: write.len() as u32,
flags: raw::ZR_I2C_MSG_WRITE,
},
raw::i2c_msg {
buf: read.as_mut_ptr(),
len: read.len() as u32,
flags: raw::ZR_I2C_MSG_READ | raw::ZR_I2C_MSG_STOP,
},
];

todo!()
}
}

/// An i2c transaction.
pub struct ReadWrite<'a> {
_phantom: PhantomData<&'a ()>,
msgs: [raw::i2c_msg; 2],
}

impl<'a> ReadWrite<'a> {
/// Construct a new read/write transaction.
pub fn new(write: &'a [u8], read: &'a mut [u8]) -> Self {
Self {
_phantom: PhantomData,
msgs: [
raw::i2c_msg {
buf: write.as_ptr() as *mut _,
len: write.len() as u32,
flags: raw::ZR_I2C_MSG_WRITE,
},
raw::i2c_msg {
buf: read.as_mut_ptr(),
len: read.len() as u32,
flags: raw::ZR_I2C_MSG_READ | raw::ZR_I2C_MSG_STOP,
},
],
}
}
}
2 changes: 2 additions & 0 deletions zephyr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ pub mod embassy;
pub mod error;
pub mod logging;
pub mod object;
#[cfg(CONFIG_RTIO)]
pub mod rtio;
#[cfg(CONFIG_RUST_ALLOC)]
pub mod simpletls;
pub mod sync;
Expand Down
Loading
Loading