Skip to content

Instantly share code, notes, and snippets.

@immengineer
Created April 16, 2019 05:15
Show Gist options
  • Save immengineer/446ee9dcd2b9ff70ab7e7c169848b86e to your computer and use it in GitHub Desktop.
Save immengineer/446ee9dcd2b9ff70ab7e7c169848b86e to your computer and use it in GitHub Desktop.
高砂電源 KX-210制御クラス
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
namespace GetOscData
{
class Kx210
{
// 電源通信用COMポート名(COM1等で指定)
public static SerialPort PowerCom;
/// <summary>
/// 電源用通信ポートオープン
/// </summary>
/// <param name="com">COMポート名(COM1等)</param>
/// <returns>Open出来ればtrue</returns>
public bool OpenPowerCom(string com)
{
PowerCom = new SerialPort(com);
// 以下は高砂デフォルト値
PowerCom.BaudRate = 9600;
PowerCom.Parity = Parity.None;
PowerCom.RtsEnable = true; // これを設定しないと動かない
// 一応タイムアウト1秒にしとこう
PowerCom.ReadTimeout = 1000;
PowerCom.WriteTimeout = 1000;
// Open済みなら一旦閉じる
if (PowerCom.IsOpen == true) PowerCom.Close();
// Openしてみる
try
{
PowerCom.Open();
}
catch
{
MessageBox.Show("電源通信用ポート " + com + " をOpenできません", "通信ポートエラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// Open出来たか結果を返す
return PowerCom.IsOpen;
}
/// <summary>
/// 電源用通信ポートクローズ
/// </summary>
public void ClosePowerCom()
{
if (PowerCom != null)
{
if (PowerCom.IsOpen == true) PowerCom.Close();
}
}
/// <summary>
/// 電源ONOFF
/// </summary>
/// <param name="onoff">trueでON、falseでOFF</param>
public void PowerONOFF(bool onoff)
{
if (onoff == true) PowerCom.WriteLine("A1,OT1"); // 電源ON
else PowerCom.WriteLine("A1,OT0"); // 電源OFF
}
/// <summary>
/// 電源にコマンドを送り、応答文字列を読む
/// </summary>
/// <param name="command">コマンドの文字列</param>
/// <returns>電源からの応答文字列</returns>
private string ReadLine(string command)
{
string s = "";
try
{
PowerCom.WriteLine(command);
System.Threading.Thread.Sleep(100); //送信後の待ち時間
s = PowerCom.ReadLine();
}
catch (Exception ex)
{
s = ex.Message;
}
return s;
}
/// <summary>
/// 電圧値取得
/// </summary>
/// <returns>電圧値文字列(末尾V)</returns>
public string GetVoltage()
{
string s = "V";
if (PowerCom.IsOpen == true)
{
s = ReadLine("A1,TK6");
s.TrimEnd('\r');
}
return s;
}
/// <summary>
/// 電流値取得
/// </summary>
/// <returns>電流値文字列(末尾A)</returns>
public string GetCurrent()
{
string s = "A";
if (PowerCom.IsOpen == true)
{
s = ReadLine("A1,TK7");
}
return s;
}
/// <summary>
/// 電源接続確認 TK4で戻り値を見る
/// </summary>
/// <returns>接続出来ればtrue</returns>
public bool ConnectCheck()
{
bool result = false;
if (PowerCom.IsOpen == true)
{
string s = ReadLine("A1,TK4");
if (s.Contains("STAT")) result = true; // STATが戻ってこなければFALSE
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment