Arduino Forum

Using Arduino => Motors, Mechanics, Power and CNC => Topic started by: backbone on Apr 24, 2014, 11:09 am

Title: (Solved)Steppermotor and serial.print and read combined
Post by: backbone on Apr 24, 2014, 11:09 am
Curious what I do wrong.

Button currrently controls up and down movement of the stepper motor.
Code works but as soon as I uncomment a line related to serial.print it also stops to work correctly.

I need the combination as I use the stepper to compress a spring and measure the force and the current position which need to be send to a PC application.

Am I asking to much from this combo?

Paco

Code: [Select]

#include <HX711.h>

// HX711.DOUT - pin #A1
// HX711.PD_SCK - pin #A0

HX711 scale(A1, A0); //load cell libary


int Analog2 = 16;           // Use analog port on shield for push button to control movement and Direction
int Analog3 = 17;           // Use analog port on shield for push button to control movement and Direction
int Distance = 0;           // Record the number of steps the motor has done
int delayTimeUp = 300;
int delayTimeDown = 100;
int Position = 1000;
boolean MotorStopDown = 0;
boolean MotorStopUp = 0;
boolean flagStartInit = 0;
boolean flagRecording = 0;
boolean flagReturn = 0;
const int DirPin = 8;
const int StepPin =9;
const int EnablePin = 10;
int IncomingData = 0;
int outByte = 0;
int cmdTemp = 0;
int MaxTravel = 0;
boolean LeftTurn = 0;
boolean RightTurn = 0;

void setup()
{
 pinMode(DirPin, OUTPUT);
 pinMode(StepPin, OUTPUT);
 pinMode(EnablePin, OUTPUT);
 pinMode(Analog2,INPUT);   // set the A2 pin to input
 pinMode(Analog3,INPUT);   // set the A3 pin to input
 digitalWrite(DirPin, LOW);
 digitalWrite(StepPin, LOW);
 digitalWrite(EnablePin, HIGH);
 Serial.begin(9600);
}

void loop()
{  
 
 LeftTurn = digitalRead(Analog2);
 RightTurn = digitalRead(Analog3);  

 if (LeftTurn == 1)  // upwards
 {
   digitalWrite(EnablePin, LOW);
   digitalWrite(DirPin, LOW);
   digitalWrite(StepPin, HIGH);
   delayMicroseconds(delayTimeUp);          
   digitalWrite(StepPin, LOW);
   delayMicroseconds(delayTimeUp);
   digitalWrite(EnablePin, HIGH);
   digitalWrite(DirPin, LOW);
   Distance = Distance + 1;   // record this Step as part of a rotation where 900 is a quarter rotation
   if (Distance == 900);
   {
     digitalWrite(EnablePin, HIGH);
     digitalWrite(DirPin, LOW);
     Distance = 0;   // reset the Motorstep counter to 0
     Position = Position - 1;
   }
 }
 else if (RightTurn == 1)  // downwards
 {
   digitalWrite(EnablePin, LOW);
   digitalWrite(DirPin, HIGH);
   digitalWrite(StepPin, HIGH);
   delayMicroseconds(delayTimeDown);          
   digitalWrite(StepPin, LOW);
   delayMicroseconds(delayTimeDown);
   digitalWrite(EnablePin, HIGH);
   digitalWrite(DirPin, LOW);
   Distance = Distance + 1;   // record this Step as part of a rotation where 900 is a quarter rotation
   if (Distance == 900);
   {
     digitalWrite(EnablePin, HIGH);
     digitalWrite(DirPin, LOW);
     Distance = 0;   // reset the Motorstep counter to 0
      Position = Position + 1;
   }
 }
 else
 {
   digitalWrite(EnablePin, HIGH);
   digitalWrite(DirPin, LOW);
 }

 //Serial.print ("A,");
 //Serial.println (Position); // keeps score of the steps done to calulate the movement in 0.5 mm + or -
 //Serial.print ("B,");
 //Serial.println(scale.read()/100); //raw loadcell data devided by 100
}


Title: Re: Steppermotor and serial.print and read combined
Post by: knut_ny on Apr 24, 2014, 11:14 am
Take a look at the stepper libraries  (also see accelstepper)
This will require a rewrite, but may solve your problem
Title: Re: Steppermotor and serial.print and read combined
Post by: MarkT on Apr 24, 2014, 02:34 pm

Curious what I do wrong.

Button currrently controls up and down movement of the stepper motor.
Code works but as soon as I uncomment a line related to serial.print it also stops to work correctly.

You need to explain what working correctly and working incorrectly means for
your code, and to tell us which line you commented/uncommented.

Quote

Am I asking to much from this combo?

Perhaps explaining exactly what you want would be a start.

And why are you setting the enable pin of the stepper motor low - it would normally
just be tied to 5V and left that way.

Is there a reason you forgo the AccelStepper library btw?
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on Apr 24, 2014, 05:50 pm
OK appolgies for the info.

If I uncomment the line with serial print the stepper motor runs in a very very low speed.

The reason I did not used the accelstepper lib was that I used a piece of sample code that was not refering to it.
So now I for test used this piece of code and added the serial.print in this demo just to see if it keeps the stepper motor speed and a serial value is written. It keeps the speed but serial.print doesnt show anything happening in the serial monitor.

Enable is used on the easy driver too de-energize the coils if the stepper motor is in rest position. There is no need to keep them alive as this only heats up the driver IC.

Code: [Select]
#include <AccelStepper.h>

// Define a stepper and the pins it will use
AccelStepper stepper(1, 9, 8);

int pos = 900;
int Position = 1000;

void setup()
{  
 stepper.setMaxSpeed(3000);
 stepper.setAcceleration(1000);
}

void loop()
{
 if (stepper.distanceToGo() == 0)
 {
   delay(500);
   pos = -pos;
   stepper.moveTo(pos);
 }
 stepper.run();
 
 Serial.print ("A,");
}


What I need in the end...........
I need to measure a force by a spring on a weigth sensor and the compression in 0.5 mm steps.
Sensor and HX711 IC works fine and with serial.print I send the raw value to the PC.
All other weight calculation and calibration is done in the PC.
I compress the spring step by step and need to measure the force that belong to it.
The coil spring is for example 70 mm long. So I need to compress it to 35 mm. No need to compress it more.
I start a measurement sequence.
Pulse is send from PC to arduino. The rest of the sequence need to be done in the Arduino UNO.
Reset the force value to zero in PC is done too.
The pulse gives the stepper motor the action to start rotate downwards.
As soon as the PC sens a force larger (>) then 1 gram we reset the force and reset the counter of the stepper motor and start to write the data to a file in the PC. So each certain compression value gets it force value. So each 0.5 mm step has a force value.
As soon as the 35 mm is reached the motor rewinds upwards and decompress the spring untill it is 2mm above the point where the measurement of the force started.
We repeat the same sequence and after 5 in row we stop and show the dat in a graph and tabellist.
During the compression the data is shown in a graph too.

I had it all working fine but that was with a H bridge stepper using the L298 IC.
But for easier use I like to use the easy stepper driver but ran in the problem of the serial.print problem,

I hope my intentions with this project are clear if not shoot the questions to me. :-)
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on Apr 24, 2014, 06:21 pm
You have forgotten to put Serial.begin() in setup()

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on Apr 24, 2014, 06:22 pm
oohps forgot the Serial.begin(9600); to add to the setup.
Now we have serial data out but again the stepper motor slows down.

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 24, 2014, 10:42 pm
OK,
I did some more homework.
But I still am having problems to finalize the project.
1] I used the accelstep lib instead of stepper.h
2] I added an encoder disk to the output shaft of the steppermotor as the accuracy was not good enough and I use the interrupts to measure the steps on pin 2 and 3

But it looks like the arduino cant cope with sending the force data to the PC in the voidloop and simultanously controlling the stepper motor and sending the encoder data. I changed the serialprint to a place where it is updated if 1 mm displacement has been measured. But this way I am missing the continously measurement of the force. it is the HX711 slowing down when it serialprint action is placed in the VOID LOOP root.

I had to raise the baudrate to 57600 too.

In this part of the project I cant use a DC motor as the stepper motor is part of the mechanism I have to use.

Would it be better to run the stepper board on its own Arduino so it only drives the Stepper as DC motor?

Code: [Select]
#include <HX711.h>
#include <AccelStepper.h>

// HX711.DOUT - pin #A1
// HX711.PD_SCK - pin #A0

HX711 scale(A1, A0); // 24 bit load cell amplifier

int LeftTurnUp = 0;
int RightTurnDown = 0;
int incomingByte = 0;   // for incoming serial data
int enablePin10 = 10;  // switch off coils when not in use to reduce heat build up
int dirPin = 8;
int stepPin = 9;
int StepCounter =0;

AccelStepper stepper(4,4,5,6,7); // set up the stepper as 4 wire bipolair on pin 4,5,6,7
//AccelStepper stepper(1,8,9); // set up the stepper as 4 wire bipolair on pin 8,9 for EASY DRIVER

/////
enum PinAssignments
{
  encoderPinA = 2,   // rigth
  encoderPinB = 3,   // left
};

volatile unsigned long encoderPos = 100000;  // a starting counterposition for the encoder
long encoderPosOld = 100000;
unsigned int lastReportedPos = 1;   // change management
static boolean rotating=false;      // debounce management

// interrupt service routine vars
boolean A_set = false;             
boolean B_set = false;
//////


void setup()
{
  Serial.begin(57600);
  StepCounter = 500;
  stepper.setMaxSpeed(1000);
  stepper.setSpeed(1000);
  stepper.setAcceleration(800); // do not remove!

  pinMode(enablePin10, INPUT);

  // encoder disk part
  pinMode(encoderPinA, INPUT);
  pinMode(encoderPinB, INPUT);
  // turn on pullup resistors
  digitalWrite(encoderPinA, HIGH);
  digitalWrite(encoderPinB, HIGH);
  // encoder pin on interrupt 0 (pin 2)
  attachInterrupt(0, doEncoderA, CHANGE);
  // encoder pin on interrupt 1 (pin 3)
  attachInterrupt(1, doEncoderB, CHANGE);

}

void loop()
{

  //Serial.print ("A,");
  //Serial.println (encoderPos,DEC); // keeps score of the steps done to calulate the movement in mm + or -
  //Serial.print ("B,");
  //Serial.println(scale.read()/100); //raw loadcell data devided by 100

  if (Serial.available() > 0)
  {
    incomingByte = Serial.read();
    {
      if (incomingByte == '1')
      {
        digitalWrite(enablePin10, HIGH);
        LeftTurnUp = 1;
        RightTurnDown = 0;
      }

      if (incomingByte == '2')
      {
        digitalWrite(enablePin10, HIGH);
        RightTurnDown = 1;
        LeftTurnUp = 0;
      }

      if (incomingByte == '3')
      {
        LeftTurnUp = 0;
        RightTurnDown = 0;
        stepper.moveTo(0);
        digitalWrite(enablePin10, LOW);
      }
    }
  }

  if (LeftTurnUp == 1)  //left turn
  {
    stepper.moveTo(1000000); //move many steps - more then mechanical needed
  }

  if (RightTurnDown == 1)  //right turn
  {
    stepper.moveTo(-1000000); //move many steps - more then mechanical needed
  }


  //if (encoderPos >= (encoderPosOld + 1081)) //if the value is 1081 higher then last known send data to PC
  if ((encoderPos >= (encoderPosOld + 1081)) || (encoderPos <= (encoderPosOld - 1081))) //if the value is 1081 higher or 1081 lower then last known send data to PC
  {
    encoderPosOld = encoderPos;
    Serial.print ("A,");
    Serial.println (encoderPos,DEC); // keeps score of the steps done to calulate the movement in mm + or -
    Serial.print ("B,");
    Serial.println(scale.read()/100); //raw loadcell data devided by 100
  }

  stepper.run();


// Interrupt on A changing state
void doEncoderA(){
  // debounce
  if ( rotating );  //removed the 1 us delay // wait a little until the bouncing is done

  // Test transition, did things really change?
  if( digitalRead(encoderPinA) != A_set ) {  // debounce once more
    A_set = !A_set;

    // adjust counter + if A leads B
    if ( A_set && !B_set )
      encoderPos += 1;

    rotating = false;  // no more debouncing until loop() hits again
  }
}

// Interrupt on B changing state, same as A above
void doEncoderB(){
  if ( rotating ); //removed the 1 us delay
  if( digitalRead(encoderPinB) != B_set ) {
    B_set = !B_set;
    //  adjust counter - 1 if B leads A
    if( B_set && !A_set )
      encoderPos -= 1;

    rotating = false;
  }
}

Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 24, 2014, 11:38 pm
If the stepper motor is missing steps then you need to sort that out - not add an encoder as a band-aid.

You have a lot of Serial.print() commads - they take a lot of time.

You should calculate how often it is necessary for the motor to step (how many millisecs or microsecs between steps) so you can then figure out if loop() repeats sufficiently often.

You could have stepper.run two or three times within loop().

I presume data is only received occasionally - like once per second or less.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 25, 2014, 08:30 am
Hi Robin,

Thanks for the response.
I know the encoder is a band-aid but if I use the stepper and send a pulse to rotate 180 degree and then 180 degree reverse the encoder shows me we are not returning at the same spot. I have no idea how to use the stepper without encoder to get accurate position, no idea what is causing it or how to solve it.

I need the force to be measured and send to the PC constantly so that is why the serialprint was originally in the void loop root.
The reason for this constant measurement is that I send the motor down in constant motion and as soon as I starts to measure a force it has to start recording. the value of the force and the mm steps. During recording I can reduce the measurement of the force with each 1 mm step and put the serial print in:
Code: [Select]
//if (encoderPos >= (encoderPosOld + 1081)) //if the value is 1081 higher then last known send data to PC
  if ((encoderPos >= (encoderPosOld + 1081)) || (encoderPos <= (encoderPosOld - 1081))) //if the value is 1081 higher or 1081 lower then last known send data to PC
  {
    encoderPosOld = encoderPos;
    Serial.print ("A,");
    Serial.println (encoderPos,DEC); // keeps score of the steps done to calulate the movement in mm + or -
    Serial.print ("B,");
    Serial.println(scale.read()/100); //raw loadcell data devided by 100
  }


If there any other options to try or sort out let me know.
Eager to get this going.
I will make a picture of the current set up of the compression device so it more clear of its purpose.

Thanks, Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 25, 2014, 09:34 am
Attached the picture of the unit.
At the bottom the loadcell at the top the stepper motor with the attached encoder.
The encoder is 300LPI, the steppermotor is a NEMA 17 version.
I control the up and down motion by PC.

I hope this give a visualisation of the project,
BTW the stepper is not used to send to a certain location like a CNC machine.
The unit gives information in return (force) which a CNC is not doing.
When only using the stepper you always have to presume the stepper is at the correct position at the time you need to measure the force, there is no feedback from the stepper it is.
Correct me if I am wrong.
Other issue is that the measurement needs to be done in a fluent motion not in start/stop steps.

Any help is appriciated.
If I have to break down the project in parts and test and enhance it for eaxmple the stepper accuracy, no problem.

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 25, 2014, 11:26 am
I can only think of 2 reasons why the stepper is missing steps - either the load against it is too great (need a bigger motor?) or the pulses are being sent too quickly and the motor can't keep up.

Are you using the motor in micro-stepping mode? If so it will have much less torque than in full step mode.

I have the impression that the core of your project involves a loop of code like this

Code: [Select]
void loop() {
   readLoadCell();
   readEncoder();
   analyzeData();
   moveMotorOneStep();
}


I don't immediately see why all that can't be done.

How often do you need to step the motor (milli/microsecs between steps)?
How many steps does the motor need to make (in one direction) during a test?

Are you sure the motor is working at its full permitted coil current?
Have you posted the specifications for the motor, driver and power supply?

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 25, 2014, 12:16 pm
Robin,

Motor is rated for 1,5 amps per coil.
Powersupply is rated 4 amps at 18 volts.

I do full steps (as far as I am aware of) I currently use the L298 board (fullbridge) and I cant set microstep.
I am await new Easy driver boaards as I blew up two of them. The L298 board is more forgiving.
Or this is done in the accelstep.h file but I did not alter it.

I did some more testing with below code and found out that the the accelstepper.h lib the stepper is accurate enough.
Before it was missing 20 to 30 steps now it is accurate on the step or +/- 2.
It might have to do that the accelstep lib use accellaration where the stepper.h does not.
Even without compressing the spring in previous setups the tolerance was 20 to 30 steps and very irragular.
So motor is strong enough.

Each half rotation of the motor is 100 steps is 180 degree is 1 mm displacment of the upper plate to compress the spring.
I need to measure upto 70 mm displacement so we are talking about 70 x 100 motor steps in total.

For below code I have to find a way to switch off the coils after each step because I will smoke this board too..
Switching off currently it only happens when I send "3" to the serial monitor.
After sending "1" or "2" the coils should be automaticly de-energized.
Have tried several options but did not worked.

Code: [Select]

// debug code for steppermotor using serial monitor to control 100 steps in either direction
#include <AccelStepper.h>

int LeftTurnUp = 0;
int RightTurnDown = 0;
int incomingByte = 0;   // for incoming serial data
int enablePin10 = 10;  // switch off coils when not in use to reduce heat build up
int dirPin = 8;
int stepPin = 9;
int StepCounter =0;

AccelStepper stepper(4,4,5,6,7); // set up the stepper as 4 wire bipolair on pin 4,5,6,7
//AccelStepper stepper(1,8,9); // set up the stepper as 4 wire bipolair on pin 8,9 for EASY DRIVER

/////
enum PinAssignments
{
 encoderPinA = 2,   // rigth
 encoderPinB = 3,   // left
};

volatile unsigned long encoderPos = 100000;  // a starting counterposition for the encoder
long encoderPosOld = 100000;
unsigned int lastReportedPos = 1;   // change management
static boolean rotating=false;      // debounce management

// interrupt service routine vars
boolean A_set = false;              
boolean B_set = false;
//////


void setup()
{
 Serial.begin(57600);
 StepCounter = 500;
 stepper.setMaxSpeed(1000);
 stepper.setSpeed(1000);
 stepper.setAcceleration(800); // do not remove!

 pinMode(enablePin10, INPUT);

 // encoder disk part
 pinMode(encoderPinA, INPUT);
 pinMode(encoderPinB, INPUT);
 // turn on pullup resistors
 digitalWrite(encoderPinA, HIGH);
 digitalWrite(encoderPinB, HIGH);
 // encoder pin on interrupt 0 (pin 2)
 attachInterrupt(0, doEncoderA, CHANGE);
 // encoder pin on interrupt 1 (pin 3)
 attachInterrupt(1, doEncoderB, CHANGE);

}

void loop()
{


 if (Serial.available() > 0)
 {
   incomingByte = Serial.read();
   {
     if (incomingByte == '1')
     {
       LeftTurnUp = 1;
     }

     if (incomingByte == '2')
     {
       RightTurnDown = 1;
     }

     if (incomingByte == '3')
     {
       LeftTurnUp = 0;
       RightTurnDown = 0;
       stepper.moveTo(0);
       digitalWrite(enablePin10, LOW);
     }
   }
 }

 if ((LeftTurnUp == 0) && (RightTurnDown == 0))
 {
   digitalWrite(enablePin10, LOW);
 }

 if ((LeftTurnUp ==1) || (RightTurnDown == 1))
 {
   digitalWrite(enablePin10, HIGH);
 }

 if (LeftTurnUp == 1)  //left turn
 {
   stepper.moveTo(100); //move 100 steps  = 180 degree = 1mm
 }

 if (RightTurnDown == 1)  //right turn
 {
   stepper.moveTo(-100); //move 100 steps  = 180 degree = 1mm
 }



 if ((encoderPos >= (encoderPosOld + 1081)) || (encoderPos <= (encoderPosOld - 1081)))
 {
   encoderPosOld = encoderPos;
   Serial.print ("A,");
   Serial.println (encoderPos,DEC); // keeps score of the steps done to calulate the movement in mm + or -
 }

 stepper.run();
}  

// Interrupt on A changing state
void doEncoderA(){
 // debounce
 if ( rotating );  //removed the 1 us delay // wait a little until the bouncing is done

 // Test transition, did things really change?
 if( digitalRead(encoderPinA) != A_set ) {  // debounce once more
   A_set = !A_set;

   // adjust counter + if A leads B
   if ( A_set && !B_set )
     encoderPos += 1;

   rotating = false;  // no more debouncing until loop() hits again
 }
}

// Interrupt on B changing state, same as A above
void doEncoderB(){
 if ( rotating ); //removed the 1 us delay
 if( digitalRead(encoderPinB) != B_set ) {
   B_set = !B_set;
   //  adjust counter - 1 if B leads A
   if( B_set && !A_set )
     encoderPos -= 1;

   rotating = false;
 }
}



void loop() {
  readLoadCell(); >correct
  readEncoder(); >correct
  analyzeData(); > done in PC
  moveMotorOneStep(); >correct
}
Way of working:
1] PC button start click reset all values including force value to 0 and starts motor
2] Motor starts to turn downwards unconditional.
3] If we measured force > 1 gram
reset stepcounter
start recording
4] If stepcounter is > then the preset value (for example 35 mm)
Stop recording
Reverse motor
As we know how far we have to compress the spring we might use the steppermotor steps to calculate the steps we have dne and reverse the motor

5] If steps are 2 mm past starting point
Stop motor
Reset all and prepare for next automatic measurement.
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 25, 2014, 01:21 pm
Did some more test.

As soon as I put any a serial.print in the "void loop" root it slows down the stepper motor.

I tried to put the "stepper.run();" into a "blinkwithout delay" so it would be called in a lesser tempo but that slows down the stepper too. When I set 1 millisecond it still is to slow even.
So it is the combination of the serial.print with the stepper control but why???

Paco

Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 25, 2014, 02:34 pm
I haven't time to study all of your 2 posts now. Will try later.

An Easydriver isn't able to provide the current for a 1.4 amp motor. You need a BigEasydriver or equivalent.

What voltage is your power supply. With a BigEasydriver it could usefully be 20v or more. But you couldn't use that with an L298. Also the L298 has significant voltage losses so you may not be getting the voltage you expect across the motor coils.

You really need a proper stepper motor driver board and an high voltage power supply to ensure you get the full motor torque.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 25, 2014, 10:06 pm
Let the accuracy or motor amp be the last hurdle to sort out.

I recode and thought I found a bypass/reroute around the serial.print for detecting for a change in the initial start start stage.

I thought I was clever and use
"ForceValueTemp = (scale.read()/100);"
in the VOID LOOP and use it inside the arduino to send a reset signal to the PC.
Same problem as with the serial.print line added.stepper runs step by step in low rate.
If I comment the line high speed stepper again.

The HX711 amplifier is used with a lib. do not know if there is something inside that blocks.

Paco

BTW I have a video of the unit moving. (without serial prints in the void loop) :-)
https://www.youtube.com/watch?v=JCNRUc1FTfo&feature=youtu.be (https://www.youtube.com/watch?v=JCNRUc1FTfo&feature=youtu.be)

Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 26, 2014, 12:12 pm
I've now had a little time to look at your earlier posts ...

If this means that you don't care about missing steps
Quote
Let the accuracy or motor amp be the last hurdle to sort out.
then you will have to sort the problem out without my help. Going that route is like trying to push something with string.

In an earlier post you have
Quote
For below code I have to find a way to switch off the coils after each step because I will smoke this board too..
Sorry, but this is nonsense and just gets in the way. Choose a suitable motor voltage that works with your driver and motor and stop confusing your code with stuff lke this.

Quote
I tried to put the "stepper.run();" into a "blinkwithout delay" so it would be called in a lesser tempo but that slows down the stepper too. When I set 1 millisecond it still is to slow even.
You need more frequent calls to stepper.run() - not less. There is nothing to prevent you having stepper.run() at a few places within loop().

Quote
use it inside the arduino to send a reset signal to the PC
Why would you want to reset the PC? How could that speed things up. My PC takes a minute or so to reset.

My advice is simple ...

Take out the encoder stuff (at least for now)
Get the motor to step accurately without a load and then see if it also works under load.
Don't do anything else until the motor ALWAYS steps accurately under load.

Before concluding that you need a more powerful motor
Check the voltage available to the motor - perhaps by temporarily replacing the motor with an equivalent high wattage resistor.
Try it with a proper stepper motor driver board and a high voltage power supply.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: Gilgamesh90 on May 26, 2014, 06:55 pm
Is that a unipolar or bipolar stepper? Why dont you use a personally developed code to run the stepper and avoid any problems with the library?
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 26, 2014, 07:01 pm

Why dont you use a personally developed code to run the stepper and avoid any problems with the library?

Rest assured, the problem is not with the library in this case.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 26, 2014, 08:33 pm
Robin,

Thanks for your time again.

In the end I care about using the stepper only to make it less complicated and no encoder part and code but I had to start somewhere and the encoder is/was a part of detecting and learning. I know it is all a steep curve but willing to learn.
The first original design of this device to emasure compression was a rebuild vertical drilling stand equipped with an linear encoder strip so that was a heritage for counting the steps. The second design used a DC motor and the YES the encoder again, but I promiss I will get rid of all related to the encoder.

Due to limited time I have to work currently with the mechanics and electronics I have in stock.
New parts can be ordered but that takes time and I am not the person to sit down and wait untill........parts arrive.
Then for a certain time with less accuracy untill all the coding is working properly and the harware can be tuned to perfection to over come the accuracy.

Switching off the coils was a workaround for not having the good hardware.

I will not reset the PC! :-) I send a reset signal from the Arduino to the program on the PC so it knows we can start to measure.
Sorry if that was not clear written down.

I will crank up the motor voltage  and working on getting an other driver board.
The lastest BED driver is 1,4 amps max. So I have to look for other options.

I know the accelstep lib is OK.
It looks like the HX711.lib is causing the problem in combination with the stepper.lib.

Stepper is a bipolar one as far as I know as the spec with the unit only say 1.5 amps. Stepper Motor :42BYGH series ( NEMA17)

Did I for got something? :-)





Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 26, 2014, 08:54 pm
The Pololu A4988 driver uses the same chip as the BIgEasydriver and "claims" it can manage up to 2 amps with adequate cooling. according to the Allegro datasheet the absolute max is "about" 2 amps. I think Pololu has another board that can provide a bit more current. The problem is that the drivers get a lot more expensive if you want to go beyond those current levels. If you already have (or have ordered) a BigEasydriver I would try that with the current suitably limited before buying another board. You would be only a tiny bit below the motor's capacity.

The reason I have been focusing on getting the harware right is because, without that, you can't tell whether you have a hardware or a software problem.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 26, 2014, 10:16 pm
Robin,

I understand about the focusing on hardware.
But I cant relax waiting for..................... I hope you understand. ;-)
Not yet ordered an other driver.
But I think one of these babys would do the job in the future. Not on the limit.
[url][/http://www.ebay.nl/itm/TB6560-3A-Driver-Board-CNC-Router-Stepper-Motor-Drivers-1-Axis-Controller-/360919866303?pt=LH_DefaultDomain_0&hash=item5408801bbfurl]

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 26, 2014, 10:49 pm
I removed all encoder, coil enable and serial.prints code and this a quick test again.

As soon as I uncomment the trouble line of code

Code: [Select]
ForceValueTemp = (scale.read()/100);

the stepper goes into slow mode.
So this is step one to solve.

Code: [Select]
#include <HX711.h>
#include <AccelStepper.h>

// HX711.DOUT - pin #A1
// HX711.PD_SCK - pin #A0

HX711 scale(A1, A0) // 24 bit load cell amplifier

int LeftTurnUp = 0;
int RightTurnDown = 0;
int incomingByte = 0;   // for incoming serial data
int dirPin = 8;
int stepPin = 9;
int StepCounter =0;
boolean stepperPuls = 0;
long ForceValueTemp = 0;
long ForceValueTempOld = 0;
boolean Start = 0;
boolean Recording = 0;

AccelStepper stepper(4,4,5,6,7); // set up the stepper as 4 wire bipolair on pin 4,5,6,7 for L298 driver board
//AccelStepper stepper(1,8,9); // set up the stepper as 4 wire bipolair on pin 8,9 for EASY DRIVER

void setup()
{
  Serial.begin(9600);
  StepCounter = 200;
  stepper.setMaxSpeed(1000);
  stepper.setSpeed(1000);
  stepper.setAcceleration(800); // do not remove!
}

void loop()
{

  ForceValueTemp = (scale.read()/100); // problem code line!!!!!!!!!!!!!!!!!!!!!!!!

  if (Serial.available() > 0)
  {
    incomingByte = Serial.read();
    {
      if (incomingByte == '1') // move motor Up
      {
        LeftTurnUp = 1;
        RightTurnDown = 0;
      }

      if (incomingByte == '2') //move motor Down
      {
        RightTurnDown = 1;
        LeftTurnUp = 0;
      }

      if (incomingByte == '3') //stop motor and disable coils
      {
        LeftTurnUp = 0;
        RightTurnDown = 0;
        stepper.moveTo(0);
      }

      if (incomingByte == '4') // Start motor turn downwards
      {
        ForceValueTempOld = ForceValueTemp;
        Start = 1;
        RightTurnDown = 1;
        LeftTurnUp = 0;
      }

    }
  }

  if (LeftTurnUp == 1)  //left turn
  {
    stepper.moveTo(100); //move many steps - more then mechanical needed
    stepper.run();
  }

  if (RightTurnDown == 1)  //right turn
  {
    stepper.moveTo(-100); //move many steps - more then mechanical needed
    stepper.run();
  }
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 26, 2014, 11:02 pm
That stepper driver should be fine, and the price is good.

Is it necessary to read the scale between every step of the motor?

How much does it slow the motor? How slow is slow? Does slow really matter?

I know nothing about that scale-reading library. Maybe you could write your own code to read the scale without using the library.

Even if it is slow, is it stepping correctly?

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 26, 2014, 11:43 pm
With slow I mean it is just ticking.
if I have to describe it, it looks like 1 microstep inside 1 second.
A full turn would take one hour............ :-)
If needed I make a video of it what the slow speed is....
looks like the loop is blocked by the HX711.lib and release the stepper.run only once in every second.

As explained I need to measure the change in force as soon as the spring starts to compress.
That is the key point to start all.
Before the spring is compressed the value stays the same but when it rises I need to do an action which is start to record the values. Then I can measure in sync with the 1mm steps.

Writing my own code is out of my knowledge.
I can ask the lib writer to have a look at it.

paco

Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 27, 2014, 11:30 am
If it was my project I would write a short sketch (that doesn't use any stepper code) to measure the time (millis()) needed to do 100 or 1000 scale readings just to see how long it actually takes. But that may provide information without providing a solution. It would be very useful to discover that reading the scale does NOT cause a delay.

I guess you could use separate Arduinos for reading the scale and driving the stepper motor - but that seems a bit of a bodge.

Looking at your latest post again, I'm not sure what you mean by 1 microstep every second. Earlier you said you are using full steps. Are you back to a problem of not driving the motor properly rather than a software problem? Also, accelstepper has to do a lot more work to drive a stepper through an L298 chip than if it just has to produce step and direction signals.

If you had a "proper" stepper motor driver board I would suggest writing your own code to step the motor in case there is some strange conflict between accelstepper and the scale libraries.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 27, 2014, 12:56 pm
Quote
Looking at your latest post again, I'm not sure what you mean by 1 microstep every second. Earlier you said you are using full steps. Are you back to a problem of not driving the motor properly rather than a software problem?


No, the L298 does not allow microsteps.
This is a mechanicla behaviour I see happening  visual.
I drive the stepper with the same code the only exception is uncomment the line with the scale reading.
So it is code/software problem/conflict. I will make a video this evening so you see the thicking steps when the scale reading is active in the code.

Quote
If it was my project I would write a short sketch (that doesn't use any stepper code) to measure the time (millis()) needed to do 100 or 1000 scale readings just to see how long it actually takes. But that may provide information without providing a solution. It would be very useful to discover that reading the scale does NOT cause a delay


Good idea even if it does not solve the problem. Only current problem is "just writing a simple sketch":-)
Something like this you mean

Void loop()
{
Scalevalue = (scale.read()/100);
Serial.print(Scalevalue);
time = millis;
Serial.print(time-timeold);
timeold = time;
}

The HX711 is set to 10 Hz


Title: Re: Steppermotor and serial.print and read combined
Post by: wildbill on May 27, 2014, 03:05 pm
Quote
I had to raise the baudrate to 57600 too.


Why stop there? The arduino can handle twice that easily enough. Some people have reported getting substantially more working. If serial comms are causing you timing issues, at least step it up to 115200.
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 27, 2014, 03:14 pm
Wildbill,

Thanks for the info and concerns.
Somewhere in all the debugging  at 115200 bps setting at both sides there was no communication anymore.
Did not know the cause but logical the first thing I did was step down in bps level.
So I tried 57600 bps and that was the speed that worked.
Past days are done on 9600.
Will try once again this evening. Let you know the result.

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 27, 2014, 03:16 pm
I am thinking of much simpler code

Code: [Select]
#include <HX711.h>

HX711 scale(A1, A0) // 24 bit load cell amplifier

unsigned long startMillis = 0;
unsigned long endMillis = 0;

void setup() {
  Serial.begin(9600);
  startMillis = millis();
   for (int n = 0; n < 100; n++) {
      int s = scale.read();
   }
   endMillis = millis();
   Serial.println(startMillis - endMillis);
}

void loop() {

}


...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 27, 2014, 08:52 pm
Just had time to test the timing code

Will now first make the video of the thicking

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 27, 2014, 09:23 pm
here the video opf the hicking of the motor or the so called slow speed.
https://www.youtube.com/watch?v=FlJV74cAU-M&feature=youtu.be (https://www.youtube.com/watch?v=FlJV74cAU-M&feature=youtu.be)

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 27, 2014, 09:41 pm
Ok result of the timing code.  :smiley-roll:
I took 5 seperate reading
4294958292
4294958260
4294958222
4294958264
4294958238
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 27, 2014, 09:48 pm
For WIldbill,

Tried 115200bps not working
57600bps no problem.................!?
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 27, 2014, 10:03 pm

Ok result of the timing code


Something is wrong. Those numbers are far too big.

The Serial.println shoud be (endMillis - startMillis)  - sorry.

From the video the motor seems to be moving properly, just slowly.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 27, 2014, 10:15 pm
New values:   :-)
9038
9004
9032
9069
9001

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 27, 2014, 11:48 pm
They are the sort of numbers I was expecting based on the huge numbers.

Assuming that is for 100 scale.read()s it means that each one takes about 90 millisecs- which seems incredibly slow.

Change the 100 to 500 just to confirm that 90 msecs per read is correct - I don't expect any change.

I have no idea whether other code could read the scale more quickly. I suspect the library may be averaging several analogRead()s and maybe fewer reads would be sufficient for your purposes. That would either require modifying the library or writing your own code. Have you a link to where you got the library?

If there is no alternative to lengthy reads of the scale you have two options - put up with a slow stepper or don't read the scale between every single step.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 28, 2014, 07:52 am
Robin,

https://github.com/bogde/HX711 for the lib
As far as I know I just read each and single value. There is an average option in the lib but I do not use that on purpose.

With 500 reading the value is 45296

Thanks, Paco

Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 28, 2014, 08:29 pm
Got an answer from the lib designer.

i'm sorry but the library was not written with speed in mind, as that wasn't a concern for me at that time.
i guess one easier way to speed it up would be to use https://code.google.com/p/digitalwritefast/ (https://code.google.com/p/digitalwritefast/) and replace the slow calls in the read() function with their faster counterparts.

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 28, 2014, 11:05 pm
I will have a look at the library and what options there might be tomorrow - too late now.
-------
I have now downloaded the library and the PDF datasheet that is linked to by the author.

The Library code seems reasonably straightforward and there is a very short C example in the datasheet.

It should be relatvely simple to write your own code to read the device and then you can check for yourself what is the shortest time to do a single reading. The library uses the function bitWrite() which is going to be an awful lot slower than the simple << shift that is in the code in the datasheet.

The datasheet does say that the device can produce either 10 or 80 samples per second. Neither of those is fast by stepper motor standards and that might be the root of the problem. As far as I can see the library waits until the scale is ready rather than quickly returning with a not_ready indicator. That would be easy to change, but it won't give you more samples per second.

Maybe you need a different device to read the load at more frequent intervals?

Perhaps you should be one doing all the reading ?????

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 29, 2014, 02:49 pm
Hi Robin,

Thanks for the checking and the info.
With 10 samples per second for the loadcell value I am already happy.
If the motor steps the 1 mm in 1 second.
That would give me 10 samples for 1 mm.
So a sample per 0,1mm in the ideal world without delays :-)
If I raise the HX711 to 80 samples it would give me a sample per 0,08mm.
But a tolerance of 0.1 mm to start the real measurement of the data to the PC is acceptable.

For my application I only need the raw data with 128 or 64 amplification.
So need for average, tare or what ever just the raw data.
I know in these two cases the HX711 needs 25 or 27 pulses when the ADO is low and then the data is in the ADO should be high again.
Currently the pulses come and the data is written  from an analog port.
I do not have the knowledge to say if the suggested digitalwritefast lib and using a digital dedicated port Like D10 and D11 could speed things up.

The C code looks much like C++ code or am I wrong?

With my knowledge I reworked that code (will not work and full of errors but it is that I understand what is going on to get the data retreived as fast as possible

Code: [Select]
#include <digitalWriteFast.h>

int ADDOPin = 10;
int ADSKPin = 11;
unsigned long Count;
unsigned char i;

void setup()
{
  Serial.begin(115200);
  pinModeFast(ADDOPin, INPUT);
  pinModeFast(ADSKPin, OUTPUT);
  Count = 0;
}

void loop()
{
  Serial.print(Count);
}

unsigned long ReadCount(void)
{
  while digitalReadFast (ADDOPin, LOW)
  {
    for (i=0;i<24;i++) // for channel A and 128X
      //for (i=0;i<26;i++) // for channel A and 64X
    {
      digitalWriteFast(ADSKPin, HIGH);
      Count=Count<<1;
      digitalWriteFast(ADSKPin, LOW);

      if digitalReadFast(ADDOPin) Count++;
    }
    digitalWriteFast(ADSKPin, HIGH);
    Count=Count^0x800000;
    digitalWriteFast(ADSKPin, LOW);
    return(Count);
  }
}




Paco

reworked the code


Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 29, 2014, 08:40 pm
Paco, As far as I can see the only speed limitation is the frequency of getting samples from the scale. I don't think that has anything to do with digitalWrite() being slow and using any other function won't speed it up.

If you are content with 10 (or 80) samples per second (sps) then all you need to do is decouple the reading of the scale from the individual steps of the motor.

For simplicity, let's work on 10sps.

You say you want the motor to cause 1mm of movement in one second, or, more usefully 0.1mm of movement between samples. How many steps must the motor make to acheive 0.1mm of movement?

When we know this, we can work out how to program things. It may be necessary/convenient/useful to make a small change to the library but let's leave that for the moment.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 29, 2014, 09:31 pm
Hi Robin,

Sorry I confused you with the steps.
I reframe.....
200 stepper steps is 360 degree = 2 mm pitch/compression
100 stepper steps is 180 degree = 1 mm pitch/compression
1mm over 1 second is 10 samples = 1 sample per 0,1 mm
I have no objection to step slower but then measuring takes a longer time.
Lets say the average compression is 35 mm that would take 35 seconds to go down.
If you measure 5 times in a row that would be  10 times 35 seconds as we also have to return the motor to its original position.
For this debugging I have no problem stay with this timeframe.
In a later stage I can always enhance.

Quote
then all you need to do is decouple the reading of the scale from the individual steps of the motor.

You mean controlling the stepper with its own controller?




Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 29, 2014, 11:47 pm

Quote
then all you need to do is decouple the reading of the scale from the individual steps of the motor.

You mean controlling the stepper with its own controller?


No. Based on the numbers you have supplied all I mean is that you get the stepper to move 10 steps at 0.01 second intervals between each reading of the scale. If I recall correctly, your earlier code only moved it one step between each reading.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 30, 2014, 08:56 am
OK so the timingtable/storyboard should look like this:
1]
Start puls received from PC
Startflag = 1
Read in maximum value of compression ....35 mm from PC so counterMax is 35
Save current raw force value > rawValue.
Start rotation downwards in 18 degree steps = 0.1 mm
1 sample per 18 degree step = 0.1 mm
Measure raw force value each 18 degree step
rawValueOld = rawValue

2]
If rawValue > rawValueOld
counter = 0
Recordingflag = 1
send reset signal to pc so force value is set to zero
send reset signal to pc to start recording force and step value
Rotate motor in 180 degree steps
Serial.print(rawvalue)
Serial.print(counter)
Counter--
3]
if counter == counterMax (35)
Recordingflag = 0
Returnflag = 1
send reset signal to pc to stop recording force and step value
Rotate motor in 180 degree steps upwards
counter++
4]
if counter = - 4
Stop motor
Startflag = 0
Returnflag = 0


Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 30, 2014, 10:35 am
Hi Paco,
I have to confess I can't follow your steps (perhaps because I am not as familiar with the experiment).

I'm not sure if this helps but the logic in my head is a bit like this

   for (number of scale readings) {
          read scale
          for (10 steps) {
                    step motor
                    wait 0.01 sec
          }
    }

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 30, 2014, 10:31 pm
Robin,

I have viewed your idea several times but I cant get the grip on it. Sorry.
What can we do to solve that (if we can  :-)  )
Do I understand correct that the motor will stop for 0.01 sec?

On facebook I have a video of what the software at the PC side can do although that was with a manual drillstand and encoder strip recorded!.Maybe that gives a better feeling on it.
https://www.facebook.com/photo.php?v=714254455270548&set=vb.100000580005809&type=3&theater
Do not know if you can view it.
Let me know otherwise I have to search for an other option.

Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 31, 2014, 12:12 am
I have looked at your video but it doesn't tell me anything about the Arduino system.

I have been trying to match the information you have given me and the information I got from a brief read of the PDF for the scale interface.

I thought you said that 10 steps of the motor cause 1mm movement of the spring (or whatever). And that one reading of the scale every 0.1 seconds would be adequate. I put those together and came to the conclusion (perhaps wrong) that you need 10 steps of the motor between every scale reading and that would correspond with one step of the motor every 1/100th of a second. (And, yes, I know this is not watertight logic, but it explains my thinking).

Can you confirm if I have understood you properly, and if not please correct me.

Then you ask if the stepper motor will stop every 1/100th of a second and the answer is probably YES. That's how stepper motors work. I say "probably" because the momentum of the motor may carry it forward while the load will try to stop it.

Hope this helps.

if not, please try to explain what you don't understand.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 31, 2014, 10:33 am
Hi Robin,

The video was more to show that all should go in a fluent motion.

Ok here he comes again, no problem
The basic of the hardware.
1 stepper motor
1 leadscrew axle with 2 mm pitch
1 load cell.
Stepper motor full rotation = 360 degrees
With a leadscrew pitch of 2 mm each full rotation of 360 degrees of the motor the spring is compressed 2 mm.
2 mm steps are to large for fine measurments so we prefer avalue like 1 mm or less.
So to get 1mm compression we only have to turn 180 degrees.
If we want to compress 0.1 mm we ony have to turn 18 degrees.
The steppermotor I use has 200 steps for 360 degrees rotation.
100 steps is 180 degrees = 1 mm
10 steps is 18 degrees = 0.1 mm

Are you still with me? :-)

I put the spring on the loadcell bottomcone  and the loadcell now will give a certain value if we would measure it.
The spring is still uncompressed as the topcone part that moves down is not in contact yet. So first basic point is to find that TOUCHING POINT.
Now we can do this manually but turning the steppermotor by hand and look at the loadcell value when it starts to become higher, but we are trying to automate the measurement so we like to skip that manual part and do it fully automaticly to reduce time. Now we have to electronicly find the point where the topcone touches the top of the spring.
We can do that easily by measuring the point where the value on the loadcell starts to rise.
The HX711 lib slows down the steppermotor as each reading takes average 90 ms and we cant speed this up we found out.
So catching this first TOUCHING POINT is the key problem of this combo stepper and HX711.

Am I correct sofar and can you folow the basics of the project?

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 31, 2014, 01:15 pm
I think I understand what you want to do.

I will try to write a complete demo sketch later today (well, give me 24hrs).

Perhaps the concept you are missing is that, although you can't read the scale more than (say) 10 times per second it doesn't take long to read it if the scale is ready to provide data. So my notion is to move the motor while the scale is getting itself ready.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 31, 2014, 06:08 pm
I've written the following demo code. It compiles for me on an Uno but, of course I can't run it.

The code just tests how long it takes to move the motor 10 steps followed by a single read of the scales. The steps happen at intervals of 10 millisecs. As far as I can see that should give enough time for the scale to be ready so the scale.read() should return a value almost instantly. My plan is to prove (or disprove) this assumption by running the tests with the scale.read() line commented out and then with it active. If my assumption is correct there will be very little difference in the two sets of timings.

If there is a signficant difference in the timings perhaps you would increase the interval to 20 msecs and try again. If that solves the problem find the smallest interval that works.

Note that I added the line #include "HX711.h" because I didn't save the HX711 stuff into my libraries directory. You can delete that line.

I hope this brings you forward a little bit.

...R

Code: [Select]
// this is just to test the understanding of using the HX711

#include "HX711.h"
#include <HX711.h>
#include <AccelStepper.h>

// HX711.DOUT - pin #A1
// HX711.PD_SCK - pin #A0

HX711 scale(A1, A0); // 24 bit load cell amplifier

unsigned long startMillis;
unsigned long endMillis;
unsigned long currMillis;
unsigned long prevMillis;
unsigned long intervalMillis = 10;

byte maxTests = 5;
byte curTest = 1;

byte maxSteps = 10;
byte curStep = 1;

long scaleData = 0;

byte ledPin = 13; // onboard led

void setup() {

 Serial.begin(9600);
 Serial.println("Starting DemoCode1.ino");
 
 pinMode(ledPin, OUTPUT);
 digitalWrite(ledPin, LOW);

 prevMillis = millis();
}

void loop() {

 if (curTest > maxTests) {
   return;
 }
 startMillis = millis();
 curStep = 0;
 testTiming();
 endMillis = millis();
 Serial.print("Test ");
 Serial.print(curTest);
 Serial.print(" Time  ");
 Serial.println(endMillis - startMillis);
 curTest ++;

}

void testTiming() {
 
 while (curStep < maxSteps) {  // will loop through the steps at the speed set by intervalMillis
    currMillis = millis();
   if (currMillis - prevMillis >= intervalMillis) {
      stepMotor();
      prevMillis += intervalMillis;
      curStep ++;
   }
 }
 // now the Scale should be ready for reading
 scaleData = scale.read();
}

void stepMotor() {
 // something visible as an alternative to actually doing motor code
 digitalWrite(ledPin, ! digitalRead(ledPin));
}


Edited code to correct an error in the placement of currMillis = millis();  ...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on May 31, 2014, 09:11 pm
Robin,

Thanks for the demo code and the time.
I tried it with all suggested options like 10 up to 100 ms
With and without comment line for scaleData = scale.read();
Also removed the extra HX711.h line in the top.
Only line that is printed in the serial monitor = Starting DemoCode1.ino.

:~

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on May 31, 2014, 11:34 pm
Look at my code carefully - there is probably some stupid mistake.

I will look at it in the morning.

...in the morning.

Just as I thought - stupid mistake. I had currMillis = millis(); in the wrong place and it was never being updated.

I have corrected the code in the earlier post.

I realized that I can run the program on my Uno with the call to scale.read() commented out.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on Jun 02, 2014, 09:24 pm
We have a BINGO.
If 10 is selected all readings are 100.
I raised the sample numbers from 5 to 100.
All OK.
Then I lowered to 90 but then I get readings radom ranging from 89 to 91.
So no need to go higher but low is not prefered. :-)

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on Jun 02, 2014, 11:23 pm

We have a BINGO.
If 10 is selected all readings are 100.
I raised the sample numbers from 5 to 100.
All OK.
Then I lowered to 90 but then I get readings radom ranging from 89 to 91.
So no need to go higher but low is not prefered. :-)

Paco


You need to be a lot more precise.
Do you mean that you changed the maxTests value from 5 to 100 and it still worked?
By "alll readings" do you mean with and without the scale.read() command?

What did you lower to 90?
I wonder if you mean that you lowered intervalMillis to 9 (not 90)?
In what circumstances did you get 89 and when did you get 91?


Did you get it to print scaleData so you could see if it is giving correct values? (I have no way to test that).

Do you know what to do next or do you need some more advice?

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on Jun 03, 2014, 06:44 am
Sorry for half info.

Code: [Select]
Do you mean that you changed the maxTests value from 5 to 100 and it still worked?
YES

Quote
I wonder if you mean that you lowered intervalMillis to 9 (not 90)?

YES and then the result is random between 89 and 91.
If I lower intervalMiliis to a lower value like 8 or 7 the random numbers are more and more varying in larger up and down values like 65 to 73 for 7 intervalMiliis value.
Quote

By "alll readings" do you mean with and without the scale.read() command?

did not changed the standard setting yet.

Quote
Did you get it to print scaleData so you could see if it is giving correct values? (I have no way to test that).

Will test this evening.

I let you know if I need more of your time :-)

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on Jun 03, 2014, 11:46 am

did not changed the standard setting yet.


[sound] grinding of teeth in frustration [/sound]

The whole / the ONLY / point of the code was to try it with and without the call to scale.read().

Looking at the results with and without scale.read() makes even MORE sense when you change intervalMillis.

And checking that scale.read() gets sensible values will, of course, also be essential.

My jaw has now unclenched - have fun :)

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on Jun 03, 2014, 08:04 pm
Robin,

Please do not be frustrated. Sorry if I made you feel that way. Not my intention.
I have limited time sometimes.
See the pictures.
One with the commented line the other without.
Also the added line for the serial print of the load cell does not change the timing reading.
Results for 20 readings all the same except for the first one.
The reading of the loadcell value also stays the same.

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on Jun 03, 2014, 09:12 pm
It looks a bit strange to be showing scaleData values when the scale.read() is commented out ?????

Also, you haven't said whether the scaleData values are correct. Not much point moving forward until they are.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on Jun 04, 2014, 06:41 am
Robin,
Your correct about the two files showed.
My mistake. It seems I only make mistakes lately.
I forgot to upload the new sketch so the serial monitor showed same sketch.
This added file3.jpg with the serial monitor shows the values with lines commented out.
The value of the load cell is correct.
This just a raw value of the milivolts from the load cell amplified by the HX711.

Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on Jun 04, 2014, 12:45 pm
Thanks Paco.

Now you can see how it is possible to move the motor and read the scale without the process of reading the scale slowing things down.

What next?

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on Jun 05, 2014, 06:37 am
Next is to find out the touching point of the spring by the moving top plate. I hope I can find some time this evening to add some code and test it. One step furhter!

Thanks, Paco
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on Jun 06, 2014, 09:59 pm
Robin,

I changed the code to see how a real stepper would react instead of pulsing led 13 in the void stepperMotor()
So for the test I want to move the stepper in 180 degrees = 100 steps just to see if it works and if there is any motion.
But the stepper only steps one step per second with this code.

Paco

Code: [Select]
[/// this is just to test the understanding of using the HX711 and steppermotor

#include <HX711.h>
#include <AccelStepper.h>

// HX711.DOUT - pin #A1
// HX711.PD_SCK - pin #A0

HX711 scale(A1, A0); // 24 bit load cell amplifier

AccelStepper stepper(1,9,8); // set up the stepper as 4 wire bipolair on pin 8,9 for EASY DRIVER or other driver board

unsigned long startMillis;
unsigned long endMillis;
unsigned long currMillis;
unsigned long prevMillis;
unsigned long intervalMillis = 10; // do not change

byte maxTests = 100;
byte curTest = 1;

byte maxSteps = 100;
byte curStep = 1;

long scaleData = 0;

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(3000);
  stepper.setSpeed(3000);
  stepper.setAcceleration(800); // do not remove!
  prevMillis = millis();
}

void loop()
{
  if (curTest > maxTests)
  {
    return;
  }
  startMillis = millis();
  curStep = 0;
  testTiming();
  endMillis = millis();
  curTest ++;
  stepper.run(); // does it block the 100 steps?
}

void testTiming()
{
  while (curStep < maxSteps)   // will loop through the steps at the speed set by intervalMillis
  {   
    currMillis = millis();
    if (currMillis - prevMillis >= intervalMillis)
    {
      stepMotor();
      prevMillis += intervalMillis;
      curStep ++;
    }
  }
  // now the Scale should be ready for reading
  scaleData = (scale.read()/100);
  Serial.print("B,");
  Serial.println(scaleData);
  Serial.print("A,");
  Serial.println(stepper.currentPosition());
}

void stepMotor()
{
  stepper.moveTo(100);
}
code]
Title: Re: Steppermotor and serial.print and read combined
Post by: Robin2 on Jun 07, 2014, 12:40 am
Shouldn't you have stepper.run() inside stepMotor() and nothing else.

Stepper.run() is what actually causes the steps to happen. Because this is a demo program very little happens in loop and there is no use putting stepper.run() there.

You seem to have chosen acceleration - that may interfere with what you are trying to do, take it out for now. And be sure to set the motor speed to match the step time that you want.

...R
Title: Re: Steppermotor and serial.print and read combined
Post by: backbone on Jun 08, 2014, 02:58 pm
Quote
Shouldn't you have stepper.run() inside stepMotor() and nothing else.

stepper.runSpeed(); did the trick.
For testing purpose I just set maxTest to 100.
Motor runs and values of the force come in.

Quote
You seem to have chosen acceleration - that may interfere with what you are trying to do, take it out for now. And be sure to set the motor speed to match the step time that you want.


Acceleration line removed.

Thanks,

Paco
Title: Re: Steppermotor and serial.print and read combined(Solved)
Post by: backbone on Aug 03, 2014, 08:07 am
Hi Robin,

I could not get your solution to work with satisfaction.
So I went for a bypass.
2 x Nano
Nano1 to measure Position and Force
nano2 to control the stepper motor.
Two digital pins in between them to control the ON/OFF of the stepper motor.

Thanks for all the effort and time taken.

Paco