Could I please get a few hints on how to improve my code below.
I am replicating a hardware keypad, which sends out the following for each button press:
11bit constant header & 11bit button data & checksum (checksum is constant header + button data)
e.g.
header 0x14B & button0 0x030 & checksum 0x7B
header 0x14B & button1 0x031 & checksum 0x7C
header 0x14B & button2 0x032 & checksum 0x7D
etc.. for a total 16 buttons.
I have written the code for outputting one button press, which is below.
Do I need a function for each button press? Or can I use some clever trick? Any general pointers are appreciated.
/*
Arrays
http://www.arduino.cc/en/Tutorial/Array
*/
int timer = 800; //pulse width of 800microseconds
int headerData[] = { 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1 }; // array for header data - (common to all buttons)
int button0[] = { 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, }; //array for button 0 data
int checksum0[] = { 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1 }; //array for button 0 checksum - (checksum = header & button data)
//NOTE - header is same each time, checksum is header + button data added together
int commsPin = 2; //output pin to COMMS connection on panel
int arrayCount = 11; // the length of each 11-bit word
void setup()
{
pinMode(commsPin, OUTPUT);
}
void loop ()
{
button0pressed();
delay(1000); //just for test purposes
}
void button0pressed()
{
//HEADER
for (int thisBit = 0; thisBit < arrayCount; thisBit++)
{
digitalWrite(commsPin, headerData[thisBit]);
delayMicroseconds(timer);
}
//BUTTON PRESS
for (int thisBit = 0; thisBit < arrayCount; thisBit++)
{
digitalWrite(commsPin, button0[thisBit]);
delayMicroseconds(timer);
}
//CHECKSUM
for (int thisBit = 0; thisBit < arrayCount; thisBit++)
{
digitalWrite(commsPin, checksum0[thisBit]);
delayMicroseconds(timer);
}
}
Example logic trace of the output from pin 2 - matches physical keypad:

