engrmonkey
engrmonkey

Reputation: 33

Arduino code does not read input from C#

My C# code sends a signal to the arduino for the servo motor to start running, but when I run my code there is no response from the arduino and the servo motor does not start. If I use the serial monitor in the arduino IDE, the arduino and the servo motor works perfectly. what is wrong?

Here is my code:

 string dir = " ";
        string distance;
        string result = " ";

        string port1 = "COM12";
        int baudRatePort1 = 9600;
        SerialPort arduino1 = new SerialPort(port1, baudRatePort1);

        string port2 = "COM8";
        int baudRatePort2 = 115200;
        SerialPort arduino2 = new SerialPort(port2, baudRatePort2);

        Console.WriteLine("Enter Direction:\n");
        dir = Console.ReadLine();


        if (dir == "S")
        {
            Console.WriteLine("Enter Distance:\n");
            distance = Console.ReadLine();
            arduino2.Open();
            if (arduino2.IsOpen)
            {
                try
                {
                    arduino2.WriteLine(distance.ToString());
                    result = arduino2.ReadLine();
                    string[] words = result.Split('\r');

                    foreach (string word in words)
                    {
                        result = word;
                        break;
                    }
                    arduino1.Open();
                    if (arduino1.IsOpen)
                    {
                        try
                        {
                            arduino1.WriteLine("S");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Arduino connecting Servo is in problem");
                        }
                    }
                    while (result != distance)
                    {
                        if (result != "ON")
                        {
                            result = arduino2.ReadLine();
                            Console.WriteLine(result);

                            words = result.Split('\r');

                            foreach (string word in words)
                            {
                                result = word;
                                break;
                            }
                            result = arduino1.ReadLine();
                            Console.WriteLine(result);
                        }
                        else
                        {
                            Console.WriteLine("Please Excuse Me!");
                        }

                    }
                    arduino1.WriteLine("P");
                    arduino1.Close();
                    arduino2.Close();
                    Console.WriteLine("Finish");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Arduino connecting LRF is in problem does not open");
                }
            }
        }
        else if(dir == "R")
        {
            arduino1.Open();

            if(arduino1.IsOpen)
            {
                try
                {
                    arduino1.WriteLine("R");
                    result = arduino1.ReadLine();
                    string[] words = result.Split('\r');

                    foreach (string word in words)
                    {
                        result = word;
                        break;
                    }
                    while (result != "F")
                    {
                        result = arduino1.ReadLine();
                        words = result.Split('\r');

                        foreach (string word in words)
                        {
                            result = word;
                            break;
                        }
                    }
                    arduino1.WriteLine("P");
                    arduino1.Close();
                    Console.WriteLine("Finish");
                }
                catch(Exception e)
                {
                    Console.WriteLine("Problem in arduino connecting servo");
                }
            }
        }
        else if (dir == "L")
        {
            arduino1.Open();

            if (arduino1.IsOpen)
            {
                try
                {
                    arduino1.WriteLine("L");
                    result = arduino1.ReadLine();
                    string[] words = result.Split('\r');

                    foreach (string word in words)
                    {
                        result = word;
                        break;
                    }
                    while (result != "F")
                    {
                        result = arduino1.ReadLine();
                        words = result.Split('\r');

                        foreach (string word in words)
                        {
                            result = word;
                            break;
                        }
                    }
                    arduino1.WriteLine("P");
                    arduino1.Close();
                    Console.WriteLine("Finish");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Problem in arduino connecting servo");
                }
            }
        }

Port 2 is for the laser range finder which works perfectly.

For the arduino code which is in port1:

  #include <Servo.h>
  #include <Wire.h>
  #include <MPU6050.h>

  MPU6050 mpu;

  Servo servoLeft;
  Servo servoRight;

  unsigned long timer = 0;
  float timeStep = 0.01;

  //Pitch, Roll, Yaw values
  float yaw = 0;

  char dir; //direction to be travelled
  int hold = 0;
  int gyroVal = 0;

  void setup()
  {
    Serial.begin(9600);
    servoRight.attach(9); //BLUE SERVO
    servoLeft.attach(8); //YELLOW SERVO

     while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
    {
      Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
      delay(500);
    }

    // Calibrate gyroscope. The calibration must be at rest.
    // If you don't want calibrate, comment this line.
    mpu.calibrateGyro();

    // Set threshold sensivty. Default 3.
    // If you don't want use threshold, comment this line or set 0.
    mpu.setThreshold(3);
  }

  void loop() 
  {
    timer = millis();
    int gyroYaw = readGyro();
    //Serial.println(dir);
    while(Serial.available()>0)
    {
      dir = Serial.read();
    }

    Stop();
    Serial.println(dir);
    if(dir == 'S')
    {

     // Serial.print(gyroYaw);
        //Serial.print (hold);
       // Serial.println();
        //delay(1000);
      if(gyroYaw >= 1)
      {
        adjustToRight();
      //  Serial.println("Adjust Right");
       // Serial.print (hold);
        //Serial.println();
        //delay(1000);
        //Forward();
        /*if(gyroYaw=1)
        {
          hold = 1;
        }
        else if(gyroYaw<=-0)
        {
          hold = 2;
        }
        else
        {
          hold = 0;
        }*/
      }
      else if(gyroYaw<=-1)
      {
        //Serial.println("Adjust Left");
        adjustToLeft();
      }
      else
      {
        //Serial.println("forward");
        Forward();
      }

     /* if(hold = 1)
      {
        Serial.print(gyroYaw);
        Serial.print (hold);
        Serial.println();
        delay(1000);
        //adjustToLeft();
        if(gyroYaw == 0)
        {
          hold = 0;
        }
      }

      if(hold = 2)
      {
        Serial.print(gyroYaw);
        Serial.print (hold);
        Serial.println();
        delay(1000);
       // adjustToRight();
        if(gyroYaw == 0)
        {
          hold = 0;
        }
      }*/
    }
    else if(dir == 'R')
    {
      TurnRight();
    }
    else if(dir == 'L')
    {
      TurnLeft();
    }
    else
    {
      Stop();
    }
  }
  void Stop()
  {
    servoRight.write(0);
    servoLeft.write(0);
  }
  void Forward()
  {
    servoRight.write(50);
    servoLeft.write(96.9);
  }
  void TurnRight()
  {
      servoLeft.write(170);
      servoRight.write(180);
      delay(2200);
      Stop();
      Serial.println("F");
  }
  void TurnLeft()
  {
    servoLeft.write(80);
    servoRight.write(30);
    delay(2200);
    Stop();
    Serial.println("F");
  }
  void adjustToRight()
  {
    servoRight.write(100);
    servoLeft.write(100);
    //delay(1500);
  }
  void adjustToLeft()
  {
    servoRight.write(50);
    servoLeft.write(70);
  }

  int readGyro()
  {
     // Read normalized values
    Vector norm = mpu.readNormalizeGyro();

    // Calculate Pitch, Roll and Yaw
    yaw = yaw + norm.ZAxis * timeStep;

    //Serial.println(yaw);
    // Wait to full timeStep period
    delay((timeStep*1000) - (millis() - timer));
    return ((int)yaw);
  }

Thank you!

Upvotes: 1

Views: 599

Answers (2)

lumos0815
lumos0815

Reputation: 4326

you are sending utf16 strings that end with \r\n -> so you are sending 4 bytes of data. on the arduino site you read the data in a while loop and take only the last byte. so you are always reading \n

Upvotes: 0

user3704293
user3704293

Reputation: 1056

I think it would be easier to answer your question if we break down the code to a simple bidirectional communication problem between Arduino and C#.

For a stable communication between Arduino and C# there are several libraries available, which simplifies the communication, such as SolidSoils4Arduino and CmdMessenger and have additionally comprehensive examples. Furthermore, there are already some similar questions (e.g Recieve and send data from arduino to c# and vice versa) on stackoverflow.

I hope this helps you to check and improve your code and integrate your motor control.

Upvotes: 2

Related Questions