Serial

The second API we’ll rediscover is Serial which replaces our old code thatinvolved direct register manipulation and busy waiting.

Here’s an example of this API.

  1. #![deny(unsafe_code)]
  2. #![no_main]
  3. #![no_std]
  4. #[macro_use]
  5. extern crate pg;
  6. use pg::{Async, Future, Serial};
  7. #[inline(never)]
  8. #[no_mangle]
  9. pub fn main() -> ! {
  10. let Serial { mut rx, mut tx } = Serial::new().unwrap();
  11. let mut bytes = rx.bytes();
  12. loop {
  13. if let Async::Ready(byte) = bytes.poll() {
  14. // immediately echo back the byte we just received
  15. tx.write(byte).wait();
  16. }
  17. }
  18. }

Serial contains two fields: Rx and Tx which provide an asynchronous APIover the receiver and transmitter parts of the serial interface.

One of Rx methods is bytes which returns a Bytes struct that represents aninfinite stream of bytes that are read from the receiver pin/line. The next bytecan be requested without blocking using the poll method.

Tx provides a write method that queues a write onto the TX line. The writeis not performed immediately because there may be pending write. wait can beused to force the write; this may involve waiting for a pending write to end.