I'm trying to write some code to operate a relay on a current value and set value (a PID). I have the PID working correctly, but I want to use a rotary encoder to control the set value.
The problem I have is that the 'PID' process in the loop is quite slow (I think this is mainly caused by reading temperature from a DS18B20)
As the code is slow, the LCD screen has a delay when changing the rotary encoder position.
here is my code
- I've removed the code for the PID as its quite long, and replaced it with 'delay(3000);' to simulate the delay it causes
//LCD
#include <Wire.h> // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address// push button switch
int inPin = 4; // the number of the input pin
int state = HIGH; // the current state of the output pin
int reading; // the current reading from the input pin
int previous = LOW; // the previous reading from the input pin
long time = 0; // the last time the output pin was toggled
long debounce = 200; // the debounce time, increase if the output flickers// rotary switch
const int PinCLK = 2; // Used for generating interrupts using CLK signal
const int PinDT = 3; // Used for reading DT signal
volatile boolean encChanged;
volatile long encPosition = 0;
volatile boolean up;void isr() { // Interrupt service routine is executed when a HIGH to LOW transition is detected on CLK
volatile boolean CLK = digitalRead(PinCLK);
volatile boolean DT = digitalRead(PinDT);
up = ((!CLK && DT) || (CLK && !DT));
if (!up)
encPosition++;
else
encPosition--;if (encPosition < 0)
{
encPosition = 0;
}else if (encPosition > 100)
{
encPosition = 100;
}encChanged = true;
delay(10);
}void setup() {
// push button switch
pinMode(inPin, INPUT_PULLUP);
// rotary switch
pinMode(PinCLK, INPUT);
pinMode(PinDT, INPUT);
attachInterrupt(0, isr, FALLING); // interrupt 0 is always connected to pin 2 on Arduino UNO
Serial.begin(9600);
Serial.println("Start");
// LCD
lcd.begin(20,4);
lcd.setCursor(0,0); //Start at character 4 on line 0
lcd.print(" Sous Vide");}
void loop() {
//push button
reading = digitalRead(inPin);
if (reading == HIGH && previous == LOW && millis() - time > debounce) {
buttonPress();
}previous = reading;
//rotary
if (encChanged) { // do this only if rotation was detected
encChanged = false; // do NOT repeat IF loop until new rotation detected
Serial.print("Count = ");
Serial.println(encPosition);
}delay(3000); // to simulate PID process
lcd.setCursor(0,0);
lcd.print("Encoder: ");
lcd.print(encPosition);
lcd.setCursor(0,1);
lcd.print("Button State: ");
lcd.print(state);}
void buttonPress()
{
if (state == HIGH)
{
state = LOW;
Serial.println(state);
}
else{
state = HIGH;
Serial.println(state);
}time = millis();
}