Iterate an Arduino String

Asked

Viewed 35 times

0

I would like to perform the following operation:

Read a String (come by Bluetooh).

This String will have 6 positions, each refers to whether an led.

If it is 0 lights up the led or lights up!

How do I iterate this String?

Follows the code:

#include <SoftwareSerial.h>
#define led1 8
#define led2 9
#define led3 10
#define led4 11
#define led5 12
#define led6 13

SoftwareSerial BT(5,6); // RX, TX
String device;
void setup() {
  pinMode(led1, OUTPUT);  
  pinMode(led2, OUTPUT);  
  pinMode(led3, OUTPUT);  
  pinMode(led4, OUTPUT);  
  pinMode(led5, OUTPUT);  
  pinMode(led6, OUTPUT);  
  verificarLeds();
  BT.begin(9600);
  Serial.begin(115200);
}

void verificarLeds(){
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
  digitalWrite(led3, HIGH);
  digitalWrite(led4, HIGH);
  digitalWrite(led5, HIGH);
  digitalWrite(led6, HIGH);
  delay(1000);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);
  digitalWrite(led5, LOW);
  digitalWrite(led6, LOW);
}



void loop() {
  device ="";
  while(BT.available()){
    char c = (char)BT.read();
    device += c;
    delay(10);
  }
  if(device == ""){
    Serial.println("NO READ!");  
  }else{
        Serial.println(device);  
  }


}

1 answer

0

I got it this way, but I still don’t think it’s the best way!

Follows:

#include <SoftwareSerial.h>
#define led1 8
#define led2 9
#define led3 10
#define led4 11
#define led5 12
#define led6 13

SoftwareSerial BT(5,6); // RX, TX
// cada posicao representa um led
char itens[6];
// ponteiro com a posição que vamos gravar
int ponteiro;
void setup() {
  pinMode(led1, OUTPUT);  
  pinMode(led2, OUTPUT);  
  pinMode(led3, OUTPUT);  
  pinMode(led4, OUTPUT);  
  pinMode(led5, OUTPUT);  
  pinMode(led6, OUTPUT);  
  BT.begin(9600);
  Serial.begin(115200);
}


void loop() {
  // zeramos o ponteiro;
  ponteiro = 0;
  while(BT.available()){
    char c = (char)BT.read();
    Serial.println(c);  
    // Se o ponteiro é menor que 6, adiciona...
    if(ponteiro <6){
      itens[ponteiro]= c;
    }else{
      break; // já temos todas as posições, ignoramos o resto!
    }
    ponteiro++;
    delay(10);
  }

  // atulizando os leds!
  if('0' == itens[0]){
    digitalWrite(led1, LOW);
  }else{
    digitalWrite(led1, HIGH);
  }

  if('0' == itens[1]){
    digitalWrite(led2, LOW);
  }else{
    digitalWrite(led2, HIGH);
  }
  if('0' == itens[2]){
    digitalWrite(led3, LOW);
  }else{
    digitalWrite(led3, HIGH);
  }
  if('0' == itens[3]){
    digitalWrite(led4, LOW);
  }else{
    digitalWrite(led4, HIGH);
  }
  if('0' == itens[4]){
    digitalWrite(led5, LOW);
  }else{
    digitalWrite(led5, HIGH);
  }
  if('0' == itens[5]){
    digitalWrite(led6, LOW);
  }else{
    digitalWrite(led6, HIGH);
  }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.