Bidirectional Serial Communication with Teensy

Status
Not open for further replies.

crazy sketti

New member
I've got a board which requires communication between a Teensy 4.1 and a Teensy 4.0. I decided to use Serial to achieve this, but am having trouble with them communicating. Each board has to be able to communicate with the other at the press of a button. The 4.1 should be able to send bytes (or strings) of data to the 4.0, and the 4.0 needs to send data to the 4.1 (strings), each when a button is pressed. I've attached a simplified code for each board. Is there a certain library I have to use to accomplish this, or is communication only 1 way (master/slave only)?

Code:
//Teensy 4.0 Code

#include <Bounce.h>

const int HomeEntpin = 25;
String sendchoice = "Teensy 4.0 command received";
int recchoice = 0;
Bounce H = Bounce(HomeEntpin, 10);

#include <Bounce.h>

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  pinMode(HomeEntpin, INPUT);
}

void loop() {
  if (H.update()) {
    if (H.fallingEdge()) {
      Serial.println("A pressed");
      Serial1.println(sendchoice);
      Serial.println("String sent");
    }
  }
  if (Serial2.available() > 0) {
    Serial.println("Serial 1 Read");
    recchoice = Serial1.read();
    Serial.println(recchoice);
    delay(100);
  }
}

Code:
//Teensy 4.1 code

#include <Bounce.h>

const int Apin = 20;
Bounce A = Bounce(Apin,10);
String recchoice = "";
int sendchoice = 1;

void setup() {
  Serial.begin(9600);
  Serial2.begin(9600);
  pinMode(Apin, INPUT);

}

void loop() {
  if (A.update()) {
    if (A.fallingEdge()) {
      Serial.println("A pressed");
      Serial2.write(sendchoice);
      Serial.println("Int 1 sent");
    }
  }
  if (Serial2.available() > 0) {
    Serial.println("Serial 2 Read");
    recchoice = Serial2.read();
    Serial.println(recchoice);
    delay(100);
  }
}
 
In your first program, change
Code:
  if (Serial2.available() > 0) {
to
Code:
  if (Serial1.available() > 0) {
 
Thanks for the correction, thebigg. With that change the simplified code works.

I just found out why it didnt for my main code: I accidentally allocated pin 0 (RX) as an regular digital input. Its been fixed and now properly works. Sorry for wasting everyones time lol.
 
Status
Not open for further replies.
Back
Top