Root/atusb/fw/spi.c

1/*
2 * fw/spi.c - ATmega8 family SPI I/O
3 *
4 * Written 2011, 2013 by Werner Almesberger
5 * Copyright 2011, 2013 Werner Almesberger
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13
14#include <stdbool.h>
15#include <stdint.h>
16
17#include <avr/io.h>
18
19#include "board.h"
20#include "spi.h"
21
22
23static bool spi_initialized = 0;
24
25
26void spi_begin(void)
27{
28    if (!spi_initialized)
29        spi_init();
30    CLR(nSS);
31}
32
33
34uint8_t spi_io(uint8_t v)
35{
36// while (!(UCSR1A & 1 << UDRE1));
37        UDR1 = v;
38        while (!(UCSR1A & 1 << RXC1));
39        return UDR1;
40}
41
42
43void spi_end(void)
44{
45// while (!(UCSR1A & 1 << TXC1));
46    SET(nSS);
47}
48
49
50void spi_recv_block(uint8_t *buf, uint8_t n)
51{
52    if (!n)
53        return;
54        UDR1 = 0;
55    while (--n) {
56        while (!(UCSR1A & 1 << RXC1));
57        *buf++ = UDR1;
58        UDR1 = 0;
59    }
60    while (!(UCSR1A & 1 << RXC1));
61    *buf++ = UDR1;
62}
63
64
65void spi_off(void)
66{
67    spi_initialized = 0;
68    UCSR1B = 0;
69}
70
71
72void spi_init(void)
73{
74    SET(nSS);
75    OUT(SCLK);
76    OUT(MOSI);
77    OUT(nSS);
78    IN(MISO);
79
80    UBRR1 = 0; /* set bit rate to zero to begin */
81    UCSR1C = 1 << UMSEL11 | 1 << UMSEL10;
82            /* set MSPI, MSB first, SPI data mode 0 */
83    UCSR1B = 1 << RXEN1 | 1 << TXEN1;
84            /* enable receiver and transmitter */
85    UBRR1 = 0; /* reconfirm the bit rate */
86
87    spi_initialized = 1;
88}
89

Archive Download this file



interactive