1
votes

Hi first of all im new to Arduino. But i have some experience in Java.

I got a void setup and a void loop. What i want is that it keeps looping my LED patterns. If i send a 1 or 2 to arduino it will tell him to run a LED pattern. But i want that it keeps looping that chosen pattern. In the void loop i got val = Serial.read() - '0'; I think this thing in the loop will keep setting it back to 0. But if i put it in the global variables i cant send a 1 or 2 to the Arduino Uno controller.

Here is my code so far:

//Pins initaliseren in de setup d.m.v. for loop.
int ledPins[] = {2,3,4,5,6,7,8,9,10};
int pinCount = 9;

//Patronen voor de knipper leds
int patroonEen[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3};
int patroonEenLength = 16;
int patroonTwee[] = {2,3,4,5,6,5,4,3};
int patroonDrie[] = {10,9,8,7,6,7,8,9};
int patroonTweeDrieLength = 9;

int val = 0;

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

  //Inladen van de pins die we gebruiken.
  for (int i = 0; i < pinCount; i++) {
     pinMode(ledPins[i], OUTPUT); 
  }
}

void loop() { 
  while (Serial.available() == 0);
  val = Serial.read() - '0';

  if ( val == 1) {
    for (int i = 0; i < patroonEenLength; i++) {
      digitalWrite(patroonEen[i], HIGH);
      delay(100);
      digitalWrite(patroonEen[i], LOW);
    }  
  } else if (val == 2) {
    for (int i = 0; i < patroonTweeDrieLength; i++) {
      digitalWrite(patroonTwee[i], HIGH);
      digitalWrite(patroonDrie[i], HIGH);
      delay(100);
      digitalWrite(patroonTwee[i], LOW);
      digitalWrite(patroonDrie[i], LOW);
    }  
  } else {
    Serial.print("Ongeldige input");
  }
  Serial.flush();
 }

I'm looking forward to hear from anyone soon :). Any comment is welcome.

1

1 Answers

2
votes

Your code

while (Serial.available() == 0);

blocks the main loop unless there is data availabe from the serial interface. Thus it will not keep looping. You need to parse the serial input without blocking. For example like so:

while (Serial.available() > 0) {
    val = Serial.read() - '0';
}

More examples how to parse without blocking can be found in my blog.

Parsing Numbers, Parsing different modes of operation