Skip to content

Commit 03b04a2

Browse files
committed
kblight: Fix duty/percentage scaling
Signed-off-by: Daniel Schaefer <dhs@frame.work>
1 parent 731ec3f commit 03b04a2

2 files changed

Lines changed: 21 additions & 15 deletions

File tree

framework_lib/src/chromium_ec/commands.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,16 @@ impl EcRequest<()> for EcRequestPwmSetFanDutyV1 {
246246

247247
pub const PWM_MAX_DUTY: u16 = 0xFFFF;
248248

249+
pub fn percent_to_duty(percent: u8) -> u16 {
250+
let duty = percent as u32 * PWM_MAX_DUTY as u32;
251+
(duty / 100) as u16
252+
}
253+
254+
pub fn duty_to_percent(duty: u16) -> u8 {
255+
let percent = duty as u32 * 100;
256+
(percent / PWM_MAX_DUTY as u32) as u8
257+
}
258+
249259
#[repr(C, packed)]
250260
pub struct EcRequestPwmSetDuty {
251261
/// Duty cycle, min 0, max 0xFFFF

framework_lib/src/chromium_ec/mod.rs

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -770,7 +770,7 @@ impl CrosEc {
770770
/// * `percent` - An integer from 0 to 100. 0 being off, 100 being full brightness
771771
pub fn set_keyboard_backlight(&self, percent: u8) {
772772
debug_assert!(percent <= 100);
773-
let duty = percent as u16 * (PWM_MAX_DUTY / 100);
773+
let duty = percent_to_duty(percent);
774774

775775
let res = EcRequestPwmSetDuty {
776776
duty,
@@ -782,14 +782,12 @@ impl CrosEc {
782782
// Early systems (hx20/hx30) don't enable CONFIG_PWM_KBLIGHT in their EC firmware;
783783
// keyboard backlight is at generic PWM channel index 1.
784784
let res = match res {
785-
Err(EcError::Response(EcResponseStatus::InvalidParameter)) => {
786-
EcRequestPwmSetDuty {
787-
duty,
788-
pwm_type: PwmType::Generic as u8,
789-
index: 1,
790-
}
791-
.send_command(self)
785+
Err(EcError::Response(EcResponseStatus::InvalidParameter)) => EcRequestPwmSetDuty {
786+
duty,
787+
pwm_type: PwmType::Generic as u8,
788+
index: 1,
792789
}
790+
.send_command(self),
793791
other => other,
794792
};
795793
debug_assert!(res.is_ok());
@@ -806,17 +804,15 @@ impl CrosEc {
806804
// Early systems (hx20/hx30) don't enable CONFIG_PWM_KBLIGHT in their EC firmware;
807805
// keyboard backlight is at generic PWM channel index 1.
808806
let kblight = match res {
809-
Err(EcError::Response(EcResponseStatus::InvalidParameter)) => {
810-
EcRequestPwmGetDuty {
811-
pwm_type: PwmType::Generic as u8,
812-
index: 1,
813-
}
814-
.send_command(self)?
807+
Err(EcError::Response(EcResponseStatus::InvalidParameter)) => EcRequestPwmGetDuty {
808+
pwm_type: PwmType::Generic as u8,
809+
index: 1,
815810
}
811+
.send_command(self)?,
816812
other => other?,
817813
};
818814

819-
Ok((kblight.duty / (PWM_MAX_DUTY / 100)) as u8)
815+
Ok(duty_to_percent(kblight.duty))
820816
}
821817

822818
pub fn ps2_emulation_enable(&self, enable: bool) -> EcResult<()> {

0 commit comments

Comments
 (0)