JohnKofee

LIN

Feb 22nd, 2021
751
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Create the Lin ID parity */
  2. #define BIT(data,shift) ((addr & (1 << shift)) >> shift)
  3. uint8_t Lin_addrParity(uint8_t addr)
  4. {
  5.   uint8_t p0 = BIT(addr, 0) ^ BIT(addr, 1) ^ BIT(addr, 2) ^ BIT(addr, 4);
  6.   uint8_t p1 = ~(BIT(addr, 1) ^ BIT(addr, 3) ^ BIT(addr, 4) ^ BIT(addr, 5));
  7.   return (p0 | (p1 << 1)) << 6;
  8. }
  9.  
  10. /* Lin defines its checksum as an inverted 8 bit sum with carry */
  11. uint8_t Lin_dataChecksum(const uint8_t* message, char nBytes, uint16_t sum)
  12. {
  13.     while (nBytes-- > 0) sum += *(message++);
  14.  
  15.     // Add the carry
  16.     while(sum >> 8)  // In case adding the carry causes another carry
  17.       sum = (sum & 255) + (sum >> 8);
  18.  
  19.     return (~sum);
  20. }
  21.  
  22. /* Send a message across the Lin bus */
  23. void Lin_send_master(uint8_t addr, const uint8_t* message, uint8_t nBytes,uint8_t proto)
  24. {
  25.   uint8_t addrbyte = (addr & 0x3f) | addrParity(addr);
  26.   uint8_t cksum = dataChecksum(message, nBytes, addrbyte);
  27.   serialBreak();       // Generate the low signal that exceeds 1 char.
  28.   write(0x55);  // Sync byte
  29.   write(addrbyte);  // ID byte
  30.   write(message, nBytes);  // data bytes
  31.   write(cksum);  // checksum  
  32. }
  33.  
RAW Paste Data