2

I am trying to build a simple arduino thermometer that lights up a different LED depending on the temperature. I am using an adafruit 5v trinket and a 12 neopixel ring with a tmp36 temperature sensor. My problem is that only LED 11 lights up. I have tried changing the range to test the temperature and I know that my room is colder than this.Here is the code I'm using:

#include <Adafruit_NeoPixel.h>
#include <avr/power.h>

#define PIN            3
#define NUMPIXELS      12
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int delayval = 500; 
int sensorPin = 1;

void setup() {

#if defined (__AVR_ATtiny85__)
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif

  pixels.begin(); 
}

void loop() {

  int reading = analogRead(sensorPin);
  int voltage = reading * 5.0;
  voltage /= 1024; 
  int temp = (voltage - 0.5) * 100;
  temp = constrain(temp, 23, 35);
  temp = map(temp, 23, 35, 0, 11);

  pixels.setPixelColor(temp, 0, 255, 38);
  pixels.show();

  delay(100);

}

Help would be much appreciated. Thanks :)

  • please anyone. I really need help. – user3880247 Feb 13 '15 at 20:33
  • 2
    I don't know exactly what your code is doing, but I notice there are **real** values in the calculations and `voltage /= 1024` and then multiplying by 100 is going to be pretty crude working with `int`. Should you be using a `float` for all this before converting back to `int`? – Weather Vane Feb 13 '15 at 20:52
  • 1
    "only LED 11 lights up" is that when using the above code. Or is about in general. I suspect the initial - Are you really max'ing out your temp input? I would debug it on an UNO first putting in prints in the code as to see the numbers you are really getting. A suspect area may be you are not really getting the max number out from the MAP. – mpflaga Feb 13 '15 at 21:43
  • 1
    The first thing to do is `Serial.println(reading)` and see what you get. Also, the line `voltage/=1024` does integer division, which truncates the result. I'm guessing that `voltage` is always 0 after that line. Another thing to check with `Serial.println`. – user3386109 Feb 13 '15 at 22:09

1 Answers1

1

You need to consider the type of number (int vs float) you are using for your calculations. Math done with integers will truncate floating point results. The Math.round() function may help you get better results from your math.

You may want to consider something like:

voltage = Math.round(voltage/1024.0);

The division operation will take place with floating point precision, then you will get the rounded result. Rounding will round up (duh) if the result is closer to that integer value, else round down.

Also, AnalogRead() returns values from 0 to 1023. If you divide that (with truncation) by 1024 you will never get 1024.

I'd suggest looking at the example code on the Adafruit or Sparkfun sites, they give good examples of interpreting thermistor/thermocouple transducers.

Arduinerd
  • 53
  • 3