0

I have a project where I have to combine 4 sensors and get data wireless via Bluetooth (HC05). I just want help with combining just 1 sensor sketch and the Bluetooth sketch. I want the data from the temperature sensor to be displayed on my phone.

Temperature sensor code:

#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 2


OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();
}


void loop(void)
{
  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures();
  Serial.println("DONE");

  Serial.print("Temperature is: ");
  Serial.print(sensors.getTempCByIndex(0)); 
  delay(1000);
}



Bluetooth code:

#include <SoftwareSerial.h>
SoftwareSerial BT(11, 10);
int ledPin = 8;
int state = 0;

void setup()

{
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
BT.begin(9600);   
}

void loop() {
  if(BT.available() > 0){ 
  state = BT.read();

  }
    if (state == '0'){
      digitalWrite(ledPin, LOW);
      BT.println("LED: OFF");
      state = 0;
    }
    else if (state == '1'){
      digitalWrite(ledPin, HIGH);
      BT.println("LED: ON");;
      state = 0;

    }
}
0

Instead of writing it all out, I give some tips:

  • First combine the content of both setup functions. You can remove duplicate lines (e.g. Serial.begin(9600); is needed only once. Keep the order in a logical way.

  • Than combine the content of both loop functions. However, the delay could cause a problem. Replace this by keeping a variable with the current time, and check when it's at least a second ago you checked the temperature sensor, if so, measure the sensor (and update the variable to the current time).

So you get something like:

unsigned long lastSensorMeasurement;

void setup()
{
   // Combination of both setup functions

   lastSensorMeasurement = millis();
}

void loop()
{
   // Process sensor
   if (lastSensorMeasurement + 1000 >= millis())
   {
      // Code for sensor as in loop
   }

   // Process Bluetooth
   // Code for bluetooth as in loop
}
  • 1
    now() only has a resolution of 1 second. Usually you use millis() for timing, which gives 1/1000 of a second resolution. – Duncan C Mar 6 at 13:27
  • @DuncanC Thanks ... of course I meant that; I updated my answer, thanks for the notification. – Michel Keijzers Mar 6 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.