You are on page 1of 6

D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai6KTTN\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 ctn = 0;
bool enaPID;
int counterchart;
double curangle, setangle;
double ek, ek1, ek2, uk, uk1, output, kp, ki, kd;
double tcycle = 0.05;

#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,
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai6KTTN\HIF++\Form1.cs 2
MessageBoxIcon.Question) == DialogResult.Yes)
{

}
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 goc quay 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 = "Goc (o)";
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)
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai6KTTN\HIF++\Form1.cs 3
{
// Sinh vien tu them chuong trinh ket noi voi DAQ card
if (btnconnection.Text == "Connect")
{
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_setval.Text = "";
txt_kp.Text = "";
txt_ki.Text = "";
txt_kd.Text = "";
txt_counter.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))
{
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai6KTTN\HIF++\Form1.cs 4
wholeUsbDevice.SetConfiguration(1);
wholeUsbDevice.ClaimInterface(0);
}
//Open usb end point reader and writer
reader = myUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
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];
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai6KTTN\HIF++\Form1.cs 5
counterValueTmp[0] = input[4];
counterValue = BitConverter.ToInt32(counterValueTmp, 0);
if (counterValue > 32767)
counterValue = counterValue - 65536;
// 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 Counter
txt_counter.Text = counterValue.ToString();

}
#endregion USB DATA RECEIVER INTERRUPT SERVICE ROUNTIE

//Timer1 de gui data


private void timer1_Tick(object sender, EventArgs e)
{
//Xu ly gia tri counter
curangle = ((float)counterValue)*360/400;
txtangle.Text = curangle.ToString();
setangle = double.Parse(txt_setval.Text);
//PID controller
if (enaPID == true)
{
ctn = 1; //Thuc hien chuc nang nut nhan nha Start
ek2 = ek1;
ek1 = ek;
ek = setangle - curangle;
uk1 = uk;

uk = uk1 + kp * (ek - ek1) + (ki * tcycle / 2) * (ek + ek1) + (kd / tcycle) * (ek - 2 * ek1
+ ek2);
output = uk;
if (output < 0)
{
output = 0;
}
if (output > 1)
{
output = 1;
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\ThiNghiem\Dethi\Bai6KTTN\HIF++\Form1.cs 6
}

output = output * 100;


}
if (enaPID == false)
{
output = 0;
uk = 0;
}
txtpwm.Text = output.ToString();
DOValue[0] = Convert.ToByte(output);

//Gui tin nhan voi du lieu duoc cap nhat


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)counterchart, curangle);
counterchart++;
}

private void butstart_Click(object sender, EventArgs e)


{
if (ctn == 0)
{
enaPID = true;
butstart.Text = "STOP PID";
}
if (ctn == 1)
{
enaPID = false;
butstart.Text = "START PID";
ctn = 0;
}
}

}
}

You might also like