Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Qi packet analyzer
const int input_pin = 9;
void setup() {
Serial.begin(115200);
Serial.println("START");
pinMode(input_pin, INPUT);
}
int count = 0;
int last = 0;
unsigned long start;
void loop() {
int data[16], p, i;
if (count < 10) {
while (!digitalRead(input_pin));
}
start = micros();
last = 1;
int sig = detectSignal();
if (count < 10 && sig != 1 || sig == -1) {
count = 0;
last = 0;
return;
}
if (sig == 1) { // preamble
count++;
return;
}
// Serial.print("Preamble:");
// Serial.println(count);
for (p = 0; p < 16;) {
data [p]= detectByte();
if (data[p] < 0) break;
p++;
sig = detectSignal();
if (sig < 0) break; // start byte
if (sig == 1) { Serial.println("invalid start bit"); break; }
}
byte check = 0;
for (i = 0; i < p; i++) {
Serial.print(data[i], HEX);
Serial.print(" ");
check ^= data[i];
}
if (check) {
Serial.print("checksum error ");
Serial.print(check, HEX);
}
Serial.println("");
count = 0;
last = 0;
}
int printLen() {
for (;;) {
unsigned long start = micros();
while (digitalRead(input_pin) == last);
unsigned long len = micros() - start;
Serial.println(len);
last = !last;
if (len > 1500) break;
}
}
int detectSignal() {
unsigned long len, len2;
while (digitalRead(input_pin) == last) {
len = micros() - start;
if (len > 1000) return -1; // no signal
}
if (len < 4) {
if (count) {
Serial.print("invalid t1 : ");
Serial.println(len);
}
return -1;
}
last = !last;
if (len > 350) {
start = micros();
return 0;
}
while (digitalRead(input_pin) == last) {
len2 = micros() - start;
if (len2 > 1500) {
return -1;
}
}
if (len2 < 100) {
if (count) {
Serial.print("invalid t2 : ");
Serial.println(len2);
}
return -1;
}
last = !last;
start = micros();
return 1;
}
int detectByte() {
int data = 0;
for (int i = 0; i < 8; i++) {
int sig = detectSignal();
// Serial.print(sig);
if (sig == -1) return -1;
if (sig) data |= (1 << i);
}
int parity = detectSignal();
// Serial.print(parity);
if (parity == -1) return -1;
// Serial.print(" ");
int stop = detectSignal();
if (stop == 1) return data;
if (stop == 0) { Serial.println("invalid stop bit"); return data; }
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment