简体   繁体   中英

Using Serial.read() with const char * in Arduino RadioHead

I'm trying to send text over the serial monitor using RadioHead ASK. Text input from the serial monitor is not sent to the receiver. I have read up on C++ theory with char arrays and pointers... it's not computing in my head :). How can *msg exist without first declaring char msg? Please see the sample below. It would be great if you could explain the theory with any sample solution. Thank you for your help!

void setup() {
  Serial.begin(9600); // Debugging only
  if (!driver.init())
    Serial.println("init failed");
  else
    Serial.println("TX");
}

void loop() {
  const char *msg = Serial.read();
  driver.send((uint8_t *)msg, strlen(msg));
  driver.waitPacketSent();
  delay(200);
}

This seems to work. strMsg.toCharArray(msg, i); Can you please comment on the efficiency of the code? Is there a better way? Thanks!

void setup() {
  Serial.begin(9600); // Debugging only
  if (!driver.init())
    Serial.println("init failed");
  else
    Serial.println("TX");
}

void loop() {
if (Serial.available() > 0)
  {
String strMsg = "";
int i;

strMsg = Serial.readString();
i = (strMsg.length() + 1);
char msg[i] = {};
Serial.print("Sent: ");
Serial.println(strMsg);
Serial.print("Size: ");
Serial.println(i);
strMsg.toCharArray(msg, i);
driver.send((uint8_t *)msg, strlen(msg));
driver.waitPacketSent();
delay(200);
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM