How to use serial port pins as digital pins

If you are using Arduino MEGA 2560, you have 4 hardware serial ports (USART port to be precise). Not everyone needs to use all of them. You can, if you want, use Serial1,2,3 as regular digital pins, or GPIO (general purpose input and output). All you have to do is to call Serial1.end() before you set RX1 and TX1 with pinMode and digitalWrite/read.

What if you are in my situation: I have a few serial port sonic rangers. They have an enable pin that enables ranging if they are held high for over 20us. It also has a free running mode, with the enable pin internally pulled up. I was using the free running mode until some interference between two rangers were discovered. Now with my shield already designed and a few dozens in service, I need a way to retrofit them to work with a screw terminal block. Arduino header and jumper is not the solution when these units are deployed in the field. Fortunately I routed both TX and RX to the board’s edge and I can solder on some 2-pin block. But I still need RX to function so I can’t call Serial1.end().

This would need some register operation. If you are interested in the whole detail, the doc2549 from atmel has everything in chapter 22 (USART). There are example codes on P211. It’s pretty clear that the Transmit only functions when the TXEN1 bit of the UCSR1B register is set. The following is from that chapter:


The USART Transmitter is enabled by setting the Transmit Enable (TXEN) bit in the UCSRnB

Register. When the Transmitter is enabled, the normal port operation of the TxDn pin is overridden

by the USART and given the function as the Transmitter’s serial output. The baud rate,

mode of operation and frame format must be set up once before doing any transmissions. If synchronous

operation is used, the clock on the XCKn pin will be overridden and used as

transmission clock.


So all we need to do to get the GPIO function back is to reset that TXEN1 bit as such: cbi(UCSR1B,TXEN1);

I tested this and it worked. I was able to drive the sonic ranger with the TX1 pin and still receive data on the RX1 pin.

Leave a Reply