0
#include <VirtualWire.h>

int PWMB = 5; //Speed control

void setup(){
  Serial.begin(9600);

  //receiver setup
  vw_set_rx_pin(2);  
  vw_set_ptt_inverted(true); 
  vw_setup(2000);
  vw_rx_start();
}

void loop(){
  uint8_t buf[VW_MAX_MESSAGE_LEN]; 
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  if (vw_get_message(buf, &buflen)) // Non-blocking
  {
    int i;
    int column = 0;
    String message;
    int commands[30];

    for (i = 0; i < buflen; i++)
    { 
      //DEBUG:
      Serial.print(char(buf[i]));

      if(char(buf[i]) == '|'){
        commands[column] = message.toInt();
        message = "";
        column++;
      } else {
        message += char(buf[i]);
      }
    }

  commands[column] = message.toInt();
  }
}

This topic is the receiver side of my last topic: please explain the sketch attached that one sending date and this is a receiver.

questions:

  1. The transmitter transfer date array of [60] like: 523 | 487, here int commands[30]; just 30, is it OK?
  2. if(char(buf[i]) == '|') / commands[column] = message.toInt();, seems just convert the date before '|'?
  3. What is the result of message += char(buf[i]);?

Thanks

1

The transmitter transfer date array of [60] like: 523 | 487, here " int commands[30];" just 30, is it OK?

If you have a maximum of 59 characters (59 printable characters plus the NULL at the end equals 60), and each number is separated by a | character, then the maximum possible numbers you can have, if they are all single digit, is 30. So yes, an array of 30 integers is fine.

" if(char(buf[i]) == '|') / commands[column] = message.toInt();", seems just convert the date before '|'?

Yes. It takes whatever has been placed in message and converts it to an integer, then empties message ready for the next number.

what is the result of " message += char(buf[i]);"? Thanks

It adds the current character from the buffer (pointed to by i) to the end of the message string.

It's not the best way of doing it, and it can make a mess of your heap causing your Arduino to crash after a while.

Personally I would use strtok() directly on the buffer:

int i = 0;
char *part = strtok(buffer, "|");
while (part) {
    command[i] = atoi(part);
    i++;
    part = strtok(NULL, "|");
}

This of course assumes that buffer is properly NULL terminated.

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.