add lcd-writer

This commit is contained in:
Simon 2023-12-19 15:42:15 +01:00
parent fe616b76e0
commit 3bb22e568a
6 changed files with 107 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
Cargo.lock
target/

6
Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[workspace]
resolver = "2"
members = [
"server",
"lcd-writer",
]

4
lcd-writer/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
target/
Cargo.lock

9
lcd-writer/Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "lcd-writer"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
linux-embedded-hal = "0.3.2"

85
lcd-writer/src/main.rs Normal file
View File

@ -0,0 +1,85 @@
use linux_embedded_hal::{
i2cdev::{core::I2CDevice, linux::LinuxI2CError},
I2cdev,
};
use std::{
io::{self, stdin, stdout, BufRead, Write},
path::Path,
};
const C0: u8 = 7;
const A0: u8 = 6;
#[allow(unused)]
#[repr(u8)]
enum LcdCommand {
Clear = 1,
ReturnHome = 2,
DisplayOn = 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0,
FunctionSet = 1 << 5 | 1 << 4 | 1 << 3,
EntryModeSet = 1 << 2 | 1 << 1,
}
#[allow(unused)]
#[repr(u8)]
enum ControlByte {
Normal = 1 << C0,
Last = 0 << C0,
Data = 0 << C0 | 1 << A0,
}
struct Lcd {
bus: I2cdev,
}
impl Lcd {
pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, LinuxI2CError> {
let mut bus = I2cdev::new(path)?;
let setup = [
ControlByte::Last as u8,
LcdCommand::FunctionSet as u8,
LcdCommand::DisplayOn as u8,
LcdCommand::EntryModeSet as u8,
LcdCommand::Clear as u8,
];
bus.write(&setup)?;
Ok(Self { bus })
}
pub fn write(&mut self, value: &str) -> Result<(), LinuxI2CError> {
let mut data = vec![ControlByte::Data as u8];
data.extend(value.bytes());
self.bus.write(&data)
}
pub fn set_cursor(&mut self, col: u8, row: u8) -> Result<(), LinuxI2CError> {
let pos = col | (row * 0x40) | 1 << 7;
let data = vec![ControlByte::Last as u8, pos];
self.bus.write(&data)
}
pub fn clear(&mut self) -> Result<(), LinuxI2CError> {
let data = vec![ControlByte::Last as u8, LcdCommand::Clear as u8];
self.bus.write(&data)
}
}
fn main() -> io::Result<()> {
let device = "/dev/i2c-21";
println!("device = {device}");
let mut lcd = Lcd::new(device)?;
loop {
print!("> ");
stdout().lock().flush()?;
let mut line = String::new();
stdin().lock().read_line(&mut line)?;
if line.starts_with("clear") {
lcd.clear()?;
lcd.set_cursor(0, 0)?;
} else if line.starts_with("print") {
lcd.write(&line[6..])?;
} else {
println!("unrecognized command \"{line}\"");
}
}
}

1
server/.gitignore vendored
View File

@ -1,3 +1,4 @@
target/
Cargo.lock