1

I have LED bar graph on pins 2-11. Eventually I want to use a voltage divider to figure out the amount of voltage left in a power supply. Currently, this script should set the number of LEDs on the bar graph based on round((v_actual/v_reference)*10), I am just using some placeholder numbers in the mean time to test this portion of the script e.g. v_actual of 5 and v_reference of 10. However, the convert variable keeps printing 0. I've checked that the other variables were passing and they are. What is the issue here?

#include <Wire.h>

int ledBarNum = 10;    // # of leds
int vref = 10;     // max voltage of power supply

void setup(){
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
}

void loop() {

  ledBarSetup(5);
}

void ledBarSetup(int v) {

  // logic vref=8; vactual or v = 4; (4/8)*10 = 2 
  // e.g. number of leds we need to light up to represent the total amt left

  Serial.println(v);
  Serial.println(vref);

  int convert = round((v/vref)*10);

  Serial.println(convert);

  ledBar(convert);



}

void ledBar(int n) {

  int startingPin = 2;

  for (int thisPin = 2; thisPin < ledBarNum; thisPin++) {

    if (thisPin <= n) {

      digitalWrite(thisPin, HIGH);

    } else {

      digitalWrite(thisPin, LOW);

    }

  }

}
1
  • 1
    In integer math, 5/10 is equal to 0. – Gerben Aug 10 '16 at 20:11
4

Both v and vref are integers, which means that integer division will be performed. if v is ever less than vref then the result will be 0. Multiply first, then divide.

1
  • ah yes I suppose I should have looked up the diff between int and float in arduino. Was completely unaware of this. Doing the multiply then divide method! (v*10/vref) – Alex Aug 10 '16 at 20:17

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.