blob: 9e86c73f519c40e6689ef802ffb3e4c87459169b [file] [log] [blame]
Anthony DiGirolamoeea0d772020-08-06 12:00:36 -07001// Copyright 2019 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15#include <Arduino.h>
16
17#include <cinttypes>
18#include <cstdint>
19
20#include "pw_preprocessor/compiler.h"
21#include "pw_sys_io/sys_io.h"
22
Anthony DiGirolamob5355ee2020-11-14 17:19:06 -080023extern "C" void pw_sys_io_Init() { Serial.begin(115200); }
Anthony DiGirolamoeea0d772020-08-06 12:00:36 -070024
25namespace pw::sys_io {
26
27// Wait for a byte to read on USART1. This blocks until a byte is read. This is
28// extremely inefficient as it requires the target to burn CPU cycles polling to
29// see if a byte is ready yet.
30
31Status ReadByte(std::byte* dest) {
32 while (true) {
Keir Mierle6909f182020-11-06 14:04:00 -080033 if (TryReadByte(dest).ok()) {
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -080034 return OkStatus();
Anthony DiGirolamoeea0d772020-08-06 12:00:36 -070035 }
36 }
Keir Mierle6909f182020-11-06 14:04:00 -080037}
38
39Status TryReadByte(std::byte* dest) {
40 if (!Serial.available()) {
41 return Status::Unavailable();
42 }
43 *dest = static_cast<std::byte>(Serial.read());
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -080044 return OkStatus();
Anthony DiGirolamoeea0d772020-08-06 12:00:36 -070045}
46
47// Send a byte over USART1. Since this blocks on every byte, it's rather
48// inefficient. At the default baud rate of 115200, one byte blocks the CPU for
49// ~87 micro seconds. This means it takes only 10 bytes to block the CPU for
50// 1ms!
51Status WriteByte(std::byte b) {
52 // Wait for TX buffer to be empty. When the buffer is empty, we can write
53 // a value to be dumped out of UART.
54 while (Serial.availableForWrite() < 1) {
55 }
56 Serial.write((uint8_t)b);
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -080057 return OkStatus();
Anthony DiGirolamoeea0d772020-08-06 12:00:36 -070058}
59
60// Writes a string using pw::sys_io, and add newline characters at the end.
61StatusWithSize WriteLine(const std::string_view& s) {
62 size_t chars_written = 0;
63 StatusWithSize result = WriteBytes(std::as_bytes(std::span(s)));
64 if (!result.ok()) {
65 return result;
66 }
67 chars_written += result.size();
68
69 // Write trailing newline.
70 result = WriteBytes(std::as_bytes(std::span("\r\n", 2)));
71 chars_written += result.size();
72
73 return StatusWithSize(result.status(), chars_written);
74}
75
76} // namespace pw::sys_io