@mIka01

Как отправить значений по SerialPort в Arduino с помощью c#?

Здраствуйте, помогите решить вроде простую задачу.
У меня микроконтроллер Iskra Neo.
Необходимо из textBox передать информацию по SerialPort в Arduino. Всего 4 переменные.
Я глупый или как но у меня это не получается.

Лучше предложите свой код.

Мой код. Нерабочий.
Библиотеки.
using System.Threading;
using System.IO.Ports;

Код.
SerialPort port;
            int timeout = 100;
            port = new SerialPort("COM7", 9600);
            port.Open();
            port.ReadTimeout = timeout;

            textBox3.Text = "Начало";
            port.WriteLine(textBox1.Text);
            while (port.BytesToRead <= 0) { Thread.Sleep(1000); }
            port.WriteLine(textBox2.Text);
            while (port.BytesToRead <= 0) { Thread.Sleep(1000); }
            port.WriteLine(textBox6.Text);
            while (port.BytesToRead <= 0) { Thread.Sleep(1000); }
            port.WriteLine(textBox5.Text);
            while (port.BytesToRead <= 0) { Thread.Sleep(1000); }
            textBox3.Text = "Конец";
            Thread.Sleep(1000);
            textBox3.Text = "Заново";

6080609fdf3d5629122350.png
Arduino.
void setup() {
      Serial.begin(9600);
      Serial.setTimeout(100);
}

void loop() {
  
  int arr[4];
  int i = 0;
  while (i < 4) {
    if (Serial.available()) {
    arr[i] = Serial.parseInt(); 
    Serial.println("ещё");  
    i++;    
    }
  }   
  turn(arr[0], arr[1], 1, 2, 3, 4, 18); 
  turn(arr[2], arr[3], 6, 7, 8, 9, 18); 
}

Функция.
void turn(int a, int velocity, byte shim, byte in1, byte in2, int encoderIn, int holes)
{
  int detectState = 0;
  bool freq;
  int longer = 0;

  pinMode(encoderIn, INPUT);
  detectState = digitalRead(encoderIn);
  freq = detectState;

  bool executed = true;
  int tics = (abs(a) * 2) / (360 / holes);

  pinMode( shim, OUTPUT );
  pinMode( in1, OUTPUT );
  pinMode( in2, OUTPUT );
  analogWrite( shim, velocity );

  if (a < 0) {
    digitalWrite( in1, HIGH );
    digitalWrite( in2, LOW );
  } else {
    digitalWrite( in1, LOW );
    digitalWrite( in2, HIGH );
  }



  while (executed) {
    detectState = digitalRead(encoderIn);

    if (detectState != freq) {
      longer++;
      freq = detectState;
    }

    if (longer > tics) {
      digitalWrite( in1, LOW );
      digitalWrite( in2, LOW );
      executed = false;
    }

  }

}


Однако если у кого-то может сложится мнение, что не работает turn то вы ошибаетесь.
Вот как пример рабочего кода.
void setup() {
      Serial.begin(9600);
      Serial.setTimeout(100);
}

void loop() {
  while (true) {
    if (Serial.available()) {
       turn(Serial.parseInt(), 255, 1, 2, 3, 4, 18); 
       goto d;
    }
  }   
d:{}
}

turn из предыдущего кода.

SerialPort port;
            int timeout = 100;
            port = new SerialPort("COM7", 9600);
            port.Open();
            port.ReadTimeout = timeout;
            port.WriteLine(textBox1.Text);


Заранее благодарю.
  • Вопрос задан
  • 419 просмотров
Решения вопроса 1
@mIka01 Автор вопроса
У меня получилось так .
Arduino.
Serial.begin(9600);
      Serial.setTimeout(100);
    while (true) {
    if (Serial.available()) {   
    turn(Serial.parseInt(), 100, 2, 3, 4, 5, 18);
    goto g0;
    }
  }   
   g0:
   {}

А код для c#.
SerialPort port;
            port = new SerialPort("COM12", 9600);

            port.Open();            
            port.WriteLine(textBox1.Text);
            port.Close();
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
Выход за границы массива:
int arr[4];
....
while (i < 5)


ну и goto d; лучше вообще не использовать, тем более в вашем примере. Простого break; более чем достаточно.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы