/* * spreadspace avr utils * * * Copyright (C) 2014-2018 Christian Pointner * * This file is part of spreadspace avr utils. * * spreadspace avr utils is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * spreadspace avr utils is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with spreadspace avr utils. If not, see . */ #include #include #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; void serialio_init(const uint32_t baudrate, const uint8_t doublespeed) { Serial_Init(baudrate, doublespeed); Serial_CreateStream(&serial_stream); stdin = stdout = stderr = &serial_stream; } void serialio_task(void) { } int16_t serialio_bytes_received(void) { return (int16_t)Serial_IsCharReceived(); }