setComparator()
Description
Set the counter value to trigger interrupt. When the encoder’s counter value reach this value, it trigger an interrupt event and reset the counter.
This function can only be use in the Pulse/DIR, CW/CCW and A/B Pulse modes.
Syntax
Enc0.setComparator(val)
Enc0.setComparator(val, condition)
Enc1.setComparator(val)
Enc1.setComparator(val, condition)
Enc2.setComparator(val)
Enc2.setComparator(val, condition)
Enc3.setComparator(val)
Enc3.setComparator(val, condition)
Parameters
Enc0、Enc1、Enc2、Enc3
:Corresponding to ENC0, ENC1, ENC2 and ENC3 encoder interfaces.
val
:Set the counter value to trigger the comparator’s interrupt event (unsigned long).
condition
:true or false. Set to true to enable interrupt event (default is set to true).
Returns
None
Example
Set ENC0 to A/B Pulse mode, output the total number of turns from the rotary encoder and counter value. (assuming pin A, B and Z are connected).
#include <Encoder.h> volatile unsigned long num1 = 0L; volatile unsigned long num2 = 0L; void encoder_isr(int flag) { // ISR function if(flag == INTR_COMPARE) num1++; // When counter value reaches the specified value, increase variable by 1 else if(flag == INTR_INDEX) num2 ++; // When rotary encoder completes a full turn, increase variable by 1 } void setup() { Serial.begin(9600); Enc0.begin(MODE_AB_PHASE); Enc0.setIndexReset(); // set the index signal (when pin Z changes to HIGH) to trigger an interrupt event and call the associated ISR function Enc0.setComparator(20L); Set a condition when the counter value reach 20, trigger an interrupt to call the associated ISR function Enc0.attachInterrupt(encoder_isr); // Mount ISR function and enable interrupt } void loop() { Serial.print("Pulse number: "); Serial.print(Enc0.read()); // Read the pulse value Serial.print(" "); Serial.print("index: "); Serial.print(num1); // Output total number of turns from the rotary encoder Serial.print(" "); Serial.print("trigger: "); // Output total number of occurrence where the counter reached 20 and reset. Serial.println(num2); delay(100); }
See also
- attachInterrupt()
- read()
- setIndexReset()
The text of the 86Duino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.