expander.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * expander.c
  3. * k4be 2022
  4. * License: BSD
  5. *
  6. * PCA9539/TCA9539 GPIO expander driver
  7. */
  8. #include "main.h"
  9. #include "I2C.h"
  10. #include "expander.h"
  11. #include <avr/io.h>
  12. unsigned char exp_output[EXPANDER_COUNT*2];
  13. void expander_init(unsigned char addr, unsigned char p1in, unsigned char p2in){
  14. addr += EXPANDER_ADDR;
  15. expander_write_all();
  16. System.global_error |= I2C_SendCommand3byte(addr, CMD_PORT0_CONFIG, p1in, p2in);
  17. }
  18. unsigned int expander_read(unsigned char addr){
  19. unsigned char low, high;
  20. System.global_error |= I2C_ReceiveCommand(addr, CMD_PORT0_INPUT, &low);
  21. System.global_error |= I2C_ReceiveCommand(addr, CMD_PORT1_INPUT, &high);
  22. return (unsigned int)low | (((unsigned int) high)<<8);
  23. }
  24. void expander_write(unsigned char expaddr){
  25. unsigned char addr = EXPANDER_ADDR + expaddr;
  26. System.global_error |= I2C_SendCommand3byte(addr, CMD_PORT0_OUTPUT, exp_output[expaddr*2], exp_output[expaddr*2 + 1]);
  27. }
  28. void expander_write_all(void){
  29. unsigned char i;
  30. for(i=0; i<EXPANDER_COUNT; i++)
  31. expander_write(i);
  32. }
  33. void expander_set_bit(unsigned char port, unsigned char val, unsigned char on){
  34. if(on){
  35. exp_output[port] |= val;
  36. } else {
  37. exp_output[port] &= ~val;
  38. }
  39. /* if(SREG & _BV(SREG_I)){
  40. System.expander_pending = 1;
  41. } else {*/
  42. expander_write(port / 2);
  43. // }
  44. }