First post! I certainly hope I posted this in the right section.
Project goal: This is a section of code I'm trying to get working as part of my project. The deliverables are to poll a set of inputs and then send a serial string through Bluetooth when a button is pressed. I'm using a Bluetooth terminal on my phone and it has made troubleshooting easier. The issue I am trying to avoid is flooding the serial port and only send a string when there is pin state change.
Hardware setup:
- Arduino Due
- HC 05 Bluetooth connected to serial lines
- Raspberry Pi (to receive string)
- I have 2 pushbuttons on the input with pull down resistors. I checked them with an Oscilloscope and the signals are clean. I also ran code to make sure I was getting the inputs fine.
My current project involves looking at only 2 inputs at the moment but I wrote code to be able to scale it up to multiple inputs on my board, which is why I opted to use arrays. Initially I was using functions to sum the array and compare it, but it didn't work because each loop would just add to the sum, so I abandoned it. I didn't figure out a way to reset the array. I switched it up to compare each array element with this current implementation:
#define pin1 53
#define pin2 51
#define Maxnum 2
int currArray[Maxnum];
int prevArray[Maxnum];
int pinx1 = pin1;
int pinx2 = pin2;
int pinArray[Maxnum]={pinx1,pinx2};
void setup() {
Serial.begin(9600);
pinMode(pin1,INPUT);
pinMode(pin2,INPUT);
}//end setup
void readarray(){
int i;
for (i=0;i<Maxnum;i++){
currArray[i] = digitalRead(pinArray[i]);
}
//if the current array elements are equal to past array
for(i=0;i<Maxnum;i++){
prevArray[i]=currArray[i];
}
if (comparearray(currArray,prevArray) == 1){
pinchange();
}
}//end read array
char comparearray(int currArray[],int prevArray[]){
int i;
for(i=0;i<Maxnum;i++){
if (currArray[i]!= prevArray[i]){//change back to not equal
Serial.println("In comparearray");//did not print here, when condition is set to equal, it goes in the routine
return 1;
}
}
}//end compare array
void pinchange(){//detect a change in pin states
if(pin1 == HIGH){
Serial.write("<Pin_1_on>");
}
else if (pin1 == LOW){
Serial.write("<Pin_1_off>");
}//end pin1
if(pin2 == HIGH){
Serial.write("<Pin_2_on>");
}
else if(pin2 == LOW){
Serial.write("<Pin_2_off>");
}//end pin2
}//pinchange
void loop() {
readarray();
}//end main program loop
Please let me know if I need to clarify anything.