Arduino Uno Programming Assistance Request

Advert

Arduino Uno Programming Assistance Request

Home Forums Electronics in the Workshop Arduino Uno Programming Assistance Request

Viewing 25 posts - 51 through 75 (of 86 total)
  • Author
    Posts
  • #335870
    SillyOldDuffer
    Moderator
      @sillyoldduffer

      Just to finish off the original question, I finally managed to get the Snippet method to work last night by thinking carefully about the logic and wrapping it in a Class. As no good deed goes unpunished, I stumbled across a solution on the Adafruit site this morning which would have saved us all a lot of time. I have reinvented the wheel. My version does have the smidgen of extra logic needed to strike hours though.

      Bah!

      Dave

      Advert
      #335956
      Neil Wyatt
      Moderator
        @neilwyatt

        Most larger AVR chips have provision for an on-board RTC driven by a 32 KHz watch crystal. Not sure if the required pins are broken out on an arduino?

        Personally I've found using a separate RTC better as it can run 24/7 while the main chip is powered down, plus they keep track of days etc.

        Should be possible to use switches/optos etc. to allow all mechanical parts to initialise to a know position, then advance to the correct one. Also the clock could remember its position in eeprom (or on the RTC's ram) when going to sleep for the night and then have an entertaining wake up sequence.

        It's always good to watch something complex setting itself up – who here has deliberately unset a radio clock or watch just to see the hands sort themselves out

        Neil

        (Reminds me of the cheap radio clock we had at work – it showed CET. Several folk spent ages trying to get it to show UK time, then I had the idea of removing the front 'glass', taking off the hands and replacing them in the correct position…)

        Edited By Neil Wyatt on 08/01/2018 18:59:13

        #335977
        duncan webster 1
        Participant
          @duncanwebster1
          Posted by Neil Wyatt on 08/01/2018 18:57:30:

          (Reminds me of the cheap radio clock we had at work – it showed CET. Several folk spent ages trying to get it to show UK time, then I had the idea of removing the front 'glass', taking off the hands and replacing them in the correct position…)

          Edited By Neil Wyatt on 08/01/2018 18:59:13

          Reminds me of when we had some through wall TV cameras the picture rotated as the cameras panned and tilted. They spent a lot of effort making picture processing software to keep the picture the right way up, I wanted to mount the monitor of an axle so you could swing it round but that was too easy!

          #335981
          doubletop
          Participant
            @doubletop
            Posted by duncan webster on 08/01/2018 20:34:59:

            Posted by Neil Wyatt on 08/01/2018 18:57:30:

            (Reminds me of the cheap radio clock we had at work – it showed CET. Several folk spent ages trying to get it to show UK time, then I had the idea of removing the front 'glass', taking off the hands and replacing them in the correct position…)

            Edited By Neil Wyatt on 08/01/2018 18:59:13

            Reminds me of when we had some through wall TV cameras the picture rotated as the cameras panned and tilted. They spent a lot of effort making picture processing software to keep the picture the right way up, I wanted to mount the monitor of an axle so you could swing it round but that was too easy!

            The software enginneers wanted to modify the software

            The mechical engineers wanted to use a gimbal

            The electrical engineers wanted to add a servo

            The civil engineers wanted to knock a bigger hole in the wall….

            #336010
            Marcus Bowman
            Participant
              @marcusbowman28936

              There are lots of ready-made programs for clocks and watches, but although using one of those MIGHT have saved time, we would not have learned as much as engaging directly with the problem and the code. I certainly learned a lot by studying the RTC chip structure and its internal registers and counters; which is something I had glossed over in other projects.

              Thanks for the excuse for a mental workout!

              Marcus

              #337365
              James Alford
              Participant
                @jamesalford67616

                Good morning.

                With the help that I received from this forum, I have now rewritten large parts of my code, replacing my original method of turning the output pins on and off with the t.pulse code. This has made the code tidier and made it much easier to control the length of time for which the pins remain high and the duration between pulses.

                I am now looking to see whether I can incorporate PWM into this code so that I can give the solenoids that the pins will drive a soft start, rather than coming on with a bang: I also hope that it will reduce overall power consumption.

                I have written a separate piece of code that works on a spare pin, but I am now trying to integrate it with the pulse.

                Is there any way that I can put this "soft start" code into a routine on its own and then replace pulseLength_ms in the line t.pulse( LED_PIN, pulseLength_ms, LOW ); with a call to this sub-routine?

                I have only just started to look at this, so have tried little yet.

                Regards,

                James.

                #337384
                John Haine
                Participant
                  @johnhaine32865

                  Just another thought – I am making a synchronome-based clock at the moment, but didn't like the idea of having a big electromagnet resetting the escapement with a loud click every 30s. You could have similar prpoblems with a number of solenoids. I'm planning to use a small stepper and a cam to reset the gravity arm – steppers can be run very quietly and take considerably lower peak current than a solenoid. They might turn out cheaper too!

                  #337439
                  SillyOldDuffer
                  Moderator
                    @sillyoldduffer

                    Posted by James Alford on 19/01/2018 07:38:18:

                    I am now looking to see whether I can incorporate PWM into this code so that I can give the solenoids that the pins will drive a soft start, rather than coming on with a bang: I also hope that it will reduce overall power consumption.

                    Is there any way that I can put this "soft start" code into a routine on its own and then replace pulseLength_ms in the line t.pulse( LED_PIN, pulseLength_ms, LOW ); with a call to this sub-routine?

                    ...

                    I hope someone else will have a crack at this: I think James has set another hard exam question!

                    Here's a program that 'sort of' does what James wants.

                    <code>

                    #include <Event.h>
                    #include <Timer.h>

                     

                    class jaTimer : public Timer
                    {
                      public:
                        int8_t pwmRamp( uint8_t pin, unsigned long period, uint8_t startingValue, int repeatCount = 1 )
                        {
                          int8_t i = findFreeEventIndex();
                          if (i == NO_TIMER_AVAILABLE) return NO_TIMER_AVAILABLE;
                        
                          _events[i].eventType = EVENT_OSCILLATE;
                          _events[i].pin = pin;
                          _events[i].period = period;
                          _events[i].pinState = startingValue;
                          if (  _events[i].pinState )
                          {
                            for (uint8_t count=100; count<250; count+=50 )
                            {
                              analogWrite(pin, count);
                              delayMicroseconds( 60000 );
                              
                            }
                            analogWrite(pin, 255);
                          }
                          else analogWrite(pin, 0);
                          
                          _events[i].repeatCount = repeatCount * 2; // full cycles not transitions
                          _events[i].lastEventTime = millis();
                          _events[i].count = 0;
                          return i;
                        }
                    };

                    jaTimer t;
                    const char pwmOutputPin = 2;
                    unsigned long previousTime = millis();

                    void setup() {
                      pinMode( pwmOutputPin, OUTPUT );
                    }

                    void loop() {
                      t.update();

                      if ( millis() – previousTime > 4000 )
                      {
                        // A 1000ms ramped pulse once every 4000ms
                     
                        t.pwmRamp( pwmOutputPin, 1000, HIGH );
                      }
                    }

                     

                    </code>

                    In it, I have derived a new class (called jaTimer) from the Timer class that James is already using. The derived class does everything that Timer does and has a new function called pwmRamp(). It behaves exactly like pulse() except an internal loop takes a PWM pin up from 0 to 255 in 4 steps with a delay between each step.

                    We have a problem Houston!

                    Firstly, I'm not convinced my new code is quite right.

                    Secondly Arduino PWM is based on a 500Hz square wave, meaning that an analogWrite() change isn't meaningful unless it lasts at least 2mS. Actually my experiments seem to show that PWM takes rather longer than that to settle.

                    Thirdly because changing the PWM value too quickly generates confused outputs that aren't very ramp-like, it will be necessary to play with both the number of steps in the ramp up and the inter-step delay to get the effect James wants.

                    Fourthly, if the ramp takes too long to output in total, it will mess up the timing of the main pulse.

                    In short I think the code I've written can be made to work but it's far from friendly. It may be necessary to find an alternative, for example:

                    • Using external faster PWM to control the solenoids.
                    • Using a digital output to charge an RC combination that uses the solenoid driving transistor as a fast rheostat rather than a switch. (Wastes power and the transistor might overheat.)
                    • Firing the solenoid at full speed (this is easy) and using some form of mechanical linkage to slow down the strike.

                    Can anyone suggest a simple way of achieving James' goal, either in code, or with electronics (ideally with an off-the-shelf module), or mechanically?

                    Dave

                    Edited By SillyOldDuffer on 19/01/2018 15:13:08

                    #337499
                    doubletop
                    Participant
                      @doubletop
                      Posted by James Alford on 19/01/2018 07:38:18:

                      I am now looking to see whether I can incorporate PWM into this code so that I can give the solenoids that the pins will drive a soft start, rather than coming on with a bang: I also hope that it will reduce overall power consumption.

                      .

                      James

                      I can only ask why? This won't save any power at all and will most probably waste it. The overall purpose is to transfer energy from the battery through the solenoid to strike the bell with enough force e.g. converting the electrical energy into acoustic energy. All the time your PWM pulses are below the threshold to create enough flux in the coil and overcome the inertia of the striker linkage you are wasting that energy.

                      Just whack out a single the pulse and move on. The width of the single pulse is all that needs to be investigated so that it contains enough power to strike the bell with sufficient force to make it ring

                      Just because the box has got toys in it you don't need to use them all.

                      Pete

                      #337511
                      doubletop
                      Participant
                        @doubletop

                        A further thought on this. Under certain conditions the use of PWM could result in the striker progressing slowly towards the bell as the power level increases. So basically you are reducing the acceleration rate of the striker when actually you want it to be at a maximum.

                        Pete

                        #337533
                        Marcus Bowman
                        Participant
                          @marcusbowman28936

                          You might look at AccelStepper, available at: **LINK**

                          That is a PWM library, designed for steppers, but giving a PWM output nevertheless. It accelerates up to a maximum, then, as nears the end of a sequence, decelerates. All, or part, of that might be useful.

                          Marcus

                          #337540
                          James Alford
                          Participant
                            @jamesalford67616

                            Good morning.

                            Thank you for the replies and for the suggested code. My aim seems to be a lot harder to achieve that I had initially realised and I am wondering whether I should be better using a mechanical approach, as suggested. I had two reasons for wanting to use PWM: firstly, possibly mistakenly, I had thought that ramping up the power would save energy. However, if this is not the case, it lessens the point of the additional complexity of code. Secondly, it was to lessen the initial blow caused by the solenoid. However, this can be overcome, if no other way, by putting a firm rubber pad on the end of the actuator to absorb some of the impact.

                            I have gone down the route of solenoids, rather than stepper motors, simply because of familiarity. I agree that they might well prove rather noisy, though, and that stepper motors would be less intrusive. I shall have a look at the coding for these as I have never played with them before.

                            Regards,

                            James.

                            #337545
                            SillyOldDuffer
                            Moderator
                              @sillyoldduffer

                              I'm finding your questions and the answers fruitful James! For instance, I didn't know of the AccellStepper library, thanks Marcus!

                              Despite the attractions of steppers, my inclination would be to ring bells with solenoids as you propose. It might pay to strike the bell via a spring loaded arm : something like a piano key mechanism perhaps. Before leaping in to that complexity I'd experiment with a simple ON/OFF solenoid that directly hits the bell when activated. If it sounds OK, it is OK. If not, think again.

                              An interesting challenge in this sort of project is deciding what's best done by the Arduino, and what's best done externally. It's fairly obvious that using an Arduino and RTC to keep time eliminates a mass of difficult mechanical clockmaking. It's not so obvious where best to manage something like the acceleration of a striker. It could be done with an Arduino, but my feeling is a simple mechanism would produce better results from less effort.

                              It's all part of the learning curve. Don't be discouraged by difficulties – it may be painful at the time but overcoming them is pure gold in terms of gaining experience. At this stage I wouldn't worry too much about saving power. Get the thing working first and then refine it.

                              Dave

                              #337564
                              Neil Wyatt
                              Moderator
                                @neilwyatt
                                Posted by James Alford on 19/01/2018 07:38:18:

                                Good morning.

                                With the help that I received from this forum, I have now rewritten large parts of my code, replacing my original method of turning the output pins on and off with the t.pulse code. This has made the code tidier and made it much easier to control the length of time for which the pins remain high and the duration between pulses.

                                I am now looking to see whether I can incorporate PWM into this code so that I can give the solenoids that the pins will drive a soft start, rather than coming on with a bang: I also hope that it will reduce overall power consumption.

                                I have written a separate piece of code that works on a spare pin, but I am now trying to integrate it with the pulse.

                                Is there any way that I can put this "soft start" code into a routine on its own and then replace pulseLength_ms in the line t.pulse( LED_PIN, pulseLength_ms, LOW ); with a call to this sub-routine?

                                I have only just started to look at this, so have tried little yet.

                                Regards,

                                James.

                                Solenoids are inductors, which 'resit' rapid changes in current.

                                This means solenoids 'soft start' by their very nature. Applying a 'soft start' current is likely to result in missed movements as ideally you want the current to rise rapidly to overcome inertia/stiction.

                                The ideal way to drive a solenoid is to reduce the current to just above where they operate reliably. if you want to save milliamps, you can safely reduce the hold-in current by a considerable amount, assuming you need to keep them energised.

                                Bear in mind that a high PWM frequency may not drive solenoids reliably.

                                Neil

                                #337568
                                Ian P
                                Participant
                                  @ianp

                                  In addition to what Neil said bear in mind that normal plunger type solenoids have a very non linear action regarding produced output. Their maximum force is only available when the plunger is at or near the end of its travel (when the magnetic circuit is complete (or almost complete).

                                  Over the first part of the solenoid plunger movement relatively little force is available, many applications I have seen put a high voltage/current into the winding so get the armature moving and then reduce it to a small level to keep the plunger extended.

                                  I think quite a bit of experimentation and engineering would be needed to keep audible noise to an acceptable level. I cannot imagine any amount of software tweaking that would improve the action. Certainly software can be optimised to change the audible noise that the stepper motor makes, HDD manufacturers have had years of practice!

                                  I apologise for not going back through the whole thread, but what is the device producing the sound (bell, rod, or what)?

                                  Ian P

                                  #337579
                                  Les Jones 1
                                  Participant
                                    @lesjones1

                                    I don't know the design of this clock but I imagine the solenoid will be stepping a ratchet type wheel one step at a time. Some alternatives are a model servo motor. The position of these is controlled by a pulse betwee 1.5 and 2.5 mS (From memory) at a PRF of about 50 hz. You could just cange the pulse width for a short time to make it move out and back to step the ratchet one position. You could use a small geared motor with a cam on it with one notch cut out. A micro switch would engage against the cam so its contacts were open at the notch position. The contacts would be in series with the motor. A relay or transistor in parallel with these contacts could be pulsed for just longer than the time required for the motor to move enough for the micro switch to close. The motor would then continue for a full rotation and stop at the notch. A crank on the motor could be arranged to step the ratchet wheel one position. A variation on this is to have a number of notches (say 6 , 10, 12, 24) so the wheel would move one position for each pulse. An optical sensor could be used in place of the micro switch.

                                    Les.

                                    #337648
                                    James Alford
                                    Participant
                                      @jamesalford67616

                                      Good morning.

                                      Thank you for the continued and additional suggestions.

                                      Les: I did consider motors, cams and micro-switches initially and they are still a possibility for some elements of the finished design.

                                      Neil and Ian: thank you for the information about solenoids and relays. I studied electromechanics at college for a few years when I was training to be a telephone exchange engineer, but it is scary just how little I can truly recall. Your posts have been fruitful refreshers.

                                      Dave: I agree with you in that it is likely to be easier to refine the control of the device mechanically than with programming and I shall focus on that approach.

                                      As mentioned, I do wish to complete my other main project before embarking on this at all, but below are some drawings of my ideas so far. It is quite small, the wheels being four inches in diameter: much more would exceed the capacity of my lathe. The base will house most of the solenoids, the Uno, circuitry and some batteries. The actuating arms pushing the wheels around will have a hinge and spring in them so that they can slide over the teeth when retracting for the next impulse. I am still trying to decide how best to display the time, but I am leaning towards a vertical, numbered ring on top of each wheel and a pointer; the time will be read vertically by reading off from the marker. I envisage a day of the week and a night time or day time display on the top. The whole thing, other than the base, will be placed within a clear tubular case.

                                      Still, plenty of time to settle on a design that interests me enough to actually spend the time building it. I have designed two other clocks, but neither really engaged me anywhere as much as this has.

                                      vertical clock front.jpgvertical clock base.jpg

                                       

                                      Regards,

                                      James.

                                       

                                      Edited By James Alford on 21/01/2018 09:55:09

                                      Edited By James Alford on 21/01/2018 09:55:50

                                      Edited By James Alford on 21/01/2018 09:57:34

                                      #337662
                                      James Alford
                                      Participant
                                        @jamesalford67616

                                        An irritating update.

                                        I updated my Uno board and libraries following the prompts that came up when plugged it in this morning.

                                        Now, on all versions of my programme, I get an error message on compiling saying:

                                         

                                        error: no matching function for call to 'DS3231::DS3231(const uint8_t&, const uint8_t&'

                                         

                                        DS3231 rtc(SDA, SCL);

                                        The emoji is not my addition. I have no idea what has happened, but now need to try and unpick what is causing it………………

                                        James.

                                         

                                         

                                        Edited By James Alford on 21/01/2018 11:17:25

                                        #337669
                                        SillyOldDuffer
                                        Moderator
                                          @sillyoldduffer
                                          Posted by James Alford on 21/01/2018 11:15:58:

                                          An irritating update.

                                          I updated my Uno board and libraries following the prompts that came up when plugged it in this morning.

                                          Now, on all versions of my programme, I get an error message on compiling saying:

                                          error: no matching function for call to 'DS3231::DS3231(const uint8_t&, const uint8_t&'

                                          DS3231 rtc(SDA, SCL);

                                          The emoji is not my addition. I have no idea what has happened, but now need to try and unpick what is causing it………………

                                          James.

                                          Edited By James Alford on 21/01/2018 11:17:25

                                          Have a look at the definitions of SDA and SCL. Should be something like:

                                          const uint8_t SDA = 11;

                                          rather than, say, the very similar:

                                          int SDA = 11;

                                          The compiler is complaining because one or both of the SDA and SCL type definitions don't match what the RTC library is expecting. Presumably the RTC library specification was tightened by the last update.

                                          The other way of fixing it is with a cast. eg:

                                          DS3231 rtc( (const uint8_t) SDA, (const uint8_t) SCL);

                                          The first method is the more correct – everything matches. The second method tells the compiler "I know the definition of SDA isn't quite right and I know what it should be, stop moaning".

                                          Dave

                                          #337677
                                          Marcus Bowman
                                          Participant
                                            @marcusbowman28936

                                            Updates are a pain. Updating to the current version caused the IDE to refuse to compile anything correctly, so it will not run on my MAC. Won't compile on XP of course, but does do the job nicely on W7.

                                            Yes; I know my Mac OS is 'no longer supported' as is XP, but it is annoying when things like this are not at least backward compatible to the extent that they continue to work with existing sketches.

                                            Marcus

                                            #337752
                                            James Alford
                                            Participant
                                              @jamesalford67616

                                              Dave,

                                              Thank you for the suggestions. I have been playing with this, but to no avail so far. I have to confess that, to be honest, I do not really know what I am doing.

                                              I have searched through the code for the SDA and SC definitions, but can find nothing there. I have added the "cast" code, but that has not worked either. The trouble is, though, that I am not sure quite what the bits const uint8_t really mean nor where I should place the "cast".

                                              I shall carry on looking and playing…………

                                              James.

                                              #337759
                                              SillyOldDuffer
                                              Moderator
                                                @sillyoldduffer

                                                Did you replace

                                                DS3231 rtc(SDA, SCL);

                                                with

                                                DS3231 rtc( (const uint8_t) SDA, (const uint8_t) SCL);

                                                What error do you get from the second form?

                                                The explanation – if interested read, on.

                                                In C, all variables must be declared before use. For example:

                                                int a; // a is an integer
                                                int b=2; // b is an integer set to 2
                                                float f; // f is a floating point number

                                                Somewhere near the front of your code there will integer definitions for SDA and SCL. They define the pins on the Arduino to which the RTC Modules SDA and SCL terminals are connected. Something like:

                                                char SDA = 11; // Not necessarily 11 – depends on your wiring
                                                or int SDA = 11;
                                                or byte SDA = 11;
                                                or similar

                                                uint8_t is an Unsigned 8-bit integer. It's a close relative of char, int and byte, but not identical.

                                                A declaration like

                                                const uint8_t SDA = 11; means "SDA is an unsigned integer (can't be negative) that's set to 11. Also, it's a constant number that cannot be changed later."

                                                "error: no matching function for call to 'DS3231::DS3231(const uint8_t&, const uint8_t& ) ;" means that the DS3231 RTC is expecting to be initialised with a pair of constant unsigned 8-bit integers and that's not how SDA and SCL are defined further up the code.

                                                This is sensible. There are no circumstances where it would be legitimate to change an RTC module's connections while the program is running. Attempting it is almost certainly a bad mistake. The compiler is 'helpfully' preventing you from making that mistake – it's 'tough love'.

                                                A 'cast' is a conversion. int a = (int) 3.141; would set a = 3. The cast is what's between the brackets.

                                                Usually you don't get entangled in this arcane stuff: most sensible conversions are done automatically.

                                                Dave

                                                #337780
                                                James Alford
                                                Participant
                                                  @jamesalford67616

                                                  Dave,

                                                  Thank you for the explanation, which makes sense and makes the problem both clearer and, perversely, more puzzling to me.

                                                  Firstly: I tried replacing DS3231 rtc(SDA, SCL); with DS3231 rtc( (const uint8_t) SDA, (const uint8_t) SCL); but received the same error message as before.

                                                  However, after reading your explanation, I read through the my code to try and find definitions of SDA, SCL or indeed anything else to do with the RTC. The only definitions or setting up that I can find are as below.

                                                  Near the top, before the void setup or void loop, but amongst the other definitions, was

                                                  DS3231 rtc(SDA, SCL); which is now replaced by DS3231 rtc( (const uint8_t) SDA, (const uint8_t) SCL);

                                                  A couple of lines down is this:

                                                  //define RTC address
                                                  #define DS3231_I2C_ADDRESS 0x68

                                                  There are no other references to the RTC or DS3231 that I can find, other than

                                                  // Initialize the rtc object
                                                  rtc.begin();

                                                  in void setup and a series of commands to read from the RTC for the display.

                                                  I thought that I had possibly managed to delete something vital without realising it, so checked a much earlier version of the sketch that was fully operational, but this was the same.

                                                  I am assuming that I need to add something to the code to specifically define the RTC. I shall have to have another go this evening after work.

                                                  Regards,

                                                  James.

                                                   

                                                   

                                                   

                                                  #define DS3231_I2C_ADDRESS 0x68

                                                  Edited By James Alford on 22/01/2018 07:25:40

                                                  #337788
                                                  SillyOldDuffer
                                                  Moderator
                                                    @sillyoldduffer

                                                    Morning James.

                                                    First of all my apologies for misleading you yesterday. Brain-fade at my end. The RTC is an I2C device and on the Arduino, SCL is always on pin A5 and SDA on pin A4. The pins are predefined and you can't change them. You can't find the definitions because they're not in your code – I sent you on a wild-goose chase!

                                                    Something else is wrong:

                                                    • Which RTC library are you using?
                                                    • Are there any other error messages or warnings in the window?

                                                    Quite often as a program grows and this sort of error suddenly strikes it can be hard to see the wood for the trees. Nothing worse than looking for a subtle bug in a mass of code. If we don't crack this quickly, write a new sketch, as short as possible, that does nothing but prove the RTC works. Quite likely you won't need to write it yourself – most Arduino libraries come with an examples folder containing a few simple demo sketches.

                                                    Good news – as you had it working before, it's likely that the error will be easy to fix. Bad news, small errors can be hard to find.

                                                    If you get really stuck, we can exchange email addresses via a PM. If you send me a copy of your program, I'll have a closer look.

                                                    Dave

                                                    #337846
                                                    Marcus Bowman
                                                    Participant
                                                      @marcusbowman28936

                                                      Testing the RTC is quite straightforward. Here's a sketch (below). As indiated in the comments, you will need to instal the RTC library from Adafruit (link inside the sketch.

                                                      // Date and time functions using a DS3231 RTC connected via I2C and Wire lib
                                                      // This example taken from Adafruit. Info at https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/arduino-usage

                                                      // Wire.h is part of the Arduino IDE
                                                      #include <Wire.h>

                                                      // RTClib.h comes from https://codeload.github.com/adafruit/RTClib/zip/master
                                                      #include "RTClib.h"

                                                      // Connections:
                                                      // RTC SDA to Arduino A4
                                                      // RTC SCL to Arduino A5

                                                      RTC_DS3231 rtc;

                                                      char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

                                                      void setup () {

                                                      #ifndef ESP8266
                                                      while (!Serial); // for Leonardo/Micro/Zero
                                                      #endif

                                                      Serial.begin(9600);

                                                      delay(3000); // wait for console opening

                                                      if (! rtc.begin()) {
                                                      Serial.println("Couldn't find RTC&quot;
                                                      while (1);
                                                      }

                                                      if (rtc.lostPower()) {
                                                      Serial.println("RTC lost power, lets set the time!&quot;
                                                      // following line sets the RTC to the date & time this sketch was compiled
                                                      rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
                                                      // This line sets the RTC with an explicit date & time, for example to set
                                                      // January 21, 2014 at 3am you would call:
                                                      // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
                                                      }
                                                      }

                                                      void loop () {
                                                      DateTime now = rtc.now();

                                                      Serial.print(now.year(), DEC);
                                                      Serial.print('/&#39;
                                                      Serial.print(now.month(), DEC);
                                                      Serial.print('/&#39;
                                                      Serial.print(now.day(), DEC);
                                                      Serial.print(" (&quot;
                                                      Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
                                                      Serial.print(&quot &quot;
                                                      Serial.print(now.hour(), DEC);
                                                      Serial.print(':&#39;
                                                      Serial.print(now.minute(), DEC);
                                                      Serial.print(':&#39;
                                                      Serial.print(now.second(), DEC);
                                                      Serial.println();

                                                      Serial.print(" since midnight 1/1/1970 = &quot;
                                                      Serial.print(now.unixtime());
                                                      Serial.print("s = &quot;
                                                      Serial.print(now.unixtime() / 86400L);
                                                      Serial.println("d&quot;

                                                      // calculate a date which is 7 days and 30 seconds into the future
                                                      DateTime future (now + TimeSpan(7,12,30,6));

                                                      Serial.print(" now + 7d + 30s: &quot;
                                                      Serial.print(future.year(), DEC);
                                                      Serial.print('/&#39;
                                                      Serial.print(future.month(), DEC);
                                                      Serial.print('/&#39;
                                                      Serial.print(future.day(), DEC);
                                                      Serial.print(' &#39;
                                                      Serial.print(future.hour(), DEC);
                                                      Serial.print(':&#39;
                                                      Serial.print(future.minute(), DEC);
                                                      Serial.print(':&#39;
                                                      Serial.print(future.second(), DEC);
                                                      Serial.println();

                                                      Serial.println();
                                                      delay(3000);
                                                      }

                                                      Compile, then upload. Then open a Serial Monitor window. There is a pause before the first time reading appears, then an update every 3 seconds. Works very well.

                                                      Marcus

                                                    Viewing 25 posts - 51 through 75 (of 86 total)
                                                    • Please log in to reply to this topic. Registering is free and easy using the links on the menu at the top of this page.

                                                    Advert

                                                    Latest Replies

                                                    Viewing 25 topics - 1 through 25 (of 25 total)
                                                    Viewing 25 topics - 1 through 25 (of 25 total)

                                                    View full reply list.

                                                    Advert

                                                    Newsletter Sign-up