My code is this ;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace SerialTest2
{
    public partial class Form1 : Form
    {
        int  my_Value, SerialConverted_IntValue;
        public Form1()
        {
            InitializeComponent();
        }
        SerialPort mySerial = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
        private void Start_Button_Click(object sender, EventArgs e)
        {
            if (mySerial.IsOpen == false)
            {
                mySerial.Open();
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            mySerial.Handshake = Handshake.None;
            mySerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
        }
        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            if (mySerial.IsOpen)
            {
                int bytes = mySerial.BytesToRead;
                byte[] byte_buffer = new byte[bytes];
                mySerial.Read(byte_buffer, 0, bytes);
                SerialConverted_IntValue = byte_buffer[0];// Error shows this line
            }
        }



        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            my_Value = trackBar1.Value;
            textBox1.Text = my_Value.ToString();
            byte[] buffer_2_send = new byte[1];

            byte[] data_2_send = BitConverter.GetBytes(trackBar1.Value);
            buffer_2_send[0] = data_2_send[0];
            if (mySerial.IsOpen)
            {
                mySerial.Write(buffer_2_send, 0, buffer_2_send.Length);
            }
            Thread.Sleep(20);

            textBox2.Text = SerialConverted_IntValue.ToString();
        }
    }
}

What this code does is simply sends trackbar value to serialport and gets a response from serialport. And then writes that reasponse to textbox.

Problem is this: It works perfectly for a while. I continue to change trackbar value. After a while I get the exception message in this post's title.

I can't understand what's wrong. Can anyone please figure out what's going on? thanks

有帮助吗?

解决方案

This could happen if this line returns zero

 int bytes = mySerial.BytesToRead

so protect your read with

if(bytes > 0)
    SerialConverted_IntValue = byte_buffer[0];

其他提示

This is a normal mishap, the BytesToRead property value can be zero. While this sounds odd, you'd expect an event named "data received" to fire when data is received, the event also fires for other reasons. The e.EventType property tells you why.

And if you receive binary data then occasionally one of the bytes will have the value 0x1a, the ASCII code for Ctrl+Z which the legacy value for the end-of-file control character. Which is reported with e.EventType = SerialData.Eof. Kaboom in your code of course when you index an empty array. Whether or not Eof is reported is normally something that can be configured on serial ports, for some strange reason that was overlooked on the .NET wrapper.

Either checking e.EventType or the BytesToRead value are workarounds. Or the better one in your case, your code also mis-behaves when BytesToRead is larger than 1. You'll completely ignore the extra bytes you receive, that is data loss that's normally rather detrimental:

   if (e.EventType == SerialData.Chars) {
        SerialConverted_IntValue = mySerial.BaseStream.ReadByte();
   }

It seems that problem is here that bytes to read is 0 in this line

int bytes = mySerial.BytesToRead;

so you get that error here when trying to read first byte of array with length 0

SerialConverted_IntValue = byte_buffer[0];

If bytes is zero just return from function:

if(bytes == 0)
    return;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top