ring_buffer.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #pragma once
  2. /*--------------------------------------------------------------------
  3. * Ring buffer to store scan codes from keyboard
  4. *------------------------------------------------------------------*/
  5. #define RBUF_SIZE 32
  6. #include <util/atomic.h>
  7. static uint8_t rbuf[RBUF_SIZE];
  8. static uint8_t rbuf_head = 0;
  9. static uint8_t rbuf_tail = 0;
  10. static inline void rbuf_enqueue(uint8_t data)
  11. {
  12. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  13. uint8_t next = (rbuf_head + 1) % RBUF_SIZE;
  14. if (next != rbuf_tail) {
  15. rbuf[rbuf_head] = data;
  16. rbuf_head = next;
  17. } else {
  18. print("rbuf: full\n");
  19. }
  20. }
  21. }
  22. static inline uint8_t rbuf_dequeue(void)
  23. {
  24. uint8_t val = 0;
  25. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  26. if (rbuf_head != rbuf_tail) {
  27. val = rbuf[rbuf_tail];
  28. rbuf_tail = (rbuf_tail + 1) % RBUF_SIZE;
  29. }
  30. }
  31. return val;
  32. }
  33. static inline bool rbuf_has_data(void)
  34. {
  35. bool has_data;
  36. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  37. has_data = (rbuf_head != rbuf_tail);
  38. }
  39. return has_data;
  40. }
  41. static inline void rbuf_clear(void)
  42. {
  43. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  44. rbuf_head = rbuf_tail = 0;
  45. }
  46. }