我使用LiveCharts和串口数据绘制线图。我从另一个类中获取了数据,同时图形函数在它自己的单独类中。我试图让串口的数据与我的X轴相等。这是我的代码:
图形代码:
public ChartValues<ChartDataPoints> Values { get; set; }
public GraphControl()
{
InitializeComponent();
//Mapper
var mapper = Mappers.Xy<ChartDataPoints>()
.X(model => model.Session)
.Y(model => model.Value);
Charting.For<ChartDataPoints>(mapper);
Values = new ChartValues<ChartDataPoints>();
var _session = new Stopwatch();
_session.Start();
//Task
Task.Run(() =>
{
while (true)
{
Thread.Sleep(30);
//we add the lecture based on our StopWatch instance
Values.Add(new ChartDataPoints
{
Session = _session.ElapsedMilliseconds,
Value = 1 //This needs to be replaced with data from the Serial port!!
});
}
});
DataContext = this;
}
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName = null)
{
if (PropertyChanged != null)
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
ChartDataPoints类:
public class ChartDataPoints
{
public double Session { get; set; }
public double Value { get; set; }
}
这是我的SerialPort类:(它在一个名为Hardware的独立项目中。)
public ForceCellData()
{
try
{
string _port3 = "COM3";
SerialPort defaultSerial = new SerialPort(_port3);
defaultSerial.BaudRate = 9600;
defaultSerial.Parity = Parity.None;
defaultSerial.StopBits = StopBits.One;
defaultSerial.DataBits = 8;
defaultSerial.Handshake = Handshake.None;
defaultSerial.RtsEnable = true;
defaultSerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
defaultSerial.Open();
}
catch
{
Console.WriteLine("Could not connect to COM3!");
}
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(200);
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
indata = indata.Trim().Replace("\r", string.Empty);
indata = indata.Trim().Replace("\n", string.Empty);
indata = indata.Trim().Replace("-", string.Empty);
var split = indata.Split('.');
foreach (var stringData in split)
{
if (!string.IsNullOrWhiteSpace(stringData) && double.TryParse(stringData, out double convertdata))
{
double Xdata;
Xdata = convertdata; //Don't know what to do here...
}
}
}
}
那么我缺少什么能够从串口获取数据等于变量值?那么图表将绘制来自串口的数据?
答案 0 :(得分:0)
如果你有2个单独的项目,那么你需要它们之间的某种形式的连接,也可以在某个地方的图形代码中引用SerialPort类,否则你希望如何访问indata。
否则,如果您不想激活绘图,则将ForceCellData中的数据保存在txt文件中,然后从中读取并在以后使用图形代码绘制它。