I'm starting to build my first Arduino project but I'm running into some problems with serial communication.
I get serial data from the console and store it in a char array called "nilai".
Then, when I send a new console message to the Arduino, I want it to clear the existing "nilai" array and store only the new data in that array
this is the code
const int NUMBER_OF_FIELDS = 4;
int fieldIndex = 0;
int nilai[NUMBER_OF_FIELDS];
const int led1 = PB8;
const int led2 = PA5;
const int led3 = PA6;
const int led4 = PA7;
int gas = PC0;
// threshold value
//int nilai[4]={600,700,800,900};
void setup() {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(gas, INPUT);
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
digitalWrite(led3,HIGH);
digitalWrite(led4,HIGH);
Serial.begin(9600);
}
void loop() {
if( Serial.available())
{
char ch = Serial.read();
if(ch >= '0' && ch <= '9') // is this an ascii digit between 0 and 9?
{
// yes, accumulate the value if the fieldIndex is within range
// additional fields are not stored
if(fieldIndex < NUMBER_OF_FIELDS) {
nilai[fieldIndex] = (nilai[fieldIndex] * 10) + (ch - '0');
}
}
else if (ch == ',') // comma is our separator, so move on to the next field
{
fieldIndex++; // increment field index
}
else
{
// any character not a digit or comma ends the acquisition of fields
// in this example it's the newline character sent by the Serial Monitor
// print each of the stored fields
for(int i=0; i < min(NUMBER_OF_FIELDS, fieldIndex+1); i++)
{
Serial.println(nilai[i]);
// nilai[i] = 0; // set the values to zero, ready for the next message
}
fieldIndex = 0; // ready to start over
}
}