I want 2 Arduinos Leonardo to communicate, send a string for instance, so I have to use Serial1
to communicate via RS232 on pins 0 (RX) and 1 (TX).
I need to write binary data in that pins, the problem is how can I send a String using Serial1.write
. Serial1.print
works without errors but I think it does not do what I want. Any suggestion?
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
while (!Serial); // while not open, do nothing. Needed for Leonardo only
}
void loop() {
String outMessage = ""; // String to hold input
while (Serial.available() > 0) { // check if at least one char is available
char inChar = Serial.read();
outMessage.concat(inChar); // add Chars to outMessage (concatenate)
}
if (outMessage != "") {
Serial.println("Sent: " + outMessage); // see in Serial Monitor
Serial1.write(outMessage); // Send to the other Arduino
}
}
this line Serial1.write(outMessage);
is giving me the error
"
no matching function for call to 'HardwareSerial::write(String&)'
"
Use toCharArry(), write() uses char*, not string, here is what i mean:
You're using the String object(Wiring/C++). The function is using C strings: Serial.write(char*). To turn it into a C string, you use the toCharArray() method.
If we do not allocate the memory for our C string with malloc, we will get a fault. The following code WILL crash.
In the Serial Monitor the only message we will get is: Using toCharArray. At that point execution stops. Now if we correct the problem and use malloc() to allocate memory for our buffer and also use free() when done....
The output we see in the Serial Monitor is: Using toCharArray This is some new text Freeing the memory No leaking!