InSim之间的串口连接丢失.. NET和arduino
本文关键字:NET arduino 连接 之间 串口 InSim | 更新日期: 2023-09-27 17:54:25
我尝试使用InSim制作应用程序。. NET将数据包从udp重定向到arduino连接的串行端口,但遇到了一个问题。
正确传输几秒钟后,连接断开。控制台的数字和arduino显示停止刷新。我不知道问题出在哪里。请帮助
这是我的c#代码:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using InSimDotNet.Out;
namespace dotnet
{
class Program
{
static void Main()
{
TimeSpan timeout = TimeSpan.FromSeconds(10);
SerialPort serialport = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
serialport.Open();
// Create OutGauge object with the specified timeout.
using (OutGauge outgauge = new OutGauge())
{
// Attach event handler to packet-received event.
outgauge.PacketReceived += (sender, e) =>
{
Console.Clear();
//String command = 'S' + speed.ToString("D3") + ''r';
int speed = Convert.ToInt32(e.Speed * 3.6);
int rpm = Convert.ToInt32(e.RPM);
String command = "S " + speed.ToString("D3") + "'r" + "R " + rpm.ToString("D4") + "'r";
Console.Write(command);
serialport.Write(command);
};
outgauge.TimedOut += outgauge_TimedOut;
// Start listening for packets from LFS.
outgauge.Connect("127.0.0.1", 30001);
// Stop program from exiting while listening.
Console.ReadLine();
}
serialport.Close();
}
static void outgauge_TimedOut(object sender, EventArgs e)
{
Console.WriteLine("OutGauge timed out!");
}
}
}
和arduino代码:
#include <Messenger.h>
#include <LiquidCrystal.h>
#define LCD_LINES 2
#define LCD_ROWS 16
Messenger message;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void sendVersion()
{
Serial.println(F("AD 01.12 ArduDash"));
}
void sendOK()
{
Serial.println(F("OK"));
}
void sendERROR()
{
Serial.println(F("ERROR"));
}
void setSpeedLCD(int speed)
{
lcd.setCursor(0, 0);
lcd_rjust_number(speed, 3);
lcd.print(F(" km/h"));
}
void setSpeed()
{
int speed = message.readInt();
if (speed < 3 || speed > 230)
{
sendERROR();
speed=0;
}
//setSpeedServo(speed);
setSpeedLCD(speed);
sendOK();
}
void lcd_rjust_number(int num, byte length)
{
if (num < 10)
{
lcd.print(F(" "));
}
if (num < 100)
{
lcd.print(F(" "));
}
if (num < 1000 && length == 4)
{
lcd.print(F(" "));
}
lcd.print(num);
}
void setRPM()
{
int rpm = message.readInt();
if (rpm > 10000 || rpm < 0)
{
sendERROR();
return;
}
setRPMLCD(rpm);
sendOK();
}
void setRPMLCD(int rpm)
{
lcd.setCursor(0, 1);
byte progress_width = map(rpm, 0, 10000, 0, 10);
for (byte x=0; x<10; x++)
{
if (x < progress_width)
{
lcd.print(F("#"));
}
else
{
lcd.print(F(" "));
}
}
lcd.print(" ");
lcd_rjust_number(rpm, 4);
}
void onMessage()
{
switch (message.readChar())
{
case 'S':
setSpeed();
break;
case 'R':
setRPM();
break;
}
Serial.flush();
}
void serialEvent()
{
message.process(Serial.read());
}
void setup()
{
Serial.begin(9600);
message.attach(onMessage);
lcd.begin(LCD_ROWS, LCD_LINES);
}
void loop()
{
// put your main code here, to run repeatedly:
}
我会尝试将SeriarlEvent代码更改为
while ( Serial.available() ) message.process(Serial.read () );