Reading temperature sensor through HC-05 from Arduino Mega

Hi, i am still new to this and i have been trying different ways to solve the problem to no avail. What i am trying to archive is to be able to activate actuator and display the value of the temperature sensor, I was able to activate actuator but not able to receive the data from temperature sensor Thank you in advance for the help.

Sensor: Grove - Temperature Sensor V1.2 (Temp Only)

The empty box are for making the button/list picking central to my phone

Code(App Inventor):

image

image

image


Arduino Mega code:

type or paste code here
```#include <RGBmatrixPanel.h>
#include <Servo.h>

#define CLK 11  // For Arduino Mega
#define OE  9
#define LAT 10
#define A   A0
#define B   A1
#define C   A2
#define D   A3

#define LED 12

int servoPin = 4; // Declare the Servo pin 
Servo Servo1; 
RGBmatrixPanel matrix(A, B, C, D, CLK, LAT, OE, false, 64);

//Temperature
int sensorPin = A4; // Analog pin where the temperature sensor is connected
int sensorValue;
float temperature;

void setup() 
{
    
    //Led
    pinMode(LED, OUTPUT);

    //Servo motor
    Servo1.attach(servoPin); 
    int startpoint = 5;  // Set the starting point (0 to 180)
    Servo1.write(startpoint);  // Move the servo to the start position

    //Serial Monitor
    Serial.begin(9600);       // Start Serial Monitor for debugging
    Serial1.begin(9600);      // Start Bluetooth Serial on Serial1
    Serial.println("Bluetooth test: Waiting for messages...");

    //Matrix
    matrix.begin();
    matrix.setTextSize(1);      // Set text size to 1 (8 pixels high)
    matrix.setTextWrap(false);  // Don't wrap text when false, wrap text when true
    matrix.fillScreen(matrix.Color333(0, 0, 0)); // Clear the matrix screen
    matrix.setTextColor(matrix.Color333(7, 7, 0)); // Bright yellow text color
   
}

void loop() 
{
    sensorValue = analogRead(sensorPin); // Read the raw analog value from the sensor
    temperature = (sensorValue * 5.0 / 1023.0) * 10;


    // Send temperature to Serial Monitor
    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.println(" °C");

    // Send temperature data via Bluetooth
    Serial1.println(String(temperature));
    Serial.println(String(temperature));
   
    delay(1000); // Wait for 1 second before reading again

    static String incomingMessage = "";
    bool messageComplete = false;

    // Collect data from Bluetooth serial input
    while (Serial1.available()) 
    {
        char c = Serial1.read();
        if (c >= 32 && c <= 126) 
        {
            incomingMessage += c;
        } 
        else if (c == '\n')  // End of message (newline received)
        {
            messageComplete = true;
            incomingMessage.trim();
            incomingMessage.toLowerCase();  // Convert to lowercase for case-insensitive check
            Serial.print("Received Message: ");
            Serial.println(incomingMessage);
        }
    }

    // Process complete message
    if (messageComplete) 
    {
        if (incomingMessage == "on" || incomingMessage == "1") 
        {
            digitalWrite(LED, HIGH);
        } 
        else if (incomingMessage == "off" || incomingMessage == "0") 
        {
            digitalWrite(LED, LOW);
        } 
        else if (incomingMessage == "open")
        {
            Servo1.write(65); // Move the servo to 65 degrees
            delay(1000);
        }
        else if (incomingMessage == "close") 
        {
            Servo1.write(5); // Move the servo to 5 degrees
            delay(1000);
        }
        else 
        {
            displayMessage(incomingMessage.c_str());  // Display other messages on matrix
        }

        incomingMessage = "";  // Clear the message buffer
        messageComplete = false;  // Reset the flag
    }
}

void displayMessage(const char* message) 
{
    matrix.fillScreen(matrix.Color333(0, 0, 0)); // Clear the matrix screen
    int textWidth = strlen(message) * 6;         // Approximate width: 6 pixels per character

    if (textWidth <= 64) 
    {
        // If the message fits, display it statically on the left side
        matrix.setCursor(0, 0);
        matrix.print(message);
    } 
    else 
    {
        // If the message is too wide, scroll it from left to right
        //for (int x = 64; x <= -textWidth; x--) 

        // If the message is too wide, scroll it from right to left
        for (int x = 64; x >= -textWidth; x--) 
        {
            matrix.fillScreen(matrix.Color333(0, 0, 0)); // Clear screen each time
            matrix.setCursor(x, 0);                     // Update cursor position
            matrix.print(message);
            delay(50);                                  // Adjust scrolling speed here
        }
    }
}

I am guessing you didn't set the Bluetooth Delimiter to 10.

Standard advice:

Be sure to use println() at the end of each message to send from the sending device, to signal end of message.

Only use print() in the middle of a message.

Be sure not to println() in the middle of a message, or you will break it into two short messages and mess up the item count after you split the message in AI2.

Do not rely on timing for this, which is unreliable.

In the AI2 Designer, set the Delimiter attribute of the BlueTooth Client component to 10 to recognize the End of Line character.
BlueToothClient1_Properties
Also, return data is not immediately available after sending a request,
you have to start a Clock Timer repeating and watch for its arrival in the Clock Timer event. The repeat rate of the Clock Timer should be faster than the transmission rate in the sending device, to not flood the AI2 buffers.

In your Clock Timer, you should check

  Is the BlueTooth Client still Connected?
  Is Bytes Available > 0?
     IF Bytes Available > 0 THEN
       set message var  to BT.ReceiveText(-1) 

This takes advantage of a special case in the ReceiveText block:

ReceiveText(numberOfBytes)
Receive text from the connected Bluetooth device. If numberOfBytes is less than 0, read until a delimiter byte value is received.

If you are sending multiple data values per message separated by | or comma, have your message split into a local or global variable for inspection before trying to select list items from it. Test if (length of list(split list result) >= expected list length) before doing any select list item operations, to avoid taking a long walk on a short pier. This bulletproofing is necessary in case your sending device sneaks in some commentary messages with the data values.

Some people send temperature and humidity in separate messages with distinctive prefixes like "t:" (for temperature) and "h:" (for humidity).
(That's YAML format.)

The AI2 Charts component can recognize these and graph them. See Bluetooth Client Polling Rate - #12 by ABG

To receive YAML format messages, test if the incoming message contains ':' . If true, split it at ':' into a list variable, and find the prefix in item 1 and the value in item 2.

1 Like

i have tried changing the delimiterbyte as u mentioned but its still the same.

image

(Canned Reply: ABG- Export & Upload .aia)
Export your .aia file and upload it here.
export_and_upload_aia

FYP.aia (37.6 KB)

I can open your aia in 6 hours.
(I am sleeping)

1 Like

alright thanks for helping me out :slight_smile:

Try:

Change this:

    Serial1.println(String(temperature));
    Serial.println(String(temperature));

To this:

    Serial1.print(temperature);
    Serial.println();  //ASCII 10 in App Inventor

just change it, still remain the same i think it would be my app inventor side at this point if nothing else is wrong with my arduino code.

image

...Also do not use delay(1000) in your loop - everything is 'off' during that time and that can adversely affect sensor value accuracy. Instead, use an elapsed time code.

Here is an example that you can adapt:

//vars
unsigned long lgUpdateTime;
char val[];

void setup()
{
         Serial.begin(9600);
         Serial1.begin(9600);
         lgUpdateTime = millis();
}

void loop()
{
         //Excute loop every 1/2 second
	     if(millis() - lgUpdateTime > 500) 
         {
               lgUpdateTime = millis();
               
               if (Serial1.available() > 0)
               {
                    //Read Data From App
                    val = Serial1.read();
               
                    //Send to Arduino Serial Monitor on PC (via USB cable)
                    Serial.println(val)
               }
         }
}

A golden rule is to ensure data frequency is sensible. For example, there isn't any point in sending data to an App for display every second, the human eye cannot tolerate it. If you don't need more than one reading per hour, that is what should be set. On the other hand, if the data is to produce a live 'line' chart, that will be drawn more smoothly with data sent at short intervals. So, apply common sense

I don't see anything wrong in your aia export, if you are sending line feeds as delimiters.

I suggest getting a BlueTooth terminal program from the Play Store, and seeing if it can connect to your sketch and receive data from it.

This will verify that the sketch is indeed working to transmit data.

1 Like

I have solve the problem and it was a simple one at that.After checking my hardware again i realized that my RX and TX was connected wrongly to voltage divider which allow data to be receive but not send out.

1 Like

It's always difficult to check your own work because of course you think it's right - we have all been there and done that! Well done for tracking the fault down.

1 Like