Using Serial after using Pin 1 for GPIO

Hi Everyone.
I have an Arduino Due and experiencing a slight issue.

I would like to send custom width MARK and SPACE signals on a serial interface.
So my idea was to use the pin in GPIO mode and then switch to Serial like this:

	pinMode(TX_PIN,OUTPUT);
	
	// Mark before break (100 us)
	digitalWrite(TX_PIN, HIGH);
	delayMicroseconds(100);
	
	// Break 100 us
	digitalWrite(TX_PIN, LOW);
	delayMicroseconds(100);
	
	// Mark after break
	digitalWrite(TX_PIN, HIGH);
	delayMicroseconds(20);

	// Transfer over to normal serial mode
	Serial.begin(115200);

	_blockOfBytes = &sensor_db[0];
	Serial.write(_blockOfBytes,32);
	Serial.flush();

	Serial.end();

This gets called from loop every 250 milliseconds.

However the serial device never sends any bytes.
I see all the mark/space activity - but no serial data.

If I comment out everything before the Serial.begin() then the 32 bytes gets sent properly.
I've done much experimenting with this and it looks like Serial just doesn't want to send anything if the pin has previously been configured with pinMode().

I have tried setting the pin to all possible states (OUTPUT [HIGH/LOW], INPUT, INPUT_PULLUP) before callign Serial.begin() but nothing makes any difference.

It just seems as though the pin cannot be released for use by Serial afterhaving been set by pinMode()

Any ideas?

It was not designed to do what you want. Your best solution is either some external logic or use software serial and modify it for your purposes. Note software serial operates only in simplex mode.

Your idea should work fine on an AVR based Arduino, like the Uno or similar.

"Bit banged serial" will work on any processor, and you are free to introduce timing variations.

It looks like the Due inexplicably initializes the various USART pins in init() instead of in Serialx.begin() :frowning:

try adding the following code just before your "Serial.begin()" statement...

  // Initialize Serial port U(S)ART pins
  PIO_Configure(
    g_APinDescription[PINS_UART].pPort,
    g_APinDescription[PINS_UART].ulPinType,
    g_APinDescription[PINS_UART].ulPin,
    g_APinDescription[PINS_UART].ulPinConfiguration);

(from ArduinoCore-sam/variant.cpp at master · arduino/ArduinoCore-sam · GitHub )

1 Like

Thank you! That works :slight_smile: