0

I'm trying to make a quick proof of concept of two trinket M0s talking to each other via their RX and TX pins and I'm not able to get it working.

I uploaded sender and receiver sketches to two trinkets:

//sender.ino
char state[10] = "hello";

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

void loop()
{
    Serial.write(state, 5);
    delay(1000);
}

//receiver.ino
char state[10];

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

void loop()
{
    Serial.println("reading bytes");
    Serial.readBytes(state, 10);
    Serial.println(state);
    delay(1000);
}

After the uploads I wired the two trinkets together, jumping the RX of the first to the TX of the other and TX of the first to the RX of the other. I also connected their grounds to have a common ground.

wiring

I plugged the sender into a battery and the receiver into my computer. The problem I'm running into is that when I look at the serial monitor for the receiver instead of getting the expected "hello" I'm getting broken strings of "TestingOpen":

serial output

I double checked the pinout diagram and guide for the Trinket M0 to make sure I was using the correct RX/TX pins (pin 3 for RX, 4 for TX) and it all seems fine but obviously something is still going wrong.

Anyone know what I'm missing or misunderstanding?

0

1) you should use if (Serial.available()) before starting to read with readBytes. now you print random memory

2) readBytes is blocking. it waits for the next character until a timeout. default timeout is 1 second. after "hello" was received it waits a second. you could use readBytesUntil and some 'separator' character for example '\n' (new line)

3) readBytes returns the count of bytes read. you should use it to terminate the buffer

void loop()
{
  if (Serial.available()) {
    Serial.println("reading bytes");
    size_t l = Serial.readBytesUntil('\n', state, 10);
    state[l] = 0;
    Serial.println(state);
  }
}

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.