Skip to content

Commit 59c44fe

Browse files
committed
Converting bcd to decimal in get time, we can now set and get time! Date should be relatively straight forward from here. I woul dlike to refactor the PWR and RTC modules to produce a clear api also.
1 parent 92bf11a commit 59c44fe

File tree

2 files changed

+28
-13
lines changed

2 files changed

+28
-13
lines changed

examples/rtc.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ fn main() -> ! {
5050
let mut timer = Delay::new(cp.SYST, clocks);
5151
let mut pwr = Pwr::pwr(&mut rcc.apb1r1);
5252
let rtc = Rtc::rtc(dp.RTC, &mut rcc.apb1r1, &mut rcc.bdcr, &mut pwr.cr1);
53-
let time = Time::new(19, 0, 0, false);
53+
let time = Time::new(21, 57, 32, false);
5454
rtc.set_time(&time);
5555

5656
timer.delay_ms(1000_u32);

src/rtc.rs

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ use stm32l4::stm32l4x2::{RTC};
77

88
#[derive(Clone,Copy,Debug)]
99
pub struct Time {
10-
seconds: u8,
11-
minutes: u8,
1210
hours: u8,
11+
minutes: u8,
12+
seconds: u8,
1313
daylight_savings: bool
1414
}
1515

@@ -104,15 +104,18 @@ impl Rtc {
104104
{
105105
init_mode(&self.rtc, true);
106106
{
107+
let (ht, hu) = byte_to_bcd2(time.hours);
108+
let (mnt, mnu) = byte_to_bcd2(time.minutes);
109+
let (st, su) = byte_to_bcd2(time.seconds);
107110
self.rtc.tr.write(|w| unsafe {
108-
w.pm()
111+
w.ht().bits(ht)
112+
.hu().bits(hu)
113+
.mnt().bits(mnt)
114+
.mnu().bits(mnu)
115+
.st().bits(st)
116+
.su().bits(su)
117+
.pm()
109118
.clear_bit()
110-
.hu()
111-
.bits(time.hours)
112-
.mnu()
113-
.bits(time.minutes)
114-
.su()
115-
.bits(time.seconds)
116119

117120
});
118121

@@ -135,7 +138,11 @@ impl Rtc {
135138
{
136139
let timer = self.rtc.tr.read();
137140
let cr = self.rtc.cr.read();
138-
time = Time::new(timer.hu().bits(), timer.mnu().bits(), timer.su().bits(), cr.fmt().bit());
141+
let ht = timer.ht().bits();
142+
time = Time::new(bcd2_to_byte((timer.ht().bits(), timer.hu().bits())),
143+
bcd2_to_byte((timer.mnt().bits(), timer.mnu().bits())),
144+
bcd2_to_byte((timer.st().bits(), timer.su().bits())),
145+
cr.fmt().bit());
139146
}
140147
init_mode(&self.rtc, false);
141148
}
@@ -176,7 +183,7 @@ fn init_mode(rtc: &RTC, enabled: bool) {
176183

177184
}
178185

179-
fn byte_to_bcd2(byte: u8) -> u8{
186+
fn byte_to_bcd2(byte: u8) -> (u8, u8){
180187
let mut bcd_high: u8 = 0;
181188
let mut value = byte;
182189

@@ -185,5 +192,13 @@ fn byte_to_bcd2(byte: u8) -> u8{
185192
value -= 10;
186193
}
187194

188-
return ((bcd_high << 4) | value) as u8;
195+
(bcd_high, ((bcd_high << 4) | value) as u8)
196+
}
197+
198+
fn bcd2_to_byte(bcd: (u8, u8)) -> u8 { // TODO fix this
199+
let value = bcd.1 | bcd.0 << 4;
200+
201+
let tmp = ((value & 0xF0) >> 0x4) * 10;
202+
203+
(tmp + (value & 0x0F))
189204
}

0 commit comments

Comments
 (0)