Definindo variáveis: Voltando ao Exemplo BLINK e imprimindo valores no monitor serial
Serial Monitor
Exibe os dados de série a ser enviada a partir da placa Arduino (USB ou placa de série). Para enviar dados para o conselho, digite o texto e clique no botão "Enviar" ou pressione Enter. Escolha a taxa de transmissão a partir do drop-down que corresponde a taxa passou para Serial.begin em seu desenho. Note que em Mac ou Linux, a placa Arduino irá resetar (reprise seu esboço, desde o início) quando você se conectar com o monitor serial.
Blink Sem Demora
Às vezes você precisa fazer duas coisas ao mesmo tempo. Por exemplo, você pode querer piscar um LED (ou em algum momento sensível outra função), enquanto a leitura de um aperto de botão ou outra entrada. Neste caso, você não pode usar delay () , ou que você parasse de tudo o resto o programa enquanto o LED piscou. O programa pode perder a pressionar o botão, se acontecer durante o delay (). Esse desenho demonstra como a piscar o LED sem usar delay () . Ele mantém um registro da última vez que o Arduino virou o LED ligado ou desligado. Então, cada vez com loop () , ele verifica se um intervalo longo o suficiente passou. Se tiver, ele alterna o LED ligado ou desligado.
Hardware Requerido
- Arduino Câmara
- LED
Circuito
Para construir o circuito, pegue um LED e anexar a sua perna, muito positivo (chamado de anodo) para o pino 13. Anexar a perna curta e negativo (chamado de anodo) para o solo. Em seguida, conecte a sua placa Arduino em seu computador, inicie o programa Arduino, e insira o código abaixo.
Código
O código abaixo usa o millis () função, um comando que retorna o número de milissegundos desde a placa Arduino começou a correr o seu programa atual, a piscar um LED.
/* Blink without Delay
Turns on and off a light emitting diode(LED) connected to a digital
pin, without using the delay() function. This means that other code
can run at the same time without being interrupted by the LED code.
The circuit:
* LED attached from pin 13 to ground.
* Note: on most Arduinos, there is already an LED on the board
that's attached to pin 13, so no hardware is needed for this example.
created 2005
by David A. Mellis
modified 8 Feb 2010
by Paul Stoffregen
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/
// constants won't change. Used here to
// set pin numbers:
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated
// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000; // interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}
void loop()
{
// here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
}
/* Blink without Delay
Turns on and off a light emitting diode(LED) connected to a digital
pin, without using the delay() function. This means that other code
can run at the same time without being interrupted by the LED code.
The circuit:
* LED attached from pin 13 to ground.
* Note: on most Arduinos, there is already an LED on the board
that's attached to pin 13, so no hardware is needed for this example.
created 2005
by David A. Mellis
modified 8 Feb 2010
by Paul Stoffregen
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/
// constants won't change. Used here to
// set pin numbers:
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated
// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000; // interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}
void loop()
{
// here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
}
Turns on and off a light emitting diode(LED) connected to a digital
pin, without using the delay() function. This means that other code
can run at the same time without being interrupted by the LED code.
The circuit:
* LED attached from pin 13 to ground.
* Note: on most Arduinos, there is already an LED on the board
that's attached to pin 13, so no hardware is needed for this example.
created 2005
by David A. Mellis
modified 8 Feb 2010
by Paul Stoffregen
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/
// constants won't change. Used here to
// set pin numbers:
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated
// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000; // interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}
void loop()
{
// here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
}
Experimento 08/06
Objetivo :
Imprimir valores no “Serial Monitor”
1 Passo - Abrir File > Examples > Digital > BlinkWithoutDelay
2 Passo -
Copiar o código :
int ledPin = 13; // define o pino em que o LED será conectado
int ledState = LOW; // estado inicial do LED
long tempoinicial = 0; // este será o instante inicial que registra
o estado do LED
long interval = 100; // intervalo de tempo que o led irá piscar
void setup() {
Serial.begin(9600); // estabelece a comunicação com a serial
pinMode(ledPin, OUTPUT); // estabelece pino de saida para o led
}
void loop(){
// Código que vai rodar o tempo todo
unsigned long tempoatual = millis(); // define o instante da medida
(base de tempo em milisegundos)
if(tempoatual - tempoinicial > interval) { // se a diferença entre o
tempo atual e o tempo inicial for maior que o
// intervalo estabelecido ajuste o tempo atual para zero e execute a
operação abaixo
tempoinicial = tempoatual;
if (ledState == LOW)
// se o estado do led neste momento for LOW, faça o led ir para o
estado alto
ledState = HIGH;
else // caso contrario leve ao estado baixo
ledState = LOW;
digitalWrite(ledPin, ledState); //escreva na porta digital em que o
LED está conectado o estado do LED
Serial.print(ledState); // imprima este estado no monitor serial
delay(1000); // intervalo de impressão
}
}
No Serial Monitor após fazer o upload do código no Arduino irá aparecer a variação do LED enquanto ele se mantém ON e OFF sendo assim ficando
1,0,1,0,1,0,1,0,1,0,1,0...
Foi proposto o seguinte desafio :
Se o estado do led for alto “imprima a letra H”
Caso contrário “imprima L”.
Dica para a impressão de uma palavra você deve escrever dentro do parêntese a palavra desejada entre
aspas.
Serial.println(“palavra”)
Para que o Serial Monitor imprima as letras devesse ocorrer a
seguinte mudança no código :
// definindo variáveis e pinos utilizados
int ledPin = 13; // define o pino em que o LED será conectado
int ledState = LOW; // estado inicial do LED
long tempoinicial = 0; // este será o instante inicial que registra
long interval = 100; // intervalo de tempo que o led irá piscar
void setup() {
Serial.begin(9600); // estabelece a comunicação com a serial
pinMode(ledPin, OUTPUT); // estabelece pino de saida para o led
}
void loop(){
// Código que vai rodar o tempo todo
unsigned long tempoatual = millis(); // define o instante da medida
if(tempoatual - tempoinicial > interval) { // se a diferença entre o
// intervalo estabelecido ajuste o tempo atual para zero e execute a
tempoinicial = tempoatual;
if (ledState == LOW){
Serial.println("H");
// se o estado do led neste momento for LOW, faça o led ir para o
ledState = HIGH;
}
else{// caso contrario leve ao estado baixo
ledState = LOW;
Serial.println("L");
}digitalWrite(ledPin, ledState); //escreva na porta digital em que o
}}
Nenhum comentário:
Postar um comentário