На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
  
> COM-Port C# , Общение с COM-портом отдать команду, получить ответ на команду...
    Здраствуйте господа-товарищи)) Знач так, буду конкретен:
    у нас есть :
    -новичек в программировании, т.е. Я ... опыта понты, но есть такая черта, как настырность... ;-)
    -Microsoft Visual Studio 2005.
    -Комп
    -компаратор (электронные весы, для взвешивания)
    -связь через ком-порт, компоратор+комп.
    Наша задача, нажав кнопку на форме программы, высылать команду на компаратор, получить результат взвешивания..
    Главная проблема, это общение с ком-портом, отдать команду - получить ответ...

    Что сделано, уже?

    ExpandedWrap disabled
      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Text;
      using System.Windows.Forms;
       
      namespace Sartorius
      {
          public partial class Form1 : Form
          {
              public Form1()
              {
                  InitializeComponent();
              }
       
              public void Test(object o, System.IO.Ports.SerialDataReceivedEventArgs args)
              {
       
                  MessageBox.Show("!");
                  
                  //lbFromUnit.Items.Add("Something has gone!");
       
              }
       
              private void button1_Click(object sender, EventArgs e)
              {
                  
                  System.IO.Ports.SerialPort myPort = new System.IO.Ports.SerialPort("COM1", 1200, System.IO.Ports.Parity.Odd, 7,
                      System.IO.Ports.StopBits.One);
       
                  myPort.ReadTimeout = 15*1000;
                  myPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Test);
                  myPort.RtsEnable = false;
                  myPort.DtrEnable = true;
                  
       
                  if (myPort.IsOpen == true)
                  {
                      myPort.Close();
                      System.Threading.Thread.Sleep(5 * 1000);
                  }
       
                  
                  char[] str= new char [100];
       
                  myPort.Open();
                
                  if (myPort.CtsHolding == true)
                  {
                      //MessageBox.Show("True");
                  }
                  else
                  {
                      //MessageBox.Show("False");
                  };
                  
       
                  //SerialDataReceivedEventHandler
       
                  //SerialDataReceivedEventHandler
       
                  //myPort.Read(str, 0, 22);
                  string s1;
                  //int bread = 0;
                  try
                  {
                      // Obtain the number of bytes waiting in the port's buffer
                      myPort.Write("1B 50 0D 0A"); // команда !? думаю тут я торможу от невежества в данном вопросе
                      
       
                      //int bytes = myPort.BytesToRead;
       
                      // Create a byte array buffer to hold the incoming data
                      //byte[] buffer = new byte[bytes];
       
                      // Read the data from the port and store it in our buffer
                      
                      //myPort.Read(buffer,0,bytes);
       
                      //int bread = myPort.ReadByte();
                      //s1 = bread.ToString();
                      //s1 = myPort.ReadExisting();
                      //s1 = myPort.ReadLine();
                      //myPort.Close();
                      //string s1 = new string(str);
                      s1 = myPort.ReadLine(); //myPort.ReadExisting();
       
                       lbFromUnit.Items.Add(s1);
                  }
       
                  catch(Exception e1)
                  {
                      MessageBox.Show(e1.Message.ToString()+"! "+e1.ToString());
                  }
                  finally
                  {
                      myPort.Close();
                  }
                  
                  
              }
       
              private void button2_Click(object sender, EventArgs e)
              {
                  lbFromUnit.Items.Clear();
                  string [] sp = System.IO.Ports.SerialPort.GetPortNames();
                  for (int i = 0; i < sp.Length; i++)
                  {
                      lbFromUnit.Items.Add(sp[i]);
                  }
              }
          }
      }

    Заранее благодарен за информацию, которая поможет мне решить этот вопрос..
    Сообщение отредактировано: juice -

    Прикреплённый файлПрикреплённый файлSartorius.rar (34.09 Кбайт, скачиваний: 747)
      :whistle:
        Цитата Graff_KotyarO:D @
        myPort.Write("1B 50 0D 0A"); // команда !? думаю тут я торможу от невежества в данном вопросе

        ExpandedWrap disabled
                      byte[] toSend = new byte[] {0x1B, 0x50, 0x0D, 0x0A};
                      port.Write(toSend, 0, toSend.Length);
          Чувак! Пасиба!.. :ph34r:
          0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
          0 пользователей:


          Рейтинг@Mail.ru
          [ Script execution time: 3,6230 ]   [ 16 queries used ]   [ Generated: 5.05.24, 00:45 GMT ]