SPEED CONTROL DC MOTOR WITH SPEED SENSOR

dc spped motor

The code can be downloaded at:

https://github.com/triantara/ARDUINO-TRIANTARA/blob/main/DC%20MOTOR%20SPEED.zip

int encoder_pin = 2; // pulse output from the module
int pulses;
unsigned long timeold;
int pinState = 0;
int lastpinState = 0;
int laju;
int turn;
int dir1PinA = 7;
int dir2PinA = 8;
int speedPinA = 9;
#include <avr/interrupt.h>
#include <avr/eeprom.h>
int addr = 1;
int readValue = 0;
int a;
int signalPWM = 0;

void setup()
{
Serial.begin(9600);
pinMode(encoder_pin, INPUT);
attachInterrupt(0, counter, FALLING);
pulses = 0;
timeold = 0;
pinMode(dir1PinA,OUTPUT);
pinMode(dir2PinA,OUTPUT);
pinMode(speedPinA,OUTPUT);
}
void loop()
{
if (Serial.available() > 0) {
a = Serial.parseInt();
while (!eeprom_is_ready());
cli();
if(eeprom_read_word((uint16_t*)addr) != a) {
eeprom_write_word((uint16_t*)addr, a);
}
sei();

}
signalPWM = constrain(signalPWM, 0, 255);
readValue = eeprom_read_word((uint16_t*)addr);
maju();
if (millis() – timeold >= 100) {
detachInterrupt(0);
laju=(pulses)*(6.28/2000)*1000*60; //number pulses in 100ms with 20 hole disk
turn=(pulses)/2;
if (laju <= readValue) {
signalPWM++;
}
else if (laju > readValue) {
signalPWM–;
}
Serial.print(pulses);
Serial.print(” pulses/100ms “);
Serial.print(” Speed: “);
Serial.print(laju);
Serial.print(” rpm “);
Serial.print(turn);
Serial.print(” turn/second “);
Serial.print(” PWM signal: “);
Serial.print(signalPWM);
Serial.print(” Set point: “);
Serial.println(readValue);
timeold = millis();
pulses = 0;
attachInterrupt(0, counter, FALLING);

}
}
void counter()
{
pinState = digitalRead(encoder_pin);
if (pinState != lastpinState) {
if (pinState == HIGH) {
pulses++;
}
lastpinState = pinState;
}
}
void maju(){
readValue = eeprom_read_word((uint16_t*)addr);
analogWrite(speedPinA, signalPWM);//Sets speed variable via PWM
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, HIGH);

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s