Skip to content

Instantly share code, notes, and snippets.

@fjolnir
Created April 9, 2014 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fjolnir/10255347 to your computer and use it in GitHub Desktop.
Save fjolnir/10255347 to your computer and use it in GitHub Desktop.
#ifdef DEBUG
#include "usart.h"
#include "hardware.h"
#include "interrupt.h"
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#define TIMEOUT (30000)
static volatile bool _data_available;
static volatile unsigned char _received_char;
static volatile int foo = 0;
void usart_putc(unsigned char out)
{
while(!TXSTAbits.TRMT);
TXREG = out;
}
void usart_puts(const unsigned char *buf)
{
while(*buf != '\0') {
usart_putc(*buf++);
}
}
void usart_putln(const unsigned char *buf)
{
usart_puts(buf);
usart_putc('\n');
}
#define PRINTF_MAX_LEN (64)
void usart_printf(const unsigned char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
char outbuf[PRINTF_MAX_LEN+1];
char *outbuf_head = outbuf;
char *fmt_head = fmt;
uint16_t outlen = 0;
#define APPEND(c) do { \
if(outlen < PRINTF_MAX_LEN-1) { \
*outbuf_head++ = (c); \
++outlen; \
} else continue; \
} while(0)
char *temp;
while(*fmt_head != '\0' && outlen < PRINTF_MAX_LEN) {
if(*fmt_head == '%') {
char fmt_char = *(fmt_head+1);
fmt_head += 2;
switch(fmt_char) {
case 'd':
temp = itoa(outbuf_head, va_arg(ap, int), 10);
outlen += strlen(temp);
outbuf_head += strlen(temp);
break;
default:
APPEND('%');
APPEND(fmt_char);
}
} else
APPEND(*fmt_head++);
}
#undef APPEND
outbuf[outlen] = '\0';
usart_puts(outbuf);
va_end(ap);
}
unsigned char usart_read_char(void)
{
if(_data_available) {
_data_available = false;
return _received_char;
} else
return 0;
}
uint16_t usart_read(unsigned char *out_buf, uint16_t max_len)
{
unsigned char c;
uint16_t len = 0;
for(; len < max_len; ++len) {
c = 0;
while(c == 0) {
c = usart_read_char();
}
*out_buf++ = c;
if(c == '\0')
break;
}
return len;
}
void usart_interrupt_handler(void)
{
_data_available = true;
_received_char = RCREG;
// usart_putc(_received_char);
}
void usart_init(void)
{
// SPBRGL = 207 => 9600 baud
// SPBRGL = 34 => 57600 baud
SPBRGL = 34;
SPBRGH = 0;
BAUDCON = 0; // 8 bit baud rate generator used
TXSTA = 0;
TXSTAbits.TXEN = true; // Enable transmission
TXSTAbits.BRGH = true; // High baud rate
RCSTAbits.SPEN = true; // Enable serial port
RCSTAbits.CREN = true; // Enable continuous receival
// PIE1bits.RCIE = true; // Enable USART rcv interrupt
// PIE1bits.TXIE = false; // Disable USART snd interrupt
// KEEP_FUN(usart_interrupt_handler);
// int_register_handler(int_rx, &usart_interrupt_handler);
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment