Week 5

This example shows you how to set up a threshold value for your sensors once you start running your Arduino.

int sensorPin = 0; //the analog pin the TMP36's Vout (sense) pin is connected to
float threshold = 0.0; // threshold value
int numOfReading = 10; //number of readings (number of samples)
float totalVal = 0.0; //sum up of all sensor readings

const int LED = 11;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  for (int i = 0; i < numOfReading; i++) {
    totalVal = totalVal + getFah();
    Serial.print("total Value ");
    Serial.println( totalVal);
    delay(2);
  }
  threshold = totalVal / numOfReading;
  Serial.print("Threshold Value ");
  Serial.println( threshold);

  pinMode(LED, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  float fah = getFah();
  if (threshold < fah) {
    float dif = fah - threshold;
    float brightness = map(dif, 0, 20 , 0, 255);
    analogWrite(LED, brightness);
  }
}


float getFah() {
  int reading = analogRead(sensorPin);
  float voltage = reading * 5.0;
  voltage /= 1024.0;
  float temperatureC = (voltage - 0.5) * 100 ;  //converting from 10 mv per degree wit 500 mV offset
  float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;
  return temperatureF;
}


float getCel() {
  int reading = analogRead(sensorPin);
  float voltage = reading * 5.0;
  voltage = voltage / 1024.0;
  float temperatureC = (voltage - 0.5) * 100 ;  //converting from 10 mv per degree wit 500 mV offset
  return temperatureC;
}

 

This example shows you how to keep last 10 sensor readings in Arduino’s mind, and sum up those 10 values to find an average of the 10 values. You can use this example for smoothing your sensor values.

const int numArray = 10;
float val[numArray];
const int acc = 0;
float smooth = 0.0;
float sum = 0.0;


void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  for (int i = 0; i < numArray; i++) {
    val[i] = 0.0;
  }
}

void loop() {
  // put your main code here, to run repeatedly:

  for (int i = 1 ;  i < numArray; i++) {
    val[i - 1] = val[i];
    Serial.print( i );
    Serial.print("  " );
    Serial.println(val[i]);
  }
  val[9] = analogRead(acc);

  sum = 0 ;

  for (int i = 0 ;  i < numArray; i++) {
    sum = sum + val[i];
  }

  smooth = sum / (numArray);
  Serial.print("Smooth ");
  Serial.println( smooth);
}

 

 

Leave a Reply