Doel:€250.00
Donaties:€50.00

Per saldo:€-200.00

Steun ons nu!

Laatst bijgewerkt
op 03-01-2024

Vacature: secretaris bestuur
Algemeen

De stichting

Recente berichten

On traXS 15 t/m 17 maart Spoorwegmuseum Utrecht door Ronaldk
Vandaag om 07:35:23
Geluid NS Mat'46 vs NS Mat'54 door Thom
Vandaag om 02:40:57
De bouw van mijn modelbaan in Thailand door Thai-Bundesbahn
Vandaag om 02:07:57
Mallnitzer Tauernbahnstrecke ÖBB N Spoor door Schachbrett
Vandaag om 00:54:59
Bahnstrecke 5867 door Schachbrett
Vandaag om 00:39:27
Mijn Ned. N. Spoorbaan ''Echthoven'' door Schachbrett
Vandaag om 00:37:53
Bouw Bührtal III door Schachbrett
Vandaag om 00:36:33
Schneidersein door MartinRT
Vandaag om 00:00:05
NS/32 door RK
18 maart 2024, 23:49:38
Modelbaan Beltheim. door Ronald69
18 maart 2024, 23:41:34
01TREFF 2024, 26&27 OKTOBER door bernhard67
18 maart 2024, 23:27:22
Mijn eerste H0-modeltreinbaan in aanbouw door Modelbaan BeltHeim
18 maart 2024, 23:18:36
De Hondsrugbaan door Modelbaan BeltHeim
18 maart 2024, 23:17:58
Vraag over 20 voets container met vlakke zijwanden door MOVisser
18 maart 2024, 23:09:27
Ijzeren Rijn: militair transport door ijzeren rijn
18 maart 2024, 23:03:28
Perronhoogte TP3 door Klaas Zondervan
18 maart 2024, 22:35:55
Kranenberg, een exercitie in code 70 door wob
18 maart 2024, 22:14:45
EifelBurgenBahn door Reinout van Rees
18 maart 2024, 22:07:31
Loconet over TCP/IP door bask185
18 maart 2024, 22:00:49
bezetmelder aantal lengte en treinstellen door Bobos
18 maart 2024, 21:36:41
Les Billards du Vivarais door Hans1963
18 maart 2024, 21:36:19
plaatsen bezetmelders lengte en treinstellen door Bobos
18 maart 2024, 21:33:54
Am Ende der Strecke, modulebaan op 1 M2 door Frank 123
18 maart 2024, 21:34:50
Resetten decoder via Twin Center Fleischmann door Pieter Bregman
18 maart 2024, 21:33:18
Foto's gevraagd Den Haag CS, oude toestand door Pauldg
18 maart 2024, 21:30:41
Zee. Land. door Huup
18 maart 2024, 21:23:57
Digikeijs DR80010 door TBBW
18 maart 2024, 20:03:37
US diorama in H0 door basjuh1981
18 maart 2024, 20:02:44
Kemlerborden (Gevi / UN nummers) ketelwagens door Falkenberg
18 maart 2024, 19:36:20
Rheinburg, TP V/VI door gdh
18 maart 2024, 19:15:56
  

Auteur Topic: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie  (gelezen 20505 keer)

Daan Neijenhuis

  • Offline Offline
  • Berichten: 1508
  • HCC!m-IG
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #60 Gepost op: 18 juni 2018, 07:33:12 »
Staat die AVRISP MkII bij de Device Manager of is het een optie in de Arduino IDE?
Het is in ieder geval niet de COM-poort naar de Arduino; die van mij staat als "Arduino Mega 2560 (COM5)" onder COM&LPT in de Device Manager en in de IDE na het selecteren van de MEGA 2560 wordt ook COM5 als poort getoond. De Programmers staan verderop maar die gebruik je niet om de MEGA 2560 van jouw programma te voorzien...
Net als bij modelspoorautomatisering eerst klein beginnen; Ovaaltje-Inhaalspoortje oftwel eerst een Blink of HelloWorld sketch en dan pas verder.
Heeft deze Mega al wel eerder gewerkt op deze computer, of is dit de eerste poging?

Suc6!
Wanneer lees je nou een handleiding?   ;D

NS264

  • En maar rijden over het asfalt, kilometers.Sinds kort ook met langer materieel.
  • Online Online
  • Berichten: 8471
    • Midland
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #61 Gepost op: 18 juni 2018, 08:48:45 »
Hoi,

De Com poort werkt weer.
Hij staat op COM3.

De Led's branden nu wel weer en af en toe draait er 1 servo.
De min van de 2 gewone Led's zitten bij elkaar gedraaid in 1 Pin, voorheen heeft dat bij testen gewerkt.

De Arduino heb ik eerder getest met die Led's en apart met een sketch van Arduino voor 1 servo, dat werkte ook.
Het hele gebeuren zit sowieso niet op een baan maar bij een demo opstelling de Arduino nog niet gemonteerd kan er nog alle kanten mee op.
Gisteravond de sketch tig keer in een nieuwe file gedaan en de oudere weer verwijderd.
Ik vroeg me af welk 'programmer' je moet inschakelen, misschien dat die niet goed staat nu.

Om de jumpers te checken, ik krijg een plaatje ervan niet geupload momenteel.

Thanks voor de hulp tot nu toe ;)

Gr Koen.
Voor meer interactie voor topic Voorbereiding bouw Swalbenburg: volg Instagram@swalbenburg_moba_n#

meino

  • Offline Offline
  • Berichten: 2085
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #62 Gepost op: 18 juni 2018, 10:40:44 »
Koen

als je mijn laatste schets geladen hebt, dan moet er het volgende gebeuren.

- direct na het starten van de arduino, gebeurt er niets, led brandt niet, servo beweegt niet, of gaat naar de stand die hoort bij open bomen.
- Verbind pin 11 even met gnd
   Servo beweegt langzaam naar de stand die hoort bij een gesloten boom, led gaat branden.

- Verbind pin 12 met gnd. Op het moment dat je pin 12 van gnd losmaakt gebeurt het volgende.
  Servo beweegt langzaam naar de stand die hoort bij een geopende boom, led stopt met branden.

Vanuit de geopende (veilige) toestand, kun je het ook in de omgekeerde volgorde doen, beginnen met pin 12.

Groet Meino
A clean desk is a sign of an empty mind

Kranenberg
De CanBus komt naar Kranenberg

gvandersel

  • HCC!m maar toch Selectrix (RMX)
  • Offline Offline
  • Berichten: 3602
  • Als het maar elektrisch is.
    • Homepage Gerard van der Sel
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #63 Gepost op: 18 juni 2018, 11:00:40 »
Meino bedoelt de ingangen A0 en A1 of A2 en A3. Druk een draadje in A0 en een tweede draadje in A1. Doe eerst A0 tegen GND houden (Doe hier een kort stukje draad in zonder isolatie).  Tik daarna A1 tegen GNG en zie de LED uitgaan en de servo weer draaien. Dit kan veel of weinig zijn, want Meino kan natuurlijk niet de juiste hoek opgeven. Die wordt als alles is ingebouwd pas definitief bepaald.

Groet,

Gerard van der Sel.
Holzburg (IIIb/IVa) schaal N.
Kijk ook eens bij de bouw en lees de avonturen.

gvandersel

  • HCC!m maar toch Selectrix (RMX)
  • Offline Offline
  • Berichten: 3602
  • Als het maar elektrisch is.
    • Homepage Gerard van der Sel
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #64 Gepost op: 18 juni 2018, 11:02:32 »
Meino,

Een veilige overweg is een overweg die geblokkeerd is voor wegverkeer.

Groet,

Gerard van der Sel.
Holzburg (IIIb/IVa) schaal N.
Kijk ook eens bij de bouw en lees de avonturen.

NS264

  • En maar rijden over het asfalt, kilometers.Sinds kort ook met langer materieel.
  • Online Online
  • Berichten: 8471
    • Midland
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #65 Gepost op: 18 juni 2018, 14:21:09 »
Don't try this at home without professional help....

 ;D
Voor meer interactie voor topic Voorbereiding bouw Swalbenburg: volg Instagram@swalbenburg_moba_n#

NS264

  • En maar rijden over het asfalt, kilometers.Sinds kort ook met langer materieel.
  • Online Online
  • Berichten: 8471
    • Midland
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #66 Gepost op: 19 juni 2018, 00:45:32 »
Hoi,

Heren, U mag het even doen met de melding dat het gelukt is ;D.

Ik heb nu twee, bijna synchroon draaiende servo's.
Ze gaan rustig omhoog maar vallen als een speer naar beneden.

Zal even zien of ik dat morgenochtend op YouTube vertoond kan krijgen.

Ik heb zoals aangegeven die ingangen gebruikten en een jumper(met geïsoleerde pluggen, tenminste, ik hoef er niks aan te doen)
En A0 of A1 verbonden met GND en het werkt .
De Led's zijn nu  wel uit en flikkeren heel zachtjes op.
Ik druk nu wel "koud" op de resetknop bij gebrek aan drukknop dus zo gaat het wel even.

Ik ben blij (y)

Gr Koen.
« Laatst bewerkt op: 19 juni 2018, 00:49:26 door NS264 »
Voor meer interactie voor topic Voorbereiding bouw Swalbenburg: volg Instagram@swalbenburg_moba_n#

72sonett

  • Team encyclopedie
  • Offline Offline
  • Berichten: 2083
    • El Carrilet
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #67 Gepost op: 19 juni 2018, 01:19:17 »
Citaat van: NS264
... servo's ...  rustig omhoog maar vallen als een speer naar beneden.
Wat is de waarde van 'SERVO1_WACHTTIJD' en 'SERVO2_WACHTTIJD' (vanaf regel 604)?
« Laatst bewerkt op: 19 juni 2018, 01:41:33 door 72sonett »
El Carrilet
"te dom om te poepen"
MH

NS264

  • En maar rijden over het asfalt, kilometers.Sinds kort ook met langer materieel.
  • Online Online
  • Berichten: 8471
    • Midland
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #68 Gepost op: 19 juni 2018, 08:41:19 »
Heren,
Een kort filmpje .

De groene jumper overdwars is de kabel geplaatst volgens beschrijving van Meino en Gerard.

Te zien is ook het type Led wat ik kaar heb liggen, zeer minuscuul en dun draad.
En btw ik denk dat het geen fotocel is maar een lichtsluis dat micro-onderdeel op het breadboard.

Grtz Koen.
« Laatst bewerkt op: 19 juni 2018, 09:08:01 door NS264 »
Voor meer interactie voor topic Voorbereiding bouw Swalbenburg: volg Instagram@swalbenburg_moba_n#

gvandersel

  • HCC!m maar toch Selectrix (RMX)
  • Offline Offline
  • Berichten: 3602
  • Als het maar elektrisch is.
    • Homepage Gerard van der Sel
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #69 Gepost op: 19 juni 2018, 09:52:21 »
Hoi Koen,

Ik kan me geen groene jumper herinneren. De servo's bewegen, maar hopeloos verkeerd. Na druk op de knop moeten ze 90 graden draaien en dan blijven staan. Bij de volgende druk op de knop bewegen ze weer terug naar de oorspronkelijke positie. Je beweegt de servo's door op de reset toets te drukken. Dat is echt niet de bedoeling. Deze toets zou je nooit nodig moeten hebben.
Even een test:
Haal de groene draad eens los aan de kant van de gele draden. Laat de andere kant maar in de GND zitten.
Opstart:
1) Zet de Arduino aan en wacht even tot alles tot rust is gekomen.
Werking:
2) Druk nu de groene draad in de A0 en wacht even tot alles weer tot rust is gekomen.
3) Haal nu de groene draad los, als het goed is gebeurt er niets.
4) Stop de Groene draad in A1. Ook nu gebeurt er niets.
5) Verwijderen de groene draad, nu zullen de servo's gaan bewegen.
Herhaal de stappen 2 t/m 5 net zo vaak als je wilt.
In een van de twee standen zullen de LEDs branden/knipperen.

Wat beterft je lichtsensor. Dit is inderdaad een lichtsluis, zoals je in de draad van Edskoo hebt gezien. Echter de aanstuur electronica ontbreekt.
Die moet er nog bij.

Groet,

Gerard van der Sel.
Holzburg (IIIb/IVa) schaal N.
Kijk ook eens bij de bouw en lees de avonturen.

NS264

  • En maar rijden over het asfalt, kilometers.Sinds kort ook met langer materieel.
  • Online Online
  • Berichten: 8471
    • Midland
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #70 Gepost op: 19 juni 2018, 11:32:29 »
Hoi,

Ik was in de veronderstelling dat ie al op de sketch draaide.
De kwartslag beweging....

Verkeerde gedachtengang dus.

Zal vanavond de groene jumper omzetten.

Gr Koen.
Voor meer interactie voor topic Voorbereiding bouw Swalbenburg: volg Instagram@swalbenburg_moba_n#

72sonett

  • Team encyclopedie
  • Offline Offline
  • Berichten: 2083
    • El Carrilet
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #71 Gepost op: 19 juni 2018, 12:34:17 »
... als je mijn laatste schets geladen hebt
Meino,
In jouw programma zie ik vanaf regel 122 het volgende stukje:

...
  public:
    ArmServo(int newServoPin, int newWaitTime, int newHighPosition, int newLowPosition)
    {
      this->target = 0;
      this->current = 0;
      this->highPosition = 0;       //  Arm position high
      this->lowPosition = 0;        //  Arm position low
      this->servoWaitTime = 40;     //  Wait time between 2 steps
      this->active = false;
      this->myServo = new Servo();
      this->servoPin = newServoPin;
      this->servoWaitTime = newWaitTime;    //  Wait time between 2 steps
      this->highPosition = newHighPosition;
      this->lowPosition = newLowPosition;
      this->target = newHighPosition;     // We asume that the arms are initial in their
      this->current = newHighPosition;    // upper position.
      this->current = 0;
      this->active = false;
    }

Het lijkt mij dat na de eerste toekenning veel variabelen meteen een andere waarde krijgen, bij deze lijkt me dat niet correct :

 
    this->current = newHighPosition;
    this->current = 0;

Doet het volgende niet hetzelfde?


...
  public:
    ArmServo(int newServoPin, int newWaitTime, int newHighPosition, int newLowPosition)
    {
      this->myServo = new Servo();
      this->servoPin = newServoPin;
      this->servoWaitTime = newWaitTime;    //  Wait time between 2 steps
      this->highPosition = newHighPosition;
      this->lowPosition = newLowPosition;
      this->target = newHighPosition;     // We asume that the arms are initial in their  upper position.
      this->current = 0;
      this->active = false;
    }


Waarom gebruik je #define ipv const?
« Laatst bewerkt op: 19 juni 2018, 18:20:50 door 72sonett »
El Carrilet
"te dom om te poepen"
MH

gvandersel

  • HCC!m maar toch Selectrix (RMX)
  • Offline Offline
  • Berichten: 3602
  • Als het maar elektrisch is.
    • Homepage Gerard van der Sel
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #72 Gepost op: 19 juni 2018, 13:58:57 »
Hoi Koen,

Even voor de zekerheid:

Dit niet
Zal vanavond de groene jumper omzetten.

Maar dit
Haal de groene draad eens los aan de kant van de gele draden. Laat de andere kant maar in de GND zitten.
Opstart:
1) Zet de Arduino aan en wacht even tot alles tot rust is gekomen.
Werking:
2) Druk nu de groene draad in de A0 en wacht even tot alles weer tot rust is gekomen.
3) Haal nu de groene draad los, als het goed is gebeurt er niets.
4) Stop de Groene draad in A1. Ook nu gebeurt er niets.
5) Verwijderen de groene draad, nu zullen de servo's gaan bewegen.
Herhaal de stappen 2 t/m 5 net zo vaak als je wilt.
In een van de twee standen zullen de LEDs branden/knipperen.

Groet,

Gerard van der Sel.
Holzburg (IIIb/IVa) schaal N.
Kijk ook eens bij de bouw en lees de avonturen.

meino

  • Offline Offline
  • Berichten: 2085
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #73 Gepost op: 19 juni 2018, 18:34:00 »
@72sonett

je hebt gelijk, dat stukje code is niet goed. Dat komt ervan als je met snel knip en plakwerk even wat in elkaar zet.

Ik realiseerde me ook dat bij AHOB's de rode lichten pas stoppen als de bomen helemaal open zijn, dus dat heb ik ook nog even aangepast.

@NS264

Koen ik heb nog even een stukje gewijzigde code, die je even moet laden in je Arduino Mega

Groet Meino
#define DEBUG 0

#include <Servo.h>

enum SpoorState {leeg,
                 sensor1komend,
                 sensor2komend,
                 sensor1gaand,
                 sensor2gaand
                };


//
//  Class for a single (white) led which flickers 50 times per
//  minute when on
//
class SingleLed
{
  private:
    int ledPin;
    bool ledOn = false;
   
  public:
    //
    //  Create a new instance of a (white) led, connect it to the specified
    //  digital pin and put it in the specified state (true = on, false = off)
    //
    SingleLed(int aPin, bool state)
    {
      ledPin = aPin;
      ledOn = state;
     
      pinMode(ledPin, OUTPUT);
    }

    //
    //  Set the state of the led (true = on, false = off)
    //
    void setOn(bool state)
    {
#if (DEBUG)
      if (ledOn != state)
      {
        Serial.print("[SingleLed::setOn]");
        if (state)
          Serial.println(" aan");
        else
          Serial.println(" uit");
      }
#endif
      ledOn = state;
    }

    //
    //  If the state is on, put power on the pin of the led, using timers
    //  to make the flicker work.
    //  If the led is off, remove the power from the pin of the led.
    //
    void heartBeat()
    {
      if (ledOn)                               // Do we need to light the led?
      {
#if (DEBUG)
        Serial.println("[SingleLed::heartBeat] led aan");
#endif
        digitalWrite(ledPin, HIGH);        // No, so switch it on               
      }
      else
      {
#if (DEBUG)
        Serial.println("[SingleLed::heartBeat] led uit");
#endif
        digitalWrite(ledPin, LOW);             // Switch ir off
      }
    }
};

/*
   A wrapper class for controlling RC servo's
*/
class ArmServo
{
  private:
#define REFRESH_TIME  30000
    Servo *myServo;
    unsigned long timeOfLastStep;
    unsigned long lastTimeActive;

    unsigned int target;
    unsigned int current;
   
    unsigned int highPosition;       //  Arm position high
    unsigned int lowPosition;        //  Arm position low
    unsigned int servoWaitTime;      //  Wait time between 2 steps
   
    int servoPin;
    bool active = false;

    void attachServo() //  Intialize the servo
    {
#if (DEBUG)
      Serial.print("[ArmServo::attachServo] Servo pin: ");
      Serial.println(this->servoPin);
#endif //DEBUG
      this->myServo->attach(this->servoPin);
      this->active = true;

      this->myServo->write(this->current);  // Restore last known position
    }
   
    void detachServo()
    {
#if (DEBUG)
      Serial.print("[ArmServo::detachServo] Servo pin: ");
      Serial.println(this->servoPin);
#endif //DEBUG

      this->myServo->detach();
      this->active = false;
    }

  public:
    ArmServo(int newServoPin, int newWaitTime, int newHighPosition, int newLowPosition)
    {
      this->active = false;
      this->myServo = new Servo();
      this->servoPin = newServoPin;
      this->servoWaitTime = newWaitTime;
      this->highPosition = newHighPosition;
      this->lowPosition = newLowPosition;
      this->target = newHighPosition;     // We asume that the arms are initial in their upper position
      if (this->highPosition > this->lowPosition)
        this->current = newHighPosition - 1;  // But force a small initial movement
      else
        this->current = newHighPosition + 1;  // But force a small initial movement
      this->active = false;
    }
   
    void laag()
    {
#if (DEBUG)
      Serial.print("[ArmServo::laag] arm going to low position: ");
      Serial.println(lowPosition);
      Serial.flush();
#endif //DEBUG

      target = lowPosition;
    }

    bool isLaag()
    {
      if (current == lowPosition)
        return true;
      else
        return false;     
    }
   
    void hoog()
    {
#if (DEBUG)
      Serial.print("[Armservo::hoog] arm going to high position: ");
      Serial.println(highPosition);
      Serial.flush();
#endif //DEBUG

      target = highPosition;
    }

    bool isHoog()
    {
      if (current == highPosition)
        return true;
      else
        return false;
    }

    bool stepServo()
    {
      //
      //  When the arm's position isn't at the target, we have to move the arm
      //
      if (this->target != this->current)
      {
        //
        //  Is the servo active? if not attach it to it's pin so it can start moving
        //
        if (!this->active)
        {
#if (DEBUG)
          Serial.println("{ArmServo::stepServo] attach");
          Serial.flush();
#endif // DEBUG

          this->attachServo();
        }

        lastTimeActive = millis();

        if ((lastTimeActive - this->timeOfLastStep) >= this->servoWaitTime)
        {
          //
          //  The servo is moving to it's new location.
          //
#if (DEBUG)
          Serial.print("[ArmServo::stepServo] target: ");
          Serial.print(this->target);
          Serial.print(", current: ");
          Serial.print(this->current);
#endif //DEBUG

          if (this->target > this->current)
          {
            this->current++;
          }
          else
          {
            this->current--;
          }

#if (DEBUG)
          Serial.print(", going to: ");
          Serial.println(this->current);
          Serial.flush();
#endif // DEBUG

          this->myServo->write(this->current);
          this->timeOfLastStep = lastTimeActive;
        }

        return true;    // The arm is still moving
      }
      else
      {

        if ((millis() - lastTimeActive) >= REFRESH_TIME)
        {
          //
          //  Is the servo active? if not attach it to it's pin so it can start moving
          //
          if (!this->active)
          {
#if (DEBUG)
            Serial.println("{ArmServo::stepServo] attach");
            Serial.flush();
#endif // DEBUG

            this->attachServo();
          }

#if (DEBUG)
          Serial.print(", refreshing to: ");
          Serial.println(this->current);
          Serial.flush();
#endif // DEBUG

          this->myServo->write(this->current);
          this->lastTimeActive = millis();
        }

        //
        //  The arm reached it's position, so we can now detach the servo (if it was attached)
        //
        if (this->active)
        {
          this->detachServo();
        }

        return false;   // The arm has stopped moving
      }
    }
};

enum AkiStaat {aan, uit};

//
//  A simple class that represents a complete AHOB with all its leds and two Servo's
//  for moving the arms
//
//  TBD, the sound of the bells
//
class AHOB
{
  private:
    SingleLed    *redLight;
    ArmServo  *arm1;
    ArmServo  *arm2;
    AkiStaat state = uit;

  public:
    //
    //  Create an instance of the AHOB, using the specified Led and ArmServo objects
    //
    AHOB(SingleLed *aRedLed, ArmServo *aServo1, ArmServo *aServo2)
    {
      redLight = aRedLed;
      arm1 = aServo1;
      arm2 = aServo2;
      state = uit;

      //
      //  AHOB is veilig, dus roodlicht uit en armen omhoog
      //
      redLight->setOn(false);

      arm1->hoog();
      arm2->hoog();
    }

    //
    //  Activate the connected leds and arm servo's. TBD: the sound
    //
    void heartBeat()
    {
      if (arm1->isHoog() && arm2->isHoog())
      {
        redLight->setOn(false); // Als de armen omhoog staan mag het rode licht niet branden
      }
     
      redLight->heartBeat();
      arm1->stepServo();
      arm2->stepServo();
    }

    void set(AkiStaat aState)
    {
#if (DEBUG)
      if (state != aState)
      {
        Serial.print("[AKI::set]");
        if (aState == uit)
          Serial.println(" uit");
        else
          Serial.println(" aan");
      }
#endif
      state = aState;

      if (state == uit)
      {
        //
        //  AHOB is open, armen omhoog. Het rode licht stopt pas als de armen omhoog staan
        //
        arm1->hoog();
        arm2->hoog();
      }
      else
      {
        //
        //  AHOB is dicht, dus roodlicht aan en arme omlaag
        //
        redLight->setOn(true);

        arm1->laag();
        arm2->laag(); 
      }
    }
};

//
//  Some sensors use a digital signal and keep it high when not active and drop the signal
//  when the sensor trips, use in that case the "laag" setting. Others use a digital signal
//  and are low when not active and make the signal high when the sensor trips, use in that case
//  the "hoog" setting.
//  if the sensor doesn't generate a digital signal, you have to use a pullup resistor (or INPUT_PULLUP)
//  and in that case specify hoog.
//
//  The Flying Fish proximity detectors, when used in reflective mode, need the "laag" setting,
//  when their sensors are removed and positioned opposit each other, they need the "hoog" setting
//
enum SensorTrigger {laag, hoog};

//
//  A simple class which represents the state of a single sensor
//
class Sensor
{
  private:
    int sensorPin;
    SensorTrigger type = hoog;
    bool state = false;           // true = on, false = off

    unsigned long lastTime = 0;   // Timer to ignore short interrupts
#define JITTER_TIME   1000    // wait a second before the sensor goes off

  public:
    //
    //  Create a new instance
    //
    Sensor(int aPin)
    {
      sensorPin = aPin;
      pinMode(sensorPin, INPUT_PULLUP);
    }

    //
    //  Create a new instance
    //
    Sensor(int aPin, SensorTrigger aType)
    {
      sensorPin = aPin;
      type = aType;
      pinMode(sensorPin, INPUT_PULLUP);
    }

    //
    //  Return the current logical state of the sensor
    //
    bool getState()
    {
      return state;
    }

    //
    //  Monitor the physical sensor and update the state accordingly
    //
    void heartBeat()
    {
      if (digitalRead(sensorPin) == HIGH)
      {
        if (type == laag)       // For sensors type laag an high signal means they are in the off state
        {
          if (state != false)   // Process this signal only when the current state is ON
          {
            if (lastTime == 0)
            {
              lastTime = millis();  // start Interval
            }
            else
            {
              unsigned long currTime = millis();
              if ((currTime - lastTime) >= JITTER_TIME)
              {
#if (DEBUG)
                Serial.println("[Sensor::heartBeat] sensor(laag) goes off");
#endif
                state = false;       // sensor goes OFF
                lastTime = 0;        // Reset interval timer
              }
            }
          }
        }
        else
        {
#if (DEBUG)
          if (state != true)
          {
            Serial.println("[Sensor::heartBeat] sensor(hoog) goes on");
          }
#endif
          state = true;        // Sensor goes ON
          lastTime = 0;        // Reset interval timer
        }
      }
      else          // sensorPin  = LOW
      {
        if (type == laag)
        {
#if (DEBUG)
          if (state != true)
          {
            Serial.println("[Sensor::heartBeat] sensor(laag) goes on");
          }
#endif
          state = true;       // Sensor goes ON
          lastTime = 0;        // Reset interval timer;
        }
        else
        {
          if (state != false)   // Process this signal only when the current state is ON
          {
            if (lastTime == 0)
            {
              lastTime = millis();  // start Interval
            }
            else
            {
              unsigned long currTime = millis();
              if ((currTime - lastTime) >= JITTER_TIME)
              {
#if (DEBUG)
                Serial.println("[Sensor::heartBeat] sensor(hoog) goes off");
#endif
                state = false;       // sensor goes OFF
                lastTime = 0;        // Reset interval timer
              }
            }
          }
        }
      }
    }
};

//
//  A finite state machine that guards a occupance of a single track
//
class SpoorControl
{
  private:
    Sensor *sensor1;
    Sensor *sensor2;

    SpoorState  state = leeg;

    //
    //  Based on the state of sensor 1 and the current state of the FSM, a new state
    //  is calculated.
    //
    void handleSensor1(bool trigger)
    {
      if (trigger)                      // Sensor 1 is ON
      {
        if (state == leeg)              // If the state is "leeg" it means that a train enters the section
        {
#if (DEBUG)
          Serial.println("[SpoorControl::handleSensor1] state is sensor1komend");
#endif
          state = sensor1komend;        // so set it to state komend
        }
        else if (state == sensor2komend) // if the other sensor tripped first
        {
#if (DEBUG)
          Serial.println("[SpoorControl::handleSensor1] state is sensor1gaand");
#endif
          state = sensor1gaand;          // The train is starting to leave the section
        }
      }
      else
      { // Sensor went OFF
        if (state == sensor1gaand)       // If the train started to leave via sensor 1
        {
#if (DEBUG)
          Serial.println("[SpoorControl::handleSensor1] state is leeg");
#endif
          state = leeg;                  // the section is "leeg"
        }
      }
    }

    //
    //  Based on the state of sensor 2 and the current state of the FSM, a new state
    //  is calculated.
    //
    void handleSensor2(bool trigger)
    {
      if (trigger)                          // Sensor 2 is ON
      {
        if (state == leeg)                  // Is the section "leeg"?
        {
#if (DEBUG)
          Serial.println("[SpoorControl::handleSensor2] state is sensor2komend");
#endif
          state = sensor2komend;            // A Train entered the section via sensor 2
        }
        else if (state == sensor1komend)    // No a train entered the section via the other sensor
        {
#if (DEBUG)
          Serial.println("[SpoorControl::handleSensor2] state is sensor2gaand");
#endif
          state = sensor2gaand;             // Start the leaving process
        }
      }
      else
      {
        if (state == sensor2gaand)          // A train is in the process of leaving
        {
#if (DEBUG)
          Serial.println("[SpoorControl::handleSensor2] state is leeg");
#endif
          state = leeg;                     // Section is empty again
        }
      }
    }

  public:
    //
    // Create an instance with two sensors
    //
    SpoorControl(Sensor *aSensor1, Sensor *aSensor2)
    {
      sensor1 = aSensor1;
      sensor2 = aSensor2;
    }

    //
    //  Get give the sensors a kick and check their state so we can update our own
    //  state.
    //
    void heartBeat()
    {
      sensor1->heartBeat();
      sensor2->heartBeat();

      handleSensor1(sensor1->getState());
      handleSensor2(sensor2->getState());
    }

    //
    // Return the current state of the section
    //
    SpoorState getState()
    {
      return state;
    }
};

//
//  Create 2 FSM controling two track sections
//
#define SENSOR1_PIN A0    // Analoge pin A0
#define SENSOR2_PIN A1    // Analoge pin A1
#define SENSOR3_PIN A2    // Analoge pin A2
#define SENSOR4_PIN A3    // Analoge pin A3

SpoorControl spoor1(new Sensor(SENSOR1_PIN, laag), new Sensor(SENSOR2_PIN, laag)); // Sensor works reflective
SpoorControl spoor2(new Sensor(SENSOR3_PIN, laag), new Sensor(SENSOR4_PIN, laag));

#define LED1_PIN A5       // Analoge pin A5

SingleLed roodlicht(LED1_PIN, false);

#define SERVO1_PIN  11          // PWM pin 11
#define SERVO1_WACHTTIJD 40     // Wachttijd (in MS) tussen 2 servo stapjes, Hogere waarden = langzamer
#define SERVO1_LAAGPOSITIE 45   // Positie arm in laag stand
#define SERVO1_HOOGPOSITIE 100  // Positie arm in hoog stand

#define SERVO2_PIN  12          // PWM pin 12
#define SERVO2_WACHTTIJD 40     // Wachttijd (in MS) tussen 2 servo stapjes, Hogere waarden = langzamer
#define SERVO2_LAAGPOSITIE 45   // Positie arm in laag stand
#define SERVO2_HOOGPOSITIE 100  // Positie arm in hoog stand

ArmServo arm_een(SERVO1_PIN, SERVO1_WACHTTIJD, SERVO1_LAAGPOSITIE, SERVO1_HOOGPOSITIE);
ArmServo arm_twee(SERVO2_PIN, SERVO2_WACHTTIJD, SERVO2_LAAGPOSITIE, SERVO2_HOOGPOSITIE);

//
// Create an instance of the AHOB
//
AHOB ahob(&roodlicht, &arm_een, &arm_twee);

void setup()
{
#if (DEBUG)
  //Serial.begin(9600);
  Serial.begin(115200);
  while (!Serial);
  Serial.println("Starting");
  Serial.flush();
#endif //DEBUG


}

void loop()
{
  spoor1.heartBeat();     // These object must monitor their sensors
  spoor2.heartBeat();     // so they can update their states


  if ((spoor1.getState() == leeg) && (spoor2.getState() == leeg))
  {
    ahob.set(uit);         // Stop sound and flashing red lights
  }
  else
  {
    ahob.set(aan);         // Start flashing red lights and sound
  }

  ahob.heartBeat();        // Let the AKI update it's connected bells and leds
}
A clean desk is a sign of an empty mind

Kranenberg
De CanBus komt naar Kranenberg

72sonett

  • Team encyclopedie
  • Offline Offline
  • Berichten: 2083
    • El Carrilet
Re: Arduino Mega 2560, voor spoorwegoverweg met fotocellendetectie
« Reactie #74 Gepost op: 19 juni 2018, 21:41:04 »
Citaat van: meino
... dat stukje code is niet goed.

Dit staat er nog 2x in;
  this->active = false;
Ik heb nog een witte led aan de AHOB toegevoegd die zou moeten knipperen als de bomen omhoog zijn. Het compileert OK maar ik weet niet of het werkt want ik heb even geen Arduino om te testen.
In de tekst staat dat de rode leds knipperen met 50x/minuut, maar ik zie niet hoe dat gerealiseerd wordt. Het zou mooi zijn als de witte leds knipperen met de halve freq van de rode, 25x/min dus.
Verder heb ik #define vervangen door een const int declaratie (const byte is nog beter) en ze allemaal bovenin het programma gezet zodat het makkelijker is om b.v. pinnummers te veranderen


Code deel 1:
#include <Servo.h>

bool DEBUG = false;                  // zodra alles werkt, anders true

const int SENSOR1_PIN = A0;          // Analoge pin voor lichtsluis 1
const int SENSOR2_PIN = A1;          // Analoge pin voor lichtsluis 2
const int SENSOR3_PIN = A2;          // Analoge pin voor lichtsluis 3
const int SENSOR4_PIN = A3;          // Analoge pin voor lichtsluis 4
const int LED_RED_PIN = A5;          // Analoge pin voor rode leds
const int LED_WHITE_PIN = A6;        // Analoge pin voor witte leds
const int BEL_PIN     = A7;          // Analoge pin voor bel

const int SERVO1_PIN         = 11;   // PWM pin voor servo 1
const int SERVO1_WACHTTIJD   = 40;   // Wachttijd (in MS) tussen 2 servo stapjes, hogere waarden = langzamer
const int SERVO1_LAAGPOSITIE = 45;   // Positie arm in laag stand (0..180 graden servo)
const int SERVO1_HOOGPOSITIE = 100;  // Positie arm in hoog stand (0..180 graden servo)

const int SERVO2_PIN         = 12;   // PWM pin voor servo 2
const int SERVO2_WACHTTIJD   = 40;   // Wachttijd (in MS) tussen 2 servo stapjes, hogere waarden = langzamer
const int SERVO2_LAAGPOSITIE = 45;   // Positie arm in laag stand
const int SERVO2_HOOGPOSITIE = 100;  // Positie arm in hoog stand

enum SpoorState {leeg,
                 sensor1komend,
                 sensor2komend,
                 sensor1gaand,
                 sensor2gaand
                };

enum AkiStaat {aan, uit};
enum SensorTrigger {laag, hoog};
//
// ---------------------------------------------------------------------------------
//
//  Class for a single red led which flickers 50 times per
//  minute when on
//
class SingleRedLed
{
  private:
    int ledPin;
    bool ledOn = false;
   
  public:
    //
    //  Create a new instance of a red led, connect it to the specified
    //  digital pin and put it in the specified state (true = on, false = off)
    //
    SingleRedLed(int aPin, bool state)
    {
      ledPin = aPin;
      ledOn = state;
      pinMode(ledPin, OUTPUT);
    }
    //
    //  Set the state of the led (true = on, false = off)
    //
    void setOn(bool state)
    {
#if (DEBUG)
      if (ledOn != state)
      {
        Serial.print("[SingleRedLed::setOn]");
        if (state)
          Serial.println(" aan");
        else
          Serial.println(" uit");
      }
#endif
      ledOn = state;
    }
    //
    //  If the state is on, put power on the pin of the led, using timers
    //  to make the flicker work.
    //  If the led is off, remove the power from the pin of the led.
    //
    void heartBeat()
    {
      if (ledOn)     // Do we need to light the led?
      {
#if (DEBUG)
        Serial.println("[SingleRedLed::heartBeat] rode led aan");
#endif
        digitalWrite(ledPin, HIGH);        // No, so switch it on               
      }
      else
      {
#if (DEBUG)
        Serial.println("[SingleRedLed::heartBeat] led uit");
#endif
        digitalWrite(ledPin, LOW);             // Switch it off
      }
    }
};
// --------------------------------
class SingleWhiteLed
{
  private:
    int ledPin;
    bool ledOn = false;
   
  public:
    //
    //  Create a new instance of a white led, connect it to the specified
    //  digital pin and put it in the specified state (true = on, false = off)
    //
    SingleWhiteLed(int aPin, bool state)
    {
      ledPin = aPin;
      ledOn = state;
      pinMode(ledPin, OUTPUT);
    }
    //
    //  Set the state of the led (true = on, false = off)
    //
    void setOn(bool state)
    {
#if (DEBUG)
      if (ledOn != state)
      {
        Serial.print("[SingleWhiteLed::setOn]");
        if (state)
          Serial.println(" aan");
        else
          Serial.println(" uit");
      }
#endif
      ledOn = state;
    }
    //
    //  If the state is on, put power on the pin of the led, using timers
    //  to make the flicker work.
    //  If the led is off, remove the power from the pin of the led.
    //
    void heartBeat()
    {
      if (ledOn)                           // Do we need to light the led?
      {
#if (DEBUG)
        Serial.println("[SingleWhiteLed::heartBeat] witte led aan");
#endif
        digitalWrite(ledPin, HIGH);        // No, so switch it on               
      }
      else
      {
#if (DEBUG)
        Serial.println("[SingleWhiteLed::heartBeat] witte led uit");
#endif
        digitalWrite(ledPin, LOW);             // Switch it off
      }
    }
};
// ----------------------------------------------------------------------
/*
   A wrapper class for controlling RC servos
*/
class ArmServo
{
  private:
    const int REFRESH_TIME = 30000;
    Servo *myServo;
    unsigned long timeOfLastStep;
    unsigned long lastTimeActive;

    unsigned int target;
    unsigned int current;
   
    unsigned int highPosition;       //  Arm position high
    unsigned int lowPosition;        //  Arm position low
    unsigned int servoWaitTime;      //  Wait time between 2 steps
   
    int servoPin;
    bool active = false;

    void attachServo() //  Intialize the servo
    {
#if (DEBUG)
      Serial.print("[ArmServo::attachServo] Servo pin: ");
      Serial.println(this->servoPin);
#endif //DEBUG
      this->myServo->attach(this->servoPin);
      this->active = true;

      this->myServo->write(this->current);  // Restore last known position
    }
   
    void detachServo()
    {
#if (DEBUG)
      Serial.print("[ArmServo::detachServo] Servo pin: ");
      Serial.println(this->servoPin);
#endif //DEBUG

      this->myServo->detach();
      this->active = false;
    }

  public:
    ArmServo(int newServoPin, int newWaitTime, int newHighPosition, int newLowPosition)
    {
      // this->active = false;
      this->myServo = new Servo();
      this->servoPin = newServoPin;
      this->servoWaitTime = newWaitTime; //  Wait time between 2 steps
      this->highPosition = newHighPosition;
      this->lowPosition = newLowPosition;
      this->target = newHighPosition;     // We asume that the arms are initial in their
      if (this->highPosition > this->lowPosition)
        this->current = newHighPosition - 1;  // But force a small initial movement
      else
        this->current = newHighPosition + 1;  // But force a small initial movement
      this->active = false;
    }
   
    void laag()
    {
#if (DEBUG)
      Serial.print("[ArmServo::laag] arm going to low position: ");
      Serial.println(lowPosition);
      Serial.flush();
#endif //DEBUG

      target = lowPosition;
    }

    bool isLaag()
    {
      if (current == lowPosition)
        return true;
      else
        return false;     
    }
   
    void hoog()
    {
#if (DEBUG)
      Serial.print("[Armservo::hoog] arm going to high position: ");
      Serial.println(highPosition);
      Serial.flush();
#endif //DEBUG

      target = highPosition;
    }
 
     bool isHoog()
    {
      if (current == highPosition)
        return true;
      else
        return false;
    }
       
    bool stepServo()
    {
      //
      //  When the arm's position is not at the target, we have to move the arm
      //
      if (this->target != this->current)
      {
        //
        //  Is the servo active? if not attach it to its pin so it can start moving
        //
        if (!this->active)
        {
#if (DEBUG)
          Serial.println("{ArmServo::stepServo] attach");
          Serial.flush();
#endif // DEBUG

          this->attachServo();
        }

        lastTimeActive = millis();

        if ((lastTimeActive - this->timeOfLastStep) >= this->servoWaitTime)
        {
          //
          //  The servo is moving to its new location.
          //
#if (DEBUG)
          Serial.print("[ArmServo::stepServo] target: ");
          Serial.print(this->target);
          Serial.print(", current: ");
          Serial.print(this->current);
#endif //DEBUG

          if (this->target > this->current)
          {
            this->current++;
          }
          else
          {
            this->current--;
          }

#if (DEBUG)
          Serial.print(", going to: ");
          Serial.println(this->current);
          Serial.flush();
#endif // DEBUG

          this->myServo->write(this->current);
          this->timeOfLastStep = lastTimeActive;
        }

        return true;    // The arm is still moving
      }
      else
      {

        if ((millis() - lastTimeActive) >= REFRESH_TIME)
        {
          //
          //  Is the servo active? if not attach it to its pin so it can start moving
          //
          if (!this->active)
          {
#if (DEBUG)
            Serial.println("{ArmServo::stepServo] attach");
            Serial.flush();
#endif // DEBUG

            this->attachServo();
          }

#if (DEBUG)
          Serial.print(", refreshing to: ");
          Serial.println(this->current);
          Serial.flush();
#endif // DEBUG

          this->myServo->write(this->current);
          this->lastTimeActive = millis();
        }
        //
        //  The arm reached its position, so we can now detach the servo (if it was attached)
        //
        if (this->active)
        {
          this->detachServo();
        }
        return false;   // The arm has stopped moving
      }
    }
};
//

« Laatst bewerkt op: 20 juni 2018, 22:35:16 door 72sonett »
El Carrilet
"te dom om te poepen"
MH