i have created a GUI in VS to control LED's using buttons. This is programmed in C#.
I need help with terminating the bytes as I am experiencing delays when pressing the buttons.
Also I have a slider to fade the LED's on and off and this is disrupting the buttons due to the data not being parsed.
Am I sending a new line correctly, and also I am not sure where to put the if(Serial.read() == 'a'), whether it should be in the loop or in the processData function.
const unsigned int MAX_INPUT = 50;
/*
New line is a terminating character
When received, the buffer is sent off to another function for processing
The buffer is then emptied
*/
void setup()
{
Serial.begin(9600);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
}
void processData(const char * data)
{
if (Serial.read() == 'a')
{
Serial.print("LED's are On - Red.");
analogWrite(9, 255);
analogWrite(10, 0);
analogWrite(11, 0);
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
}
}
void loop()
{
static char input_line [MAX_INPUT];
static unsigned int input_pos = 0;
if (Serial.available () > 0)
{
int inByte = Serial.read ();
switch (inByte)
{
case '\n': // end of text
input_line [input_pos] = 0; // terminating null byte
// terminator reached! process input_line here ...
processData(input_line);
// reset buffer for next time
input_pos = 0;
break;
case '\r': // discard carriage return
break;
default:
// keep adding if not full ... allow for terminating null byte
if (input_pos < (MAX_INPUT - 1))
input_line [input_pos++] = inByte;
break;
} // end of switch
} //end of data
}
and the Visual Studio code is:
private void redButton_Click(object sender, EventArgs e)
{
serialPort1.Write("a, \n");
}
private void redTrackbar_Scroll(object sender, EventArgs e)
{
redTrackbar.Minimum = 0;
redTrackbar.Maximum = 255;
redTrackbar.TickFrequency = 50;
byte pwm;
pwm = Convert.ToByte(redTrackbar.Value);
data[0] = pwm;
serialPort1.Write(data,0,1);
textBox7.Text = pwm.ToString();
}