Struggling for the last 6 hours, add to current Int

Hi all,
Been working on some code that would take an Int or string(not sure which one it is)
and add it to another int or string.

for example:
int Count = 0
Count = Total accumulated // Max 200
Count = Count + 20 //random number between 0-200

when count = 200
reset count to 0
and run some one off code.

I'v been getting some advice from a different post but im guessing there asleep now, I was asked to try and work this out for my self, Its been 6 hours now and im tired, and I would really like to get this done in the next hour or at least workout why my code dont work. Hopefully you can make sense of it.
I'v commented the new code like this "// NEW CODE" so you can find it easily.

Best Regards

Dave

#include <MobaTools.h>        //  Stepper-Lib
#include <L298N.h>            //  Dc Motor Driver-Lib
#include <LiquidCrystal.h>    //  LCD Display-Lib

//const int rs = 5, en = 6, d4 = A1, d5 = A2, d6 = A3, d7 = A4;
//LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

// defines pin numbers for DC Motors
#define ENA 11 // Take-Up Reel // PWM
#define IN1 8
#define IN2 12
#define ENB 3 // ReWind Reel  // PWM
#define IN3 4
#define IN4 7
#define DC_SPEED 255 //Dc Motor Default Speed. Min 40 to get the reel spinning.

#define MOTOR_STEPS 200 // 1/4 Step but i think library only support full or half
#define MICROSTEPS 4
#define DIR 9
#define STEP 13
#define SLEEP 2

// Attaches defines to stepper
MoToStepper stepper(MOTOR_STEPS, STEPDIR);
// Create one motor instance
L298N RightMotor (ENA, IN1, IN2);  //  Take up Reel
//L298N LeftMotor (ENB, IN3, IN4);   //  Rewind Reel
////////////////////////////////////////////////////////////////////////////////////
int  rotationSpeed1;
char termChar = '\n';
bool rotResult = false;
//long int g = 0;
//long int sum;
/////////////////////////////////////////////////////////////////////
void setup() {


  
  // Used to display information
  Serial.begin(9600);

  // Wait for Serial Monitor to be opened
  while (!Serial)
  {
    //do nothing
  }

  //Serial.write(0x0C);
  //  serialCLS();
  //////////////////////////////////////////////////////////////////////////////////////
  pinMode(SLEEP, OUTPUT);
  digitalWrite(SLEEP, HIGH);

 

  // set up the LCD's number of columns and rows:
  //lcd.begin(16, 2);

  delay(5000); // Gives me time to clear the serial monitor! //

  //lcd.setCursor(0, 0);

  Serial.println("+-+ +-+ +-+ +-+   +-+ +-+ +-+ +-+ +-+ +-+ +-+");
  Serial.println("|C| |i| |n| |e|   |S| |c| |a| |n| |n| |e| |r|");
  Serial.println("+-+ +-+ +-+ +-+   +-+ +-+ +-+ +-+ +-+ +-+ +-+");
  Serial.println("");
  Serial.println("");

  Serial.println("*********************");
  Serial.println("** Loading Configs **");
  //lcd.print("Loading Configs");
  //lcd.setCursor(0, 1);
  Serial.println("** Stepper Driver **");
  //lcd.print("Stepper Driver");
  // Stepper Motor(s)
  pinMode(STEP, OUTPUT);
  pinMode(DIR, OUTPUT);
  //delay(3500);
  //lcd.clear();

  // DC Motor(s)
  //lcd.setCursor(0, 0);
  //lcd.print("Loading Configs");
  //lcd.setCursor(0, 1);
  Serial.println("** DC Motors **");
  //lcd.print("DC Motors");
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);

  // Turn off motors - Initial state
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  //delay(3500);
  //lcd.clear();

  //lcd.setCursor(0, 0);
  //lcd.print("Loading Complete!");
  //delay(3500);
  //lcd.clear();

  //lcd.setCursor(0, 0);
  Serial.println("** Ready **");
  Serial.println("*********************");
  //lcd.print("Ready");
  //delay(500);



  stepper.attach(STEP, DIR); //STEP=Pin, DIR=Pin
}

void loop()
{
  while (!Serial.available());
  String incommingString = Serial.readStringUntil('\n');
  int len;
  len = incommingString.length();
  //lcd.clear();
  //lcd.setCursor(0, 0);

  Serial.print("\nincommingString = "); // for IDE to test
  Serial.println(incommingString);   // for IDE to test
  Serial.println();
  //lcd.print("Incomming String "); // for IDE to test
  //lcd.setCursor(2, 1);
  //lcd.print(incommingString);   // for IDE to test
  
  String incommingStr = incommingString.substring(len - 12, len); // truncate to the correct length

  if  (incommingStr.length() != 12)
  {
    rotResult = false;    // rotation was not successfull
  }
  else
  {

    Serial.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    String mode = incommingStr.substring(0, 1); // 1 byte
    Serial.print("mode = ");
    Serial.print(mode);
    Serial.println(" (F)ull Step, (H)alf Step (M)icro Step 1/4");
    delay(10);
    String dir = incommingStr.substring(1, 2);  // 1 byte
    Serial.print("direction = ");
    Serial.print(dir);
    Serial.println(" (F)orwards, (B)ackwards");
    String noOfSteps = incommingStr.substring(2, 6); //4 bytes
    Serial.print("Number Of Steps = ");
    Serial.println(noOfSteps);
    String rotationSpeed = incommingStr.substring(6, 10); //4 bytes
    Serial.print("rotationSpeed = ");
    Serial.println(rotationSpeed);
    String sdelay = incommingStr.substring(10, 12); //2 bytes (Unused)
    Serial.print("sdelay(not used) = ");
    Serial.println(sdelay);
    int    rotationSpeed1 = rotationSpeed.toInt();
    int    noOfSteps1 = noOfSteps.toInt();
    String sum2, g; // NEW CODE
    
    int    sdelay1 = sdelay.toInt();
    Serial.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    
    
    
    /////////////////////////////////////////////////////////////////////////////
    
    stepper.setSpeed(rotationSpeed1); //RPM

    rotResult = true;  // initialize rotation result to erronous
    if (dir == "F")
    {
      stepper.doSteps(-noOfSteps1 * MICROSTEPS);  // Moves Stepper Forwards
      Serial.print("\nsum = "); // NEW CODE
       sum2 = g + noOfSteps;  // NEW CODE
      Serial.print("\nsum = "); // NEW CODE
  //Serial.println(countedSteps);
  Serial.println();
      /*
      currentStep = stepper.readSteps();
      Serial.println("Just After The Move ");
      Serial.print("Steps From ReadSteps = ");
      Serial.println(stepper.readSteps());
      Serial.print("Step From Variable = ");
      Serial.println(currentStep);
      Serial.print("Step From Stepper Pos = ");
      Serial.println(stepper.currentPosition());
      */
     // if (S_Switch_State == HIGH)
      {
        delay(500);          //////////////////////////////////
        analogWrite(ENA, 0); //50  //  Take Up Reel (Forward)
        digitalWrite(IN1, LOW);     //
        digitalWrite(IN2, HIGH);    //  Winds excess film onto
        //delay(noOfSteps1);          //  the reel.
        delay(18);
        analogWrite(ENA, 0);        //////////////////////////////////
      }
    }
    else
    {
      stepper.doSteps(noOfSteps1 * MICROSTEPS);  // Moves Stepper Backwards
    }

    if (mode == "F")
    {

      //stepper.doSteps(noOfSteps1);  // Moves Stepper Backwards
      for (int i = 0; i < noOfSteps1; i++)
      {
        //tmc26XStepper.move();
        delay(6);
      }
    }
    if (mode == "H")
    {
      //stepper.doSteps(noOfSteps1 * MICROSTEPS);  // Moves Stepper Backwards
      for (int i = 0; i < noOfSteps1; i++)
      {
        //tmc26XStepper.step(noOfSteps1);
        //tmc26XStepper.move();
        delay(10);
      }
    }
    if (mode == "M")
    {
      //stepper.doSteps(noOfSteps1 * MICROSTEPS + 200);  // Moves Stepper Backwards
      for (int i = 0; i < noOfSteps1; i++)
      {
        //tmc26XStepper.step(noOfSteps1);
        //tmc26XStepper.move();
      }
    }
    rotResult = true;    // rotation was successfull
  }

  if (rotResult == true)
  {
    Serial.write("1111111111"); Serial.print(" Error Code "); Serial.println();  // rotation successfull
          Serial.print("\nsum = "); // NEW CODE

/*
    Serial.println("End The Of Loop ");
      Serial.print("Steps From ReadSteps = ");
      Serial.println(stepper.readSteps());
      Serial.print("Step From Variable = ");
      Serial.println(currentStep);
      Serial.print("Step From Stepper Pos = ");
      Serial.println(stepper.currentPosition());
      */
  }
  else
  {
    Serial.write("0000000000"); Serial.print(" Error Code "); Serial.println();// rotation failed
          Serial.print("\nsum = "); // NEW CODE

    
  }
}  
{
  checkCount();  // call this whenever you want to see if count is ready

}

void checkCount ()
{
  if (count >= 200)
  {
    count = 0;
    oneOffstuff();
  }
}

void oneOffstuff ()
{
  // whatever to do
}

thanx runaway, what i cant work out is how to do this part
Count = Count + noOfSteps1
i cant seem to find where to put Count = Count + noOfSteps1

Best Regards

Dave

1 Like

I guess I wish I understood what that means.

1 Like

Same. I have no clue what im doing lol not to worry. Im gonna have to do a bit more research. Thank you for replying

Regards

Dave

Explain what the program is supposed to do.

You can start by not trying to write the entire program at once. I'd start a new file without the steppers or fancy strings. In that file I'd just read the input and manipulate the variables.
Post that and an explanation and help will likely be much more beneficial.

I thank you for replying, But im taking a break for a week. iv spent way to much time on this already and help is slow coming. Im gonna do a little reading. perhaps a few tuts and take some notes. perhaps ill come across what i need there.

Best Regards

Dave

I think we can help but as @er_name_not_found said we need an explanation of what the program is supposed to do. I can only assume bits and pieces from your code.

Im sure you guys can help. But im so limited on time atm. Work, kids, commitments and helping my brother move home. I dont have time to keep explaining what im doing over and over again. Damn if i could spare the cash id get someone to write this code for me. There would probably have it done in a day or two. Till I get some free time, im gonna have to pit this project on hold for a bit. Any ways, iv just learned that variable dont store there info in if statments unless you use static int. Who knew? Lol.
Anyway thanks for offering to help.

Best Regards

Dave

That's just nonsense.

1 Like

Hi @creativesamurai1982 In the other thread I wrote

make a start on your own. Shwo some own effort. Whenever a question arises ask the question.
trying it for 6 hours on your own was a real great effort

@moderator: is there some kind of high stamina batch you can honor to @creativesamurai1982 ?

If I remember right you have the stepper-motor for pull next single-picture of the film under film-scanner.

And the DC-motor is for winding up the film on a reel. The DC-motor has to stop if springloaded lever reaches a max-position that presses a microswitch. If micro-switch has been pressed stop DC-motor for some time.

Where "some time" shall be a certain amount of steps the stepper-motor has done after micro-switch has been pressed.

So this means: store actual position of the stepper-motor at the moment the micro-switch is pressed. Let's call the variable for this switchOFFmotorStepNr
and switch off DC-motor

then do a repeated compare between actual steps-number and switchOFFmotorStepNr
if the difference reaches 200 switch on DC-motor again.

I cannot find Count variable in your sketch of post #1 though noOfSteps1 variable is there.

Why and where do you want to insert the above code?

Hi all. Im going to explain everything so there's a reference of what im doing and what iv done so far. I'm going to start at the beginning.
I want to save/restore/digitize old 8mm cine film using a scanner to scan each frame individually at my scanners highest dpi. I found a software combo that can do that. alas, the software is not combatable with my hardware. So... I'm trying to edit the Arduino code to work with my hardware.

The software is in two parts, The windows software(which sends commands based on options selected, ie-number of sprockets on the capstan, how may step per stepper revolution) im guess there's some kind of math going on to determine how many steps to move the stepper in order to keep it all aligned. And there's the Arduino part. which receives the commands and moves the film transport system according to parameters sent.

The string that the Arduino receives is as follows.
TDssssvvvvii
T = F-full steps, H-half step, M-microsteps 1/4
D = F-forward, B-backward
ssss = number of steps to be performed (0-1999)
vvvv = rotation of stepper in rpm.
ii = // NOT USED YET. FUTURE PROOFING

so... MF0040050000 and think it sends a \n

This is my current code


//      FF0200050000


// Expected a string from CineFrameCatcher with the following layout TDssssssvvvviii
// T = type: F = fullsteps, H = halfsteps, M = microsteps (16 or 256 per fullstep)
// D = direction: F = forward,  B = backward
// ssssss = number of full, half or micro steps to be perfomed (according to type)
// vvvv = velocity of rotation in rpm (rotations per minute)
// iii = idle time in milliseconds - can be multiplied to get longer idle times
//
#include <MobaTools.h>        //  Stepper-Lib
#include <L298N.h>            //  Dc Motor Driver-Lib
#include <LiquidCrystal.h>    //  LCD Display-Lib
#include <Bounce2.h>          // De-Bounce-Lib

//const int rs = 5, en = 6, d4 = A1, d5 = A2, d6 = A3, d7 = A4;
//LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

// defines pin numbers for DC Motors
#define ENA 11 // Take-Up Reel // PWM
#define IN1 8
#define IN2 12
#define ENB 3 // ReWind Reel  // PWM
#define IN3 4
#define IN4 7
#define DC_SPEED 255 //Dc Motor Default Speed. Min 40 to get the reel spinning.

// defines pin numbers for Stepper Motor(s)
#define MOTOR_STEPS 200 // 1/4 Step but i think library only support full or half
#define MICROSTEPS 4
#define DIR 9
#define STEP 13
#define SLEEP 2

// defines pin number for switches.
#define STOP_SW 5

// Attaches defines to stepper
MoToStepper stepper(MOTOR_STEPS, STEPDIR);
// Create one motor instance
L298N RightMotor (ENA, IN1, IN2);  //  Take up Reel
//L298N LeftMotor (ENB, IN3, IN4);   //  Rewind Reel

// INSTANTIATE A Bounce OBJECT
Bounce bounce = Bounce();

////////////////////////////////////////////////////////////////////////////////////
int  rotationSpeed1;
char termChar = '\n';
bool rotResult = false;
int motorStatus = HIGH;

/////////////////////////////////////////////////////////////////////
void setup() {

  // SELECT ONE OF THE FOLLOWING :
  // 1) IF YOUR INPUT HAS AN INTERNAL PULL-UP
  bounce.attach( STOP_SW ,  INPUT_PULLUP ); // USE INTERNAL PULL-UP
  // 2) IF YOUR INPUT USES AN EXTERNAL PULL-UP
  //bounce.attach( BOUNCE_PIN, INPUT ); // USE EXTERNAL PULL-UP

// DEBOUNCE INTERVAL IN MILLISECONDS
  bounce.interval(5); // interval in ms

  //pinMode(ENA, OUTPUT);
  digitalWrite(ENA, motorStatus);
  
  // Used to display information
  Serial.begin(9600);

  // Wait for Serial Monitor to be opened
  while (!Serial)
  {
    //do nothing
  }

  //Serial.write(0x0C);
  //  serialCLS();
  //////////////////////////////////////////////////////////////////////////////////////
  pinMode(SLEEP, OUTPUT);
  digitalWrite(SLEEP, HIGH);

  // set up the LCD's number of columns and rows:
  //lcd.begin(16, 2);

  delay(5000); // Gives me time to clear the serial monitor! //

  //lcd.setCursor(0, 0);

  Serial.println("+-+ +-+ +-+ +-+   +-+ +-+ +-+ +-+ +-+ +-+ +-+");
  Serial.println("|C| |i| |n| |e|   |S| |c| |a| |n| |n| |e| |r|");
  Serial.println("+-+ +-+ +-+ +-+   +-+ +-+ +-+ +-+ +-+ +-+ +-+");
  Serial.println("");
  Serial.println("");

  Serial.println("*********************");
  Serial.println("** Loading Configs **");
  //lcd.print("Loading Configs");
  //lcd.setCursor(0, 1);
  Serial.println("** Stepper Driver **");
  //lcd.print("Stepper Driver");
  // Stepper Motor(s)
  pinMode(STEP, OUTPUT);
  pinMode(DIR, OUTPUT);
  //delay(3500);
  //lcd.clear();

  // DC Motor(s)
  //lcd.setCursor(0, 0);
  //lcd.print("Loading Configs");
  //lcd.setCursor(0, 1);
  Serial.println("** DC Motors **");
  //lcd.print("DC Motors");
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);

  // Turn off motors - Initial state
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  //delay(3500);
  //lcd.clear();

  //lcd.setCursor(0, 0);
  //lcd.print("Loading Complete!");
  //delay(3500);
  //lcd.clear();

  //lcd.setCursor(0, 0);
  Serial.println("** Ready **");
  Serial.println("*********************");
  //lcd.print("Ready");
  //delay(500);



  stepper.attach(STEP, DIR); //STEP=Pin, DIR=Pin

}
void loop()
{
    Serial.println(motorStatus);

  bounce.update();
  // <Bounce>.changed() RETURNS true IF THE STATE CHANGED (FROM HIGH TO LOW OR LOW TO HIGH)
  if ( bounce.changed() ) {
    // THE STATE OF THE INPUT CHANGED
    // GET THE STATE
    int deboucedInput = bounce.read();
    // IF THE CHANGED VALUE IS LOW
    if ( deboucedInput == HIGH ) {
      motorStatus = !motorStatus; // SET ledState TO THE OPPOSITE OF ledState
      digitalWrite(ENA,motorStatus); // WRITE THE NEW ledState
    }
  }
  /*
    stepper.setZero( );

    Serial.println(stepper.read());
    Serial.println(stepper.currentPosition());
  */





  while (!Serial.available());
  String incommingString = Serial.readStringUntil('\n');
  int len;
  len = incommingString.length();
  //lcd.clear();
  //lcd.setCursor(0, 0);

  Serial.print("\n\nincommingString = "); // for IDE to test
  Serial.println(incommingString);   // for IDE to test
  Serial.println();
  //lcd.print("Incomming String"); // for IDE to test
  ////lcd.setCursor(2, 1);
  //lcd.print(incommingString);   // for IDE to test */
  String incommingStr = incommingString.substring(len - 12, len); // truncate to the correct length

  if  (incommingStr.length() != 12)
  {
    rotResult = false;    // rotation was not successfull
  }
  else
  {

    Serial.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    String mode = incommingStr.substring(0, 1); // 1 byte
    Serial.print("mode = ");
    Serial.print(mode);
    Serial.println(" (F)ull Step, (H)alf Step (M)icro Step 1/4");
    delay(10);
    String dir = incommingStr.substring(1, 2);  // 1 byte
    Serial.print("direction = ");
    Serial.print(dir);
    Serial.println(" (F)orwards, (B)ackwards");
    String noOfSteps = incommingStr.substring(2, 6); //4 bytes
    Serial.print("Number Of Steps = ");
    Serial.println(noOfSteps);
    String rotationSpeed = incommingStr.substring(6, 10); //4 bytes
    Serial.print("rotationSpeed = ");
    Serial.println(rotationSpeed);
    String sdelay = incommingStr.substring(10, 12); //2 bytes (Unused)
    Serial.print("sdelay(not used) = ");
    Serial.println(sdelay);
    int    rotationSpeed1 = rotationSpeed.toInt();
    int    noOfSteps1 = noOfSteps.toInt();
    int    sdelay1 = sdelay.toInt();
    //printSomeInfo();
    Serial.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    Serial.println();


    /////////////////////////////////////////////////////////////////////////////

    stepper.setSpeed(rotationSpeed1); //RPM

    rotResult = true;  // initialize rotation result to erronous
    if (dir == "F")
    {
      static int motorStatus = 0;
      stepper.doSteps(-noOfSteps1 * MICROSTEPS);  // Moves Stepper Forwards
      static int waitSteps = 0;  //static variables persist beyond the function call, preserving their data between function calls.
      waitSteps += noOfSteps1;
      Serial.print("waitSteps = ");
      Serial.println(waitSteps);

      /*

        count


      */


      {
        delay(500);          //////////////////////////////////
        analogWrite(ENA, 255); //50  //  Take Up Reel (Forward)
        digitalWrite(IN1, LOW);     //
        digitalWrite(IN2, HIGH);    //  Winds excess film onto
        //delay(noOfSteps1);          //  the reel.
        delay(18);
        analogWrite(ENA, 0);        //////////////////////////////////
      }
    }
    else
    {
      stepper.doSteps(noOfSteps1 * MICROSTEPS);  // Moves Stepper Backwards
    }

    if (mode == "F")
    {

      //stepper.doSteps(noOfSteps1);  // Moves Stepper Backwards
      for (int i = 0; i < noOfSteps1; i++)
      {

        delay(6);
      }
    }
    if (mode == "H")
    {
      //stepper.doSteps(noOfSteps1 * MICROSTEPS);  // Moves Stepper Backwards
      for (int i = 0; i < noOfSteps1; i++)
      {
        //tmc26XStepper.step(noOfSteps1);
        //tmc26XStepper.move();
        delay(10);
      }
    }
    if (mode == "M")
    {
      //stepper.doSteps(noOfSteps1 * MICROSTEPS + 200);  // Moves Stepper Backwards
      for (int i = 0; i < noOfSteps1; i++)
      {

      }
    }
    rotResult = true;    // rotation was successfull
  }

  if (rotResult == true)
  {
    Serial.println("Move Complete! "); Serial.print("PC App Error Code = "); Serial.write("1111111111"); Serial.println(); // rotation successfull
  }
  else
  {
    Serial.println("Move Failed! "); Serial.print("PC App Error Code = "); Serial.write("0000000000"); Serial.println(); // rotation failed
  }
  // int count = 0;
  // checkCount();  // call this whenever you want to see if count is ready

}   // end pf script

And this is what I added to start counting steps

      static int waitSteps = 0;  //static variables persist beyond the function call, preserving their data between function calls.
      waitSteps += noOfSteps1;

Im now trying to work out how to get my microswitch working using the Bounce2-Lib Seams easy enough.

Then i need to work out a if else section. if button pressed stop motor and start checking waitSteps, if waitSteps => 200 re enable the dc motor and set waitSteps = 0.

Here are a few pictures of my setup:-







I hope that iv not forgetting anything.

1 Like

That code's pretty hard to read, especially given the length of the loop function. There's a hint that it was factored better previously in the commented out printSomeInfo call. I would refactor it so that loop is much smaller and readable.

I didnt understand your comment sorry. im not a coder. im just trying to get someone elses code to work with my hardware. tell you what. ill post the original code with no edits but me.

// Arduino script to support the TMC26XStepper driver
// Thanks to Lawrence Cockell who has written this script
#include <SoftwareSerial.h>
#include <SPI.h>
#include <TMC26XStepper.h>
#include <Wire.h>
#include <Adafruit_MotorShield.h>
// Expected a string from CineFrameCatcher with the following layout TDssssssvvvviii
// T = type: F = fullsteps, H = halfsteps, M = microsteps (16 or 256 per fullstep)
// D = direction: F = forward,  B = backward
// ssssss = number of full, half or micro steps to be perfomed (according to type)
// vvvv = velocity of rotation in rpm (rotations per minute)
// iii = idle time in milliseconds - can be multiplied to get longer idle times
//
const int stepsPerRevolution = 400;  // set according to the used motor
                                     // for 7.5° motor :  48 steps per rotation (full step)  - not supported - not precise enough
                                     // for 1.8° motor : 200 steps for stepper initialisation
                                     // for 0.9° motor : 400 steps for stepper initialisation
                                     //
//we have a stepper motor with 400 steps per rotation, CS pin 6, dir pin 4, step pin 5 and a current of 700mA
TMC26XStepper tmc26XStepper = TMC26XStepper(400,6,4,5,700);
int  rotationSpeed1;
char termChar = '\n';
bool rotResult = false;;

void setup()
{
Serial.begin(9600);
    Serial.println("Configuring stepper driver");  // can be taken out for CineFrameCatcher, it does not care abaout that feedback
    //char constant_off_time, char blank_time, char hysteresis_start, char hysteresis_end, char hysteresis_decrement
    tmc26XStepper.setSpreadCycleChopper(2,24,8,6,0);
    tmc26XStepper.setRandomOffTime(0);
    tmc26XStepper.setMicrosteps(1);
    tmc26XStepper.setStallGuardThreshold(4,0);
    tmc26XStepper.start();
    Serial.println("config finished, starting");
    Serial.println("started");
}

void loop()
{
    while(!Serial.available());
    String incommingString = Serial.readStringUntil('\n');
    int len;
    len = incommingString.length();
    // Serial.print("incommingString ="); // for IDE to test
    // Serial.println(incommingString);   // for IDE to test  
    String incommingStr = incommingString.substring(len-15,len); // truncate to the correct length
    
  	if  (incommingStr.length() != 15)
    {
        rotResult = false;    // rotation was not successfull
    }
    else
	  {   //input has correct length
        String mode = incommingStr.substring(0,1);
        String dir = incommingStr.substring(1,2);
        String noOfSteps = incommingStr.substring(2,8);
        String rotationSpeed = incommingStr.substring(8,12);
        String sdelay = incommingStr.substring(12,15);   
        int    rotationSpeed1 = rotationSpeed.toInt();
        int    noOfSteps1 = noOfSteps.toInt();
        int    sdelay1 = sdelay.toInt();
        int    microsteps;
     
        tmc26XStepper.setSpeed(rotationSpeed1);  //adafruit v2
        rotResult = true;  // initialize rotation result to erronous 
        if (dir == "F")
        {
			tmc26XStepper.step(noOfSteps1);
		}
		else
		{
			tmc26XStepper.step(-noOfSteps1);
		}
		
        if (mode == "F")
        {
            tmc26XStepper.setMicrosteps(1);
            tmc26XStepper.step(noOfSteps1);
            for (int i = 0; i < noOfSteps1; i++)
            {
                tmc26XStepper.move();
                delay(6);
            }
        }
        if (mode == "H")
        {
            tmc26XStepper.setMicrosteps(2);
    	    for (int i = 0; i < noOfSteps1; i++)
            {
                tmc26XStepper.step(noOfSteps1);
                tmc26XStepper.move();
                delay(10);
            }
        }
        if (mode == "M")
        {   
            tmc26XStepper.setMicrosteps(256);       // 16 or 256 depending on controller board
            for (int i = 0; i < noOfSteps1; i++)
            {
                tmc26XStepper.step(noOfSteps1);
                tmc26XStepper.move();
            } 
        }        
        rotResult = true;    // rotation was successfull                   
    }
      
    if (rotResult == true)
    {
        Serial.write("1111111111");  // rotation successfull
    }
    else
    {
       Serial.write("0000000000");  // rotation failed
    }  
}   // end pf script

1 Like

@creativesamurai1982 I assume that you can easily imagine a machine with different modes of operation.
Example a Kitchen stove with integrated oven

This "machine" can be set to different operation-modes

  • One to four hotplates switched on
  • Oven operated with hot air
  • Oven operated with top heat / bottom heat
  • Oven operated as a microwave

Your film-scanner can be seen as a machine with different-operation-modes.

  • mode 1: waiting for a serial command to arrive

  • mode 2:

    • springloaded lever not at max-tension-position (= microwitch is unpressed)
    • DC motor on
    • driving the stepper-motor to pull the film to have the next single-picture aligned above scanner
  • mode 3:

    • springloaded lever IS at max-tension-position (microswitch is pressed
    • switch DC-motor off
    • driving the stepper-motor to pull the film to have the next single-picture aligned above the scanner check if stepper-motor has done 200 steps since microswitch was pressed

different modes of operation can be achieved using a state-machine

It is very normal that from this description you were not yet able to write the code for the state-machine.
This is just an introductional description that shall describe the concept.

It will take some more steps to write the code.
If you don't want to invest money to engage somebody to write the code for you.
You have to invest time. Time to ask step by step

  • asking how this code works
  • sometimes asking about programming-basics
  • posting a new attempt to write the code after 15 to 30 minutes (not after 6 hours) in combination with a specific question related to your code.

To make the code easier readable the code should be grouped into parts where each part does a one thing in the sense of dealing with things like

  • decode sended serial message = divide the character-sequence into the logocal parts and convert chars to numbers

  • drive stepper-motor

  • switch on/off DC-motor

best regards Stefan

1 Like

Iv heard of state machines. So today im gonna try and cleam my code so you guys can read it better. Perhaps I got try void functions? As im unsure how to make them with return functions. Ill make that my next read.

Thanks Stefan for being so patient with me.

Best Regards

Dave

1 Like

@StefanL38 may well be onto something with the state machine thought. Given your lack of coding experience though, I'd avoid them. They're great, but curiously difficult to comprehend to start with.

1 Like

Block Diagram
(because verbalizing doesn't help)

I think this is just a question of using an everyday analogon and everyday words that illustrate / explain the function / how it works

The difficulties start with the word "state-machine" If I would have the power to establisch a different word for this kind of functionality than the common term "state-machine" I would choose the word operation-mode. Maybe you or somebody else has an even better idea.
Though I don't have the power to establish this other word I stay with it after an introduction that compares it with "operation-mode"

The analogon has to show the repetitive-character like calling the "state"-function again and again.

best regards Stefan