Answer the question
In order to leave comments, you need to log in
Serial not opening on arduino?
In arduino IDE, everything works, but in my program it doesn't. The Tx and Rx LEDs do not flash.
Serial Connection:
Structure
//Структура для передачи данных в поток
public struct COMInfo
{
public readonly string Port;
public readonly int Baud;
public COMInfo(string port, int baud){ this.Port = port; this.Baud = baud; }
}
public void Create()
{
Thread Creator = new Thread(Conect); //Поток для создания Serial
var TimeController = new System.Timers.Timer(2500.00); // Таймер для защиты от долгого создания
//Событие, которое закрывает поток
TimeController.Elapsed += delegate {if (Creator.IsAlive) Creator.IsBackground = false; };
Creator.Start(Info);
//Ожидание
while (Creator.IsAlive) { }
TimeController.Close();
if (Serial != null)
{
//Подписка на событие приёма данных
Serial.DataReceived += Serial_DataReceived;
Serial.WriteTimeout = 500;
Serial.ReadTimeout = 500;
}
}
//Создание экземпляра, открытия Serial
private void Conect(object info)
{
//Получение данных о порте
COMInfo cominfo = (COMInfo)info;
int speed = cominfo.Baud;
string port = cominfo.Port;
lock (this)
{
try
{
Serial = new SerialPort(port, speed);
Serial.Open();
Thread.Sleep(1000); //Ожидание, нужное для подключения к Serial
Serial.Write("Оpen");
}
catch(Exception e)
{
//Вызов события при возникновении ошибки
if (CreatedExceptionEvent != null) CreatedExceptionEvent(this, e);
throw e;
}
}
}
//Эта строчка есть в потоке
//Serial.DataReceived += Serial_DataReceived;
private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);
if (InputData != null) InputData(this, Serial.ReadExisting());
}
private void Reader_InputData(object sender, string e)
{
MainForm.AddText(e);
}
public void AddText(string text) => tbSerial.Text = text;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question