Receiving data from Arduino to the textbox in c#

Asked

Viewed 26 times

0

I’m developing a design using Arduino Nano with Microsoft Visual Studio using the C#language. My goal is to turn on and erase the Arduino LED by MVS and tb read a message sent by the Arduino serial with a message set in the Arduino programming script sent by the Serial.println command ("Led on") when the led is on and the message: "Led Off" when the led is on.

Follow the codes:

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 LedOnLedOffStatus
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            getAvailablePorts(); //Obter portas disponíveis

            // Obter Portas Disponíveis
            button1.BackColor = Color.White;
            button2.BackColor = Color.White;

        }
        void getAvailablePorts()
        {
            String[] ports = SerialPort.GetPortNames();// Selecionar a COM
            comboBox1.Items.AddRange(ports);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            serialPort1.Open();
            if (serialPort1.IsOpen)
            {
                serialPort1.WriteLine("1");
            }
            serialPort1.Close();
            button1.BackColor = Color.Red;
            button2.BackColor = Color.White;
            
        }

       
        private void button2_Click(object sender, EventArgs e)
        {
            serialPort1.Open();
            if (serialPort1.IsOpen)
            {
                serialPort1.WriteLine("0");
            }
            serialPort1.Close();
            button2.BackColor = Color.Red;
            button1.BackColor = Color.White;

        }

        
        private void OnPrint(string v)
        {
            throw new NotImplementedException();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            serialPort1.Open();
            if (serialPort1.IsOpen == true)
            {
                serialPort1.ReadLine();
            }
        }
    }
}
'''
No Arduino:
'''
int led = 13;
char leitura;
void setup() {
Serial.begin(9600);
pinMode(led,OUTPUT);
}

void loop() {
leitura = Serial.read();
if (leitura == '1')
{
  digitalWrite(led,HIGH);
  Serial.println(" Led ligado");
}
  else if (leitura == '0')
  {
    digitalWrite(led,LOW);
    Serial.println( " Led desligado");
  }
}

The script worked on turning the led on and off, but the message does not appear in the led message textbox access and off.

Which script should I use and where is my error?

  • At what point do you want to read this message?

No answers

Browser other questions tagged

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