body:
based on the concept of [user1843591 answer](https://arduino.stackexchange.com/a/31339/13509), i researched some more and found the [example of Nick Gammon](https://forum.arduino.cc/t/how-to-create-a-38-khz-pulse-with-arduino-using-timer-or-pwm/100217/44) in the arduino forum.

after some tweaks i came up with the following:
(based on both)
it uses Timer1 to generate a 38kHz signal and
Timer2 to generate a 760Hz cycle that switches the 38kHz signal on and off.
this way [the recommend pulse-cycles and gap times](https://www.vishay.com/docs/82459/tsop48.pdf#page=6&zoom=250,-155,381) for the Receiver (for me TSOP4438) is preserve.
it also implements *global flags* to decouple  the ISRs & mainloop.

(both files should be in a folder `IR_TSOP4438_light_barrier`)

`IR_TSOP4438_light_barrier.ino`
```
// simple light barrier test

extern volatile bool light_barrier_broken;

void setup(){
    Serial.begin(115200);
    Serial.println("IR_TSOP4438_light_barrier");
    Serial.println("setup...");
    setupIRLightBarrier();
    Serial.println("running.");
}

void loop() {
  if(light_barrier_broken) {
    Serial.println("light barrier 1 break detected");
    delay(20);
    digitalWrite (LED_BUILTIN, LOW);
    light_barrier_broken = false;
  }
}

```

`ir_light_barrier.ino`
```
// based on
// Example of modulating a 38 KHz carrier frequency at 500 Hz with a variable duty cycle
// Author: Nick Gammon
// Date: 24 September 2012
// https://forum.arduino.cc/t/how-to-create-a-38-khz-pulse-with-arduino-using-timer-or-pwm/100217/44

// tweaked for TSOP4438
// https://www.vishay.com/docs/82459/tsop48.pdf
// find max burst length and min gap times:
//
// Minimum burst length 10 cycles/burst
// After each burst of length 10 to 40 cycles
//  a minimum gap time is required of ≥ 10 cycles
// Maximum number of continuous short bursts/second: 1500
//
// translates to:
// 38kHz = 26,3 us / Pulse → *10= 263us
// max burst length: <= 1052us  (26,3*40)
// min gap   length: >=  263us  (26,3*10)
// total cycle time of (1052+263=) 1315us
// that violates the max bursts/second (666us/burst)
//
// on option is to optimize for the most bursts/second:
// so we use the min gap time as given and use the rest of the available time.
// 666us - 263us = 403 us burst length
// hopefully this way the AGC does not filter our stream...
// we now have to fit this to the best available prescaler / counter values:
// 672us fits good (this way we have less than the 1500 burst)
// this translates to 42 counts a' (0,0625us*256=) 16us
// so we use a gap length of 16us*17 = 272us
// this gives us a burst length of 16us*(42-17)= 400us
//
// second option is to optimize for the longest burst length and have less bursts/second.
// here we will use a in-between leaning towards longer bursts:
// 0,0625us*256=16us
// 16us*50counts =  800us = 0,80ms = 1250,00Hz = 1250bursts/s
// 16us*80counts = 1280us = 1,28ms =  781,25Hz = 781,25bursts/s
// gap   length: 16us*17      =  272us
// burst length: 16us*(80-17) = 1008us

// http://www.gammon.com.au/forum/?id=11504
// Timer 1
//   OC1A: D9
//   OC1B: D10
const byte LED = 9;

// Timer 2 (8bit)
//   OC2A: D11
//   OC2B: D3

// https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
const byte light_barrier_PIN = 2;
// const byte light_barrier_PIN = 3;

// global flags to be handled in the main loop...
volatile bool light_barrier_broken = false;

// Clock frequency divided by 38 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 38000L;
// (16000000 / 38000) = 421,05
// this only works on Timer 1 - as it is a 16bit timer.

// // ------------------------------------------
// // this is about the slowest possible setting.
// // timer2 target counts:
// // CPU          16MHz (0,0625us)
// // target       63Hz (16000us = 16ms)
// // prescaler    1024
// const long timer2_top = F_CPU / 63L / 1024;
// // (16000000 / 63 / 1024) = 250

// // ------------------------------------------
// // optimized for ~1500 bursts /second
// // target counts:
// // CPU          16MHz (0,0625us)
// // prescaler    256
// // target       1,488kHz (672us = 0,672ms)
// const long timer2_top = (F_CPU / 256L) / 1488L;
// // (16000000 / 256) / 1488 = 42
// // calculate on / off ratio (toggle point)
// const long timer2_compare = timer2_top * 400L / 672L;
// // 42 * 400 / 672   = 42 - 17   = 25

// ------------------------------------------
// in-between -  leaning for longer bursts
// target counts:
// CPU          16MHz (0,0625us)
// prescaler    256
// target       781kHz (1280us = 1,28ms)
const long timer2_top = (F_CPU / 256L) / 781L;
// (16000000 / 256) / 781 = 80
// calculate on / off ratio (toggle point)
const long timer2_compare = timer2_top * 1008L / 1280L;
// 80 * 1008 / 1280   =  80 - 17  =  63

volatile bool sender_active = false;

void light_barrier_ISR() {
    if (
        sender_active
        && digitalRead(light_barrier_PIN) == HIGH
    ) {
        digitalWrite (LED_BUILTIN, HIGH);
        light_barrier_broken = true;
        // if() {
        // }
    } else {
        digitalWrite (LED_BUILTIN, LOW);
    }
}

ISR (TIMER2_COMPA_vect) {
    // used to combine the two timers...

    // toggle D13
    // PINB = bit (5);
    // digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)) ;

    if (sender_active == false) {
        // enable timer1 output
        TCCR1A |= bit(COM1A0) ;  // Toggle OC1A on Compare Match
        // digitalWrite (LED_BUILTIN, HIGH);
        delayMicroseconds(100);
        sender_active = true;
    } else {
        sender_active = false;
        delayMicroseconds(100);
        // disable IR-Receiver Input check
        //detachInterrupt(digitalPinToInterrupt(light_barrier_PIN));
        // disable timer1 output
        TCCR1A &= ~bit(COM1A0) ;  // DO NOT Toggle OC1A on Compare Match
        digitalWrite (LED, LOW);  // ensure off
        // digitalWrite (LED_BUILTIN, LOW);
    }
}

void setupIRLightBarrier() {
    pinMode(LED, OUTPUT);
    digitalWrite(LED, LOW);
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, LOW);

    // set up Timer 1 - gives us 38.095 KHz
    TCCR1A = bit (COM1A0); // toggle OC1A on compare
    TCCR1B = _BV(WGM12) | _BV (CS10);   // CTC to OCR1A, No prescaler
    OCR1A =  (16000000L / 38000L / 2) - 1;  // zero relative

    // setup Timer 2
    TCCR2A = 0;
    TCCR2B = 0;
    // toggle OC2A on compare
    // TCCR2A |= bit(COM2A0);
    // fast pwm to OCR2A
    TCCR2A |= bit(WGM21) | bit(WGM20);
    TCCR2B |= bit(WGM22);
    // prescaler 1024
    // TCCR2B |= bit(CS22) | bit(CS21) | bit(CS20);
    // prescaler 265
    TCCR2B |= bit(CS22) | bit(CS21);
    // top
    OCR2A = timer2_top - 1;  // zero relative
    // switch point
    OCR2B = timer2_compare - 1;  // zero relative
    // enable interrupts
    TIMSK2 = bit(OCIE2A);
    // TIMSK2 = bit(OCIE2B) | bit(OCIE2A);

    // enable IR-Receiver Input check
    attachInterrupt(
        digitalPinToInterrupt(light_barrier_PIN),
        light_barrier_ISR,
        CHANGE
    );
}

```


sender: user

message:
Read time digits from DS1307 and run code based on return

I am currently reading a DS1307 adafruit breakout board and I need to drive two nixie tubes from a shift register. The shift register is running two 74141 IC chips. I have code that loops through all the nixie digits one at a time with a delay of 1 second between each. Now I need to write some code to pull min, hour, and second and change the shift register low/high outputs to display the correct nixie digit. I have the DS1307 returning the correct time on my com by using

     Serial.print(now.hour(), DEC);
     Serial.print(now.minute(), DEC);
     Serial.print(now.second(), DEC);

However, I am not sure how to dimension a string, set that string equal to the two digits on the hour, minute, or time, and then divide the two digits and write if statements to correctly display the tubes. I am used to VB.NET and now C coding.

=======================UPDATE=======================

I am using this code to set any individual digit of the nixie tube to on.

           //Turn on 0
     sr.set(4, LOW);
     sr.set(5, LOW);
     sr.set(6, LOW);
     sr.set(7, LOW);

The sr is the shift register and each number is which leg of the shift register I am turning low or high. This specific piece turns on the digit 0.

sender: assistant

body:
You can set up an array containing the bit patterns to turn on different digits, and then use code that sends the bits for the high digit of `now.hour()/12` and the bits for the low digit of `now.hour()`.  For example:

    const byte digiBits[] = { B0000, B0001,
    // and so forth for all the digits ...
    };

    void send1Digit(byte digiVal, byte whichDigit) {
      // somehow use whichDigit to direct the bits someplace...

      // To send the bits:
      byte bits = digiBits[digiVal];
      for (byte i=4; i<8; ++i) {
        sr.set(i, bits & 1);  // Set a bit in SR to 0 or 1
        bits >>= 1; // shift out the used bit
      }
    }

    void send2Digits(byte numVal, byte whichDigit) {
      send1Digit(numVal/10, whichDigit);
      send1Digit(numVal, whichDigit+1);
    }

    void loop() {
      // other stuff, then:
      send2Digits(now.hour(), HourSpot);
      send2Digits(now.minute(), MinuteSpot);
      send2Digits(now.second(), SecondSpot);
      // other stuff ...
    }

Note 1:  If your `sr.set()` routine is doing any complicated masking or shifting, you may be able to avoid some of that by ORing `digiBits[digiVal]` with whatever number `sr.set()` might be building up to shift out.

Note 2:  If the numerical value of `digiBits[digiVal]` is equal to `digiVal`, then don't bother defining `digiBits[]`, but instead in `send1Digit()` just say `byte bits = digiVal`, or use `digiVal` directly in place of `bits`.


message:
7 Segment display dimming

I've got project that needed to have some (4) digits display, and had plenty of 7 seg. displays lying around. I didn't have any multiplexers left but have instead wired it up as per this diagram:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/KC1fL.png

I've the wired my duemilanove with the a-dp pins on the 13-6, and the transistors on 5-2.

Getting the right segments on has been a breeze, but I'm finding that if I have any kind of counting logic, the displays dim to about 20%.
What I mean by this is that I can have my sketch run with all digits full brightness displaying 8s no problem, but if anywhere in the loop I have a variable that I increment up (say by incrementing up 1 per loop), and change nothing else, the display will go from 100% brightness, to 20% (at best).

Below is the demo code I'm using (there are tons of weird things in it at the moment as I've been desperately trying to track this dimming issue down), and all I have to change to see the effect take place is to uncomment the line at the end of the loop: "//count = count + 1;"

    const int sub_delay = 1000;

    const int middle_middle = 13;
    const int middle_top = 11;
    const int middle_bottom = 8;

    const int top_left = 12;
    const int top_right = 10;
    const int bottom_left = 9;
    const int bottom_right = 7;
    //Build the digit quick table

    int digits_all[] = {top_left, top_right, middle_top, middle_bottom, bottom_right, bottom_left, middle_middle};
    int digits0[] = {top_left, middle_top, top_right, middle_bottom, bottom_right, bottom_left};
    int digits1[] = {top_right, bottom_right};
    int digits2[] = {middle_top, middle_middle, middle_bottom, top_right, bottom_left};
    int digits3[] = {middle_top, middle_middle, middle_bottom, top_right, bottom_right};
    int digits4[] = {};
    int digits5[] = {};
    int digit_selector0 = 2;
    int digit_selector1 = 3;
    int digit_selector2 = 4;
    int digit_selector3 = 5;
    int digit_selectors[] = {digit_selector0, digit_selector1, digit_selector2, digit_selector3};

    int last = digits_all;
    int last_size = sizeof(digits_all);
    int last_selector = digit_selector0;

    String test = "12, 13, 10, 8, 7, 9";

    int count = 0;

    // the setup function runs once when you press reset or power the board
    void setup() {
      //Initialize the digit segments
      for (int c = 0; c < sizeof(digits0); c++) {
        //digitalWrite(digits0[c], HIGH);
        pinMode(digits0[c], OUTPUT);
      }

    //demo
      //digitalWrite(middle_middle, HIGH);
      //digitalWrite(top_left, HIGH);
      //digitalWrite(middle_top, HIGH);
      //digitalWrite(top_right, HIGH);
      //digitalWrite(bottom_left, HIGH);
      //digitalWrite(middle_bottom, HIGH);
      //digitalWrite(bottom_right, HIGH);

        Serial.begin(9600);

    }

    void turn_off_all (int digit, int digits[], int digits_size, int num) {

      last = digits;
      last_size = digits_size;

      digitalWrite(last_selector, LOW);
      last_selector = digit;

      digitalWrite(digit, HIGH);
    int temp = 1;
      if (num == 0) {
        digitalWrite(top_left, HIGH);
        digitalWrite(top_right, HIGH);
        digitalWrite(middle_bottom, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(bottom_left, HIGH);
        digitalWrite(middle_top, HIGH);

        digitalWrite(middle_middle, LOW);
      }

      if (num == 1) {
        digitalWrite(top_right, HIGH);
        digitalWrite(bottom_right, HIGH);

        digitalWrite(top_left, LOW);
        digitalWrite(middle_bottom, LOW);
        digitalWrite(bottom_left, LOW);
        digitalWrite(middle_top, LOW);
        digitalWrite(middle_middle, LOW);
      }

      if (num == 2) {
        digitalWrite(middle_top, HIGH);
        digitalWrite(middle_middle, HIGH);
        digitalWrite(middle_bottom, HIGH);
        digitalWrite(top_right, HIGH);
        digitalWrite(bottom_left, HIGH);

        digitalWrite(top_left, LOW);
        digitalWrite(bottom_right, LOW);
      }

      if (num == 3) {
        digitalWrite(middle_top, HIGH);
        digitalWrite(middle_middle, HIGH);
        digitalWrite(middle_bottom, HIGH);
        digitalWrite(top_right, HIGH);
        digitalWrite(bottom_right, HIGH);

        digitalWrite(top_left, LOW);
        digitalWrite(bottom_left, LOW);
      }

      if (num == 4) {
        digitalWrite(top_right, HIGH);
        digitalWrite(top_left, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(middle_middle, HIGH);

        digitalWrite(middle_bottom, LOW);
        digitalWrite(middle_top, LOW);
        digitalWrite(bottom_left, LOW);
      }

      if (num == 5) {
        digitalWrite(top_left, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(middle_bottom, HIGH);
        digitalWrite(middle_middle, HIGH);
        digitalWrite(middle_top, HIGH);

        digitalWrite(top_right, LOW);
        digitalWrite(bottom_left, LOW);
      }

      if (num == 6) {
        digitalWrite(top_left, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(bottom_left, HIGH);
        digitalWrite(middle_bottom, HIGH);
        digitalWrite(middle_middle, HIGH);
        digitalWrite(middle_top, HIGH);

        digitalWrite(top_right, LOW);
      }

      if (num == 7) {
        digitalWrite(top_right, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(middle_top, HIGH);

        digitalWrite(bottom_left, LOW);
        digitalWrite(middle_bottom, LOW);
        digitalWrite(middle_middle, LOW);
        digitalWrite(top_left, LOW);
      }

      if (num == 8) {
        digitalWrite(top_left, HIGH);
        digitalWrite(top_right, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(bottom_left, HIGH);
        digitalWrite(middle_bottom, HIGH);
        digitalWrite(middle_middle, HIGH);
        digitalWrite(middle_top, HIGH);
      }

      if (num == 9) {
        digitalWrite(top_left, HIGH);
        digitalWrite(top_right, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(middle_middle, HIGH);
        digitalWrite(middle_top, HIGH);
        digitalWrite(middle_bottom, HIGH);

        digitalWrite(bottom_left, LOW);
      }

    }

    // the loop function runs over and over again forever
    void loop() {

        turn_off_all(digit_selector0, digits0, sizeof(digits0), 1);
      delay(1000);

      //count = count + 1;

    }

Any suggestions welcome!

Extra notes: I haven't yet tried another arduino board, but I've never had issues with this particular board before (Though I am hoping to switch to an ESP8622, but that is irrelevant to this issue).

body:
You seem to be trying to do this from scratch. I haven't analysed the code, but you would be better off using one of the established libraries.

The code is unclear - I am not sure what much of it is trying to do (a few comments would help). There are obvious errors - in particular the incorrect use of `sizeof()` which is a common error.

I use the following http://playground.arduino.cc/Main/SevenSegmentLibrary

This just requires a single call to set the digits to be displayed and includes a Brightness call.


body:
If, as comments suggest, the problem also occurs when you are using a library, it's possible the problem is hardware related.  The 10KΩ base resistors are inordinately large, and are so large the transistors probably are limiting the total current per display to under 50 mA.

When you turn on one of d2 ... d5 (your digit-select drives), at most half a milliamp (5V/10KΩ) will enter the base.  If transistor beta is 100, that will allow 50 mA to flow.  (Not knowing the transistor type you used, I don't know its range of betas.)

Consider replacing the 10KΩ base resistors with 500-700 Ω resistors.

I see no place in the circuit where capacitors would make any positive difference.


message:
Detailed analyse of memory usage

When compiling a sketch, after linking, the build outputs a kind of forecast on RAM usage, e.g.:

> Minimum Memory Usage: 1456 bytes (71% of a 2048 byte maximum)

Is it possible to somehow get a breakdown or itemization of these 1456 bytes and details on exactly where in my code, or in included libraries, they are used?

body:
Looking at an assembly listing of your code is the most direct method for finding out details of space allocation.  On my Ubuntu Linux system, I use a shell script (that is, a file containing shell commands) like the following to produce an assembly listing of the most-recently-compiled `.ino` file, which must be in the working directory when the script executes:

    #!/bin/sh
    # Look for .ino in current directory, and find recent /tmp/build...
    item=*.ino
    [ -z "$item" ] && echo ino file not found && exit
    BDIR=/tmp/$(ls -t /tmp | egrep -m1 build.*tmp)
    BASE=$(basename $item .ino)
    avr-objdump -S -I$PWD $BDIR/$BASE.cpp.elf > $BASE.ino.asm

All the stuff before the `avr-objdump` line allows the script to find out the name of the current `.ino` file and the name of the `/tmp/` subdirectory where the `.ino`'s `.elf` file is found.

You can also use `avr-objdump` to get a more concise size listing, as follows, where `$BDIR` and `$BASE` are as in the script above and represent the build directory in `/tmp/`, and the basename of the `.ino` file.

    avr-objdump -C -d $BDIR/$BASE.cpp.o| egrep -C2 '^Disassembly' | egrep -v '^--|^$|^Disassembly' | less

This will produce a list with two-line entries like the following, in which each line beginning with 00000000 is a subroutine name, and the next line shows the last line of its compiled code.  In this example output, the `setup_PowerDown()` routine has `0xA4` bytes of code, ISR `__vector_13` has `0xC6` bytes, `keepAlive()` has `0x10` bytes, etc.

    00000000 <setup_PowerDown()>:
      a4:   08 95           ret
    00000000 <__vector_13>:
      c6:   18 95           reti
    00000000 <keepAlive()>:
      10:   08 95           ret
    00000000 <eeWrite1(unsigned char, unsigned char)>:
      3a:   08 95           ret
    00000000 <eeWrite2(unsigned char, unsigned char)>:
      18:   0c 94 00 00     jmp     0       ; 0x0 <eeWrite2(unsigned char, unsigned char)>
    00000000 <parValidate(unsigned char, unsigned char, unsigned char)>:
      64:   08 95           ret
    00000000 <loadSettings()>:
      e0:   08 95           ret
    00000000 <applySettings()>:
      84:   08 95           ret

Some IDEs provide symbol table information that includes sizes of routines, stack frames, and data.  I don't know if that's available via Arduino IDE, AVR-libc, or [GNU Binutils](http://www.sourceware.org/binutils/).  The symbol table provided by `avr-readelf -s` (as in following command) provides quite detailed symbol information that seems quite useless in its raw form.

    avr-readelf  -s  $BDIR/$BASE.cpp.o

The methods described above are somewhat ad hoc, and depend on files left after `avr-gcc` or `avr-g++` run.  I don't know of any “official” methods for getting the information you want to see.


body:
Since you seem interested about RAM, rather than flash usage, I suggest
you look at the symbol table of your compiled program, which will be
more telling than the disassembly. On my Linux system, I usually do the
following:

    avr-nm -Crtd --size-sort the_program.elf | grep -i ' [dbv] '

`avr-nm` is the utility for displaying the symbol table. It is normally
packaged with the Arduino IDE. It is invoked here with the following
options:

* `--size-sort` is quite explicit
* `-C` means “demangle the C++ names”
* `-r` means “reverse sort”, i.e. sort from largest to smallest
* `-td` means “display numbers in decimal rather than hexadecimal”

This will output the list of all symbols that have a size, in three
columns: size, type and name. You are only interested in the symbols
that consume RAM, i.e. those of type `b` (BSS, or uninitialized data),
`d` (initialized data) and `v` (vtable), either in upper or lower case.
The `grep` command is a standard Unix utility which is used here to
extract only the relevant lines from the output of `avr-nm`.

Example output for a small program:

    00000068 B tx_buffer
    00000068 B rx_buffer
    00000034 B Serial
    00000016 V vtable for HardwareSerial
    00000004 B timer0_overflow_count
    00000004 B timer0_millis
    00000002 b loop::last_print
    00000001 b timer0_fract

The first 4 entries come from the `Serial` object. The 3 entries
starting with `timer0_` are used by the Arduino timekeeping functions
(`millis()`, `micros()` and `delay()`). The entry named
`loop::last_print` is a static local variable I declared in `loop()`.


body:
You can automatically generate a "map" file every time you compile. This gives you a full breakdown of how everything is linked together by the linker, including the size of each section and other useful debugging information.

A simple modification to platforms.txt in `hardware/arduino/avr` is all that is needed.  Find the line starting `compiler.c.elf.flags=` and add to the end of it:

     -Wl,-Map,"{build.path}/{build.project_name}.map"

If you like you can replace `{build.path}` with a hard-coded path, such as your desktop, and the `.map` with `.txt` to allow it to easily be opened by notepad or whatever you use (assuming Windows, of course).


body:
This was a great question and helped me recently as I'm building quite an extensive Arduino app using a Nano (ATMega328 and 32K of program memory).
At one point I was almost out of program memory and I was a bit shocked.
I didn't think the code was that large.

**My Tests and Results**

With the comments I read through the posts on this answer I decided to build a blank app and examine the results as I added libraries etc.  Here are my results (*Using Arduino IDE 1.8.13*):

1.  blank sketch takes up 444 bytes of program storage space (max is 30720 bytes).
2. Sketch which includes 6 libraries✔ uses up 6218 bytes

    `<LiquidCrystal_I2C.h>, <Wire.h>,<ds3231.h>,<SD.h>,<EEPROM.h>,<SoftwareSerial.h>`

3. adding one line `Serial.begin(9600);` uses 6324 bytes **NOTE**: 6324 - 6218 = 106 bytes even though I only added 19 bytes (the characters for that line).
4. Adding on more line `Serial.print("a");` results in 6342 bytes used. That's 18 more bytes (6324 - 6342 = 18) which is the exact number of characters I added with that line (including semicolon).
5. Adding a 2nd line with `Serial.print("a");` results in 6358 (16 bytes)
6. Adding a 3rd line of `Serial.print("a");` results in 6374 (16 additional bytes).

I hope this helps a bit. I'm going back to my app now and removing all the Serial lines I used for debug output.  They're just eating up program memory now.
Actually, I'll probably even use the conditional compilation ([shown in this SO answer][1]) so I can still print when in debug.

 Blank sketch means one with only the `void setup() {} void loop() {}` structures and nothing else.

✔ These are the libraries which I am using in my project.

 I came back and added these additional lines with the amount of Program Memory used because there was a comment that lines of code do not impact memory at all. Of course they do.  At some point all Program Memory is used up and your program will no longer fit into flash.  This is what I was having a challenge with as my extensive program (which includes sensors, LCD, sd card, and bluetooth) continues to grow.

  [1]: https://stackoverflow.com/questions/57554719/how-to-provide-conditional-compilation-to-arduino-code


message:
Is there a non-float alternative to pow()?

I've scoured the LANGUAGE REFERENCE in the [Arduino web-site][1], and I can't find a non-Float equivalent to `pow()`  I've got to be missing something big, but for the life of me, I'm stumped!  I found `pow()` in the FUNCTIONS column under the Math heading (like I would expect), but it says that both parameters,  [base] and [exponent] are both (float). And there are only six other entries under the Math heading; none of them seem to be seem to be an integer version. All I want to do is generate the powers of 2 using the exponents from 0 to 10. Like 2^0=1 then 2^1=2 then 2^2=4 then 2^3=8 then 2^4=16 then 2^5=32 then 2^6=64 then 2^7=128 then 2^8=256 then 2^9=512 then 2^10 is 1024

Is using floats the only way I can do this? I'm starting to feel like I'm at odds with reality, and have actually counted my medication, but I'm right where I should be. Let me apologize in advance for this egregious oversight that I've wasted your time with, but I've gone through all 9 pages of tags and have done ever search I could think of. I'll admit that I haven't spent all THAT much time, but I was sure this was only going to be like a five minute thing!

  [1]: https://www.arduino.cc/en/Reference/HomePage

body:
It works with `int`, `double`, `long` and `float`. `unsigned long` and `unsigned int` should also work. You are not required to use ONLY floats.

Hope it helped!


body:
For the general case, @dat_ha 's answer is correct, but it is worth noting that you want a very special case... powers of two. Because computers use binary arithmetic, operations involving powers of two often have some shortcuts available.

Multiplying a number by a power of two can be accomplished by the left shift operation (`<<`), which literally shifts the digits of the binary representation of the number (i.e., bits) leftward.  In base two, shifting bits one place to the left is the same as multiplying by 2, just as in base 10 shifting digits one place to the left is the same as multiplying by 10. For a full explanation of the left shift operator in C++, see [this answer on Stack Overflow][1].

It is important to note that left shifting can lose information; bits shifted off the end are lost. Because you need powers of 2 up to 10, you are safe when working with signed integers, which [have a max value of `2^15-1` on Arduino Uno][2].

Given those caveats, here's a function to calculate powers of two within these constraints.  This is very fast code because the left shift operation is a very low level operation, and no multiplication is actually performed.

    int pow2(int p){
        return 1 << p;
    }

[1]: https://stackoverflow.com/a/141873
[2]: https://www.arduino.cc/en/Reference/Int


message:
Difficulties with raw string literals

I have an application where I would like to include an external multiline script as a const in my sketch. As far as I understand from C++11, this should work:

**raw_string_literal_test.ino**

    const char *script =
    #include "script.txt"
    ;

    void setup() {
      // put your setup code here, to run once:

    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

**script.txt**

    R"(Line 1
    Line 2
    Line 3
    Line 4
    Line 5
    Line 6)"

script.txt is placed in the same folder as raw_string_literal_test.ino

However, upon clicking Verify (selected board is Arduino/Genuino Uno, Arduino version is 1.6.12 on Mac OS 10.11.6) I get the following error:

    /Users/owner/Desktop/raw_string/raw_string.ino:2:22: fatal error: script.txt: No such file or directory
     #include "script.txt"
                          ^
    compilation terminated.
    exit status 1
    Error compiling for board Arduino/Genuino Uno.

What am I doing incorrectly?

body:
Unlike other more "normal" build systems, the Arduino IDE doesn't compile the files in the project directory.

Instead it loads all the files with certain extensions into the IDE, each in its own tab. When you press the compile button it then writes the contents of each of those tabs to files in a temporary build folder and then compiles there.

Because of that only files with certain extensions ever get placed in the build folder. Those include:

* `.pde` and `.ino` for sketch files
* `.c` and `.cpp` for C and C++ source
* `.h` for headers
* `.S` for assembly source.

There may be a few others as well but those are the main ones. Things like text files aren't considered source files and thus aren't ever seen by the IDE.


message:
Can I connect to a DALI network as a master node using an Arduino?

I have googled a lot, and mostly every website you can link me I have already explored, some are outdated and don't work, others aren't clear in their documentation, and use equipment too expensive to run the risk of buying it and it not working.

https://github.com/edinburghhacklab/dali

https://github.com/sde1000/python-dali

https://github.com/krzychb/DimSwitch/blob/master/extras/pictures/PHILIPS-HF-REGULATOR-TOUCH-a-DALI 18-58w-T8- 1-a-2-LAMPS.pdf

http://microcontrollershop.com/product_info.php?products_id=5384

Moreover, like any free protocol, you have to pay to access the DALI standard.

What can I do to control a network of connected DALI dimmable ballasts?

body:
I have made a simple DALI controller with Arduino Nano. Maybe it will be useful for you. Look here: [Simple DALI Controller][1]

  [1]: https://create.arduino.cc/projecthub/NabiyevTR/simple-dali-controller-506e44


message:
Arduino as analog to digital converter for temperature sensor

I have an ESP8266 module that must receive some data and send it to a server, my problem is that this data is given by a temperature sensore and a light sensor which must be connected to analog pins and my ESP has only 2 digital pins.

So I thought that I can measure the temperature and the light with an arduino (the sensors are the ones included in arduino starter pack) and then connect my esp digital pins to arduino digital pins and write a sketch to send digital data as output of arduino.

I think this is possible but I can't figure out how to do it because I can only set pins to high or low.

Can somebody help me? Thanks a lot

P.S: I already tried ther solutions like connecting tx and rx of esp to arduino but they didn't work so I prefer to use ESP8266 as standalone

body:
Both the ESP8266 and the Arduino have UART serial interfaces. This is by far the simplest method of communicating between two boards.

Connect the TX of the Arduino, through a voltage divider to drop it to 3.3V, to the RX of the ESP8266. Connect the grounds together. That's all you need. Yes, you can connect the TX of the ESP8266 to the RX of the Arduino but if you are never going to send anything from the ESP8266 to the Arduino then there is little point.

Then, with both devices set to the same baud rate, you can `Serial.print` on the Arduino, and `Serial.read` on the ESP8266. Just follow one of the many many tutorials about communicating between Arduinos using UART.


message:
What can I do in this situation

I only currently have 2 arduinos and I find that any project I build I feel bad because I have to rip it apart to get the arduino because I want to build something else. Is there a way to get arduinos for cheap? (I'm new to arduino)

body:
Possibly not "genuine" Arduinos, but eBay has many sellers in China and Hong Kong who sell boards that are just like Arduinos, if you're willing to wait several weeks for delivery.

I was able, just now, to find an Arduino UNO compatible board for US$3.59, plus less than $2 shipping to the US. Note that they do not come with tech support, and none of the profit goes to support the official Arduino developers.


message:
Lowering cost of using NRF24L01 radio module for communication between several Arduinos

I have several Arduino Uno's if I am using several NRF24L01 modules to transmit a simple pulse (1 bit of information which can be high or low) between them-from one Arduino to the rest of them. Then I was considering, because the information is one bit of information only can I replace the other receiving NRF24L01 module's with something cheaper (and probably simpler) ?-may something based on like a simple tank LC circuit?-or it maybe another simple circuit instead of the LC one. The intuition for asking the question is because only 1 bit of information (which maybe represented by a string of 1's or another known string X if it makes the decoding simpler)  is transmitted then the receiving circuit maybe simplified somehow -rather than use something like the full circuitry of a NRF24L01 module. Elaborating further on a possible scheme for decoding X may be done by just counting the "marks ratio"-as done "in a marks and spaces style scheme"-e.g. if there are known ratio of 1's, than compared to the usual ratio, then we can consider that to be a high signal received -the number of 1s sent is such that the binary information from the NRF24L01 protocol, that sends X, would not significantly affect the ratio of the 1s. however I don't know how accurate my intuition is here.

So in a nutshell, I want to know if there is a simple circuit that does what I want - an answer may include a custom Arduino sketch suggestion for the transmitter and/or receiver.

body:
To receive a signal from an nRF24L01 you either need another nRF24L01 or to reimplement the nRF24L01 in discrete components. That's a big, complex circuit requiring precision components and PCB layout. At 2.4GHz, with GFSK modulation, you need amazing skills to create something that would work reliably - and the cost would be astronomical compared to the cost of an nRF24L01.

Your thought that you are "only sending 1 bit of data" is completely wrong. Yes, you may be providing only 1 bit of data to the library that controls your nRF24L01 - however the nRF24L01 then encapsulates that single bit into a fixed length packet including source and destination addresses, checksums, and even implements a reliable ACK/NACK system for packet retransmission. None of that can be thought of as a "single bit" once it gets out onto the airwaves - so the system that you came up with would have to be able to interpret and handle that entire packet and provide any requested ACK/NACK signals back to the transmitter.

If you want to receive with a simpler system then you need to also transmit with a simpler system. The simplest system is probably the [433MHz PAM systems you find on eBay](http://www.ebay.co.uk/itm/252503539009). You pull the input pin HIGH on the transmitter and the output pin on the receiver goes HIGH. You pull the transmitter pin LOW and the receiver pin goes LOW. (Basically you turn the carrier on and off at one end, and the other end tells you if the carrier is on or off - Pulse Amplitude Modulation [also known as On Off Keying - OOK]).

Coupling that with UART signals it's possible to send actual data, but if all you need is HIGH/LOW signalling then you can drive it direct with any GPIO pin.

They are incredibly crude, and would never pass any kind of emissions testing, but they get the job done at a very low cost.

While it may be possible to create a crude 2.4GHz PAM transmitter and receiver, owing to the broadband spectrum harmonics you would have unless you managed to produce an absolutely pure sine-wave with zero harmonic distortion, the interference it would cause to other devices nearby (such as your WiFi connection) would cause untold problems. No doubt your neighbours would have something to say about that - and maybe FCC / OFCOM / whoever.


body:
> I have several Arduino Uno's if I am using several NRF24L01 modules to transmit a simple pulse (1 bit of information which can be high or low) between them-from one Arduino to the rest of them.

Let us assume that the broadcast has to reach all. None of the listeners are allowed to drop messages. How would this be achieved? Each listener would have to acknowledge the message.

Anyway reasoning about the application requirements and communication protocol may help determine if a "cheaper" solution is possible.

IMHO using NRF24L01+ is a cheap solution in this scenario.

Cheers!


message:
Cannot assign COM port to HC-05 bluetooth device

I can't set a COM port to my paired BT module. For better understanding [I recorded a YouTube video](http://youtu.be/vu9cK6emnIo) to make sure I show everything.

Hardware:

 - Arduino Nano knock-off by [RobotDyn](http://robotdyn.com) (atmega168)
 - Bluetooth module HC-05 (zs-040) which looks [like this](https://cdn.instructables.com/FLP/2YI3/HX6ARQKC/FLP2YI3HX6ARQKC.MEDIUM.jpg)
 - Windows 10 Home 64 bit on tablet

I have wired them up like this ![](https://i.stack.imgur.com/lwMAs.jpg).

However, before that, I tried to wire it up without the resistors (so I hope I didn't damage anything).

Here is my very simple code which should just echo back what it get.

    void setup() {
      Serial.begin(9600);
    }

    void loop() {
      if(Serial.available())
      {
        Serial.println(Serial.parseInt());
      }
      delay(100);
    }

body:
Based on my experience, there is nothing wrong (yet) on the Arduino. You can check  [this][1] or [this][2]. Unlike previous windows version, Win 10 tend to "ignore" bluetooth connection, so you have to assign the COM port manually.

  [1]: http://www.technorms.com/46164/bluetooth-guide-windows-10
  [2]: https://www.verizonwireless.com/support/knowledge-base-20605/


message:
Comma between two values in a macro

I am working on a project involving an Aduino and screen.

As i was going through the [u8glib (Arduino Monochrome Graphics Library for LCDs and OLEDs)][1], something caught my attention:

    #define U8G_ESC_DLY(x) 255, ((x) & 0x7f)
    #define U8G_ESC_CS(x) 255, (0xd0 | ((x)&0x0f))

How can i interpret this macro for a given x value ?

  [1]: https://github.com/olikraus/u8glib

body:
> How can i interpret this macro for a given x value ?

As normal. First expand the macro, and *then* worry about what the comma means in context. In an expression the result is the expression on the right of the comma. In a function call it stands in for two arguments. Just look at where it's used and that's what it will mean.


message:
Cannot set Pins to LOW

I am controlling 2 motors from my Arduino Pro Mini and L293D motor driver module. Problem is, I have to set a pin high and after 1 second set it to LOW. But that doesn't happen... The pin just stays HIGH and is never LOW.

Here's my Code -

        int IN2Left = 10;
        int E1 = 12;
        int E2 = 7;
        int IN3RevRight = 6;
        int trigPin1 = A0;
        int echoPin1 = A1;
        int distance1 = 0;
        int IN4Right = 5;
        int IN1RevLeft = 11;

        void setup()
        {
          pinMode(IN2Left, OUTPUT);
          pinMode(E1, OUTPUT);
          pinMode(E2, OUTPUT);
          pinMode(IN3RevRight, OUTPUT);
          pinMode(IN4Right, OUTPUT);
          pinMode(IN1RevLeft, OUTPUT);
          pinMode(trigPin1, OUTPUT);
          pinMode(echoPin1, INPUT);
          pinMode(13, OUTPUT);
          Serial.begin(9600);
        }

        void loop() {
      digitalWrite(13, HIGH);
      digitalWrite(E1, HIGH);
      digitalWrite(E2, HIGH);
      digitalWrite(IN2Left, HIGH);
      digitalWrite(IN4Right, HIGH);
      delay(3000);
      digitalWrite(IN4Right, LOW);
      digitalWrite(IN3RevRight,HIGH);
      delay(500);
      digitalWrite(IN3RevRight, LOW);
      digitalWrite(IN4Right, HIGH);
      delay(1500);
      digitalWrite(IN2Left, LOW);
      digitalWrite(IN1RevLeft, HIGH);
      delay(500);
      digitalWrite(IN1RevLeft, LOW);
      digitalWrite(IN2Left, HIGH);
      delay(100000);
        }

The `IN2Left` Pin never goes LOW... I am assuming a faulty Arduino but my Arduino seems to be working just fine as it runs other stuff (tested blink and reading an Ultrasonic sensor) just fine.

My deadline is 2 hours from now...

EDIT: Here's the complete void loop function... Note the two pins on top which go HIGH? They Never go LOW again in the entire code.

body: Your code sets it high, delays for 1000ms, sets it low, and then... turns around and sets it high almost immediately after. Try delaying in between.


body:
      digitalWrite(IN2Left, HIGH);
      delay(1000);
      digitalWrite(IN2Left, LOW);

It would go LOW for a few microseconds. Maybe put a delay after going LOW?


message:
The easiest and most time efficent way to connect to the internet regardless of the cost

I am working on my graduation Project. I want to use the cayenne (mydevices) platform to control my Arduino. Mainly I want to be able to control a servo Motor through the Cayenne app and I want to use a gyro sensor that would also control the servo using the app after obtaining the readings from the sensor. The Options are:
1- Yun arduino
2- Arduino Ethernet
3- Arduino uno (which I currently have) + Arduino Ethernet shield or arduino wifi shield

Cayenne (mydevices) APP supports all of the above Options

What is the easiest to implement? I have short time period and working on the mechanical design for the Project in the same time.

Your help is appreciated

body:
The Arduino Uno and Arduino Ethernet are very simple to program, to connect it to the Internet.

I never used the Yun Arduino, but it seems a little bit harder.


body:
If you want to stick with Arduino (instead of SBC), I suggest you use Arduino Yun.

 The Linux side of the Yun will provide very much greater scope for web programming compared to Arduino+Ethernet shield. There also a bridge library to communicate with the Yun.


message:
Shrink array to save memory

In my project I need three arrays to store data inside.

I define a maximal number of elements as a macro variable. However, at a certain point in the setup function, the program could determine, that the arrays would actually store a smaller number of elements. In other words, it is possible (and even likely) that there is more memory reserved for the arrays than actually necessary.

As I think that memory might be a critical factor on a micro controller like the Arduino, I would like to set the excess memory free.

Is there a way to dynamically resize **and shrink** the arrays at runtime?

Something like this (pseudocode)

    #define maxSize 50
    int theArray[maxSize];

    int actualSize = getActualArraySize();
    // sets actualSize to a value <= 50, let's assume actualSize = 20
    shrinkArray(theArray, actualSize);
    // shrinkArray doesn't exist :) I need something like that.

body:
This is a common question when designing software. The simple answer (rule of thumb) is **statically allocate the maximum size of the array**. In this case the maximum size of the arrays. This simple rule will keep you out of trouble and make testing etc much simpler.

Using dynamic allocation (adjusting array size etc) especially for small scale embedded systems such as the Arduino opens a "can of worms" with possible memory (heap) fragmentation and hidden concurrency and performance issues.

If the required maximum size of the array is 32 elements the application has to allow that and there is no memory to save. Statically allocating will make the sketch simpler and easier to test.

Cheers!


message:
Powering 24 volt solenoid valve with Arduino uno

Today I received normally closed solenoid valve which I am going to use in automated pot watering system ,
I realised the valve takes 24 dc volt as input and Arduino has maximum of 5volt , using some power booster I can convert it to some extent but I think 24 volt is too much .

So how should power 24volt solenoid valve from Arduino uno?![enter image description here](https://i.stack.imgur.com/CRrtO.jpg)

body:
[![enter image description here][1]][1]Since the solenoid requires higher current than the arduino can provide you can use an alternative power source for the solenoid (maybe a couple of batteries) and switch it with a TIP120 transistor.

  [1]: https://i.stack.imgur.com/GKPUO.png


body:
You have 2 choices:

1 - Preferably, use a N-channel MOSFET. Best for usage of voltage between 9 and 60, these are great little modules that can control voltage flow.

2 - Use a relay. A little more expensive, but can handle main's voltage.


message:
Will a transistor always reduce the voltage?

I have an NPN transistor that's connected over a 12V adapter. I have tried using a potentiometer to change the resistance of the incomming current. Even if i take the resistance down to 0, I end up with at most 11 Volts when measuring over the magnet.

I have measure the energy without the transistor, in that case it's 12V. Is this expected behaviour of a transistor or is something wrong?

body: Yes, it is, as both VCE(sat) and the "Collector-Emitter Saturation Voltage vs Collector Current" chart in the datasheet tells you.


message:
What pin is the external interrupt #0 for an arduino micro?

I'm putting an MPU6050 on an arduino Micro but the interrupt is different than the arduino uno. The external interrupt #0 pin on an arduino uno is pin 2 but its not pin 2 on an arduino micro. So I'm trying to figure out what pin it is on an arduino micro

body: The ATmega32U4 pin mapping says 3.


message:
Multiple client server over wifi

Trying to setup a server on Arduino to support multiple clients,
I am able to support one but I don't want to flush that client to make another connection.

    #include <ESP8266WiFi.h>
    const char* ssid = "your-ssid";
    const char* password = "your-password";
    // Create an instance of the server
    // specify the port to listen on as an argument
    WiFiServer server(80);

    void setup() {
      Serial.begin(115200);
      delay(10);

      // prepare GPIO2
      pinMode(2, OUTPUT);
      digitalWrite(2, 0);

      // Connect to WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      // Start the server
      server.begin();
      Serial.println("Server started");

      // Print the IP address
      Serial.println(WiFi.localIP());
    }

    void loop() {
      // Check if a client has connected
      WiFiClient client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      Serial.println("new client");
      while(!client.available()){
        delay(1);
      }

      // Read the first line of the request
      String req = client.readStringUntil('\r');
      Serial.println(req);
      client.flush();

      // Match the request
      int val;
      if (req.indexOf("/gpio/0") != -1)
        val = 0;
      else if (req.indexOf("/gpio/1") != -1)
        val = 1;
      else {
        Serial.println("invalid request");
        client.stop();
        return;
      }

      // Set GPIO2 according to the request
      digitalWrite(2, val);

      client.flush();

      // Prepare the response
      String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
      s += (val)?"high":"low";
      s += "</html>\n";

      // Send the response to the client
      client.print(s);
      delay(1);
      Serial.println("Client disonnected");

      // The client will actually be disconnected
      // when the function returns and 'client' object is detroyed
    }

Using this code, the server handles only one client at a time, but I need to connect multiple clents simultaneously.

body:
You need to keep track of multiple `WiFiClient`s - declare an array of them, for example, and each time `server.available()` gives you a new one, store it in the array.

Then you need to make sure your code doesn't stick waiting for data from each item.  You could service each WifiClient in turn: if it has data waiting (`client[i].available()` is true), read the data (`client[i].read()`) and store it. When you get a `\r` from a client, you know you have a whole line, and you can process it.

Here's a nearly-complete (but untested) example so you can see what I'm talking about.  Naturally it's not the only way to do it.

    #include <ESP8266WiFi.h>
    const char* ssid = "your-ssid";
    const char* password = "your-password";
    #define MAX_CLIENTS 10
    #define MAX_LINE_LENGTH 50
    // Create an instance of the server
    // specify the port to listen on as an argument
    WiFiServer server(80);
    WiFiClient *clients[MAX_CLIENTS] = { NULL };
    char inputs[MAX_CLIENTS][MAX_LINE_LENGTH] = { 0 };

    void setup() {
      Serial.begin(115200);
      delay(10);

      // prepare GPIO2
      pinMode(2, OUTPUT);
      digitalWrite(2, 0);

      // Connect to WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      // Start the server
      server.begin();
      Serial.println("Server started");

      // Print the IP address
      Serial.println(WiFi.localIP());
    }

    void loop() {
      // Check if a new client has connected
      WiFiClient newClient = server.available();
      if (client) {
        Serial.println("new client");
        // Find the first unused space
        for (int i=0 ; i<MAX_CLIENTS ; ++i) {
            if (NULL == clients[i]) {
                clients[i] = new WiFiClient(newClient);
                break;
            }
         }
      }

      // Check whether each client has some data
      for (int i=0 ; i<MAX_CLIENTS ; ++i) {
        // If the client is in use, and has some data...
        if (NULL != clients[i] && clients[i]->available() ) {
          // Read the data
          char newChar = clients[i]->read();

          // If we have the end of a string
          // (Using the test your code uses)
          if ('\r' == newChar) {
            // Blah blah, do whatever you want with inputs[i]

            // Empty the string for next time
            inputs[i][0] = NULL;

            // The flush that you had in your code - I'm not sure
            // why you want this, but here it is
            clients[i]->flush();

            // If you want to disconnect the client here, then do this:
            clients[i]->stop();
            delete clients[i];
            clients[i] = NULL;

          } else {
            // Add it to the string
            strcat(inputs[i], newChar);
            // IMPORTANT: Nothing stops this from overrunning the string and
            //            trashing your memory. You SHOULD guard against this.
            //            But I'm not going to do all your work for you :-)
          }
        }
      }

    }


body:
Here , I have  used array of WiFiClient .
The reason is  array pointer will hold previous plus latest WiFiClients (emoteIP and remotePort ) and user will be able to choose which WIFiClient to be used for communication.

We can store  IPAddress , Port as well as whole WiFiClient object in an array

     //===========================================
           WebServer  Wserver(80);

           WiFiClient Wclient;

           WiFiClient *Wificlients[10] = { NULL };

           int  Clientindex=-1;

           Wclient = Wserver.client(); // or  server.avilable() if WiFiServer

           Wificlients[Clientindex++]=new WiFiClient(Wclient);

           int   cntloggedinclient=0;
           int kk=0;

           while(Wificlients[kk] != NULL)
               {
                   cntloggedinclient++;  // Total clients count
                   kk++;
               }

             // Multicasting bytes to all connected clients.
             int kkk =0;
             while(kkk<cntloggedinclient)
             {
               Wificlients[kkk]->write((unsigned char*) &newbuff,len);
               kkk++;
             }


message:
Clear GET params from URL

I have a simple GET webform that takes in text. Once that text is submitted the URL permanently displays the text as the parameter. This causes echoing issues when I check the input from the web form; the string I am looking for is always found because the URL is never cleared. I cannot use an HTTP redirect and am looking for a way to do this based upon code.

body: this is exaclty waht get are supposed to do. Use a POST or use a redirect; a POST is way better as the "back" button of the browser will take care of it


message:
Making a current GPS code run once, and only once, after the code is 'activated'

I have a GPS code that I need to run only once, but every different try gives me errors, including placing the whole code in `void setup()`. Is there any way that this code can be run just once? As of now, the code repeats itself, putting out data over and over again - I need just one set, right when the code is activated.

Here is the code:

    #include <Adafruit_GPS.h>
    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(3, 2);
    Adafruit_GPS GPS(&mySerial);
    #define GPSECHO  true
    boolean usingInterrupt = false;
    void useInterrupt(boolean);

    void setup() {
      Serial.begin(115200);
      Serial.println("Adafruit GPS library basic test!");
      GPS.begin(9600);
      GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
      GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
      GPS.sendCommand(PGCMD_ANTENNA);
      useInterrupt(true);
      delay(1000);
      mySerial.println(PMTK_Q_RELEASE);
    }

    SIGNAL(TIMER0_COMPA_vect) {
      char c = GPS.read();
    #ifdef UDR0
      if (GPSECHO)
        if (c) UDR0 = c;
    #endif
    }

    void useInterrupt(boolean v) {
      if (v) {
        OCR0A = 0xAF;
        TIMSK0 |= _BV(OCIE0A);
        usingInterrupt = true;
      } else {
        TIMSK0 &= ~_BV(OCIE0A);
        usingInterrupt = false;
      }
    }

    uint32_t timer = millis();
    void loop() {                  // run over and over again
      if (! usingInterrupt) {
        char c = GPS.read();
        if (GPSECHO)
          if (c) Serial.print(c);
      }
      if (GPS.newNMEAreceived()) {
        if (!GPS.parse(GPS.lastNMEA()))
          return;

      if (timer > millis())
        timer = millis();

      if (millis() - timer > 2000) {
        timer = millis(); // reset the timer
        Serial.print("\nTime: ");
        Serial.print(GPS.hour, DEC); Serial.print(':');
        Serial.print(GPS.minute, DEC); Serial.print(':');
        Serial.print(GPS.seconds, DEC); Serial.print('.');
        Serial.println(GPS.milliseconds);
        Serial.print("Date: ");
        Serial.print(GPS.day, DEC); Serial.print('/');
        Serial.print(GPS.month, DEC); Serial.print("/20");
        Serial.println(GPS.year, DEC);
        Serial.print("Fix: "); Serial.print((int)GPS.fix);
        Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
        if (GPS.fix) {
          Serial.print("Location: ");
          Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
          Serial.print(", ");
          Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
          Serial.print("Location (in degrees, works with Google Maps): ");
          Serial.print(GPS.latitudeDegrees, 4);
          Serial.print(", ");
          Serial.println(GPS.longitudeDegrees, 4);
          Serial.print("Speed (knots): "); Serial.println(GPS.speed);
          Serial.print("Angle: "); Serial.println(GPS.angle);
          Serial.print("Altitude: "); Serial.println(GPS.altitude);
          Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
        }
      }
      }
    }

I've been trying to get this for a while, and I'm new to programming!

body:
Put everything from your `void loop()` into your `void setup`. Put them AFTER the original setup and you should be good to go.

**DO NOT DELETE THE VOID LOOP!! ONLY KEEP IT EMPTY!!**

Here, try this:

    #include <Adafruit_GPS.h>
    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(3, 2);

    Adafruit_GPS GPS(&mySerial);

    #define GPSECHO  true

    boolean usingInterrupt = false;
    void useInterrupt(boolean);

    void setup()
    {

      Serial.begin(115200);
      Serial.println("Adafruit GPS library basic test!");

      GPS.begin(9600);

      GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);

      GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);

      GPS.sendCommand(PGCMD_ANTENNA);

      useInterrupt(true);

      delay(1000);

      mySerial.println(PMTK_Q_RELEASE);

      if (! usingInterrupt) {

        char c = GPS.read();

        if (GPSECHO)
          if (c) Serial.print(c);
      }

      if (GPS.newNMEAreceived()) {

        if (!GPS.parse(GPS.lastNMEA()))
          return;

        if (timer > millis())  timer = millis();

        if (millis() - timer > 2000) {
          timer = millis(); // reset the timer

          Serial.print("\nTime: ");
          Serial.print(GPS.hour, DEC); Serial.print(':');
          Serial.print(GPS.minute, DEC); Serial.print(':');
          Serial.print(GPS.seconds, DEC); Serial.print('.');
          Serial.println(GPS.milliseconds);
          Serial.print("Date: ");
          Serial.print(GPS.day, DEC); Serial.print('/');
          Serial.print(GPS.month, DEC); Serial.print("/20");
          Serial.println(GPS.year, DEC);
          Serial.print("Fix: "); Serial.print((int)GPS.fix);
          Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
          if (GPS.fix) {
            Serial.print("Location: ");
            Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
            Serial.print(", ");
            Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
            Serial.print("Location (in degrees, works with Google Maps): ");
            Serial.print(GPS.latitudeDegrees, 4);
            Serial.print(", ");
            Serial.println(GPS.longitudeDegrees, 4);

            Serial.print("Speed (knots): "); Serial.println(GPS.speed);
            Serial.print("Angle: "); Serial.println(GPS.angle);
            Serial.print("Altitude: "); Serial.println(GPS.altitude);
            Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
          }
        }
      }
    }

    SIGNAL(TIMER0_COMPA_vect) {
      char c = GPS.read();

    #ifdef UDR0
      if (GPSECHO)
        if (c) UDR0 = c;

    #endif
    }

    void useInterrupt(boolean v) {
      if (v) {

        OCR0A = 0xAF;
        TIMSK0 |= _BV(OCIE0A);
        usingInterrupt = true;
      } else {

        TIMSK0 &= ~_BV(OCIE0A);
        usingInterrupt = false;
      }
    }

    uint32_t timer = millis();

    void loop()                     // run over and over again
    {
    }


body:
Here's your sketch, modified to use my library, [NeoGPS](https://github.com/SlashDevin/NeoGPS).  It is smaller, faster, more reliable and more accurate than all other libraries.

I added a `waitForFix` routine that, well, waits for the GPS to get a fix.  Then it calls `printFix`, just once:

    #include <NMEAGPS.h>
    #include <NeoSWSerial.h>

    NeoSWSerial gpsSerial(3, 2);
    NMEAGPS     GPS;
    gps_fix     fix;

    void setup()
    {
      Serial.begin(115200);
      Serial.println( F("Run once!") ); // F macro saves RAM!

      gpsSerial.begin(9600);
      gpsSerial.println( F("$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28") ); // RMC & GGA only
      gpsSerial.println( F("$PMTK220,1000*1F") ); // 1Hz update rate

      waitForFix();
      printFix();
    }

    void loop()
    {
    }

    void waitForFix()
    {
      uint8_t fixes = 0;

      do {
        if (GPS.available( gpsSerial )) {
          fix = GPS.read();
          fixes++;
        }
      } while ((fixes < 2) && !fix.valid.location);

    } // waitForFix

    void printFix()
    {
      Serial.print( F("Time: ") );
      if (fix.valid.time) {
        if (fix.dateTime.hours < 10)
          Serial.print( '0' );
        Serial.print(fix.dateTime.hours);
        Serial.print(':');
        if (fix.dateTime.hours < 10)
          Serial.print( '0' );
        Serial.print(fix.dateTime.minutes);
        Serial.print(':');
        if (fix.dateTime.hours < 10)
          Serial.print( '0' );
        Serial.print(fix.dateTime.seconds);
        Serial.print('.');
        if (fix.dateTime_cs < 10)
          Serial.print( '0' );
        Serial.print(fix.dateTime_cs);
      }
      Serial.println();

      Serial.print( F("Date: ") );
      if (fix.valid.date) {
        Serial.print(fix.dateTime.day);
        Serial.print('/');
        Serial.print(fix.dateTime.month);
        Serial.print('/');
        Serial.print( fix.dateTime.full_year() );
      }
      Serial.println();

      Serial.print( F("Fix status: ") );
      if (fix.valid.status)
        Serial.print( (int) fix.status );
      Serial.println();

      if (fix.valid.location) {
        Serial.print( F("Location: ") );
        Serial.print( fix.latitude(), 4 );
        Serial.print( F(", ") );
        Serial.println(fix.longitude(), 4);
      }

      if (fix.valid.speed) {
        Serial.print("Speed (knots): ");
        Serial.println( fix.speed() );
      }

      if (fix.valid.heading) {
        Serial.print( F("Angle: ") );
        Serial.println( fix.heading() );
      }

      if (fix.valid.altitude) {
        Serial.print( F("Altitude: ") );
        Serial.println( fix.altitude() );
      }

      if (fix.valid.satellites) {
        Serial.print( F("Satellites: ") );
        Serial.println( fix.satellites );
      }
    }

The NeoGPS library waits for a complete batch of sentences, because the speed is in one sentence (RMC) and the altitude is in another sentence (see [this table](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Choosing.md)).  NeoGPS provides complete "fixes", as assembled from all the sentences your GPS device sends.  The fixes are available once per second, or whatever you have configured your device to provide.

You may also notice that I used another library I maintain, [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial).  `SoftwareSerial` is *very* inefficient because it disables interrupts for long periods of time.  This can interfere with other parts of your sketch or other libraries.

If you can put the GPS on pins 8 & 9, AltSoftSerial would be even better.  It only works on those two pins.

Your original sketch uses 12124 bytes of program space and 1031 bytes of RAM.

The NeoGPS version uses 10680 bytes of program space and 446 bytes of RAM.  A significant savings!


message:
Arduino IDE crash when I connect Blend Micro

I recently bought [Blend Micro](http://redbearlab.com/blendmicro/) and I am setting up Arduino IDE to start using it, but after installing the required libraries and the Blend Micro drivers, the IDE suddenly crashes without any visible error whenever I plug the blend micro to my PC. If it is already plugged in, the ide won't even start up. This was not happening before I installed the drivers. I don't know if it's relevant but blend micro was connected to my pc during the drivers installation. I have already looked for a way to solve this on Google without relevant results.

I am using Windows 10 with Arduino IDE 1.6.12

I would really appreciate any help with my problem, thank you in advance.

body:
you should try to run the arduino from the consolle, on windows digit cmd on the search bar and the command promp program should appear.

Well, then you should navigate in out arudiono folder: digit `cd "XXX"` where XXX is the arduino executable location (something like c:/program files/blabla), you can copy paste it from the folder explorer.

then write `arduino_debug.exe` and you should see on the terminal the error appear; with that we may find the issue.


body: The final solution to my problem was to download [the latest arduino hourly build](https://www.arduino.cc/download.php?f=/arduino-nightly-windows.zip). There is probably a bug in the stable version that has been solved in the hourly build.


message:
Power an arduino on a 12V circuit

I am doing a simple circuit with a 12V power supply to power a 12V LED strip. I'd like to be able to switch ON/OFF the strip with a relay connected to my Arduino. I'd like to know if I can power my Arduino directly from the VIN pin using 12V source. I saw that the Arduino can support up to 12V.

Thank you in advance for the help.

body: As you have noted, many Arduino (and clones) are rated for supply voltage up to 12V. But note that if you use 12V power, the on-board regulator will get rather hot.  Providing decent ventilation and maybe even extra heat sink would be a good idea.


body:
The answer is yes, you can. Since there are no information about which Arduino you are using, Lets assume that you use Arduino uno. Based on the [official webpage][1] documentation, the recomended voltage input is ranging from 7 - 12 V. Therefore it is possible.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardUno


message:
Arduino IDE in conflict with pyserial for use of serial port in OSX Yosemite

I'm trying to communicate with an Arduino Uno via pyserial using a code that I wrote for Ubuntu. However, when I try to use the same code in OSX Yosemite after identifying the serial port for the case of OSX, it doesn't work. This is the offending line:

    In [32]: ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

If I run the above line when the Arduino IDE is not running there is no error message, but the Arduino doesn't do anything (the Arduino IDE Serial Monitor must be open in order for the code to work). However, if I open the Arduino IDE and use the Serial Monitor (which works fine, i.e. it shows data that the Arduino is sending), I get the following error message:

    SerialException: [Errno 16] could not open port /dev/cu.usbmodem1421: [Errno 16] Resource busy: '/dev/cu.usbmodem1421'

If I run `lsof | grep /dev/cu.usbmodem1421` then I get that the only program using said port is Arduino IDE:

    Arduino   2012 germanchaparro   94u     CHR               18,7   0t15249    1285 /dev/cu.usbmodem1421

Clearly OSX is not letting Arduino IDE and pyserial to use the serial port (to which the Arduino UNO is connected) at the same time. I don't know how to fix this, and it's especially frustrating since Ubuntu doesn't put up a fight.

Any ideas?

body:
Ok, I solved it. First I stopped using the IDE serial monitor as Majenko suggested, and focused on getting the Arduino readings within the python code. Besides trying to use the python code and the IDE monitor at the same time (which apparently you can do in Ubuntu but not in OSX), the original problem was that my python code was not clearing the serial buffer in the r/w process. In order to do this, I wrote the following function to be called before and after a serial write:

     ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

     def readarduino(ser):
        did=True
        while ser.inWaiting(): # Check number of characters left in buffer
            if did and ser.inWaiting() < 490: # Select last 500 characters in buffer
                for i in range(6):
                    print ser.readline() # Print 6 lines in buffer
                did = False
            ser.readline()  # Clear buffer line by line until ser.inWaiting goes to 0

This ensures that the buffer is clear whenever I am writing to the Arduino.

This solution works for OSX Yosemite and Ubuntu 14.04


message:
How do I output tone() and audioFX board output through a single speaker?

I'm building a BMX start gate controller. It requires a voice sample to be played ("Riders ready, watch the gate!") before playing a series of tones at very specific frequencies and intervals. After the tones are complete, a relay is triggered which drops the start gate.

I'm intending to use one of the header pins with the tone() function to output the tones, and an Adafruit AudioFX board to play the voice sample.

How do I connect both of these to an Adafruit mono amplifier (https://www.adafruit.com/product/2130) ?

Note that only one or the other will be playing at one time.

Can I use a "passive mixer" (which I think is putting a 10kΩ resistor on each input source for the amplifier?)

body:
Yes, a passive mixer would do fine. I would recommend capacitors to remove any DC component too, before you do the mixing. 22uF should do fine.

I will draw a circuit in the morning.


message:
How can I use stepper for specific degree?

I use Arduino and I'm beginner. I use the code below, but I don't understand what `stepper.step(num)` and `STEPS` in `Stepper stepper(STEPS, 2,3,4,5)` are, and I want to use stepper for specific degree and I don't know what I can do. for example if I want to use stepper for 40 degree what are STEP and num?

<!-- language-all: lang-C++ -->

    #include <Stepper.h>

    // change this to the number of steps on your motor
    #define STEPS 100

    // create an instance of the stepper class, specifying
    // the number of steps of the motor and the pins it's
    // attached to
    Stepper stepper(STEPS, 2,3,4,5);

    // the previous reading from the analog input
    int previous = 0;

    void setup()
    {
      // set the speed of the motor to 30 RPMs
      stepper.setSpeed(100);
    }

    void loop()
    {
      // get the sensor value
      //int val = analogRead(0);

      // move a number of steps equal to the change in the
      // sensor reading
      //stepper.step(val - previous);
      stepper.step(25);
      delay(1000000);
     // stepper.step(-5);

      // remember the previous value of the sensor
      //previous = val;
    }

-----------------------------------------EDIT #2-----------------------------
my stepper is the first one in this link:
https://grahamwideman.wikispaces.com/file/view/28byj48_models_table.jpg/538898220/604x265/28byj48_models_table.jpg
( I think! )
and I don't know what it means?
------------------------------------------EDIT #3----------------------------
Thank you very much, I saw the link.

> Step Angle (8-Step sequence: Internal Motor alone): 5.625° (64 steps
> per revolution)

and I run this code for 45deg :

<!-- language-all: lang-C++ -->

    #include <Stepper.h>

    #define STEPS_PER_MOTOR_REVOLUTION 32
    #define STEPS_PER_OUTPUT_REVOLUTION 32 * 64  //2048
    Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 2, 3, 4, 5);

    int  Steps2Take;

    void setup()
    {

    }

    void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
    {

      Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 8.11;
      small_stepper.setSpeed(100);
      small_stepper.step(Steps2Take);
      delay(10000);
    }

 because I understand each turn has 2048 steps, for example if I want to have 1/2 turn, I have to have num=1024 ( 2048/2). ok, So, for 45deg, it's 1/8 turn so I have to set num=2048/8. but for example for 33 deg what should I do?
I thought num= 33*5.61
so for 45deg I use num=45*5.61
you know we have a lot of floating point and I'm not sure we do it correct. right? I'm a little confused.

body:
`stepper.step(num)`is used to rotate your motor 'num'-step. i.e. `num=25`, then calling `stepper.step` will cause your motor do 25-step.

STEPS is number of steps per revolution for your motor. It will be depending on the motor you used. For more information, you can check [here][1].

You have to check for your motor stepper resolution. Most common motor stepper has 200 steps per revolution, which means 1 step is 360/200 = 1.8 degree. If you try `Stepper.step(1)`, your motor will rotate 1.8 degree.

So in your case, if you already found out the resolution of your motor stepper, just do a simple conversion task:

    const float resolution  = xx.xx; // put your step resolution here
    int step_degree(float desired_degree){
        return (desired_degree/resolution);}

This can be use by calling

    stepper.step(step_degree(40)); //rotate 40 degree.

**--EDIT--**
You can check this [link][2], since it (perhaps) using same motor stepper (24BYJ48)

Based on 24BYJ48 [datasheet][3], it has 5.625 degree resolution / 64 steps per revolution.

  [1]: https://www.arduino.cc/en/Tutorial/StepperOneStepAtATime
  [2]: https://arduino-info.wikispaces.com/SmallSteppers
  [3]: https://www.google.co.id/url?sa=t&rct=j&q=&esrc=s&source=web&cd=7&cad=rja&uact=8&ved=0ahUKEwi-7Lf4sa_QAhWKpY8KHWL1D7AQFggrMAY&url=http://smart-elektronic.strefa.pl/silnik/datasheet.pdf&usg=AFQjCNGcovDwZtfT8XvQGshhTXc1g-o5Qw&sig2=F752FfDr8P0FzKlwsoRzTQ&bvm=bv.139138859,d.c2I


message:
Regarding Arduino Mega hardware serial

I have a doubt interfacing with fingerprint module (R305) with the Arduino Mega.
I have been able to interface it to Arduino Uno before but not Arduino Mega so far.

I have used the Mega's hardware Serial1 pins 19 (Rx) and 18 (Tx) pins.

However, I am unable to get output from the module. How do I connect hardware serial and what is a sketch to do this?

body:
Try Pin digital pins 0 (RX) and 1 (TX), as they also should be Serial0 on ArduinoMega (PWM 0 and 1)

see:
https://www.arduino.cc/en/Reference/Serial

The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX). To use these pins to communicate with your personal computer, you will need an additional USB-to-serial adaptor, as they are not connected to the Mega's USB-to-serial adaptor. To use them to communicate with an external TTL serial device, connect the TX pin to your device's RX pin, the RX to your device's TX pin, and the ground of your Mega to your device's ground.


message:
Running quartz clock off an arduino

I am trying to run a clock off of an arduino following this site: http://www.cibomahto.com/2008/03/controlling-a-clock-with-an-arduino/comment-page-1/ and I tried to combine it with this to get it to run accurately. https://contractorwolf.com/arduino-pwm-interrupt-clock/

For the project that I want to do I need to slow down the minute hand by 23.9345 (So that it will run on sidereal time)

Now the bare code of the first link with some mods works perfectly, but the delay does not seem to be accurate:

        const int a1  =  8;     //use digital I/O pin 8
        const int a2  =  9;
        const int tick1 = 1000;
        const int tick2 = 50;

        void setup()
        {
        pinMode(a1,OUTPUT);   //set pin 8 to be an output output
        pinMode(a2,OUTPUT);   //set pin 9 to be an output output
        }

        void loop()
        {
           delay(tick1);          //delay 1000 milliseconds
           digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
           delay(tick2);          //delay 1000 milliseconds
           digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
           delay(tick1);          //delay 1000 milliseconds
           digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
           delay(tick2);          //delay 1000 milliseconds
           digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
        }

For this reason I have tried to merge it with the 1 wire clock project and got

    const int a1  =  8;     //use digital I/O pin 8
    const int a2  =  9;
    const int tick1 = 1000;
    const int tick2 = 50;

    int cyclesPerSecond = 974;

    //pins
    int clockInterrupt = 0; //interrupt 0 is pin 2 on UNO
    int pwmOut = 6; //pin 6

    //timekeeping
    int seconds = 0;
    int masterClock = 0;//number of square waves

    void setup()
    {
    attachInterrupt(clockInterrupt, clockCounter, RISING);
    pinMode(a1,OUTPUT);   //set pin 8 to be an output output
    pinMode(a2,OUTPUT);   //set pin 8 to be an output output

    Serial.println(pwmOut);
    analogWrite(pwmOut, 127); // this starts our PWM 'clock' with a 50% duty cycle//digital pin 10 for analogWrite pwm out
    }

    void clockCounter() // called by interrupt 0 (pin 2 on the UNO) receiving a rising clock edge PWM
    {
    masterClock ++; // with each clock rise add 1 to masterclock count
    if(masterClock >= cyclesPerSecond*23.9345) // 974hz on pin 6, may be 490Hz if you use pin 9 or 10
    {
    seconds ++; // after one cycle add 1 second
    masterClock = 0; //reset clock counter
    }
    }

    void loop()
    {
      if (seconds == 1){
       digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
       else if(seconds == 2)
       seconds = 0;
       digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
      }
    }
However this does not seem to move the second hand properly, so the clock does tick but not strong enough to actually work. Is this a hardware thing or a processor thing? I have no idea why this would not work while the other code does.

body:
I'm not 100% certain of what you are trying to do but I noticed a few bits in the code which don't look right to me.  For instance this function:

<!-- language-all: c -->

    void clockCounter() // called by interrupt 0 (pin 2 on the UNO) receiving a rising clock edge PWM
    {
      masterClock ++; // with each clock rise add 1 to masterclock count
      if(masterClock >= cyclesPerSecond*23.9345) // 974hz on pin 6, may be 490Hz if you use pin 9 or 10
      {
        seconds ++; // after one cycle add 1 second
        masterClock = 0; //reset clock counter
      }
    }

This is causing a part of your inaccuracy.  You are incrementing the integer `masterClock` variable and then seeing if it is `>=` to a floating point value, the equals is not necessary and will almost never be true.  If the condition occurs then you increment seconds before setting `masterClock` to zero, losing any part of a second you had left over.

Looking at what others have said I would be inclined to take a different approach to this project rather than try and fix this code.


body:
As I said in my comment, the idea of using the Arduino's own PWM as a
clock source is completely misguided. It will be no more accurate than
using `millis()` or `micros()`: both these functions and the PWM rely on
the same primary clock source, namely the ceramic resonator clocking the
chip.

Also, you should avoid using `delay()` for timekeeping. The time it
takes to run around the `loop()` is the sum of all your delays _plus the
time needed to execute the actual instructions_, which you do not know
accurately. It is far better to use either `millis()` or `micros()`.

Here is a tentative sidereal clock code, not tested:

<!-- language: lang-c++ -->

    // Pins driving the clock.
    const int a1 = 8;
    const int a2 = 9;

    // Length of one sidereal second in microseconds.
    const unsigned long SIDEREAL_SECOND = 997270;

    void setup()
    {
        pinMode(a1, OUTPUT);
        pinMode(a2, OUTPUT);
    }

    void tick()
    {
        static int activePin = a1;

        // Pulse the pin.
        digitalWrite(activePin, HIGH);
        delay(50);
        digitalWrite(activePin, LOW);

        // Next time use the other pin.
        if (activePin == a1) activePin = a2;
        else activePin = a1;
    }

    void loop()
    {
        static unsigned long last_tick;
        if (micros() - last_tick >= SIDEREAL_SECOND) {
            tick();
            last_tick += SIDEREAL_SECOND;
        }
    }

You can tune the speed of the clock by changing the constant
`SIDEREAL_SECOND`. I set the constant to the actual length of a sidereal
second, in microseconds, but you may find that the clock does not run
exactly at the correct speed. This is because the ceramic resonator
inside the Arduino is not very accurate. You can remove most of the
inaccuracy by calibration: measure how fast or slow it runs and change
the value of `SIDEREAL_SECOND` to compensate. You will still face some
residual inaccuracy owing to the fact that the resonator's frequency is
not very stable, and is highly temperature-dependent.

If you want to build a clock that has decent accuracy, your best bet is
to use a 32768 Hz quartz crystal, as suggested by Ignacio
Vazquez-Abrams in his comment. I did that on a bare ATmega chip (a
“barebones Arduino”) to make a
[24-hour analog wall
clock](https://www.logre.eu/wiki/24-hour_analog_clock). You should be
able to easily adapt the code I published in that page to fit your
project.


body:
Writing another answer because I just had a completely different idea.

A standard option for keeping reasonably accurate time with an Arduino
is to use an RTC module. If possible, choose one based on the DS3231
rather than the DS1307, as the former has builtin temperature
compensation, which makes it significantly more accurate.

The RTC is typically used to provide the time over I2C in a broken-down
form: year, month, day, hour, minute and second. This is not really
convenient for a sidereal clock, as it would require complex conversions
to derive the sidereal time. However, most RTC modules have the option
to output a 32,768 Hz square wave. If you can feed this signal to
the digital pin 5 of your Arduino Uno, then you can use the
Timer/Counter 1 to count the cycles and raise an interrupt every
sidereal second, i.e. every 32,678.53 cycles of the RTC signal.

There is small issue with the above number not being an integer. One
could just round it to the nearest integer, which would make the clock
slow by about 14 ppm, or 1.2 s/day. This may not seem like a
large error, but the DS3231 is capable of much greater accuracy:
±2 ppm from 0°C to +40°C.

An elegant solution is to count the cycles internally using a 32-bit
fixed-point number, with 16 bits for the integer part and 16 bits for
the fractional part. On each timer interrupt, we compute what value the
timer should have on the next interrupt (variable `next_count` below),
simply by adding 32,678.53 to the previous value. Then we use the
integer part of the result (16 most significant bits) to program the
next interrupt. This way the interrupts will be spaced by either 32,678
or 32,679 signal periods, with the average being exactly the value we
need. This provides very high granularity, as our time unit is now
effectively 2<sup>−31</sup> s ≈ 0.466 ns.

In the code below, the first three functions are left empty, as “an
exercise for the reader”. Or rather because they are dependent on the
specifics of the hardware setup. I am only showing the logic of using
the Timer 1 for getting an interrupt every sidereal second.

<!-- language: lang-c++ -->

    /*
     * RTC-based sidereal clock.
     *
     * Configure the RTC to output a 32,768 Hz square wave.
     * Feed this square wave to pin T1 = PD5 = digital 5.
     */

    #include <avr/sleep.h>

    static void setup_rtc()
    {
        // Configure the RTC to output a 32,768 Hz square wave.
    }

    static void setup_clock_pins()
    {
        // Configure the pins for driving the clock.
    }

    static void tick()
    {
        // Advance the clock by one second.
    }

    /*
     * For better granularity, time is counted in units of 2^-16 cycles of
     * the 32768 Hz square wave (~ 0.47 ns), as a 32-bit unsigned integer.
     * Timer 1 holds the 16 most significant bits.
     */
    const uint32_t SI_SECOND       = 32768UL << 16;
    const uint32_t SIDEREAL_SECOND = 0.99726958 * SI_SECOND;

    // Interrupt fired every sidereal second.
    ISR(TIMER1_COMPA_vect)
    {
        static uint32_t next_count;
        next_count += SIDEREAL_SECOND;
        OCR1A = next_count >> 16;  // use the 16 most significant bits
        tick();
    }

    void setup()
    {
        // Configure Timer 1.
        TCCR1A = 0;            // normal counting mode
        TCCR1B = _BV(CS10)     // count rising edges of T1
               | _BV(CS11)     // ditto
               | _BV(CS12);    // ditto
        TIMSK1 = _BV(OCIE1A);  // enable COMPA interrupt

        // Enable pullup on T1 = PD5.
        PORTD |= _BV(PD5);

        setup_rtc();
        setup_clock_pins();
    }

    void loop()
    {
        sleep_mode();
    }


message:
Problem understanding code

This is a segment of an Arduino sketch, that I am trying to understand.

I know that the purpose of the entire code is to control 2 stepper motors linked to their respective drivers which are linked to a Mega 2560, but since I am new to Arduino, I am having problems with some functions.

This is a segment of the code. I am having problems with some statements such as `unsigned short FLG = 0;` and I cannot make out at all the timer interrupts part.

What does it all mean?

<!-- language-all: c -->

    /* The “define” function is NOT A PROGRAMMING STATEMENT. Actually it sets up a macro which causes a text replace to occur before code is compiled. The pre-processor of the IDE will replace the variables such as “stp” to the integer value 22 in the following subsequent sections like the “void setup” function and the “loop” function if they are called. This function helps reduce RAM usage. */

    #define stp 22
    #define dir 23
    #define stp2 26
    #define dir2 27
    #define EN  24
    #define dir_ 25

    int i, j, t, X = 0, Y = 0, Z = 0;
    // here, the integer is creating variables such as i, j, t
    //and also assigning values to some of them such as X, Y and Z.

    unsigned short FLG = 0;

    unsigned int Speed1 = 0, Speed2 = 0; // creating variables assigning initial values; due to unsinged only positive

    int ser_1[3];

    int po(int, int);

    void setup() {     // You define how your Arduino will be used and set up any pins and communications you will be using. This will run first and only once.

      Serial.begin(9600); // begin the data transmission between Arduino and pc at speed of 9600 bits per sec
      delay(500); // stop for 500 milliseconds

      Serial.println(“hi”); // this will print the word “hi” on the serial monitor window on pc via serial port

      pinMode(stp, OUTPUT); // tells arduino to use digital Pin 22 to output electricity
      pinMode(dir, OUTPUT); // tells arduino to use digital Pin 23 to output electricity
      pinMode(stp2, OUTPUT); // tells arduino to use digital Pin 26 to output electricity
      pinMode(dir2, OUTPUT); // tells arduino to use digital Pin 27 to output electricity
      pinMode(EN, OUTPUT); // tells arduino to use digital Pin 24 to output electricity

      noInterrupts(); // to prevent disruption of timing of codes, disables some functions in the background

      /* To use timers, the built-in timer registers on the AVR chip that store timer settings need to be configured.  There are a number of registers per timer.  Two of these registers –the Timer/Counter Control Registers- hold setup values, and are called TCCRxA and TCCRxB, where x is the timer number (TCCR1A and TCCR1B, etc.).   Each register holds 8 bits, and each bit stores a configuration value. */

      TCCR1A = 0x80; //
      TCCR1B = 0x0A; // Enable reset on compare match, 1:8 clock. don’t understand
      OCR1AH = 0x9C;
      OCR1AL = 0x3F;
      TIMSK1 = (1 << OCIE1A); // enable timer compare interrupt
      interrupts();
    }
    ISR(TIMER1_COMPA_vect)   // timer compare interrupt service routine
    {
      res();
    }
    void loop(){

    if(Serial.available())
     {
      ser_1[i] = Serial.read();
      char ch = Serial.read();
    if(ch==’S’)
       { i=0;
         X=0;
         while(1)
    {
      if (Serial.available() > 0)
         {
          ser_1[i]=Serial.read();
          ser_1[i]=ser_1[i]-48;
          X=X+(ser_1[i]*(po(10,i)));
          i++;
         if(i==3)
           {
            FLG++;
            break;
            }
          }
        }
    }

    if (ch==’A’)
      { i=0;
        Y=0;
         while(1)
         {
            if (Serial.available() > 0)
          {
          ser_1[i]=Serial.read();
          ser_1[i]=ser_1[i]-48;
          Y=Y+(ser_1[i]*(po(10,i)));
           i++;
          if (i==3)
              {
               FLG++;
               break;
               }
              }
            }
          }

         if(FLG==2)
        {
          Speed1=X;
          Speed2=Y;
          digitalWrite(EN,LOW);
            delay(100);
          StepForwardDefault();
            delay(1000);
          StepForwardDefault2();
             delay(1000);
          ReverseStepDefault2();
          ReverseStepDefault();
          delay(1000);
          digitalWrite(EN,HIGH);
          delay(1000);
          }
          else
          Serial.println(“sequence is stop”);
    }
     /*****************po******************/

    int po(int num, int pow)
    { int result=1;
      if(pow==0)
      return 1;
      else
     {
      for(int f=1;f<=pow;f++)
        {
      result=result*num;
        }
     return result;
     }
    }

    /************ MOTOR 1 Function *****************/

    void ReverseStepDefault()
    {
      Serial.println(“motor a reverse”);
      Serial.println(“Moving in reverse at default step mode.”);
    digitalWrite(dir_, HIGH); // Pull direction pin high to move in “reverse”
    digitalWrite(dir, LOW);
    delay(100);
    for(int x=1; x<200; x++) // Loop the stepping enough times for motion to be visible
    {
      digitalWrite(stp, HIGH); //Trigger one step
      delay(305-X);
      digitalWrite(stp, LOW);  // Pull step pin low so it can be triggered again3
      delay(305-X);
      }
    }

    /************ MOTOR 2 Function *****************/

    void ReverseStepDefault2()
    {
      Serial.println(“Moving b reverse”);
      digitalWrite(dir_, HIGH); // Pull direction pin high to move in “reverse”
      digitalWrite(dir2, LOW);
      delay(100);
      for(int x =1; x<200; x++) // Loop the stepping enough times for motion to be visible
      {
       digitalWrite(stp2,HIGH); // Trigger one step
       delay(305-Y);
       digitalWrite(stp2,LOW); // Pull step pin low so it can be triggered again3
       delay(305-Y);
       }
    }

    void StepForwardDefault2()
    {
       Serial.println(“motor b forward”);
       digitalWrite(dir_,HIGH); // Pull direction pin high to move in “reverse”
       digitalWrite(dir2,HIGH);
       delay(100);
       for(int x=1; x<200; x++) // Loop the forward stepping enough times for motion to be visible

    {
      digitalWrite(stp2,HIGH); // Trigger one step forward
      delay(305-Y);
      digitalWrite(stp2,LOW); // Pull step pin low so it can be triggered again
      delay(305-Y);
        }
    }

    void res()
     {
       if(Serial.available())
      {
       ser_1[i]=Serial.read();
       char ch = Serial.read();
       if(ch ==’T’)
          {
           FLG=0;
           Serial.println(“stop is pressed”);
          }
       }
    }

body:
> I am having problems with some statements such as
> "unsigned short FLG = 0;"

This is the C and C++ syntax for declaring a variable. The statement
means “Let `FLG` be an unsigned short integer and let it's initial value
be zero”. An `unsigned short` can hold any integer value between 0 and
65535 inclusive.

The Arduino language reference documents the types
[`short`](https://www.arduino.cc/en/Reference/Short) and
[`unsigned int`](https://www.arduino.cc/en/Reference/UnsignedInt) but,
for a mysterious reason, it does not document `unsigned short`.

> I cannot make out at all the timer interrupts part.

Nobody can unless they know the internals of the AVR timers, which are
non trivial but are well covered in [the
datasheet](http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf).
It's a thick document, but you only need to study chapters 14:
_Interrupts_ and 17: _16-bit Timer/Counter (Timer/Counter 1, 3, 4, and
5)_.

I recommend you first read the [Timers and counters
tutorial](http://gammon.com.au/timers) by Nick Gammon, then go to the
datasheet for the most authoritative information.

**Edit**: Just a comment... I find the program you have posted to be
written with poor programming style. More specifically, the section
setting the Timer 1 registers would be better written as follows:

<!-- language: lang-c++ -->

    TCCR1A = bit(COM1A1);  // set OC1A to LOW on compare match
    TCCR1B = bit(WGM12)    // CTC mode, TOP = OCR1A
           | bit(CS11);    // clock at F_CPU / 8
    OCR1A  = 40000 - 1;    // period = 40000 prescaled clock cycles
    TIMSK1 = bit(OCIE1A);  // enable COMPA interrupt

It is still obscure if you don't know the timer, but using explicit bit
names instead of pure numbers makes things a lot easier when you refer
to the datasheet. Also, there is no point in setting each byte of
`OCR1A` in a different statement: it only makes things harder to read.


body:
I'm assuming you don't mean "all" when you ask "what does it _all_ mean?"
I also assume that the comments are from you - in which case you've done reasonably well!

    /* The “define” function is NOT A PROGRAMMING STATEMENT... */

True, `#define` isn't a programming statement that produces code: it's a way of defining a symbol that you can use in the rest of the code, both for explanation purposes and ease of changing: without having to search for all copies of `22` - and then decide if _this particular_ `22` is for that pin or not.

    unsigned short FLG=0;

`int` is 16 bits in the Arduino, but in some systems it's 32 (and in others 64). `short` is (practically) always 16 bits regardless of system, so many programmers use `short` when they know they definitely want a 16-bit integer. `unsigned` merely means that it can never go negative - which allows the variable to hold higher values (0 to 65,535 instead of -32,768 to 32,767).

    int ser_1[3];

This is an array of 3 `int`s called `ser_1`, which can be accessed as `ser_1[0]`, `ser_1[1]` and `ser_1[2]`. In C, all arrays start at `0`. Why use an array? It makes it possible to use _another_ variabe to say _which_ `ser_1` you want: e.g. `ser_1[i]`. If `i` is `2`, you get the last one.

    int po(int,int);

This says that there will be a function called `po` that takes two `int` values, processes them, and returns an `int` result.

    noInterrupts(); // to prevent disruption of timing of codes, disables some functions in the background

Pretty much. An interrupt can happen at any time: the CPU will stop executing the main program, execute the interrupt code, then resume where it left off in the main program. Sometimes that's a bad thing! If the interrupt code is going to change something that _this_ code needs to stay the same (or vice versa!), then Bad Things can happen. To prevent that, you can turn off interrupts temporarily with this function, and turn them on again later with `interrupts()` (which you'll see below).

    /* To use timers, the built-in timer registers on the AVR chip that store timer settings need to be configured.  There are a number of registers per timer.  Two of these registers –the Timer/Counter Control Registers- hold setup values, and are called TCCRxA and TCCRxB, where x is the timer number (TCCR1A and TCCR1B, etc.).   Each register holds 8 bits, and each bit stores a configuration value. */

     TCCR1A = 0x80; //
     TCCR1B = 0x0A; // Enable reset on compare match, 1:8 clock. don’t understand

OK, this is complicated:

* By default, a timer simply counts from `0` to `65,535` (maximum 16 bit value), then resets and starts again.
* How quickly? One 'tick' is the system clock, so _very_ quickly! But you can "pre-scale" that with a divisor. In this case, they're using a divisor of 8, so the timer will "tick" an eighth as fast.
* You can configure the timer to interrupt when it resets, so that special code will execute on a timed basis.
* You can also tell it that if at any time it hits a certain number to _also_ interrupt (Compare Match) - that's two different interrupts.
* You can _also_ tell it that when it hits that Compare number, to reset back to `0` and start counting again. That means that the timer will interrupt more often.

`OCR1AH = 0x9C;`
`OCR1AL = 0x3F;`

These stand for "Output Compare Register 1A High" and "Output Compare Register 1A Low" - a 16 bit value that is 0x9C3F (37839 decimal). If you divide the system clock by that number, (and a further 8 for the pre-scaler), you'll find out how often it interrupts.

    interrupts();

This turns on interrupts again.

    ISR(TIMER1_COMPA_vect)   // timer compare interrupt service routine
    {
    res();
    }

This is the code that executes every timer interrupt. I don't know what `res()` does.


body:
Here is some explanation :

    TCCR1A = 0x80; //OC1 will cleared on compare match
    TCCR1B = 0x0A; //Turn on CTC mode --> it means the interrupt counter will reset to 0, and causing the interrupt happen again and again.
                   //Divide clock 1:8 (prescaler)
    OCR1AH = 0x9C;
    OCR1AL = 0x3F; //compare value = 0x9C3F = 39999
    TIMSK1 = (1<<OCIE1A); // the micro will jump to the Output Compare A Interrupt vetor upon compare match.

Overall, this setup will make your program do whatever you put in the Interrupt Service Routine `ISR(TIMER1_COMPA_vect){...do whatever here...}`

The interrupt interval is =

> (OCR1A+1) × prescaler ÷ F_CPU
>
> (39999+1) × 8 ÷ 16.000.000 = 0.02 sec

as for `res();` and `unsigned short FLG;` I dont know what that is, since its probably your own creation (not from arduino libs)

You can found more detailed explanation [here][1] and [here][2]

  [1]: http://www.avrbeginners.net/architecture/timers/timers.html
  [2]: http://letsmakerobots.com/node/28278