As you can see, I used a MOC70T3 optical sensor in my circuit, which was connected as recommended by the datashet. At the end of the gearbox shaft, a disc with 30 divisions was used.
Frequency of the waveform is 40hz.
Below is a simplified code that I used to do just these reading tests:
#define motor 4
#define rotary_encoder 14
boolean signal_encoder = 0;
ICACHE_RAM_ATTR void waveForm() {
signal_encoder = !signal_encoder;
}
void setup() {
Serial.begin(115200);
pinMode(rotary_encoder, INPUT_PULLUP);
pinMode(motor, OUTPUT);
//the line below was uncommented in the firt test
// attachInterrupt(digitalPinToInterrupt(rotary_encoder), waveForm, CHANGE);
}
void loop() {
digitalWrite(motor, 1);
//the two lines below were commented while testing interrupt readings
if(digitalRead(rotary_encoder))signal_encoder=1;
else signal_encoder = 0;
Serial.println(signal_encoder);
delay(1);
}
interrupting the "normal" code-execution regardless which line of code it will be
executing the interrupt and return to the "normal" code-exection at exact that place the interruption occured.
This means interrupts work "in the backround" in parallel to your code.
If the encoder is connected to the interrupt-pin the change of the signal-level from LOW-to_HIGH or HIGH-to_LOW is enough to start executing the interrupt-code.
Does yur encoder just have a single output or does the encoder have two outputs (the typical A/B-channel quadrature rotary-encoder)
For A/B-channel quadrature rotary-encoder I recommend using the NewEnocder-library. This library works very reliable even with the most bouncy-mechancial rotary-encoders.
Your schematic does not show a rotary-encoder. What is the rotary-enocder used for?
Do you want to have feedback about the motor?
or do you want to use the rotary encoder for user-input?
I used a MOC70T3 optical sensor as encoder (a led in front of a phototransistor, encapsulated). The diagram is in the right part of the image I attached. In the middle of the MOC70T3 was a rotating a disc with 30 divisions. The second wave form I got with digitalRead shows the result as expected.
The question is: why I got regular reading as I showed in the second wave form, but i don't had the same result using attachInterrupt(), as showed in the first wave form, if I used the same pin and the same circuit?
The encoder is actualy a MOC70T3 series wired as showed in the right part of the image I attached. The pulses produced for the internal phototransistor is read by the pin 14.