1 // 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 pw_sys_io_Init()23extern "C" void pw_sys_io_Init() { Serial.begin(115200); } 24 25 namespace 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 ReadByte(std::byte * dest)31Status ReadByte(std::byte* dest) { 32 while (true) { 33 if (TryReadByte(dest).ok()) { 34 return OkStatus(); 35 } 36 } 37 } 38 TryReadByte(std::byte * dest)39Status TryReadByte(std::byte* dest) { 40 if (!Serial.available()) { 41 return Status::Unavailable(); 42 } 43 *dest = static_cast<std::byte>(Serial.read()); 44 return OkStatus(); 45 } 46 47 // Send a byte over the default Arduino Serial port. WriteByte(std::byte b)48Status WriteByte(std::byte b) { 49 // Serial.write() will block until data can be written. 50 Serial.write((uint8_t)b); 51 return OkStatus(); 52 } 53 54 // Writes a string using pw::sys_io, and add newline characters at the end. WriteLine(const std::string_view & s)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 71