blob: 4709ad5aae0c031a27ee34611125f074f0bd480d [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
Anthony DiGirolamoacfc9d12021-02-05 21:57:35 -080047// Send a byte over the default Arduino Serial port.
Anthony DiGirolamoeea0d772020-08-06 12:00:36 -070048Status WriteByte(std::byte b) {
Anthony DiGirolamoacfc9d12021-02-05 21:57:35 -080049 // Serial.write() will block until data can be written.
Anthony DiGirolamoeea0d772020-08-06 12:00:36 -070050 Serial.write((uint8_t)b);
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -080051 return OkStatus();
Anthony DiGirolamoeea0d772020-08-06 12:00:36 -070052}
53
54// Writes a string using pw::sys_io, and add newline characters at the end.
55StatusWithSize WriteLine(const std::string_view& s) {
56 size_t chars_written = 0;
57 StatusWithSize result = WriteBytes(std::as_bytes(std::span(s)));
58 if (!result.ok()) {
59 return result;
60 }
61 chars_written += result.size();
62
63 // Write trailing newline.
64 result = WriteBytes(std::as_bytes(std::span("\r\n", 2)));
65 chars_written += result.size();
66
67 return StatusWithSize(result.status(), chars_written);
68}
69
70} // namespace pw::sys_io