Last week I was asking ChatGPT to help me with a Arduino program.
After a lot of back and forth, mostly me correcting ChatGPT output.
ChatGPT suggested it best that I ask my question to someone who would actually
know the answer. And suggested this forum.
This is a related but different question.
/*
Author: Ralph Hulslander a non programmer rhulslander@gmail.com
Contributing Author: Danny van den Brande, Arduinosensors.nl using the KY-040 Rotary encoder.
Encoder 2
*/
#include <AccelStepper.h>
// Motor Connections (constant current, step/direction bipolar motor driver)
const int dirPin = 4;
const int stepPin = 5;
AccelStepper myStepper(AccelStepper::DRIVER, stepPin, dirPin);
int runSpeed1000 = 0;
int runSpeed100 = 0;
int runSpeed10 = 0;
int runSpeed = 0;
int CLK2 = 3; // Pin 3 to clk on encoder for Interrupt
int DT2 = 11; // Pin 11 to DT on encoder
int RotPosition2 = 0;
int rotation2;
int value2;
boolean LeftRight2;
void setup()
{
myStepper.setMaxSpeed(10000);
myStepper.setSpeed(50);
Serial.begin (9600);
pinMode (CLK2,INPUT);
pinMode (DT2,INPUT);
rotation2 = digitalRead(CLK2);
}
void loop()
{
value2 = digitalRead(CLK2);
if (value2 != rotation2)
{
// we use the DT pin to find out which way we turning.
if (digitalRead(DT2) != value2)
{ // Clockwise
RotPosition2 ++;
LeftRight2 = true;
runSpeed100 = runSpeed100 + 100;
}
else
{ //Counterclockwise
LeftRight2 = false;
RotPosition2--;
runSpeed100 = runSpeed100 - 100;
}
if (runSpeed100 <= 0)
{
runSpeed100 = 0;
}
if (runSpeed100 >= 900);
{
//runSpeed100 = runSpeed100 - 100;
runSpeed100 = 900; // This Stops the program from decrementing
}
if (LeftRight2)
{
Serial.println ("clockwise2");
}
else
{
Serial.println("counterclockwise2");
}
//this will print in the serial monitor.
Serial.print("Encoder RotPosition2: ");
Serial.println(RotPosition2);
Serial.println(runSpeed100);
}
rotation2 = value2;
runSpeed = runSpeed1000 + runSpeed100 + runSpeed10;
myStepper.runSpeed();
}
Encoder RotPosition2: 4
900 The runSpeed100 should decrement
counterclockwise2
Encoder RotPosition2: 3
900
counterclockwise2
Encoder RotPosition2: 2
900
counterclockwise2
Encoder RotPosition2: 1
900
counterclockwise2
Encoder RotPosition2: 0
900
counterclockwise2
Encoder RotPosition2: -1
900
counterclockwise2
Encoder RotPosition2: -2
900