Go Down

Topic: Sending commands to Arduino Using C# (Read 30641 times) previous topic - next topic

bdourass

Awesome..I will try it first thing in the morning when i get to the lab...it seems like both codes are for the Arduino...i guess the code for C# that you provided me before remains the same..I can run it still!!!??

Thank you very very much

GrooveFlotilla

#16
Jul 20, 2010, 08:53 am Last Edit: Jul 20, 2010, 04:01 pm by GrooveFlotilla Reason: 1
Quote
case 48:


As AWOL pointed out earlier,
Code: [Select]
case '1': is much easier to read than
Code: [Select]
case 49:, and has been said many, many times before, you don't need to carry around an ASCII chart in your head.

@greymalkin:
Quote
it should be positive numbers returned by Serial.read();

"read" returns -1 when the buffer is empty.
It's mentioned in the documentation.
Some people are like Slinkies.

Not really good for anything, but they bring a smile to your face when pushed down the stairs.

bdourass

It works perfectly...God you just made my day:)
I will now try to modify it to shift to a GUI and that is  my last stage as far as C# goes...thank God.
How do you know all this at 15? very impressive

bdourass

Groove, you are right!! i just wanted to see if there is a communication between C# and Arduino an the fact that it returns -1 tells me that C# knows that nothing is in the Arduino. and as far as ASCII goes, you are absolutely right!! i'll make the change accordignly...thank you for the hints

graymalkin

#19
Jul 20, 2010, 06:50 pm Last Edit: Jul 21, 2010, 12:30 am by Gray_Malkin Reason: 1
ooh, yes... I forget that chars are just ints in disguise... well then that makes life easier still!
Code: [Select]

switch (input){
 case '0':
    digitalWrite(13, LOW);
    break;
 case '1':
    digitalWrite(13, HIGH);
    break;
}



Also, apologies to AWOL for posting exactly the opposite of what he put in the first place which was use a char instead of case 1: or case 49:

graymalkin

#20
Jul 20, 2010, 06:59 pm Last Edit: Jul 20, 2010, 07:00 pm by Gray_Malkin Reason: 1
Ok, for a GUI you just have to make a Windows Forms app, and create a serial object, first off add buttons and such to your app.

Then, double click the window, it should make an even handeler for window loaded, also, on the first line (with the other using statements) add

Code: [Select]
using System.IO.Ports;

above the Window loaded method add
Code: [Select]
SerialPort port;
Then make window loaded look a bit like this.
Code: [Select]

void Window_Load(object sender, EventArgs e)
{
   // Like a setup thing this...  We need to make a new serial object.
   // We'll give the port a name, baud and start it now
   port = new SerialPort("COM4", 115200);  // Name and baud, change as required
   port.Open()  // Open the new port! Done.
}


Ok, so now go back and double click your button(s)
add something like this in each method:
Code: [Select]
port.Write("1");

Easy.

bdourass

I am on it master...I'll let you know how easy it is for me... :-X...thank you much

bdourass

One quick question!! in c# i noticed when you click new project on Microsoft Visual C# 2010 software it asks what type of project: console applcation,windows appli, WPF application,etc...do i choose WPF for a GUI or windows application will do the trick....just thought it might better to get it for once and all

PaulS

Choose Windows Application.

I have a completed windows application that communicates with the Arduino that you could use a starting point. Let me know, and I'll email you a zip file.

bdourass

PaulS,
That would be awesome..i guess it would better not to reinvent the wheel if i can if i can have a starting point..and they can expand however needed.

bdourass

Sorry fast typing is not a good option without revising...I basically wanted to say then instead of they toward the last sentence..thank god we're not graded for this:)

graymalkin

I don't see why WPF apps wouldn't work, but for the sake of sending a 1 or 0 over serial, it hardly seems worth it

bdourass

OK..I guess I'm looping around the answer but i'm too blind to see it..
this is the code to read or write to a serial Arduino port so far:

+++++++++++++++++++++++++++++++++++++++++


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

namespace TuesdayGUItrial1
{
     /// <summary>
     /// Description of MainForm.
     /// </summary>
     ///
     
     public partial class MainForm : System.Windows.Forms.Form
     {
           string InputData = String.Empty;
       System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
       delegate void SetTextCallback(string text);


           private System.Windows.Forms.ListBox listBox1;
         private System.Windows.Forms.Button button1;
         private System.Windows.Forms.TextBox textBox1;
         private System.Windows.Forms.Button button2;
         
         
         
          
          public MainForm()
           {
                 //
                 // The InitializeComponent() call is required for Windows Forms designer support.
                 //
                 InitializeComponent();
                 
                 //
                 // TODO: Add constructor code after the InitializeComponent() call.
                 //
                 port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(ReadSample3_Load);//port_DataReceived_1
           }
          
          
          private void ReadSample3_Load(object sender, EventArgs e)
       {
           if (port.IsOpen)
               port.PortName = "COM4";
           
           // try to open the selected port:
           try
           {
              port.PortName = "COM4";

               port.BaudRate = 115200;
               //port.DataBits = 8;
               //port.Parity = Parity.None;
               //port.StopBits = StopBits.One;
               //port.DtrEnable = true;
               //port.Handshake = Handshake.None;
               //port.DtrEnable = true;
               port.Open();
           }
           // give a message, if the port is not available:
           catch
           {
               MessageBox.Show("Serial port " + port.PortName +
               "cannot be opened!", "RS232 tester",
               MessageBoxButtons.OK, MessageBoxIcon.Warning);
               
           }
       }

          
           private void port_DataReceived_1(object sender,SerialDataReceivedEventArgs e)
       {
                 Thread.Sleep(500);
           InputData = port.ReadExisting();
           if (InputData != String.Empty)
           {
               this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
           }
       }

       private void SetText(string text)
       {
           this.textBox1.Text += text;
       }

           private void button1_Click(object sender, System.EventArgs e)
         {
                 port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
                 
         }

         private void button2_Click(object sender, System.EventArgs e)
         {
               if (port.IsOpen) port.WriteLine(textBox1.Text);
           else MessageBox.Show("Serial port is closed!",
                                "USB tester",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
           textBox1.Clear();

           //Application.Exit();
         }      

         
   }
}
+++++++++++++++++++++++++++++++++++++
it pops a GUI with a "Send" and "Stop" buttons and a List Box
I can click on"Stop" and the computer displays a meassage as requested" serial port is closed"
BUT when i click"Send" nothing happens...so i'm not sure if the functions were called and the PORT was open and set to "COM4" and "115200" ......1) how can i display whether the port is read and the baud rate was set?
2) am I calling the right method when i click "Send" ?
3) Is the structure of the code is where everything supposed to be?
It is kind of confusing to do the whole eventhandling thing!!!! :-[  

I need any help I can get ...thank you

graymalkin

#28
Jul 21, 2010, 11:44 am Last Edit: Jul 21, 2010, 11:48 am by Gray_Malkin Reason: 1
Not sure why you are using threading... You should be able to just use the event hadneler and add the data straight to the text box. There is the issue with packet splitting perhaps, but that doesn't warrant a half second delay, it needs a cleverer way of fixing that.  Also, I used port.Write("blah blah blah"); because it sends a new line character too if you use write line

With delegates it is better practice to use the object being delegated with to invoke, eg,
Code: [Select]
this.textBox1.Invoke();

PaulS

Quote
it pops a GUI with a "Send" and "Stop" buttons and a List Box

There is also a Connect! button. You need to set the correct port, from the drop down list, and the correct speed (whatever the Arduino is communicating at), and then click the Connect! button.

The button title will change to <Connected> if the connection can be established.

It sends nothing to the Arduino during this process.

Strings to be sent to the Arduino can then be typed in the Data to send field. Press the Send button to send the data. There is no carriage return/line feed appended to the string sent, so, if your Arduino is expecting them, you need to change the sendBtn_Click method to send them, too.

Any data received on the serial port triggers a callback that reads the data and shows it in the response field.

The 3 buttons on the bottom send specific commands that my LCD understands. You probably won't have a need for them.

Go Up