interrupt stuff that doesn't work

This commit is contained in:
Andy Killorin 2024-10-29 22:44:47 -04:00
parent 17fee3dc7d
commit 311b0c1599
Signed by: ank
GPG key ID: 23F9463ECB67FE8C
7 changed files with 2852 additions and 0 deletions

View file

@ -0,0 +1,10 @@
#[target.'cfg(all(target_arch = "arm", target_os = "none"))']
#runner = "probe-rs run --chip RP2040"
[target.'cfg(all(target_arch = "arm", target_os = "none"))']
runner = "elf2uf2-rs --deploy --serial --verbose"
[build]
target = "thumbv6m-none-eabi" # Cortex-M0 and Cortex-M0+
[env]
DEFMT_LOG = "debug"

1
outside/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
target

2479
outside/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

71
outside/Cargo.toml Normal file
View file

@ -0,0 +1,71 @@
[package]
edition = "2021"
name = "outside"
version = "0.1.0"
license = "MIT OR Apache-2.0"
[dependencies]
embassy-executor = { version = "0.6.0", git="https://github.com/embassy-rs/embassy", features = ["task-arena-size-98304", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] }
embassy-time = { version = "0.3.2", git="https://github.com/embassy-rs/embassy", features = ["defmt", "defmt-timestamp-uptime"] }
embassy-rp = { version = "0.2.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl", "rp2040"] }
embassy-usb = { version = "0.3.0", git="https://github.com/embassy-rs/embassy", features = ["defmt"] }
embassy-net = { version = "0.4.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet", "dns"] }
embassy-net-wiznet = { version = "0.1.0", git="https://github.com/embassy-rs/embassy", features = ["defmt"] }
embassy-futures = { version = "0.1.0", git="https://github.com/embassy-rs/embassy"}
embassy-usb-logger = { version = "0.2.0", git="https://github.com/embassy-rs/embassy" }
cyw43 = { version = "0.2.0", git="https://github.com/embassy-rs/embassy", features = ["defmt", "firmware-logs", "bluetooth"] }
cyw43-pio = { version = "0.2.0", git="https://github.com/embassy-rs/embassy", features = ["defmt"] }
defmt = "0.3"
defmt-rtt = "0.4"
fixed = "1.23.1"
fixed-macro = "1.2"
# for web request example
reqwless = { version = "0.12.0", features = ["defmt",]}
serde = { version = "1.0.203", default-features = false, features = ["derive"] }
serde-json-core = "0.5.1"
# for assign resources example
assign-resources = { git = "https://github.com/adamgreig/assign-resources", rev = "94ad10e2729afdf0fd5a77cd12e68409a982f58a" }
#cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] }
cortex-m = { version = "0.7.6", features = ["inline-asm"] }
cortex-m-rt = "0.7.0"
critical-section = "1.1"
panic-probe = { version = "0.3", features = ["print-defmt"] }
display-interface-spi = "0.4.1"
embedded-graphics = "0.7.1"
st7789 = "0.6.1"
display-interface = "0.4.1"
byte-slice-cast = { version = "1.2.0", default-features = false }
smart-leds = "0.3.0"
heapless = "0.8"
usbd-hid = "0.8.1"
embedded-hal-1 = { package = "embedded-hal", version = "1.0" }
embedded-hal-async = "1.0"
embedded-hal-bus = { version = "0.1", features = ["async"] }
embedded-io-async = { version = "0.6.1", features = ["defmt-03"] }
embedded-storage = { version = "0.3" }
static_cell = "2.1"
portable-atomic = { version = "1.5", features = ["critical-section"] }
log = "0.4"
pio-proc = "0.2"
pio = "0.2.1"
rand = { version = "0.8.5", default-features = false }
embedded-sdmmc = "0.7.0"
bt-hci = { version = "0.1.0", default-features = false, features = ["defmt"] }
hex = { version = "0.4.3", default-features=false}
[profile.release]
debug = 2
lto = true
opt-level = 'z'
[profile.dev]
debug = 2
lto = true
opt-level = "z"

36
outside/build.rs Normal file
View file

@ -0,0 +1,36 @@
//! This build script copies the `memory.x` file from the crate root into
//! a directory where the linker can always find it at build time.
//! For many projects this is optional, as the linker always searches the
//! project root directory -- wherever `Cargo.toml` is. However, if you
//! are using a workspace or have a more complicated build setup, this
//! build script becomes required. Additionally, by requesting that
//! Cargo re-run the build script whenever `memory.x` is changed,
//! updating `memory.x` ensures a rebuild of the application with the
//! new memory settings.
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
fn main() {
// Put `memory.x` in our output directory and ensure it's
// on the linker search path.
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(include_bytes!("memory.x"))
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
// By default, Cargo will re-run a build script whenever
// any file in the project changes. By specifying `memory.x`
// here, we ensure the build script is only re-run when
// `memory.x` is changed.
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rustc-link-arg-bins=--nmagic");
println!("cargo:rustc-link-arg-bins=-Tlink.x");
println!("cargo:rustc-link-arg-bins=-Tlink-rp.x");
println!("cargo:rustc-link-arg-bins=-Tdefmt.x");
}

17
outside/memory.x Normal file
View file

@ -0,0 +1,17 @@
MEMORY {
BOOT2 : ORIGIN = 0x10000000, LENGTH = 0x100
FLASH : ORIGIN = 0x10000100, LENGTH = 2048K - 0x100
/* Pick one of the two options for RAM layout */
/* OPTION A: Use all RAM banks as one big block */
/* Reasonable, unless you are doing something */
/* really particular with DMA or other concurrent */
/* access that would benefit from striping */
RAM : ORIGIN = 0x20000000, LENGTH = 264K
/* OPTION B: Keep the unstriped sections separate */
/* RAM: ORIGIN = 0x20000000, LENGTH = 256K */
/* SCRATCH_A: ORIGIN = 0x20040000, LENGTH = 4K */
/* SCRATCH_B: ORIGIN = 0x20041000, LENGTH = 4K */
}

238
outside/src/main.rs Normal file
View file

@ -0,0 +1,238 @@
//! This example uses the RP Pico W board Wifi chip (cyw43).
//! Creates an Access point Wifi network and creates a TCP endpoint on port 1234.
#![no_std]
#![no_main]
#![allow(async_fn_in_trait)]
use core::array;
use core::borrow::BorrowMut;
use core::cell::RefCell;
use core::fmt::Formatter;
use core::marker::PhantomData;
use core::panic::PanicInfo;
use core::str::from_utf8;
use core::sync::atomic::{AtomicU8};
use bt_hci::cmd::info;
use critical_section::Mutex;
use cyw43_pio::PioSpi;
use embassy_futures::join::join;
use embassy_rp::interrupt::typelevel::{Handler, Interrupt, IO_IRQ_BANK0};
use embassy_rp::pwm::{self, Pwm};
use fixed::FixedU16;
use log::*;
//use embassy_rp::i2c::InterruptHandler;
use embassy_executor::{InterruptExecutor, Spawner};
use embassy_net::tcp::TcpSocket;
use embassy_net::{Config, StackResources};
use embassy_rp::{bind_interrupts, interrupt};
use embassy_rp::clocks::RoscRng;
use embassy_rp::gpio::{AnyPin, Input, InterruptTrigger, Level, Output};
use embassy_rp::peripherals::{DMA_CH0, PIN_21, PIO0, USB};
use embassy_rp::pio::{InterruptHandler, Pio};
use embassy_rp::usb::Driver;
use embassy_time::{Duration, Timer};
use embedded_io_async::Write;
use rand::RngCore;
use reqwless::response;
use static_cell::StaticCell;
use defmt_rtt as _;
bind_interrupts!(struct Irqs {
PIO0_IRQ_0 => InterruptHandler<PIO0>;
USBCTRL_IRQ => embassy_rp::usb::InterruptHandler<USB>;
});
static READ_CARD: Mutex<RefCell<u64>> =
Mutex::new(RefCell::new(0));
static BIT: AtomicU8 = AtomicU8::new(0);
static DATA_IN: Mutex<RefCell<Option<(Input, Input)>>> =
Mutex::new(RefCell::new(None));
#[embassy_executor::task]
async fn logger_task(driver: Driver<'static, USB>) {
embassy_usb_logger::run!(1024, log::LevelFilter::Debug, driver);
}
#[embassy_executor::task]
async fn cyw43_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! {
runner.run().await
}
#[embassy_executor::task]
async fn net_task(mut runner: embassy_net::Runner<'static, cyw43::NetDriver<'static>>) -> ! {
runner.run().await
}
#[panic_handler]
fn panic( info: &PanicInfo) -> ! {
error!("{}", info);
loop { }
}
#[embassy_executor::task]
async fn data_handler() {
info!("start");
let (data_0, data_1) = critical_section::with(|cs| {
let borrow_ref_mut = DATA_IN.take(cs);
borrow_ref_mut.unzip()
});
let mut data_0 = data_0.unwrap();
let mut data_1 = data_1.unwrap();
info!("gyatt");
loop {
join(data_0.wait_for_falling_edge(), data_1.wait_for_falling_edge()).await;
info!("happen");
critical_section::with(|cs| {
let mut partial = READ_CARD.borrow_ref_mut(cs);
let bit = BIT.load(core::sync::atomic::Ordering::SeqCst);
let borrow_ref_mut = DATA_IN.take(cs);
let (data_0, data_1) = borrow_ref_mut.as_ref().unwrap();
if data_1.is_low() {
*partial &= 1 << bit;
}
if data_0.is_low() {
*partial |= !1u64.rotate_left(bit as u32);
}
});
}
}
#[embassy_executor::main]
async fn main(spawner: Spawner) {
let p = embassy_rp::init(Default::default());
let data_0= Input::new(p.PIN_21, embassy_rp::gpio::Pull::None);
let data_1= Input::new(p.PIN_16, embassy_rp::gpio::Pull::None);
critical_section::with(|cs| {
DATA_IN.replace(cs, Some((data_0, data_1)));
});
//spawner.spawn(data_handler()).unwrap();
let mut rng = RoscRng;
let driver = Driver::new(p.USB, Irqs);
spawner.spawn(logger_task(driver)).unwrap();
let fw = include_bytes!("../../cyw43-firmware/43439A0.bin");
let clm = include_bytes!("../../cyw43-firmware/43439A0_clm.bin");
// To make flashing faster for development, you may want to flash the firmwares independently
// at hardcoded addresses, instead of baking them into the program with `include_bytes!`:
// probe-rs download 43439A0.bin --binary-format bin --chip RP2040 --base-address 0x10100000
// probe-rs download 43439A0_clm.bin --binary-format bin --chip RP2040 --base-address 0x10140000
//let fw = unsafe { core::slice::from_raw_parts(0x10100000 as *const u8, 230321) };
//let clm = unsafe { core::slice::from_raw_parts(0x10140000 as *const u8, 4752) };
let pwr = Output::new(p.PIN_23, Level::Low);
let cs = Output::new(p.PIN_25, Level::High);
let mut pio = Pio::new(p.PIO0, Irqs);
let spi = PioSpi::new(&mut pio.common, pio.sm0, pio.irq0, cs, p.PIN_24, p.PIN_29, p.DMA_CH0);
static STATE: StaticCell<cyw43::State> = StaticCell::new();
let state = STATE.init(cyw43::State::new());
let (net_device, mut control, runner) = cyw43::new(state, pwr, spi, fw).await;
defmt::unwrap!(spawner.spawn(cyw43_task(runner)));
control.init(clm).await;
control
.set_power_management(cyw43::PowerManagementMode::PowerSave)
.await;
// Use a link-local address for communication without DHCP server
let config = Config::ipv4_static(embassy_net::StaticConfigV4 {
address: embassy_net::Ipv4Cidr::new(embassy_net::Ipv4Address::new(169, 254, 1, 1), 16),
dns_servers: heapless::Vec::new(),
gateway: None,
});
// Generate random seed
let seed = rng.next_u64();
// Init network stack
static RESOURCES: StaticCell<StackResources<3>> = StaticCell::new();
let (stack, runner) = embassy_net::new(net_device, config, RESOURCES.init(StackResources::new()), seed);
defmt::unwrap!(spawner.spawn(net_task(runner)));
//control.start_ap_open("door409", 5).await;
control.start_ap_wpa2("door409-outside", "outerbabes", 5).await;
let mut rx_buffer = [0; 4096];
let mut tx_buffer = [0; 4096];
let mut buf = [0; 4096];
loop {
let card = critical_section::with(|cs| {
READ_CARD.borrow_ref(cs).clone()
});
//info!("datah: {}", card);
Timer::after_millis(100).await;
}
loop {
let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(Duration::from_secs(3)));
control.gpio_set(0, false).await;
info!("Listening on TCP:1234...");
if let Err(e) = socket.accept(1234).await {
warn!("accept error: {:?}", e);
continue;
}
info!("Received connection from {:?}", socket.remote_endpoint());
control.gpio_set(0, true).await;
loop {
let mut n = match socket.read(&mut buf).await {
Ok(0) => {
warn!("read EOF");
break;
}
Ok(n) => n,
Err(e) => {
warn!("read error: {:?}", e);
break;
}
};
info!("rxd {}", from_utf8(&buf[..n]).unwrap());
Timer::after_millis(30).await;
let mut segs = buf[..n].trim_ascii().split(|c| *c == ' ' as u8);
match char::from_u32(segs.next().unwrap()[0] as u32).unwrap() {
'D' => {
},
_ => {}
}
//let mut response: [u8;2] = [0;2];
//let _ = bus.read_async(0xC0u16, &mut response).await;
//let _ = hex::encode_to_slice(response, &mut buf);
match socket.write_all(&buf[..n]).await {
Ok(()) => {}
Err(e) => {
warn!("write error: {:?}", e);
break;
}
};
}
}
}