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
#![no_std]
use core::ops::Deref;
use core::ops::DerefMut;
use embedded_hal_async::i2c::ErrorType;
use embedded_hal_async::i2c::I2c;
use embedded_hal_async::i2c::SevenBitAddress;
use sh1107::Direction;
use sh1107::{AddressMode, Sh1107};
use sh1107::{Command, DisplayMode};
pub use sh1107::DisplayState;
pub const COLUMN: u8 = 64;
pub const ROW: u8 = 128;
pub const PAGE: u8 = ROW / 8;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", defmt::Format)]
pub enum Destination {
Frame1,
Frame2,
}
pub trait ValidBus:
sh1107::WriteIter<SevenBitAddress, Error = <<Self as ValidBus>::I2c as ErrorType>::Error>
+ Deref<Target = Self::I2c>
+ DerefMut
{
type I2c: I2c<SevenBitAddress>;
}
impl<T, U> ValidBus for T
where
T: sh1107::WriteIter<SevenBitAddress, Error = U::Error> + Deref<Target = U> + DerefMut,
U: I2c<SevenBitAddress>,
{
type I2c = U;
}
pub struct Display<T, const ADDRESS: SevenBitAddress>(Sh1107<T, ADDRESS>);
impl<T, const ADDRESS: SevenBitAddress> Display<T, ADDRESS>
where
T: ValidBus,
{
pub async fn new(i2c_bus: T) -> Result<Self, (T, T::Error)> {
let mut sh1107 = Sh1107::new(i2c_bus);
use Command::*;
let init_sequence = [
DisplayOnOff(DisplayState::Off),
SetClkDividerOscFrequency {
divider: 2, osc_freq_ratio: 0, },
SetMultiplexRatio(COLUMN),
SetDisplayOffset(96),
SetStartLine(0),
SetSegmentReMap(false),
SetCOMScanDirection(Direction::Normal),
SetChargePeriods {
precharge: Some(2),
discharge: 2,
},
SetVCOMHDeselectLevel(0x35),
SetDCDCSettings(0xF),
SetContrastControl(128), ForceEntireDisplay(false),
SetDisplayMode(DisplayMode::BlackOnWhite),
];
match sh1107.run(init_sequence).await {
Ok(_) => {}
Err(e) => return Err((sh1107.release(), e)),
}
Ok(Display(sh1107))
}
pub async fn set_state(&mut self, state: DisplayState) -> Result<(), T::Error> {
self.0.run([Command::DisplayOnOff(state)]).await
}
pub async fn set_start_line(&mut self, line: u8) -> Result<(), T::Error> {
self.0.run([Command::SetStartLine(line)]).await
}
pub async fn set_contrast(&mut self, contrast: u8) -> Result<(), T::Error> {
self.0.run([Command::SetContrastControl(contrast)]).await
}
pub async fn write_frame_by_column(
&mut self,
dest: Destination,
mut buf: impl Iterator<Item = u8>,
) -> Result<(), T::Error> {
self.0
.run([Command::SetAddressMode(AddressMode::Column)])
.await?;
let buf = &mut buf;
for col in 0..COLUMN {
self.0
.run_then_write_to_ram(
[
Command::SetColumnAddress(
match dest {
Destination::Frame1 => 0,
Destination::Frame2 => 64,
} + (col as u8),
),
Command::SetPageAddress(0),
],
buf.take(PAGE.into()),
)
.await?;
}
Ok(())
}
pub async fn write_frame_by_page(
&mut self,
dest: Destination,
mut buf: impl Iterator<Item = u8>,
) -> Result<(), T::Error> {
self.0
.run([Command::SetAddressMode(AddressMode::Page)])
.await?;
let buf = &mut buf;
for page in 0..PAGE {
self.0
.run_then_write_to_ram(
[
Command::SetColumnAddress(match dest {
Destination::Frame1 => 0,
Destination::Frame2 => 64,
}),
Command::SetPageAddress(page as u8),
],
buf.take(COLUMN.into()),
)
.await?;
}
Ok(())
}
pub async fn read_frame(&mut self, buf: &mut [u8]) -> Result<(), T::Error> {
self.0
.run([Command::SetAddressMode(AddressMode::Page)])
.await?;
for page in 0..PAGE {
self.0
.run([Command::SetColumnAddress(0), Command::SetPageAddress(page)])
.await?;
let col = usize::from(COLUMN);
let start = usize::from(page) * col;
let end = start + col - 1;
self.0.read_from_ram(&mut buf[start..=end]).await?;
}
Ok(())
}
pub async fn is_busy(&mut self) -> Result<bool, T::Error> {
self.0.is_busy().await
}
pub async fn wait_while_busy(&mut self) -> Result<(), T::Error> {
while self.is_busy().await? {}
Ok(())
}
pub fn release(self) -> T {
self.0.release()
}
}
#[cfg(feature = "embedded-graphics")]
pub use self::embedded_graphics::BufferedDisplay;
#[cfg(feature = "embedded-graphics")]
mod embedded_graphics {
use core::ops::Deref;
use core::ops::DerefMut;
use crate::ValidBus;
use crate::COLUMN;
use crate::PAGE;
use crate::ROW;
use super::Destination;
use super::Display;
use super::SevenBitAddress;
use embedded_graphics::pixelcolor::BinaryColor;
use embedded_graphics::prelude::*;
use embedded_graphics::primitives::Rectangle;
use itertools::Itertools;
use sh1107::AddressMode;
use sh1107::Command;
pub struct BufferedDisplay<T, const ADDRESS: SevenBitAddress> {
display: Display<T, ADDRESS>,
bitmask: [u8; 128 * 64],
bitmap: [u8; 128 * 64],
}
impl<T, const ADDRESS: SevenBitAddress> Deref for BufferedDisplay<T, ADDRESS> {
type Target = Display<T, ADDRESS>;
fn deref(&self) -> &Self::Target {
&self.display
}
}
impl<T, const ADDRESS: SevenBitAddress> DerefMut for BufferedDisplay<T, ADDRESS> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.display
}
}
impl<T: ValidBus, const ADDRESS: SevenBitAddress> BufferedDisplay<T, ADDRESS> {
pub async fn new(i2c_bus: T) -> Result<Self, (T, T::Error)> {
Ok(Self {
display: Display::new(i2c_bus).await?,
bitmask: [0xFF; 128 * 64],
bitmap: [0; 128 * 64],
})
}
pub async fn flush(&mut self) -> Result<(), <T as embedded_hal::i2c::ErrorType>::Error> {
self.flush_to(Destination::Frame1).await
}
pub async fn flush_to(
&mut self,
destination: Destination,
) -> Result<(), <T as embedded_hal::i2c::ErrorType>::Error> {
self.display
.0
.run([Command::SetAddressMode(AddressMode::Page)])
.await?;
use itertools::{iproduct, izip};
let mut idx = 0;
let pages = itertools::put_back(izip!(
iproduct!(0..PAGE, 0..COLUMN),
self.bitmask.iter().cloned()
))
.batching(|it| {
let mut skip_before = 0;
let mut take_count = 0;
let mut skip_after = 0;
let mut first = None;
while let Some((coords, mask)) = it.next() {
if first.is_none() && mask == 0 {
skip_before += 1;
continue;
}
if let Some((first_page, _)) = first {
if first_page != coords.0 {
it.put_back((coords, mask));
break;
}
} else {
first = Some(coords);
}
if mask == 0 {
skip_after += 1;
} else {
take_count += 1 + skip_after;
skip_after = 0;
}
if skip_after == 8 || (take_count == COLUMN.into()) {
break;
}
}
let start = idx + skip_before;
let end = start + take_count;
idx = end + skip_after;
first.map(move |coord| (coord, start..end))
});
for ((page, col), range) in pages {
self.display
.0
.run_then_write_to_ram(
[
Command::SetColumnAddress(
match destination {
Destination::Frame1 => 0,
Destination::Frame2 => 64,
} + col,
), Command::SetPageAddress(page), ],
self.bitmap[range].iter().cloned(),
)
.await?;
}
self.bitmask.fill(0);
Ok(())
}
}
impl<T, const ADDRESS: SevenBitAddress> Dimensions for BufferedDisplay<T, ADDRESS> {
fn bounding_box(&self) -> Rectangle {
Rectangle::new(Point::new(0, 0), Size::new(128, 64))
}
}
impl<T, const ADDRESS: SevenBitAddress> DrawTarget for BufferedDisplay<T, ADDRESS> {
type Color = BinaryColor;
type Error = core::convert::Infallible;
fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
where
I: IntoIterator<Item = Pixel<Self::Color>>,
{
for Pixel(coord, color) in pixels
.into_iter()
.filter(|Pixel(coord, _)| coord.x < COLUMN.into() && coord.y < ROW.into())
{
let page = coord.y / 8;
let lsh = coord.y % 8;
let column = coord.x;
let idx = page * i32::from(COLUMN) + column;
let pixel = (matches!(color, BinaryColor::On) as u8) << lsh;
let mask = 1 << lsh;
self.bitmask[idx as usize] |= mask;
self.bitmap[idx as usize] = (self.bitmap[idx as usize] & !mask) | pixel;
}
Ok(())
}
}
}