View Single Post
Old 23-12-2012, 06:04 PM   #17
buivanbinh12
Nhập môn đệ tử
 
Tham gia ngày: Dec 2012
Bài gửi: 1
:
BÁC NÀO BIẾT ĐOẠN CODE VẼ ĐỒ THỊ NÀY CHÚ THÍCH CHO EM ÍT

#region Namespace Inclusions
using System;
using System.Linq;
using System.Data;
using System.Text;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using DynamicData.Properties;
using System.Threading;
using System.IO;
using ZedGraph;
#endregion

namespace DynamicData
{
#region Public Enumerations
public enum DataMode { Text, Hex }
public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
#endregion

public partial class frmMain : Form
{
#region Local Variables
// The main control for communicating through the RS-232 port
private SerialPort comport = new SerialPort();
// Various colors for logging info
private Color[] LogMsgTypeColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red };
// Temp holder for whether a key was pressed
//private bool KeyHandled = false;
private Settings settings = Settings.Default;
#endregion

private GraphPane myPane;
private PointPairList m_pointsList;

int flagData = 0;
int flagPoint = 0;
int nIndex = 0;
int inputData1 = 0;
int inputData2 = 0;
// Starting time in milliseconds
int tickStart = 0;
public frmMain()
{
InitializeComponent();

// Restore the users settings
InitializeControlValues();

// Enable/disable controls based on the current state
EnableControls();

// When data is recieved through the port, call this method
comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

button1.Enabled = false;
button2.Enabled = false;

CurrentDataMode = DataMode.Hex;

}

private void Form1_Load( object sender, EventArgs e )//khi
{
myPane = zedGraphControl1.GraphPane;
myPane.Title.Text = "Biểu đồ\n" +
"Ứng Suất/Độ biến dạng";
myPane.YAxis.Title.Text = "Ứng Suất, kN/Cm2";//truc x ghi ung suat
myPane.XAxis.Title.Text = "Độ biến dạng, mm/m";

// Scale the axes
zedGraphControl1.AxisChange();

// Save the beginning time for reference
tickStart = Environment.TickCount;

m_pointsList = new PointPairList();
}

private void CreateLineGraph()
{
myPane.CurveList.Clear();

/*
// Test
m_pointsList.Add(0, 0);
m_pointsList.Add(10, 2000);
m_pointsList.Add(50, 10000);
m_pointsList.Add(100, 20000);
*/
// Generate a blue curve with Star symbols
LineItem myCurve = myPane.AddCurve("Đường đặc tính", m_pointsList, Color.Blue, SymbolType.Star);

// Make sure the Y axis is rescaled to accommodate actual data
zedGraphControl1.AxisChange();
// Force a redraw
zedGraphControl1.Invalidate();
}

private void Form1_Resize( object sender, EventArgs e )
{
SetSize();
}

// Set the size and location of the ZedGraphControl
private void SetSize()
{
// Control is always 10 pixels inset from the client rectangle of the form
Rectangle formRect = this.ClientRectangle;
formRect.Inflate( -10, -10 );

if ( zedGraphControl1.Size != formRect.Size )
{
zedGraphControl1.Location = formRect.Location;
zedGraphControl1.Size = formRect.Size;
}
}

private void btnOpenPort_Click(object sender, EventArgs e)
{
bool error = false;

// If the port is open, close it.
if (comport.IsOpen) comport.Close();
else
{
// Set the port's settings
comport.BaudRate = int.Parse(cmbBaudRate.Text);
comport.DataBits = int.Parse(cmbDataBits.Text);
comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
comport.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
comport.PortName = cmbPortName.Text;

try
{
// Open the port
comport.Open();
}
catch (UnauthorizedAccessException) { error = true; }
catch (IOException) { error = true; }
catch (ArgumentException) { error = true; }

if (error) MessageBox.Show(this, "Could not open the COM port. Most likely it is already in use, has been removed, or is unavailable.", "COM Port Unavalible", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}

// Change the state of the form's controls
EnableControls();
}

/// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
/// <param name="s"> The string containing the hex digits (with or without spaces). </param>
/// <returns> Returns an array of bytes. </returns>
private byte[] HexStringToByteArray(string s)
{
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}

/// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
/// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
/// <returns> Returns a well formatted string of hex digits with spacing. </returns>
private string ByteArrayToHexString(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
return sb.ToString().ToUpper();
}

/// <summary> Enable/disable controls based on the app's current state. </summary>
private void EnableControls()
{
// Enable/disable controls based on whether the port is open or not
gbPortSettings.Enabled = !comport.IsOpen;
//txtSendData.Enabled = btnSend.Enabled = comport.IsOpen;
//chkDTR.Enabled = chkRTS.Enabled = comport.IsOpen;

if (comport.IsOpen)
{
btnOpenPort.Text = "&Close Port";
button1.Enabled = true;
button2.Enabled = true;
}
else
{
btnOpenPort.Text = "&Open Port";
button1.Enabled = false;
button2.Enabled = false;
}
}

private string[] OrderedPortNames()
{
// Just a placeholder for a successful parsing of a string to an integer
int num;

// Order the serial port names in numberic order (if possible)
return SerialPort.GetPortNames().OrderBy(a => a.Length > 3 && int.TryParse(a.Substring(3), out num) ? num : 0).ToArray();
}

/// <summary> Populate the form's controls with default settings. </summary>
private void InitializeControlValues()
{
cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Pari ty)));
cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(St opBits)));

cmbParity.Text = settings.Parity.ToString();
cmbStopBits.Text = settings.StopBits.ToString();
cmbDataBits.Text = settings.DataBits.ToString();
cmbParity.Text = settings.Parity.ToString();
cmbBaudRate.Text = settings.BaudRate.ToString();

RefreshComPortList();

// If it is still avalible, select the last com port used
if (cmbPortName.Items.Contains(settings.PortName)) cmbPortName.Text = settings.PortName;
else if (cmbPortName.Items.Count > 0) cmbPortName.SelectedIndex = cmbPortName.Items.Count - 1;
else
{
MessageBox.Show(this, "There are no COM Ports detected on this computer.\nPlease install a COM Port and restart this app.", "No COM Ports Installed", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
}

private void tmrCheckComPorts_Tick(object sender, EventArgs e)
{
// checks to see if COM ports have been added or removed
// since it is quite common now with USB-to-Serial adapters
RefreshComPortList();
}

private void RefreshComPortList()
{
// Determain if the list of com port names has changed since last checked
string selected = RefreshComPortList(cmbPortName.Items.Cast<string>( ), cmbPortName.SelectedItem as string, comport.IsOpen);

// If there was an update, then update the control showing the user the list of port names
if (!String.IsNullOrEmpty(selected))
{
cmbPortName.Items.Clear();
cmbPortName.Items.AddRange(OrderedPortNames());
cmbPortName.SelectedItem = selected;
}
}

private string RefreshComPortList(IEnumerable<string> PreviousPortNames, string CurrentSelection, bool PortOpen)
{
// Create a new return report to populate
string selected = null;

// Retrieve the list of ports currently mounted by the operating system (sorted by name)
string[] ports = SerialPort.GetPortNames();

// First determain if there was a change (any additions or removals)
bool updated = PreviousPortNames.Except(ports).Count() > 0 || ports.Except(PreviousPortNames).Count() > 0;

// If there was a change, then select an appropriate default port
if (updated)
{
// Use the correctly ordered set of port names
ports = OrderedPortNames();

// Find newest port if one or more were added
string newest = SerialPort.GetPortNames().Except(PreviousPortNames ).OrderBy(a => a).LastOrDefault();

// If the port was already open... (see logic notes and reasoning in Notes.txt)
if (PortOpen)
{
if (ports.Contains(CurrentSelection)) selected = CurrentSelection;
else if (!String.IsNullOrEmpty(newest)) selected = newest;
else selected = ports.LastOrDefault();
}
else
{
if (!String.IsNullOrEmpty(newest)) selected = newest;
else if (ports.Contains(CurrentSelection)) selected = CurrentSelection;
else selected = ports.LastOrDefault();
}
}

// If there was a change to the port list, return the recommended default selection
return selected;
}

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Read all the data waiting in the buffer
int data = comport.ReadByte();
// Check data
if (data == 0xAA)
{
flagData = 1;
nIndex++;
return;
}
if ((flagData == 1) & (nIndex == 1))
{
inputData1 = data;
nIndex++;
return;
}
if ((flagData == 1) & (nIndex == 2))
{
inputData2 = data;
flagPoint = 1;
nIndex++;
}
if ((data == 0x55) & (nIndex == 3))
{
nIndex = 0;
flagData = 0;
}
if (flagPoint == 1)
{
m_pointsList.Add((inputData1 * 256 + inputData2) / 10, (inputData1 * 256 + inputData2) * 0.2/10000);
CreateLineGraph();
flagPoint = 0;
}
}

private void cmbBaudRate_Validating(object sender, CancelEventArgs e)
{ int x; e.Cancel = !int.TryParse(cmbBaudRate.Text, out x); }

private void cmbDataBits_Validating(object sender, CancelEventArgs e)
{ int x; e.Cancel = !int.TryParse(cmbDataBits.Text, out x); }

#region Local Properties
private DataMode CurrentDataMode
{
get
{
if (rbHex.Checked) return DataMode.Hex;
else return DataMode.Text;
}
set
{
if (value == DataMode.Text) rbText.Checked = true;
else rbHex.Checked = true;
}
}
#endregion

private void button2_Click(object sender, EventArgs e)
{
CreateLineGraph();
}

private void button1_Click(object sender, EventArgs e)
{
myPane.CurveList.Clear();
m_pointsList.Clear();
// Force a redraw
zedGraphControl1.Invalidate();
}

private void btnClear_Click(object sender, EventArgs e)
{

}
}
}
buivanbinh12 vẫn chưa có mặt trong diễn đàn   Trả Lời Với Trích Dẫn