nrf/twim: add examples

This commit is contained in:
Dario Nieuwenhuis 2021-05-26 18:15:37 +02:00
parent 8dfb6dff86
commit 11f9ad6867
2 changed files with 89 additions and 0 deletions

View File

@ -0,0 +1,35 @@
//! Example on how to read a 24C/24LC i2c eeprom.
//!
//! Connect SDA to P0.03, SCL to P0.04
#![no_std]
#![no_main]
#![feature(min_type_alias_impl_trait)]
#![feature(impl_trait_in_bindings)]
#![feature(type_alias_impl_trait)]
#![allow(incomplete_features)]
#[path = "../example_common.rs"]
mod example_common;
use defmt::{panic, *};
use embassy::executor::Spawner;
use embassy_nrf::twim::{self, Twim};
use embassy_nrf::{interrupt, Peripherals};
const ADDRESS: u8 = 0x50;
#[embassy::main]
async fn main(_spawner: Spawner, p: Peripherals) {
info!("Initializing TWI...");
let config = twim::Config::default();
let irq = interrupt::take!(SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0);
let mut twi = Twim::new(p.TWISPI0, irq, p.P0_03, p.P0_04, config);
info!("Reading...");
let mut buf = [0u8; 16];
twi.write_then_read(ADDRESS, &mut [0x00], &mut buf).unwrap();
info!("Read: {=[u8]:x}", buf);
}

View File

@ -0,0 +1,54 @@
//! Example on how to read a 24C/24LC i2c eeprom with low power consumption.
//! The eeprom is read every 1 second, while ensuring lowest possible power while
//! sleeping between reads.
//!
//! Connect SDA to P0.03, SCL to P0.04
#![no_std]
#![no_main]
#![feature(min_type_alias_impl_trait)]
#![feature(impl_trait_in_bindings)]
#![feature(type_alias_impl_trait)]
#![allow(incomplete_features)]
#[path = "../example_common.rs"]
mod example_common;
use core::mem;
use defmt::{panic, *};
use embassy::executor::Spawner;
use embassy::time::{Duration, Timer};
use embassy_nrf::twim::{self, Twim};
use embassy_nrf::{interrupt, Peripherals};
const ADDRESS: u8 = 0x50;
#[embassy::main]
async fn main(_spawner: Spawner, mut p: Peripherals) {
info!("Started!");
let mut irq = interrupt::take!(SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0);
loop {
info!("Initializing TWI...");
let config = twim::Config::default();
// Create the TWIM instance with borrowed singletons, so they're not consumed.
let mut twi = Twim::new(&mut p.TWISPI0, &mut irq, &mut p.P0_03, &mut p.P0_04, config);
info!("Reading...");
let mut buf = [0u8; 16];
twi.write_then_read(ADDRESS, &mut [0x00], &mut buf).unwrap();
info!("Read: {=[u8]:x}", buf);
// Drop the TWIM instance. This disables the peripehral and deconfigures the pins.
// This clears the borrow on the singletons, so they can now be used again.
mem::drop(twi);
// Sleep for 1 second. The executor ensures the core sleeps with a WFE when it has nothing to do.
// During this sleep, the nRF chip should only use ~3uA
Timer::after(Duration::from_secs(1)).await;
}
}