Operácie

Acro02b

Zo stránky SensorWiki

Príklad na pripojenie a prečítanie tlačítka.

#define   redLED 2    // LED connected to digital pin 2
#define greenLED 3    // LED connected to digital pin 3
#define   button 7    // SW 1 connected to D7
int state=0;
  
void setup()   {                
  // initialize the digital pins as an outputs:
  pinMode(  redLED, OUTPUT);     
  pinMode(greenLED, OUTPUT);     
  pinMode(  button, INPUT);

// !!! Bez tohoto obyc. tlacitko na zem nefunguje!!!

 digitalWrite( button, HIGH);   // pull-up ON
 
  Serial.begin(9600);
}

void loop()                     
{
 
 
  state = digitalRead(button);     // read the value from the sensor

  Serial.print("Sensor = ");
  Serial.println(state, DEC);
  delay(200);

}


Príklad na stavový diagram. Sú 4 stavy, prechody sú riešené tlačítkom. Prepracovať, treba aby boli rôzne prechody a potom viditeľne v programe oddeliť prechodové a stavové riadky.

#define   redLED 2    // LED connected to digital pin 2
#define greenLED 3    // LED connected to digital pin 3
#define   button 7    // SW 1 connected to D7
int state=0;
  
void setup()   {                
  // initialize the digital pins as an outputs:
     pinMode(  redLED, OUTPUT);     
     pinMode(greenLED, OUTPUT);     
     pinMode(  button, INPUT);
// !!! Bez tohoto obyc. tlacitko na zem nefunguje!!!
 digitalWrite( button, HIGH);   // pull-up ON
 
  Serial.begin(9600);
}

void loop()                     
{
  if ( state>3 )  state=0;
  
  Serial.print("State = ");
  Serial.println(state, DEC);

  switch (state) {
  case 0: 
    digitalWrite(  redLED, LOW);   // set the LED on
    digitalWrite(greenLED, LOW);    // set the LED off
    break;
  case 1:
    digitalWrite(  redLED, HIGH);   // set the LED on
    digitalWrite(greenLED, LOW);    // set the LED off
    break;
  case 2:
    digitalWrite(  redLED, LOW);   // set the LED on
    digitalWrite(greenLED, HIGH);    // set the LED off
    break;
  case 3:
    digitalWrite(  redLED, HIGH);   // set the LED on
    digitalWrite(greenLED, HIGH);    // set the LED off
    break;
  default: break;
  }
  
      // stay here until switch pressed
    do{/*nothing*/ } while(digitalRead(button)==1);
    do{/*nothing*/ } while(digitalRead(button)==0);
    delay(200); //debouncing
    state++;

}


Predošlá úloha... | Späť do menu | Pokračovanie...