How to use two sensors in the Arduino and show the data in a C#application?

Asked

Viewed 98 times

-2

I have a code in the Arduino where has 1 ultrasonic sensor that measures the amount of liquid, and in a tank a flow sensor that measures the amount of water consumed. In the other code C# I have an ihm that takes the values of the ultrasonic sensor and the flow sensor, but in the code I am not able to separate the received values in the serial port, generates an error someone can help me?

#define motor1 13
#define motor2 12
///////////////////////////////
      //SENSOR DE VAZÃO//
int Pulso; //VARIÁVEL PARA QUANTIDADE DE PULSOS.
int j=0; //VARIÁVEL PARA CONTAGEM
float vazaoagua; // Variável para armazenar o valor em L/min
float valormedia = 0; //VARIÁVEL PARA TIRAR A MÉDIA A CADA 1 MINUTO
//////////////////////////////

//PORTA EM QUE O SENSOR ULTRASSONICO ESTARA LIGADO...

#define trigPin 10 //PINO TRIG DO SENSOR NO PINO ANALÓGICO A1
#define echoPin 11 //PINO ECHO DO SENSOR NO PINO ANALÓGICO A0

unsigned int duracao = 0;
unsigned int distancia = 0;

int data;

////////////////////////////////////////////

void setup() {

  Serial.begin(9600);// DEFINE VELOCIDADE CONEXÃO SERIAL

  //DEFINE OS PINOS DE ENTRADA E SAÍDA ...
  pinMode (trigPin, OUTPUT);// DEFINE SAÍDA
  pinMode (echoPin, INPUT);// DEFINE ENTRADA

  //MOTOR DA BOMBA 1
  pinMode(motor1, OUTPUT); //DEFINE O PINO COMO SAÍDA

   //MOTOR DA BOMBA 2
  pinMode(motor2, OUTPUT); //DEFINE O PINO COMO SAÍDA

  ///////////////////////////////////////////////////////////
         //SENSOR DE FLUXO DE AGUA//
  pinMode(2, INPUT);
  attachInterrupt(0, incrpulso, RISING); //CONFIGURA A PORTA DIGITAL 2, PARA INTERRUPÇÃO

}

void loop() {
   

  /////ACIONAMENTO DAS BOMBAS //////
  if(Serial.available()){
    data= Serial.read();

  //ACIONAMENTO DA BOMBA 1
    if(data== 'A'){
      digitalWrite(motor1, HIGH);
    }
    if(data== 'B'){
      digitalWrite(motor1, LOW);
    }
  //ACIONAMENTO DA BOMBA 2
    if(data== 'C'){
      digitalWrite(motor2, HIGH);
    }
    if(data== 'D'){
      digitalWrite(motor2, LOW);
    }

  }

  //////////////SENSOR ULTRASSONICO.../////////////////

    digitalWrite(trigPin, HIGH); //ELEVA O SINAL DO TRIGGER
    delayMicroseconds(10);//POR 10 MICROSEGUNDOS
    digitalWrite(trigPin, LOW);

    //Armazena o valor em microsegundos  que foi lido
    duracao= pulseIn(echoPin, HIGH);

    distancia = duracao * 0.017175; //(340 * 100 / 10e6)

    Serial.print(distancia);
    Serial.println("cm");
    delay(500);

    ///////////////SENSOR DE FLUXO DE AGUA /////////////////////

   Pulso = 0; //Começa do 0 variável para contar os giros das pás internas,ek segundos
   sei(); //liga interrupção
   delay (2000); //Espera 2 segundos
   cli(); //Desliga interrupção

   vazaoagua = Pulso / 7.5; //Converte para Litros/minuto
   valormedia = valormedia+vazaoagua; //Soma a vazão para o calculo da valormedia
   j++;

   Serial.print(vazaoagua); //Imprime na serial o valor da vazão
   Serial.println("L"); //Imprime L/min
   if(j==60)

   {

    valormedia = valormedia/60; //Tira a valormedia dividindo por 60
    Serial.print("\n Media por minuto = "); //Imprime a frase valormedia por minuto =
    Serial.print(valormedia); //Imprime o valor da valormedia
    Serial.println(" Litros/minutos - "); //Imprime L/min
    valormedia = 0; //Torna variável valormedia = 0, para uma nova contagem
    j=0; //Torna a variável 0,para uma nova contagem
   }
    
   }

   void incrpulso ()
   { 
    Pulso++;
    }

Code 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;

namespace Abastecimento_de_tanque
{
    public partial class Form1 : Form
    {
        string serialDataIn;
        sbyte indexOfA, indexOfB;
        string dataSensor1, dataSensor2;

        public Form1()
        {
            InitializeComponent();
        }

        //CLASSE ACIONAMENTO DA BOMBA 1...
        public void Ligarbomba1()
        {
            try
            {
                if (btnLigar.BackColor.Equals(Color.Green))
                {
                    btnLigar.BackColor = Color.Red;
                    serialPort1.Write("A");
                    btnLigar.Text = "BOMBA LIGADA";

                }
                else
                {
                    serialPort1.Write("B");
                    btnLigar.BackColor = Color.Green;
                    btnLigar.Text = "BOMBA DESLIGADA";
                }
              
            }
            catch (Exception erro)
            {
                //erro
                MessageBox.Show(erro.Message);
            }
        }

        //CLASSE ACIONAMENTO DA BOMBA 2...
        public void LigaBomba2()
        {
            try
            {
                if (btnLigaBomba2.BackColor.Equals(Color.Green))
                {
                    btnLigaBomba2.BackColor = Color.Red;
                    serialPort1.Write("C");
                    btnLigaBomba2.Text = "BOMBA LIGADA";

                }
                else
                {
                    serialPort1.Write("D");
                    btnLigaBomba2.BackColor = Color.Green;
                    btnLigaBomba2.Text = "BOMBA DESLIGADA";
                }

            }
            catch (Exception erro)
            {
                //erro
                MessageBox.Show(erro.Message);
            }
        }

        //carrega a porta serial escolhida...
        private void Form1_Load(object sender, EventArgs e)
        {

            //regra de negocio barra de status do tranque...
            lblVazio.Enabled = false;
            lblMedio.Enabled = false;
            lblCheio.Enabled = false;
            lblCetentaPorcento.Enabled = false;
            lblVintePorCento.Enabled = false;


            //classe buscar porta serial...
            BuscarPortSerial();

            //recebe leitura de dados da port aserial (do sensor ultrassonico)..
          

            //configurações do botão liga bomba 1
            btnLigar.Text = "BOMBA DESLIGADA";
            btnLigar.BackColor = Color.Green;

            //configurações do botão liga bomba 2
            btnLigaBomba2.Text = "BOMBA DESLIGADA";
            btnLigaBomba2.BackColor = Color.Green;
        }

        //---conexão com a porta serial
        public void BuscarPortSerial()
        {
            try
            {
                if (serialPort1.IsOpen==false)
                {
                    serialPort1.Open();
                    lblPort.Text = serialPort1.PortName.ToString();
                    lblStatus.Text = "ON";
                }
                else
                {
                    lblStatus.Text = "OFF";
                }
            }
            catch (Exception erro)
            {
                MessageBox.Show(erro.Message);
                this.Close();
            }
        }

        // fecha a porta serial ao dispositivo conectado...
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (serialPort1.IsOpen)
                {
                    serialPort1.Close();
                }
            }
            catch (Exception erro)
            {
                erro.Message.ToString();
            }
        }

        //acionamento da classe liga bomba 1...
        private void btnLigar_Click(object sender, EventArgs e)
        {
            Ligarbomba1();
        }

        //acionamento da classe bomba 2
        private void btnLigaBomba2_Click(object sender, EventArgs e)
        {
            LigaBomba2();
        }

        //recebe informaçãoe da porta serial...
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            serialDataIn = serialPort1.ReadLine();
            this.BeginInvoke(new EventHandler(ProcessData));

            serialDataIn = serialPort1.ReadLine();
            this.BeginInvoke(new EventHandler(FluxoAgua));
        }

        //barra de processebar mostra o status do tanque se esta cheio ou vazio...
        private void ProcessData(object sender, EventArgs e)
        {
            try
            {

                // MOSTRA O NÍVEL DO TANQUE
                indexOfA = Convert.ToSByte(serialDataIn.IndexOf("cm"));
                indexOfB = Convert.ToSByte(serialDataIn.IndexOf("L"));


                dataSensor1 = serialDataIn.Substring(0,indexOfA);
                //dataSensor2 = serialDataIn.Substring(indexOfB);

                lblPorcentagem.Text = dataSensor1;
                //lblConsumo.Text = dataSensor2;

                progressBar9.Value = Convert.ToInt16(dataSensor1);
                //textBox1.Text = Convert.ToString(dataSensor2);

            }
            catch (Exception erro)
            {
                lblInformacao.Text = (erro.Message);
            }
        }
        private void FluxoAgua(object sender, EventArgs e)
        {
            indexOfB = Convert.ToSByte(serialDataIn.IndexOf("L"));

            dataSensor2 = serialDataIn.Substring(indexOfB);

            textBox1.Text = Convert.ToString(dataSensor2);

        }

        //mostra o status do nível da caixa d'agua...
        private void timer1_Tick(object sender, EventArgs e)
        {
           // BuscarPortSerial();

            try
            {
              
                if (lblPorcentagem.Text == "15")
                {
                    //MENSAGEM DE TANQUE NÍVEL BAIXO
                    lblInformacao.Text=("TANQUE A 15% BOMBA LIGADA");
                    serialPort1.Write("A");
                    btnLigar.Text = "BOMBA LIGADA";
                    btnLigar.BackColor = Color.Red;
                }
                if (lblPorcentagem.Text == "50")
                {
                    //
                   // listMensagens.Items.Add("TANQUE A 50% DO NÍVEL DESEJADO");
                }
                if (lblPorcentagem.Text == "75")
                {
                    //
                  //  listMensagens.Text = "TANQUE ESTA QUASE CHEIO.";
                }
                if (lblPorcentagem.Text == "90")
                {
                    //MENSAGEM DE TANQUE CHEIO
                    lblInformacao.Text = "TANQUE CHEIO, BOMBA DESLIGADA.";
                    serialPort1.Write("B");
                    btnLigar.Text = "BOMBA DESLIGADA";
                    btnLigar.BackColor = Color.Green;
                }
            }
            catch (Exception erro)
            {
                lblInformacao.Text =(erro.Message);
            }
        }

        //Informa status de mensagens de erro e advertencia do sistema...
        private void picMensagem_Click(object sender, EventArgs e)
        {
            frmMensagens frm = new frmMensagens();
            frm.ShowDialog();
        }
    }
}

inserir a descrição da imagem aqui

System.Argued tofrangeexception: 'Length cannot be less than zero.

I tried to make some modifications more unsuccessfully.

  • 1

    When you say that it generates an error, it is important that you present the generated error and also point out in the code where it occurs. Always try to ask the question based on a [mcve]

  • System.Argued tofrangeexception: 'Length cannot be less than zero.

1 answer

0

This is what we call an XY problem. Fixing the error in the code is simple, but that doesn’t mean it will solve your problem.

The error happens because you try to catch part of the string starting from position 0 to -1, because no "L" was found in serialDataIn at the time when the method FluxoAgua() was invoked. Now, if there should be any value in that string, it is another point that you will also have to fix.

private void FluxoAgua(object sender, EventArgs e)
{
    var indexOfL = serialDataIn.IndexOf("L");   

    textBox1.Text = indexOfL > 0 ? serialDataIn.Substring(indexOfL): string.Empty;

}

Your code has a number of scope problems, namespace, unnecessary conversions and redundancy you need to review. In addition to not making sense to keep the indices in a "global" scope, this can cause several problems in logic when running any of the methods.

  • Thanks for the help!

  • Thanks for the help! Yes the Code is full of unnecessary things, but when I started I tried to do it in a more organized way, more like it is for study and a course work I was testing some things changing other, I made a salad kkkkk, more with your help I managed to solve this problem, Thanks even :)

  • Then accept the post as an answer or close the question :P

Browser other questions tagged

You are not signed in. Login or sign up in order to post.