// (C) 2020 Philip Endecott.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENCE.txt or copy at https://www.boost.org/LICENSE_1_0.txt

#ifndef lipstick_adc_hh
#define lipstick_adc_hh

#include "registers.hh"
#include "clocks.hh"


inline uint32_t adcr() 
{
  constexpr int max_clk = 4'500'000;
  constexpr int min_divisor = f_pclk / max_clk;  // This rounds down, but the value we need is minus 1.
  return (min_divisor << 8)  // CLKDIV bits 15:8
       | (1 << 21);          // PDN bit to enable.
}


inline void setup_adc()
{
  *ADCR = adcr();
// FIXME check if I need to do some pin mux settings as well.
}


inline void start_adc_read(int channel)
{
  *ADCR = adcr()
        | (1 << channel)   // Set one SEL bit (7:0) for required channel.
        | (1 << 24);       // Set START bits (26:24) to 001 to start conversion now.
}


inline int adc_read(int channel)
{
  start_adc_read(channel);
  while (!(*ADGDR & 0x80000000)) {} // Wait for DONE bit to be set
  int result = (*ADGDR & 0xffff) >> 6;
  return result;
}


#endif

