1 // Copyright 2019 The Pigweed Authors
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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
20 #include "pw_preprocessor/compiler.h"
21 #include "pw_sys_io/sys_io.h"
23 extern "C" void pw_sys_io_Init() { Serial.begin(115200); }
25 namespace pw::sys_io {
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.
31 Status ReadByte(std::byte* dest) {
33 if (TryReadByte(dest).ok()) {
39 Status TryReadByte(std::byte* dest) {
40 if (!Serial.available()) {
41 return Status::Unavailable();
43 *dest = static_cast<std::byte>(Serial.read());
47 // Send a byte over the default Arduino Serial port.
48 Status WriteByte(std::byte b) {
49 // Serial.write() will block until data can be written.
50 Serial.write((uint8_t)b);
54 // Writes a string using pw::sys_io, and add newline characters at the end.
55 StatusWithSize WriteLine(const std::string_view& s) {
56 size_t chars_written = 0;
57 StatusWithSize result = WriteBytes(std::as_bytes(std::span(s)));
61 chars_written += result.size();
63 // Write trailing newline.
64 result = WriteBytes(std::as_bytes(std::span("\r\n", 2)));
65 chars_written += result.size();
67 return StatusWithSize(result.status(), chars_written);
70 } // namespace pw::sys_io