collapse

* Posts Recentes

Amplificador - Rockboard HA 1 In-Ear por almamater
[Ontem às 19:13]


O que é isto ? por KammutierSpule
[26 de Março de 2024, 19:35]


Bateria - Portátil por almamater
[25 de Março de 2024, 22:14]


Emulador NES em ESP32 por dropes
[13 de Março de 2024, 21:19]


Escolher Osciloscópio por jm_araujo
[06 de Fevereiro de 2024, 23:07]


TP4056 - Dúvida por dropes
[31 de Janeiro de 2024, 14:13]


Leitura de dados por Porta Serie por jm_araujo
[22 de Janeiro de 2024, 14:00]


Distancia Cabo por jm_araujo
[08 de Janeiro de 2024, 16:30]


Meu novo robô por josecarlos
[06 de Janeiro de 2024, 16:46]


Laser Engraver - Alguém tem? por almamater
[16 de Dezembro de 2023, 14:23]

Autor Tópico: Ajuda na programação deste projecto, arduino autonomus stopwatch  (Lida 8716 vezes)

0 Membros e 1 Visitante estão a ver este tópico.

Offline amando96

  • Mini Robot
  • *
  • Mensagens: 1.631
  • MAC address? But I have windows...
    • Projects, News, Blog, Tutorials
bem há uns tempos vi um codigo de um cronometro, quando chegou o lcd foi logo posto lá ;D

o que eu quero fazer mas não tenho acerteza como, é em vez de trabalhar com um botão (On/Off) trabalhar com analog in, uma LDR mais propriamente, para quando passar de um valor que vai ser determinado por um potenciometro, começara contar, e quando outro ldr passa de outro valor definido pelo potenciometr, para de contar, e lcd.print aquilo tudo.

o código que tenho é este

Código: [Seleccione]
#include <LiquidCrystal.h>
// LiquidCrystal display with:
// rs on pin 12
// rw on pin 11
// enable on pin 10
// d4, d5, d6, d7 on pins 5, 4, 3, 2
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);
#define ledPin  13                  // LED connected to digital pin 13
#define buttonPin 6                 // button on pin 4

int value = LOW;                    // previous value of the LED
int buttonState;                    // variable to store button state
int lastButtonState;                // variable to store last button state
int blinking;                       // condition for blinking - timer is timing
long interval = 100;                // blink interval - change to suit
long previousMillis = 0;            // variable to store last time LED was updated
long startTime ;                    // start time for stop watch
long elapsedTime ;                  // elapsed time for stop watch
int fractional;                     // variable used to store fractional part of time


void setup() {
pinMode(ledPin, OUTPUT);         // sets the digital pin as output

   pinMode(buttonPin, INPUT);       // not really necessary, pins default to INPUT anyway
   digitalWrite(buttonPin, HIGH);   // turn on pullup resistors. Wire button so that press shorts pin to ground.


pinMode(4, OUTPUT);
// limpa o ecra
  lcd.clear();
  // setCursor(coluna [0-15], linha [0-1])
  
}

void loop(){
  lcd.setCursor(0,0);
  lcd.print("StopWatch, He");
  lcd.setCursor(0,1);
  lcd.print("Took");
  lcd.setCursor(11,1);
  lcd.print("Sec's");
  lcd.setCursor(5,1);

 
   // check for button press
   buttonState = digitalRead(buttonPin);                   // read the button state and store

   if (buttonState == LOW && lastButtonState == HIGH  &&  blinking == false){     // check for a high to low transition
      // if true then found a new button press while clock is not running - start the clock

      startTime = millis();                                   // store the start time
      blinking = true;                                     // turn on blinking while timing
      delay(5);                                               // short delay to debounce switch
      lastButtonState = buttonState;                          // store buttonState in lastButtonState, to compare next time

   }

   else if (buttonState == LOW && lastButtonState == HIGH && blinking == true){     // check for a high to low transition
      // if true then found a new button press while clock is running - stop the clock and report

        elapsedTime =   millis() - startTime;              // store elapsed time
        blinking = false;                                  // turn off blinking, all done timing
        lastButtonState = buttonState;                     // store buttonState in lastButtonState, to compare next time

       // routine to report elapsed time
        lcd.print( (int)(elapsedTime / 1000L));         // divide by 1000 to convert to seconds - then cast to an int to print

        lcd.print(".");                             // print decimal point

        // use modulo operator to get fractional part of time
       fractional = (int)(elapsedTime % 1000L);

       // pad in leading zeros - wouldn't it be nice if
       // Arduino language had a flag for this? :)
       if (fractional == 0){
          lcd.print("000");      // add three zero's
     }  else if (fractional < 10)    // if fractional < 10 the 0 is ignored giving a wrong time, so add the zeros
          lcd.print("00");       // add two zeros
       else if (fractional < 100)
          lcd.print("0");        // add one zero
      
       lcd.print(fractional);  // print fractional part of time

   }

   else{
      lastButtonState = buttonState;                         // store buttonState in lastButtonState, to compare next time
   }

   // blink routine - blink the LED while timing
   // check to see if it's time to blink the LED; that is, the difference
   // between the current time and last time we blinked the LED is larger than
   // the interval at which we want to blink the LED.

   if ( (millis() - previousMillis > interval) ) {

      if (blinking == true){
         previousMillis = millis();                         // remember the last time we blinked the LED

         // if the LED is off turn it on and vice-versa.
         if (value == LOW)
            value = HIGH;
         else
            value = LOW;
         digitalWrite(ledPin, value);
      }
      else{
         digitalWrite(ledPin, LOW);                         // turn off LED when not blinking
      }
   }

}

  

   
Ui não fiz muito sentido, espero ter-me feito entender :S

obrigado
« Última modificação: 12 de Julho de 2009, 15:29 por metRo_ »

Offline metRo_

  • Administrator
  • Mini Robot
  • *****
  • Mensagens: 3.753
Re:ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #1 em: 11 de Julho de 2009, 20:13 »
e o que é que não funciona?

Offline amando96

  • Mini Robot
  • *
  • Mensagens: 1.631
  • MAC address? But I have windows...
    • Projects, News, Blog, Tutorials
Re:ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #2 em: 11 de Julho de 2009, 21:20 »
o parte de usar o LDR, como tem 1023 hipoteses, e o botão só tem duas, não sei como fazer esta parte:


 
Código: [Seleccione]
// check for button press
   buttonState = digitalRead(buttonPin);                   // read the button state and store

   if (buttonState == LOW && lastButtonState == HIGH  &&  blinking == false){     // check for a high to low transition
      // if true then found a new button press while clock is not running - start the clock

      startTime = millis();                                   // store the start time
      blinking = true;                                     // turn on blinking while timing
      delay(5);                                               // short delay to debounce switch
      lastButtonState = buttonState;                          // store buttonState in lastButtonState, to compare next time

   }

   else if (buttonState == LOW && lastButtonState == HIGH && blinking == true){     // check for a high to low transition
      // if true then found a new button press while clock is running - stop the clock and report

« Última modificação: 12 de Julho de 2009, 01:15 por TigPT »

Offline amando96

  • Mini Robot
  • *
  • Mensagens: 1.631
  • MAC address? But I have windows...
    • Projects, News, Blog, Tutorials
Re:ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #3 em: 11 de Julho de 2009, 21:23 »
fiz dois posts, porque quando faço um post com mais de 20 linha ele começa a variar :S

será assim?

LDRpin = pino analogico 3

 
Código: [Seleccione]
// check for button press
   buttonState = analogRead(LDRpin);                   // read the button state and store

   if (buttonState == 600 && lastButtonState > 601  &&  blinking == false){     // check for a high to low transition
      // if true then found a new button press while clock is not running - start the clock

      startTime = millis();                                   // store the start time
      blinking = true;                                     // turn on blinking while timing
      delay(5);                                               // short delay to debounce switch
      lastButtonState = buttonState;                          // store buttonState in lastButtonState, to compare next time

   }

   else if (buttonState == 600 && lastButtonState > 601 && blinking == true){     // check for a high to low transition
      // if true then found a new button press while clock is running - stop the clock and report
« Última modificação: 12 de Julho de 2009, 01:15 por TigPT »

Offline amando96

  • Mini Robot
  • *
  • Mensagens: 1.631
  • MAC address? But I have windows...
    • Projects, News, Blog, Tutorials
Re:ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #4 em: 12 de Julho de 2009, 15:12 »
consegui, depois de uma noite sem pregar olho :P

agora vei-o-me outra duvida =/

o LCd diz-me os segundos que demorei a percorrer 4.70 metros, e tenho de fazer as contas de cabeça, para ver quantos Kph são

só preciso de fazer estas contas:

4.70/tempo demorado*3.6, mas dá-me resultados errados =/

tenho este código:


Código: [Seleccione]
#include <math.h>
#include <LiquidCrystal.h>
// LiquidCrystal display with:
// rs on pin 12
// rw on pin 11
// enable on pin 10
// d4, d5, d6, d7 on pins 5, 4, 3, 2
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);
#define ledPin  13                  // LED connected to digital pin 13                 // button on pin 4
int val;
int value = LOW;                    // previous value of the LED
int buttonState; // variable to store button state
int lastButtonState;
int buttonState2; // variable to store button state
int lastButtonState2;// variable to store last button state
int blinking;                       // condition for blinking - timer is timing
long interval = 100;                // blink interval - change to suit
long previousMillis = 0;            // variable to store last time LED was updated
long startTime ;                    // start time for stop watch
long elapsedTime ;                  // elapsed time for stop watch
int fractional;                     // variable used to store fractional part of time


void setup() {
pinMode(ledPin, OUTPUT);         // sets the digital pin as output

    // turn on pullup resistors. Wire button so that press shorts pin to ground.


pinMode(4, OUTPUT);
pinMode(6, INPUT);
// limpa o ecra
  lcd.clear();
  // setCursor(coluna [0-15], linha [0-1])
  
}

void loop(){
  lcd.setCursor(0,1);
  lcd.print("KPH");
  lcd.setCursor(13,0);
  lcd.print(analogRead(0));
  lcd.setCursor(0,0);
  lcd.print("Time");
  lcd.setCursor(5,0);

 
   // check for button press
   buttonState = analogRead(0);
buttonState2 = digitalRead(6);   // read the button state and store

   if (buttonState < 900 && lastButtonState > 901  &&  blinking == false){     // check for a high to low transition
      // if true then found a new button press while clock is not running - start the clock

      startTime = millis();                                   // store the start time
      blinking = true;                                     // turn on blinking while timing
      delay(5);                                               // short delay to debounce switch
      lastButtonState = buttonState;                          // store buttonState in lastButtonState, to compare next time

   }

   else if (buttonState2 == LOW && lastButtonState2 == HIGH && blinking == true){     // check for a high to low transition
      // if true then found a new button press while clock is running - stop the clock and report

        elapsedTime =   millis() - startTime;              // store elapsed time
        blinking = false;                                  // turn off blinking, all done timing
        lastButtonState = buttonState;                     // store buttonState in lastButtonState, to compare next time

       // routine to report elapsed time
        lcd.print( (int)(elapsedTime / 1000L));         // divide by 1000 to convert to seconds - then cast to an int to print

        lcd.print(".");                             // print decimal point

        // use modulo operator to get fractional part of time
       fractional = (int)(elapsedTime % 1000L);

       // pad in leading zeros - wouldn't it be nice if
       // Arduino language had a flag for this? :)
       if (fractional == 0){
          lcd.print("000");      // add three zero's
     }  else if (fractional < 10)    // if fractional < 10 the 0 is ignored giving a wrong time, so add the zeros
          lcd.print("00");       // add two zeros
       else if (fractional < 100)
          lcd.print("0");        // add one zero
      
       lcd.print(fractional);
       lcd.setCursor(5,1);
       lcd.print((4.70/fractional)*3,6);  // print fractional part of time

   }

   else{
      lastButtonState = buttonState;    
lastButtonState2 = buttonState2;      // store buttonState in lastButtonState, to compare next time
   }

   // blink routine - blink the LED while timing
   // check to see if it's time to blink the LED; that is, the difference
   // between the current time and last time we blinked the LED is larger than
   // the interval at which we want to blink the LED.

   if ( (millis() - previousMillis > interval) ) {

      if (blinking == true){
         previousMillis = millis();                         // remember the last time we blinked the LED

         // if the LED is off turn it on and vice-versa.
         if (value == LOW)
            value = HIGH;
         else
            value = LOW;
         digitalWrite(ledPin, value);
      }
      else{
         digitalWrite(ledPin, LOW);                         // turn off LED when not blinking
      }
   }

}

  

« Última modificação: 12 de Julho de 2009, 16:04 por TigPT »

Offline amando96

  • Mini Robot
  • *
  • Mensagens: 1.631
  • MAC address? But I have windows...
    • Projects, News, Blog, Tutorials
Re:ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #5 em: 12 de Julho de 2009, 15:13 »
queria fazer em BOLD esta parte:
lcd.setCursor(0,0);
 lcd.print(fractional);
       lcd.setCursor(5,1);
       lcd.print((4.70/fractional)*3,6);

mas não consigo editar posts grandes...

o que é que me está a escapar?

obrigado pela ajuda :)

Offline metRo_

  • Administrator
  • Mini Robot
  • *****
  • Mensagens: 3.753
Re:ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #6 em: 12 de Julho de 2009, 15:29 »
Código: [Seleccione]
int fractional;                     // variable used to store fractional part of time
O problema pode estar aqui, define o fractional como float.

Offline amando96

  • Mini Robot
  • *
  • Mensagens: 1.631
  • MAC address? But I have windows...
    • Projects, News, Blog, Tutorials
Re:Ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #7 em: 12 de Julho de 2009, 19:20 »
hmm não deu =/

pensei que poderia estar a confundir o fractional com as outras ordens.

criei
float fractional2

e ficou o
int fractional.

e depois

fractional2 == fractional;
mas não deu á mesma, diz sempre o mesmo resultado: 55303200553, independentemente do tempo...  :-X

Offline ricardo-reis

  • Administrator
  • Mini Robot
  • *****
  • Mensagens: 1.338
Re:Ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #8 em: 12 de Julho de 2009, 19:25 »
 fractional = (int)(elapsedTime % 1000L);


aquele L tá ali a fazer o k?

Offline amando96

  • Mini Robot
  • *
  • Mensagens: 1.631
  • MAC address? But I have windows...
    • Projects, News, Blog, Tutorials
Re:Ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #9 em: 12 de Julho de 2009, 19:29 »
para dizer a verdade não faço minima :P

deve ter-me escapado, não faz diferença, pelo que vi, se está ou não...  :-\

Offline ricardo-reis

  • Administrator
  • Mini Robot
  • *****
  • Mensagens: 1.338
Re:Ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #10 em: 12 de Julho de 2009, 19:33 »
o que o metRo_ disse tem toda a lógica.. tu tás a passar um float pra dentro da variável fractional que é int, e logo daí pode haver problemas de conversão.. n devias ter feito isso do fractional2, devias mm era ter mudado o tipo de variável fractional pra float..

Offline amando96

  • Mini Robot
  • *
  • Mensagens: 1.631
  • MAC address? But I have windows...
    • Projects, News, Blog, Tutorials
Re:Ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #11 em: 12 de Julho de 2009, 19:36 »
tambem fiz, mas como ficou na mesma, pensei que com fractional2 por alguma razão pensei que poderia dar, por estar float, podia dar-me o tempo com algum erro...
pelo que percebi no site arduino, o float arredonda um bocado o valor.

Offline metRo_

  • Administrator
  • Mini Robot
  • *****
  • Mensagens: 3.753
Re:Ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #12 em: 12 de Julho de 2009, 19:55 »
Faz debug pela porta serie, isto é, a seguir a cada calculo ou atribuição de valor faz:
Citar
Serial.print("fractional: ");
Serial.println(fractional);

Assim consegues ver como evoluem as variáveis e onde está o teu problema.

Offline amando96

  • Mini Robot
  • *
  • Mensagens: 1.631
  • MAC address? But I have windows...
    • Projects, News, Blog, Tutorials
Re:Ajuda na programação deste projecto, arduino autonomus stopwatch
« Responder #13 em: 12 de Julho de 2009, 21:47 »
brigadão  :-*, fractional é só a parte depois do ponto!

 :D

em vez de dividir o elapsed time por 1000, e depois multiplicar por 3.6 fiz isto:

lcd.print((4.70/(elapsedTime))*3600);

deu-me tudo certo at´agora :)

obrigado, não conseguia sem a ajuda :D
« Última modificação: 12 de Julho de 2009, 22:13 por little resources »

Offline amando96

  • Mini Robot
  • *
  • Mensagens: 1.631
  • MAC address? But I have windows...
    • Projects, News, Blog, Tutorials