Click here to Skip to main content
15,905,028 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
C++

Hello All,

I am trying to control a stepper motor through arduino using C#. The program works perfectly fine at the first instance. But when i launch the program at the second instance it fails.

I have tried to integrate the autodetect function (http://playground.arduino.cc/Csharp/SerialCommsCSharp) and stepper control code together. But there is some issue in the code which lets it run perfectly only once. Kindly help me to solve the issue.

C#
/*

 * Serial Port Monitor
 *
 *
 */

//Setup Output
// int ledPin_3 = 3;
#include <Stepper.h>
//#include <SoftwareSerial.h>
//SoftwareSerial mySerial(0, 1);
int out1 = 8;
int out2 = 9;
int enA  = 6;
int enB  = 11;
int dirA = 5;
int dirB = 3;
int steps=0;
int inbyte;
int dela_time;
int frm_cnt=0;
int serialdata;
int rotmode;
int rotdir;
int motspeed;    // assigning the motor speed

//int frames;
const int stepsperrev = 8000;      // No. of micro steps per revolution
Stepper myStepper(stepsperrev, out1, dirA, out2, dirB);

//Setup message bytes

byte inputByte_0;

byte inputByte_1;

byte inputByte_2;

byte inputByte_3;

byte inputByte_4;

//byte inputByte_5;

//Setup
int ledPin_3 =13;

void setup() {

  pinMode(ledPin_3, OUTPUT);
  Serial.begin(9600);
  digitalWrite(ledPin_3, HIGH);//
  delay(2500);//
  digitalWrite(ledPin_3, LOW);//
  delay(2500);//
  pinMode(enA, OUTPUT);
  digitalWrite (enA, HIGH);
  pinMode(enB, OUTPUT);
  digitalWrite (enB, HIGH);
  Serial.begin(9600);

}


void newsetup()
{
  pinMode(enA, OUTPUT);
  digitalWrite (enA, HIGH);
  pinMode(enB, OUTPUT);
  digitalWrite (enB, HIGH);

}
void reset()
{
  digitalWrite (out1, LOW);
  digitalWrite (dirA, LOW);
  digitalWrite (out2, LOW);
  digitalWrite (dirB, LOW);
  digitalWrite (enA, LOW);
  digitalWrite (enB, LOW);
  steps=0;
  frm_cnt=0;
}

void getinput()

{
  //******************************************

 //Get the delay time
getSerial();
dela_time = serialdata;
//Serial.println(dela_time);

// Get rotation mode
getSerial();
rotmode = serialdata;
//Serial.println(rotmode);

// Get direction of rotation
getSerial();
rotdir = serialdata;
//Serial.println(rotdir);

// Get motor speed
getSerial();
motspeed = serialdata;
//Serial.println(motspeed);

// Get number of frames
getSerial();
steps = serialdata;
//Serial.println(steps);

// ****************************************
}

//Main Loop

void loop() {

    //Read Buffer
  while (Serial.available()==5)
  {
    //Read buffer
    inputByte_0 = Serial.read();
    delay(100);
    inputByte_1 = Serial.read();
    delay(100);
    inputByte_2 = Serial.read();
    delay(100);
    inputByte_3 = Serial.read();
    delay(100);
    inputByte_4 = Serial.read();
  }
  //Check for start of Message
  if(inputByte_0 == 16)
  {
       //Detect Command type
       switch (inputByte_1)
       {
          case 127:
             //Set PIN and value
             switch (inputByte_2)
            {
              case 4:
                if(inputByte_3 == 255)
                {

                  digitalWrite(ledPin_3, HIGH);
                  break;
                }
                else
                {
                  digitalWrite(ledPin_3, LOW);
                  break;
                }
              break;
            }
            break;
          case 128:
            //Say hello
            Serial.println("HELLO");
            break;
        }
        //Clear Message bytes
        inputByte_0 = 0;
        inputByte_1 = 0;
        inputByte_2 = 0;
        inputByte_3 = 0;
        inputByte_4 = 0;
        //Let the PC know we are ready for more data
        delay(1000);
        //Serial.print("-READY TO RECEIVE");



        frm_cnt=0;
        getinput();
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Switch Case statment for Stepped and Continous mode

  switch(rotmode)
  {
      case 1: // Stepped motion
  {

// Switch case statement for Left and Right Motion
    switch (rotdir)
    {
      case 3: // Left motion
      {

        myStepper.setSpeed(motspeed);

    newsetup();

// Looping for a complete cycle
        while (frm_cnt<steps){

            if (frm_cnt<steps)

        {

            if (steps!=0)

                        myStepper.step(-(stepsperrev*4/steps));
                        //
                        //delay(2500);//

            delay(dela_time*1000);

        }
        else
        {
            reset();
        }

                frm_cnt = frm_cnt+1;
            } // End of While loop

        break;
      } // End of Left motion Code

      case 4: // Right motion
      {

        myStepper.setSpeed(motspeed);


        newsetup();
    // While loop for complete Cycle
            while (frm_cnt<steps){
        if (frm_cnt<steps)
        {
            if (steps!=0)
            myStepper.step((stepsperrev*4/steps));

            delay(dela_time*1000);

        }
        else
        {
            reset();
        }
            frm_cnt = frm_cnt+1;
      } // End of While loop

      break;
      } // End of Right motion code
    }

  // End of Stepped motion code
  break;
  }

  case 2: // Continous motion
  {
    break;
  }
  }


// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
           //Clear Message bytes
        //inputByte_0 = 16;
        //inputByte_1 = 0;
        //inputByte_2 = 0;
        //inputByte_3 = 0;
        //inputByte_4 = 0;
        //serialdata = 0;

  }


// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
}

//***************************************************************************

//====================== Get Serial ======================//
 // Get Serial parameters
long getSerial()
{
  serialdata = 0;
  while (inbyte != '/')
  {
    inbyte = Serial.read();
   //Serial.println(inbyte);
    if (inbyte > 0 && inbyte != '/')
    {

      serialdata = serialdata * 10 + inbyte - '0';
    }
  }
  inbyte = 0;
  return serialdata;
}
Posted
Comments
Dave Kreskowiak 4-Nov-15 12:36pm    
You never said what the error message was and exactly when it occurs.
Member 10085925 8-Nov-15 1:00am    
The C# code runs and detects the COM port for the first time but when I relaunch the program the port is not being detected. When I disconnect the USB cable and reconnect it at that instance the program runs fine for the first time, but again fails to detect the USB port when I relaunch it.
Member 10085925 8-Nov-15 0:58am    
C# code used along with the Arduino program
/**********************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
using System.Threading;
using System.Management;




namespace _360_Control
{

//string strmode =

public partial class Form1 : Form
{

SerialPort currentPort; // Create Serial Port
bool portFound; // bool for noting if the serial port has been found
string port_name = ""; // name of the prot, will be set if found in arduino detect function

public Form1()
{

SetComPort(); // Look for the serial port as the program starts
Thread t = new Thread(new ThreadStart(SplashScreen));
t.Start();
Thread.Sleep(4000);

InitializeComponent();
t.Abort();


}
// Splash Screen for the application
public void SplashScreen()
{
Application.Run(new Form2());
}




private void start_Click(object sender, EventArgs e)
{

start.Enabled = false;

String rotmode = ""; // Rotation Mode
String rotdir = ""; // Rotation Direction
String motspeed = ""; // Motor Speed
String frmcount = ""; // No. of Frames
String dela_time = ""; // Delay time between the shoots
String serialstr = ""; // String to send the Serial command

// Button for left direction rotation
if (left_btn.Checked)
{
rotdir = "3";
}
// Button for right direction rotation
if (rgt_btn.Checked)
{
rotdir = "4";
}

// Get the values of motorspeed, number of frames and delay time from the user form
motspeed = mot_speed.Value.ToString();
frmcount = frm_cnt.Value.ToString();
dela_time = delay_time.Value.ToString();


// Concatenate the serial command suitable for arduino
serialstr = dela_time + "/" + rotmode + "/" + rotdir + "/" + motspeed + "/" + frmcount + "/";


//MessageBox.Show(serialstr);


serialPort1.Open();
if (serialPort1.IsOpen)
{

serialPort1.Write(serialstr);
//serialPort1.NewLine = "\n";

}
//serialPort1.DiscardInBuffer();
//serialPort1.DiscardOutBuffer();
serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

serialPort1.Close();

//}

}


private void Form1_Load(object sender, EventArgs e)
{


if (portFound)
{
serialPort1.PortName = port_name; // Assign port name to the serial port
serialPort1.BaudRate = 9600;
sts_lbl.Text = "CONNECTED";
sts_lbl.BackColor = Color.LimeGreen;
}

else // Board not found
{
sts_lbl.Text = "DISCONNECTED";
sts_lbl.BackColor = Color.Red;
MessageBox.Show("USB Not Connected or Driver not Detected.Check for Connection Settings", "Connection Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}

}


// *************************************************************************************
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;
string data = port.ReadExisting();
// check here what data you received, if any
}

//************
[no name] 8-Nov-15 20:52pm    
Classic spaghetti code. Why not separate the serial port stuff into its own class with open, close,read,write methods. Use open/close once in your program (as Dave Kreskowiak suggests) and the rest as required. This will make it much easier to work with and debug. There is tons on the web about how to do this correctly.

1 solution

There's no way for me to test this but don't open then close the serial port every time you write to it. You're opening the port, setting up an event handler and then closing the port. That's not good as setting the event handler is a waste of time and resources since you immediately close the port.

Open the port when your Start button is clicked and leave it open. When you close the application, close AND DISPOSE of the port object.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900