Last active
October 1, 2021 06:44
-
-
Save hidsh/4437733d2ee7e5ef39aa7fd1226f1ff0 to your computer and use it in GitHub Desktop.
Windows Terminal で COM ポートを使う
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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)}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Settings for Windows Terminal
Download
Download (or Copy & Paste) this script, then save as
com_tty.ps1
anywhere you like.Create New Profile
Ctrl + ,
for the setting+
at the bottom of left menuConfigure the Profile
Input string into
Command Line
as followed:Connect
v
at the top of the Windows Terminal for new connectionExample image (circuitpython):
