Suggestions

Alternate sample code for FIT0441

userHead Richard.Sewell 2024-07-28 06:09:51 498 Views1 Replies

I've just been getting a FIT0441 running on a Nano, and found the sample on the Wiki was not as helpful as it could be. Here's my current code in case it's useful.

 

#define DIRECTION_PIN 10

#define PWM_PIN 11

#define ENCODER_PIN 2  // must be an interrupt-capable pin, 2 is a good choice on a Nano


 

long pulsesPerRev = 45*6;  // gearbox is 45:1 reduction, motor has 6 pulses/rev


 

unsigned long directionChangeTime = 0;

bool direction = HIGH;


 

int rpmTarget = 100;


 

int encoderPulses = 0;


 

long lastEncoderTime = 0;

long encoderInterval = 1;

long encoderRPM = 0;

long lastPrintMillis = 0;



 

void setup() {

  // put your setup code here, to run once:

  Serial.begin(115200);


 

  TCCR2B = TCCR2B & 0b11111000 | 1; //set PWM frequency to 32khz, good for Nano and Uno


 

  pinMode(DIRECTION_PIN, OUTPUT); //direction control PIN 10 with direction wire

  pinMode(PWM_PIN, OUTPUT);

 

  digitalWrite(DIRECTION_PIN, direction);


 

  attachInterrupt(digitalPinToInterrupt(ENCODER_PIN), encoderISR, RISING ) ;

}


 

void loop() {

 

  if (millis() - directionChangeTime > 5000)  {

    direction = !direction;

    digitalWrite(DIRECTION_PIN, direction);

    directionChangeTime = millis();

  }


 

  if (Serial.available())  {

    int a = Serial.parseInt();

    if( a != 0 )

    {

      rpmTarget = 255 - a;

      analogWrite(PWM_PIN, rpmTarget );  //input speed (must be int)

      delay(200);

    }


 

  }


 

  long now = millis();

  if( now-lastPrintMillis > 500 )

  {

    Serial.print("  r/min, target is ");

    Serial.println(rpmTarget);

    Serial.print("Encoder interval ");

    Serial.println(encoderInterval);

    Serial.print("encoderPulses ");

    Serial.println(encoderPulses);

    Serial.print("totalRevs ");

    Serial.println(encoderPulses/pulsesPerRev);

    Serial.print("encoderRPM ");

    Serial.println(encoderRPM);

    lastPrintMillis = now;

  }

  i = 0;

}



 

void encoderISR()

{

  if( direction )

    encoderPulses ++;

  else

    encoderPulses--;


 

  long now = micros();

  encoderInterval = now - lastEncoderTime;

  lastEncoderTime = now;


 

 


 

  encoderRPM = (60L * 1000000L) / (encoderInterval * pulsesPerRev);

}

2024-07-29 16:16:45

Thanks for sharing.

userHeadPic lia.ifat