Arduino Program:
const int ctrlPin1=7;
const int ctrlPin2=8;
const int enablePin=9;
const int directionSwitchPin=4;
const int onOffSwitchPin=5;
const int potPin=A0;
#define encoder0PinA 2
#define encoder0PinB 3
volatile unsigned long duration, CapTime, LastCapTime;
double Freq;
double rpm;
unsigned long now;
int onOffSwitchState=0;
int prevOnOffSwitchState=0;
int directionSwitchState=0;
int prevDirectionSwitchState=0;
int motorEnabled=0;
int motorSpeed=0;
int motorDirection=1;
void setup(){
Serial.begin(9600);
pinMode(encoder0PinA, INPUT);
pinMode(encoder0PinB, INPUT);
attachInterrupt(0, doEncoder, RISING);
pinMode(directionSwitchPin, INPUT);
pinMode(onOffSwitchPin, INPUT);
pinMode(ctrlPin1, OUTPUT);
pinMode(ctrlPin2, OUTPUT);
pinMode(enablePin, OUTPUT);
digitalWrite(enablePin, LOW);
}
void doEncoder(){
LastCapTime = CapTime;
CapTime = millis();
}
void loop(){
now = millis();
duration = CapTime – LastCapTime;
LastCapTime = CapTime;
if (duration==0){
Freq=0;
}else{
Freq = 1000/(double)duration;
}
rpm = Freq*60/2;
Serial.print(“time: “);
Serial.print(now);
Serial.print (” , speed = “);
Serial.println (rpm);
onOffSwitchState=digitalRead(onOffSwitchPin);
delay(1);
directionSwitchState=digitalRead(directionSwitchPin);
delay(1);
motorSpeed=analogRead(potPin)/4;
if(onOffSwitchState != prevOnOffSwitchState){
if(onOffSwitchState == HIGH){
motorEnabled = !motorEnabled;
}
}
if(directionSwitchState != prevDirectionSwitchState){
if(directionSwitchState == HIGH){
motorDirection = !motorDirection;
}
}
if (motorDirection == 1){
digitalWrite(ctrlPin1, HIGH);
digitalWrite(ctrlPin2, LOW);
}
else {
digitalWrite(ctrlPin1, LOW);
digitalWrite(ctrlPin2, HIGH);
}
if (motorEnabled == 1){
analogWrite(enablePin, motorSpeed);
}
else {
analogWrite(enablePin, 0);
}
prevDirectionSwitchState=directionSwitchState;
prevOnOffSwitchState=onOffSwitchState;
delay(250);
}
Labview Block Diagram (May need to improve) To drive with Labview:
Recent Comments