I have a 36 segment wheel and slotted schmitt opto switch on the shaft of 12vDC motor.
This is a new post about a specific issue with timings and interrupts with an encoder.
I have narrowed down a problem with trying to use PID to maintain speed under load at 500rpm (about 20% power)
The encoder is working.
The INT0 on pin 2 is working. Tested with short LED blink sketch.
When I use Serial monitor to look at the pcount values, they change according to velocity of shaft.
But they also do not follow the timing in the loop for what is expected during 200mS.
It depends on the value of a delay() inserted after the Serial.println(pcount);
delay(100), values are around 40.
delay(500), values are from 300 to 400.
I cannot see why this should be?
Hence, for now the PID part of sketch is commented out.
#include <PID_v1.h>
#define motor 3 //motor connected on pin 3
#define encoder 2 //encoder connected on pin 2
int pcount =0; //previous count
unsigned long count=0;
unsigned long timep, time, etime;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
//PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);
void setup()
{
Serial.begin(9600);
pinMode(encoder,INPUT);
digitalWrite(motor,HIGH);//motor control pin HIGH(mosfet off) before setting as OUTPUT
pinMode(motor,OUTPUT);
pinMode(13,OUTPUT); //LED on board
digitalWrite(13,LOW); //LED debugging
attachInterrupt(0,counter,RISING); //external interrupt INT0 on pin 2
timep=micros();
Setpoint = 60; // pulses in 200mS this will be used to control the speed.
// myPID.SetMode(MANUAL);
}
void counter()
{
count++;
}
void loop()
{
Input = pcount;
// myPID.Compute();
Serial.println(pcount);
// if (pcount < 60){
// digitalWrite(13,HIGH);
// delay(100);
// digitalWrite(13,LOW);
delay(100);
// }
Output = 25;
int val=255-Output; //inverted npn driver = 255 the motor mosfet is off and 0 is full on.
analogWrite(motor,val);
if (micros () - timep >= 200000ul)
{
timep += 200000ul ;
noInterrupts () ;
pcount = count ;
count = 0ul ;
interrupts () ;
}
}