mcu_slave_interface.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /*
  2. References: https://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c
  3. */
  4. #include "src/battery_data/battery.h"
  5. #include "mcu_slave_interface.h"
  6. #include "ti/driverlib/dl_i2c.h"
  7. #include <stdio.h>
  8. #include <string.h>
  9. /*Function to Rx and Tx data from Target to Controller*/
  10. // The code has multiple i2c instances (multiple MCUs connected) from which we
  11. // need to select the right one, passing a pointer as an argument
  12. void mcu_i2c_handle(I2C_Regs *i2c) {
  13. printf("MCU interrupt triggered\n");
  14. uint8_t receivedCommand = DL_I2C_receiveTargetData(i2c);
  15. printf("[SLAVE] Received Command: 0x%02X\n", receivedCommand);
  16. uint8_t tx_buffer[8] = {0};
  17. //changed to volatile variable, so that the compiler cannot optimize the variable out and is forced to do as told by the code
  18. volatile uint8_t rx_buffer[8] = {0};
  19. /*Handling GET commands with bitmasking*/
  20. // GET command for ADC(Battery Measurement): Voltage, Current, Temperature
  21. if ((receivedCommand & 0xF0) == 0x60) {
  22. uint8_t slot = receivedCommand & 0x0F;
  23. if (slot > NUM_SLOTS) {
  24. DL_I2C_flushTargetTXFIFO(i2c);
  25. return;
  26. }
  27. // Struct for voltage, current and temperature
  28. BatteryMeasurementData battery_measure;
  29. // take the updated battery measurement from the battery struct and store it
  30. // in the battery_measure struct
  31. battery_measure.voltage = batteries[slot].voltage;
  32. battery_measure.current = batteries[slot].current;
  33. battery_measure.temperature = batteries[slot].temperature;
  34. // Copying the memory block from battery_measure struct to tx_buffer:
  35. memcpy(tx_buffer, &battery_measure, sizeof(BatteryMeasurementData));
  36. DL_I2C_fillTargetTXFIFO(i2c, tx_buffer, sizeof(BatteryMeasurementData));
  37. printf("Battery Measurement Sent to MCU. \n");
  38. DL_I2C_flushTargetTXFIFO(i2c);
  39. }
  40. }