0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

cscの作法 その640

0
Last updated at Posted at 2026-10-11

概要

cscの作法、調べてみた。
up/downキーでボーレートを変更する。ターミナル書いてみた。

サンプルコード

using System;
using System.IO.Ports;
using System.Text;

class ManualBaudSelector
{
	private static readonly int[] BaudRates = new int[] { 
		4800, 9600, 19200, 38400, 57600, 115200 
	};
	private static int _currentIndex = 1;
	private static SerialPort _serialPort;
	private static readonly string PortName = "COM7";
	static void Main(string[] args) {
		Console.Clear();
		Console.WriteLine("=== 手動ボーレート切り替え監視 ===");
		Console.WriteLine(" [▲ Up] キー  : ボーレートを上げる");
		Console.WriteLine(" [▼ Down] キー: ボーレートを下げる");
		Console.WriteLine(" [Escape] キー : プログラムを終了する");
		Console.WriteLine("------------------------------------------------");
		ChangeBaudRate(BaudRates[_currentIndex]);
		// キー入力を監視するメインループ
		bool isRunning = true;
		while (isRunning)
		{
			// キーが押されるまで待機(画面にキー文字を表示しない)
			ConsoleKeyInfo keyInfo = Console.ReadKey(true);
			switch (keyInfo.Key)
			{
				case ConsoleKey.UpArrow:
					// 上限に達していなければインデックスを増やす
					if (_currentIndex < BaudRates.Length - 1)
					{
						_currentIndex++;
						ChangeBaudRate(BaudRates[_currentIndex]);
					}
				break;
				case ConsoleKey.DownArrow:
					// 下限に達していなければインデックスを減らす
					if (_currentIndex > 0)
					{
						_currentIndex--;
						ChangeBaudRate(BaudRates[_currentIndex]);
					}
				break;
				case ConsoleKey.Escape:
					// 終了処理へ
					isRunning = false;
				break;
			}
		}
		// 終了時にポートを確実に閉じる
		ClosePort();
	}
	// ボーレートを切り替えるメソッド
	private static void ChangeBaudRate(int newBaudRate) {
		ClosePort();
		// 新しい設定でインスタンス作成
		_serialPort = new SerialPort(PortName, newBaudRate, Parity.None, 8, StopBits.One);
		_serialPort.Encoding = Encoding.UTF8; // 文字化け判定用にUTF8推奨
		_serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
		try
		{
			_serialPort.Open();
			// 現在の設定状況を分かりやすくコンソールに明示
			Console.ForegroundColor = ConsoleColor.Green;
			Console.WriteLine(string.Format("\n[INFO] ボーレートを切り替えました -> {0} bps で監視中...", newBaudRate));
			Console.ResetColor();
		}
		catch (Exception ex)
		{
			Console.ForegroundColor = ConsoleColor.Red;
			Console.WriteLine(string.Format("\n[ERROR] ポートオープン失敗 ({0} bps): {1}", newBaudRate, ex.Message));
			Console.ResetColor();
		}
	}
	// データ受信時のイベント
	private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) {
		SerialPort sp = sender as SerialPort;
		if (sp != null && sp.IsOpen)
		{
			try
			{
				// 現在バッファにあるデータをすべて読み込んでそのまま出力
				string indata = sp.ReadExisting();
				Console.Write(indata);
			}
			catch { }
		}
	}
	// ポートを安全に閉じるユーティリティ
	private static void ClosePort() {
		if (_serialPort != null)
		{
			_serialPort.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedHandler);
			if (_serialPort.IsOpen)
			{
				try { _serialPort.Close(); } catch { }
			}
			_serialPort.Dispose();
			_serialPort = null;
		}
	}
}




以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?