Skip to content

Instantly share code, notes, and snippets.

@hidsh
Last active October 1, 2021 06:44
Show Gist options
  • Save hidsh/4437733d2ee7e5ef39aa7fd1226f1ff0 to your computer and use it in GitHub Desktop.
Save hidsh/4437733d2ee7e5ef39aa7fd1226f1ff0 to your computer and use it in GitHub Desktop.
Windows Terminal で COM ポートを使う
# Fully based on the following web pages:
# - https://qiita.com/yapg57kon/items/58d7f47022b3e405b5f3
# - https://kkamegawa.hatenablog.jp/entry/20070220/p2
# thx!
### 接続開始時のスクリプト ###
if([string]::IsNullOrEmpty($args[0])) {
$com_list = Get-WmiObject -Class Win32_PnPSignedDriver -Filter "FriendlyName LIKE '%COM%'" | Select-Object -Property FriendlyName
foreach($line in $com_list) {
Write-Host ' -' $line.FriendlyName
}
$com_num = Read-Host 'Input COM Number'
}
else {
$com_num = $Args[0]
}
# 1. COMポートのインスタンス生成 (COMxx、9600bps、パリティ無し) パリティある場合::Even、::Oddとする
$c = New-Object System.IO.Ports.SerialPort "COM$($com_num)", 9600, ([System.IO.Ports.Parity]::None)
# 2. DTR、RTSを設定 (機器・ケーブル仕様に合わせる)
$c.DtrEnable = $true
$c.RtsEnable = $true
# 3. ハンドシェイク無し (必要なら::RequestToSendや::XOnXOffとする)
$c.Handshake=[System.IO.Ports.Handshake]::None
# 4. 改行文字をCR(0x0D)に設定 (機器仕様に合わせる)
# ※NewLineプロパティはWriteLineやReadLineメソッドに適用されるため本方法では動作に影響しない
# 実際の変更方法の例は後述
$c.NewLine = "`r"
# 5. 文字コード設定 (機器仕様に合わせる)
#$c.Encoding=[System.Text.Encoding]::GetEncoding("Shift_JIS")
$c.Encoding=[System.Text.Encoding]::GetEncoding("UTF-8")
# 6. シリアル受信イベントを登録(受信したらコンソールに出力)
$d = Register-ObjectEvent -InputObject $c -EventName "DataReceived" `
-Action {param([System.IO.Ports.SerialPort]$sender, [System.EventArgs]$e) `
Write-Host -NoNewline $sender.ReadExisting()}
# 7. COMポートを開く
$c.Open()
# 8. キーボード入力をシリアルポートに送信する無限ループ (ReadKey($false)とすればローカルエコーになる)
# これ以降、ターミナルソフトのようなキーボード入力と機器の出力表示になります (コピペデータも機器に送られるので注意)
# 終了時はctrl-cで抜ける
for(;;){if([Console]::KeyAvailable){$c.Write(([Console]::ReadKey($true)).KeyChar)}}
@hidsh
Copy link
Author

hidsh commented Oct 1, 2021

Settings for Windows Terminal

Download

Download (or Copy & Paste) this script, then save as com_tty.ps1 anywhere you like.

Create New Profile

  1. Type Ctrl + , for the setting
  2. Click sign + at the bottom of left menu

Configure the Profile

Input string into Command Line as followed:

powershell -ExecutionPolicy RemoteSigned -File [PATH\TO\]com_tty.ps1

windows-terminal-setting

Connect

  1. Click sign like v at the top of the Windows Terminal for new connection
  2. Select the profile just new created
  3. Power shell script enumerates usable COM port automatically
  4. Input COM port number (e.g. input "27" for COM27)
  5. (May needs to hit any key)

Example image (circuitpython):
connected-circuitpython

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment