-
Notifications
You must be signed in to change notification settings - Fork 863
/
Copy pathspi_display.rs
390 lines (328 loc) · 11.1 KB
/
spi_display.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
#[path = "../example_common.rs"]
mod example_common;
use core::cell::RefCell;
use defmt::*;
use embassy::executor::Spawner;
use embassy::time::Delay;
use embassy_rp::spi;
use embassy_rp::spi::Spi;
use embassy_rp::{gpio, Peripherals};
use embedded_graphics::image::{Image, ImageRawLE};
use embedded_graphics::mono_font::ascii::FONT_10X20;
use embedded_graphics::mono_font::MonoTextStyle;
use embedded_graphics::pixelcolor::Rgb565;
use embedded_graphics::prelude::*;
use embedded_graphics::primitives::{PrimitiveStyleBuilder, Rectangle};
use embedded_graphics::text::Text;
use gpio::{Level, Output};
use st7789::{Orientation, ST7789};
use crate::my_display_interface::SPIDeviceInterface;
use crate::shared_spi::SpiDeviceWithCs;
use crate::touch::Touch;
const DISPLAY_FREQ: u32 = 64_000_000;
const TOUCH_FREQ: u32 = 200_000;
#[embassy::main]
async fn main(_spawner: Spawner, p: Peripherals) {
info!("Hello World!");
let bl = p.PIN_13;
let rst = p.PIN_15;
let display_cs = p.PIN_9;
let dcx = p.PIN_8;
let miso = p.PIN_12;
let mosi = p.PIN_11;
let clk = p.PIN_10;
let touch_cs = p.PIN_16;
//let touch_irq = p.PIN_17;
// create SPI
let mut config = spi::Config::default();
config.frequency = TOUCH_FREQ; // use the lowest freq
config.phase = spi::Phase::CaptureOnSecondTransition;
config.polarity = spi::Polarity::IdleHigh;
let spi_bus = RefCell::new(Spi::new(p.SPI1, clk, mosi, miso, config));
let display_spi = SpiDeviceWithCs::new(&spi_bus, Output::new(display_cs, Level::High));
let touch_spi = SpiDeviceWithCs::new(&spi_bus, Output::new(touch_cs, Level::High));
let mut touch = Touch::new(touch_spi);
let dcx = Output::new(dcx, Level::Low);
let rst = Output::new(rst, Level::Low);
// dcx: 0 = command, 1 = data
// Enable LCD backlight
let _bl = Output::new(bl, Level::High);
// display interface abstraction from SPI and DC
let di = SPIDeviceInterface::new(display_spi, dcx);
// create driver
let mut display = ST7789::new(di, rst, 240, 320);
// initialize
display.init(&mut Delay).unwrap();
// set default orientation
display.set_orientation(Orientation::Landscape).unwrap();
display.clear(Rgb565::BLACK).unwrap();
let raw_image_data = ImageRawLE::new(include_bytes!("../../assets/ferris.raw"), 86);
let ferris = Image::new(&raw_image_data, Point::new(34, 68));
// Display the image
ferris.draw(&mut display).unwrap();
let style = MonoTextStyle::new(&FONT_10X20, Rgb565::GREEN);
Text::new(
"Hello embedded_graphics \n + embassy + RP2040!",
Point::new(20, 200),
style,
)
.draw(&mut display)
.unwrap();
loop {
if let Some((x, y)) = touch.read() {
let style = PrimitiveStyleBuilder::new()
.fill_color(Rgb565::BLUE)
.build();
Rectangle::new(Point::new(x - 1, y - 1), Size::new(3, 3))
.into_styled(style)
.draw(&mut display)
.unwrap();
}
}
}
mod shared_spi {
use core::cell::RefCell;
use core::fmt::Debug;
use embedded_hal::digital::blocking::OutputPin;
use embedded_hal::spi;
use embedded_hal::spi::blocking::SpiDeviceBase;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum SpiDeviceWithCsError<BUS, CS> {
Spi(BUS),
Cs(CS),
}
impl<BUS, CS> spi::Error for SpiDeviceWithCsError<BUS, CS>
where
BUS: spi::Error + Debug,
CS: Debug,
{
fn kind(&self) -> spi::ErrorKind {
match self {
Self::Spi(e) => e.kind(),
Self::Cs(_) => spi::ErrorKind::Other,
}
}
}
pub struct SpiDeviceWithCs<'a, BUS, CS> {
bus: &'a RefCell<BUS>,
cs: CS,
}
impl<'a, BUS, CS> SpiDeviceWithCs<'a, BUS, CS> {
pub fn new(bus: &'a RefCell<BUS>, cs: CS) -> Self {
Self { bus, cs }
}
}
impl<'a, BUS, CS> spi::ErrorType for SpiDeviceWithCs<'a, BUS, CS>
where
BUS: spi::ErrorType,
CS: OutputPin,
{
type Error = SpiDeviceWithCsError<BUS::Error, CS::Error>;
}
impl<'a, BUS, CS> SpiDeviceBase for SpiDeviceWithCs<'a, BUS, CS>
where
BUS: spi::ErrorType,
CS: OutputPin,
{
type Bus = BUS;
fn transaction<R>(
&mut self,
f: impl FnOnce(&mut Self::Bus) -> R,
) -> Result<R, Self::Error> {
let mut bus = self.bus.borrow_mut();
self.cs.set_low().map_err(SpiDeviceWithCsError::Cs)?;
let res = f(&mut bus);
self.cs.set_high().map_err(SpiDeviceWithCsError::Cs)?;
Ok(res)
}
}
}
/// Driver for the XPT2046 resistive touchscreen sensor
mod touch {
use embedded_hal::spi::blocking::{SpiBusWrite, SpiDevice};
struct Calibration {
x1: i32,
x2: i32,
y1: i32,
y2: i32,
sx: i32,
sy: i32,
}
const CALIBRATION: Calibration = Calibration {
x1: 3880,
x2: 340,
y1: 262,
y2: 3850,
sx: 320,
sy: 240,
};
pub struct Touch<SPI: SpiDevice> {
spi: SPI,
}
impl<SPI: SpiDevice> Touch<SPI> {
pub fn new(spi: SPI) -> Self {
Self { spi }
}
pub fn read(&mut self) -> Option<(i32, i32)> {
let mut x = [0; 2];
let mut y = [0; 2];
self.spi
.transaction(|bus| {
bus.write(&[0x90]).unwrap();
bus.read(&mut x).unwrap();
bus.write(&[0xd0]).unwrap();
bus.read(&mut y).unwrap();
})
.unwrap();
let x = (u16::from_be_bytes(x) >> 3) as i32;
let y = (u16::from_be_bytes(y) >> 3) as i32;
let cal = &CALIBRATION;
let x = ((x - cal.x1) * cal.sx / (cal.x2 - cal.x1)).clamp(0, cal.sx);
let y = ((y - cal.y1) * cal.sy / (cal.y2 - cal.y1)).clamp(0, cal.sy);
if x == 0 && y == 0 {
None
} else {
Some((x, y))
}
}
}
}
mod my_display_interface {
use display_interface::{DataFormat, DisplayError, WriteOnlyDataCommand};
use embedded_hal::digital::blocking::OutputPin;
use embedded_hal::spi::blocking::{SpiBusWrite, SpiDeviceWrite};
/// SPI display interface.
///
/// This combines the SPI peripheral and a data/command pin
pub struct SPIDeviceInterface<SPI, DC> {
spi: SPI,
dc: DC,
}
impl<SPI, DC> SPIDeviceInterface<SPI, DC>
where
SPI: SpiDeviceWrite,
DC: OutputPin,
{
/// Create new SPI interface for communciation with a display driver
pub fn new(spi: SPI, dc: DC) -> Self {
Self { spi, dc }
}
/// Consume the display interface and return
/// the underlying peripherial driver and GPIO pins used by it
pub fn release(self) -> (SPI, DC) {
(self.spi, self.dc)
}
}
impl<SPI, DC> WriteOnlyDataCommand for SPIDeviceInterface<SPI, DC>
where
SPI: SpiDeviceWrite,
DC: OutputPin,
{
fn send_commands(&mut self, cmds: DataFormat<'_>) -> Result<(), DisplayError> {
self.spi
.transaction(|bus| {
// 1 = data, 0 = command
self.dc.set_low().map_err(|_| DisplayError::DCError)?;
// Send words over SPI
send_u8(bus, cmds)
})
.unwrap_or(Err(DisplayError::BusWriteError))
}
fn send_data(&mut self, buf: DataFormat<'_>) -> Result<(), DisplayError> {
self.spi
.transaction(|bus| {
// 1 = data, 0 = command
self.dc.set_high().map_err(|_| DisplayError::DCError)?;
// Send words over SPI
send_u8(bus, buf)
})
.unwrap_or(Err(DisplayError::BusWriteError))
}
}
fn send_u8(spi: &mut impl SpiBusWrite, words: DataFormat<'_>) -> Result<(), DisplayError> {
match words {
DataFormat::U8(slice) => spi.write(slice).map_err(|_| DisplayError::BusWriteError),
DataFormat::U16(slice) => {
use byte_slice_cast::*;
spi.write(slice.as_byte_slice())
.map_err(|_| DisplayError::BusWriteError)
}
DataFormat::U16LE(slice) => {
use byte_slice_cast::*;
for v in slice.as_mut() {
*v = v.to_le();
}
spi.write(slice.as_byte_slice())
.map_err(|_| DisplayError::BusWriteError)
}
DataFormat::U16BE(slice) => {
use byte_slice_cast::*;
for v in slice.as_mut() {
*v = v.to_be();
}
spi.write(slice.as_byte_slice())
.map_err(|_| DisplayError::BusWriteError)
}
DataFormat::U8Iter(iter) => {
let mut buf = [0; 32];
let mut i = 0;
for v in iter.into_iter() {
buf[i] = v;
i += 1;
if i == buf.len() {
spi.write(&buf).map_err(|_| DisplayError::BusWriteError)?;
i = 0;
}
}
if i > 0 {
spi.write(&buf[..i])
.map_err(|_| DisplayError::BusWriteError)?;
}
Ok(())
}
DataFormat::U16LEIter(iter) => {
use byte_slice_cast::*;
let mut buf = [0; 32];
let mut i = 0;
for v in iter.map(u16::to_le) {
buf[i] = v;
i += 1;
if i == buf.len() {
spi.write(&buf.as_byte_slice())
.map_err(|_| DisplayError::BusWriteError)?;
i = 0;
}
}
if i > 0 {
spi.write(&buf[..i].as_byte_slice())
.map_err(|_| DisplayError::BusWriteError)?;
}
Ok(())
}
DataFormat::U16BEIter(iter) => {
use byte_slice_cast::*;
let mut buf = [0; 64];
let mut i = 0;
let len = buf.len();
for v in iter.map(u16::to_be) {
buf[i] = v;
i += 1;
if i == len {
spi.write(&buf.as_byte_slice())
.map_err(|_| DisplayError::BusWriteError)?;
i = 0;
}
}
if i > 0 {
spi.write(&buf[..i].as_byte_slice())
.map_err(|_| DisplayError::BusWriteError)?;
}
Ok(())
}
_ => Err(DisplayError::DataFormatNotImplemented),
}
}
}