0

I have the following code:

      uint8_t buf[1];
      uint8_t buflen = 1;
      if (driver.recv(buf, &buflen)) // Non-blocking
         {
            int i;
            // Message with a good checksum received, dump it.
            Serial.print("Message: ");
            Serial.println((char*)buf);//this prints out okay
            highPins[(char*)buf] = 1;
         }

The problem is in highPins[(char*)buf]. highPins is array, and in (char*)buf I get index number. When I display it with Serial.println, it shows the number, but here it does not. I am guessing its because (char*)buf is not a number. I have tried to convert it to int with few functions I have found online, but it was unsuccessful. Any help is appreciated :)

3
  • String(buf).toInt() is how i do it, but there might be better ways...
    – dandavis
    Commented Jan 2, 2018 at 21:29
  • highPins[buf[0] - '0'] = 1; should do the trick :) Commented Jan 2, 2018 at 23:38
  • Note that Serial.println(const char[]) expects a NUL-terminated buffer. It will read your memory starting at &buf and continue until it finds a NUL byte. Commented Jan 3, 2018 at 18:00

2 Answers 2

1

I would suggest improving your code slightly as follows:

  uint8_t buf;
  uint8_t buflen = 1;
  if (driver.recv(&buf, &buflen)) // Non-blocking
     {
        int i;
        // Message with a good checksum received, dump it.
        Serial.print("Message: ");
        Serial.println(buf);//this prints out okay
        highPins[buf] = 1;
     }

The important point is that you do not need to declare buf as an array of just one element, but just declare the element itself (as uint8_t) and pass its address (&buf) to driver.recv(...).

As @Majenko suggested, you should alos check buf before using it as an index to highPins array, in order to avoid using an index bigger than teh array size.

2
  • The thing is, when I use your code, I get a strange result. I send string 33 with driver.send("33", sizeof("33")); , and with your code I get "53" over the serial. Any idea on what might be causing it? Commented Jan 7, 2018 at 1:18
  • You have to know what gets transferred between both devices: is that string or numbers? Your question made me think this was numbers (in binary representation, not as ASCII strings). You probably need to provide more details in your question.
    – jfpoilpret
    Commented Jan 7, 2018 at 1:21
0

The function you want is atoi.

int pinno = atoi((char *)buf);

I would suggest checking that the result is in the right range before using it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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