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?
- How can i send an int value through an serialport?
- How can i print my fadeValue (Serial.print(fadeValue)) ? It appears "Serial Port "COM6" is already in use...".
- Can i debug arduino code?