Serial Port Transmitting & Receiving

Hello guys, I am a newbie in Arduino. I need advice and guidance in programming.

I am trying to integrate Arduino Mega, Bluetooth (HC-05) and temperature sensor (TMP102) with a mobile application. TMP102 will constantly detect temperature and this data will be sent to the mobile app to display. However, I am using the internal serial port Tx (D1) & RX(D0) of Arduino Mega. It turns out to receive data 1 by 1.

Let's say the temperature is 32.87, it will first display .87 and then 32.87. My ideal idea was constantly displaying 32.87. Anyone who has experience in this and can guide me what should I do to correct it?

#include <SparkFunTMP102.h>
#define led 13
const int ALERT_PIN = A0;
TMP102 sensor0(0x48);
float temperature;
float tempCelsius;
boolean alertPinState, alertRegisterState;
const byte BTpin = 4;
boolean BTconnected = false;

void setup()
{
  Serial.begin(9600); 
  sensor0.begin();
  pinMode(ALERT_PIN,INPUT);
  sensor0.setFault(0);  // Trigger alarm immediately 
  sensor0.setAlertPolarity(1);
  sensor0.setAlertMode(0); // Comparator Mode.
  sensor0.setConversionRate(3); //conversion at 4Hz 
  sensor0.setExtendedMode(0); //12bits
  sensor0.setHighTempC(32.0); // Highest Threshold 
  sensor0.setLowTempC(26.67); // Lowest Threshold
  
  pinMode(led, OUTPUT);
  pinMode(BTpin, INPUT);   
  Serial.println("Arduino is ready");
  Serial.println("Connect the HC-05 to an Android device to continue");
  while (!BTconnected)
  {
     if ( digitalRead(BTpin)==HIGH)  { BTconnected = true;};
  }
  Serial.println("HC-05 is now connected");
  Serial.println("");
  readTemp();
}

void loop()
{
   Serial.println(temperature);
   Serial.println("|");
   if(Serial.available() > 0) 
  {
    char data = Serial.read();
    Serial.print("Data received: ");
    Serial.println(data);
    if (data == '1')
    {
      Serial.println("LED ON");
      digitalWrite(led, HIGH);
    }
    else if (data == '0')
    {
      Serial.println("LED OFF");
      digitalWrite(led, LOW);
    }
  }
}

void readTemp()
{
  sensor0.wakeup();
  temperature = sensor0.readTempC();
  alertPinState = digitalRead(ALERT_PIN); 
  alertRegisterState = sensor0.alert();
  sensor0.sleep();


  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.print(" C");
  Serial.print("\tAlert Pin: ");
  Serial.print(alertPinState);
  Serial.print("\tAlert Register: ");
  Serial.println(alertRegisterState);
  delay(1000);
}

Hardware connections
HC-05
VCC - 3.3V
GND - GND
RX - TX (D1)
TX - RX 9D0)
STATE - D4

TMP102
VCC - 3.3V
GND - GND
SDA - SDA
SCL - SCL
ALT - A0

Thanks in advance

It seems to me you are trying to use Serial for two purposes at the same time - communicating with the PC and communicating with the HC05.

A Mega has 3 spare HardwareSerial ports so the HC05 should be connected to Serial1 - pins 18 and 19.

...R

Hi Robin,

Thanks for your help! I changed the pins and it works. :slight_smile: