aboutsummaryrefslogtreecommitdiff
path: root/Source/Serial.c
blob: 087f63127fd13e0def5ba1369267056d9c9f56af (plain) (blame)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/* *************************************
 *  Includes
 * *************************************/

#include "Serial.h"

/* *************************************
 *  Defines
 * *************************************/

#define SERIAL_BAUDRATE 115200
#define SERIAL_TX_RX_TIMEOUT 20000
#define SERIAL_RX_FIFO_EMPTY 0
#define SERIAL_TX_NOT_READY 0
#define SERIAL_PRINTF_INTERNAL_BUFFER_SIZE 256

/* **************************************
 *  Structs and enums                   *
 * *************************************/

typedef enum
{
    SERIAL_STATE_INIT = 0,
    SERIAL_STATE_STANDBY,
    SERIAL_STATE_WRITING_INITIAL
}SERIAL_STATE;

/* *************************************
 *  Local Variables
 * *************************************/

static volatile SERIAL_STATE SerialState;
static volatile bool serial_busy;

/* *************************************
 *  Local Prototypes
 * *************************************/

void SerialInit(void)
{
    SIOStart(115200);
}

bool SerialRead(uint8_t* ptrArray, size_t nBytes)
{
    if (nBytes == 0)
    {
        return false;
    }

    do
    {
        //uint16_t timeout = SERIAL_TX_RX_TIMEOUT;

        while ( (SIOCheckInBuffer() == SERIAL_RX_FIFO_EMPTY)); // Wait for RX FIFO not empty

        *(ptrArray++) = SIOReadByte();
    } while (--nBytes);

    return true;
}

bool SerialWrite(void* ptrArray, size_t nBytes)
{
    serial_busy = true;

    if (nBytes == 0)
    {
        return false;
    }

    do
    {
        //uint16_t timeout = SERIAL_TX_RX_TIMEOUT;

        while ( (SIOCheckOutBuffer() == SERIAL_TX_NOT_READY)); // Wait for TX FIFO empty.

        SIOSendByte(*(uint8_t*)ptrArray++);

    } while (--nBytes);

    serial_busy = false;

    return true;
}

volatile bool SerialIsBusy(void)
{
    return serial_busy;
}

#ifdef SERIAL_INTERFACE
void Serial_printf(const char* str, ...)
{
    va_list ap;
    int result;
    static char internal_buffer[SERIAL_PRINTF_INTERNAL_BUFFER_SIZE];

    va_start(ap, str);

    result = vsnprintf( internal_buffer,
                        SERIAL_PRINTF_INTERNAL_BUFFER_SIZE,
                        str,
                        ap  );

    SerialWrite(internal_buffer, result);
}
#endif // SERIAL_INTERFACE