Advertisement
mikroavr

retry_read_tca

Jan 21st, 2024 (edited)
894
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Wire.h>
  2. #include "TCA9555.h"
  3. TCA9555 TCA1(0x20);
  4. TCA9555 TCA2(0x21);
  5. byte pin_tca[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
  6.  
  7. #define TCA9555_INPUT_PORT_REGISTER_0 0x00  //  read(0-7)
  8. #define TCA9555_INPUT_PORT_REGISTER_1 0x01  //  read(8-15)
  9. byte data_tca1_port0 = 0;
  10. byte data_tca1_port1 = 0;
  11. unsigned long cur_time, old_time;
  12. bool port0 = 0;
  13. bool port1 = 1;
  14.  
  15. byte addr_tca1 = 0x20;
  16. byte addr_tca2 = 0x21;
  17.  
  18. void setup() {
  19.   // put your setup code here, to run once:
  20.   Serial.begin(115200);
  21.   Wire.begin();
  22.   TCA1.begin();
  23.   TCA2.begin();
  24.   for (int i = 0; i < sizeof(pin_tca); i++) {
  25.     Serial.print(i);
  26.     Serial.print(",");
  27.     TCA1.pinMode(pin_tca[i], INPUT_PULLUP);
  28.     TCA2.pinMode(pin_tca[i], INPUT_PULLUP);
  29.   }
  30. }
  31.  
  32. void loop() {
  33.   // put your main code here, to run repeatedly:
  34.   cur_time = millis();
  35.   if (cur_time - old_time > 100) {
  36.     byte _retry = 0;
  37.     while (!baca_input1(addr_tca1, port0) && _retry < 10) {
  38.       _retry++;
  39.       Serial.print("retry: ");
  40.       Serial.println(_retry);
  41.       delay(20);
  42.     }
  43.     _retry = 0;
  44.     while (!baca_input1(addr_tca1, port1) && _retry < 10) {
  45.       _retry++;
  46.       Serial.print("retry: ");
  47.       Serial.println(_retry);
  48.       delay(20);
  49.     }
  50.  
  51.     Serial.print("tca1 port0: ");
  52.     Serial.println(data_tca1_port0,BIN);
  53.     Serial.print("tca1 port1: ");
  54.     Serial.println(data_tca1_port1,BIN);
  55.  
  56.     old_time = millis();
  57.   }
  58. }
  59.  
  60. bool baca_input1(byte addr, byte mask) {
  61.   bool flag_tca = 0;
  62.   Wire.beginTransmission(addr);
  63.   switch (mask) {
  64.     case 0:
  65.       Wire.write(TCA9555_INPUT_PORT_REGISTER_0);
  66.       break;
  67.     case 1:
  68.       Wire.write(TCA9555_INPUT_PORT_REGISTER_1);
  69.       break;
  70.   }
  71.  
  72.   int rv = 0;
  73.   rv = Wire.endTransmission();
  74.   if (rv != 0) {
  75.     flag_tca = 0;
  76.     Serial.println("gagal baca");
  77.   } else {
  78.     Wire.requestFrom(addr, (uint8_t)1);
  79.     switch (mask) {
  80.       case 0:
  81.         data_tca1_port0 = Wire.read();
  82.         break;
  83.       case 1:
  84.         data_tca1_port1 = Wire.read();
  85.         break;
  86.     }
  87.  
  88.     flag_tca = 1;
  89.   }
  90.   return flag_tca;
  91. }
  92.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement