ser2neo: a serial port to NeoPixel ring bridge.

serial.h 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Half-duplex interrupt based serial port.
  2. //
  3. // Copyright 2015 Google Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. #pragma once
  18. #include <stdint.h>
  19. /// Half-duplex interrupt based serial port.
  20. ///
  21. /// Loosely based on AVR304.
  22. ///
  23. class Serial {
  24. public:
  25. void init();
  26. void putch(uint8_t ch);
  27. void putstr(const char* str);
  28. uint8_t getch();
  29. private:
  30. enum State : uint8_t {
  31. Idle,
  32. Receive,
  33. Transmit,
  34. };
  35. // Note that these are all specific to an ATTINY85 USB board.
  36. static const int RxPin = 0;
  37. static const int TxPin = 2;
  38. static const auto Prescale = 2;
  39. static const auto Baud = 57600;
  40. static const auto BitTime = F_CPU / Prescale / Baud - 1;
  41. // Total number of clocks taken to service the pin change
  42. // interrupt and start the receive. Use this to reduce the first
  43. // bit-and-a-half time so sampling occurs half way through the
  44. // first bit.
  45. static const uint8_t PCIntDelay = 140;
  46. void pcint0();
  47. void timer1ovf();
  48. volatile State state_;
  49. uint8_t rxing_;
  50. // Remaining number of bits to send or receive.
  51. uint8_t bits_;
  52. volatile uint8_t rxed_;
  53. volatile bool rx_full_;
  54. volatile uint16_t txing_;
  55. static Serial* instance_;
  56. public:
  57. // Interrupt handler entry points.
  58. static void pcint0_bounce();
  59. static void timer1ovf_bounce();
  60. };