Jump to content
 

DCC Controlled (PECO) Turntable Project using a Arduino Uno


Recommended Posts

4 hours ago, melmerby said:

The RS one is digital, so I would use a digital one.
I've bought some of each and have experimented with them, not however for a turntable detent.

When you bring a magnet close to a linear one the output changes in sympathy with the closeness of the magnet, with a digital one it will trigger on once the magnetic strength reaches a certain level and off again as it decreases

 

AliExpress are good for components for Arduino projects.

e.g. Uno R3 clone = less than £2.

https://www.aliexpress.com/item/32556087234.html?algo_pvid=4df34ef1-5e85-4f28-a6fa-b01c264463b2&algo_expid=4df34ef1-5e85-4f28-a6fa-b01c264463b2-11&btsid=0b0a0ae216020832378767117ea997&ws_ab_test=searchweb0_0,searchweb201602_,searchweb201603_

 

I've had a few of them and Nanos and haven't had a dud yet.

Thanks!

 

I’ll be back in a few days when they arrive with the magnets and I’ve set it up..

 

I suspect I may have to do some adjusting of my sketch which I’ll post at a later time. I will need to add this check section in at the fore, but I’m using a different motor and sheild, so need to work out what’s relevant and what won’t work.

Link to post
Share on other sites

  • RMweb Premium
1 hour ago, andysollis1 said:

Thanks!

 

I’ll be back in a few days when they arrive with the magnets and I’ve set it up..

 

Not if you've ordered from AliExpress as the delivery can be slow.:)

I've had items take from 6 days to 8 weeks

If you're not in a hurry it's the place to go. If you want them quick go elsewhere, such as Rapid (UK based):

https://www.rapidonline.com/Catalogue/Search?Query=hall effect

  • Agree 1
Link to post
Share on other sites

I'm currently re-working my turntable from been mounted on top of the stepper to having a belt drive located under the table. 

 

It's made of 10mm aluminium its not the neatest but its my first every attempt at using my micro mill. 

 

There are three top hat bearings in the assembly two back to back on the main plate and a third in the support under the main gear. I'm using a 4:1 ratio. Should allow for some lovely fine indexing

IMG_20201007_123018.jpg

IMG_20201007_123026.jpg

  • Like 1
  • Craftsmanship/clever 4
Link to post
Share on other sites

  • RMweb Premium
On 07/10/2020 at 14:08, andysollis1 said:


I’m a latecomer to this, but using the arduino and Peco turn table deck.

 

id been having some issues with the control, but thanks to reading on here I now have it sorted. 
I’ve opted for push button location, but I’ve also decided to add the reset location at the start.. went to look for the Hall effect sensor, only RS do it and it’s now £14.50! 
 

now if I need to, I will buy one of those, but wondered if anyone had used anything less expensive ? Same thing different brand etc? 
 

andy 

Although I’m not using an arduino controlling the turntable, for the positioning I’m using photo interrupts (detectors). There very easy to set up, just a short length of wire, I’m using 0.8mm brass and they're not overly expensive, I paid just over £6 for 5 from Rapid Electronics. As I’m using relays I had to design an amplifier circuit, but I doubt you’d need one. 

 

The left hand board is the interrupter, the right hand the control relay. 

5F8EFF91-8663-4160-BB79-0F28274F1329.jpeg.02d10f8e48eabed347abc0dd5159bd8e.jpeg

 

The actuator pin from above. 

42A99C56-C925-46DA-B3E7-5F7346CBF93E.jpeg.bf86ad86590cc53103a8f1ce503f6832.jpeg

 

The actuator from the side. 

FD0DF557-323A-4974-A3E9-6DDDFE3CD7ED.jpeg.e999c892fdd49ce4f639dc6b1b1aa85a.jpeg

The interrupter operates when it passes the centre of the device, which in my case shuts off the relay, stopping the turntable. It’s very sensitive and stops immediately. 

 

Edited by BSW01
  • Craftsmanship/clever 1
Link to post
Share on other sites

  • RMweb Premium
8 hours ago, BSW01 said:

Although I’m not using an arguing, for the positioning I’m using photo interrupters. There very easy to set up, just a short length of wire, I’m using 0.8mm brass and not overly expensive, I paid just over £6 for 5 from Rapid Electronics. As I’m using relays I had to design an amplifier circuit, but I doubt you’d need one.

 

The interrupter operates when it passes the centre of the device, which in my case shuts off the relay, stopping the turntable. It’s very sensitive and stops immediately. 

 

Nothing wrong in using opto devices.

That's how printers do it and they have pretty good accuracy.

A faulty Epson printer I dismantled used an opto interrupter on the carriage with a strip of clear plastic with a series of bars printed on it (close together) for determining it's position.

There was also a similar arrangement with a disc with bars on it for the paper feed.

 

It may possibly be more accurate than using a Hall device.

  • Like 1
Link to post
Share on other sites

Now, I said I’d be back.. 

 

I can’t find how I paste the code/sketch in on my phone... so I apologise that it’s text below..

 

what I would like help with is what lines I need to add in for the hall detector and likely where is best to plug it in? (Pin numbers) so it does the zero check at power up..

 

so far, I’m running.....

 

/* Example sketch to control a 28BYJ-48 stepper motor with ULN2003 driver board, AccelStepper and Arduino UNO: acceleration and deceleration. Modified A.Sollis Oct 2020

// Include the AccelStepper library:
#include <AccelStepper.h>


// Motor pin definitions:
#define motorPin1  8      // IN1 on the ULN2003 driver
#define motorPin2  9      // IN2 on the ULN2003 driver
#define motorPin3  10     // IN3 on the ULN2003 driver
#define motorPin4  11     // IN4 on the ULN2003 driver

// Define the AccelStepper interface type; 4 wire motor in half step mode:
#define MotorInterfaceType 8

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper library with 28BYJ-48 stepper motor:
AccelStepper stepper = AccelStepper(MotorInterfaceType, motorPin1, motorPin3, motorPin2, motorPin4);
int Pin07Read ;  // step Road 1 (head)
int Pin06Read ;  // step Road 2 (head)
int Pin05Read ;  // step Road 3 (head)
int Pin04Read ;  // step Road 1 (tail)
int Pin03Read ;  // step Road 2 (tail)
int Pin02Read ;  // step Road 3 (tail)

void setup() {
  digitalWrite(7, HIGH);
  digitalWrite(6, HIGH);
  digitalWrite(5, HIGH);
  digitalWrite(4, HIGH);
  digitalWrite(3, HIGH);
  digitalWrite(2, HIGH);
  // Set the maximum steps per second:
  stepper.setMaxSpeed(300);
  // Set the maximum acceleration in steps per second^2:
  stepper.setAcceleration(15);
}

void loop() {
 
 // run to position with set acceleration
 stepper.runToPosition();
 

  Pin07Read = digitalRead(7) ;
  Pin06Read = digitalRead(6) ;
  Pin05Read = digitalRead(5) ;
  Pin04Read = digitalRead(4) ;
  Pin03Read = digitalRead(3) ;
  Pin02Read = digitalRead(2) ;

  //  check which button is being activated- move to that position.

 

  if (Pin07Read == LOW)
  {
    stepper.moveTo(-200);
  }
    else
  
  if (Pin06Read == LOW)
  {   
   stepper.moveTo(0);
}
else

 if (Pin05Read == LOW)
  {   
   stepper.moveTo(200);
}
else

 if (Pin04Read == LOW)
  {   
   stepper.moveTo(2000);
}
else

 if (Pin03Read == LOW)
  {   
   stepper.moveTo(1600);
}
else

 if (Pin02Read == LOW)
  {   
   stepper.moveTo(800);
}
else
{
 
  digitalWrite(8,LOW);
  digitalWrite(9,LOW);
  digitalWrite(10,LOW);
  digitalWrite(11,LOW);;
  }
   
}

 

I hope someone here can point me in the right direction to complete the project. 
 

andy

 

 

Link to post
Share on other sites

  • RMweb Premium
3 hours ago, andysollis1 said:

Now, I said I’d be back.. 

 

I can’t find how I paste the code/sketch in on my phone... so I apologise that it’s text below..

 

what I would like help with is what lines I need to add in for the hall detector and likely where is best to plug it in? (Pin numbers) so it does the zero check at power up..

 

so far, I’m running.....

 

 

 

andy

 

 

If you have a copy of the .ino file, you can just attach it to a post in the same way as pictures.

 

e.g.

Fade.ino

 

 

Edited by melmerby
  • Agree 1
Link to post
Share on other sites

8 hours ago, melmerby said:

If you have a copy of the .ino file, you can just attach it to a post in the same way as pictures.

 

e.g.

Fade.ino 1.14 kB · 2 downloads

 

 

I wish I could, unfortunately the program wants to look in iCloud, which I don’t use so could only copy and paste. Can’t log in off my computer as forgot my password. 

Link to post
Share on other sites

23 hours ago, andysollis1 said:

Now, I said I’d be back.. 

 

I can’t find how I paste the code/sketch in on my phone... so I apologise that it’s text below..

 

what I would like help with is what lines I need to add in for the hall detector and likely where is best to plug it in? (Pin numbers) so it does the zero check at power up..

 

so far, I’m running.....

 

/* Example sketch to control a 28BYJ-48 stepper motor with ULN2003 driver board, AccelStepper and Arduino UNO: acceleration and deceleration. Modified A.Sollis Oct 2020

// Include the AccelStepper library:
#include <AccelStepper.h>


// Motor pin definitions:
#define motorPin1  8      // IN1 on the ULN2003 driver
#define motorPin2  9      // IN2 on the ULN2003 driver
#define motorPin3  10     // IN3 on the ULN2003 driver
#define motorPin4  11     // IN4 on the ULN2003 driver

// Define the AccelStepper interface type; 4 wire motor in half step mode:
#define MotorInterfaceType 8

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper library with 28BYJ-48 stepper motor:
AccelStepper stepper = AccelStepper(MotorInterfaceType, motorPin1, motorPin3, motorPin2, motorPin4);
int Pin07Read ;  // step Road 1 (head)
int Pin06Read ;  // step Road 2 (head)
int Pin05Read ;  // step Road 3 (head)
int Pin04Read ;  // step Road 1 (tail)
int Pin03Read ;  // step Road 2 (tail)
int Pin02Read ;  // step Road 3 (tail)

void setup() {
  digitalWrite(7, HIGH);
  digitalWrite(6, HIGH);
  digitalWrite(5, HIGH);
  digitalWrite(4, HIGH);
  digitalWrite(3, HIGH);
  digitalWrite(2, HIGH);
  // Set the maximum steps per second:
  stepper.setMaxSpeed(300);
  // Set the maximum acceleration in steps per second^2:
  stepper.setAcceleration(15);
}

void loop() {
 
 // run to position with set acceleration
 stepper.runToPosition();
 

  Pin07Read = digitalRead(7) ;
  Pin06Read = digitalRead(6) ;
  Pin05Read = digitalRead(5) ;
  Pin04Read = digitalRead(4) ;
  Pin03Read = digitalRead(3) ;
  Pin02Read = digitalRead(2) ;

  //  check which button is being activated- move to that position.

 

  if (Pin07Read == LOW)
  {
    stepper.moveTo(-200);
  }
    else
  
  if (Pin06Read == LOW)
  {   
   stepper.moveTo(0);
}
else

 if (Pin05Read == LOW)
  {   
   stepper.moveTo(200);
}
else

 if (Pin04Read == LOW)
  {   
   stepper.moveTo(2000);
}
else

 if (Pin03Read == LOW)
  {   
   stepper.moveTo(1600);
}
else

 if (Pin02Read == LOW)
  {   
   stepper.moveTo(800);
}
else
{
 
  digitalWrite(8,LOW);
  digitalWrite(9,LOW);
  digitalWrite(10,LOW);
  digitalWrite(11,LOW);;
  }
   
}

 

I hope someone here can point me in the right direction to complete the project. 
 

andy

 

 

 

Hi Andy

Long time since i looked at this but i think you need something like this, taken from my original code on page 1.

Put it at the end of your void setup()

 

//configure pin3 as an input and enable the internal pull-up resistor

pinMode(3, INPUT_PULLUP);

//read the sensor (open collector type) value into a variable

int sensorVal = digitalRead(3);

 // if near reference point move away

sensorVal = digitalRead(3);

while (sensorVal == LOW) { sensorVal = digitalRead(3);

forwardstep2();

delay(50); }

// step forward to sensor index point

while (sensorVal == HIGH) { sensorVal = digitalRead(3);

forwardstep2();

delay(50); }

 

assumes that you connect the output of your hall sensor to pin 3

 

Ray.

  • Round of applause 1
Link to post
Share on other sites

15 hours ago, tender said:

 

Hi Andy

Long time since i looked at this but i think you need something like this, taken from my original code on page 1.

Put it at the end of your void setup()

 

//configure pin3 as an input and enable the internal pull-up resistor

pinMode(3, INPUT_PULLUP);

//read the sensor (open collector type) value into a variable

int sensorVal = digitalRead(3);

 // if near reference point move away

sensorVal = digitalRead(3);

while (sensorVal == LOW) { sensorVal = digitalRead(3);

forwardstep2();

delay(50); }

// step forward to sensor index point

while (sensorVal == HIGH) { sensorVal = digitalRead(3);

forwardstep2();

delay(50); }

 

assumes that you connect the output of your hall sensor to pin 3

 

Ray.

Hi Ray,

many thanks...

the Hall effect detectors arrived this morning so off to test.

 

Ive changed to digital pin 13? I’m already using the 3digital (and this is still new to me and working my way through understanding some code)

 

I was trying to get the screen to read back the steps last night but it either read 0 or just counted on it’s own? 
 

it doesn’t know what forwardstep2(); is... is this related to the Ada fruit? Which I’m not using?

Edited by andysollis1
Update
Link to post
Share on other sites

Ok possible daft question alert!

 

which one is pos and which is Neg? It’s like going to Rimmer Bros for the Triumph spitfire spares.. never have instructions and just expect you to know what your doing...?

077291AA-3DA5-4320-B621-9A419412B9E8.jpeg
 

ok, ignore last.. quick google turned up what I need, but just incase the next person is at my level of knowledge, here is a link..

 

https://components101.com/a3144-hall-effect-sensor

Edited by andysollis1
Update web address.
Link to post
Share on other sites

OK,

 

So I have the following Sketch , but I'm getting error messages.. (see below)

/* Example sketch to control a 28BYJ-48 stepper motor with ULN2003 driver board, AccelStepper and Arduino UNO: acceleration and deceleration. More info: https://www.makerguides.com */

// Include the AccelStepper library:
#include <AccelStepper.h>

// Motor pin definitions:
#define motorPin1  8      // IN1 on the ULN2003 driver
#define motorPin2  9      // IN2 on the ULN2003 driver
#define motorPin3  10     // IN3 on the ULN2003 driver
#define motorPin4  11     // IN4 on the ULN2003 driver

// Define the AccelStepper interface type; 4 wire motor in half step mode:
#define MotorInterfaceType 8

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper library with 28BYJ-48 stepper motor:
AccelStepper stepper = AccelStepper(MotorInterfaceType, motorPin1, motorPin3, motorPin2, motorPin4);
int Pin07Read ;  // step Road 1 (head)
int Pin06Read ;  // step Road 2 (head)
int Pin05Read ;  // step Road 3 (head)
int Pin04Read ;  // step Road 1 (tail)
int Pin03Read ;  // step Road 2 (tail)
int Pin02Read ;  // step Road 3 (tail)

void setup() {
  digitalWrite(7, HIGH);
  digitalWrite(6, HIGH);
  digitalWrite(5, HIGH);
  digitalWrite(4, HIGH);
  digitalWrite(3, HIGH);
  digitalWrite(2, HIGH);
  // Set the maximum steps per second:
  stepper.setMaxSpeed(300);
  // Set the maximum acceleration in steps per second^2:
  stepper.setAcceleration(15);

 //configure pin3 as an input and enable the internal pull-up resistor

pinMode(13, INPUT_PULLUP);

//read the sensor (open collector type) value into a variable

int sensorVal = digitalRead(13);

 // if near reference point move away

sensorVal = digitalRead(13);

while (sensorVal == LOW) { sensorVal = digitalRead(13);

forwardstep2();

delay(50); }

// step forward to sensor index point

while (sensorVal == HIGH) { sensorVal = digitalRead(3);

forwardstep2();

delay(50); } 
void loop() {
 
 // run to position with set acceleration
 stepper.runToPosition();
 

  Pin07Read = digitalRead(7) ;
  Pin06Read = digitalRead(6) ;
  Pin05Read = digitalRead(5) ;
  Pin04Read = digitalRead(4) ;
  Pin03Read = digitalRead(3) ;
  Pin02Read = digitalRead(2) ;

  //  check which button is being pressed - chooses which road is set

  if (Pin07Read == LOW)
  {
    stepper.moveTo(-200);
  }
    else
  
  if (Pin06Read == LOW)
  {   
   stepper.moveTo(0);
}
else

 if (Pin05Read == LOW)
  {   
   stepper.moveTo(200);
}
else

 if (Pin04Read == LOW)
  {   
   stepper.moveTo(2000);
}
else

 if (Pin03Read == LOW)
  {   
   stepper.moveTo(1600);
}
else

 if (Pin02Read == LOW)
  {   
   stepper.moveTo(800);
}
else
{
 
  digitalWrite(8,LOW);
  digitalWrite(9,LOW);
  digitalWrite(10,LOW);
  digitalWrite(11,LOW);;
  }
   
}

 

I'm getting the below error messages.. Any help is welcome and this is my last (apparent hurdle)

Quote

 

Arduino: 1.8.10 (Windows 7), Board: "Arduino Uno"

C:\Users\Hazel\Documents\Arduino\TT_modified_B\TT_modified_B.ino: In function 'void setup()':

TT_modified_B:50:1: error: 'forwardstep2' was not declared in this scope

 forwardstep2();

 ^~~~~~~~~~~~

TT_modified_B:58:1: error: 'forwardstep2' was not declared in this scope

 forwardstep2();

 ^~~~~~~~~~~~

TT_modified_B:61:13: error: a function-definition is not allowed here before '{' token

 void loop() {

             ^

TT_modified_B:119:1: error: expected '}' at end of input

 }

 ^

Multiple libraries were found for "AccelStepper.h"
 Used: C:\Users\Hazel\Documents\Arduino\libraries\AccelStepper
exit status 1

 


'forwardstep2' was not declared in this scope

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

 

 

??help  ? I'm sure the { } issue is simple, but im not sure where the "forwardstep2" bit is wrong or how to enable ? and whats the multiple libraries ? its never thrown this up before.. I'm really not seeing the wood for the trees.

 

Andy

Edited by andysollis1
edit
Link to post
Share on other sites

20 hours ago, tender said:

I think you're missing the stepper.h library

 

Have a look here for an example

https://www.makerguides.com/28byj-48-stepper-motor-arduino-tutorial/

 

You will need to change the forwardstep2() commands to those used in the library.

Look at the example on the maker guides website.

Ray.

 

 

Well, I've finally got no errors and got it on to the Uno. Didn't need stepper.h library as using the accelerator one.

 

But.. It only turns one way and stops, regardless of if I trip the sensor, it doesn't go the other way. it simply runs to the end. The "L" light goes out on the Uno board.

Am I missing some more code re the "Input_pullup"?  so it still doesn't know the location of Zero ?

 

 The push buttons don't work until I trip the sensor with the magnet.

 

Andy

 

/* Example sketch to control a 28BYJ-48 stepper motor with ULN2003 driver board, AccelStepper and Arduino UNO: acceleration and deceleration. More info: https://www.makerguides.com */

// Include the AccelStepper library:
#include <AccelStepper.h>


// Motor pin definitions:
#define motorPin1  8      // IN1 on the ULN2003 driver
#define motorPin2  9      // IN2 on the ULN2003 driver
#define motorPin3  10     // IN3 on the ULN2003 driver
#define motorPin4  11     // IN4 on the ULN2003 driver

// Define the AccelStepper interface type; 4 wire motor in half step mode:
#define MotorInterfaceType 8

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper library with 28BYJ-48 stepper motor:
AccelStepper stepper = AccelStepper(MotorInterfaceType, motorPin1, motorPin3, motorPin2, motorPin4);
int Pin07Read ;  // step Road 1 (head)
int Pin06Read ;  // step Road 2 (head)
int Pin05Read ;  // step Road 3 (head)
int Pin04Read ;  // step Road 1 (tail)
int Pin03Read ;  // step Road 2 (tail)
int Pin02Read ;  // step Road 3 (tail)

void setup() {
  digitalWrite(7, HIGH);
  digitalWrite(6, HIGH);
  digitalWrite(5, HIGH);
  digitalWrite(4, HIGH);
  digitalWrite(3, HIGH);
  digitalWrite(2, HIGH);
  // Set the maximum steps per second:
  stepper.setMaxSpeed(300);
  // Set the maximum acceleration in steps per second^2:
  stepper.setAcceleration(15);
 //configure pin3 as an input and enable the internal pull-up resistor

pinMode(13, INPUT_PULLUP);

//read the sensor (open collector type) value into a variable

int sensorVal = digitalRead(13);

 // if near reference point move away

sensorVal = digitalRead(13);

while (sensorVal == LOW) { sensorVal = digitalRead(13);
stepper.moveTo(3400);

delay(50); }

// step forward to sensor index point

while (sensorVal == HIGH) { sensorVal = digitalRead(13);
stepper.moveTo(-3400);

delay(50);}
  
}

void loop() {
 
 // run to position with set acceleration
 stepper.runToPosition();
 

  Pin07Read = digitalRead(7) ;
  Pin06Read = digitalRead(6) ;
  Pin05Read = digitalRead(5) ;
  Pin04Read = digitalRead(4) ;
  Pin03Read = digitalRead(3) ;
  Pin02Read = digitalRead(2) ;

  //  check which button is being pressed - chooses which road is set

  if (Pin07Read == LOW)
  {
    stepper.moveTo(-200);
  }
    else
  
  if (Pin06Read == LOW)
  {   
   stepper.moveTo(0);
}
else

 if (Pin05Read == LOW)
  {   
   stepper.moveTo(200);
}
else

 if (Pin04Read == LOW)
  {   
   stepper.moveTo(2000);
}
else

 if (Pin03Read == LOW)
  {   
   stepper.moveTo(1600);
}
else

 if (Pin02Read == LOW)
  {   
   stepper.moveTo(800);
}
else
{
 
  digitalWrite(8,LOW);
  digitalWrite(9,LOW);
  digitalWrite(10,LOW);
  digitalWrite(11,LOW);;
  }
   
}

 

Edited by andysollis1
Correct spelling
Link to post
Share on other sites

On 29/01/2015 at 21:10, luce001 said:

Firstly I would like to thank Ray for his hard work in starting off this excellent post! also for Eric and friends for the various coding updates..  I have made a few changes to the code and managed to get a working turntable on my layout, including an OLED display to show the position and head/tail indication.  I only have 4 positions on my turntable and I didn't use the servo brake or manual pot but left these functions in.

 

The display I used was a 1.3" I2C IIC Serial 128X64 OLED LCD LED Display Module Digital for Arduino W which can be obtained easily on eBay... the driver for this is U8glib.h https://code.google.com/p/u8glib/ and the other components as mentioned by others I ordered from Proto-pic.

 

The revised coding is as follows, pictures to follow...

 

Jonathan


////////////////////////////////////////////////////////////////////////////////
//
//   DCC Turntable Rev 17 9 Jan 2015
//   based on code from rmweb.co.uk forum - edited by J.Luce
//   Program functions:
//     "Real World" interface
//     2- N.O. Push buttons to enable move to "Head" or "Tail"
//     1- 10k Continuous turn POT to select track.
//     1- N.O. Reset button on fascia
//     Use digital inputs on 6 & 7 to stepforward and backward and 
//       read out in the serial monitor so that you can program easier.
//     Release & Servo Brake function works with brake and release function.
//     Route positioning not taking shortest route to next location- (i.e. Tk.1 to Tk. 10 would be through 0)
//     Always approaches a track from the same direction to account for gear/mechanical lash/slop.
//       if the table was going CW to pos. 1 it approaches value B and stops
//       if the table was going CCW to Pos 1 it should go past B a (value B-X) and then go CW to B.
//     Added a (commented out)set up tool in the "loop" section of the code to set up the POT on the fascia panel.
//       this let's you align the POT to the markings on the panel.  Uncomment to use, then re-comment to hide.
//     Set up tool in the "loop" section of the code to set up the Brake Servo using the POT on the fascia panel. 
//       this let's you find the optimal Release and Brake position for the servo brake.  Uncomment to use, then re-comment to hide.
//     Added u8g display to show track position and heading, initialise at startup
//     Move to track 0 "Head" at startup
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
//
// DCC Turntable Control Routines

#include <DCC_Decoder.h>
#include <AccelStepper.h>
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"
#include <Servo.h>            //servo library reference
#include "U8glib.h"

// setup u8g object, please remove comment from one of the following constructor calls
// IMPORTANT NOTE: The following list is incomplete. The complete list of supported 
// devices with all constructor calls is here: http://code.google.com/p/u8glib/wiki/device

U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_DEV_0|U8G_I2C_OPT_FAST);	// Dev 0, Fast I2C / TWI

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Defines and structures
//
#define kDCC_INTERRUPT            0

typedef struct
{
    int               address;                // Address to respond to
   
} DCCAccessoryAddress;

DCCAccessoryAddress gAddresses[5];          // Allows 4 dcc addresses: [XX] = number of addresses you need (including 0).

const unsigned long releaseTimeout_ms = 2000;      //reduced to 2 seconds for now    
const long MOTOR_STEP_COUNT = 200 * 16;	            //number of steps for a full rotation
       
//new stuff
boolean tableTargetHead = false;        //the new variable for Head/Tail Position either from DCC or Analog
int tableTargetPosition = 0;            //the new variable for Table Postition either from DCC or Analog
boolean newTargetLocation = false;
boolean buttonPushedHead = false;
boolean buttonPushedTail = false;
boolean inMotionToNewTarget = false;
boolean isReleased = false;		// isReleased tries to make sure the motor is not continuously released
unsigned long stepperLastMoveTime = 0;
const long MOTOR_OVERSHOOT = 10;        // the amount of overshoot/ lash correction when approaching from CCW
int overshootDestination = -1;

//Servo Stuff
Servo brakeservo;  // create servo object to control a servo
const int servoBrake = 9;  //value for brake position
const int servoRelease = 2;  //value for release position

//Programming button variables
boolean programmingMode = false;
boolean programmingModeMoveForward = true;	//If in programming mode, are we moving forward?  
unsigned long programmingLastMoveMillis = 0;	//When was the last programming move done?
const int programRotateDelay = 100;			//Delay between steps in ms while holding button

//location variables
const int A = 144;          //TT Track 0-  Head
const int B = 328;          //TT Track 1-  Head
const int C = 482;          //TT Track 2-  Head
const int D = 632;          //TT Track 3-  Head
const int N = 1745;         //TT Track 0-  Tail
const int O = 1928;         //TT Track 1-  Tail
const int P = 2080;         //TT Track 2-  Tail
const int Q = 2230;         //TT Track 3-  Tail

const int PositionTrackHead[] = { A, B, C, D };
const int PositionTrackTail[] = { N, O, P, Q };

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Adafruit Setup

Adafruit_MotorShield AFMStop(0x60); // Default address, no jumpers

// Connect stepper with 200 steps per revolution (1.8 degree)
// to the M3, M4 terminals (blue,yellow,green,red)

Adafruit_StepperMotor *myStepper2 = AFMStop.getStepper(200, 2);

// you can change these to SINGLE, DOUBLE, INTERLEAVE or MICROSTEP!

// wrapper for the motor! (3200 Microsteps/revolution)
void forwardstep2() {  
  myStepper2->onestep(BACKWARD, MICROSTEP);
}
void backwardstep2() {  
  myStepper2->onestep(FORWARD, MICROSTEP);
}
void release2()   {
  myStepper2->release();
}

// Now we'll wrap the stepper in an AccelStepper object  

AccelStepper stepper2 = AccelStepper(forwardstep2, backwardstep2);

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Decoder Initiation 
//
void ConfigureDecoder()
{                                    //Put all the decoder #'s you need here.  Remember to change
                                     //DCCAccessoryAddress gAddresses[XX];(above) where XX = number of addresses you need. 
    gAddresses[0].address = 200;      
    gAddresses[1].address = 201;      
    gAddresses[2].address = 202;
    gAddresses[3].address = 203;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Basic accessory packet handler 
//

void BasicAccDecoderPacket_Handler(int address, boolean activate, byte data)
{
        // Convert NMRA packet address format to human address
    address -= 1;
    address *= 4;
    address += 1;
    address += (data & 0x06) >> 1;
    
    boolean enable = (data & 0x01) ? 1 : 0;
    
    for(int i=0; i<(int)(sizeof(gAddresses)/sizeof(gAddresses[0])); i++)
    {
        if( address == gAddresses[i].address )
        { 
 
            Serial.println("");  
            Serial.print("DCC addr: ");
            Serial.print(address,DEC);
            Serial.print("   Head/Tail = (1/0) : ");
            Serial.println(enable,DEC);
                                  
			//new stuff
                        tableTargetHead = enable;
                        tableTargetPosition = i;

                        //picture loop
                        u8g.firstPage();  
                        do {
                          draw(tableTargetPosition, tableTargetHead);
                        } while( u8g.nextPage() ); 

			//New packet and we have a new target location, set the flag
			newTargetLocation = true;
                        doStepperMove();   
			
  			// old location for if/else statements
		}
	}
}

/////////////////////////////////////////////////////////////////////////////
//
//  draw ug8 display
//  

void draw(int address, boolean enable) {
  // graphic commands to redraw the complete screen should be placed here  
  u8g.setFont(u8g_font_unifont);
  u8g.setPrintPos(20, 25);
  u8g.print("Position ");
  u8g.print(address,DEC);
  u8g.setPrintPos(20, 45); 
  if (enable)
  { 
    u8g.print("Head");
  }
  else
  {
    u8g.print("Tail");
  }
  u8g.drawRFrame(0,0,128,64,8);
}
      
/////////////////////////////////////////////////////////////////////////////
//
//  readAnalogLocation() Reads the pot input on analog pin 1, displays some
//  information out the serial, and sets the target position variable
//

int readAnalogLocation()
{
	int potDisp = analogRead(1);
	int potOut = potDisp / 79; //1023 / 13

	Serial.println("");
        Serial.print("Analog Location: ");
	Serial.print("Track # ");
	Serial.print(potOut, DEC);
	Serial.print("   Head/Tail = (1/0) : ");
	Serial.println(tableTargetHead, DEC);

	//tableTargetPosition = potOut;
	return potOut;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Subroutine: doStepperMove()
//	 Moves the stepper based on location inputs, calls up "SetStepperTargetLocation()"
//
///////////////////////////////////////

void doStepperMove()
{

        // Run the Stepper Motor //
        stepper2.run();

	boolean isInMotion = (abs(stepper2.distanceToGo()) > 0);
	boolean newTargetSet = false;

	// If there is a new target location, set the target
	if (newTargetLocation)
	{
		Serial.println("Moving to New Target Location...");
		SetStepperTargetLocation();
		newTargetSet = true;
	}

	if (inMotionToNewTarget)
	{
		if ((!isInMotion) && (!newTargetSet))
		{
			Serial.print("Not Moving!  DtG: ");
			Serial.print(stepper2.distanceToGo());
			Serial.print(" TP: ");
			Serial.print(stepper2.targetPosition());
			Serial.print(" CP: ");
			Serial.print(stepper2.currentPosition());
			Serial.print(" S: ");
			Serial.print(stepper2.speed());
			Serial.println();
		}
				//release the brake
                                brakeservo.write(servoRelease);
                                delay (5);  
		inMotionToNewTarget = isInMotion;
	}
	else
	{
		if (programmingMode)
		{
			//If we are programming, do that move
				//release the brake
                                brakeservo.write(servoRelease);
                                delay (5);  
        
                        if ((millis() - programmingLastMoveMillis) >= programRotateDelay)
			{
				programmingLastMoveMillis = millis();
				stepper2.move(programmingModeMoveForward ? 1 : -1);
                                
                                Serial.println("");
				Serial.print("Programming mode, Current location: ");
				Serial.println(stepper2.currentPosition());
		                int potDisp = analogRead(1);
		                int potOut = potDisp / 79; //1023 / 13
		                Serial.print("Analog Location: ");
                                Serial.print("Track # ");
		                Serial.println(potOut, DEC);
		                delay(45);
			}
		}
		if ((stepper2.currentPosition() % MOTOR_STEP_COUNT) == 0)
		{
    		        //setCurrentPosition seems to always reset the position to 0, ignoring the parameter
			Serial.print("Current location: ");
			Serial.print(stepper2.currentPosition());
			Serial.println(" % STEPCOUNT.  Why here?");
		}
	}
                      //stepper timer subroutine came from here.
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Subroutine: SetStepperTargetLocation()
//     Takes the global variables: tableTargetHeadOrTail, and tableTargetPosition, and sets the stepper2
//   object moveTo() target position in steps-  inserts values back into "doStepperMove()"
//
///////////////////////////////////////

void SetStepperTargetLocation()
{
    int newTargetLoc = -1;
    if (tableTargetHead)
    {    //use head location variable
        {
            newTargetLoc = PositionTrackHead[tableTargetPosition];
            inMotionToNewTarget = true;
        }
    }
    else
    {    //use tail location variable
        {
            newTargetLoc = PositionTrackTail[tableTargetPosition];
            inMotionToNewTarget = true;
        }
    }

    if (newTargetLoc > 0)
    {
        int currentLoc = stepper2.currentPosition();
        int mainDiff = newTargetLoc - currentLoc;
        if (mainDiff > (MOTOR_STEP_COUNT / 2))
        {
            mainDiff = mainDiff - MOTOR_STEP_COUNT;
        }
        else if (mainDiff < (-MOTOR_STEP_COUNT / 2))
        {
            mainDiff = mainDiff + MOTOR_STEP_COUNT;
        }

        if (mainDiff < 0)
        {
            mainDiff -= MOTOR_OVERSHOOT;
            overshootDestination = MOTOR_OVERSHOOT;
        }
        stepper2.move(mainDiff);
    }
    programmingMode = false;
    newTargetLocation = false;
  }
 
//////////////////////////////////////////////////////////////////////////////////////////////////
//
//  Stepper Timer sub routine this runs from the main loop. It also supports the release function.
//
//////////////////////////////////////////////////////////////////////////////////////////////////

void stepperTimer()
{
    // Run the Stepper Motor //
    stepper2.run();
       
    boolean isInMotion = (abs(stepper2.distanceToGo()) > 0);
    //Check if we have any distance to move for release() timeout.  Can check the
    // buffered var isInMotion because we also check the other variables.
    if (isInMotion || programmingMode )
    {
        //We still have some distance to move, so reset the release timeout
        stepperLastMoveTime = millis();
        isReleased = false;
    }
    else
    {
        if (!isReleased)
        {
            if (overshootDestination > 0)
            {
                stepper2.move(overshootDestination);
                overshootDestination = -1;
            }
            if (((millis() - stepperLastMoveTime) >= releaseTimeout_ms))
            {
                //If isReleased, don't release again.
                isReleased = true;
                Serial.print ("Relative Current Position: ");
                Serial.print(stepper2.currentPosition());    //shows position the table thinks it is at (how it got here)

                int currentLoc = stepper2.currentPosition();    // Resets the positon to the actual positive number it should be
                currentLoc = currentLoc % MOTOR_STEP_COUNT;
                if (currentLoc < 0)
                {
                    currentLoc += MOTOR_STEP_COUNT;
                }
                stepper2.setCurrentPosition(currentLoc);
                stepper2.moveTo(currentLoc);
                
                Serial.print ("    Actual Current Position: ");
                Serial.println(stepper2.currentPosition());    // shows the position value corrected.

                //Set the servo brake
                brakeservo.write(servoBrake);
                delay(750);

                //release the motor
                release2();
                Serial.println("    Brake Set & Motor Released ");
            }
        }
    }
}

///////////////////////////////////////////////////////
//
//  Check Programming Buttons-  look for either of the programming buttons being pushed
//

void checkProgrammingButtons()
{
	programmingMode = false;
	bool buttonPushedProgUp = (digitalRead(6) == LOW);
	bool buttonPushedProgDown = (digitalRead(7) == LOW);

	//If one button is pushed, but not both
	if ((buttonPushedProgDown || buttonPushedProgUp) && !(buttonPushedProgDown && buttonPushedProgUp))
	{
		programmingMode = true;
		programmingModeMoveForward = buttonPushedProgUp;
	    doStepperMove();
        }
}

///////////////////////////////////////////////////////////////
// Manual move to using the pushbuttons and POT
//

void checkManualButtons()
{
	//Read the Head button input
	if (digitalRead(4) == LOW)
	{
		buttonPushedHead = true;
	}
	else if (buttonPushedHead)
	{
		//Button was pushed, but is not being pushed now
		//Clear pushed variable
		buttonPushedHead = false;
		//Set the target head variable
		tableTargetHead = true;
		//Read the analog location
		tableTargetPosition = readAnalogLocation();

		//Then set the new target flag
		newTargetLocation = true;
          doStepperMove();
	}

	//Read the Tail button input
	if (digitalRead(5) == LOW)
	{
		buttonPushedTail = true;
	}
	else if (buttonPushedTail)
	{
		//Button was pushed, but is not being pushed now
		//Clear pushed variable
		buttonPushedTail = false;
		//Set the target head variable
		tableTargetHead = false;
		//Read the analog location
		tableTargetPosition = readAnalogLocation();

		//Then set the new target flag
		newTargetLocation = true;
          doStepperMove();  
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
// Setup
//

void setup()
{
	Serial.begin(9600);

	AFMStop.begin(); // Start the shield

        //servo brake release before stepp moves
        brakeservo.attach(10);  // attaches the servo on pin 10 to the servo object
        brakeservo.write(servoRelease);
        delay (30);

        //initial display
        tableTargetHead = true;
        tableTargetPosition = 0;

        u8g.firstPage();  
        do {
        draw(tableTargetPosition, tableTargetHead);
        } while( u8g.nextPage() ); 

	//configure pin3 as an input and enable the internal pull-up resistor
	pinMode(3, INPUT_PULLUP);		//Hall Effect sensor: to reset position on startup
	//configure pin4 as an input and enable the internal pull-up resistor
	pinMode(4, INPUT_PULLUP);		//Head button
	//configure pin5 as an input and enable the internal pull-up resistor
	pinMode(5, INPUT_PULLUP);		//Tail button
	//configure pin6 as an input and enable the internal pull-up resistor
	pinMode(6, INPUT_PULLUP);		//Programming: Move forward single step
	//configure pin7 as an input and enable the internal pull-up resistor
	pinMode(7, INPUT_PULLUP);		//Programming: Move reverse single step

	//read the sensoron Dig I/O #3 (open collector type- Hall Effect sensor) value into a variable
	int sensorVal = digitalRead(3);

	//set stepper motor speed and acceleration 
	stepper2.setMaxSpeed(80.0);
	stepper2.setAcceleration(10.0);

	// if near reference point move away
	while (sensorVal == LOW) {
		sensorVal = digitalRead(3);
		forwardstep2();
		delay(25);
		Serial.println("Stepper Home");
	}

	// step backward to sensor index point
	while (sensorVal == HIGH) {
		sensorVal = digitalRead(3);
		backwardstep2();
		delay(50);
	}

        //when home- sets brake
        delay (500);
        brakeservo.write(servoBrake);

       //initial track position 0 head
       newTargetLocation = true;
       doStepperMove();   

       
   DCC.SetBasicAccessoryDecoderPacketHandler(BasicAccDecoderPacket_Handler, true);
   ConfigureDecoder();
   DCC.SetupDecoder( 0x00, 0x00, kDCC_INTERRUPT );
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Main loop
//

void loop()
{
   static int addr = 0;
    
        ////////////////////////////////////////////////////////////////
        // Loop DCC library

    DCC.loop();

        ////////////////////////////////////////////////////////////////
        // Bump to next address to test
    if( ++addr >= (int)(sizeof(gAddresses)/sizeof(gAddresses[0])) )
    {
        addr = 0;
    }

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//  To configure the POT (uncomment this text)
	//configure alalog pin 1 as an input
	
        //  int potDisp = analogRead(1);
	// 
	//  int potOut = potDisp / 79; //1023 / 13
	//     delay(1000);  
	//     Serial.print("Analog Location: ");
	//     Serial.println(potOut);
	
        // end of POT configuration- re-comment this section to hide during normal use
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//  To configure the Servo Brake (uncomment this text) 
	//configure alalog pin 1 as an input
	
        //    int potDisp = analogRead(1);            // reads the value of the potentiometer (value between 0 and 1023)
        //    int potOut = map(potDisp, 0, 1023, 0, 50);     // scale it to use it with the servo (value between 0 and 180)
        //    brakeservo.write(potOut);                  // sets the servo position according to the scaled value
        //    delay(1000); 
	//    Serial.print("Servo Position Value: ");
	//    Serial.println(potOut);
        
	// end of POT configuration- re-comment this section to hide during normal use
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	//Tests to see if the manual move buttons are pressed, if so set the needed flags
          checkManualButtons();

	//Checks the programming buttons, if depressed then set the right flags
          checkProgrammingButtons();

	//StepperAccel.Run() in this function
          stepperTimer();

}

 

Good Evening, i am wanting to use this code, i have replaced my adafruit shield with a 'all in one' shield with the dcc decoder built in. it has a A4988 driver installed.

 

Can Anyone advise how i can modify the code to work with the A4988 driver rather than the adafruit sheild, i realise the servo stuff will need to be changed but i can do that, i'm just struggling to get my head around the stepper side of the coding as the attached code uses both the adafruit and accelstepper libaries.

 

my stepper is currently setup as AccelStepper stepper1(1, 5, 4); on the example code from dccinterfaces.

 

i'm running a 5:1 reduction from the stepper. (16t to 80t)

 

 

IMG_20201011_210844.jpg

  • Like 2
Link to post
Share on other sites

On 10/10/2020 at 20:44, andysollis1 said:

Well, I've finally got no errors and got it on to the Uno. Didn't need stepper.h library as using the accelerator one.

 

But.. It only turns one way and stops, regardless of if I trip the sensor, it doesn't go the other way. it simply runs to the end. The "L" light goes out on the Uno board.

Am I missing some more code re the "Input_pullup"?  so it still doesn't know the location of Zero ?

 

 The push buttons don't work until I trip the sensor with the magnet.

 

Andy

 



/* Example sketch to control a 28BYJ-48 stepper motor with ULN2003 driver board, AccelStepper and Arduino UNO: acceleration and deceleration. More info: https://www.makerguides.com */

// Include the AccelStepper library:
#include <AccelStepper.h>


// Motor pin definitions:
#define motorPin1  8      // IN1 on the ULN2003 driver
#define motorPin2  9      // IN2 on the ULN2003 driver
#define motorPin3  10     // IN3 on the ULN2003 driver
#define motorPin4  11     // IN4 on the ULN2003 driver

// Define the AccelStepper interface type; 4 wire motor in half step mode:
#define MotorInterfaceType 8

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper library with 28BYJ-48 stepper motor:
AccelStepper stepper = AccelStepper(MotorInterfaceType, motorPin1, motorPin3, motorPin2, motorPin4);
int Pin07Read ;  // step Road 1 (head)
int Pin06Read ;  // step Road 2 (head)
int Pin05Read ;  // step Road 3 (head)
int Pin04Read ;  // step Road 1 (tail)
int Pin03Read ;  // step Road 2 (tail)
int Pin02Read ;  // step Road 3 (tail)

void setup() {
  digitalWrite(7, HIGH);
  digitalWrite(6, HIGH);
  digitalWrite(5, HIGH);
  digitalWrite(4, HIGH);
  digitalWrite(3, HIGH);
  digitalWrite(2, HIGH);
  // Set the maximum steps per second:
  stepper.setMaxSpeed(300);
  // Set the maximum acceleration in steps per second^2:
  stepper.setAcceleration(15);
 //configure pin3 as an input and enable the internal pull-up resistor

pinMode(13, INPUT_PULLUP);

//read the sensor (open collector type) value into a variable

int sensorVal = digitalRead(13);

 // if near reference point move away

sensorVal = digitalRead(13);

while (sensorVal == LOW) { sensorVal = digitalRead(13);
stepper.moveTo(3400);

delay(50); }

// step forward to sensor index point

while (sensorVal == HIGH) { sensorVal = digitalRead(13);
stepper.moveTo(-3400);

delay(50);}
  
}

void loop() {
 
 // run to position with set acceleration
 stepper.runToPosition();
 

  Pin07Read = digitalRead(7) ;
  Pin06Read = digitalRead(6) ;
  Pin05Read = digitalRead(5) ;
  Pin04Read = digitalRead(4) ;
  Pin03Read = digitalRead(3) ;
  Pin02Read = digitalRead(2) ;

  //  check which button is being pressed - chooses which road is set

  if (Pin07Read == LOW)
  {
    stepper.moveTo(-200);
  }
    else
  
  if (Pin06Read == LOW)
  {   
   stepper.moveTo(0);
}
else

 if (Pin05Read == LOW)
  {   
   stepper.moveTo(200);
}
else

 if (Pin04Read == LOW)
  {   
   stepper.moveTo(2000);
}
else

 if (Pin03Read == LOW)
  {   
   stepper.moveTo(1600);
}
else

 if (Pin02Read == LOW)
  {   
   stepper.moveTo(800);
}
else
{
 
  digitalWrite(8,LOW);
  digitalWrite(9,LOW);
  digitalWrite(10,LOW);
  digitalWrite(11,LOW);;
  }
   
}

 

 

I think you need to change the stepper.moveTo(-3400) statements in the sensor routine to one that just moves the motor one step. As it stands the stepper.moveTo(-3400) in the while statement is just moving the motor to absolute position -3400 before it rechecks the status of the sensor.

Try:

stepper.moveTo(stepper.currentPosition()+1);

Ray.

Edited by tender
  • Like 1
  • Friendly/supportive 1
Link to post
Share on other sites

6 hours ago, tender said:

 

I think you need to change the stepper.moveTo(-3400) statements in the sensor routine to one that just moves the motor one step. As it stands the stepper.moveTo(-3400) in the while statement is just moving the motor to absolute position -3400 before it rechecks the status of the sensor.

Try:

stepper.moveTo(stepper.currentPosition()+1);

Ray.

Hello Ray,

 

I am in debt for your time and help, but alas, it still doesn’t do anything. 
Now it sits until I trigger the sensor with the magnet and it flashes the sheild to say it’s moving once and stops.  I am (always have been) at a loss how to make it increment by one step. I thought you had got it with the +1 in brackets but sadly, it doesn’t want to budge. 
 

Have I maybe got something in the wrong order? I even removed the code at the end that turns off the stepper sheild with no joy?

 

andy

 

Link to post
Share on other sites

Ah! At last - Little bit of fudging Ive got the code to check for the sensor and back up. Yae!!!

 

But, its not resetting the zero, So I guess I'm still missing something on the Input_Pullup entry ? as I cant see it does anything further.

 

Here is the working code that does everything but the reset now... Any suggestions ?

 

I'm actually quite pleased now. Hopefully I can post a video soon.

 

Andy

 

/* Example sketch to control a 28BYJ-48 stepper motor with ULN2003 driver board, AccelStepper and Arduino UNO: acceleration and deceleration. More info: https://www.makerguides.com */

// Include the AccelStepper library:
#include <AccelStepper.h>
#include <Wire.h> 

// Motor pin definitions:
#define motorPin1  8      // IN1 on the ULN2003 driver
#define motorPin2  9      // IN2 on the ULN2003 driver
#define motorPin3  10     // IN3 on the ULN2003 driver
#define motorPin4  11     // IN4 on the ULN2003 driver

// Define the AccelStepper interface type; 4 wire motor in half step mode:
#define MotorInterfaceType 8

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper library with 28BYJ-48 stepper motor:
AccelStepper stepper = AccelStepper(MotorInterfaceType, motorPin1, motorPin3, motorPin2, motorPin4);
int Pin07Read ;  // step Road 1 (head)
int Pin06Read ;  // step Road 2 (head)
int Pin05Read ;  // step Road 3 (head)
int Pin04Read ;  // step Road 1 (tail)
int Pin03Read ;  // step Road 2 (tail)
int Pin02Read ;  // step Road 3 (tail)

void setup() {
  digitalWrite(7, HIGH);
  digitalWrite(6, HIGH);
  digitalWrite(5, HIGH);
  digitalWrite(4, HIGH);
  digitalWrite(3, HIGH);
  digitalWrite(2, HIGH);
 
  // Set the maximum steps per second:
  stepper.setMaxSpeed(300);
  // Set the maximum acceleration in steps per second^2:
  stepper.setAcceleration(15);
 
 //configure pin13 as an input and enable the internal pull-up resistor
pinMode(13, INPUT_PULLUP);

//read the sensor (open collector type) value into a variable

int sensorVal = digitalRead(13);

 // if near reference point move away

sensorVal = digitalRead(13);

while (sensorVal == HIGH) { sensorVal = digitalRead(13);
stepper.moveTo(stepper.currentPosition()+10);
stepper.runSpeedToPosition();

delay(50); }

// step forward to sensor index point

while (sensorVal == LOW) { sensorVal = digitalRead(13);
stepper.moveTo(stepper.currentPosition()-10);
stepper.runSpeedToPosition();

delay(50);}
  
}

void loop() {
 
 // run to position with set acceleration
 stepper.runToPosition();
 

  Pin07Read = digitalRead(7) ;
  Pin06Read = digitalRead(6) ;
  Pin05Read = digitalRead(5) ;
  Pin04Read = digitalRead(4) ;
  Pin03Read = digitalRead(3) ;
  Pin02Read = digitalRead(2) ;

  //  check which button is being pressed - chooses which road is set

  if (Pin07Read == LOW)
  {
    stepper.moveTo(-200);
  }
    else
  
  if (Pin06Read == LOW)
  {   
   stepper.moveTo(0);
}
else

 if (Pin05Read == LOW)
  {   
   stepper.moveTo(200);
}
else

 if (Pin04Read == LOW)
  {   
   stepper.moveTo(800);
}
else

 if (Pin03Read == LOW)
  {   
   stepper.moveTo(1600);
}
else

 if (Pin02Read == LOW)
  {   
   stepper.moveTo(2000);
}
else
{
 
  digitalWrite(8,LOW);
  digitalWrite(9,LOW);
  digitalWrite(10,LOW);
  digitalWrite(11,LOW);;
  }
   
}

 

Link to post
Share on other sites

Well, after a quick google for a similar issue, I have found the one line I was missing... simple really!

 

 stepper.setCurrentPosition(0);

 

doh!

 

ok, so next move is to transfer from the dummy set up Solder the wires for the preset switch box and move it to the Peco turn table.

 

once done I can then adjust my figures to match the entry:exit points on the turntable.

 

thanks to Ray for his help earlier in the week.

I’ll post a video soon!

 

andy 

  • Like 1
Link to post
Share on other sites

5 hours ago, tender said:

Well done Andy.

I was going to suggest the stepper.setCurrentPosition(0); command but you already sorted it before i got back to you.

 

Ray.


 

thanks. I kept puzzling over the original Sketch and couldn’t find what was missing. I did a google for something similar and tried it and it worked.

 

it was more a case for me of knowing what command I needed, but knowing what the specific wording was that i needed. I’m hoping to go an fit it soon, but Nottinghamshire has now had its amber light re covid, so not sure I can go to my Dads... although, the layout is in the shed in the garden, so I may be able to get away with it.

 

I’ll keep you informed on progress.

 

thanks again Ray, your topic has been a great inspiration - I’m still reading the earlier posts and only on page 11!!!

 

Andy

Link to post
Share on other sites

Gents,

I’m not getting a result I expect and would like to ask for some further help.

so when the turntable is in place and on the layout I can work out the final figures to align the tracks to I have used the following to show on the serial monitor.:

 

Serial.print(“Position: “);

Serial.print(stepper.currentPosition());

 

but this only updates when it stops?

 

anyone know a change to show it as it increments and decreases live? (Is it possible?)

 

Andy

 

Link to post
Share on other sites

Hello again...

 

Ive finally caught up on the previous 27 pages of the topic..

 

now a few years back someone mentioned re adding in a line to the sketch re “Backlash”.... as I’m still learning on the programming side, how do I set this up? I think I can follow how to add it in later in the loop, but I’ve not really understood the setup phase? Would it be something like stepper == backlash ? 
 

I think if I can master this bit it will really put the cream on the cake for my very basic (and cheap) set up non DCC using the 28BJY-48 stepper with the ULN2003 sheild. 
Andy 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...