I haven't set it up for this functionality, but I connected regular LEDs to the pins on the send side (in place of the optocouplers) and the problem persisted (1 would produce the 1101 pattern on the LEDs).
Yes, the values show up correctly.
I took a more closer look at the code on the send side and made the following change -- see the comment // <--ADDED THIS LINE HERE
The code in recvWithStartEndMarkers() is from Robin2's post on serial communication. I had originally commented this line out and then removed it completely. Restoring it as shown in Robin2's original code solved the problem. Now when 1 is sent, 1 is also received on the receiving side.
I have looked into the meaning of '\0' in the past and have revisited it again just now. I'm not sure why receivedChars[ndx] = '\0'
would resolve the problem, and it would be interesting to learn why it works.
const byte OutputPins[6] = {2, 3, 4, 5, 6, 7};
//index is..................0, 1, 2, 3, 4, 5
String SerialMessageForCode;
const byte numChars = 4;
char receivedChars[numChars];
boolean newData = false;
void setup() {
for (int i = 0; i <= 5; i++) pinMode(OutputPins[i], OUTPUT);
Serial.begin(9600);
}
void SetOutputs(int value) {
for (int i = 0; i <= 5; i++)
digitalWrite(OutputPins[i], (value & (1 << i)) ? HIGH : LOW);
}
void loop() {
recvWithStartEndMarkers(); //Receive data enclosed in <> i.e., <Message>
sendData(); //Send data by optoisolator to other Leonardo
}
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0' // <--ADDED THIS LINE HERE
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
}
void sendData() {
if (newData == true) {
newData = false;
SetOutputs(atoi(receivedChars));
delay(2000);
}
}