//encoder
volatile byte rpmcount;
unsigned int rpm;
unsigned long timeold;
//motor and keyin data
int cw = 7;
int pwm = 6;
int ledPin1 = 5;
int ledPin2 = 4;
void setup()
{
Serial.begin(9600);
Serial.print("BEGIN");
pinMode(cw,OUTPUT);
pinMode(pwm,OUTPUT);
pinMode(ledPin1,OUTPUT);
pinMode(ledPin2,OUTPUT);
//key in data
digitalWrite(2, HIGH);
attachInterrupt(0, rpm_fun, RISING);
rpmcount = 0;
rpm = 0;
timeold = 0;
}
void loop()
{
int inLetter;
if(Serial.available())
{
inLetter = Serial.read();
if(inLetter == 'C')
{
char buffer[] = {' ',' ',' ',' '}; // Receive up to 4 bytes
while(!Serial.available());
Serial.readBytesUntil('\n', buffer, 4);
int incomingValue = atoi(buffer);
Serial.println("R");
digitalWrite(cw,HIGH);
digitalWrite(ledPin1,HIGH);
digitalWrite(ledPin2,LOW);
analogWrite(pwm,incomingValue);
//Serial.print(pwm);
Serial.println(incomingValue);
delay(500);
}
else if (inLetter == 'A')
{
char buffer[] = {' ',' ',' ',' '}; // Receive up to 4 bytes
while(!Serial.available());
Serial.readBytesUntil('\n', buffer, 4);
int incomingValue = atoi(buffer);
digitalWrite(cw,LOW);
digitalWrite(ledPin1,LOW);
digitalWrite(ledPin2,HIGH);
analogWrite(pwm,incomingValue);
//Serial.print(pwm);
Serial.println("T");
Serial.println(incomingValue);
delay(500);
}
else
{
char buffer[] = {' ',' ',' ',' '}; // Receive up to 4 bytes
while(!Serial.available());
Serial.readBytesUntil('\n', buffer, 4);
int incomingValue = atoi(buffer);
digitalWrite(cw,LOW);
digitalWrite(ledPin1,LOW);
digitalWrite(ledPin2,LOW);
analogWrite(pwm,0);
//Serial.print(pwm);
Serial.println("T");
Serial.println(incomingValue);
delay(500);
}
}
if(rpmcount >=20)
{//Update RPM every 20 counts, increase this for better RPM resolution,
//decrease for faster update
float rpm = float (14*60)/(millis() - timeold)*rpmcount;
timeold = millis();
rpmcount = 0;
Serial.println(rpm,4);
}
}
void rpm_fun()
{
rpmcount++;
//Each rotation, this interrupt function is run twice
}
this program is functionable and i had test it.
i had solve the problems...thanks to all who guide and help me...this is the code used in my motor project, hope it can be improved and re-used to others...