Kelly Kelly - 2 months ago 13
C++ Question

433 Receiver Arduino if statement

433 MHz receiver

Arduino environment

The transmitter sends Y, N or M which works just fine. The problem lies in the receivers code. The goal is, after the receiver has value message equal N, its suppose to trigger an if statement which would do a thing. I simply need to have a system that can determine if the receiver takes in a specific value.

void loop()
{
if (vw_get_message(message, &messageLength)) // Non-blocking
{
Serial.print("Received: ");
for (int i = 0; i < messageLength; i++)
{
Serial.write(message[i]);
const char *p = reinterpret_cast<const char*>(message);
if(p == "N")
{
Serial.print("if statement works when = N");
}
}
}
}


The problem, is it simply does not do the job, and after 2 weeks of struggle, I am completely at a loss. This code will compile and run, but the if statement is completely ignored.

Answer

Thankfully I was able to find a solution.

The working code:

void loop()
{
        if (vw_get_message(message, &messageLength))
    {
        for (int i = 0; i < messageLength; i++)
        {
             const char *p = reinterpret_cast<const char*>(message);
             if(p[0] == 'Y')
             {
                  Serial.print(" - Yes");
                  break;
             }
             else if(p[0] == 'N')
             {
                  Serial.print(" - No");
                  break;
             }
        }
        Serial.println();
    }
}

The point of const char *p = reinterpret_cast<const char*>(message); was to turn message, which is a byte, into a char. Yes p is a pointer, but it's pointing to a char, so with that, I can get the data in the char that p is pointing to by simply doing p[#]. A simple if statement can now be made

if(p[0] == 'M')
{
     ...
}