# How to decode this

I have a device that is outputting the signal shown in the attached image.

The signal goes low for 3ms to start. Then a zero is indicated by high of 1ms and a low of 2ms, while a one is indicated by a high of 2ms and a low of 1ms. There are 8 bits in the signal. Then there is an approximately 9ms gap before it repeats as long as the signal is present.

Since I don’t know when the signal will come in, I started by triggering an interrupt on the falling edge. Obviously this will trigger for every falling edge in the signal. So, I expect it to trigger every 3ms except during the gap of course. but what I am interested in is what happens during that 3ms.

This kind of thing has always been my weakest point and would love to learn how to do this.

Hmmm.. I just did a bit of a writeup on decoding digital signals using the Input Capture function on Arduino the other day:

The sketch there could be adapted to decode this type of signal.

Thanks! I'll take a look.

polling version in pseudocode

``````byte = 0;
wait for low;
wait 1.5 ms;  // go to middle of start bit
for (int i=0; i< 7; i++)
{
wait  3ms; // middle of next bit;
byte = byte << 1 + digitalRead(pin);
}
``````

You can make it also interrupt based and compare the timestamp of the LOW with the timestamp of the last HIGH.
You need an ISR on CHANGE

pseudocode not tested

``````ISR()
{
if (pin == HIGH) lastHIGH = millis();
else
{
if (millis() - lastHIGH == 3)
{
byte = 0; // start a new byte
count = 0;
}
else if (millis() - lastHIGH == 2) byte << 1 + 1;
else byte << 1;
count++;
if (count == 8) ==> action on the byte.
}
}
``````