Monday, April 13, 2015

Arduino Due muilt serial and serialEvent

Arduino Due have 4 hardware serial ports. This example show how to use two serial port together, Serial and Serial3. Serial connect to PC via USB, once data received from Serial, it will be transmitted out to Serial3. Once data received from Serial3, it will be transmitted to Serial.

int LED = 13;
boolean LEDst = false;

void setup() {
  Serial.begin(9600);
  Serial3.begin(9600);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LEDst);
}

void loop() {
  while (Serial.available() > 0) {
    char a = Serial.read();
    Serial3.write(a);
  }
  
  while (Serial3.available() > 0) {
    char a = Serial3.read();
    Serial.write(a);
    ToggleLED();
  }
}

void ToggleLED(){
  digitalWrite(LED, LEDst = !LEDst);
}

Connect a wire between TX3 and RX3 on Arduino Due board, such that anything type in Arduino IDE Serial Monitor will be sent to Serial, then to Serial3, and loop back to Serial3, and sent back to Serial, to Serial Monitor.
It's another version do the same thing, with serialEvent3() for Serial3.

SerialEvent occurs whenever a new data comes in the hardware serial RX.  This routine is run between each time loop() runs, so using delay inside loop can delay response.  Multiple bytes of data may be available. ~ reference: http://arduino.cc/en/Tutorial/SerialEvent

int LED = 13;
boolean LEDst = false;

void setup() {
  Serial.begin(9600);
  Serial3.begin(9600);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LEDst);
}

void loop() {
  while (Serial.available() > 0) {
    char a = Serial.read();
    Serial3.write(a);
  }
  
}

void serialEvent3() {
  while (Serial3.available() > 0) {
    char a = Serial3.read();
    Serial.write(a);
    ToggleLED();
  }
}

void ToggleLED(){
  digitalWrite(LED, LEDst = !LEDst);
}

No comments:

Post a Comment