Serial Communication using Arduino and C#

Hi everyone,

I want to make an simple program which will help me understand how to communicate with arduino using C# code. The program consists in fade in/out a LED by changing an brightness value using a Scroll bar. See in this image.

In C# code first i defined my serial port.

 private void Portname_SelectedIndexChanged(object sender, EventArgs e)
        {
            serialPort1.BaudRate = 9600;
            serialPort1.PortName = Portname.Text;
            try
            {
                serialPort1.Open();
            
            }
            catch (Exception ex)
            {   MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
            
            }

then i designed my fade barscroll to balance my fade value and comunicate this value to arduino.

private void Fadebar_Scroll(object sender, EventArgs e)
        {
            int value = Fadebar.Value * 10;
   
            serialPort1.Write(Convert.ToString(value));
        }

Finally i use this arduino code:

#include<stdlib.h>


int ledPin = 9;    // LED connected to digital pin 9
String incomingstring = "";
int fadeValue = 0;

int stringToNumber(String thisString) {
  int i, value, length;
  length = thisString.length();
  char new[(length)];
  for(i=0; i<length; i++) {
    new[i] = thisString.charAt(i);
  }

  value = atoi(blah);
  return value;
}
void setup()  { 
  Serial.begin(9600); 
  pinMode(ledPin,OUTPUT);
} 

void loop()  { 
 if (Serial.available()>0){
 char incomingbyte =(char)Serial.read();
 incomingstring += incomingbyte;
 // Checks for null termination of the string.
    if (incomingbyte == '\0') {
      int fadeValue = stringToNumber(incomingstring);
      analogWrite(ledPin,fadeValue); 
        // Serial.print(fadeValue); 
        
      incomingstring = "";
    }
         
 }
}

Why doesnt work?

  1. How can i send an int value through an serialport?
  2. How can i print my fadeValue (Serial.print(fadeValue)) ? It appears "Serial Port "COM6" is already in use...".
  3. Can i debug arduino code?
            int value = Fadebar.Value * 10;

Why isn't the range of the Fadebar simply 0 to 255? Then, there would be no reason to multiply by 10.

int stringToNumber(String thisString) {
  int i, value, length;
  length = thisString.length();
  char new[(length)];
  for(i=0; i<length; i++) {
    new[i] = thisString.charAt(i);
  }

  value = atoi(blah);
  return value;
}

Extract the data into an array called new. Then, convert the data in blah to an int, and return that value. blah isn't even defined.

The String class, which has documented issues, has a toInt() method. Why aren't you using it?

The String class has a toCharArray() method. Why aren't you using it?

Why doesnt work?

It does work. As a matter of fact, it's working perfectly. It just, clearly, doesn't do what you want, or expect, it to. So, what does it do? What do you expect it to do? How do those differ?

  1. How can i send an int value through an serialport?

How is the Arduino supposed to know when the integer value, converted to a string, has been fully received? You are sending an int, now, but the Arduino has no way of knowing when the whole string has arrived. Supposed that Fadebar has a value of 14. You multiply that by 10 (why is a mystery) and send 140, as '1', '4', '0'.

Now some data arrives at the Arduino. Likely, just the '1'.

That clearly isn't a NULL (which will never be sent), so you add it to the String. Then, sometime later, the '4' arrives, so you add it to the String. Later, the '0' arrives, so you add it to the String.

No NULL ever gets sent, so, your String just keeps filling up. Clearly, you need to send something to indicate that the end of the packet has arrived, and you need to read the data until that end of packet marker arrives. That end of packet marker can NOT be a NULL.

  1. How can i print my fadeValue (Serial.print(fadeValue)) ? It appears "Serial Port "COM6" is already in use...".

COM6 is in use by your C# application, which, believe it or not, is perfectly capable of reading serial data, too. So, the Arduino can send serial data back.

  1. Can i debug arduino code?

Yes, but it is far better to not write buggy code in the first place.

Hi PaulS,
First of all, thanks for your reply.

Why isn't the range of the Fadebar simply 0 to 255? Then, there would be no reason to multiply by 10.

My scroll bar have a maximum of 10. So, it goes to maximum of 100. Sure it is better made all to 255, but i believe it is not a big problem.

The String class, which has documented issues, has a toInt() method. Why aren't you using it?
The String class has a toCharArray() method. Why aren't you using it?

Like i said before this is arduino code (C code). So i include stdlib.h which i believe it dont have such functions.

How is the Arduino supposed to know when the integer value, converted to a string, has been fully received?

In C code, '\0' is the final mark that a string have by default. Falling your example the string received by arduino is {'140\0'}. You can see how i stop fill my number in arduino code (C code) that i posted.

Yes, but it is far better to not write buggy code in the first place.

My problem is how can i see what im sending to arduino. How can i print on the serial monitor of arduino software?

The problem is solved. Thanks anyway. The problem is that in C# is necessary to concatenate the Null Char ('\0') to your string otherwise arduino could not recognize where the string ends.
Can anyone tell me how can i see what im sending to arduino once i cant use the arduino's serial monitor because it's already being used by visual studio.

Can anyone tell me how can i see what im sending to arduino once i cant use the arduino's serial monitor because it's already being used by visual studio.

It's not being used by Visual Studio. It is being used by your application that was developed using Visual Studio.

Your application CAN read from the serial port, too. So, it can read whatever the Arduino write()s/print()s to the serial port.

Like i said before this is arduino code (C code). So i include stdlib.h which i believe it dont have such functions.

It is NOT C code. It is C++ code, and String is a class that DOES have those members.

In C code, '\0' is the final mark that a string have by default. Falling your example the string received by arduino is {'140\0'}. You can see how i stop fill my number in arduino code (C code) that i posted.

The NULL tells the sender when to stop sending. It does NOT send the NULL by default. The NULL is then NOT in the stream of data received. Even if it were, the Arduino would not know how to deal with '140\0', because that is a multibyte character, and the Arduino can not receive multibyte characters.

Hi Paul!

It is NOT C code. It is C++ code, and String is a class that DOES have those members.

Can you show me an example using an string in arduino code with string classes? Can you replace my arduino code for other else using those string methods that you said before like .toInt(), for example? or show me some link that show some example of arduino code using classes. Like i said, i'm new in arduino's world, i'll apreciate that because i didn't find yet any arduino code using classes.

Thanks again for your reply.

i'll apreciate that because i didn't find yet any arduino code using classes.

Perhaps you just didn't recognize the use of a class.

String incomingstring = "";

A class, String, with an instance.

  Serial.begin(9600);

Another instance of a class, HardwareSerial in this case.