Arduino代码不读取C#的输入

时间:2015-05-08 06:50:40

标签: c# arduino arduino-uno

我的C#代码向arduino发送信号,伺服电机开始运行,但是当我运行代码时,arduino没有响应,伺服电机无法启动。如果我在arduino IDE中使用串行监视器,则arduino和伺服电机可以完美地工作。怎么了?

这是我的代码:

 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");
                }
            }
        }

端口2用于激光测距仪,可以很好地工作。

对于port1中的arduino代码:

  #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);
  }

谢谢!

2 个答案:

答案 0 :(得分:2)

如果我们将代码分解为Arduino和C#之间的简单双向通信问题,我认为回答您的问题会更容易。

为了在Arduino和C#之间进行稳定的通信,有几个可用的库,这简化了通信,例如SolidSoils4ArduinoCmdMessenger,还有其他全面的示例。此外,stackoverflow上已经存在一些类似的问题(例如Recieve and send data from arduino to c# and vice versa)。

我希望这有助于您检查和改进代码并集成电机控制。

答案 1 :(得分:0)

您发送的utf16字符串以\ r \ n - &gt;结尾所以你要发送4个字节的数据。 在arduino网站上,你在while循环中读取数据,只取最后一个字节。所以你总是在阅读\ n