using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Ports; using System.Threading; namespace Tps_LQ_Transmitter.com { /// /// 蚯蚓直流程控电源控制类 /// [使用计算机串口COM4通信] /// class RainwormPower:MySerial { SerialPort serial = null; public enum State { ON, OFF }; public RainwormPower() { serial = new SerialPort(); serial.PortName = "COM4"; //使用计算机串口COM4通信 serial.BaudRate = 9600; serial.DataBits = 8; serial.StopBits = StopBits.One;//停止位设置为com_stop的值 serial.Parity = Parity.None;//获取奇偶校验选项的值 serial.ReadTimeout = 1000; //读取等待时间1000 serial.RtsEnable = true; if (!serial.IsOpen) { serial.Open(); } } public override void portClose() { serial.Close(); } /// /// 电源控制与查询读写 /// /// 询问命令 /// 延时mS /// 返回数据byte[] public byte[] powerWriteRead(byte[] data,int delay=100) { if (data == null) return null; //先读空 if (serial.BytesToRead > 0) serial.DiscardInBuffer(); byte[] crc = crc16(data); byte[] newarray = new byte[data.Length + 2]; Array.Copy(data, newarray, data.Length); newarray[data.Length] = crc[0]; newarray[data.Length + 1] = crc[1]; serial.Write(newarray, 0, newarray.Length); Thread.Sleep(delay); if (serial.BytesToRead > 0) { byte[] dat = new byte[serial.BytesToRead]; serial.Read(dat, 0, dat.Length); return dat; } else { return null; } } /// /// 电源输出ON/OFF /// /// 输出状态ON/OFF public void powerOnoff(State st) { byte[] byOn = { 0x00, 0x10, 0x10, 0x04, 0x00, 0x01, 0x02, 0x00, 0x01 }; byte[] byOFF = { 0x00, 0x10, 0x10, 0x04, 0x00, 0x01, 0x02, 0x00, 0x00 }; if (st==State.ON) { powerWriteRead(byOn); } else { powerWriteRead(byOFF); } } /// /// 电源输出电压与限流电流设置 /// /// 电压值 /// 电流值 public void powerSetting(double volt,double curr) { int vt, ct; byte[] byVolt = { 0x00, 0x10, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00 }; byte[] byCurr = { 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x02, 0x00, 0x00 }; vt = (int) (volt * 100); byVolt[7] = (byte)((vt & 0xFF00)>>8); byVolt[8] = (byte)(vt & 0x00FF); ct = (int)(curr * 100); byCurr[7] = (byte)((ct & 0xFF00) >> 8); byCurr[8] = (byte)(ct & 0x00FF); powerWriteRead(byCurr); powerWriteRead(byVolt); } } }