//#include <Wire.h>
#include <LiquidCrystal_I2C.h>
//#include <PWM.h>
// Define the input pins for the voltage signals
const int Cloc = A1;
const int Anti = A2;
const int Speed = A0;
const int di = A3;
const int cdi = 12;
int s, p = 0, t, last = 0, state = 0;
// Define the output pins for the DM542T driver
const int stepPin = 9;
const int dirPin = 8;
const int enPin = 11;
// Define the maximum and minimum motor speeds
const int maxSpeed = 10;
const int minSpeed = 1;
// Define the LCD address
const int lcdAddr = 0x27;
// Set up the LCD display object
LiquidCrystal_I2C lcd(lcdAddr, 16, 2);
void setup() {
Serial.begin(115200);
// Set the step and direction pins as output pins
pinMode(Speed, INPUT);
pinMode(di, INPUT);
pinMode(Cloc, INPUT);
pinMode(Anti, INPUT);
pinMode(cdi, INPUT);
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(enPin, OUTPUT);
analogWrite(enPin, 255);
// Set up the I2C LCD display
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Motor Speed:");
lcd.print("0%");
lcd.setCursor(0, 1);
lcd.print("Motor Dir:");
digitalWrite(enPin, HIGH);
}
void loop() {
/*
int v=digitalRead(di);
if (v==1)
{
digitalWrite(enPin, LOW);
digitalWrite(dirPin, HIGH);
last = 1;
p = 0;
}
else if (digitalRead(cdi) == HIGH )
{
digitalWrite(enPin, LOW);
digitalWrite(dirPin, LOW);
last = 1;
p = 1;
}
else {
digitalWrite(enPin,LOW);
last = 0;
}*/
// Read the input voltage signals
int speed = analogRead(Speed);
// Map the input voltages to motor speed and direction
speed = map(speed, 0, 1024, minSpeed, maxSpeed);
if (state == 0)
{
digitalWrite(stepPin, HIGH);
state = 1;
}
else if (state == 1)
{
digitalWrite(stepPin, LOW);
state = 0;
}
delayMicroseconds(speed);
if (last == 0)
{
if (analogRead(Cloc) <500 ) {
p = 0;
digitalWrite(enPin, LOW);
digitalWrite(dirPin, HIGH);
delay(10000);
}
else if (digitalRead(Anti) == HIGH) {
p = 1;
digitalWrite(enPin, LOW);
analogWrite(dirPin, 0);
}
else {
digitalWrite(enPin, HIGH);
}
}
if ((speed != s) || (t != p)) {
//InitTimersSafe();
//SetPinFrequency(9,speed);
// Display the current speed and direction on the LCD display
lcd.clear();
int speedPercent = map(speed, minSpeed, maxSpeed, 0, 100);
speedPercent = 100 - speedPercent;
lcd.setCursor(0, 0);
lcd.print("Motor Speed:");
lcd.print(speedPercent);
lcd.print("% ");
lcd.setCursor(0, 1);
lcd.print("Motor Dir:");
if (p == 0) {
lcd.print("CW ");
}
else {
lcd.print("CCW");
}
s = speed;
t = p;
}
}