Overclock.net - An Overclocking Community - View Single Post - Arduino code help, way out of my depth

View Single Post
post #3 of (permalink) Old 03-01-2018, 04:38 AM
Mrzev
New to Overclock.net
 
Mrzev's Avatar
 
Join Date: Feb 2008
Location: Texas
Posts: 2,258
Rep: 96 (Unique: 76)
vout0-2 are calcuated before you read the voltage, so your actually using the voltage based on the previous iteration. You should move the read to the top so that the vouts get calculated after you get the reading.
Code:
void loop() {
  vout0 = (value * 3.98) / 1023.0; 
  vout1 = (value * 3.98) / 1023.0; 
  vout2 = (value * 3.98) / 1023.0; 
  value = analogRead(a0);

It depends on how you want to code it really. I like this approach better. Your doing your if else on the previous condition, leaving 4 possible options, and then you just set the values accordingly. A bit more optimized in this situation IMO.
Code:
if (vin0 < 14.4 && vin0 > 11.8) {
    digitalWrite(led_d11, HIGH);
    digitalWrite(led_d12, LOW);
    digitalWrite(led_d13, LOW);
  }
else if (vin1 < 11.8 && vin1 > 14.4) {
    digitalWrite(led_d11, LOW);
    digitalWrite(led_d12, HIGH);
    digitalWrite(led_d13, LOW);
  } 
  else if (vin2 < 11.8 && vin2 > 14.4){
    digitalWrite(led_d11, LOW);
    digitalWrite(led_d12, LOW);
    digitalWrite(led_d13, HIGH);
  }
  else {
    digitalWrite(led_d11, LOW);
    digitalWrite(led_d12, LOW);
    digitalWrite(led_d13, LOW);
  }
  delay(500);

Edit: You also can get more fancy by setting them all to low in the setup, and use a global variable to keep track of what was set last, and then before flipping the new, you flip the old off. By doing this your only flipping 1-2 leds instead of 3. You can also change it so that you can check to see if it is the same , prior to flipping them, so you can end up with 0-2 flips. But that just adds more work and stuff, and depending on the architecture, it may even take more cycles that way.




Last edited by Mrzev; 03-01-2018 at 04:47 AM.
Mrzev is offline