text:
Can anybody advise what type of connector this is?
I recently purchased an LiPower shield from SparkFun.
I also bought a Lithium Polymer battery off eBay and it appears to have a JST male connector (i could be wrong)?
I expected it to slot right into the board however the fit is slightly too large. Can any advise me of the name of the connector for the board battery supply, or have I mistaken the battery output connector?
Please see pictures below, thanks!

The board uses a JST PH connector, with 2.0mm spacing. The battery has a JST XH connector, with 2.5mm spacing. You will need to replace the battery connector or put a XH socket on the board.

That is generically a "JST" connector.  Named from the company that originally designed and made them.  But I believe there are many "second-source" (and likely counterfeit) sources of similar or identical connectors.
They are avaiable in a variety of mechanical configurations (horizontal, vertical, PC board mount, wire-end, etc. etc.)  And there are several variations with different pin sizes and pin-pitch (distance between the pins). They all look very similar, especially in photographs, but as you demonstrate, the different pitch families are NOT inter-connectable.
If you had bought the battery from SparkFun, it is quite likely that it would have the mating connector.  But since there is no standardization here, you will end up dealing with these kinds of mismatches.

header on the board IS jst XHA connector,but wirinhg harness is XH,


text:
IRRemote send and receive same Arduino
I am an Arduino (and C/C++) newbie so apologies if I am missing something obvious.
I am using IRremote (github link) as my IR library.
I can get the simple send and receive demos working  individually.
However, I cannot get send AND receive working in the same Arduino at the same time.
I do not wish to do something like the "IRrecord" example but what I do want to do is have Arduino send and receive at all times and then trigger alarm/LED once the "beam" is broken.
I am using a TSOP 22 series as my IR receiver. I have tried to use protothreads but no luck. Any tips appreciated.
My current code snippet:
#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);
IRsend irsend;

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  Serial.println("IR Receiver... Started");
}

void loop() {
  //single threaded nature seems to break below

  // i want to start receiver here
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  //delay(5000);

  //trying to send here
  for (int i = 0; i < 3; i++) {
    irsend.sendSony(0xa90, 12);
    Serial.println("Sent Sony......");
    delay(40);
  }
  //delay(5000); //5 second delay between each signal burst
}

I managed to do this using solution from Ken Sheriff's Blog. Ken provides a simple example and documents it perfectly. Due to the nature of my IR Receiver (rejecting continuous beam) I used the sample code provided by Stephane Deniaud in the comments section. Thanks to both...
#include <IRremote.h>

#define PIN_DETECT 2
IRsend irsend;

void setup()
{
    pinMode(PIN_DETECT, INPUT);

    Serial.begin(115200);
    Serial.println("READY");

    attachInterrupt(digitalPinToInterrupt(PIN_DETECT), checkIRBeamBreak, RISING);

    // Note : the IR emitter is on PIN #3
    irsend.enableIROut(38);
    IREmitterOn();
}

// Use this function instead of delay() as delay() does not work in interrupt callbacks
void pause(int ms) {
    // We need a loop as the largest value for delayMicroseconds that will produce an accurate delay is 16383
    for (int i = 0; i < ms; i++) {
        delayMicroseconds(1000);
    }
}

void IREmitterOff() {
    irsend.space(0);
    pause(60); // 60 ms is OK for my TSOP but should be tuned
}

void IREmitterOn() {
    irsend.mark(0);
    pause(10);
}

void switchOffOnIREmitter() {
    IREmitterOff();
    IREmitterOn();
}

void checkIRBeamBreak() {
    int val = digitalRead(PIN_DETECT);
    // LOW : no beam break
    // HIGH : beam break
    if (val == LOW)
        return;

    detachInterrupt(digitalPinToInterrupt(PIN_DETECT));
    switchOffOnIREmitter();
    if (digitalRead(PIN_DETECT) == HIGH) {
        Serial.println("IR BEAM BREAK !!!!");
    }
    attachInterrupt(digitalPinToInterrupt(PIN_DETECT), checkIRBeamBreak, RISING);
}

void loop() {

}

based on the concept of user1843591 answer, i researched some more and found the example of Nick Gammon 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 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
    );
}

I THINK the problem is that the Arduino takes some time (very minimal) to send the signal, but when it comes to receive it, the signal has already dissipated though your room.

send and receive at all times and then trigger alarm/LED once the "beam" is broken.

Use a laser, it's cheaper, more acurate, and more "James Bond'ish'" :)

Thanks for the idea @Dat Ha. I considered it, it is cooler!....but I ruled it out as this project will be used by kids so I thought best to avoid lasers! thanks for taking the time to respond

This theory here is not really correct - while the light propagation is fast enough to ignore, the response time of a demodulating detector is Arduino-scale.  The issue is one of software architecture - IR remote control schemes are not applicable here, rather what is needed is to be sending modulation (pulsing on and off) and checking the receiver at points in between.  But also note as the correct answer clarifies that the modulated signal itself must be pulsed on and off at a slower cycle time, or the detector will reject it.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
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.

There's no reason at all to develop strings if what you need are digits.  What bit patterns do you need to output to turn on different digits?  Ie, what is the interface to the nixies?

The nixies have an anode positive leg and then a cathode leg for each digit. The 74141 just swaps out which cathode to run to gnd. I will update some code that shows how I turn a number on or off.

@jwpat7 All i need is to read the minute and say if the minute time is 12 then change one tube to a HIGH/LOW pattern to display 1 and the other for 2.

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()%12.  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%10, 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.

After days of trying i got it to work. This way probs works but my way is how i had to end up doing it.

@Cheddar, ok, good you got it to work

Yea, a noob question though, I want to upload my code to show how i got it. Instead of doing indentations can I use come kind of bracket. I am having a hard time putting arduino code into the textboxes on this site.

@Cheddar, copy & paste your code into the question edit box, then select it and press Ctrl-K.  That is, highlight the code with mouse (or by placing cursor at start of code, and holding down shift while moving cursor to end of code); then press ctrl-K or click the {} icon in edit tools bar. This marks the code as code.  ¶ Note, you can make the edit box bigger by dragging the bottom bar of it downward.  Makes code easier to see while editing.  ¶ If your code is indented ok as you wrote it, it should be ok as pasted, except that tabs don't expand, so select 'tabs as spaces' in your editor

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
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:

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).

You can try to change "digitalWrite" into directly assign to the PORT. It will be a lot more efficient

It is often because of a lack of current. Use an external 5V supply some good enough current.

I'm definitely open to it being a current issue, but that doesn't explain why it would only occur if I start counting (or seemingly any other math op)

@dpw: I'll look into that and see if the increased efficiency helps at all

I don't see how count is relevant to the function. Is this also the same code you used to turn on all the segments?

Have you tried  adding a few capacitors (plus other sundry components) to give it extra power?

@TisteAndii, it certainly is, minus the extra 3    turn_off_all(digit_selectorX, digitsX, sizeof(digitsX), 8); .
And I completely agree, the two things have nothing to do with each other, except when I uncomment the count increment-er the displays dim...

@DatHanBag: I'll give it a go and see if that helps!

@ShaneGadsby Tell us how much it helps-if you need more help with capacitor idea after trying it- ask here-we'll find the solution

The caps didn't seem change anything, thanks for the suggestion

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.

I did start with this, and seemed to have the same results, so I went the manual route to see if that pinpointed the issue; I'll try it again just to be extra sure however!

If you posted your original code using the library it would be easier to debug. Also add some comments.

Further to the wrong use of sizeof: if I change it from that I get the dimming issues again, haha, which is even more puzzling...
I'll re-write it with the 7-seg lib and post it (assuming it still fails), and yeah, more comments == more better

I assume you are trying to get the number of elements. The correct use would be (sizeof(digits0)/sizeof(int))

I didn't get it working how I wanted it to with this library, but it certainly is the better option over all - thanks again for showing me the correct usage of sizeof!

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.


text:
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?

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().

That looks promising, but I will have to wait until tonight to try it. Will it only list the 'local' name of the variables? I suppose that e.g. the tx_buffer and rx_buffer variables listed in your example are actually HardwareSerial::_tx_buffer and HardwareSerial::_rx_buffer? Might omitting the -C option give any hint on the variable's class name?

@jarnbjo: You get the full name of the variable, e.g. loop::last_print is a local variable from loop() named last_print. The serial buffers are actually outside HardwareSerial in my version of the Arduino core, and HardwareSerial has no static variables, so you see no HardwareSerial::foo. The per-instance variables are part of the sole instance Serial and are not listed separately. Omitting -C will only hurt readability, e.g. it will print _ZZ4loopE10last_print instead of loop::last_print.

I see. The fields in the HardwareSerial class were the closest match I could find for tx_buffer and rx_buffer in the current version of the library source code and I didn't consider that you might have an older library version. That makes sense.

This solved my problem. I had expected the compiler optimizer to be much more clever than it obviously is and I had lots of dependencies linked into the binary, which are never used. Without much more than deleting unused library files saved me almost 500 bytes of RAM usage.

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.  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.

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).

Also very helpful, but do you happen to know why the avr-nm tool suggested by Edgar in his answer lists memory usage, which is not accounted for in this generated map. avr-nm e.g. lists 64 bytes used by an rxBuffer (full name _ZL8rxBuffer), which is not listed in the map, and which I am not able to find in any dependency.

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):

 blank sketch takes up 444 bytes of program storage space (max is 30720 bytes).

Sketch which includes 6 libraries✔ uses up 6218 bytes
<LiquidCrystal_I2C.h>, <Wire.h>,<ds3231.h>,<SD.h>,<EEPROM.h>,<SoftwareSerial.h>

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).

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).

Adding a 2nd line with Serial.print("a"); results in 6358 (16 bytes)

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) 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.

The length of a line of source is completely unrelated to memory usage.

@DaveNewton Yeah, I should've thought about that since it must be counting the compiled bytes, right? is it the bytes added to .elf, maybe?

Also, I'm not sure it's completely unrelated, because more source code means larger program and larger binary size in the end. Otherwise why would you reach a limit as your program grows and why would the IDE warn you about the size of your app all the time?

What I said was that the length of a line of source is unrelated to memory usage--for example, if the exposed instance of the serial driver was ThisIsTheRealSerialDriverInstanceInUse.print("a"); the compiled size would be (assuming no debug symbols) the same as S.print("a"). Obviously a larger program is... larger--but there's a difference between the size of source code in bytes (the human readable form) and the size of the executable.

In other words, counting the characters in a line of source, while it may coincidentally align with memory usage, it's just that--a coincidence.

Thanks for the additional information.

To expand on Dave Newton's comment: A short line of code that invokes a heavyweight library can have a huge impact on the size of the binary. If you add variables that store temporaries that the compiler has to evaluate anyway, that makes your source grow but has zero effect on the size of the binary. If you add local variables to cache volatile data, your source still grows but the binary actually shrinks!

@EdgarBonet Thanks for additional info. I'm just attempting to discover how to "clean" my code to the extreme since I am getting to limits of program space.  I wish there was a bit more guidance on this but it's a lot of trial and error.

Also, as I'm cleaning my code I got to a point where it was at 23436 bytes of prog mem.  I removed all Serial.begin(), Serial.print() etc calls and recompiled and prog mem went to 23110 so this would be your point.  But I'm not sure how removing code would actually make the program memory usage go up?? And, yes, I'm confirming that I only removed code.  Very weird.

Just removing code on its own will almost never make the binary size increase; I don't think anybody said it would. There are multiple resources available for optimizing general code for size (and Arduino as well) and a lot of compilation/linker games that can be played as well.

I'm sorry I got all mixed around on my numbers thinking lower number meant less avail space. Phew...been staring at this too long.  Removing code does seem to help the number go down -- but not directly of course.  Thanks for discussing this with me.

Removing code does directly decrease binary size; every time you remove a call it decreases the binary size by the number of bytes of binary code it takes to implement the call (the call instruction, parameter wrangling, etc). Once compiler/linker games start being played you can often removed unused library code as well.


text:
Is there a non-float alternative to pow()?
I've scoured the LANGUAGE REFERENCE in the Arduino web-site, 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!

For the general case of integer pow(), see http://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int.  For powers of 2, just use shifts.

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.
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.
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;
}

Error: It can go up to 2^32 - 1 if you use an unsigned long.

@DatHa thanks, I seemed to have lost the word "signed" during editing.  Fixed.

It can go past 2^32 - 1 if you use an implementation of arbitrary precision integer arithmetic

I'd like, specifically to know why the results of an integer conversion on the results of pow() DOES NOT work for powers of 2. For me, pow(2,3) returns 8.00, but while int(8.00) returns 8, int(pow(2,3)) returns 7!

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!

The reason the answer above answer works is because the set of real numbers (which contain floats) contains the set of integers

@DatHanBag: And more importantly, every 32-bit integer is exactly representable by a double.  Actually, since IEEE floating point is based on a binary mantissa/exponent representation, every power of 2 should be exactly representable even beyond 2^53 (the point where double can't represent every arbitrary integer, an 1 unit in the last place of the mantissa is greater than 1.0).

@PeterCordes Yes I did know that. Maybe I should have said "bounded sets" when referring to float and integer sets for arduino in my comment about the answer of

This is a somewhat valid answer to the general question of using pow() for integers, but AFAICT arduino doesn't even have hardware floating point, so it's a terrible answer.  An integer pow() implementation like this one that runs in log2(n) time multiplying and adding to accumulate a result would almost certainly probably perform better, and failing to mention that bit shifts work for powers of 2 just makes this a terrible answer to this question.

@PeterCordes  "so it's a terrible answer". -agreed that it is kind of a low quality simplistic answer. pow() is certainly computable in log2(n)- the simple method learned in school (multiply number by itself to the power is not so efficient). You can do it better with a Fourier transform for really big integers -for example.  But maybe the OP will accept and like it.


text:
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?

Try renaming the script to "script.h".

Perfect - thanks Mikael - I am guessing the build recipe doesn't like the .txt extension!

I guess that you could have a "script.h" that includes a "script.txt" once the Arduino preprocessor is convinced that the sketch is using the local directory the path is included in the build/compile.

That's a good point - but practically I can deal with a little renaming. The main aim is to avoid escape hell (and the readability issues that it brings) in putting a small test script into flash (on an ARM device).

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.


text:
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%2018-58w-T8-%201-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?

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

This is [almost] a link only answer. Links tend to die over time. If you could expand your answer with a summary of the content of the link then that would be very helpful.

This tutorial is poetry! Amazing! Thanks! Is there a way to have it in PDF or any other offline mean (without the videos for ex.). This should be eternalized!

Hi, can you confirm that these resistors values are correct? How can you drop 12V to those voltages using that resistors? http://prntscr.com/e4guvx

Yes, you are right. It was a mistake. I have corrected. You need 2,2 and 3,3 kOhm resistors.

DOCX version of tutorial


text:
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

Serial connection (RX/TX) seems like the way to go. If it didn't work it only means you had a bug to fix.

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.


text:
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)

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.


text:
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.

Comments are not for extended discussion; this conversation has been moved to chat.

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. 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.

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!


text:
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 to make sure I show everything.
Hardware:

Arduino Nano knock-off by RobotDyn (atmega168)
Bluetooth module HC-05 (zs-040) which looks like this
Windows 10 Home 64 bit on tablet

I have wired them up like this .
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);
}

Hi Tomas, can you add details about your Windows? what version is it? and version of bluetooth adapter

@dpw I have Windows 10 Home 64 bit. It's a tablet and the BT adapter for the tablet is build in so I don't know any additional information about it.

I have exact the same problem.
Expect also to see a com port number after my device a MLT-B05 (clone of HC-05) is paired and (after fill in correct pass-code) is connected.
Did you see a you tube film for a correct assignment of the com port? I did everything the same as you did, but perhaps we are both wrong. Harry

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

That's exactly what I did. However when I want to assign the COM port I have no device to choose from even though I can see it paired in the main BT window.

link Here is screenshot of the problem.

Ah, the same problem also occur to me. I don't know if there are any solution other than mine, which solved by using external bluetooth dongle. Turns out my build-in bluetooth adapter is not compatible with the bluetooth module (which is HC-05 and HC-06).

Well but my mobile phone also cannot communicate with the module. It seems to me pretty odd that the built-in BT cannot communicate with other BT devices.


text:
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), 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 ?

Macro's aren't really code. They just work on the plain text. Just look at them as if they are a "find and replace" function in a text editor.

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.

U8G_ESC_DLY(10),              /* delay 10 ms */
so in a concept like this, i can omit the left side of the comma.But can you elaborate on the function call part ? How can you define a function like this in the first place ?

somefunctionthattakestwoargs(SOMEMACROWITHACOMMA)

The library uses that to create a list of commands to initialize the display. See where it is used. As you can see, they store an array of commands that have to be send to initialize. So in this case, send 255 and then send the last x (with the first bit set to zero).


text:
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.

If you load a blank sketch, like int main () { } does the pin in question start off high?

Are you sure there isn't something else connected to pin 10?

@NickGammon No... Its very strange..

@Gerben Too damn sure

I tried your amended code and the pin went low every 1 minute 40 seconds for half a second, which is what you told it to do. You have to watch closely to spot it.

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.

Beaten by 24 seconds. :)

yeah it does... However, if the LOW command is in an if it never executes even when the if block runs.

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

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

yeah it does... However, if the LOW command is in an if it never executes even when the if block runs...

@YaddyVirus Maybe you are trying to pull down something stronger than output driver. How about using LEDs with series resistors to confirm it (with everything else disconnected)?

if the LOW command is in an if - What are you talking about? There is no if in your code.

@NickGammon Actually I tried various ways of setting pins to LOW... One was to set a condition and accordingly set the pins to LOW.

Try: void setup() { pinMode(10, OUTPUT); digitalWrite (10, LOW); } void loop () {} - is pin 10 low then? If so, you can't say that pin 10 "never" goes low.


text:
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

Option 2 and 3 are kind of the same, as the Arduino Ethernet has the same components as the Ethernet shield. The ethernetShieldV2 has a slightly newer chip on it, but I don't expect that much difference. The Yun might be easier, but the problem is that not a lot of people have used it, so there aren't a lot of tutorial online. So I'd probably go with  option 2 or 3. Unless you need HTTPS for the Cayenne API.

Guess there are a few more requirements such as bandwidth, message/protocol frequency, motor control speed, etc. Also available libraries and support.

What about the ESP8266 or a raspberry pi

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.

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.

authors: Вадим Чеховский


text:
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.

Arrays can not be resized, but if you know the required size of the array before any data is written into it, you can declare theArray as a pointer instead of array: int *theArray; and then later allocate the required amount of memory: theArray = malloc(requredArrayLength * sizeof(int)); - Would that solve your problem?

However, if it is not the case that you somewhere else use an inversely proportional amount of memory to the size of these arrays, it might not be necessary to save bytes here. E.g. if you conditionally reduce an array of ints from 50 to 30 elements, you will save 40 bytes of memory only if the condition is met and you can not rely on this memory always being available for other purposes.

thank you jarnbjo! malloc() could be a way to go. Actually it would be three arrays reduced from 50 to 30 elements. So 40 bytes * 3 = 120 bytes. I don't know enough about memory allocation on a micro controller but I thought it might be significant? If you could share your opinion and some more information about the "malloc solution" this would help me a lot!

... to clarify: in my project I need to match a user input against a password. The input is stored (and translated) in the arrays. The password is stored in the eeprom and can only be changed in the setup function. But at compile time I don't know the exact length of the password. However, it is very likely that the password is much shorter than the maximal possible length.

I am not sure if you understood what I wrote in my second comment. What are you intending to use the 120 bytes for, which you may save, as long as you won't be sure if the memory is actually available. Do you have any other parts of your code, which will need more memory if a short password is configured? If not, spare yourself the effort and forget about those 120 bytes, since you won't have any situation, in which you can use them.

In fact I really didn't (and maybe still don't) understand what you wrote in this comment. If I get it right, you state that if there is the possibility that the arrays reach the length of maxSize, I might just as well allocate the memory fitting to maxSize. My idea is that the mc might run faster if it has more memory available - therefore the arrays shouldn't use more memory than necessary. However, my view might come from my lack of knowledge about the function of an mc. On a desktop computer, saving RAM would be advantageous, but is this also true for an mc?

and to answer your question: no, if the password is short there are no other parts of the code that need more memory.

The amount of memory available has no bearing on the speed the MCU runs at all. You are thinking of a phenomenon on PCs where when there is not enough memory available some memory is "swapped" to hard disk, which slows it down. Since there is no hard disk, no swapping, no memory management, none of that applies. So speed can never be affected by lack of RAM in the way you are supposing.

Neither a microcontroller, nor a desktop computer will magically run faster if you use less RAM. On a desktop computer, your software is usually running in a multitasking environment and it might be advantageous to save RAM to leave resources for other processes, but on the microcontroller you are 'on your own' and can manage the resources as you need them and not worry about other processes.

I see. In this case the only restriction is that all variables I define will fit inside the SRAM - no need to reduce memory usage as long as this condition holds... Thank you. Would anybody want to formulate an answer so that I can accept it?

Do the elements of the array really need to be ints? If the values you store in it are between 0 and 255, you could use a array of bytes, halving the amount of RAM required.

You could also consider hashing the password into a much smaller value, if memory consumption is a problem.

As a matter of fact, not all arrays are ints - this was just for illustration.

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!

To elaborate a little, while you CAN allocate the arrays smaller, there's really no point leaving some memory free: the program has to work even in the worst case, with the arrays as big as they'll ever be, and it won't work any better if you sometimes have some memory left over.


text:
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?

Howmany power does the solenoid use? Get a 24V power supply, or your 19V laptop power supply may actually do the trick just fine.

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.

Got it here : http://www.instructables.com/id/Use-Arduino-with-TIP120-transistor-to-control-moto/

Yes that was my source when i first implemented it.

Actually I have plan to power over Ethernet if Arduino can handle 24 volt dc I can break part of voltage from same dc input to solenoid valve

Arduino Uno Input Voltage Limit

Input Voltage (limit)  6-20V

Well that's a problem than I would have to invest a little bit more, thanks

You can get a DC-DC (buck) converter, to step down the 24V to 5V.

Doesnt the transistor need a heatsink?

Using XL6009 I can convert 9 volts to 24 volts

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.

Why PNP instead of NPN? How do you turn off a PNP with only 5V?

@Gerben, my bad...

An “NPN MOSFET”? You mean an N-channel MOSFET, or an NPN BJT.

@EdgarBonet An N-channel MOSFET. Could an NPN MOSFET also mean NPN BJT? Because I think I was clear enough by putting MOSFET in capitals.

A BJT can be either NPN or PNP. A MOSFET can be either N-channel or P-channel. There is no such thing as an NPN MOSFET.

24V AC or DC?  Relay would be good for either.
Low Rds N-channel logic level MOSFET (IRFL540) would be good for sinking DC current.

The OP said "the valve takes 24 dc volt as input" in his question. I think that means 24VDC. Dat Ha recommended using a N-channel MOSFET back on Nov 15, 2016. Do you think your answer adds any new information that may help the OP or any future visitors to this question?

Dang, I need to remember to look at the dates of the original question! That's the 2rd or 3rd time I've been caught up like that.

Do you think your answer adds any new information that may help the OP or any future visitors to this question?

No, feel free to remove the whole thing.


text:
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?

I'm voting to close this question as off-topic because it has nothing to do with Arduino and should be posted on EE.SE. There isn't even the word "Arduino" once in the question.

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

By context I'm assuming "yes it is expected behaviou"

1V seems a bit high. But since we don't know the current through the electromagnet, or the transistor, or the base-resistor, it might well be true.

@Himmators the actual vales in datasheet depend on your specific transistor -which you didnt state in this question


text:
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

The ATmega32U4 pin mapping says 3.

But pin 3 is the SCL. I'm using that pin to communicate an nrf24l01

Well, you have the mapping now. Pick something.


text:
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.

Please post the code you're using (a minimal complete verifiable example http://stackoverflow.com/help/mcve) and perhaps someone will help you.

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.

You need to keep track of multiple WiFiClients - 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 :-)
      }
    }
  }

}

Should i create multiple server ir multiple clients

No - you create one WiFiServer and it will give you a new WiFiClient for each client which connects.

I have created an array of clients, how to use server.available with that

Do you know how to put items into an array in general?

Create_client (){

int i=1;                                                               Create_client (){ WiFiClient client [i];  i++;}

Whenever there is new connection i use create_client function

How to check when there is a new connection and what is server.available for

OK, pretty much full code added. It's untested so I recommend you read it and try to understand what it's doing, then do it yourself, RATHER THAN trying to run it as-is and finding all my typos.  If this is helpful, please consider accepting and up-voting the answer. Thanks.

This should be accepted as the answer, and since the question comes up so often it probably should be added to the arduino IDE built-in examples for WiFi101 and other similar WiFi libraries.

I'm not sure storing IP adress is a good way of doing....
Internet is not a network with constant connection. So no way to be sure the computer using an IP at one time is the same computer one minute later, just because it has the same IP.

@Peter Should this comment be under the other answer?

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++;
         }

You can't rely on all the data arriving together - your loop which does tree read() will be unreliable. You need to store the WiFiClient object if you want to have multiple connections at the same time.

I have a solution using RTOS Tasks, I think this is the best way to manage multiple clients at same time. I test this code in ESP32 dev module.
#if CONFIG_FREERTOS_UNICORE
#define ARDUINO_RUNNING_CORE 0
#else
#define ARDUINO_RUNNING_CORE 1
#endif
#include <WiFi.h>

const char* ssid = "[YOUR-NETWORK-SSID]";
const char* password = "[YOUR-SSID-PASSWORD]";

void TaskClientSocket( void *pvParameters );

WiFiServer wifiServer(80);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(1000);
  WiFi.begin(ssid,password);
  Serial.println("Connecting to Wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("Connected to WiFi network");
  Serial.println(WiFi.localIP());

  wifiServer.begin();
}

void loop() {
  WiFiClient client = wifiServer.available();
  if( client){
    Serial.println("New Client Connected...");
    xTaskCreatePinnedToCore(
    TaskClientSocket
    ,  "TaskClientSocket"
    ,  4098
    ,  &client
    ,  2
    ,  NULL
    ,  ARDUINO_RUNNING_CORE);
  }
}

void TaskClientSocket( void *pvParameters )
{
    WiFiClient clientHandle = *((WiFiClient*)pvParameters);
    for (;;)
    {
      while(clientHandle.connected()){
        while(clientHandle.available()>0){
          char c = clientHandle.read();
          clientHandle.write(c);
        }
        vTaskDelay(100);
      }
      clientHandle.stop();
      Serial.println("Client disconnected");
      vTaskDelete(NULL);
    }
}


text:
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.

I'm voting to close this question as off-topic because their isn't even the word "Arduino", not even once, in the question. How is this suppose to be on topic?

@DatHa I am using the Arduino EthernetClient and EthernetServer

Try Stack Overflow

@DatHa the forum is specifically for Arduino so I assumed it was generally understood any programming questions were related to Arduino programming

Not my problem. The question has to be clear.
Be specific : program, schematic, part used.
See : http://stackoverflow.com/help/how-to-ask

This can only be done with a redirect. If you cannot use a redirect (because something about your web server doesn't let you) then you need to re-think your website design.

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


text:
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!

How is the code 'activated'?

Here's your sketch, modified to use my library, 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).  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.  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!

But when trying to verify this sketch, I still get the same error, that the timer wasn't declared.

Sorry, that wasnt the error, got mixed up.

The error says;    #include <NeoSWSerial.h>
                     ^

compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.

Did you download and install NeoSWSerial from the link? It's a standard Arduino library that you download, unzip, and copy the NeoSWSerial-master directory to a new Arduino/Libraries/NeoSWSerial subdirectory.

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
{
}

Dat Ha...  After uploading this code, i recieved the error ' timer' was not declared in this scope, in this line if (millis() - timer > 2000) {

Do you know what might be causing this??

void setup is a loop that run once. void loop is a code that runs and repeat. Open a blank sketch a see what happens. If it works, please consider accepting the answer to mark this question as resolved.

Well, the error tells you that the variabele 'timer' was not declared... Which basically means you're missing your declaration of the timer variable: 'uint32_t timer = millis();'

authors: เพ็ญพยอม คํานวณ


text:
Simultaneous output from sonar array
I am working on a project that records the elevation changes of a 1 foot wide section using sonar distance measurement. I have 10 HC-SR04 sensors arranged in a straight line over this 1 foot section.
The issue I am having is that when I send an output from my sonar sensor, I must wait until the return signal is recorded before I can trigger the next sonar sensor to take a measurement. This is rather slow and decreases the sampling frequency significantly. I need each sonar sensor to take 1000 measurements per second for my project.
Is there a way to have the HC-SR04 sensors simultaneously output and listen for the return signal? I would want all 10 sensors to send a 40 kHz pulse at the same time, and then when a return signal is recorded, another 40 kHz pulse is sent out.
The average distance to the 1 foot wide section is about 11 inch. If the Arduino is limited and there are other control boards that can accomplish this, it would help a lot if you can point me in the right direction.

1000 measurement for 10 sensors per seconds, it means there are 10000 measurement per sec with 0.1 mS time slot for each measurement.
According to SRF-04 Documentation,
(1)

If nothing is detected then the SRF04 will lower its echo line anyway after about 36mS.

So, time slot for each reading is 36 mS ("if" nothing is detected), which means for 10 SRF04 x 1000 reading, it will take 360000 mS = 360 Sec.
(2)

I would want all 10 sensors to send a 40kHz pulse at the same time, and then when a return signal is recorded, another 40kHz pulse is sent out.

Its seems reasonable. But,

According to the timing diagram, 1 cycle minimum period consist of :

100 us Trigger pulse ==> 0.0001 s
8 Cycle burst at 40 kHz = (1/40000)*8 s ==>  0.0002 s
100 us Echo pulse ==> 0.0001 s
10 ms delay time ==> 0.01 s

Total for 1 cycle is 0.0104 s, so for 1000 readings x 10 sensors (object to detect is present) will be 104 s.
All sensor burst at the same frequency, great idea. However it's not advised (or rather not possible) because that will disturb each sensor reading unless you successfully change each sensors frequency or doing sound modulation. Even if you success in modulating 10 sensors frequency, the needed time is still not met 1 s interval

100uS for 10 sensors trigger pulse at once ==> 0.0001 s
8 Cycle burst at 40 kHz = (1/40000)*8 s ==>  0.0002 s
100 us (minimum) Echo pulse --> 0.0001 s x 10 sensors ==> 0.001 s, because Arduino does not support threading, which mean there is no way you can read all at same time
10 ms delay time ==> 0.01 s

Time for 1 cycle (10 sensors reading): 0.0113, 1000 readings : 11.3 s
(3)
"How about changing the beam pattern?"

Changing beam pattern and beam width
You can't! This is a question which crops up regularly, however there is no easy way to reduce or change the beam width that I'm aware of. The beam pattern of the SRF04 is conical with the width of the beam being a function of the surface area of the transducers and is fixed.

So, rather than trying to modify the ultrasonic, more reasonable solution is changing the way you do elevation measurement.


text:
Replacement crystal on Uno for cold temperatures
I want to run an arduino out in the cold (-40), and use the serial communication - I believe that the crystal is the weakest link (the one for the serial chip) - however I don't see any drop-in (through-hole) replacement crystals that would work in such cold, so would a SMT version work instead? if so, which one would be possible to solder (package?), and do I need to change the caps to match?
P.S. - Yes, I could heat it/insulate it, but that comes at a fairly high power/complexity cost

Have you tried it at -40?  The crystal may still function but be out of spec, and you might need lower standard baud rates, or to tweak the generated baud rate to match what the reciever would expect..

@DaveX The baudrate seems to fail around -20c at 9600, have not tried tweaking it much

You could run the Arduino of the internal oscillator. After that you can calibrate the oscillator on the fly using the UART. PS are you even sure crystals exist that do work at -40?

All crystals change physical properties as their temperature changes. Heating it is always the fix.

@Gerben it's actually not the the arduino that has the issues, it's the serial to usb chip on the board
@ IgnacioVazquez-Abrams I know heating can fix it.. but I would end up increasing the power draw by a factor of 10 in order to keep the thing heated - also there are different components with different temperature ratings

If it's the USB to serial you could try connecting to the serial pins directly and have a separate USB to serial breakout, outside of the -40 environment.

What Gerben said--use the hardware serial instead of the 12MB USB2.0 connection, and its lower speeds should be more resistant to mismatched speeds, and should also be tunable if you get far out of spec.

Please give more details about the application. How are you connecting the board? Maybe using a remote oscillating circuit is the best way, or you can make a small board with a compensated oscillator. But... -40° is the limit for the atmega328p, so are you sure that you really need to have a arduino out there? You will need to power it, and batteries are useless at that temperature, so you'll need a power cable. If you have to wire it, then you can wire just the sensor you need to put there...

if you insulated it you wouldn't need 10X the power of running it to keep it "warm"

@dandavis that's assuming it starts warm, if it starts cold (which without running not even insulation will help against) it will take a while to warm up

Why do you think the crystal is the weakest link (the one for the serial chip)? Tolerancewise it is 200 times better than the ceramic oscillator (+/- 0.5%) used by the main processor. The ceramic oscillator has a 0.2% temperature sensitivity and is only specified to work for -20 °C to +80 °C.

There is a solution for just this problem, it's a "crystal oven". It is used to keep a crystal at a constant temperature so that the oscillating ferquency remains very stable.
Crystal ovens are usually expensive as they are quite precise and have good insultaion, but here's a kit that you might adapt for your uses: http://www.minikits.com.au/Oscillator-Heater, or google around to see if you find something that might suit you better.
You could also consider making a heater with a simple temperature regulator of your own to keep the crystal warm  (many temperature sensors for Arduino are available on the web).