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

[WIP] USB OTG FS support #36

Open
wants to merge 5 commits 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
48 changes: 42 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,31 @@ rustdoc-args = ["--cfg", "docsrs"]
default-target = "x86_64-unknown-linux-gnu"

[dependencies]
gd32vf103xx-hal = "0.5.0"
embedded-hal = "0.2.6"
embedded-hal = "0.2.7"
nb = "1.0.0"
riscv = "0.6.0"
riscv = { version = "0.10.1", features = ["critical-section-single-hart"] }
st7735-lcd = { version = "0.8.1", optional = true }
embedded-sdmmc = { version = "0.3.0", optional = true }
embedded-sdmmc = { version = "0.4.0", optional = true }
usb-device = { version = "0.2.9", optional = true }

[dependencies.gd32vf103xx-hal]
git = "https://github.com/katyo/gd32vf103xx-hal"
branch = "upcoming"

[dev-dependencies]
riscv-rt = "0.8.0"
riscv-rt = "0.11.0"
panic-halt = "0.2.0"
embedded-graphics = "0.7.1"
ushell = "0.3.5"
usbd-serial = "0.1.1"

[dev-dependencies.ushell]
git = "https://github.com/katyo/ushell"
branch = "upcoming"

[features]
lcd = ["st7735-lcd"]
sdcard = ["embedded-sdmmc"]
usb = ["gd32vf103xx-hal/usb_fs", "usb-device"]

[[example]]
name = "display"
Expand All @@ -44,3 +53,30 @@ required-features = ["lcd"]
name = "sdcard_test"
required-features = ["sdcard"]

[[example]]
name = "led_shell_usb"
required-features = ["usb"]

[[example]]
name = "serial_usb"
required-features = ["usb"]

[profile.dev]
opt-level = 1
debug = true
debug-assertions = true
overflow-checks = true
lto = false
#panic = 'unwind'
incremental = true
codegen-units = 256

[profile.release]
opt-level = "s"
debug = true
debug-assertions = false
overflow-checks = false
lto = true
panic = "abort"
incremental = false
codegen-units = 1
168 changes: 168 additions & 0 deletions examples/led_shell_usb.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
#![no_std]
#![no_main]

use panic_halt as _;

use core::fmt::Write;
use longan_nano::{
hal::{pac, prelude::*},
led::{rgb, Led, BLUE, GREEN, RED},
usb::{usb, UsbBusType},
};
use riscv_rt::entry;
use ushell::{autocomplete::*, history::*, *};
use usb_device::prelude::*;
use usbd_serial::{SerialPort, USB_CLASS_CDC};

#[entry]
fn main() -> ! {
let dp = pac::Peripherals::take().unwrap();

// Configure clocks
let mut rcu = dp
.RCU
.configure()
.ext_hf_clock(8.mhz())
.sysclk(96.mhz())
.freeze();

assert!(rcu.clocks.usbclk_valid());

let gpioa = dp.GPIOA.split(&mut rcu);
let gpioc = dp.GPIOC.split(&mut rcu);

let (mut red, mut green, mut blue) = rgb(gpioc.pc13, gpioa.pa1, gpioa.pa2);
red.off();
green.off();
blue.off();

static mut EP_MEMORY: [u32; 1024] = [0; 1024];

let usb_bus = usb(
dp.USBFS_GLOBAL, dp.USBFS_DEVICE, dp.USBFS_PWRCLK,
gpioa.pa11, gpioa.pa12, &rcu,
unsafe { &mut EP_MEMORY },
);

let serial = SerialPort::new(&usb_bus);
let mut usb_dev = UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x16c0, 0x27dd))
.manufacturer("Longan Nano")
.product("Led Shell")
.serial_number("1234")
.device_class(USB_CLASS_CDC)
.build();

let autocomplete = StaticAutocomplete(["clear", "help", "status", "off ", "on "]);
let mut shell = UShell::new(serial, autocomplete, LRUHistory::default());
let mut env = Env { red, green, blue };

loop {
if !usb_dev.poll(&mut [shell.as_mut()]) {
continue;
}

shell.spin(&mut env).ok();
}
}

const CMD_LEN: usize = 16;
const HISTORY_SIZE: usize = 4;
const COMMANDS: usize = 5;

type Serial<'s> = SerialPort<'s, UsbBusType>;
type Autocomplete = StaticAutocomplete<{ COMMANDS }>;
type History = LRUHistory<{ CMD_LEN }, { HISTORY_SIZE }>;
type Shell<'s> = UShell<Serial<'s>, Autocomplete, History, { CMD_LEN }>;

struct Env {
red: RED,
green: GREEN,
blue: BLUE,
}

type EnvResult<'s> = SpinResult<Serial<'s>, ()>;

impl<'s> Env {
fn on_cmd(&mut self, shell: &mut Shell<'s>, args: &str) -> EnvResult<'s> {
match args {
"r" | "red" => self.red.on(),
"g" | "green" => self.green.on(),
"b" | "blue" => self.blue.on(),
"a" | "all" => {
self.red.on();
self.green.on();
self.blue.on();
}
_ => {
write!(shell, "{0:}unsupported color channel", CR).ok();
}
}
shell.write_str(CR)?;
Ok(())
}

fn off_cmd(&mut self, shell: &mut Shell<'s>, args: &str) -> EnvResult<'s> {
match args {
"r" | "red" => self.red.off(),
"g" | "green" => self.green.off(),
"b" | "blue" => self.blue.off(),
"a" | "all" => {
self.red.off();
self.green.off();
self.blue.off();
}
_ => {
write!(shell, "{0:}unsupported color channel", CR).ok();
}
}
shell.write_str(CR)?;
Ok(())
}

fn status_cmd(&mut self, shell: &mut Shell<'s>, _args: &str) -> EnvResult<'s> {
let red = if self.red.is_on() { "On" } else { "Off" };
let green = if self.green.is_on() { "On" } else { "Off" };
let blue = if self.blue.is_on() { "On" } else { "Off" };
write!(
shell,
"{0:}Red: {1:}{0:}Green: {2:}{0:}Blue: {3:}{0:}",
CR, red, green, blue,
)?;

Ok(())
}
}

impl<'s> Environment<Serial<'s>, Autocomplete, History, (), { CMD_LEN }> for Env {
fn command(&mut self, shell: &mut Shell<'s>, cmd: &str, args: &str) -> EnvResult<'s> {
match cmd {
"clear" => shell.clear()?,
"help" => shell.write_str(HELP)?,
"status" => self.status_cmd(shell, args)?,
"on" => self.on_cmd(shell, args)?,
"off" => self.off_cmd(shell, args)?,
"" => shell.write_str(CR)?,
_ => write!(shell, "{0:}unsupported command: \"{1:}\"{0:}", CR, cmd)?,
}
shell.write_str(SHELL_PROMPT)?;
Ok(())
}

fn control(&mut self, _shell: &mut Shell<'s>, _code: u8) -> EnvResult<'s> {
Ok(())
}
}

const SHELL_PROMPT: &str = "#> ";
const CR: &str = "\r\n";
const HELP: &str = "\r\n\
\x1b[31mL\x1b[32mE\x1b[34mD\x1b[33m Shell\x1b[0m\r\n\r\n\
USAGE:\r\n\
\x20 command [arg]\r\n\r\n\
COMMANDS:\r\n\
\x20 on <ch> Switch led channel on [r,g,b,a]\r\n\
\x20 off <ch> Switch led channel off [r,g,b,a]\r\n\
\x20 status Get leds status\r\n\
\x20 clear Clear screen\r\n\
\x20 help Print this message\r\n
";
84 changes: 84 additions & 0 deletions examples/serial_usb.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#![no_std]
#![no_main]

use panic_halt as _;

use gd32vf103xx_hal::pac;
use gd32vf103xx_hal::prelude::*;
use riscv_rt::entry;

use longan_nano::usb::usb;
use usb_device::prelude::*;
use usbd_serial::{SerialPort, USB_CLASS_CDC};

use embedded_hal::digital::v2::OutputPin;

#[entry]
fn main() -> ! {
let dp = pac::Peripherals::take().unwrap();

// Configure clocks
let mut rcu = dp
.RCU
.configure()
.ext_hf_clock(8.mhz())
.sysclk(96.mhz())
.freeze();

assert!(rcu.clocks.usbclk_valid());

let gpioc = dp.GPIOC.split(&mut rcu);
let mut led = gpioc.pc13.into_push_pull_output();
led.set_high().unwrap(); // Turn off

let gpioa = dp.GPIOA.split(&mut rcu);

static mut EP_MEMORY: [u32; 1024] = [0; 1024];
let usb_bus = usb(
dp.USBFS_GLOBAL, dp.USBFS_DEVICE, dp.USBFS_PWRCLK,
gpioa.pa11, gpioa.pa12, &rcu,
unsafe { &mut EP_MEMORY },
);

let mut serial = SerialPort::new(&usb_bus);
let mut usb_dev = UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x16c0, 0x27dd))
.manufacturer("Fake company")
.product("Serial port")
.serial_number("TEST")
.device_class(USB_CLASS_CDC)
.build();

loop {
if !usb_dev.poll(&mut [&mut serial]) {
continue;
}

let mut buf = [0u8; 64];

match serial.read(&mut buf) {
Ok(count) if count > 0 => {
led.set_low().unwrap(); // Turn on

// Echo back in upper case
for c in buf[0..count].iter_mut() {
if 0x61 <= *c && *c <= 0x7a {
*c &= !0x20;
}
}

let mut write_offset = 0;
while write_offset < count {
match serial.write(&buf[write_offset..count]) {
Ok(len) if len > 0 => {
write_offset += len;
}
_ => {}
}
}
}
_ => {}
}

led.set_high().unwrap(); // Turn off
}
}
12 changes: 12 additions & 0 deletions rv-link.gdb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
target remote /dev/ttyRvlGdb

# print demangled symbols
set print asm-demangle on

set confirm off

# set backtrace limit to not have infinite backtrace loops
set backtrace limit 32

load
continue
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@ pub mod stdout;
#[cfg(feature = "sdcard")]
#[cfg_attr(docsrs, doc(cfg(feature = "sdcard")))]
pub mod sdcard;
#[cfg(feature = "usb")]
#[cfg_attr(docsrs, doc(cfg(feature = "usb")))]
pub mod usb;
6 changes: 3 additions & 3 deletions src/stdout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub fn configure<X, Y>(
let serial = Serial::new(uart, (tx, rx), config, afio, rcu);
let (tx, _) = serial.split();

interrupt::free(|_| {
interrupt::free(|| {
unsafe {
STDOUT.replace(SerialWrapper(tx));
}
Expand All @@ -66,7 +66,7 @@ pub fn configure<X, Y>(

/// Writes string to stdout
pub fn write_str(s: &str) {
interrupt::free(|_| unsafe {
interrupt::free(|| unsafe {
if let Some(stdout) = STDOUT.as_mut() {
let _ = stdout.write_str(s);
}
Expand All @@ -75,7 +75,7 @@ pub fn write_str(s: &str) {

/// Writes formatted string to stdout
pub fn write_fmt(args: fmt::Arguments) {
interrupt::free(|_| unsafe {
interrupt::free(|| unsafe {
if let Some(stdout) = STDOUT.as_mut() {
let _ = stdout.write_fmt(args);
}
Expand Down
Loading