Thank you for your reply.
The following changes were done to your code:
- Value Change instead of rising for the trigger. Since you want something done in both the rising and the falling edges.
- Use only one function for both triggers.
- If both are high start a timer.
- If one of the input signals and no longer high save the duration and signal to print
Try the code:
const int pin2 = 2; //define input pin to be 2
const int pin3 = 3; //define input pin to be 3
const int t = 30; //define count integral in seconds
unsigned long secondCounter = 0; //define variable
/*GERRY MOD
unsigned long counts = 0; //define variable for pin 2
void pulse () {
counts = counts + 1; //calculation adds 1 to counts on pulse for pin 2
}
void pulse2 () {
secondCounter = secondCounter + 1; //calculation adds 1 to counts on pulse for pin 3
}
*/
unsigned long countArray[t]; //define array size to be t
unsigned long cps = 0; //define counts per second
//GERRY MOD
unsigned long startTimer = 0;
bool printValues = false;
void inputValChanged() {
if (digitalRead(pin2) == HIGH && digitalRead(pin3) == HIGH) {
if (startTimer == 0)
startTimer = millis();
} else if (startTimer != 0) {
countArray[secondCounter % t] = millis() - startTimer ;
startTimer = 0;
secondCounter++;
printValues = true;
}
}
void setup() {
Serial.begin(9600); //start serial connection
pinMode(pin2, INPUT); //initialize input
pinMode(pin3, INPUT); //initialize input
/*GERRY MOD
if ((digitalRead(2) == RISING) && (digitalRead(3) == RISING)) {
attachInterrupt(digitalPinToInterrupt(2), pulse, RISING);
attachInterrupt(digitalPinToInterrupt(3), pulse2, RISING);
}
*/
attachInterrupt(digitalPinToInterrupt(2), inputValChanged, CHANGE);
attachInterrupt(digitalPinToInterrupt(3), inputValChanged, CHANGE);
}
void loop() {
/*GERRY MOD
if ( millis() > ((secondCounter + 1) * 1000) ) { //counts seconds from start
countArray[secondCounter % t] = counts; //puts last seconds counts into array
counts = 0; // resets counts
*/
if (printValues) {
printValues = false;
Serial.print("secondCounter: ");
Serial.println(secondCounter);
unsigned long arraySum = 0; //define variable
int arraySize = min(secondCounter, t); //only relevant at startup
for (int i = 0; i < arraySize; i++) {
arraySum += countArray[i]; // sum counts in array.
Serial.print("Count: ");
Serial.println(countArray[i]);
}
cps = arraySum / t;
Serial.print("Count per Second: ");
Serial.println(cps);
}
}