当前位置:编程学习 > C#/ASP.NET >>

怎样将数据从串口写入到数据库中

最近碰到一个问题,也是和串口通信有关,各位兄弟姐妹帮我看看啊

[color=#FFFF00]protected void butt_Click(object sender, EventArgs e)//设置串口
        {
            MessageBox.Show("开始连接串口!!!");
            SerialPort serialPort1 = new System.IO.Ports.SerialPort();
            serialPort1.PortName = "COM1";           
            serialPort1.BaudRate = 38400;
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            serialPort1.ReadBufferSize = 4096;                 //接收缓冲区大小 
            serialPort1.ReceivedBytesThreshold = 17;//设置引发OnComm事件的字节长度     
            serialPort1.Open();
        }
        protected void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {      
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
                serialPort1.Open(); //打开串口
            }
            else
            {
                serialPort1.Open();//打开串口
            }
                System.Threading.Thread.Sleep(150);
                byte bytData;
                int bytnum;
                bytnum = serialPort1.BytesToRead;
                rebyte = bytnum;
                byte[] message = new byte[bytnum];
                for (int k = 0; k <= (bytnum - 1); k++)
                {
                    //bytData = (byte)serialPort1.ReadByte();
                    message[k] = (byte)serialPort1.ReadByte();
                    //this.Invoke(inte易做图ceUpdateHandle, bytData);
                    //message[k] = bytData;
                }
                decomposite(message);
            }[/color]
调试时,总执行不到 serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)函数,要不就提示串口已关闭,不知道为什么??? --------------------编程问答--------------------  if (serialPort1.IsOpen)
  {
  serialPort1.Close();
  serialPort1.Open(); //打开串口
  }
  else
  {
  serialPort1.Open();//打开串口
  }

你在这写着个干什么?

数据接收到,你又来开关串口干什么?? --------------------编程问答-------------------- 建议楼主找点串口的资料看看 --------------------编程问答--------------------
protected void butt_Click(object sender, EventArgs e)//设置串口
  {
  MessageBox.Show("开始连接串口!!!");
  SerialPort serialPort1 = new System.IO.Ports.SerialPort();
  serialPort1.PortName = "COM1";   
  serialPort1.BaudRate = 38400;
  serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
  serialPort1.ReadBufferSize = 4096; //接收缓冲区大小  
  serialPort1.ReceivedBytesThreshold = 17;//设置引发OnComm事件的字节长度   
  serialPort1.Open();
  }
  protected void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
  {   
string dataStr=serialPort1.ReadExisting(); //或使用  serialPort1.Read(dataSP, 0, 18); }
补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,