Receive data from Alpha via serial in C#

Asked

Viewed 804 times

3

I need to make an application that sends and receives data from an Aryan Eonard. I searched some examples of serial connection between c# and Arduin application and in all examples I had the same problem, Arduino receives the data sent by the application but the application does not receive the data sent by Arduino.

Follows codes used.

Application code c#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2 {
public partial class Form1 : Form {

    string RxString;
    public Form1() {
        InitializeComponent();
        timerCOM.Enabled = true;
    }

    private void atualizaListaCOMs() {
        int i;
        bool quantDiferente; //flag para sinalizar que a quantidade de portas mudou

        i = 0;
        quantDiferente = false;

        //se a quantidade de portas mudou
        if (comboBox1.Items.Count == SerialPort.GetPortNames().Length) {
            foreach (string s in SerialPort.GetPortNames()) {
                if (comboBox1.Items[i++].Equals(s) == false) {
                    quantDiferente = true;
                }
            }
        } else {
            quantDiferente = true;
        }

        //Se não foi detectado diferença
        if (quantDiferente == false) {
            return;                     //retorna
        }

        //limpa comboBox
        comboBox1.Items.Clear();

        //adiciona todas as COM diponíveis na lista
        foreach (string s in SerialPort.GetPortNames()) {
            comboBox1.Items.Add(s);
        }
        //seleciona a primeira posição da lista
        comboBox1.SelectedIndex = 0;
    }

    private void timerCOM_Tick(object sender, EventArgs e) {
        atualizaListaCOMs();
    }

    private void btConectar_Click(object sender, EventArgs e) {
        if (serialPort1.IsOpen == false) {
            try {
                serialPort1.PortName = comboBox1.Items[comboBox1.SelectedIndex].ToString();
                serialPort1.Open();

            } catch {
                return;

            }
            if (serialPort1.IsOpen) {
                btConectar.Text = "Desconectar";
                comboBox1.Enabled = false;

            }
        } else {

            try {
                serialPort1.Close();
                comboBox1.Enabled = true;
                btConectar.Text = "Conectar";
            } catch {
                return;
            }

        }
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
        if (serialPort1.IsOpen == true)  // se porta aberta
            serialPort1.Close();         //fecha a porta
    }

    private void btEnviar_Click(object sender, EventArgs e) {
        if (serialPort1.IsOpen == true)          //porta está aberta
            serialPort1.Write(textBoxEnviar.Text);  //envia o texto presente no textbox Enviar
    }

    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) {
        RxString = serialPort1.ReadExisting();              //le o dado disponível na serial
        this.Invoke(new EventHandler(trataDadoRecebido));   //chama outra thread para escrever o dado no text box
    }

    private void trataDadoRecebido(object sender, EventArgs e) {
        textBoxReceber.AppendText(RxString);
    }
    }
}

Code Arduin:

void setup()
{
  Serial.begin(9600);  //inicia comunicação serial com 9600
}

void loop()
{
  if(Serial.available())        //se algum dado disponível
  {
    char c = Serial.read();   //le o byte disponivel
    delay(500);
    Serial.write(c);           //retorna o que foi lido
  }
}
  • 1

    I have an application with C# and Arduino. I will organize it to post to you.

  • Please, it would be great. I have the problem yet, I’m already thinking about changing language.

  • I did it between a Mac and a Leonardo. I used the Lib "Webusbserial" on Leonardo. This can be used to send and receive data in Google Chrome using Javascript. I don’t know if it can help. https://github.com/webusb/arduino

1 answer

0

In your Arduino code, modify the Serial.write command to Serial.Println. The latter sends the data output to the connected application. Note: Serial.read receives in bytes.

void setup()
{
  Serial.begin(9600);  //inicia comunicação serial com 9600
}

void loop()
{
  if(Serial.available())        //se algum dado disponível
  {
    char c = Serial.read();   //le o byte disponivel
    delay(500);
    Serial.println(c);           //retorna o que foi lido
  }
}
  • I tried using println, it didn’t work either.

Browser other questions tagged

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