tagCANDY CGI VBレスキュー(花ちゃん) の Visual Basic 2010 用 掲示板(VB.NET 掲示板)
VBレスキュー(花ちゃん) の Visual Basic 2010 用 掲示板(VB.NET 掲示板)
[ツリー表示へ]  [ワード検索]  [Home]

タイトル VB2005で、シリアル通信について
投稿日: 2009/04/27(Mon) 13:43
投稿者AMI
お世話になっております。
現在PCとFA機器との通信をRS232Cで行おうと思っております。

(FA機器には、コマンドがありたとえばPCから「DATE?」と
送信すると自動的に「2008/04/26」
といった形にレスポンスがきます)

そこで現在、下記コードを記載し、PCからFA機器に対して、
シリアル通信を行おうとしております。
232Cのラインモニタもつなげているので、データの送受信の流れは見えております。
VB側から「DATE?」と送信はできました。
しかし、その答えの「「2008/04/26」を受信することが出来ません。
ラインモニタ上では、そのレスポンスは帰ってきております。

受信イベントが下記の処理だとおもうのですが、
まったくはしりません。

*****************************
'--------------------------------------------------------------------------------
    'データ受信イベント
    '--------------------------------------------------------------------------------
    Private Sub _com_DataReceived(ByVal sender As Object, _
                                  ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
                                  Handles _com.DataReceived

        Dim addmsg As New AddMessageDelegate(AddressOf AddMessage)
        Dim strDataReceived As String

        'Select Case e.EventType
        '    Case SerialData.Chars
        '    Case SerialData.Eof
        'End Select

        Try
            strDataReceived = _com.ReadLine
        Catch ex As Exception
            strDataReceived = ex.Message
        End Try
        txtMessage.Invoke(addmsg, New Object() {"[RCV]" + strDataReceived})

        'txtMessage.Invoke(addmsg, New Object() {"[RCV]" + SerialData.Chars})

    End Sub
******************************



VB2005を使用
下記が現在使用しているコードです。

Imports System.IO.Ports
Imports System.Threading

Public Class Form1

    Private WithEvents _com As New System.IO.Ports.SerialPort

    Delegate Sub AddMessageDelegate(ByVal str As String)

    '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    'テキストボックスにメッセージを表示する
    '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    Private Sub AddMessage(ByVal str As String)
        txtMessage.Text = DateTime.Now.ToString("HH:mm:ss") + " " + _
                          str + ControlChars.CrLf + _
                          txtMessage.Text
    End Sub

    '--------------------------------------------------------------------------------
    'データ受信イベント
    '--------------------------------------------------------------------------------
    Private Sub _com_DataReceived(ByVal sender As Object, _
                                  ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
                                  Handles _com.DataReceived

        Dim addmsg As New AddMessageDelegate(AddressOf AddMessage)
        Dim strDataReceived As String

        'Select Case e.EventType
        '    Case SerialData.Chars
        '    Case SerialData.Eof
        'End Select

        Try
            strDataReceived = _com.ReadLine
        Catch ex As Exception
            strDataReceived = ex.Message
        End Try
        txtMessage.Invoke(addmsg, New Object() {"[RCV]" + strDataReceived})

        'txtMessage.Invoke(addmsg, New Object() {"[RCV]" + SerialData.Chars})

    End Sub

    '--------------------------------------------------------------------------------
    'エラー受信イベント
    '--------------------------------------------------------------------------------
    Private Sub _com_ErrorReceived(ByVal sender As Object, _
                                   ByVal e As System.IO.Ports.SerialErrorReceivedEventArgs) _
                                   Handles _com.ErrorReceived

        Dim addmsg As New AddMessageDelegate(AddressOf AddMessage)
        Dim strErrorMessage As String = "ErrorReceived"

        Select Case e.EventType
            Case SerialError.Frame
                strErrorMessage = "The hardware detected a framing error."
            Case SerialError.Overrun
                strErrorMessage = "A character-buffer overrun has occurred. The next character is lost."
            Case SerialError.RXOver
                strErrorMessage = "An input buffer overflow has occurred. There is either no room in the input buffer, or a character was received after the end-of-file (EOF) character."
            Case SerialError.RXParity
                strErrorMessage = "The hardware detected a parity error."
            Case SerialError.TXFull
                strErrorMessage = "The application tried to transmit a character, but the output buffer was full."
        End Select
        txtMessage.Invoke(addmsg, New Object() {"[ERR]" + strErrorMessage})

    End Sub

    '--------------------------------------------------------------------------------
    'Pin変更イベント
    '--------------------------------------------------------------------------------
    Private Sub _com_PinChanged(ByVal sender As Object, _
                                ByVal e As System.IO.Ports.SerialPinChangedEventArgs) _
                                Handles _com.PinChanged

        Dim addmsg As New AddMessageDelegate(AddressOf AddMessage)
        Dim strPinMessage As String = "PinChanged"
        Select Case e.EventType
            Case SerialPinChange.Break
                strPinMessage = "A break was detected on input."
            Case SerialPinChange.CDChanged
                strPinMessage = "The Receive Line Signal Detect (RLSD) signal changed state."
            Case SerialPinChange.CtsChanged
                strPinMessage = "The Clear to Send (CTS) signal changed state."
            Case SerialPinChange.DsrChanged
                strPinMessage = "The Data Set Ready (DSR) signal changed state."
            Case SerialPinChange.Ring
                strPinMessage = "A ring indicator was detected."
        End Select
        txtMessage.Invoke(addmsg, New Object() {"[PIN]" + strPinMessage})

    End Sub

    '--------------------------------------------------------------------------------
    '終了イベント
    '--------------------------------------------------------------------------------
    Private Sub Form1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed

        ''ポートがオープンされている場合閉じる
        If (_com.IsOpen = True) Then
            Call _com.Close()
        End If

    End Sub

    '--------------------------------------------------------------------------------
    'フォームロード
    '--------------------------------------------------------------------------------
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ''ポート
        With cmbPortName.Items
            .Clear()
            .Add("COM1")
            .Add("COM2")
            .Add("COM3")
            .Add("COM4")
            .Add("COM5")
            .Add("COM6")
        End With
        cmbPortName.Text = "COM1"
        ''速度
        With cmbBaudRate.Items
            .Clear()
            .Add("2400")
            .Add("4800")
            .Add("9600")
            .Add("19200")
            .Add("38400")
            .Add("57600")
            .Add("115200")
        End With
        cmbBaudRate.Text = "9600"
        ''パリティ
        With cmbParity.Items
            .Add("なし")     '0:Parity.None
            .Add("奇数")     '1:Parity.Odd
            .Add("偶数")     '2:Parity.Even
            .Add("マーク")   '3:Parity.Mark
            .Add("スペース") '4:Parity.Space
        End With
        cmbParity.Text = "なし"
        ''データ長
        With cmbDataBits.Items
            .Add("4")
            .Add("5")
            .Add("6")
            .Add("7")
            .Add("8")
        End With
        cmbDataBits.Text = "8"
        ''ストップビット
        With cmbStopBits.Items
            .Add("なし")    '0:StopBits.None
            .Add("1")       '1:StopBits.One
            .Add("2")       '2:StopBits.Two
            .Add("1.5")     '3:StopBits.OnePointFive
        End With
        cmbStopBits.Text = "1"
        ''受信バッファサイズ
        txtReadBufferSize.Text = "1024"
        ''送信バッファサイズ
        txtWriteBufferSize.Text = "512"
        ''パリティエラー時の置換文字
        txtParityReplace.Text = "?"
        ''Null文字を破棄
        chkDiscardNull.Checked = False
        ''RTSラインを有効
        chkRtsEnable.Checked = False
        ''DTRラインを有効
        chkDtrEnable.Checked = True

        ''コントロール制御
        btnComClose.Enabled = False
        pnlBody.Enabled = False

    End Sub

    '--------------------------------------------------------------------------------
    '「接続」ボタンクリック
    '--------------------------------------------------------------------------------
    Private Sub btnComOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComOpen.Click

        Try
            With _com
                ''プロパティセット
                .PortName = cmbPortName.Text
                .BaudRate = CInt(cmbBaudRate.Text)
                .Parity = CType(cmbParity.SelectedIndex, Parity)
                .DataBits = CInt(cmbDataBits.Text)
                .StopBits = CType(cmbStopBits.SelectedIndex, StopBits)
                .ReadBufferSize = CInt(txtReadBufferSize.Text)
                .WriteBufferSize = CInt(txtWriteBufferSize.Text)
                .ParityReplace = System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes(txtParityReplace.Text)(0)
                .DiscardNull = chkDiscardNull.Checked
                .RtsEnable = chkRtsEnable.Checked
                .DtrEnable = chkDtrEnable.Checked
                ''既にオープンされていないか?
                If (.IsOpen = True) Then
                    MessageBox.Show(.PortName & "は既にオープンされています。", "エラー", _
                                    MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Exit Sub
                End If
                ''ポートオープン
                Call .Open()
                Call AddMessage(" --- " + .PortName + "オープン")
                '****************************************************************************
                Dim strSend As String               'NewLine格納用文字列変数

                strSend = .NewLine 'NewLineを取得
                strSend = strSend.Replace(vbLf, vbCr)       '文字中のLFをCRに置換する場合

                SerialPort1.NewLine = strSend                   '置換したデリミタをNewLineに格納
                '****************************************************************************
                Dim aa As String
                aa = .NewLine
                .NewLine = aa
                '.NewLine = "LFCR"
                '.NewLine = "LF"
                aa = .NewLine
                '.ReceivedBytesThreshold = 1
            End With

            ''コントロール制御
            btnComOpen.Enabled = False
            btnComClose.Enabled = True
            tabComInfo.Enabled = False
            pnlBody.Enabled = True

            'Catch exInvalidOperation As System.InvalidOperationException
            'Catch exArgumentOutOfRange As System.ArgumentOutOfRangeException
            'Catch exArgument As System.ArgumentException
            'Catch exIO As System.IO.IOException
            'Catch exUnauthorizedAccess As System.UnauthorizedAccessException
        Catch ex As Exception

            MessageBox.Show(ex.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    '--------------------------------------------------------------------------------
    '「切断」ボタンクリック
    '--------------------------------------------------------------------------------
    Private Sub btnComClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComClose.Click

        ''ポートがオープンされている場合閉じる
        If (_com.IsOpen = True) Then
            Call _com.Close()
            Call AddMessage(" --- " + _com.PortName + "クローズ")
        End If

        ''コントロール制御
        btnComOpen.Enabled = True
        btnComClose.Enabled = False
        tabComInfo.Enabled = True
        pnlBody.Enabled = False

    End Sub

    '--------------------------------------------------------------------------------
    '「文字列送信」ボタンクリック
    '--------------------------------------------------------------------------------
    Private Sub btnSendData_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) Handles btnSendData.Click

        If (txtSendData.Text.Length = 0) Then
            MessageBox.Show("送信文字列を入力してください", "エラー", _
                            MessageBoxButtons.OK, MessageBoxIcon.Error)
            txtSendData.Focus()
            Exit Sub
        End If

        Try
            _com.WriteLine(txtSendData.Text)
            Call AddMessage("[SND]" + txtSendData.Text)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub

    '--------------------------------------------------------------------------------
    '「終了」ボタンクリック
    '--------------------------------------------------------------------------------
    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click

        Me.Close()

    End Sub
End Class

- 関連一覧ツリー をクリックするとツリー全体を一括表示します)

古いスレッドにレスはつけられません。