unit ufp_uartserial;
{
UART AVR.
Copyright (C) 2022 Dimitrios Chr. Ioannidis.
Nephelae - https://www.nephelae.eu
https://www.nephelae.eu/
Licensed under the MIT License (MIT).
See licence file in root directory.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
}
{$mode objfpc}
{$modeswitch result-}
{$modeswitch advancedrecords}
{$longstrings off}
{$writeableconst off}
{$inline on}
{$macro on}
{$if defined(fpc_mcu_atmega328p) }
{$DEFINE UART_UCSRA := UCSR0A }
{$DEFINE UART_UCSRB := UCSR0B }
{$DEFINE UART_UCSRC := UCSR0C }
{$DEFINE UART_UBRRL := UBRR0L }
{$DEFINE UART_UBRRH := UBRR0H }
{$DEFINE UART_UDR := UDR0 }
{$DEFINE UART_UDRE := UDRE0 }
{$DEFINE UART_TXEN := TXEN0 }
{$DEFINE UART_RXEN := RXEN0 }
{$DEFINE UART_RXC := RXC0 }
{$DEFINE UART_U2X := U2X0 }
{$elseif defined(fpc_mcu_atmega16a) or defined(fpc_mcu_attiny2313)}
{$DEFINE UART_UCSRA := UCSRA }
{$DEFINE UART_UCSRB := UCSRB }
{$DEFINE UART_UCSRC := UCSRC }
{$DEFINE UART_UBRRL := UBRRL }
{$DEFINE UART_UBRRH := UBRRH }
{$DEFINE UART_UDR := UDR }
{$DEFINE UART_UDRE := UDRE }
{$DEFINE UART_TXEN := TXEN }
{$DEFINE UART_RXEN := RXEN }
{$DEFINE UART_RXC := RXC }
{$DEFINE UART_U2X := U2X }
{$endif}
interface
type
{ TUART }
TUART = packed record
public
procedure Init(const ABaudRate: UInt32 = 57600);
function ReadChar: Char;
procedure WriteChar(const AChar: char);
procedure WriteStr(const s: ShortString = '');
procedure WriteStrLn(const s: ShortString = '');
end;
var
UART: TUART;
implementation
{ TUART }
procedure TUART.Init(const ABaudRate: UInt32);
var
Prescaler: UInt16;
begin
//Prescaler := ((F_CPU div 4) div ABaudRate - 1) div 2;
Prescaler := F_CPU div 8 div ABaudRate - 1;
UART_UBRRL := Prescaler;
UART_UCSRA := (1 shl UART_U2X);
UART_UCSRB := (1 shl UART_TXEN) or (1 shl UART_RXEN);
UART_UCSRC := %10000110;
end;
procedure TUART.WriteChar(const AChar: char); inline;
begin
while ((UART_UCSRA and (1 shl UART_UDRE)) = 0) do ;
UART_UDR := byte(AChar);
end;
function TUART.ReadChar: Char;
begin
while ((UART_UCSRA and (1 shl UART_RXC)) = 0) do ;
ReadChar := Char(UART_UDR);
end;
procedure TUART.WriteStr(const s: ShortString);
var
i: integer;
begin
if length(s) > 0 then
begin
for i := 1 to length(s) do
WriteChar(s[i]);
end;
end;
procedure TUART.WriteStrLn(const s: ShortString);
begin
WriteStr(s);
WriteStr(#13#10);
end;
end.