Jump to content
 

Arduino Applications and Programs


Simond
 Share

Recommended Posts

Hi to one and all.

 

over the last 5 or 6 months that I have been involved in RMWeb, there have been many productive and interesting discussions about Arduinos and their applications, including stepper motor driven traversers and turntables, and signal / point control.

 

I promised to post some sketches (otherwise known as programs, source code, etc.,) and rather than have it in different threads, I thought I would start a new topic, and add pointers to the threads where relevant.  I hope this makes sense, and doesnt cause the Mods a brownout.

 

I firstly bought a Raspberry Pi when they first came out - I have had very little success with this, probably due to a lack of finding the right examples and bits of source code to copy from.  Also, Linux is to me, at least, a bit of a black art, and my earlier programming experience was in Algol 68 (yes, I said "earlier"), Fortran and Basic.  The Arduino is programmed in C, which is pretty much like Basic, without the line numbers, and many examples are included in the IDE which you can download here ;-

 

http://arduino.cc/en/Main/Software

 

The Arduino website has a full language and syntax reference, plus links to various forums (fora?) in which help seems to be readily available.

 

http://arduino.cc/en/Reference/HomePage

 

I have no connection to any of the traders or sites mentioned.  The code I have posted is available to download on an "as is" basis with no warranty of any sort, and is free to use for non-profit - please do credit me (or any other contributors) where applicable.  IF you are planning to incorporate it in something you plan to sell, please PM me and we can discuss crossing my palms with gold... :)

 

first instalment to follow very shortly...

best

SD

 

 

 

Link to post
Share on other sites

Following Andy's adjustments to the uploading permissions, I have attached the sketch, rather than embedded it in the body of the post.
 

Servo control v4 is a very simple program to operate three servos from three single pole on-off (or change over) switches.  In order to use the sketch, you need to download it into a directory whose name is the same as the sketch.  You can then open it in the Arduino proigram and upload to the Arduino itself.

 

In order to use this sketch, you will need to adjust the end positions of the servos. The sketch for doing this will be attached to the next post.


best
SD


bracket_signal_v4.ino

Edited by Simond
Link to post
Share on other sites

In the original of this post, I referred to an error in the servo program - fixed it in the attachment above.

 

This post has also been edited to take the program out of the body of the thread and attach it.

 

Now, as I said earlier, you need to know what the limits of your servo travel are.  I think that the best results would be if the servo travels as much as possible, by using the holes in the horns as near to the axis as possible - but if you see my photos, link below, I haven't done this, so the action is a bit quick, and the settings are quite critical.

 

To find the right settings for the servo end points, I used a very simple program, listed below, which uses a potentiometer on an analog input of the Arduino.  The program makes a ratio between the voltage on the pot wiper and +5V, converts it to an output for the servo, and moves the servo accordingly.  This is straight from the Arduino "examples", with the addition of the few lines to print the servo output to the serial monitor.  This allows you to note down the correct positions, and to then implement them in the program that controls the servos.

 

The program refers to the signal I posted at #22 in http://www.rmweb.co.uk/community/index.php?/topic/79052-porth-dinllaen-in-0/&do=findComment&comment=1272968

 

The servos should not normally be powered from the Arduino - but you will probably get away with it for this exercise, because you are only operating one at a time, and it is not likely to cause any malfunction, but if you have several, they will cause the Arduino to "brown out" and reset itself.   Anyway, for the purposes of this exercise, connect one end of the pot to +5V, and the other to GND.   Connect the wiper to pin A0.  Connect the red wire on the servo to +5V and the black to GND, and the signal wire to pin 9.

 

Run the program with servo not connected to signal.  Centre servo.  Connect to signal, use pot (gently) to find the end position, and write it down.  Ditto other end position, write that down too.  Use those positions in the operation program by inputting the numbers in this statement

 

int sigbracket[2]={
  70,91};

 

eg, "70" is normal, "91" is pulled.  If I had ensured that the operating wires were in holes nearer the axis, there would have been a bigger gap between these numbers (but I would have also had to make sure that the servo horn didn't hit anything as it would travel through a greater angle for the same linear displacement).  It doesn't matter which is bigger or smaller, but do make sure you know which is which!

 

Hope this makes sense!

 

SD

 

servo_setting_with_pot.ino

 

 

Edited by Simond
Link to post
Share on other sites

I don't think I made my aims clear in my original post - please feel free to add your own sketches, and link to other threads - hopefully this will enable people find things that they are looking for!

 

best

SD

Link to post
Share on other sites

and another one...

 

my turntable appears in JeffP's thread here

 

http://www.rmweb.co.uk/community/index.php?/topic/76732-stepper-motor-turntable-drive/page-6

 

The program, needs a bit of refinement, and some comments, looks like this;  I'll pretty it up when I have time, but it does work...

 

best

SD

 

turntable_1mar14_a4988_subroutines_with_sensor.ino

 

Edited by Simond
Link to post
Share on other sites

It would be very useful for all concerned if code was enclosed within code tags like this (using the <> icon)

void setup() {
  Serial.begin(9600);
  Serial.println("Hello World");

}

void loop() {

}

...R

Link to post
Share on other sites

For the purposes of this thread attaching would probably be more useful as it makes it easier for people to download.

 

Its possible to edit  existing posts to enclose the code within code tags.

 

...R

Edited by Robin2
Link to post
Share on other sites

  • RMweb Premium

One thing you might want to add to any of your sketches that use digital ports for switch position detection is some form of "debouncing". A small glitch on your power supply line created by a noisy/dirty loco motor or the like can cause your signals/points to flap about. In it's simplest form it could be something like this...

 

  int state = digitalRead(10);
  delay(10);
  int state2 = digitalRead(10);
  if (state == state2) {
    if (state == LOW) {
      servomain.write(sigmain[1]);
    } else {
      servomain.write(sigmain[0]);
    }
  }
In this case we take two readings of the port 10 milliseconds apart and if they are the same we can safely assume the switch state is stable.

 

Cheers

Dave

Edited by eldavo
Link to post
Share on other sites

This thread ought to be relocated into the 'Computer Control' section rather than here because it's general subject matter is not necessarily specific to PWay and Signalling, even if it is to start with. Other Arduino related threads are located there already.

Link to post
Share on other sites

Right!

 

Gordon - spoke to Andy, and we are now in Computer Control

 

Dave - thanks for the suggestion - I don't think I have had a problem as it is, but your suggested code makes perfect sense - I'll implement at some point.

 

Robin - Andy has enabled the attachment of ".ino" files. I am currently in a hotel in Poland with no access to my programs - would you like to try attaching and downloading a file to see if it works? If you're busy, I'll do it at the weekend. Whilst I have your attention, how do I edit a previous post (sorry if this is dumb...) to implement the quotation box per your suggestion?

 

Thanks to all for the contributions

Best

SD

Link to post
Share on other sites

Hi Simon,

 

As requested this is an attempt to upload a .ino file

 

It seems to work.

 

Readers should realize that the Arduino IDE expects .ino files to be in a directory with the same name. In other words you need to create a directory called "HelloWorld" and place the attached file "HelloWorld.ino" into it.

 

(By the way I hadn't realized the file type mattered - I would have been lazy and changed it to a .txt file :))

 

...R

HelloWorld.ino

Edited by Robin2
Link to post
Share on other sites

Thanks Robin

 

I was on the same page, I had already been lazy and changed the name to ".txt", but it didn't let me do that either! :(

 

Anyway, thanks to Andy, we can now attach ino files.

 

Now, I need to work out how to go back and edit my previous posts to tidy the thread!

 

Later

SD

Link to post
Share on other sites

Hi all

 

you will see that I have now moved all my program text out of the thread and added attachments.

 

I hope to get a Pro Mini and programming interface for the turntable in the next few weeks, and will then install that permanently, I'll probably try to tidy up the code then, and post it.

 

best

SD

Link to post
Share on other sites

I have written a couple of simple Arduino sketches to control servos using an Arduino Uno. They may be helpful to people you are new to Arduinos.

 

One of the sketches can control 9 servos with 9 toggle switches.

 

The other sketch can control 6 servos with 6 toggle switches an also light 2 LEDs per servo to indicate point setting.

 

I have also prepared a simple wiring diagram.

 

I haven't tested the sketches with all the servos connected but I have no reason to believe they won't work.

 

Please ensure that the servos have their own power supply as the Arduino can't provide enough current for a servo.

 

Let me know if anything isn't clear.

 

...R

TrainServos9.ino

TrainServos6WithLeds.ino

post-10065-0-03795300-1394743992_thumb.png

Link to post
Share on other sites

Robin

 

Thanks for this!

 

I didn't realise you could do an input pull-up on an analog pin

 

Your programming appears to be rather more sophisticated/advanced than mine... :)

 

I won't have a chance to try this out for a few weeks, but I'm interested particularly as your approach seems to offer opportunities for interlocking - thinking cap on!

 

Best

Simon

Link to post
Share on other sites

Thanks Simon,

 

Yes interlocking (and as complex as you like) should be possible.

 

One idea might be to define meaningful names for each servo such as

#define downMain 3

meaning that the servo in the 3 position is for the downMain. Then the code for point 5 could be something like this (assuming it is in the existing for loop)

if (n == 5 && servoPos[downMain] == LOW) {
   do something
}

...R

Link to post
Share on other sites

Robin,

 

I was thinking of having two (groups of) variables attached to / incorporated in a function for each lever, one would represent the "released by" and the other would be "locked by", each referring to other lever(s) in the frame.

 

This would allow almost prototypical locking schemes to be used. As it is unlikely to be feasible in any sensible way to actually lock the levers (small toggle switches in my imagination) I had in mind a suitably located red led to indicate whether any particular lever is locked.

 

The other option would be to get a Modratec or Scale Signal Supply frame and do it properly, I think MSE also did frames, but afaik they didn't offer locking. In any case, it's overkill if we're already using an Arduino as a servo driver, (but the SSS ones are very nice...)

 

I'll try to sketch something out over the next week or so - depends how things are at work - all day on the laptop doesn't leave one in the right frame of mind to start thinking logically!

 

Best

Simon

Link to post
Share on other sites

Hi Simon,

 

It sounds like your design is essentially the same as mine, down to the red-LED locking indicators and interlocking variables!

 

I was thinking of making the LED flash if the lever/switch was moved when it should be locked, and no movement of the associated servo(s).

 

I've been considering defining the config along the lines of:

 

lever n operates servos x,y,z locked by levers a,b,c

 

I have to read up on interlocking to see what other things need to be taken into account.

 

I was figuring something like a facing point lock could be implemented by just knowing the switch should be locked, so not moving the servo(s) when it is thrown.

 

Having the ability to associated multiple servos to a switch is probably useful in a number of cases. Simply moving two sets of point switches can probably be done with one servo and a mechanical linkage, but there are bound to be other cases (both sides of a loop?) where things are far apart.

 

Mechanical interlocking would be cooler, but quite a lot of work. It would also be nice to have electrically lockable switches but the only ones I found were big, expensive industrial things. Perhaps little solenoids could shoot locking bars in and out of the ends of the levers?

 

Regards,

David.

Link to post
Share on other sites

I had also been thinking of causing an LED to flash to warn of an erroneous movement. You could also have the LED for a locked point flash in a suitable way.

 

I don't know enough about interlocking to suggest how the locking requirements might be recorded. It would be nice if it could be in a table - a bit like the way I have presented the angles for the servos - but it may be too complex for that.

 

Perhaps if someone could describe a reasonably complex locking arrangement for one set of points and signals we would have something to get our teeth into.

 

...R 

Link to post
Share on other sites

Thanks guys,

 

I hadn't thought of flashing the led - absolutely obvious, once someone says it!!!

 

I have a very good pal who know a bit about signalling - I'll ask him about it over a beer or two when I see him, but my understanding is that it is absolutely a table of "permits" and "prohibits"

 

More when I can

Simon

Link to post
Share on other sites

Just found this rather nice implementation - I like the two-wire connection between lever frame (row of buttons...) and yard, and the consequently short wiring from servos to driver board

 

 

Best

Simon

Link to post
Share on other sites

  • RMweb Premium

Here's a sketch for controlling up to 6 semaphore signals using servos. The movement includes pull-up and bounce simulation plus direction and limits of throw are adjustable for each servo. I've used it to control a couple of signals on our clud layout using an Arduino pro mini.

 

Semaphore6_0_1.ino

 

Cheers

Dave

 

For the codeheads here's some light reading...

////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Semaphore6
//
// Author: Dave Renshaw
//
// This sketch provides control of up to 6 servos operating semaphore signals with configurable throws. Each servo has 2 defined
// positions and is toggled by connecting an input pin on the Arduino to 0v. A calibration push button can be used
// to set the 2 throw positions for each servo.
//
// The sketch assumes an Arduino Uno, Nano or Pro mini that supports 6 PWM output ports. A push to make switch
// can be wired to connect 0 volts to analogue pin 2 (A2) to switch into set up mode. Each servo is switched 
// by connecting a digital pin to 0 volts. The switch and control output to each servo is as follows:
//
//  switch port 2  control signal output 3
//        "     4             "          5
//        "     7             "          6
//        "     8             "          9
//        "     12            "          10
//        "     A0            "          11
//
// By default the servos will move 45 degrees past the centre point i.e. from 90 degrees in the "danger"
// position to 135 degrees in the "clear" position. This set up can be inverted by operating
// the servo you wish to change using its normal switch then pressing and holding the set up button for at 
// least 2 seconds but less than 10.
//
// The power supply can be controlled so that power is only applied when a servo is to be moved. This prevents
// extreme "twitching" movements during start-up or buzzing during normal operation. For most cases the
// inertia/resistance in the servo gearbox will adequately maintain position so this is beneficial but it
// need not be used. To enable switching connect a switching cicuit to analogue pin 1 (A1). This can be a simple
// transistor circuit using a 2N2222 or similar with the base fed via a 220 ohm resistor controlling a relay
// or something more exotic. A 5v level will be output on A1 when the servos needs to be powered.
//
// To adjust the throw of a servo first operate it then push the set up button for less than 2 seconds. The
// servo should then move to its centre position. Press the set up button again and the servo will start
// moving slowly towards the "danger" position. Push the set up button again when the throw is correct and
// the servo will again centre then move slowly in the opposite direction. Push the set up button again to
// set the opposite throw limit. The controller will remember the settings and go back to normal operation.
//
// The controller can be reset back to its default settings by pressing the set up pushbutton for 10 seconds
// or more. All previously saved settings will be lost.
//
// Switching a signal to clear will cause the servo to move slightly towards the clear position, pause for a
// fraction of a second then move fully to the clear position. This is intended to emulate the signalman taking
// up the slack in the operating wires then pulling the lever fully out of the frame. When the switch is returned
// to danger the servo will provide a slight bounce in the arm movement. The degree of bounce, pull-up and the
// timings are all defined by constants.
//
// Dave Renshaw
//

#include <Servo.h> 
#include <avr/eeprom.h> 

#define VERSION                  "0.1"

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// This sketch should work OK on any of the standard Arduinos and this sketch is configured for the Uno, Nano and Pro Mini
//
//    Calibration switch is on analogue port 2 (A2)
#define SET_UP                    A2
//
//    Power switching is done using analogue port 1 (A1)
#define POWER                     A1
// 
//    Status shown by inbuilt LED on 13
#define STATUS                    13
//
//    The maximum number of servos this sketch will control...
#define MAX_DEVICES               6
//
//    Servo control is via PWM output ports 3,5,6,9,10 and 11
int servoPorts[] = {3, 5, 6, 9, 10, 11};
//
//    Switches are on digital ports 2,4,7,8,12 and A0
int switchPorts[] = {2, 4, 7, 8, 12, A0};
//
// The debounce time for switches; increase if things get twitchy!
int DEBOUNCE_PERIOD =           10;   // 10 milliseconds
//
// Long switch period
int LONG_SWITCH_PERIOD =       2000;   // 2 seconds
//
// Long switch period
int RESET_SWITCH_PERIOD =     10000;   // 10 seconds
//
// The length of time we power up the servos for each time we move one; increase if servos don't throw fully!
int POWER_TIME =               2000;   // 2 seconds
//
// Delay used in the arm bounce sequence
int BOUNCE =                    300;   // 300 milliseconds
//
// Delay used in the arm pull down sequence
int PULL =                      700;   // 700 milliseconds
//
// Number of degrees of movement to use for the arm bounce and pull down sequence
int BOUNCE_ANGLE =               15; 
//
// We track the last servo referenced through a switch and use this to decide which to calibrate
int lastServoReferenced =        -1;
//
// Default danger angle
#define DANGER                    90
//
// Default cleared angle
#define CLEAR                    135
//
// The Servo objects we use to generate the control signals
Servo  servos[MAX_DEVICES];

typedef struct
{
    int               outputPort;             // PWM output
    int               switchPort;             // port to connect switch to
    int               dangerSetting;          // Angular displacement for danger position
    int               clearSetting;           // Angular displacement for clear position
    boolean           inverted;
    int               oldSwitchState;
    long              lastSwitchChangeTime;
} ServoData;

ServoData devices[MAX_DEVICES];


// The last known state of the setup button and when we registered it (default to unpressed)
int oldSetUpButtonState = HIGH;
long lastSetUpButtonChangeTime;

//
//  s e t u p
//  =========
//
//  The function called once on power up to set everything up ready to go.
//
void setup() { 
  Serial.begin(9600);
  Serial.print(millis());
  Serial.println("-->setup()");
  Serial.print("  Semaphore6 version ");
  Serial.println(VERSION);
  
  // Enable the set-up/adjustment pushbutton...
  pinMode(SET_UP, INPUT_PULLUP);
  // Enable the status LED...
  pinMode(STATUS, OUTPUT);
  digitalWrite(STATUS, LOW);
  // Enable the power control line...
  pinMode(POWER, OUTPUT);
  digitalWrite(POWER, LOW);
   
  // Do we have a saved configuration?
  if(eeprom_read_byte(0) != 255) {
    eeprom_read_block((void*)&devices,(void*)1,sizeof(devices));
    Serial.println("  Read saved config");
  } else {
    Serial.println("  Using default config");
    // Set up the default config...
    for (int i = 0; i < MAX_DEVICES; i++) {
      devices[i].outputPort = servoPorts[i];
      devices[i].switchPort = switchPorts[i];
      devices[i].dangerSetting = DANGER;
      devices[i].clearSetting = CLEAR;
      devices[i].inverted = false;
      devices[i].oldSwitchState = -1;
      devices[i].lastSwitchChangeTime = millis();
    }
  }

  // Set up the servos and switch ports...
  for ( int i = 0; i < MAX_DEVICES; i++) {
    pinMode(devices[i].outputPort, OUTPUT );
    servos[i].attach(devices[i].outputPort);
    // Turn on the servo power for a moment to get everything to the initial position...
    powerOn();
    servos[i].write(DANGER);
    pinMode(devices[i].switchPort, INPUT);
    digitalWrite(devices[i].switchPort, HIGH);
    // set the old switch state to unknown so we read the switch to start with...
    devices[i].oldSwitchState = -1;
  } 

  oldSetUpButtonState = HIGH;
  lastSetUpButtonChangeTime = millis();

  Serial.print(millis());
  Serial.println("<--setup");
}

// setup

//
// The current phase of set up we are in:
//   0 = normal operation i.e. not in set up
//   1 = centred
//   2 = moving from centre to set danger position
//   3 = moving from centre to set clear position
//   4 = finished and saving
int setUpPhase = 0;
// when the last servo adjustment step was made
long timeOfLastSetUpStep;
// the most recent servo position during set up
int setUpPosition;
// the time between steps in the set up movement process
int STEP_INTERVAL = 300;

//
//  l o o p
//  =======
//
//  The main processing loop
//
void loop() {
  
  // look at the set_up push button...
  int newState = digitalRead(SET_UP);
  delay(DEBOUNCE_PERIOD);
  int newState2 = digitalRead(SET_UP);
  
  if ((newState == newState2) && (newState != oldSetUpButtonState)) {
    digitalWrite(STATUS, HIGH);
    delay(50);
    digitalWrite(STATUS, LOW);
    // How long since the button state last changed?
    long timeNow = millis();
    long switchTime = timeNow - lastSetUpButtonChangeTime;
    // Has the button been released and we have previously switched a servo?
    if ((newState == HIGH) && (lastServoReferenced >= 0)) {
      
      // Was that a very long button push requesting a reset?
      if (switchTime > RESET_SWITCH_PERIOD) {
        Serial.println("  Resetting config");
        setUpPhase = 0;
        // Save 255 in the first byte of the config to indicate nothing is saved then call setup()...
        eeprom_write_byte(0, 0xFF);
        setup();
        
      } else
      // Was that a long button push?
      if (switchTime > LONG_SWITCH_PERIOD) {
        Serial.print("  Inverting servo ");
        Serial.println(lastServoReferenced);
        // a long button push so invert the throw...
        int i = devices[lastServoReferenced].dangerSetting;
        devices[lastServoReferenced].dangerSetting = devices[lastServoReferenced].clearSetting;
        devices[lastServoReferenced].clearSetting = i;
        
        setUpPhase = 0;
        devices[lastServoReferenced].inverted = !devices[lastServoReferenced].inverted;
        // Save the config...
        eeprom_write_byte(0, 0x00);
        eeprom_write_block((void*)&devices,(void*)1,sizeof(devices));
        // set the servo back to the right position
        powerOn();
        if (devices[lastServoReferenced].oldSwitchState == LOW) {
          if (!devices[lastServoReferenced].inverted) {
            servos[lastServoReferenced].write(devices[lastServoReferenced].dangerSetting);
          } else {
            servos[lastServoReferenced].write(devices[lastServoReferenced].clearSetting);
          }
        } else {
          if (!devices[lastServoReferenced].inverted) {
            servos[lastServoReferenced].write(devices[lastServoReferenced].clearSetting);
          } else {
            servos[lastServoReferenced].write(devices[lastServoReferenced].dangerSetting);
          }
        }
        
      } else {
        // Just a normal length button push so go to the next set up phase...
        setUpPhase++;
        Serial.print("  Set up phase ");
        Serial.println(setUpPhase);

        if (setUpPhase == 1) {
          // center the servo...
          timeOfLastSetUpStep = timeNow;
          setUpPosition = 90;
          powerOn();
          servos[lastServoReferenced].write(setUpPosition);
        } else if (setUpPhase == 2) {
          // Nothing to do here...
        } else if (setUpPhase == 3) {
          // Save the position...
          devices[lastServoReferenced].dangerSetting = setUpPosition;
          // center the servo...
          setUpPosition = 90;
          powerOn();
          servos[lastServoReferenced].write(setUpPosition);
        } else if (setUpPhase == 4) {
          // Save the position...
          devices[lastServoReferenced].clearSetting = setUpPosition;
          setUpPhase = 0;
          // Save the config...
          eeprom_write_byte(0, 0x00);
          eeprom_write_block((void*)&devices,(void*)1,sizeof(devices));
          // set the servo back to the right position
          powerOn();
          if (devices[lastServoReferenced].oldSwitchState == LOW) {
            if (!devices[lastServoReferenced].inverted) {
              servos[lastServoReferenced].write(devices[lastServoReferenced].dangerSetting);
            } else {
              servos[lastServoReferenced].write(devices[lastServoReferenced].clearSetting);
            }
          } else {
            if (!devices[lastServoReferenced].inverted) {
              servos[lastServoReferenced].write(devices[lastServoReferenced].clearSetting);
            } else {
              servos[lastServoReferenced].write(devices[lastServoReferenced].dangerSetting);
            }
          }
        }
      }
    } // newState == HIGH
    oldSetUpButtonState = newState;
    lastSetUpButtonChangeTime = millis();
  } // newState != oldSetUpButtonState
  
  // are we doing the servo set up thing...
  if (setUpPhase > 0) {
    // Looks like it
    if ((millis() - timeOfLastSetUpStep) > STEP_INTERVAL) {
      if (setUpPhase == 2) {
        if (!devices[lastServoReferenced].inverted) {
          setUpPosition--;
        } else {
          setUpPosition++;
        }
      } else if (setUpPhase == 3) {
        if (!devices[lastServoReferenced].inverted) {
          setUpPosition++;
        } else {
          setUpPosition--;
        }
      }
      powerOn();
      servos[lastServoReferenced].write(setUpPosition);
      timeOfLastSetUpStep = millis();
    }
  } // setUpPhase > 0
  else {
    // No so check the switches...
    for(int i=0; i<MAX_DEVICES; i++) {
      newState = digitalRead(devices[i].switchPort);
      delay(DEBOUNCE_PERIOD);  
      newState2 = digitalRead(devices[i].switchPort);
      if ((newState == newState2) && (newState != devices[i].oldSwitchState)) {
        devices[i].lastSwitchChangeTime = millis();
        digitalWrite(STATUS, HIGH);
        Serial.print("  Servo ");
        Serial.print(i);
        Serial.print(" switched to ");
        Serial.println(newState);
        // Is this signal configured normally or inverted?
        powerOn();
        if (!devices[i].inverted) {
          // Normal config...
          if (newState == LOW) {
            // Clearing...
            servos[i].write(devices[i].dangerSetting + BOUNCE_ANGLE);
            delay(PULL);
            servos[i].write(devices[i].clearSetting);
          } else {
            // return to danger...
            servos[i].write(devices[i].dangerSetting);
            delay(BOUNCE);
            servos[i].write(devices[i].dangerSetting + BOUNCE_ANGLE);
            delay(BOUNCE);
            servos[i].write(devices[i].dangerSetting);
          }
        } else {
          if (newState == LOW) {
            // Clearing...
            servos[i].write(devices[i].dangerSetting - BOUNCE_ANGLE);
            delay(PULL);
            servos[i].write(devices[i].clearSetting);
          } else {
            // Return to danger...
            servos[i].write(devices[i].dangerSetting);
            delay(BOUNCE);
            servos[i].write(devices[i].dangerSetting - BOUNCE_ANGLE);
            delay(BOUNCE);
            servos[i].write(devices[i].dangerSetting);
          }
        }
        digitalWrite(STATUS, LOW);
        // remember the servo state and which one we last moved...
        devices[i].oldSwitchState = newState;
        lastServoReferenced = i;
      }
    }
  }
  
  // See if it is time to power off the servos...
  powerCheck();
  
}  // loop


// 
// A flag to track the status of the servo power
boolean power = false;
long powerOnTime = 0;

//
//  p o w e r O n
//  =============
//
// A function to turn the servo power supply.
//
void powerOn() {
//    Serial.print(millis());
//    Serial.println("-->powerOn");
    powerOnTime = millis();
    // turn on the servo power...
    digitalWrite(POWER, HIGH);
    Serial.print(millis());
    Serial.println("  power ON");
    power = true;
//    Serial.print(millis());
//    Serial.println("<--powerOn");
} // powerOn

//
//  p o w e r C h e c k
//  ===================
// Routine to check if servo power should be cut off
//
void powerCheck() {
//    Serial.print(millis());
//    Serial.println("-->powerOff");
    if (power && ((millis() - powerOnTime) > POWER_TIME)) {
      // turn off the servo power...
      digitalWrite(POWER, LOW);
      power = false;
      Serial.print(millis());
      Serial.println("  power OFF");
    }
//    Serial.print(millis());
//    Serial.println("<--powerOff");
} // powerOff

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

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...