rbuf.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //rbuf.c
  2. #include "rbuf.h"
  3. //#include <avr/interrupt.h>
  4. void rbuf_ini(uint8_t* ptr, uint8_t l)
  5. {
  6. ptr[0] = l;
  7. ptr[1] = 0;
  8. ptr[2] = 0;
  9. }
  10. //lock/unlock macros
  11. //#define _lock() uint8_t _sreg = SREG; cli();
  12. //#define _unlock() SREG = _sreg;
  13. #define _lock()
  14. #define _unlock()
  15. //put single byte to buffer
  16. int rbuf_put(uint8_t* ptr, uint8_t b)
  17. {
  18. //#ifdef _NO_ASM
  19. _lock(); //lock
  20. uint8_t buf_w = ptr[1]; //get write index
  21. uint8_t buf_r = ptr[2]; //get read index
  22. _unlock(); //unlock
  23. ptr[4 + buf_w] = b; //store byte to buffer
  24. buf_w++; //incerment write index
  25. uint8_t buf_l = ptr[0]; //get length
  26. if (buf_w >= buf_l) buf_w = 0; //rotate write index
  27. if (buf_w == buf_r) return -1; //return -1 to signal buffer full
  28. ptr[1] = buf_w; //store write index
  29. return 0; //return 0 to signal success
  30. //#else //_NO_ASM
  31. // TODO - optimized assembler version
  32. // asm("movw r26, r24");
  33. // asm("ld r18, X+");
  34. // asm("cli");
  35. // asm("ld r19, X+");
  36. // asm("ld r20, X");
  37. // asm("cp r19, r18");
  38. // asm("brne .-6");*/
  39. //#endif //_NO_ASM
  40. }
  41. //get single byte from buffer
  42. int rbuf_get(uint8_t* ptr)
  43. {
  44. //#ifdef _NO_ASM
  45. _lock(); //lock
  46. uint8_t buf_w = ptr[1]; //get write index
  47. uint8_t buf_r = ptr[2]; //get read index
  48. _unlock(); //unlock
  49. if (buf_r == buf_w) return -1; //return -1 to signal buffer empty
  50. int ret = ptr[4 + buf_r]; //get byte from buffer
  51. buf_r++; //increment read index
  52. uint8_t buf_l = ptr[0]; //get length
  53. if (buf_r >= buf_l) buf_r = 0; //rotate read index
  54. ptr[2] = buf_r; //store read index
  55. return ret; //return byte (0-255)
  56. // return 0; //return 0 to signal success
  57. //#else //_NO_ASM
  58. // TODO - optimized assembler version
  59. //#endif //_NO_ASM
  60. }