Write Serial Input to Array

Hello Arduino-People out there,

I am new to programming and I am getting a littlebit in trouble.
I want to read 3 values I typed into the console to control a RGB LED with my arduino.

I use an

int array[3]={};

to store the data sent over serial.
But I have absolutely no idea on how to write the data into the array.

It would be nice if someone has got a code-snippet.

Some example:

Serial input:

255,255,255

Output of the LED: White

Kind Regards
(Sorry for bad english)


First try:

if(Serial.available() >= 3) {

    for(int i = 0; i < 4; i ++) {

        array[i] = Serial.read();
    }
    Serial.flush();
}

The Output of the Array then is: {‘2’,‘5’,‘5’,’,’}
(Yes, I know, that I have to change the numbers, on how much data I will collect)

I use an
Code: [Select]

array[3]={};

to store the data sent over serial.

This is not C or C++ code. Looks like matlab.

If you enter the numbers using serial, the ardiuno will receive it as ascii text.

You need to collect the chars which represent each number, convert to an actual number, and store it in the array. Repeat three times. There are countless examples of this.

michinyon:
This is not C or C++ code. Looks like matlab.

Sorry, forgot the “int”. Edited.

How do I convert the characters? with (int*) ?

Thank you!

if(Serial.available() >= 3) {

    for(int i = 0; i < 4; i ++) {

        array[i] = Serial.read();

Check to see that you’ve got three characters, then go right ahead and read all four of them.
No. That won’t work.

1 Like

Let me post the actual code I use:

int array[3]={};

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  if (Serial.available()>=3)
  {
	  for (int i=0; i<4; i++)
	  {
		  array[i] = Serial.read();
	  }
  }
}

Let me post the actual code I use:

That has the same error AWOL pointed out.

The atoi() function bears investigation, as well as a beginner book on string handling in C. A string is a NULL terminated array of chars. While you have an array of chars, it is NOT NULL terminated, so it is NOT a string, so you can NOT use the string handling functions (like atoi()).

Okay, got a solution with "Serial.parseInt".

But thank you very much!

The examples in serial input basics may be useful.

...R