0

Hoping someone can help me out in my conundrum here...

I currently am testing the SoftwareSerial library out to understand how I may use it in my project.

I have a wire running from pin 6 to pin 9, so that the TX talks straight to the RX.

I have written the following:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(6,9); //RX = 6 TX = 9

void setup() {

  Serial.begin(1200);
  mySerial.begin(1200);
}

void loop() {

  mySerial.write('F');
  delay(100); // attempting to allow time between write and read commands

  while (mySerial.available()>0) {
  Serial.println(mySerial.read());
  }
}

The whole point is just to see 'F' return in the Serial Monitor.

The output, unfortunately, is absolutely nothing! If I omit the while(mySerial.available>0) I just get -1 's down the lines of the Serial Monitor.

Thank you in advance!

3

SoftwareSerial cannot talk to itself. Since it is implemented in software and not hardware it can either send or receive at one time, but not both.

Look at the code for write in SoftwareSerial:

size_t SoftwareSerial::write(uint8_t b)
{

...

  cli();  // turn off interrupts for a clean txmit

...


  // Write each of the 8 bits
  for (uint8_t i = 8; i > 0; --i)
  {
    if (b & 1) // choose bit
      *reg |= reg_mask; // send 1
    else
      *reg &= inv_mask; // send 0

    tunedDelay(delay);
    b >>= 1;
  }

...

  SREG = oldSREG; // turn interrupts back on

...

}

Since it turns interrupts off, and interrupts are needed for it to detect incoming data, therefore it cannot detect incoming data while it is sending.

  • You're the best. Thank you. Hypothetically, if I make a big delay between the TX and RX, shouldn't that solve the problem? Say,1 full second? – Jonny Hyman Aug 14 '15 at 13:53
  • It would in hardware but not software. For SoftwareSerial the code actually goes into a timed loop (to receive) similar to the timed loop to send. It can't be doing both loops at once. If you connect SoftwareSerial to a HardwareSerial port it should work (the hardware works in the background). – Nick Gammon Aug 14 '15 at 21:16
  • Exactly what I needed. Thanks! You're the best! – Jonny Hyman Aug 14 '15 at 21:26

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.