Notes About Working with Various Arduino & Netduino Microcontroller Boards

Sunday, November 4, 2012

Using the uM-FPU Co-Processor to Convert Temperature from a TMP36 Sensor to Fahrenheit

Here is some code that I have gotten to work using the uM-FPU to convert the analog temperature reading from a TMP-36 sensor to degrees Fahrenheit. Of course, the accuracy of the TMP-36 doesn't really  warrant  such exact treatment. This is just intended as a learning exercise.

#include <SPI.h>
#include <Fpu.h>
#include <FpuSerial.h>

void setup()

  // Check to make sure uM-FPU is connected
  if (Fpu.sync() != SYNC_CHAR) {
    Serial.print("uM-FPU not detected");
    while(1) ; // stop if FPU not detected

void loop() {
  // Read int voltage from TMP35 (0 - 1023)
  // & cast it as a float
  float Tmp36 = (float) analogRead(1);
  // Convert to bytes for co-processor
  byte* bTmp36 = (byte*) &Tmp36;
  // Converion factor to get volts (0V - 5V)
  float vConvFactor  = 0.004882814;
  // Translate conversion factor to bytes for co-processor
  byte* bConvFactor = (byte*) &vConvFactor;
  // Use co-processor register 1 as accumulator
  Fpu.write(SELECTA, 1);
  // Put byte version of TMP36 reading into accumulator
  Fpu.write(FWRITEA, bTmp36[3], bTmp36[2], bTmp36[1], bTmp36[0]);
  // Load byte version of conversion factor into register 0
  // Multiply accumulator by value in register 0
  Fpu.write(FWRITE0, bConvFactor[3], bConvFactor[2], bConvFactor[1], bConvFactor[0], FMUL0);
  // Multiply by 100 to get degrees Celsius
  // Subtract .5V * 100 from result in accumulator. Easier to use subtract immediate with integer
  // rather than subtracting 0.5 before multiplying by 100.   
  // Multipy by 9 as 1st step toward converting to Fahrenheit.
  Fpu.write(FMULI, 100, FSUBI, 50, FMULI, 9);
  // Finish C -> F conversion by dividing by 5 and adding 32
  Fpu.write(FDIVI, 5, FADDI, 32);
  // Return result to Arduino - only 2 decimal places 
  float result = Fpu.readFloat();
  // Print result using FpuSerial - 6 decimal places

No comments:

Post a Comment