From 15883293ac3567a2019a7ce555af00be20710ef6 Mon Sep 17 00:00:00 2001 From: Astro Date: Thu, 23 May 2019 15:37:07 +0200 Subject: [PATCH] uart: use div_round_closest in baud_rate_gen --- src/uart/baud_rate_gen.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/uart/baud_rate_gen.rs b/src/uart/baud_rate_gen.rs index 84bb60d..9904658 100644 --- a/src/uart/baud_rate_gen.rs +++ b/src/uart/baud_rate_gen.rs @@ -5,6 +5,10 @@ const BDIV_MIN: u8 = 4; const BDIV_MAX: u8 = 255; const CD_MAX: u16 = 65535; +fn div_round_closest(q: u32, d: u32) -> u32 { + (q + (d / 2)) / d +} + /// Algorithm as in the Linux 5.1 driver pub fn configure(regs: &RegisterBlock, mut clk: u32, baud: u32) { if regs.mode.read().clks() { @@ -14,7 +18,7 @@ pub fn configure(regs: &RegisterBlock, mut clk: u32, baud: u32) { let mut best = None; for bdiv in BDIV_MIN..=BDIV_MAX { let bdiv: u32 = bdiv.into(); - let cd = clk / (baud * (bdiv + 1)); + let cd = div_round_closest(clk, baud * (bdiv + 1)); if cd < 1 || cd > CD_MAX.into() { continue; }