PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

88 lines
2.3KB

  1. #include "EasyTransfer.h"
  2. //Captures address and size of struct
  3. void EasyTransfer::begin(uint8_t * ptr, uint8_t length, Stream *theStream){
  4. address = ptr;
  5. size = length;
  6. _stream = theStream;
  7. //dynamic creation of rx parsing buffer in RAM
  8. rx_buffer = (uint8_t*) malloc(size+1);
  9. }
  10. //Sends out struct in binary, with header, length info and checksum
  11. void EasyTransfer::sendData(){
  12. uint8_t CS = size;
  13. _stream->write(0x06);
  14. _stream->write(0x85);
  15. _stream->write(size);
  16. for(int i = 0; i<size; i++){
  17. CS^=*(address+i);
  18. _stream->write(*(address+i));
  19. }
  20. _stream->write(CS);
  21. }
  22. boolean EasyTransfer::receiveData(){
  23. //start off by looking for the header bytes. If they were already found in a previous call, skip it.
  24. if(rx_len == 0){
  25. //this size check may be redundant due to the size check below, but for now I'll leave it the way it is.
  26. if(_stream->available() >= 3){
  27. //this will block until a 0x06 is found or buffer size becomes less then 3.
  28. while(_stream->read() != 0x06) {
  29. //This will trash any preamble junk in the serial buffer
  30. //but we need to make sure there is enough in the buffer to process while we trash the rest
  31. //if the buffer becomes too empty, we will escape and try again on the next call
  32. if(_stream->available() < 3)
  33. return false;
  34. }
  35. if (_stream->read() == 0x85){
  36. rx_len = _stream->read();
  37. //make sure the binary structs on both Arduinos are the same size.
  38. if(rx_len != size){
  39. rx_len = 0;
  40. return false;
  41. }
  42. }
  43. }
  44. }
  45. //we get here if we already found the header bytes, the struct size matched what we know, and now we are byte aligned.
  46. if(rx_len != 0){
  47. while(_stream->available() && rx_array_inx <= rx_len){
  48. rx_buffer[rx_array_inx++] = _stream->read();
  49. }
  50. if(rx_len == (rx_array_inx-1)){
  51. //seem to have got whole message
  52. //last uint8_t is CS
  53. calc_CS = rx_len;
  54. for (int i = 0; i<rx_len; i++){
  55. calc_CS^=rx_buffer[i];
  56. }
  57. if(calc_CS == rx_buffer[rx_array_inx-1]){//CS good
  58. memcpy(address,rx_buffer,size);
  59. rx_len = 0;
  60. rx_array_inx = 0;
  61. return true;
  62. }
  63. else{
  64. //failed checksum, need to clear this out anyway
  65. rx_len = 0;
  66. rx_array_inx = 0;
  67. return false;
  68. }
  69. }
  70. }
  71. return false;
  72. }