Form1 Bai5KTTN - Cs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai5KTTN\C#\Bai5KTTN\HIF++\Form1.

cs 1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LibUsbDotNet;
using LibUsbDotNet.Info;
using LibUsbDotNet.Main;
using System.Windows.Forms.DataVisualization.Charting;

namespace HIF__
{
public partial class Form1 : Form
{
//Khai bao cac vung nho de gui du lieu xuong USB
#region variable
// DIN
byte DIValue;
// DOUT
//byte[] DODuty = new byte[8];
byte[] DOValue = new byte[8];
bool[] DOInPWMMode = new bool[8];
// PWM frequency
byte[] FValue = new byte[3];
//AIN gain
double AIGain;
// Sample time
Int16 TsValue;
// AOUT
byte[] AO0ByteValue = new byte[2];
byte[] AO1ByteValue = new byte[2];
// AIN
double[] AIValue = new double[3];
// Counter
Int32 counterValue;
byte resetCounterCmd;
//Variable for Button Q00 Q01
int ctnQ00 = 0;
int ctnQ01 = 0;
int counter;

#endregion variable

public Form1()
{
InitializeComponent();
}

#region Declaring Global Variable


public static UsbDevice myUsbDevice, myUsbDevice_temp;
UsbEndpointReader reader;
UsbEndpointWriter writer;
IAsyncResult result;
#endregion Declaring Global Variable

private void Form1_FormClosing(object sender, FormClosingEventArgs e)


{
if (MessageBox.Show("Do you want to exit ?", "Confirmation", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai5KTTN\C#\Bai5KTTN\HIF++\Form1.cs 2
}
else
{
e.Cancel = true;
}
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)


{
try
{
Usb_exit();
Application.Exit();
}
catch
{

}
}

private void Form1_Load(object sender, EventArgs e)


{
timer1.Interval = 200;
timer1.Enabled = false;

//Khoi tao thong so cho Chart


chart1.Titles.Add("Do thi dien ap AI theo thoi gian");
var chartArea = chart1.ChartAreas[0];
chartArea.AxisX.LabelStyle.Format = "";
chartArea.AxisY.LabelStyle.Format = "";
chartArea.AxisX.LabelStyle.IsEndLabelVisible = true;
chartArea.AxisY.LabelStyle.IsEndLabelVisible = true;
chartArea.AxisX.Minimum = 0;
chartArea.AxisY.Minimum = 0;
chartArea.AxisX.Maximum = 100;
chartArea.AxisY.Maximum = 5;
chartArea.AxisX.Interval = 20;
chartArea.AxisY.Interval = 20;
chartArea.AxisX.Title = "Thoi gian (s)";
chartArea.AxisY.Title = "Dien ap (V)";
chart1.Series[0].ChartType = SeriesChartType.Line;
chart1.Series[0].Color = Color.Red;
chart1.Series[0].BorderWidth = 2;
chart1.Series[0].IsVisibleInLegend = false;
}

//Ham ve Chart
private void PlotChart(double dataX, double dataY)
{
chart1.Series[0].Points.AddXY(dataX, dataY);
var chartArea = chart1.ChartAreas[0];
if (dataX > chartArea.AxisX.Maximum)
{
chartArea.AxisX.Maximum = dataX;
if (dataX / chartArea.AxisX.Interval == 10)
chartArea.AxisX.Interval = dataX / 5;
}
if (dataY > chartArea.AxisY.Maximum)
{
chartArea.AxisY.Maximum += 20;
}
}
private void btnconnection_Click(object sender, EventArgs e)
{
// Sinh vien tu them chuong trinh ket noi voi DAQ card
if (btnconnection.Text == "Connect")
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai5KTTN\C#\Bai5KTTN\HIF++\Form1.cs 3
{
if (myUsbDevice == null)
{
UsbRegDeviceList allDevices = UsbDevice.AllDevices;
foreach (UsbRegistry usbRegistry in allDevices)
{
if (usbRegistry.Open(out myUsbDevice))
{
txtproductname.Text = myUsbDevice.Info.ProductString;
txtvendorid.Text =
myUsbDevice.Info.Descriptor.VendorID.ToString();
txtproductid.Text =
myUsbDevice.Info.Descriptor.ProductID.ToString();
txtmanufacturer.Text =
myUsbDevice.Info.ManufacturerString;
USB_DATA_RECEIVER_INIT();
btnconnection.Text = "Disconnect";
timer1.Enabled = true;
}
}
}
if (myUsbDevice == null)
{
MessageBox.Show("Device Not Found !!!", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
Usb_exit();
btnconnection.Text = "Connect";
txtproductname.Text = "";
txtvendorid.Text = "";
txtproductid.Text = "";
txtmanufacturer.Text = "";
txt_AI0.Text = "";
txt_pwm0.Text = "";
txt_pwm1.Text = "";
timer1.Enabled = false;
}
}
void USBWrite(byte[] buffer)
{
try
{
int bytesWritten;
if ((myUsbDevice.IsOpen) && (writer != null))
writer.Write(buffer, 1000, out bytesWritten);
}
catch (Exception err)
{
MessageBox.Show("Can Not Send Data To USB Device\nDetails: " + err,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#region USB_DATA_RECEIVER_INIT
void USB_DATA_RECEIVER_INIT()
{
IUsbDevice wholeUsbDevice = myUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
wholeUsbDevice.SetConfiguration(1);
wholeUsbDevice.ClaimInterface(0);
}
//Open usb end point reader and writer
reader = myUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai5KTTN\C#\Bai5KTTN\HIF++\Form1.cs 4
writer = myUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

//Set Interrupt service rountie for reader complete event


reader.DataReceived += (OnRxEndPointData);
reader.DataReceivedEnabled = true;
}
#endregion USB_DATA_RECEIVER_INIT

#region USB EXIT


private void Usb_exit()
{
reader.DataReceivedEnabled = false;
reader.DataReceived -= (OnRxEndPointData);
this.EndInvoke(result);
reader.Dispose();
writer.Dispose();
if (myUsbDevice != null)
{
if (myUsbDevice.IsOpen)
{
IUsbDevice wholeUsbDevice = myUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
wholeUsbDevice.ReleaseInterface(0);
}
myUsbDevice.Close();

}
myUsbDevice = null;
UsbDevice.Exit();
}
}
#endregion USB EXIT

#region USB DATA RECEIVER INTERRUPT SERVICE ROUNTIE


Action<byte[]> UsbReceiverAction;

private void OnRxEndPointData(object sender, EndpointDataEventArgs e)


{

UsbReceiverAction = UsbReceiverActionFunction; //co su kien ngat xay ra thi ham


UsbReceiverActionFunction se duoc goi o day
if ((myUsbDevice.IsOpen) && (reader != null))
{
result = this.BeginInvoke(UsbReceiverAction, e.Buffer);
}
}

private void UsbReceiverActionFunction(byte[] input)


{
// giữ liệu nhận sẽ lưu trong chuỗi input và sẽ xử lý số liệu tại đây
/* GET VALUE */
// Doc gia tri DIN luu vao DIValue tu byte dau tien cua data truyen
DIValue = input[0];
// Doc gia tri Counter tu 4 byte tiep theo (thu tu byte bi dao nguoc khi truyen)
byte[] counterValueTmp = new byte[4];
counterValueTmp[3] = input[1];
counterValueTmp[2] = input[2];
counterValueTmp[1] = input[3];
counterValueTmp[0] = input[4];
counterValue = BitConverter.ToInt32(counterValueTmp, 0);
if (counterValue > 32767)
counterValue = counterValue - 65536;
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai5KTTN\C#\Bai5KTTN\HIF++\Form1.cs 5
// Doc gia tri Analog Input, moi AIN chiem 4 byte trong data truyen
int AI0IntValue;
byte[] AI0ByteValue = new byte[4];
AI0ByteValue[3] = input[5];
AI0ByteValue[2] = input[6];
AI0ByteValue[1] = input[7];
AI0ByteValue[0] = input[8];
AI0IntValue = BitConverter.ToInt32(AI0ByteValue, 0);
AIValue[0] = (Convert.ToDouble(AI0IntValue) / 4095) * 3.3; //Bien doi thanh dien ap (0 - 3
.3V), trong bai thi chi can lay AI0

/*int AI1IntValue;
int AI2IntValue;
byte[] AI1ByteValue = new byte[4];
byte[] AI2ByteValue = new byte[4];*/

/*AI1ByteValue[3] = input[9];
AI1ByteValue[2] = input[10];
AI1ByteValue[1] = input[11];
AI1ByteValue[0] = input[12];
AI2ByteValue[3] = input[13];
AI2ByteValue[2] = input[14];
AI2ByteValue[1] = input[15];
AI2ByteValue[0] = input[16];*/
/*AI1IntValue = BitConverter.ToInt32(AI1ByteValue, 0);
AI2IntValue = BitConverter.ToInt32(AI2ByteValue, 0);*/

/*AIValue[1] = (Convert.ToDouble(AI1IntValue) / 4095) * 3.3;


//AIValue[2] = (Convert.ToDouble(AI2IntValue) / (AIGain * 131072)) * 2.048;*/

/* DISPLAY I0.0*/
if (Convert.ToBoolean(DIValue & 0x01))
{
rectangleShape1.BackColor = Color.Red;
}
else
{
rectangleShape1.BackColor = Color.White;
}

/* DISPLAY I0.1*/
if (Convert.ToBoolean((DIValue >> 1) & 0x01))
{
rectangleShape2.BackColor = Color.Red;
}
else
{
rectangleShape2.BackColor = Color.White;
}

/* DISPLAY AI0*/
txt_AI0.Text = AIValue[0].ToString("0.000");
//txtAI1.Text = AIValue[1].ToString("0.000");
//txtAI2.Text = AIValue[2].ToString("0.000");

/* DISPLAY Counter*/
//txtCounter0.Text = counterValue.ToString();

}
#endregion USB DATA RECEIVER INTERRUPT SERVICE ROUNTIE

//Timer1 de gui data


private void timer1_Tick(object sender, EventArgs e)
{
//Xu ly cho nut nhan Q00
if (DOValue[0] == 100)
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai5KTTN\C#\Bai5KTTN\HIF++\Form1.cs 6
{
ctnQ00 = 1;
}
//Xu ly cho nut nhan Q01
if (DOValue[1] == 100)
{
ctnQ01 = 1;
}
byte[] data_send = { 14, (byte)'N', DOValue[0], DOValue[1], DOValue[2], DOValue[3], DOValue[4],
DOValue[5],
DOValue[6], DOValue[7], AO0ByteValue[0], AO0ByteValue[1], AO1ByteValue[0],
AO1ByteValue[1], resetCounterCmd };
USBWrite(data_send);
resetCounterCmd = 0;

//Draw chart
PlotChart((double)timer1.Interval / 1000.0 * (double)counter, AIValue[0]);
counter++;
}

//Nhan nut tac dong den ngo ra Q0.0


private void butQ00_Click(object sender, EventArgs e)
{
if (ctnQ00 == 0)
{
DOValue[0] = 100;
}

if (ctnQ00 == 1)
{
DOValue[0] = 0;
ctnQ00 = 0;
}
}

//Nhan nut tac dong den ngo ra Q0.1


private void butQ01_Click(object sender, EventArgs e)
{
if (ctnQ01 == 0)
{
DOValue[1] = 100;
}

if (ctnQ01 == 1)
{
DOValue[1] = 0;
ctnQ00 = 0;
}
}

private void txt_pwm0_KeyDown(object sender, KeyEventArgs e)


{
//Neu co su kien nhan enter
if (e.KeyCode == Keys.Enter)
{
try
{
int tempDuty = int.Parse(txt_pwm0.Text);
if ((tempDuty < 0) | (tempDuty > 100))
{
MessageBox.Show("Duty vuot qua gioi han");
}
else
{
DOValue[0] = (byte)tempDuty;
ctnQ00 = 0; //Reset Button Q00 de bat lai lan sau
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai5KTTN\C#\Bai5KTTN\HIF++\Form1.cs 7
}
}
catch
{
MessageBox.Show("Chua dien gia tri Duty!");
}
}
}

private void txt_pwm1_KeyDown(object sender, KeyEventArgs e)


{
//Neu co su kien nhan enter
if (e.KeyCode == Keys.Enter)
{
try
{
int tempDuty = int.Parse(txt_pwm1.Text);
if ((tempDuty < 0) | (tempDuty > 100))
{
MessageBox.Show("Duty vuot qua gioi han");
}
else
{
DOValue[1] = (byte)tempDuty;
ctnQ01 = 0; //Reset Button Q01 de bat lai lan sau
}
}
catch
{
MessageBox.Show("Chua dien gia tri Duty!");
}
}
}
}
}

You might also like