Skip to content

Commit

Permalink
iio: adc: ad400x: Simplify period calculation
Browse files Browse the repository at this point in the history
Instead of assigning the value `ref_clk_period_ps * target` assign
`DIV_ROUND_CLOSEST_ULL(1000000000000, freq)` which apart from rounding
loss is the same value:

	  ref_clk_period_ps * target
	= DIV_ROUND_CLOSEST_ULL(1000000000000, st->ref_clk_rate) * DIV_ROUND_CLOSEST_ULL(st->ref_clk_rate, freq)
	≅ 1000000000000 / st->ref_clk_rate * st->ref_clk_rate / freq
	= 1000000000000 / freq

With freq = 1800000 and st->ref_clk_rate = 166666665 (which I think are
reasonable assumptions) the exact result is 555555.5555555555. The
previous calculation yielded 558000, while now it gives 555556.

Signed-off-by: Uwe Kleine-König <[email protected]>
  • Loading branch information
Uwe Kleine-König authored and nunojsa committed Jul 12, 2024
1 parent 74c051f commit f042b95
Showing 1 changed file with 2 additions and 3 deletions.
5 changes: 2 additions & 3 deletions drivers/iio/adc/ad400x.c
Original file line number Diff line number Diff line change
Expand Up @@ -192,16 +192,15 @@ static int ad400x_get_sampling_freq(struct ad400x_state *st)

static int __ad400x_set_sampling_freq(struct ad400x_state *st, int freq)
{
unsigned long long target, ref_clk_period_ps;
unsigned long long ref_clk_period_ps;
struct pwm_state cnv_state;

/* Sync up PWM state and prepare for pwm_apply_state(). */
pwm_init_state(st->cnv_trigger, &cnv_state);

target = DIV_ROUND_CLOSEST_ULL(st->ref_clk_rate, freq);
ref_clk_period_ps = DIV_ROUND_CLOSEST_ULL(1000000000000,
st->ref_clk_rate);
cnv_state.period = ref_clk_period_ps * target;
cnv_state.period = DIV_ROUND_CLOSEST_ULL(1000000000000, freq);
cnv_state.duty_cycle = ref_clk_period_ps;
cnv_state.time_unit = PWM_UNIT_PSEC;
return pwm_apply_state(st->cnv_trigger, &cnv_state);
Expand Down

0 comments on commit f042b95

Please sign in to comment.