Comunicação Serial

Dia desses, por demanda de um projeto, resolvi criar um programa do tipo linha de comando, para enviar dados através da porta serial. Agora publico o dito, incluindo, como é de lei nesse blog, os fontes.

Para usar o programa, basta fazer o download e copiá-lo para alguma pasta (ia escrevendo "diretório", estou ficando velho...) e usar.

serialcomm -pCOM4 -b9600 -ddadosaenviar -w

Nesse caso o sistema enviará pela porta (-p) COM4, a uma taxa de (-b) 9600 bauds a sequencia de caracteres dadosaenviar (-d). Em seguida esperará (-w) que algum dado seja enviado de volta pela porta, encerrando com CRLF (char(13),char(10)). A sequência enviada sera escrita na tela e então o programa terminará. O parâmetro -w é, obviamente, opcional.

Pode-se também optar por enviar um arquivo em disco inteiro pela porta, para tanto:


serialcomm -pCOM4 -b9600 -farquivo.txt

sendo arquivo.txt o arquivo cujo conteúdo deverá ser enviado pela porta.

É isso. Abaixo, o fonte. Observem que eu usei uma lib chamada CommandLine para implementar o tratamento dos comandos enviados pelo usuário pela linha de comando. Eu acho esse lib sensacional, então aí vai para quem tiver interesse o link para a dita: http://commandline.codeplex.com/



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using CommandLine;
using CommandLine.Text;

namespace SerialComm
{
    sealed class Program
    {
        private static readonly HeadingInfo _headingInfo = new HeadingInfo("SerialComm", "0.9");
        private sealed class Options : CommandLineOptionsBase
        {
            [Option("p", "serialport", DefaultValue = "COM4", HelpText = "Serial port to be used (default=COM4).")]
            public string SerialPort { get; set; }

            [Option("b", "baudrate", DefaultValue = "9600", HelpText = "Speed to be used (bauds, default=9600).")]
            public string BaudRate { get; set; }

            [Option("d", "data", Required = true, HelpText = "Data to be sent.")]
            public string Data { get; set; }

            [Option("f", "filename", Required = false, HelpText = "Name of the file containing data to be sent.")]
            public string FileName { get; set; }

            [Option("w", "wait", HelpText = @"I will wait for data sending back. Sent data will be shown after end of transmition (/r/n ($D$A).")]
            public bool Wait { get; set; }

            [HelpOption]
            public string GetUsage()
            {
                var help = new HelpText
                {
                    Heading = _headingInfo,
                    Copyright = new CopyrightInfo("Mauro Assis (assismauro@hotmail.com)", 2012),
                    AdditionalNewLineAfterOption = true,
                    AddDashesToOption = true
                };
                help.AddOptions(this);
                return help;
            }
        }

        static SerialPort serial = null;
       
        static Options options = new Options();

        static void SendData()
        {
            try
            {
                serial.Write(options.Data);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Error sending data to {0}: {1}", options.SerialPort, ex.Message));
            }

        }

        static void SendFile()
        {
            try
            {
                byte[] binaryData = System.IO.File.ReadAllBytes(options.FileName);
                serial.Write(binaryData, 0, binaryData.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Error sending file {0} to {1}: {2}",options.FileName, options.SerialPort, ex.Message));
            }
        }

        static void WaitForReply()
        {
            string receivedData=serial.ReadLine();
            Console.WriteLine("Answer:");
            Console.WriteLine(receivedData);
        }
        
        static bool CreateSerialObject()
        {
            try
            {
                serial = new SerialPort(options.SerialPort, Convert.ToInt32(options.BaudRate));
                serial.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Error acessing {0}: {1}", options.SerialPort, ex.Message));
                return false;
            }
            return true;
        }

        static void Main(string[] args)
        {
            options = new Options();
            var parser = new CommandLineParser(new CommandLineParserSettings(Console.Error));
            if (!parser.ParseArguments(args, options))
                Environment.Exit(1);
      
            if (CreateSerialObject())
                if (options.Data != string.Empty)
                {
                    SendData();
                    if (options.Wait)
                        WaitForReply();
                    serial.Close();
                }
                else
                    SendFile();
        }
    }
}

Comentários

Postagens mais visitadas deste blog

Controle PID de Potência em Corrente Alternada - Arduino e TRIAC - Parte III

Dividindo um programa (sketch) do Arduino em mais de um arquivo

Controle PID de Potência em Corrente Alternada - Arduino e TRIAC - Parte I