2

I am working with C# and arduino. I am still a newbie on this. I wish someone can help me. So my project is to send some code to Arduino. Then apply delay on Arduino and send back some string/char back to C#. I gave a textbox on C# to show the result of reading. This is my code: C# code

Public form1()
{
    initializeComponent();
    Serialport1.Open();
}

public void Read()
{
    while (Serialport1.IsOpen)
    {
        try
        {
            string message = SerialPort1.ReadLine();
            textbox1.text = message;
        }
        catch (timeoutException)
        {
        }
    }
}
private void button1_click(object sender, eventargs e)
{
    SerialPort1.write("A");
    read();
}

arduino code:

int data;
void setup()
{
    Serial.begin(9600);
    Serial.print("START\n");
}

void loop()
{
    if(Serial.available())
    {
        data = Serial.read();
        if(data=='A')
        {
            delay(3000);
            Serial.print("B");
        }
    }
}

What I wish is textbox result write B, but nothing is come and the textbox keep blank. What did I do wrong? I hope someone can explain to me. Thank you

3 Answers 3

1

ReadLine is a method that according to documentation

returns the contents of the input buffer up to the first occurrence of a NewLine value.
....
By default, the ReadLine method will block until a line is received. If this behavior is undesirable, set the ReadTimeout property to any non-zero value to force the ReadLine method to throw a TimeoutException if a line is not available on the port.

So if you look at what the arduino is sending it is just a "B". Either you should add a newline to the message: "B\n" or use the println method which would add automatically a new line.

But the main problem is actually that you never return from you method Read so the GUI will never be updated, and even if you receive something you will not see it.
Furthermore, in your while-loop it would be advisable to only read when data is in the buffer. You can use the BytesToRead property to check whether it is worth to read from the port:

while (Serialport1.IsOpen)
{
    if (Serialport1.BytesToRead > 0)
    {
        try
        {
            string message = Serialport1.ReadLine();
            textbox1.text = message;
            // break out the while loop here so that you can see the content of the textbox
            break;
        }
        catch (Exception ex)
        {
            textbox1.text = "ERROR: " + ex.Message;
        }
    }
}

Also it is a bad habit to catch an expection and don't do anything with this information. Because quite often it allows you to grasp the nature of the error. Up to now you are just masking it.

Sign up to request clarification or add additional context in comments.

Comments

1

You Should attach a listener to the port like this:
SerialPort port = new SerialPort("COM4", 9600); port.DataReceived += new SerialDataReceivedEventHandler(dataReceivedHandler); port.open();

And then write your handler like:

private void dataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();

        Dispatcher.Invoke(
            delegate
        {
            textbox1.Text = indata;
        });
    }  

Also your button click could be like this:

private void button1_click(object sender, RoutedEventArgs e)
    {
        try {               
            port.Write("A");                
        }
        catch (Exception ex)
        {
            textbox.Text = " Send Failed !";
        }
    }

Comments

1

Try this:

Function:

  • Computer:Click ON/OFF button
  • Arduino: Turn ON/OFF LED

Arduino Code:

const int LedPin = 13;  
int ledState = 0;  

void setup()  
{   
  pinMode(LedPin, OUTPUT);  

  Serial.begin(9600);    
}  

void loop()  
{   
    char receiveVal;     

    if(Serial.available() > 0)  
    {          
        receiveVal = Serial.read();  

       if(receiveVal == '1')      
          ledState = 1;     
       else  
          ledState = 0;       
    }     

    digitalWrite(LedPin, ledState);   

    delay(50);      
}  

C# code:

using System;
using System.Windows.Forms;
using System.IO.Ports;
namespace ledcontrol
{
    public partial class Form1 : Form
    {
        SerialPort port;
        public Form1()
        {
            InitializeComponent();
            this.FormClosed += new FormClosedEventHandler(Form1_FormClosed);
            if (port==null)
            {
                port = new SerialPort("COM7", 9600);//Set your board COM
                port.Open();
            }
        }
        void Form1_FormClosed(object sender,FormClosedEventArgs e)
        {
            if(port !=null &&port.IsOpen)
            {
                port.Close();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            PortWrite("1");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PortWrite("0");
        }
        private void PortWrite(string message)
        {
            port.Write(message);
        }
    }
}

You can see the tutorial here: http://www.lattepanda.com/topic-f6t1534.html?sid=0aac1b4a519c7a2d970b81059e6e581f

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.