Hi,I have created a program to speed and directional control of DC motor, currently when I entered the directional command"forward" or "reverse" through serial terminal then the analog out become zero for speed control.
#define SV 10
#define FR 9
#define BRK 8
#define EN 7
int encoderpin = 2;
unsigned int rpm ;
volatile byte pulses;
unsigned long timeold;
unsigned int pulsesperturn=6;
int readNumber;
int pwmOutput;
String a;
void counter()
{
pulses++;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(SV, OUTPUT);
pinMode(FR,OUTPUT);
pinMode(BRK,OUTPUT);
pinMode(EN,OUTPUT);
pinMode(encoderpin, INPUT);
analogWrite(SV, 255);
digitalWrite(FR, HIGH);
digitalWrite(BRK, LOW);
digitalWrite(EN, LOW);
attachInterrupt(0,counter,FALLING);
pulses=0;
rpm=0;
timeold=0;
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available()>1){
a= Serial.readString();
if(a=="Forward"){
digitalWrite(FR, HIGH);
digitalWrite(BRK, HIGH);
delay(200);
}
if(a=="Reverse"){
digitalWrite(FR, LOW);
digitalWrite(BRK, HIGH);
delay(200);
}
if(a=="Stop"){
digitalWrite(BRK, HIGH);
delay(200);
}
else{
readNumber=a.toInt();
if (readNumber>=0 && readNumber<=100)
{
pwmOutput=map(readNumber,0,100,0,255);
analogWrite(SV,pwmOutput);
}
}
}
if (millis()-timeold>=1000){
detachInterrupt(0);
rpm = (60000/(millis()-timeold))*pulses;
rpm=rpm/4;
timeold= millis();
pulses=0;
Serial.println(rpm,DEC);
attachInterrupt(0,counter,FALLING);
}
}