logo elektroda
logo elektroda
X
logo elektroda
REKLAMA
REKLAMA
Adblock/uBlockOrigin/AdGuard mogą powodować znikanie niektórych postów z powodu nowej reguły.

Konfiguracja i obsługa SerialPort w Visual 2005 - porady i alternatywy API

kolanopan 19 Kwi 2008 11:38 2710 5
REKLAMA
  • #1 5053026
    kolanopan
    Poziom 12  
    Posty: 82
    Pomógł: 5
    Dwa pytanka do tematu

    Jak skonfigurować port i jakie są funkcje do obsługi odbierania-wysyłania danych ??

    Czy ktoś korzystał z tego komponentu, może lepiej wykorzystać API ??
  • REKLAMA
  • #2 5054168
    x3r
    Poziom 18  
    Posty: 126
    Pomógł: 32
    Ocena: 2
    Lepiej użyć klasy SerialPort niż importować API. Łap kawałek kodu z msdn. Jest prosty, czytelny i zawiera wszystko czego potrzebujesz.

    
    using System;
    using System.IO.Ports;
    using System.Threading;
    
    public class PortChat
    {
        static bool _continue;
        static SerialPort _serialPort;
    
        public static void Main()
        {
            string name;
            string message;
            StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
            Thread readThread = new Thread(Read);
    
            // Create a new SerialPort object with default settings.
            _serialPort = new SerialPort();
    
            // Allow the user to set the appropriate properties.
            _serialPort.PortName = SetPortName(_serialPort.PortName);
            _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
            _serialPort.Parity = SetPortParity(_serialPort.Parity);
            _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
            _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
            _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);
    
            // Set the read/write timeouts
            _serialPort.ReadTimeout = 500;
            _serialPort.WriteTimeout = 500;
    
            _serialPort.Open();
            _continue = true;
            readThread.Start();
    
            Console.Write("Name: ");
            name = Console.ReadLine();
    
            Console.WriteLine("Type QUIT to exit");
    
            while (_continue)
            {
                message = Console.ReadLine();
    
                if (stringComparer.Equals("quit", message))
                {
                    _continue = false;
                }
                else
                {
                    _serialPort.WriteLine(
                        String.Format("<{0}>: {1}", name, message) );
                }
            }
    
            readThread.Join();
            _serialPort.Close();
        }
    
        public static void Read()
        {
            while (_continue)
            {
                try
                {
                    string message = _serialPort.ReadLine();
                    Console.WriteLine(message);
                }
                catch (TimeoutException) { }
            }
        }
    
        public static string SetPortName(string defaultPortName)
        {
            string portName;
    
            Console.WriteLine("Available Ports:");
            foreach (string s in SerialPort.GetPortNames())
            {
                Console.WriteLine("   {0}", s);
            }
    
            Console.Write("COM port({0}): ", defaultPortName);
            portName = Console.ReadLine();
    
            if (portName == "")
            {
                portName = defaultPortName;
            }
            return portName;
        }
    
        public static int SetPortBaudRate(int defaultPortBaudRate)
        {
            string baudRate;
    
            Console.Write("Baud Rate({0}): ", defaultPortBaudRate);
            baudRate = Console.ReadLine();
    
            if (baudRate == "")
            {
                baudRate = defaultPortBaudRate.ToString();
            }
    
            return int.Parse(baudRate);
        }
    
        public static Parity SetPortParity(Parity defaultPortParity)
        {
            string parity;
    
            Console.WriteLine("Available Parity options:");
            foreach (string s in Enum.GetNames(typeof(Parity)))
            {
                Console.WriteLine("   {0}", s);
            }
    
            Console.Write("Parity({0}):", defaultPortParity.ToString());
            parity = Console.ReadLine();
    
            if (parity == "")
            {
                parity = defaultPortParity.ToString();
            }
    
            return (Parity)Enum.Parse(typeof(Parity), parity);
        }
    
        public static int SetPortDataBits(int defaultPortDataBits)
        {
            string dataBits;
    
            Console.Write("Data Bits({0}): ", defaultPortDataBits);
            dataBits = Console.ReadLine();
    
            if (dataBits == "")
            {
                dataBits = defaultPortDataBits.ToString();
            }
    
            return int.Parse(dataBits);
        }
    
        public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
        {
            string stopBits;
    
            Console.WriteLine("Available Stop Bits options:");
            foreach (string s in Enum.GetNames(typeof(StopBits)))
            {
                Console.WriteLine("   {0}", s);
            }
    
            Console.Write("Stop Bits({0}):", defaultPortStopBits.ToString());
            stopBits = Console.ReadLine();
    
            if (stopBits == "")
            {
                stopBits = defaultPortStopBits.ToString();
            }
    
            return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
        }
    
        public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
        {
            string handshake;
    
            Console.WriteLine("Available Handshake options:");
            foreach (string s in Enum.GetNames(typeof(Handshake)))
            {
                Console.WriteLine("   {0}", s);
            }
    
            Console.Write("Stop Bits({0}):", defaultPortHandshake.ToString());
            handshake = Console.ReadLine();
    
            if (handshake == "")
            {
                handshake = defaultPortHandshake.ToString();
            }
    
            return (Handshake)Enum.Parse(typeof(Handshake), handshake);
        }
    }
    


    pozdrawiam
  • REKLAMA
  • #3 5059062
    kolanopan
    Poziom 12  
    Posty: 82
    Pomógł: 5
    jak narazie po ustawieniu parametrów portu w properties i wykorzystaniu kodu:

    
    serialPort1->Open();
    String ^SendString = "A";
    serialPort1->Write(SendString);
    serialPort1->Close();
    


    Udało mi sie wysłać przez port literke "A"

    teraz będę walczyć z odczytem, generalnie trudno mi sie przyzwyczaić do tego 2005, te wszystkie ptaszki przy klasach i zawiłe przykłady z MSDN...

    będe walczyć dalej i dam znać o wynikach
  • REKLAMA
  • #4 5476849
    Maidey
    Poziom 11  
    Posty: 18
    Ocena: 1
    Witam

    Ja zabawe z VC++ dopiero zaczynam. Korzystam z wersji 2008. W każdym razie mam za zadanie wysłać przez RS232 4 bajty jeden po drugim. Np. 255, 4, 187, 148. A ponieważ polecenie Write dla serialPort wysyła tylko stringa to nie wiem jak wysłać te wartości liczbowe. Bo chyba nie musze ich jeszcze konwertować na wartości binarne?

    Czy ktoś mi może podpowiedzieć jak wysyłać wartości int? Czy musze to robić za pomocą jakiejś tablicy?

    Będę wdzięczny :)
  • REKLAMA
  • #5 5481389
    x3r
    Poziom 18  
    Posty: 126
    Pomógł: 32
    Ocena: 2
    Konwertujesz sobie byte czy int czy co tam chcesz do stringa i wysyłasz normalnie. Konwersja jest prosta i łatwo zjadziesz info na google ale ja bym użył metody ToString().

    pozdrawiam
  • #6 5482846
    Maidey
    Poziom 11  
    Posty: 18
    Ocena: 1
    Dowiedziałem sie, że można to tak wpisać:

    
    serialPort1->Open();
    array<unsigned char,1>^ buf = gcnew array<unsigned char,1>(4){0xFF, 0x03, 0xBB, 0x94};
    // Teraz wpisuje bajty
    serialPort1->Write(buf,0,buf->Length);
    serialPort1->Close();
    


    A teraz chciałem jeszcze zapytać czy da sie podejrzeć odpowiednie bufory, wartości w portach. Tzn ja więcej robiłem na sterownikach PLC i tam nawet jak nie miałem urządzenia zewnętrznego podpiętego to miałem możliwość podejrzenia co jest na odpowiednich wejściach i wyjściach. Czy jest coś takiego w VC++? Jakaś konsola czy coś takiego?

    Dzięki z góry :)
REKLAMA