Advertisement
olelek

read_internal_temp_sensor

Sep 7th, 2014
370
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. // Internal Temperature Sensor
  2. // Example sketch for ATmega328 types.
  3. //
  4. // April 2012, Arduino 1.0
  5.  
  6. void setup()
  7. {
  8.   Serial.begin(9600);
  9.  
  10.   Serial.println(F("Internal Temperature Sensor"));
  11. }
  12.  
  13. void loop()
  14. {
  15.   // Show the temperature in degrees Celcius.
  16.   long pomiar = readTemp();
  17.   Serial.print("ADC: ");
  18.   Serial.print(pomiar);
  19.   Serial.print("\t Temperatura: ");
  20.   Serial.println(normalizeTemperature(pomiar),3);
  21.   delay(1000);
  22. }
  23.  
  24. long readTemp() {
  25.   // Read temperature sensor against 1.1V reference
  26.   #if defined(__AVR_ATmega32U4__)
  27.     ADMUX = _BV(REFS1) | _BV(REFS0) | _BV(MUX2) | _BV(MUX1) | _BV(MUX0);
  28.     ADCSRB = _BV(MUX5); // the MUX5 bit is in the ADCSRB register
  29.   #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
  30.     ADMUX = _BV(REFS1) | _BV(MUX5) | _BV(MUX1);
  31.   #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
  32.     ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1) | _BV(MUX0);
  33.   #else
  34.     ADMUX = _BV(REFS1) | _BV(REFS0) | _BV(MUX3);
  35.   #endif
  36.  
  37.   delay(2); // Wait for ADMUX setting to settle
  38.   ADCSRA |= _BV(ADSC); // Start conversion
  39.   while (bit_is_set(ADCSRA,ADSC)); // measuring
  40.  
  41.   uint8_t low = ADCL; // must read ADCL first - it then locks ADCH
  42.   uint8_t high = ADCH; // unlocks both
  43.   long result = (high << 8) | low; // combine the two
  44.  
  45.   return result;
  46. }
  47.  
  48. float normalizeTemperature(long rawData) {
  49.   // replace these constants with your 2 data points
  50.   // these are sample values that will get you in the ballpark (in degrees C)
  51.   float temp1 = 17;
  52.   long data1 = 280;
  53.   float temp2 = 22.0;
  54.   long data2 = 294;
  55.  
  56.   // calculate the scale factor
  57.   float scaleFactor = (temp2 - temp1) / (data2 - data1);
  58.  
  59.   // now calculate the temperature
  60.   float temp = scaleFactor * (rawData - data1) + temp1;
  61.  
  62.   return temp;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement