blob: de6c3444520cdbb59d0a2a2e043fe589df6d672e [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
23extern "C" void pw_sys_io_Init() {
24 Serial.begin(115200);
25 // Wait for serial port to be available
26 while (!Serial) {
27 }
28}
29
30namespace pw::sys_io {
31
32// Wait for a byte to read on USART1. This blocks until a byte is read. This is
33// extremely inefficient as it requires the target to burn CPU cycles polling to
34// see if a byte is ready yet.
35
36Status ReadByte(std::byte* dest) {
37 while (true) {
Keir Mierle6909f182020-11-06 14:04:00 -080038 if (TryReadByte(dest).ok()) {
39 return Status::Ok();
Anthony DiGirolamoeea0d772020-08-06 12:00:36 -070040 }
41 }
Keir Mierle6909f182020-11-06 14:04:00 -080042}
43
44Status TryReadByte(std::byte* dest) {
45 if (!Serial.available()) {
46 return Status::Unavailable();
47 }
48 *dest = static_cast<std::byte>(Serial.read());
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070049 return Status::Ok();
Anthony DiGirolamoeea0d772020-08-06 12:00:36 -070050}
51
52// Send a byte over USART1. Since this blocks on every byte, it's rather
53// inefficient. At the default baud rate of 115200, one byte blocks the CPU for
54// ~87 micro seconds. This means it takes only 10 bytes to block the CPU for
55// 1ms!
56Status WriteByte(std::byte b) {
57 // Wait for TX buffer to be empty. When the buffer is empty, we can write
58 // a value to be dumped out of UART.
59 while (Serial.availableForWrite() < 1) {
60 }
61 Serial.write((uint8_t)b);
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070062 return Status::Ok();
Anthony DiGirolamoeea0d772020-08-06 12:00:36 -070063}
64
65// Writes a string using pw::sys_io, and add newline characters at the end.
66StatusWithSize WriteLine(const std::string_view& s) {
67 size_t chars_written = 0;
68 StatusWithSize result = WriteBytes(std::as_bytes(std::span(s)));
69 if (!result.ok()) {
70 return result;
71 }
72 chars_written += result.size();
73
74 // Write trailing newline.
75 result = WriteBytes(std::as_bytes(std::span("\r\n", 2)));
76 chars_written += result.size();
77
78 return StatusWithSize(result.status(), chars_written);
79}
80
81} // namespace pw::sys_io