tinyport.c 1.98 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
 * tinyport.c
 *
 * Created: 11/23/2017 3:31:56 PM
 *  Author: Jake
 */ 

#include "tinyport.h"

tinyport_t tinyport_new(Uart *uart, Pio *port, uint32_t peripheral_abcd, uint32_t pinRX_bitmask, uint32_t pinTX_bitmask){
	tinyport_t tp;
	
	tp.uart = uart;
	tp.port = port;
	
	tp.peripheral_abcd = peripheral_abcd;
	
	tp.pinRX_bm = pinRX_bitmask; 
	tp.pinTX_bm = pinTX_bitmask;
	
	return tp;
}

void tp_init(tinyport_t *tp){
	tp->port->PIO_PDR = tp->pinRX_bm;
	tp->port->PIO_PDR = tp->pinTX_bm;
	
	// do abcdsr - a, b, c, d | 00, 01, 10, 11
	// don't ask why - but set RX pin first 
	/*
	switch(tp->peripheral_abcd){
		case PERIPHERAL_A:
			tp->port->PIO_ABCDSR[0] = ~tp->pinRX_bm;
			tp->port->PIO_ABCDSR[0] = ~tp->pinTX_bm;
			tp->port->PIO_ABCDSR[1] = ~tp->pinRX_bm;
			tp->port->PIO_ABCDSR[1] = ~tp->pinTX_bm;
			break;
		
		case PERIPHERAL_B:
			tp->port->PIO_ABCDSR[0] = tp->pinRX_bm;
			tp->port->PIO_ABCDSR[0] = tp->pinTX_bm;
			tp->port->PIO_ABCDSR[1] = ~tp->pinRX_bm;
			tp->port->PIO_ABCDSR[1] = ~tp->pinTX_bm;
			break;
			
		case PERIPHERAL_C:
			tp->port->PIO_ABCDSR[0] = ~tp->pinRX_bm;
			tp->port->PIO_ABCDSR[0] = ~tp->pinTX_bm;
			tp->port->PIO_ABCDSR[1] = tp->pinRX_bm;
			tp->port->PIO_ABCDSR[1] = tp->pinTX_bm;
			break;
		
		case PERIPHERAL_D:
			tp->port->PIO_ABCDSR[0] = tp->pinRX_bm;
			tp->port->PIO_ABCDSR[0] = tp->pinTX_bm;
			tp->port->PIO_ABCDSR[1] = tp->pinRX_bm;
			tp->port->PIO_ABCDSR[1] = tp->pinTX_bm;
			break;
		
		default:
			break;
	}
	*/
	
	// baud rate clock is the peripheral clock / (16 * clock divisor)
	// clock divisor is written in the UART_BRGR register
	// at the moment, 9600
Jake Read's avatar
Jake Read committed
68
	tp->uart->UART_MR = UART_MR_BRSRCCK_PERIPH_CLK | UART_MR_CHMODE_NORMAL | UART_MR_PAR_NO | UART_MR_FILTER_DISABLED;
69
70
71
72
73
74
75
76
77
78
79
	tp->uart->UART_BRGR = 977;
	tp->uart->UART_CR = UART_CR_TXEN | UART_CR_RXEN;
	
	// turn on the rxready interrupt
	tp->uart->UART_IER = UART_IER_RXRDY;
}

void tp_putchar(tinyport_t *tp, uint8_t data){
	while(!(tp->uart->UART_SR & UART_SR_TXRDY)); // but wait
	tp->uart->UART_THR = data;
}