Jump to content

Really Soft UART

Recommended Posts

So I'll start up by admitting this is horrible code, you probably shouldn't use it and it's just generally a bad idea, but someone might find it useful. I'm targeting a 2452 without hardware UART and wanted to be able to printf solely for debugging purposes. I know that there's at least one implementation that uses Timer A and T0.1 to implement a soft UART. That version is much more bullet proof and if you actually need to get every last byte you should use that, or better yet a chip with a hardware UART.


That being said I only need this for debugging and can miss a character once in a while in exchange for being able to use any pin and having simpler interrupt logic. It's just a simple pure bit bang implementation but I wasn't able to find anything like it out there. Seems to work rather well at 57600 with only a junk character once in a great while. Anyways enjoy or laugh at, you won't hurt my feelings either way.


//#define BIT_DELAY __delay_cycles((1000000/9600) - 12) // 9600 BAUD
#define BIT_DELAY ; // 57600 BAUD

unsigned char *g_port_out;
unsigned char g_port_bit;

void uart_init(unsigned char *port_out, unsigned char *port_dir, unsigned char port_bit)
g_port_out = port_out;
g_port_bit = port_bit;

*port_dir |= port_bit;
*g_port_out |= port_bit;

// Clear screen
printf("\033[%d;%df", 0, 0);

int putchar(int c)
unsigned int tx_byte = (c | 0x100) << 1; // Add HIGH stop bit and low start bit

while (tx_byte) {
if (tx_byte & 0x1) {
*g_port_out |= g_port_bit;
} else {
*g_port_out &= ~g_port_bit;
tx_byte = tx_byte >> 1;


*g_port_out |= g_port_bit;

if (c == '\n')

return 1;

Link to post
Share on other sites
  • 4 weeks later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...