I currently have 2 Arduinos both hooked up to HC-12s and have successfully got them communicating. But I am now trying to be able to process the data sent across and store it as a variable so as to make comparisons. But I'm getting junk data that comes over with the code, which prevents me from being able to do these comparisons.
For example, from one arduino when I sent "stop" I received
stop<⸮=l⸮⸮⸮
I cant figure out what this junk is from, also, I've limited the receivedChars to a size of 4, why am I getting more than 4 characters?
The code from the sender
#include <SoftwareSerial.h>
SoftwareSerial HC12(3, 2); // HC-12 TX Pin, HC-12 RX Pin
void setup() {
Serial.begin(9600); // Serial port to computer
HC12.begin(9600); // Serial port to HC12
Serial.print("Checking HC-12 module: ");
HC12.write("AT"); //Check for response(this is sending data to the HC, the SET pin must be low for this to work)
delay(1000);
HC12.write("AT+RX"); //Gets configs of HC-12
}
void loop() {
while (HC12.available()) { // If HC-12 has data
Serial.write(HC12.read()); // Send the data to Serial monitor
}
while (Serial.available()) { // If Serial monitor has data
HC12.write(Serial.read()); // Send that data to HC-12
}
}
The simplified receiving code
#define BYTELENGTH 4 //Limited to 4 chars
#define ENDMARKER '\n' //To know when stop stop reading serial
SoftwareSerial HC12(3, 2); // HC-12 TX Pin, HC-12 RX Pin
Serial.begin(9600); //Fastest it can be on the nano
HC12.begin(9600); // Serial port to HC12s
char receivedChars[BYTELENGTH - 1];
int byteIndex;
char curChar;
while (HC12.available()) { // If HC-12 has data
curChar = HC12.read();
if(curChar != ENDMARKER){
receivedChars[byteIndex] = curChar;
byteIndex++;
}
}
if(strcmp(receivedChars,"") != 0){
Serial.println(receivedChars);
receivedChars[0] = 0;
}