0

I'm working on a small project that is creating me a headache. I know arduimo (ATmega 328P .... etc. ..) has an internal voltage source code millivolts, but I would like to know how the full source code become percentage where 3 volts = 0% and 4.2 volts = % 100% ??? . I appreciate the help because in codes is not my forte. I leave the code so Help me complete. Thank you.

long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1126400L / result; // Back-calculate AVcc in mV
  return result;
}

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println( readVcc(), DEC );
  delay(1000);
}
8
  • 3
    Are we talking about the calculation X = (V - 3)* 100/(4.2 - 3) where V is the voltage (in volts) and X is the percentage? When V = 3 this gives X = 0, when V = 4.2 this gives X = 100
    – JIm Dearden
    Sep 2, 2014 at 20:21
  • @jim readVCC() returns a voltage in mV, so adjust for that and add as a answer :D
    – Passerby
    Sep 2, 2014 at 20:38
  • Mind you that the band gap reference is reasonably stable over time, but its absolute value in not very accurate. You may want to 'calibrate' the returned result from your readVcc function.
    – jippie
    Sep 2, 2014 at 21:00
  • The charge on my arduino and something I'm doing wrong it gives me error :-(
    – piopio
    Sep 2, 2014 at 21:38
  • Where did the code you posted come from? That's some pretty cryptic code.
    – Duncan C
    Sep 3, 2014 at 1:19

1 Answer 1

2

map()

unsigned char level = map(readVcc(), 3000, 4200, 0, 100);
7
  • 1
    You need to find a C language tutorial very badly, because you have no clue what you're doing, and you're not doing yourself or anyone else any favors like this. Sep 2, 2014 at 22:03
  • sorry did not mean to, I just needed help, so asked.Thanks anyway
    – piopio
    Sep 2, 2014 at 22:17
  • I do not in any way mind answering questions. The thing is that the fundamentals required to understand my answer are missing. Please take some time to familiarize yourself with C language structures. Sep 2, 2014 at 22:55
  • @IgnacioVazquez-Abrams, I agree with your comment about needing a grounding in C. However, your answer uses the map function, which is part of the Arduino libraries, not straight C.
    – Duncan C
    Sep 2, 2014 at 23:22
  • @DuncanC: Sure, but understanding how functions and function calls work and interrelate is. Sep 2, 2014 at 23:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.