Diferencia entre revisiones de «Serial.read()»

De ArduWiki
Saltar a: navegación, buscar
(Referencias)
(Ejemplo 2)
Línea 33: Línea 33:
 
== Ejemplo 2 ==
 
== Ejemplo 2 ==
 
<syntaxhighlight lang="c++">
 
<syntaxhighlight lang="c++">
#define DEBUG(a) Serial.println(a);
 
 
String frase = "";
 
String frase = "";
 
   
 
   
Línea 51: Línea 50:
 
   }
 
   }
 
}
 
}
 +
</syntaxhighlight>
 +
 +
== Ejemplo 3 ==
 +
Ente ejemplo recibe una matriz de [[int]]s.
 +
 +
<syntaxhighlight lang="c++">
 +
int datos[10];
 +
 +
void setup(){
 +
  Serial.begin(115200);
 +
}
 +
 +
void loop(){ 
 +
  if (Serial.available() >= 10 * sizeof(datos[0])){
 +
      Serial.readBytes((byte*)datos, 10 * sizeof(datos[0]));
 +
  }
 +
}
 
</syntaxhighlight>
 
</syntaxhighlight>
  

Revisión del 14:27 13 jul 2018

Descripción

Lee o captura un byte (un carácter) desde el puerto serie.

Sintaxis

byte variable = Serial.read();

Parametros

variable
variable para capturar byte de entrada

Retorno

El valor recuperado según el número de bits de datos configurado, o -1 si el buffer de entrada está vacío (int).

Advertencia

  • Si por error no se verifica de antemano si hay datos disponibles, read() retornará 255 para byte en el caso que el valor real sea -1 (nada).

Ejemplo 1

void setup(){
   Serial.begin(115200);
}
void loop(){
   if (Serial.available()){
      byte car = Serial.read();    //Lee caracter enviado y borra del buffer
      Serial.write(car);           //Imprime caracter enviado
      Serial.print(" = ");
      Serial.println(car);         //Imprime código ASCII carácter enviado
   }
}

Ejemplo 2

String frase = "";
 
void setup(){
   Serial.begin(115200);
}
 
void loop(){
   while (Serial.available()){
      byte caracter = Serial.read();
      if (caracter != '\n'){
         fase.concat(caracter);
      }else{
         Serial.println(frase);
         frase = "";
      }
   }
}

Ejemplo 3

Ente ejemplo recibe una matriz de ints.

int datos[10];
 
void setup(){
   Serial.begin(115200);
} 
 
void loop(){   
   if (Serial.available() >= 10 * sizeof(datos[0])){
      Serial.readBytes((byte*)datos, 10 * sizeof(datos[0]));
   }
}

Vea también

Referencias