summaryrefslogtreecommitdiff
path: root/lib/serialio.c
diff options
context:
space:
mode:
Diffstat (limited to 'lib/serialio.c')
-rw-r--r--lib/serialio.c68
1 files changed, 68 insertions, 0 deletions
diff --git a/lib/serialio.c b/lib/serialio.c
index fde2935..1f00be8 100644
--- a/lib/serialio.c
+++ b/lib/serialio.c
@@ -20,10 +20,78 @@
* along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
*/
+#include <avr/io.h>
#include <stdio.h>
#include "serialio.h"
+
+#ifdef USES_LUFA
#include "LUFA/Drivers/Peripheral/Serial.h"
+#else
+#define SERIAL_UBBRVAL(Baud) ((((F_CPU / 16) + (Baud / 2)) / (Baud)) - 1)
+#define SERIAL_2X_UBBRVAL(Baud) ((((F_CPU / 8) + (Baud / 2)) / (Baud)) - 1)
+
+static inline void Serial_Init(const uint32_t BaudRate, const uint8_t DoubleSpeed)
+{
+ UBRR0 = (DoubleSpeed ? SERIAL_2X_UBBRVAL(BaudRate) : SERIAL_UBBRVAL(BaudRate));
+
+ UCSR0C = ((1 << UCSZ01) | (1 << UCSZ00));
+ UCSR0A = (DoubleSpeed ? (1 << U2X0) : 0);
+ UCSR0B = ((1 << TXEN0) | (1 << RXEN0));
+
+ DDRD |= (1 << 1);
+ PORTD |= (1 << 0);
+}
+
+static inline uint8_t Serial_IsSendReady(void)
+{
+ return ((UCSR0A & (1 << UDRE0)) ? 1 : 0);
+}
+
+static inline void Serial_SendByte(const char DataByte)
+{
+ while (!(Serial_IsSendReady()));
+ UDR0 = DataByte;
+}
+
+int Serial_putchar(char DataByte, FILE *Stream)
+{
+ (void)Stream;
+
+ Serial_SendByte(DataByte);
+ return 0;
+}
+
+static inline uint8_t Serial_IsCharReceived(void)
+{
+ return ((UCSR0A & (1 << RXC0)) ? 1 : 0);
+}
+
+static inline int16_t Serial_ReceiveByte(void)
+{
+ if (!(Serial_IsCharReceived()))
+ return -1;
+
+ return UDR0;
+}
+
+int Serial_getchar(FILE *Stream)
+{
+ (void)Stream;
+
+ if (!(Serial_IsCharReceived()))
+ return _FDEV_EOF;
+
+ return Serial_ReceiveByte();
+}
+
+void Serial_CreateStream(FILE* Stream)
+{
+ *Stream = (FILE)FDEV_SETUP_STREAM(Serial_putchar, Serial_getchar, _FDEV_SETUP_RW);
+}
+#endif
+
+
static FILE serial_stream;