数据接收问题接收

尖齿

新成员
已加入
2015年4月9日
留言内容
1
编程经验
Beginner
您好,
自从我从事该项目以来已经过去了一个月,该项目使用C#实现了一个通信接口,该接口可以通过串行端口在PC和轴控制之间发送和接收数据。
MCS轴控制被编程为接收或发送数据。
这是程序:
C#:
C#:
[COLOR=#008800]'User waiting press F6
wait dbtcom=on
 
'[/COLOR][COLOR=#660066]Reading[/COLOR][COLOR=#000000] bytes
repeat
  [/COLOR][COLOR=#000088]if[/COLOR][COLOR=#000000] len[/COLOR][COLOR=#666600]([/COLOR][COLOR=#000000]carac$[/COLOR][COLOR=#666600])<=[/COLOR][COLOR=#006666]8[/COLOR][COLOR=#000088]then[/COLOR][COLOR=#000000]
  [/COLOR][COLOR=#000088]char[/COLOR][COLOR=#000000]$[/COLOR][COLOR=#666600]=[/COLOR][COLOR=#000000]input$ [/COLOR][COLOR=#880000]#2,1[/COLOR][COLOR=#000000]
  [/COLOR][COLOR=#000088]end[/COLOR][COLOR=#000088]if[/COLOR][COLOR=#000000]
  carac$[/COLOR][COLOR=#666600]=[/COLOR][COLOR=#000000]carac$[/COLOR][COLOR=#666600]+[/COLOR][COLOR=#000088]char[/COLOR][COLOR=#000000]$
[/COLOR][COLOR=#000088]until[/COLOR][COLOR=#000000] carin[/COLOR][COLOR=#666600]([/COLOR][COLOR=#880000]#2)=0[/COLOR][COLOR=#000000]
 
[/COLOR][COLOR=#008800]'Acquisition of the "operation code"
car$=left$(carac$,1)
 
'[/COLOR][COLOR=#660066]If[/COLOR][COLOR=#000000] code [/COLOR][COLOR=#006666]10[/COLOR][COLOR=#000088]then[/COLOR][COLOR=#000000] launch the file receiving task
[/COLOR][COLOR=#000088]if[/COLOR][COLOR=#000000] car$[/COLOR][COLOR=#666600]=[/COLOR][COLOR=#000000]chr$[/COLOR][COLOR=#666600]([/COLOR][COLOR=#006666]10[/COLOR][COLOR=#666600])[/COLOR][COLOR=#000088]then[/COLOR][COLOR=#000000] 
halt envfile
halt recprog
halt envprog
RF[/COLOR][COLOR=#666600]=[/COLOR][COLOR=#000000]right$[/COLOR][COLOR=#666600]([/COLOR][COLOR=#000000]left$[/COLOR][COLOR=#666600]([/COLOR][COLOR=#000000]carac$[/COLOR][COLOR=#666600],[/COLOR][COLOR=#006666]3[/COLOR][COLOR=#666600]),[/COLOR][COLOR=#006666]2[/COLOR][COLOR=#666600])[/COLOR][COLOR=#000000]
run recfile
[/COLOR][COLOR=#000088]end[/COLOR][COLOR=#000088]if[/COLOR][COLOR=#000000]
 
[/COLOR][COLOR=#008800]'if code 11 then launch the task sending program
if car$=chr$(11) then
halt envfile
halt recprog
halt recfile
EPROG=right$(carac$,3)
run envprog
end if
 
'[/COLOR][COLOR=#660066]If[/COLOR][COLOR=#000000] code [/COLOR][COLOR=#006666]12[/COLOR][COLOR=#000088]then[/COLOR][COLOR=#000000] start the task reception program
[/COLOR][COLOR=#000088]if[/COLOR][COLOR=#000000] car$[/COLOR][COLOR=#666600]=[/COLOR][COLOR=#000000]chr$[/COLOR][COLOR=#666600]([/COLOR][COLOR=#006666]12[/COLOR][COLOR=#666600])[/COLOR][COLOR=#000088]then[/COLOR][COLOR=#000000]
halt envfile
halt envprog
halt recfile
RP[/COLOR][COLOR=#666600]=[/COLOR][COLOR=#000000]right$[/COLOR][COLOR=#666600]([/COLOR][COLOR=#000000]carac$[/COLOR][COLOR=#666600],[/COLOR][COLOR=#006666]3[/COLOR][COLOR=#666600])[/COLOR][COLOR=#000000]
run recprog
[/COLOR][COLOR=#000088]end[/COLOR][COLOR=#000088]if[/COLOR][COLOR=#000000]
 
[/COLOR][COLOR=#008800]'If code 13 then start the send file
if car$=chr$(13) then
halt envprog
halt recprog
halt recfile
EF=left$(carac$,1)
run envfile'[/COLOR][COLOR=#000000]
[/COLOR][COLOR=#000088]end[/COLOR][COLOR=#000088]if[/COLOR]


要开始通信,MCS希望代码10h,11h,12h或13h(对应于下面的程序已弄脏),然后在程序号上输入三个字符以开始治疗。
因此,我必须在此邮件中添加传递函数的程序。或者我必须添加以下行:
C#:
C#:
[COLOR=#880000]// if bouton reception[/COLOR][COLOR=#000000]
serialPort1[/COLOR][COLOR=#666600].[/COLOR][COLOR=#660066]WriteLine[/COLOR][COLOR=#666600]([/COLOR][COLOR=#008800]"\u000D"[/COLOR][COLOR=#666600]);[/COLOR][COLOR=#000000]

[/COLOR][COLOR=#880000]// if bouton envoyer[/COLOR][COLOR=#000000]
serialPort1[/COLOR][COLOR=#666600].[/COLOR][COLOR=#660066]WriteLine[/COLOR][COLOR=#666600]([/COLOR][COLOR=#008800]"\u000A"[/COLOR][COLOR=#666600]);[/COLOR]

我已连接到轴驱动器。
我有一些问题:
1-我并没有收集所有数据,每次按下按钮返回接收数据时您都有。
我使用dataReceived来接收数据。

2-对于发送,我无法在发送按钮和按钮之间同步(dbtcom = on,按F6,用户等待),我必须恢复信号Rx串行端口。

C#:
C#:
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.IO;
using System.Threading;


namespace Communicatio_1
{
    public partial class Form1 : Form
    {
        public byte[] bBufferBytes; //buffer a envoyer
        public delegate void myDelegate(byte sData);
        //public event SerialDataReceivedEventHandler DataReceived;
        public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
        public bool RtsEnable ;//{ get; set; };
        public bool DtrEnable ;//{ get; set; }
        public bool CtsHolding ; //{ get; }
       public bool DsrHolding ;//{ get; }




        public Form1()
        {
            InitializeComponent();
            this.Refresh();  
        }




        private void Form1_Load(object sender, EventArgs e) //l'?v?nement Form_Load nous lire tous les ports s?rie disponibles et nous assigner les valeurs ? la liste d?roulante.
        {
            //on commence par lister les voies s?ries pr?sentes
            String[] ports = SerialPort.GetPortNames(); //fonction statique
            //string [] ports = System.IO.Ports.SerialPort.GetPortNames ();
            for (int i = 0; i < ports.Length; i++) //on ajoute les ports au combo box
            {
                portBox.Items.Add(ports[i]);
                
            }


        }




        private void button_charger_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = "Chargement";// Titre
            openFileDialog1.FilterIndex = 1;


            if (openFileDialog1.ShowDialog(this) == DialogResult.OK) // Ouverture boite de dialogue OpenFile
            {
                textBox1.Text = string.Empty; // On vide le TextBox
                //backgroundWorker1.RunWorkerAsync();// executer le Background worker doWork()
                StreamReader sr = new StreamReader(openFileDialog1.OpenFile(), Encoding.Default); // Ouverture du fichier s?lectionn?
                // son nom est dans openFileDialog1.FileName


                try
                {
                    string data = sr.ReadLine();
                   
                    while (data != null)
                    {
                        bBufferBytes = System.Text.Encoding.ASCII.GetBytes(data); //Place le contenu dans un buffer d'octets (ASCII: 1 char = 1 octet) (UNICODE: 1 Char = 2 octets)
                        //serialPort1.Write(bBufferBytes, 0, bBufferBytes.Length);
                        textBox1.AppendText(data + "\r\n");


                        data = sr.ReadLine();


                        StatusLabel1.Text = "Transfert en cours...";
                        //  serialPort1.Write(bBufferBytes, 0, bBufferBytes.Length); // Ecrit le buffer complet sur le SerialPort
                        
                    }


                }


                finally
                {
                    if (sr != null)
                        sr.Close();
                     StatusLabel1.Text = "Transfert Fini ";
                }


            }
        }


        private void button_connecter_Click(object sender, EventArgs e)
        {
            serialPort1.PortName = portBox.SelectedItem.ToString();
            serialPort1.BaudRate = 9600;
            serialPort1.DataBits = 8;
            serialPort1.Parity = Parity.Even;
            serialPort1.StopBits = StopBits.One;            
            serialPort1.Handshake = Handshake.None;
            serialPort1.PortName = portBox.Text;
            serialPort1.RtsEnable = false;
            serialPort1.DtrEnable = false;
            
                
    // serialPort1.XonXoffOut = False
    //serialPort1.XonXoffIn = False
            


            // serialPort1.Open();
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            serialPort1.PinChanged += new SerialPinChangedEventHandler(serialPort1_PinChanged);
            try
            {
                serialPort1.Open();  //Ouvrez le SerialPort
                serialPort1.Write("chr13");
                bool blnCTS = serialPort1.CtsHolding;// lire CTS
                bool blnDSR = serialPort1.DsrHolding;// lire DSR
                bool blnCD = serialPort1.CDHolding;// lire CD
                StatusLabel1.Text = "serialPort1 : " + portBox.Text + " Opened";//Mettre ? jour le StatusStrip
                MessageBox.Show("Opened");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed: " + ex.Message);
            }


            button_connecter.Enabled = false;
            button_deconnecter.Enabled = true;
            textBox1.ReadOnly = false;
            textBox2.ReadOnly = false;
            radioButton.Enabled = true;
            radioButton.BackColor = Color.Black;


        }




        private void button_deconnecter_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Close();  //fermer le SerialPort
                StatusLabel1.Text = "serialPort1 : " + portBox.Text + " Closed"; //Mettre ? jour le StatusStrip
                MessageBox.Show("Closed");


            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed: " + ex.Message);
            }


            button_connecter.Enabled = true; // activer le button connecter
            button_deconnecter.Enabled = false;// desctiver le bitton deconnecter
            textBox1.ReadOnly = true;
            textBox2.ReadOnly = true;
            radioButton.BackColor = Color.White;
        }


        private void button_recevoir_Click(object sender, EventArgs e)
        {
            
            StatusLabel1.Text = "Appuyez sur 'F6' de la commande num?rique puis patientez...";
            serialPort1.Write("\u000D"); // lance la tache envoiFil


           // textBox2.SelectedText = string.Empty;
            //serialPort1.PinChanged += new SerialPinChangedEventHandler(serialPort1_PinChanged);
            //textBox2.AppendText(DataReceived.ToString());
        }




        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            
            string value = "";//string vide
              //tant qu'il y a des donn?es entr?e on continue
            
           while (serialPort1.BytesToRead > 0)
           {
                char[] buffer = new char[131072]; // on cr?e un char de 1024*128 caractere
               int  longueur_bytes_read = serialPort1.Read(buffer, 0, buffer.Length); //lecture du buffer jusqu'a sa longeur buffer.Length
                //tes characteres sont contenus dans buffer.
                //on remplit notre string value byte par byte par notre tableau de charactere buffer, le += fait que l'on ?crase pas les donn?es qui sont inser?es, mais on les ajoutes.
               for (int i = 0; i <= longueur_bytes_read; i++)
                {
                    value += buffer[i];
                }
            }
             safeInput(value.ToString());  //la methode toString passe tes bytes en characteres lisibles.
        }


        private void safeInput(string msg)
        {
            MethodInvoker method = delegate
                         {
                             textBox2.SelectedText = string.Empty; // on efface la textbox
                             textBox2.AppendText(msg + "\r\n"); // on met les donn?es dedans en string (conversion  char->string
                             StatusLabel1.Text = "Transfert en cours...";
                             
                         };
            if (InvokeRequired)
                BeginInvoke(method);
            else
                method.Invoke();
               StatusLabel1.Text = "Transfert Fini ";
            
        }


        private void button_envoyer_Click(object sender, EventArgs e)
        {
           StatusLabel1.Text = "Appuyez sur 'F6' de la commande num?rique puis patientez...";
           // backgroundWorker1.RunWorkerAsync();// executer le Background worker doWork()
          serialPort1.Write("\u000A"); // lance la tache receveFil chr13
           // backgroundWorker1.RunWorkerAsync();// executer le Background worker doWork()
          Thread.Sleep(1000);
          StatusLabel1.Text = "patient 'F6' de la commande num?rique puis patientez...";  
          StreamReader sr = new StreamReader(openFileDialog1.OpenFile(), Encoding.Default); 


            try
            {
                string data = sr.ReadLine();
               
                while (data != null)
                {
                    bBufferBytes = System.Text.Encoding.ASCII.GetBytes(data); //Place le contenu dans un buffer d'octets (ASCII: 1 char = 1 octet) (UNICODE: 1 Char = 2 octets)
                    
                    serialPort1.Write(bBufferBytes, 0, bBufferBytes.Length); // Ecrit le buffer complet sur le SerialPort                   
                    data = sr.ReadLine();
                    
                
                       // progressBar2.PerformStep();
                        StatusLabel1.Text = bBufferBytes.Length.ToString() + "%" + "T?lechargement en court...";
                       StatusLabel1.Text = "Transfert en cours...";
                    
                     }
                 } 


            finally
            {
                if (sr != null)
                    sr.Close();
                StatusLabel1.Text = "Transfert Fini ";
            } 
        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i <= 100; i++)
            {
                
                backgroundWorker1.ReportProgress(i);
                System.Threading.Thread.Sleep(100);
            }


        }


        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar2.Value = e.ProgressPercentage;
            StatusLabel1.Text = e.ProgressPercentage.ToString() + "%" + "T?lechargement en court...";
        }


        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            StatusLabel1.Text = ("T?lechargement Fini");
        }


        private void serialPort1_PinChanged(object sender, SerialPinChangedEventArgs e)
        {
            // Si les trois signaux d'entr?e changent au-dessus dudit cet ?v?nement PinChanged sera trriggered


            bool b;


            switch (e.EventType)
            {


                case System.IO.Ports.SerialPinChange.CDChanged:


                    b = serialPort1.CDHolding;


                    break;


                case System.IO.Ports.SerialPinChange.CtsChanged:


                    b = serialPort1.CtsHolding;


                    break;


                case System.IO.Ports.SerialPinChange.DsrChanged:


                    b = serialPort1.DsrHolding;


                    break;


                default:


                    break;


            }
        }


        private void button_sauvegarder_Click(object sender, EventArgs e)
        {
             
      /*  SaveFileDialog SaveFileDialog1 = new SaveFileDialog();
        SaveFileDialog1.Filter = "Text Files (*.txt)|*.txt";
        SaveFileDialog1.Title = "Save Received As";
        if (((SaveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
                    && (SaveFileDialog1.FileName.Length > 0))) {
            My.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName, Received.Text, false);
            //  Overwrite file
        }*/
    }


       
        }


    }
我的界面:
PNG格式

你能修复我的程序吗?
建议的解决方案我记得怎么办?
帮我
谢谢
 
最佳 底部