Hello,
I am working on a project were I am reading pressure and temperature from a sensor (BMP085) and put out a pwm signal to dim a lamp based on my readings. I am doing the project on an Arduino Uno board.
The code is very simple and use two standard Arduino libraries, wire.h for I2C communication with the sensor and BMP085.h for sensor commands.
But for some reason the code decides to crash sometimes for no obvious reason.
Can someone please take a look on my code and help me find any mistakes I may have done?
#include <Wire.h>
#include "BMP085.h"
BMP085 bmp;
static int ledPin = 9; // LED connected to digital pin 9
static int ledPinTemp = 10; // LED connected to digital pin 10
static int brightness = 0;
static int brightnessPrevious = 0;
static int on=0;
void setup() {
//Serial.begin(9600);
bmp.begin();
pinMode(13, OUTPUT); /*I am using a flashing LED to tell me if the processor is still running*/
}
void loop() {
float currentPressure, currentTemperature, firstTemp, firstPressure;
int index;
firstTemp = bmp.readTemperature();
firstPressure = bmp.readPressure();
while(true)
{
currentPressure = bmp.readPressure();
currentTemperature = bmp.readTemperature();
if(on)
{
on=0;
digitalWrite(13, LOW);
}
else
{
on=1;
digitalWrite(13, HIGH);
}
/*
y = k * x
k = (y2 - y1)/(x2-x1)
79.69 = (255 - 0)/(27.9 - 24.7)
tmax = 27.9
tmin = 24.7
*/
brightness = (currentTemperature - firstTemp)*80;
if(brightness > (brightnessPrevious +5) )
{
brightness = brightnessPrevious +5;
}
else if(brightness < (brightnessPrevious -5))
{
brightness = (brightnessPrevious -5);
}
if(brightness < 0)
{
brightness =0;
firstTemp = bmp.readTemperature();
}
if(brightness > 255)
{
brightness =255;
}
analogWrite(ledPin, brightness);
Serial.println(brightness);
if(currentPressure < (firstPressure +50) )
{
firstTemp = bmp.readTemperature();
firstPressure = bmp.readPressure();
}
brightnessPrevious = brightness;
//Serial.println();
delay(100);
}
}