TTP229 touch pads: I figured out how the hardware works, need help for software

I’ve recently got one of those TTP229 capacitive touchpads off eBay (link) and spent a few hours successfully researching on how to get data out of them.
Here is the datasheet to follow along: datasheet

Here is what I found out: TP1 and TP2 hove to be pulled low to enable all 16 pads and the serial comms, 1 megaohms works for that. The pins are broken out on the PCB.
The communication is NOT I2C even though one might think that, but a simple (active high) serial protocol. You can get the key numbers by pulsing the clock pin 16 times, counting those pulses and look on which rising edge the SDO pin goes from low to high. The number of pulses on SCL corresponds to the touchkey you pressed. If you touch key 4, SDO will go high on the fourth rising edge, if you touch key 5 it’s on the fifth rising edge and so on.

And that is where I need help. I figured out how to get it to spit out data, now I just need to write some code to reliably fetch the data.

Here’s the code I’ve got so far, it’s just a proof of concept and not too reliable, needs some error correction (but it works, that’s something at least :slight_smile: ) :

int clockPin = 2; //SCL pin goes here
int sdoPin = 3;  //SDO pin goes there


void setup()
{
  Serial.begin(9600);
  pinMode(clockPin,OUTPUT);
  pinMode(sdoPin,INPUT);
}

void loop()
{
  int val = fetchData();
  if(val != 0){              //if it's not 0, print to serial
    Serial.println(val);
    delay(250);
  }
}

int fetchData(){
  boolean sdoValue;                  //the data line value
  for(int i = 0; i < 17; i++){       //send pulse
    digitalWrite(clockPin,0);
    delayMicroseconds(10);
    sdoValue = digitalRead(sdoPin);    // check data line
    if(sdoValue == 1){                      //rising edge detected!
      return(i);                                  //return array position
    }
    digitalWrite(clockPin,1);
    delayMicroseconds(10);
  }
}

If someone could push me in the right direction on how to implement a basic check, like adding the received data 10 times and only return a value if data*10/data == 10, that would be nice. I have tried this, but it didn’t seem to affect anything:

int correctData(){

  const int numReadings = 10;
  int inputValue = 0;
  int readings[numReadings];
  int index = 0;
  int total = 0;
  int average = 0;

 for(int i = 0; i< numReadings; i++){
   inputValue = fetchData();
  readings[i] = inputValue;
 }
  
 for(int i = 0; i< numReadings; i++){
  total= total + readings[i];
 }
 inputValue = fetchData();
 if(total/inputValue == numReadings) return(total/numReadings);
}

See this post: http://forum.arduino.cc/index.php?topic=301382.msg2252580#msg2252580