Show Posts
Pages: [1] 2
1  Using Arduino / Storage / SD card recording a timestamp: Error on second sync on: March 04, 2011, 01:38:03 pm
I am building a device that converts a manual glue machine (pressing a foot pedal to run the machine) to a digital one where pressing a button runs the whole system through a cycle. The buttons, microswitches, and everything physical works correctly. However, when I run the program once everything is fine. Then when i trigger the Go button a second time, the SD bonks out "error:sync"

The program is a mishmash of code from SDFat's append example and RTClib's clock example.


I am trying to record a timestamp of everytime the Go button is pressed. Any idea what is going wrong?
Code:
/*

This code is to be used with the portionator glue machine device
which uses a push button to run a full stroke of glue as well as
record the time and date the glue stroke was requested. This is
stored to an SD card that can be used to monitor the machine usage.
 */
#include <SdFat.h>
#include <SdFatUtil.h> // use functions to print strings from flash memory
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;

#define ECHO_TO_SERIAL 1 //echo data to serial

// store error strings in flash to save RAM
#define error(s) error_P(PSTR(s))

void error_P(const char* str) {
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}
// these constants won't change:

const int RetractSwitch = 3; //the microswitch is closed when the cylinder is retracted
const int ExtendSwitch = 4; //the microswitch is closed when the cylinder is fully extended
const int RunLEDPin =5; //This is the RED LED output pin indicating the machine is running
const int TransPin = 6; //This is the pin which activates the solenoid through the transistor
const int GoSwitch = 7; //This is the push button that when closed, activates the glue dispense sequence.

// Variables will change:
// int buttonPushCounter = 0;   // counter for the number of button presses
int GobuttonState = 0;         // current state of the button
int RunState = 0;      //Indicates if the system is running 0 = off, 1 = on
int StrokeComplete = 0; // '1' Indicates that the extend of stroke micro has been pressed but the system has not fully retracted.
int ExtendSwitchState = 0; // Extend switch = 0 if not compressed indicating not at end of stroke
int RetractSwitchState = 0; // Retract switch =0 if not compressed indicating not at start position

void setup() {
 
  pinMode(RetractSwitch, INPUT);
  pinMode(ExtendSwitch, INPUT);
  pinMode(RunLEDPin, OUTPUT);
  pinMode(TransPin,OUTPUT);
  pinMode(GoSwitch,INPUT);
  Serial.begin(9600);  // initialize serial communication:
  Wire.begin();
  RTC.begin();

  //This section can be activated, compiled and uploaded to set the clock.
  // if (! RTC.isrunning()) {
  //  Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
  //  RTC.adjust(DateTime(__DATE__, __TIME__));
  //}

              // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
                // breadboards.  use SPI_FULL_SPEED for better performance.
                if (!card.init(SPI_HALF_SPEED)) error("card.init failed");
             
                //                 initialize a FAT volume
                if (!volume.init(&card)) error("volume.init failed");
             
             
                // open the root directory
                if (!root.openRoot(&volume)) error("openRoot failed");
               
                char name[] = "GLUEUSE.TXT";
                PgmPrint("Appending to: ");
                Serial.println(name);
               
                // clear write error
                file.writeError = false;
               
                  // O_CREAT - create the file if it does not exist
                   // O_APPEND - seek to the end of the file prior to each write
                  // O_WRITE - open for write
                  if (!file.open(&root, name, O_CREAT | O_APPEND | O_WRITE)) {
                    error("open failed");
                  }
}
void loop() {

//The system is not running, so check to see if the button is pressed
  if(RunState == 0) { //This makes sure the system is not already activated. This is reset to 0 when the system has triggered both micros (extended and then retracted)
  GobuttonState = digitalRead(GoSwitch);
    // if the button is pressed, run the glue dispenser
      if (GobuttonState == HIGH) {
            DateTime now = RTC.now();   
            RunState = 1;
            digitalWrite(RunLEDPin, HIGH); //Turns on the RED LED to indicate the machine is running
            digitalWrite(TransPin, HIGH); //Turns on the solenoid
            Serial.println("on");
            //Write the timestamp to the SDcard

 
                 
                  // print time to file
                      file.print(now.year(), DEC);
                      file.print('/');
                      file.print(now.month(), DEC);
                      file.print('/');
                      file.print(now.day(), DEC);
                      file.print(' ');
                      file.print(now.hour(), DEC);
                      file.print(':');
                      file.print(now.minute(), DEC);
                      file.print(':');
                      file.println(now.second(), DEC);
                 
                  Serial.println("Syncing.");
                  if (!file.sync()) error("sync");
                  Serial.println("Done Syncing.");
                 
                  if (file.writeError) error("write failed");
                  if (!file.close()) error("close failed");             
                Serial.println();
                Serial.println("Done");           
        }
    }
 
//The system is running and we are looking to see if we have fully extended the cylinder
  if (RunState == 1) { //If the system has been activated
      if (StrokeComplete == 0) { // This system has not already reached the end of stroke microswitch
          Serial.println("Looking for end of stroke");
          ExtendSwitchState = digitalRead(ExtendSwitch);
          if (ExtendSwitchState == 1) { //This indicates the system is running and has reached the end of the glue stroke
             Serial.println("End of stroke found");
             digitalWrite(TransPin, LOW); // Begins to retract the cylinder
             StrokeComplete = 1; //We have completed a stroke. This is set to zero when we reach the return position
          }
      }
  }

// The system is running and we have reached the end of the stroke. We are looking to see if we are back in the original position 
  if (StrokeComplete == 1) { //This indicates we are in the middle of back stroke
     Serial.println("Looking for return to start");
     RetractSwitchState = digitalRead(RetractSwitch);
     if (RetractSwitchState == 1) { //This indicates we have reached the end of stroke and need to reset for next stroke
       digitalWrite(RunLEDPin, LOW);
       StrokeComplete = 0;
       ExtendSwitchState = 0;
       RunState = 0;
       Serial.println("Stroke Complete");
     }
  } 
}








2  Using Arduino / General Electronics / Re: Using a source input to read a source output on: February 04, 2011, 04:37:56 pm
I understand that the top won't work. That is the point of the whole question. That is what i currently have. I CANNOT change the bottom line to ground. It MUST be 24VDC+. The question is what to add in the yellow box to make it the input node A will change from 24VDC to 0 when the switch is closed.

The bottom circuit is my best guess as to what might work. The question I really need answered is, can I use a transistor as a switch that grounds the input node (A), when the switch (between B and C) is closed? and do i need a resistor somewhere? Nevermind why it closes.

My concern is that without a resistor in between the switch and the transistor, the transistor could pull too much current.

I understand it is confusing but I really don't want to give you the entire circuit diagram because it includes literally hundreds and hundreds of elements. It is only this one silly little problem that i need resolved.

3  Using Arduino / General Electronics / Re: Using a source input to read a source output on: February 04, 2011, 03:49:34 pm
I have redrawn the specific question. We are getting off-track I think.

4  Using Arduino / General Electronics / Re: Using a source input to read a source output on: February 04, 2011, 01:49:19 pm
I apologize for the confusion and appreciate your willingness to try and help me despite my lack of clarity.

First, to respond to your understanding of what I said:
A) Yes, I do have a system I am monitoring. It is a rather complex control panel.
B) System M does have nodes that are either 24VDC or 0. The system I am monitoring has it's own PLC in it. The nodes I am monitoring are the outputs of that PLC.
C). Yes, I am using a PLC ("P") that are internally pulled up to 24VDC.
D). Yes, you are understanding correctly. As I wired it up I found that whether or not the system "M" is outputting 24VDC or 0VDC the plc "P" inputs read 24VDC. This is, I believe, because both of them are pulled up and there is no path to ground.
E). There is a typo in the drawing. That is intended to be 24VDC. It is the power supply used to power the PLC "P" as well as the system "M".
F). The transistor is my best guess at what I can use to deal with the problem that should up in D. It provides a method to pull down the "P" input and uses the node from "M" that really I want to sense as the Base for the transistor.
G&H). You are correct. That relay is part of system "M" and is activated or not by a different mess of events. In essence, that is what I am attempting to detect is either open or closed.

Questions:
1)The connections at the bottom of the PLC are the power connection into the PLC (V+ and GND).
2). The relay is controlled by "M" "has a set of it's own inputs that it is sensing, performing logic upon and then opening or closing the relay.
3). The 2VDC should be 24VDC and it powers pretty much everything, the PLC "P", the system "M", and is the power passing through the relay.
4). I cannot put the relay in place between the P input and ground because the relay is embedded in system "M". The only reason I showed the relay was because I didn't know if I needed a diode across it (to protect the transistor) and/or if I need a resistor between the power supply and the base of the transistor.

5). Are they sharing ground? Well, some of the inputs are. Others are not. However, I could change things a little and make them share the same ground if it helps.

As for your final comment, I did not build the system with a transistor at all. However, I did not realize that the PLC input was internally pulled up (sourcing), I thought it was a "sink" or internal pulled down. The issue I have is that I cannot change the system "M" whose nodes can only be monitored by a "sinking" input channel in P. Since I am stuck with internal pulled up inputs in P, I am looking to build a little circuit that can deal with this. My ide was using a transistor as a switch, but need to know if i require any resistors, diodes, etc to prevent causing some sort of damage or failure.

Thanks

5  Using Arduino / General Electronics / Re: Using a source input to read a source output on: February 04, 2011, 10:00:07 am
You are correct that as a sourcing input, relaying the pin to ground would close the loop and change the input from high to low. Unfortunately though, I cannot simply do that. This device exists to test to an electrical control panel and confirm that this other panel is wire correctly. Some of the lines that are to be tested read either 0 or 24V (these lines I am testing are themselves sources due to the nature of the panel I am testing).

If I wire the input channel on the PLC to the channel on the electrical board i am looking to read, the voltage at the PLC input pin remains high (as there is no sink). That is why I was thinking of using a transistor as a switch in which the PLC input shorts to ground when the transistor's base is powered (from the control panel circuit I am testing).
6  Using Arduino / General Electronics / Using a source input to read a source output on: February 03, 2011, 07:05:25 pm
I have ran into a situation that requires the expertise of the Arduino hobbyists, even though this is not particularly an Arduino question. I just find these forums to be fantastic at answering questions!

So, onward we go.

I have a PLC that has inputs that are sourcing (24VDc, .5mA).

I need to detect a couple things with these inputs:
(1). That a pin is at 24VDC (it is actually wired to the same power supply that runs the PLC).
(2). That a mechanical relay has closed. When the relay is closed the wire downstream of the relay is at 24VDC (the input to the relay is connected to the same power supply.

How can I measure these 2 situations with the sourcing inputs. If i hook them directly to that which i want to monitor they simply always read 24VDC (from themselves or from the thing i am trying to measure), so I was thinking, "a transistor."

I have attached a diagram of what I think might work. If you agree that this is the right approach, any suggestions on an actual transistor that i should use?

Thanks for teaching this fool!
7  Forum 2005-2010 (read only) / Syntax & Programs / Re: Exepected Unqualified-id numeric constant HELP! on: January 06, 2010, 06:22:46 pm
Wonderful. It looks like that should take care of it! I went through looking for those but someone missed that one. Oh, for line numbers on the errors!
8  Forum 2005-2010 (read only) / Syntax & Programs / Exepected Unqualified-id numeric constant HELP! on: January 06, 2010, 06:05:33 pm
So, I have no idea what is causing this error. Any help would be greatly appreciated!

error: expected unqualified-id before numeric constant In function 'void loop()':

Code:
#include <Ethernet.h>


/*
 * Ethernet-Stepper Server
 *
 * This program functions as a server which receives commands from a client and sends pulses to
 * a stepper motor based upon the received command. The program also sends back information reporting
 * the actions it has taken.
 * The command set as received through the ethernet shield is as follows:
 *UXXXX  Linear motor up XXXX degrees. ex. U0360 would be a 360 turn approx 1"
 *DXXXX  Linear motor down XXXX degrees. ex. D0360 would be a -360 turn approx 1"
 *LXXXX  Rotary Motor CCW XXXX degrees. ex L1080 would be 4 turns CCW
 *RXXXX  Rotary Motor CW XXXX degrees. ex R1080 would be 4 turns CW
 *TXXXX  Set Rotary Time delay speeds up or slows down the motor
 *SXXXX  set linear time delay speeds up or slows down the motor
 */

// network configuration.  gateway and subnet are optional.
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = {
  192, 168, 254, 39 };

// telnet defaults to port 23
Server server = Server(23);
int dirpin = 7; //The stepper direction is set by this pin
int steppin = 6; //The stepper motion is controlled by pulses on this pin.
int linsteppin = 9; // The linear motor motion is controlled by pulses on this pin.
int lindirpin = 8; //The linear motor direction is controlled by this pin.
int angle = 0;
int linangle = 0;
int numofsteps = 0;
int linnumofsteps = 0;
int TimeDelay = 150; //This is the stepper motor's delay parameter
int linTimeDelay = 500; //This is the linear motor's delay parameter.
int ledPin = 13 //LED connected to digital pin 13

void setup()
{
  // initialize the ethernet device
  Ethernet.begin(mac, ip);
  // start listening for clients
  server.begin();

  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  pinMode(linsteppin, OUTPUT);
  pinMode(lindirpin, OUTPUT);
  digitalWrite(dirpin, HIGH); //Set default direction
  digitalWrite(lindirpin, HIGH);
  pinMode(ledPin, OUTPUT); //sets the digital led pin as output

}

void loop()
{
  Client client = server.available();
  if (client)
  {
    boolean messageComplete = false;
    long timeOut = millis();
    char lineBuffer[100]; // large buffer for storing data
    int charCount;

    while (!messageComplete || server.available())
    {
      if ((abs(millis() - timeOut)) > 2000)
      {
        server.println("Timeout On Response");
        break;
      }
      if (server.available())
      {
        lineBuffer[charCount] = client.read();
        if (lineBuffer[charCount] == 13) //Waits for a carriage return
        {
          messageComplete = true;
        }
        charCount++;
        delay(50);
      }
    }

    if (messageComplete)
    {
      switch (lineBuffer[0])
      {

      case 'U': //"UXXXX" received where X is a number 0 to 9
        digitalWrite(lindirpin, LOW);
        server.println("Going UP. ");

        char lintempSteps[5]; //This is a string used to convert the buffer elements into a 4 long number "XXXX"
        for (int i = 1; i < 5; i++) //This loop confirms the XXXX is a number and then stores into the lintempsteps variable
        {
          if (lineBuffer[i] >= '0' && lineBuffer[i] <= '9')
          {
            lintempSteps[i - 1] = lineBuffer[i];
          }
          else
          {
            server.println("Invalid Lin Angle");
            break;
          }
        }
        linnumofsteps = atoi(lintempSteps);
        server.print("Valid Lin Angle Received = "); //This simple informs the client that a valid move command was received.
        server.print(linnumofsteps);
        server.println(" Degrees.");
        linmoveMotor(); //Moves the motor using 'linnumsteps'
        break;

      case 'D': //"DXXXX" received where X is a number 0 to 9
        digitalWrite(lindirpin, HIGH);
        server.println("Going DOWN. ");

        char lintempSteps[5]; //This is a string used to convert the buffer elements into a 4 long number "XXXX"
        for (int i = 1; i < 5; i++) //This loop confirms the XXXX is a number and then stores into the lintempsteps variable
        {
          if (lineBuffer[i] >= '0' && lineBuffer[i] <= '9')
          {
            lintempSteps[i - 1] = lineBuffer[i];
          }
          else
          {
            server.println("Invalid Lin Angle");
            break;
          }
        }
        linnumofsteps = atoi(lintempSteps);
        server.print("Valid Lin Angle Received = "); //This simple informs the client that a valid move command was received.
        server.print(linnumofsteps);
        server.println(" Degrees.");
        linmoveMotor(); //Moves the motor using 'linnumsteps'
        break;

      case 'T':
        char tempDelay[5];
        for (int i = 1; i < 5; i++)
        {
          if (lineBuffer[i] >= '0' && lineBuffer[i] <= '9')
          {
            tempDelay[i - 1] = lineBuffer[i];
          }
          else
          {
            server.println("Invalid Time Delay");
            break;
          }
        }
        TimeDelay = atoi(tempDelay);
        server.print("Valid Rotary Time Delay Received = ");
        server.print(TimeDelay);
        server.println(" Milliseconds.");
        break;

      case 'S':
        char lintempDelay[5];
        for (int i = 1; i < 5; i++)
        {
          if (lineBuffer[i] >= '0' && lineBuffer[i] <= '9')
          {
            lintempDelay[i - 1] = lineBuffer[i];
          }
          else
          {
            server.println("Invalid Time Delay");
            break;
          }
        }
        linTimeDelay = atoi(lintempDelay);
        server.print("Valid Linear Time Delay Received = ");
        server.print(linTimeDelay);
        server.println(" Milliseconds.");
        break;

      case 'R':
        digitalWrite(dirpin, HIGH);
        server.println("Going CW");
        char tempSteps[5];
        for (int i = 1; i < 5; i++)
        {
          if (lineBuffer[i] >= '0' && lineBuffer[i] <= '9')
          {
            tempSteps[i - 1] = lineBuffer[i];
          }
          else
          {
            server.println("Invalid Angle");
            break;
          }
        }
        numofsteps = atoi(tempSteps);
        server.print("Valid Angle Received = ");
        server.print(numofsteps);
        server.println(" Degrees.");
        moveMotor();
        break;

      case 'L':
        digitalWrite(dirpin, LOW);
        server.println("Going CCW");    
        char tempSteps[5];
        for (int i = 1; i < 5; i++)
        {
          if (lineBuffer[i] >= '0' && lineBuffer[i] <= '9')
          {
            tempSteps[i - 1] = lineBuffer[i];
          }
          else
          {
            server.println("Invalid Angle");
            break;
          }
        }
        numofsteps = atoi(tempSteps);
        server.print("Valid Angle Received = ");
        server.print(numofsteps);
        server.println(" Degrees.");
        moveMotor();
        break;

      default:
        server.println("Default");
        break;

      }
    }
  }  
}

void moveMotor()
{
  server.print("Taking ");
  angle = (4.4444 * numofsteps);
  server.print(angle);
  server.println(" Lines.");


  for (int i = 0; i<angle; i++)
  {
    digitalWrite(steppin, HIGH);
    delayMicroseconds(TimeDelay); //The delay helps prevent this motor from skipping steps. This variable must be set for each motor via testing.
    digitalWrite(steppin, LOW);
    delayMicroseconds(TimeDelay); //The delay helps prevent this motor from skipping steps. This variable must be set for each motor via testing.
  }
  server.println("Move Complete.");
}

void linmoveMotor()
{
  server.print("Taking ");
  linangle = (4.4444 * linnumofsteps);
  server.print(linangle);
  server.println(" Lines.");


  for (int i = 0; i<linangle; i++)
  {
    digitalWrite(linsteppin, HIGH);
    delayMicroseconds(linTimeDelay); //The delay helps prevent this motor from skipping steps. This variable must be set for each motor via testing.
    digitalWrite(linsteppin, LOW);
    delayMicroseconds(linTimeDelay); //The delay helps prevent this motor from skipping steps. This variable must be set for each motor via testing.
  }
  server.println("Move Complete.");
}
9  Forum 2005-2010 (read only) / Syntax & Programs / Re: Help! I can't find the error in my code! on: February 09, 2009, 06:50:49 pm
Yup, switching to version 13 did it. Now it is working correctly.
10  Forum 2005-2010 (read only) / Syntax & Programs / Re: Help! I can't find the error in my code! on: February 09, 2009, 06:23:57 pm
Version 12...  smiley

I'll try switching tomorrow and i'll see if it takes care of it.
11  Forum 2005-2010 (read only) / Syntax & Programs / Re: Help! I can't find the error in my code! on: February 09, 2009, 05:20:55 pm
Good spot. I changed the code to use pin 8 for the linear direction pin. Oddly, I am still unable to switch the pin. It is always at the "low" setting even when I send the command "KB". It displays the "going backward" line but does not actually change.

any ideas?
12  Forum 2005-2010 (read only) / Syntax & Programs / Re: Help! I can't find the error in my code! on: February 09, 2009, 01:40:03 pm
Also, another note on this. When I do command pin 11 to change, it briefly drops voltage but then returns right back to the 3.86V.
13  Forum 2005-2010 (read only) / Syntax & Programs / Re: Help! I can't find the error in my code! on: February 09, 2009, 01:38:26 pm
Yes. I am using pin 11. There are actually two motors being ran through the Arduino (a regular stepper & a hybrid linear stepper). The linear stepper variables are prefixed with lin. Lindirpin (Lin = Linear, Dir = direction, pin = pin) is the one that is not working right.

The variable dirpin works fine though.

Sorry for not fully commenting the code. smiley
14  Forum 2005-2010 (read only) / Syntax & Programs / Help! I can't find the error in my code! on: February 09, 2009, 01:20:14 pm
I have just begun programming the Arduino and it's quite a blast. However, I have run into a problem somewhere in my code. I have created a little program which receives commands over a TCP/IP protocol, using the arduino ethernet shield, and then commands two stepper motor drivers.

The problem is that I cannot seem to get pin 11 (the direction on the linear stepper motor to change). It sits at 3.86V. Everything else works wonderfully.

I modified a basic blink program to check if the pin was working and I could get it to switch between high and low without any problems. So, that makes me think that it is somewhere in the code. Any suggestions?

Code:
/*
 * Ethernet-Stepper Server
 *
 * This program functions as a server which receives commands from a client and sends pulses to
 * a stepper motor based upon the received command. The program also sends back information reporting
 * the actions it has taken. A EasyDriver v3 is attached to pins 2 & 3.
 * The command set as received through the ethernet shield is as follows:
 * "SXXXX" = S plus four digits produces a step of XXXX degrees. Ex. S0360 is one rotation
 * "TXXXX" = T plus four digits sets the delay between each step in milliseconds. Default is 150. EX T0300 sets a 300 millisecond delay
 * "DX" = D plus either R or L sets the direction of the stepper motor.
 * "LXXXX" = L plus four digits produces a step of XXXX degrees in the linear motor.
 * "KX" = K plus F or B sets the direction of the linear motor. Forward or backward.
 * "JXXXX" = sets the linear motor delay in milliseconds
 */

#include <Ethernet.h>

// network configuration.  gateway and subnet are optional.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 254, 39 };

// telnet defaults to port 23
Server server = Server(23);
int dirpin = 7; //The stepper direction is set by this pin
int steppin = 6; //The stepper motion is controlled by pulses on this pin.
int linsteppin = 9;
int lindirpin = 11;
int angle = 0;
int linangle = 0;
int numofsteps = 0;
int linnumofsteps = 0;
int TimeDelay = 150; //This is the stepper motor's delay parameter
int linTimeDelay = 1000; //This is the linear motor's delay parameter.

void setup()
{
  // initialize the ethernet device
  Ethernet.begin(mac, ip);
  // start listening for clients
  server.begin();
  
  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  pinMode(linsteppin, OUTPUT);
  pinMode(lindirpin, OUTPUT);
  digitalWrite(dirpin, HIGH); //Set default direction
  digitalWrite(lindirpin, LOW);
  
}

void loop()
{
  Client client = server.available();
  if (client)
  {
    boolean messageComplete = false;
    long timeOut = millis();
    char lineBuffer[100]; // large buffer for storing data
    int charCount;
  
    while (!messageComplete || server.available())
    {
      if ((abs(millis() - timeOut)) > 2000)
      {
        server.println("Timeout On Response");
        break;
      }
      if (server.available())
      {
        lineBuffer[charCount] = client.read();
        if (lineBuffer[charCount] == 13) //Waits for a carriage return
        {
          messageComplete = true;
        }
        charCount++;
        delay(50);
      }
    }

    if (messageComplete)
    {
      switch (lineBuffer[0])
      {
        case 'D':
          if (lineBuffer[1] == 'R')
          {
            digitalWrite(dirpin, HIGH);
            server.println("Going CW");
          }
          else if (lineBuffer[1] == 'L')
          {
            digitalWrite(dirpin, LOW);
            server.println("Going CCW");
           }
          break;
        case 'K':
          if (lineBuffer[1] == 'F')
          {
            digitalWrite(lindirpin, LOW);
            server.println("Going Forward");
          }
          else if (lineBuffer[1] == 'B')
          {
            digitalWrite(lindirpin, HIGH);
            server.println("Going Backward");
           }
          break;

          case 'T':
            char tempDelay[5];
          for (int i = 1; i < 5; i++)
          {
            if (lineBuffer[i] >= '0' && lineBuffer[i] <= '9')
            {
              tempDelay[i - 1] = lineBuffer[i];
            }
            else
            {
              server.println("Invalid Time Delay");
              break;
            }
          }
          TimeDelay = atoi(tempDelay);
          server.print("Valid Rotary Time Delay Received = ");
          server.print(TimeDelay);
          server.println(" Milliseconds.");
          break;
            
            case 'J':
            char lintempDelay[5];
          for (int i = 1; i < 5; i++)
          {
            if (lineBuffer[i] >= '0' && lineBuffer[i] <= '9')
            {
              lintempDelay[i - 1] = lineBuffer[i];
            }
            else
            {
              server.println("Invalid Time Delay");
              break;
            }
          }
          linTimeDelay = atoi(lintempDelay);
          server.print("Valid Linear Time Delay Received = ");
          server.print(linTimeDelay);
          server.println(" Milliseconds.");
          break;
        case 'S':
          char tempSteps[5];
          for (int i = 1; i < 5; i++)
          {
            if (lineBuffer[i] >= '0' && lineBuffer[i] <= '9')
            {
              tempSteps[i - 1] = lineBuffer[i];
            }
            else
            {
              server.println("Invalid Angle");
              break;
            }
          }
          numofsteps = atoi(tempSteps);
          server.print("Valid Angle Received = ");
          server.print(numofsteps);
          server.println(" Degrees.");
          moveMotor();
          break;

            case 'L':
          char lintempSteps[5];
          for (int i = 1; i < 5; i++)
          {
            if (lineBuffer[i] >= '0' && lineBuffer[i] <= '9')
            {
              lintempSteps[i - 1] = lineBuffer[i];
            }
            else
            {
              server.println("Invalid Lin Angle");
              break;
            }
          }
          linnumofsteps = atoi(lintempSteps);
          server.print("Valid Lin Angle Received = ");
          server.print(linnumofsteps);
          server.println(" Degrees.");
          linmoveMotor();
          break;
        default:
          server.println("Default");
          break;
      }
    }
  }  
}

void moveMotor()
{
  server.print("Taking ");
  angle = (4.4444 * numofsteps);
  server.print(angle);
  server.println(" Lines.");
    
    
  for (int i = 0; i<angle; i++)
  {
    digitalWrite(steppin, HIGH);
    delayMicroseconds(TimeDelay); //The delay helps prevent this motor from skipping steps. This variable must be set for each motor via testing.
    digitalWrite(steppin, LOW);
    delayMicroseconds(TimeDelay); //The delay helps prevent this motor from skipping steps. This variable must be set for each motor via testing.
  }
  server.println("Move Complete.");
}

void linmoveMotor()
{
  server.print("Taking ");
  linangle = (4.4444 * linnumofsteps);
  server.print(linangle);
  server.println(" Lines.");
    
    
  for (int i = 0; i<linangle; i++)
  {
    digitalWrite(linsteppin, HIGH);
    delayMicroseconds(linTimeDelay); //The delay helps prevent this motor from skipping steps. This variable must be set for each motor via testing.
    digitalWrite(linsteppin, LOW);
    delayMicroseconds(linTimeDelay); //The delay helps prevent this motor from skipping steps. This variable must be set for each motor via testing.
  }
  server.println("Move Complete.");
}
15  Forum 2005-2010 (read only) / Development / Re: Stepper Motor with EasyDrive V3 on: December 24, 2008, 10:44:57 am
Not sure this is exactly the right place for it, but I've written some code that takes input via an "official" ethernet shield and then steps a stepper motor with the easydrive V3. I am not a programmer, in fact I'd never programmed till about 3 months ago (mechanical engr by trade), but the code functions.
Code:
/*
 * Ethernet-Stepper Server
 *
 * This program functions as a server which receives commands from a client and sends pulses to
 * a stepper motor based upon the received command. The program also sends back information reporting
 * the actions it has taken. A EasyDriver v3 is attached to pins 2 & 3.

 */

#include <Ethernet.h>

// network configuration.  gateway and subnet are optional.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 254, 39 };
//byte gateway[] = { 10, 0, 0, 1 };
//byte subnet[] = { 255, 255, 0, 0 };

// telnet defaults to port 23
Server server(23);
int dirpin = 2; 'The stepper direction is set by this pin
int steppin = 3; 'The stepper motion is controlled by pulses on this pin.
int angle = 0;
int numofsteps = 0;
void setup()
{
  // initialize the ethernet device
  Ethernet.begin(mac, ip);
  
  // start listening for clients
  server.begin();
  
  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  Client client = server.available();
  if (client)
    {
      
      int passed = client.read();
      server.println(passed);
      if (passed == 76) // This is the ASCII for L (CounterClockwise)
        {
          digitalWrite(dirpin, LOW);
          server.println("Going CCW");
        }
        else
        {
          if (passed == 82) //This is the ASCII for R
          {
              digitalWrite(dirpin, HIGH);
              server.println("Going CW");
          }
          else
            {
             switch (passed)
             {
                case 97: //the letter 'a'
                    {
                    numofsteps = 8; //1.8 degrees
                    angle = 18;
                    break;
                    }
                case 98: //the letter 'b'
{
                    numofsteps = 20; //4.5 degrees
                    angle = 45;
                    break;
}
                case 99: //the letter 'c'
 {
                    numofsteps = 40; //9 degrees
                    angle = 90;
                    break;}
                case 100: //the letter 'd'
{                   numofsteps = 160; //36 degrees
                    angle = 360;
                    break;}
                case 101: //the letter 'e'
{                   numofsteps = 200; //45 degrees
                    angle = 450;
                    break;}
                case 102: //the letter 'f'
{                   numofsteps = 400; //90 degrees
                    angle = 900;
                    break;}
                case 103: //the letter 'g'
{                   numofsteps = 800; //180 degrees
                    angle = 1800;
                    break;}
                case 104: //the letter 'h'
{                   numofsteps = 1600; //360 degrees
                    angle = 3600;
                    break;}
                default:
{                   numofsteps = 0; //zero degrees
                    angle = 0;
                    break;}
             }

             server.print("Taking ");
             server.print(angle);
             server.println(" Lines.");
 
              int i;
    
             delay(10); 'The delay helps prevent this motor from skipping steps. This variable must be set for each motor via testing.
    
            for (i = 0; i<numofsteps; i++)
              {
               digitalWrite(steppin, HIGH);
               delayMicroseconds(150); 'The delay helps prevent this motor from skipping steps. This variable must be set for each motor via testing.
               digitalWrite(steppin, LOW);
               delayMicroseconds(150); 'The delay helps prevent this motor from skipping steps. This variable must be set for each motor via testing.
              }
             }
            
        }
   }
}
Pages: [1] 2