text:
How to set Inquire Access Code (IAC) via AT commands on HC-05?
I am trying to set IAC of HC05 via AT Commands, but for some reason, the result is not as desired.
I need to set the IAC as '1234', for which I enter the command:
AT+IAC=1234

The module responds OK, but when I ask AT+IAC?, it replies '01234'.
Now, it has been troubling me for the past few days. I've also tried adding '\r\n' to the end of command, but it sets the IAC as '1234444'
I would be thankful if you could help me with this! I tried searching the net but to no avail.

Are you manually talking to the HC-05 via a direct serial connection or via an Arduino program?

I do it via the serial monitor of the Arduino IDE.

You have to have \r\n in both the set and read command.
Example:
AT+IAC=12345f\r\n
OK

AT+IAC?\r\n
+IAC: 12345f
OK

Thanks MatsK, but I'm afraid it doesn't work. When I enter the code AT+IAC?\r\n , it gives Error(0) which I've looked is for command error. Trying it without \r\n in the inquiry code resulted in +IAC:12344444. Any idea what's cooking up there?


text:
I have built a battery level indicator and have tested with a 12V battery Would it harm my arduino board if I connect a 48V battery?
I am a newbie and have followed a tutorial to build a battery level indicator as below

Please suggest any changes I'll need to make to make the circuit useful with a 48V battery as the above circuit is tested with a 12V one.
Thank You.

Care to share the code?

does it work with super 1000ah, 12v battery?

You have a voltage divider there, which would give (if the pre-set pot was set to the maximum):
Vout = (Vin * R2) / (R1 + R2)
Vout = (12 * 10000) / (100000 + 10000)
Vout = 1.09

Thus a 12V battery would present 1.09V at the analog input.
This same wiring would seem to be in range for a 48V battery:
Vout = (48 * 10000) / (100000 + 10000)
Vout = 4.36

Since the analog input can handle up to 5V, then that should be OK. However I would test the voltage divider output first with a multimeter to make sure it doesn't exceed 5V - before connecting it to the Arduino.

You would probably need to change the code to test for different ranges of input voltages, other than what is used for the 12V battery.

Also, if you are using a 3-pin trimmer/pot, be sure to short the central pin to the "unused" one. In this way, if dust/dirt collects on the resistive element, or in case of a major failure, the maximum resistance of that trimmer will be 10kOhm, and not "infinite", avoinding feeding a destructive 48V to the digital input.

Good idea. You don't want the pot to go open circuit as you turn it as it hits specs of dust.

That's great! Edited because I figured it out.

You might also want to connect a 5V zener diode between the voltage sensing pin and ground. That way if you exceed 5V the zener will shunt the excess voltage to ground and protect the pin.

To get a smoother switch from one level to another you could introduce another resistor and use analogWrite() to dim one LED and make next brighter.
Ref.: https://www.arduino.cc/en/Tutorial/PWM

source: Stack Exchange

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

sort: votes


text:
Low power RGB LED for wearable device
I am trying to prototype a wearable device which will have about 120 RGB LEDs. I was considering the WS2812B but they seem to draw about 50mA and so may not be a good option since I will be powering them from a battery.
I would be glad to know of other options or ways to implement the LEDs in order to consume less power.

It would help to give an actual figure. "Less power" is pretty vague. How much, per LED, are you hoping to consume? (1 mA might be your hope, but I mean a practical hope). Obviously 120 LEDs at 50 mA each will consume 6 amps. Are you hoping for 500 mA?

You can reduce the current by simply reducing the duty cycle. For example, to display red, rather than sending 255 as the red component, send 42.
If you divide each of the R/G/B values by the same figure you get the same colour, just duller. In a quick test I found that a 24-pixel strip only used 67 mA if I sent red=0, green=0, blue=42 which made them look a dull blue. If you send a value of 8 (in a single channel) then it takes 25 mA for 24 pixels.
A bit more testing reveals a base consumption of 21 mA even if you are sending black. That is, the overhead is 21 mA, which works out at about 1.1 mA per neoPixel.
Based on that, you would consume 335 mA to make 120 NeoPixels show a moderately bright red.
I don't think there is going to be some "magic bullet" that lets you light up 120 LEDs brightly, but not use much power. However using the NeoPixels which lets you have fine control over the brightness of each of the R/G/B pixels is probably going to be about as close as you can get.
The figure of 50 mA which you quoted is to have "full brightness" on all three colours (ie. bright white).

"If you divide each of the R/G/B values by the same figure you get the same colour, just duller." : oops, that's a common misconception. color scale values are not linear. you will find colors get very "bandy" at the low end like that. the rest is good stuff though. it would be interesting to PWM incoming power and still use 0-255 instructions to maintain relative contrast...

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


text:
HC-05 module short circuit
I have bought a HC05 bluetooth module and I think I accidentally short circuited it. Is there any way to change the voltage regulator or methods to reuse it again?

Accept the answer to close your question.

I suppose you're referring to the HC05 module, already soldered on a board, with the 6-pin header. The regulator is on that board.
Online you'll find several versions of that board, therefore you should check the schematics, to find which you need to mount. For instance, on some board, a R1114-33 is used.
Changing the regulator is not the hardest task on earth, however, other components are very close to it (capacitors).
Still there are 2 things to consider:

Is it worthy to change the regulator? That module will cost few
bucks.
As you can see from the datasheet, the regulator is short-circuit protected (yes, it does not mean that it will be indestructible). I think, instead, you destroyed one of the two ICs of the bluetooth module soldered on board. And those one, beside of being quite difficult to find and expensive in small quantity, they are very hard do replace.

Thank you for your comment sir. I have already lost 2 of them due t short circuit issue ,which is really frustrating .So instead of buying I wanted to fix it. Is there any way to know if the Bluetooth ICs are destroyed?

@curious-boy do they heat up? If yes, they are dead. If not, this does not mean that they aren't... How and where did you short circuit the module? I.e. which pin?

yes they heat up .I guess i have to buy a new one.

I think that this has been caused by:

accidentally a wire (powered at 5V) contacted one of the various solder joints of your board. (always turn off power when mounting the circuit!) 2) maybe you should consider to put a resistor in series to the TXD and RXD lines (yes, many modules already have them, but in some of them they are just 100 Ohm! too low for a 5V to 3.3V conversion! Put 10k  if you're going up to 115200).

To be sure: you didn't connect that module to a serial port of a PC, right? The serial port outputs up to 12V on the RXD and TXD lines...


text:
Differences between Arduino IDE versions
I run Arduino IDE on both my Mac and under Raspbian on a Raspberry Pi, both running the latest version of OS.
The Raspberry Pi has Arduino 2:1.0.5+dfsg2-4.1 and I am running the latest 1.8.4 on macOS.
Debian is always somewhat behind the latest software, and this has not concerned me before, as I have never had issues before. (I know I could download the latest ARM32 build or compile from source, but this would probably generate a lot of dependencies.)
I have recently run into a couple of problems.
Compiling a script which has #include <SdFat.h> generates an error, although the library is present in ~/sketchbook/libraries/SdFat/src/SdFat.h. This does not seem to be an issue on macOS.
I was also trying to program an Atmega using a Uno as ISP as in "Using an Arduino as an AVR ISP". I have done this in the past, but the instructions and the Arduino program seem to have changed; there is no longer "Upload Using Programmer" menu, but suggests the "Burn Bootloader" command. Does this upload both the Bootloader and Sketch?

Debian is always somewhat behind the latest software

No, when it comes to the Arduino IDE Debian is frozen on an ancient version.
1.0.5 is considered to be too old to use. Many many things have changed since then - bug fixes, optimisations, new API components. And not least the implementation of the Board Manager for installing support for more boards, both by Arduino and other makers, and support for multi-arch libraries (which your SdFat library is with a src folder in it).
You should never install the Arduino IDE from the Debian repositories. Instead you should download the current version of the Arduino website (http://arduino.cc/download) as a tar.\z file and extract it into a folder and run it from there.

Majenko answered why my sketch did not compile.
I decided to give it a try and downloaded arduino-1.8.4-linux32.tar.xz.
I was somewhat concerned that there seemed to be no indication whether the Linux ARM supported ARM6, or ARM7.
The download itself contained absolutely no information, not even a README. I ran install.sh as outlined in  https://www.arduino.cc/en/Guide/Linux and Arduino IDE installed alongside the existing Arduino IDE, and worked (at least on the PI3).
I also solved my issue using a Uno as ISP. The documentation on the Arduino site now describes "Use the Burn Bootloader command". I found the missing "Upload Using Programmer" menu under the Sketch menu.


text:
Can't upload the program to Arduino Uno
My Arduino Uno R3 is not detected by any laptop (I tried 3 laptops). Under devices there is no Arduino port or other devices option. It does not make sound on inserting USB cable. On plugging the USB LED 13 doesn't blink. I is just continuously on. Reset also didn't blink LED 13. Even on external power also it's not resetting.
I checked the USB cable but it's working for my friend's Arduino in my laptop too.
5V Pin giving voltage around 4.96 v, and 3.3 also giving voltage around 3.27 v.
Now I don't have access to any other Arduino for testing. Is there any way to figure out whether the ATmega chip is fried or whether it's a bootloader problem? And how to fix them? Thanks in advance.

Consider swapping socketed Arduino processors to see if the problem follows the processor.  Be careful about not bending pins.  Also avoid static electricity.

Genuine Arduino or cheap oriental clone?

Please check the answer at https://arduino.stackexchange.com/questions/44957/arduino-port-grayed-out-for-arduino-uno/

While installing the Arduino software,
there are several window pop ups which occur to install the  drivers needed for the operating system to communicate with the device.
Click install to all of them.

If you have access to a linux computer, what does lsusb say when it is plugged in over USB? Compare that output to lsusb with no Arduino plugged in. If you don't, does the arduino show up as a device to your OS at all?
You could also use your friend's arduino to reflash your bootloader. If that still doesn't work, or if your arduino doesn't show up as a device, you can try reflashing the atmega16u4 ( the USB <-> serial chip ). It is the chip responsible for telling the computer that it is an arduino serial port, so if things are still getting power, but not showing up, I would check that chip.
If it is neither of those things, there may be something wrong with one of the passive USB components, maybe one of the varistors died and is now shorted to ground, for instance. I could give more help if you share the schematic for your specific board.. is it an official Arduino, or a clone?

Can't upload the program to Arduino Uno

if your trouble is limited to just "the program", then the issues must be specific to that program.
if you cannot upload "any program", then the issues must be hardware or host related.

It is probably not a problem with the Atmega328p chip or its bootloader; the Uno has a separate processor to handle USB - an Atmega 32U4, which is the flat, surface-mount chip right behind the USB connector on the board. If that or its firmware is damaged, your PC won't recognize the device when you plug it in. If that chip is up and running, your PC will see it.

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


text:
Known conflicts between use of HC-12 and Ethernet Shield on Mega2560?
I have two somewhat similar sketches that use both HC-12 [for data collection] and a W5100-type Ethernet Shield [for Email construction and transmit].
Both sketches run fine until the code for the Ethernet Shield is invoked, which creates a connection and successfully transmits an Email.
Once this happens, the HC-12 no longer receives transmits.  No exceptions are raised, and I am at a loss to determine the cause of the problem.
[The HC-12 is using pins 50-52.]
I have other sketches that use either the HC-12 or the Ethernet Shield, and they work fine.  Before I build a custom sketch to attempt problem isolation,
I thought I would simply ask the question of whether known conflicts exist.  I know that many questions are resolved by posting the sketch and someone other
than the author scanning it.  I think that impractical in this particular case.  The sketch comprises 6,000+ lines of code.
If no helpful responses are forthcoming, I will continue with problem isolation, and post again if no success is achieved.

I'm voting to close this question as off-topic because it is unanswerable without further details, especially which pins the Ethernet shield is using and the interaction between the software attempting to use each.  For that matter, it's bad form to mention something obscure like the HC12 and not explain what it is and what the utilized pins do.

Are you using SoftwareSerial on GPIO pins instead of using one of the three hardware UART ports?

@Majenko I am using SoftwareSerial simply because I started on an Uno, and didn't/don't know any better.   Bad idea, I guess? I've little experience with Mega2560, and none with the hardware UART ports.
I selected pins 50-52 for the HC-12, because I thought they were free, as the Ethernet shield plugs into pins 10-13.  However, my recent reading implies that the Ethernet code references 50-53 anyway, though I don't understand how.  If so, this certainly would be a source of conflict.  Perhaps this is the point you are leading up to?
In any case, i think I now have an avenue to pursue.

I have a feeling (though I am not sure, I'd have to check) you happened to pick the SPI pins which the Ethernet shield uses (through the ICSP header). Never use SoftwareSerial unless you absolutely have to (and you don't - you have Serial1, Serial2, etc available).

One thing I know for sure about the HC-12 is that you need to have an external power supply capable of giving it about 200 mA just for it.  Plus another 350 for the board, and some more for the shield.  I suspect the shield being activated is making the current drop below what the HC-12 needs to operate.  Can you give it a better power supply then come back and give us an update?

As suggested by Majenko, the problem results from using Software Serial for the HC-12, and unfortunately choosing the pin set 50-52, which conflicts with the pin usage specification for the Ethercard Library.
Hence, the HC-12 code works fine until usage of the Ethernet shield is finally activated.  From that point on, the Ethernet code functions properly,  whilst the HC-12 code does not.  The recommended solution, which does indeed solve the problem, is to abandon usage of SoftwareSerial for the HC-12, and use Serial1, or Serial2, or Serial3 instead.
I do not feel that the solution to the problem is truly mine, but post it only that the information may be of subsequent use to a user encountering a problem of similar nature.


text:
Midi Program not sending notes
I'm working on a midi device with a pro micro, it's reading as a midi device, but not outputting any notes, here's my program:
    const int button1 = 2;
    const int button2 = 3;
    const int button3 = 4;
    const int button4 = 5;
    const int button5 = 6;
    const int button6 = 7;
int note = 0;

const int c3 = 36;
const int d3 = 38;
const int e3 = 40;
const int f3 = 41;
const int g3 = 43;
const int a3 = 45;

void setup() {

  pinMode(button1,INPUT);
  pinMode(button2,INPUT);
  pinMode(button3,INPUT);
  pinMode(button4,INPUT);
  pinMode(button5,INPUT);
  pinMode(button6,INPUT);

  Serial.begin(31250);

}

void loop() {
  int button1State = digitalRead(button1);
  int button2State = digitalRead(button2);
  int button3State = digitalRead(button3);
  int button4State = digitalRead(button4);
  int button5State = digitalRead(button5);
  int button6State = digitalRead(button6);

  if (button1State == HIGH) {
    note = c3;
    noteOn(0x90, note, 0x64);
  }
  if (button1State == LOW) {
    note = c3;
    noteOn(0x90, note, 0x00);
  }

  if (button2State == HIGH) {
    note = d3;
    noteOn(0x90, note, 0x64);
  }
  if (button2State == LOW) {
    note = d3;
    noteOn(0x90, note, 0x00);
  }

  if (button3State == HIGH) {
    note = e3;
    noteOn(0x90, note, 0x64);
  }
  if (button3State == LOW ) {
    note = e3;
    noteOn(0x90, note, 0x00);
  }

  if (button4State == HIGH) {
    note = f3;
    noteOn(0x90, note, 0x64);
  }
  if (button4State == LOW) {
    note = f3;
    noteOn(0x90, note, 0x00);
  }

  if (button5State == HIGH) {
    note = g3;
    noteOn(0x90, note, 0x64);
  }
  if (button5State == LOW) {
    note = g3;
    noteOn(0x90, note, 0x00);
  }

  if (button6State == HIGH) {
    note = a3;
    noteOn(0x90, note, 0x64);
  }
  if (button6State == LOW ) {
    note = a3;
    noteOn(0x90, note, 0x00);
  }

}

void noteOn(int cmd, int pitch, int velocity) {
  Serial.write(cmd);
  Serial.write(pitch);
  Serial.write(velocity);
}

You are handling your buttons in completely the wrong way. You are basically saying:

While I press this button send a constant stream of NOTE ON commands. Otherwise send a constant stream of NOTE OFF commands.
At the same time, send more NOTE OFF commands because the other buttons aren't pressed.

So you can see it's going to be a bit of a mess.
Instead you need to detect changes in the state of a button.
For example:
void loop() {
    static bool oldButton1 = LOW;

    bool button1State = digitalRead(button1);

    if (button1State != oldButton1) { // It changed from last time
        oldButton1 = button1State; // Remember it for next time
        if (button1State) { // Pressed
            noteOn(0x90, c3, 0x64);
        } else { // Released
            noteOn(0x80, c3, 0x00); // Note: 0x80 is NOTE OFF, not 0x90.
        }
    }

    ... etc for the other buttons ...
}

Check:

If your serial properties are ok (baudrate 31250, 8 bits, 1 stop bit)
Check if noteOn is really called (print out the values which are sent)
Show your MIDI circuit, assuming you think no MIDI notes are send because you have a MIDI connector attached.
Use a protocol analyzer if you have one to check the MIDI signals sent
Check the components of your circuit, e.g. if you use an opto-coupler, what types is it? some are too slow for MIDI
Do not use virtual serial ports, I tried with MIDI and they give bad results (checked on Uno).


text:
Wiring diagram for Arduino to prevent relay firing on reboot
I'm starting to explore using an Arduino to control a couple of switches programatically. I have read somewhere about relays firing during reboot due to floating inputs/outputs during the reboot phase.
What is the best way to ensure that a relay will not fire on a reboot?
Is there a simple wiring diagram to explain it? I am using an Arduino Uno and a Relay Module.
Any assistance would be greatly appreciated.

Two things:

If that relay uses a FET input with no pulldown then you should add your own. If it uses an opto-isolator there is no floating problem to deal with.
Don't use pin 13 for a relay - that is connected to the LED which blinks during reset and will "flash" your relay.

You can add a pull down/up resistor between the wire and ground/vcc so that when the arduino pin is set to high impedance during reboot the wire is pulled low/high as desired.

What is the best way to ensure that a relay will not fire on a reboot?

put pull-up/down, as appropriate, on those pins.


text:
Avoiding false rising and falling edge when using demultiplexer
I have 8 sets of 8 push buttons. There is a Teensy and a demultiplexer. The demultiplexer has 8 outputs. When an output is selected it is pulled low. Each output is connected to a group of 8 push buttons. The 8 push buttons are then connected to 8 pullup inputs on the Teensy.
Each group of 8 push buttons is connected to a unique demultiplexer output, but all the push buttons are connected to the same 8 inputs on the Teensy. That is, push button #1 in group 1 shares a Teensy input with push button #1 in group 2. The push buttons are isolated from each other with diodes.
I'm using bounce.h for debouncing. It looks for rising and falling edges.
The problem is this:

Push button #1 in group #1 is pressed, pulling that input low, causing a falling edge to be detected. This is good.
The demultiplexer shifts to group #2, where the #1 button hasn't been pressed, and thus is high.
Because both #1 buttons in group #1 and #2 share the same input line, the Teensy sees this change as a rising edge. This is undesired.

What is the better approach to this?
Thanks,
Dan

Why is a rising edge undesired when the switch going low is what you are looking for? Who cares if it goes high?

When you press a button there is an initial rising edge, and if you keep that button pressed until the demux cycles all the way around, it will detect another rising edge, and will keep doing this. It also detects a falling edge right as soon as the demux shifts away from the still-pressed button. These extra rising and falling edges don't accurately portray the state of the buttons, and so I'm trying to filter them out, or go about detecting the button states differently.

When you press a button there is an initial rising edge - When an output is selected it is pulled low - these statements contradict each other. When you press a button these is a falling edge.

Yes I have those backwards.

To do multiplexing with bounce.h you will need one bounce object per button. That's 64 bounce objects for an 8x8 matrix.
Then you only want to update the bounce objects for the group you currently have active.
That is:

Switch to group 1.
Update objects 1-8
Switch to group 2
Update objects 9-16
... etc ...

You need one object per button so that the internal data can track the state of that specific button, and you only update the 8 objects for the currently selected group otherwise the objects that aren't associated with that group will get confused by incorrect data.

What is the better approach to this?

write your code so it debounces each pin / group of pins separately.
looks like your code used global / static variables.


text:
Arduino MEGA2560 Standalone
I had an Arduino UNO (ATmega168) standalone working, but I need more pins, and I decided to use the ATmega2560, I was searching for some schematics, and none of them shown an ATmega2560 standalone, only the full Arduino, with the FTDI, power transformers... etc integrated. So taking parts from those designs, I made this, but I don't know if it's enough or I need Something more:

Note: VCC2 is connected to 5V.

Looks like R1 has both sides connected to GND.

This might be helpful: https://github.com/MCUdude/MegaCore#minimal-setup

See http://www.atmel.com/Images/Atmel-2521-AVR-Hardware-Design-Considerations_ApplicationNote_AVR042.pdf

You need more decoupling capacitors - one per VCC and AVCC pin, plus a larger (10µF) for the whole chip.
You need a pullup resistor (and maybe button) on RESET.

In theory (page 58 and 355 of the datasheet) the reset line has already a 30-60 kOhm pull-up resistor.
Yes, it might not be enough in very noisy/humid/dirty environments (as I found sometimes). I also always put a 10kOhm: it does not harm.

So it does. I'm used to MCUs with no internal pullup, but yes, it's good to add a proper external one anyway since that is quite a high value for a pullup.

Especially if you plan to use an external DTR+100nF based reset circuit for programming - the lower pullup value will recharge the capacitor faster.

Here in the Arduino forum: http://forum.arduino.cc/index.php?topic=152319.msg1143618#msg1143618 they say that just changing the processor, will be enough to work, basing on this: http://arduino.cc/en/Tutorial/ArduinoToBreadboard.

check the datasheet;
I would put a pull-up on the reset pin, plus a small capacitor;
crystal + capacitors as optional;
AVCC to VCC with filtering, if you need good analog performance;
separate Vbat domain, if it has one.

...


text:
ESP needs a reboot after wifi OTA flash
I would like to use OTA in some of my less accessible esp's. I am using the examples/BasicOTA and BasicOTA_test. My esp is a -01 model with 1Mb of flash.
I upload the BasicOTA to my esp through the COM port, then upload the BasicOTA_test over WiFi.  Everything appears to go OK, but the test sketch doesn't run until I press reset on the esp.
If I upload BasicOTA over the com port then upload a simple blink sketch over WiFi without the OTA code, it uploads fine then runs without a reset.  But then, I can't upload over WiFi anymore.
If I have to hit reset every time I upload a new sketch that contains the OTA code, then why bother?
Tips would be appreciated.

Why bother? it's still FAR easier to power cycle an installed device than it is to wire uart to a built-out thing... fwiw, this doesn't seem to happen each time anyway; i suspect it happens most upon the first OTA.

You can add ESP.restart() in the following line to make it restart.
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
ESP.restart();
});

Now you can upload code each time without hitting reset.

the ArduinoOTA library does the reset. but who knows now what was the state of the library in 9/2017

I've done some research and this appears to be a common problem while using OTA to update the ESP8266. In fact, this bug has been reported on their GitHub and it's due to the watchdog timer resetting after the ESP8266 is flashed via OTA.
It appears the problem can be solved by manually resetting (once) after you upload it via serial BEFORE you can upload it via OTA. After that, you shouldn't have any problems.

That is a different issue, that issues is when you have to reset before upload via OTA. OTA not running the new sketch untill after manual reset as described above is another. Did you solve both?

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


text:
Particle Spark (Arduino) How to flash 2 LED sequences at the same time?
I can't find any information that relates to my problem. The few things I did find confused me (I'm quite new to this).
I'm trying to flash 2 sequences of 4 lights at the same time. I can get 1 set flashing but I don't know how to run other sequences at the same time. My probably laughable attempt at the code is below:
int led1 = D0;
int led2 = D1;
int led3 = D2;
int led4 = D3;
int led5 = D4;
int led6 = D5;
int led7 = D6;
int led8 = D7;

void setup() {
  setupPart1();
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  setupPart2();
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(led7, OUTPUT);
  pinMode(led8, OUTPUT);
}

void loop() {
  loopPart1();
  digitalWrite(led1, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led1, LOW);
  digitalWrite(led2, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led2, LOW);
  digitalWrite(led3, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led3, LOW);
  digitalWrite(led4, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led4, LOW);
  loopPart2();
  digitalWrite(led5, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led5, LOW);
  digitalWrite(led6, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led6, LOW);
  digitalWrite(led7, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led7, LOW);
  digitalWrite(led8, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led8, LOW);
}

How about the example that comes with the IDE: BlinkWithoutDelay?

You could use a simple scheduler. Here is a multi-blink example: https://github.com/mikaelpatel/Arduino-Scheduler/blob/master/examples/SchedulerBlink/SchedulerBlink.ino

I cover this exact question in my web page: http://www.gammon.com.au/blink
Example code that blinks two LEDs at different rates:
// Which pins are connected to which LED
const byte greenLED = 12;
const byte redLED = 13;

// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long greenLEDinterval = 500;
const unsigned long redLEDinterval = 1000;

// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer;
unsigned long redLEDtimer;

void setup ()
  {
  pinMode (greenLED, OUTPUT);
  pinMode (redLED, OUTPUT);
  greenLEDtimer = millis ();
  redLEDtimer = millis ();
  }  // end of setup

void toggleGreenLED ()
  {
   if (digitalRead (greenLED) == LOW)
      digitalWrite (greenLED, HIGH);
   else
      digitalWrite (greenLED, LOW);

  // remember when we toggled it
  greenLEDtimer = millis ();
  }  // end of toggleGreenLED

void toggleRedLED ()
  {
   if (digitalRead (redLED) == LOW)
      digitalWrite (redLED, HIGH);
   else
      digitalWrite (redLED, LOW);

  // remember when we toggled it
  redLEDtimer = millis ();
  }  // end of toggleRedLED

void loop ()
  {

  // Handling the blink of one LED.
  if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleGreenLED ();

  // The other LED is controlled the same way. Repeat for more LEDs
  if ( (millis () - redLEDtimer) >= redLEDinterval)
    toggleRedLED ();

/* Other code that needs to execute goes here.
   It will be called many thousand times per second because the above code
   does not wait for the LED blink interval to finish. */

}  // end of loop

thank you very much, i dont understand it but i will sit down tonight and try to figure it all out from the guide on your site

This kind of problem (doing several things in parallel) is frequent enough to merit a more elegant solution. While projects like this are excellent (Tasks: A Time-Triggered Scheduler for Arduino), I can't get it working.
I wrote this minimal self-contained example of how to do two things simultaneously. It will blink the built-in LED and write "*" to the serial monitor:
--- Task Scheduler ---
Runtime in SS:MMMM
10:9 **********
110:64 **********
210:89 ***

This is the sketch. Study it and adapt it to your own problem:
/*
 * Task Scheduler for Arduino/ESP2866 by Look Alterno - 2017/8/9.0
 * Show how to execute tasks at regular intervals without using delay() or interrupts.
 * For educational purposes only; not production ready.
 *
 * This sketch have two example tasks running:
 * - Task 1 blinks the builtin led every second
 * - Task 2 write lines with run time and one "*" every ten seconds in the Serial Monitor.
 * Tasks are run in sequence, so keep them short.
 * No interrupts are used; you have to call runTasks() in each loop() pass.
 */

// Definition: Every task must receive nothing and return nothing.
typedef void (*fcnptr)();
//  Here we must declare our task functions (required by C)
void fcnBlink();      // Task 1
void fcnSerial();     // Task 2
//  Add more tasks here.

//  The interval between fcnBlink execution. Adjustable between 25 to 250 ms.
//  LED still will blink every second at the same freq (250ms on, 750ms off).
#define BLINK_LEN 25

//  The task list
struct {
    uint8_t  runnable;  // The task is runnable (true/false).
    uint32_t start;     // Next start time for the task (ms).
    uint32_t interval;  // Execution interval in ms.
    fcnptr fcn;          // Function to execute.
} taskList[] = {
    {true, 0, BLINK_LEN,fcnBlink}, // Execute fcnBlink every 25 ms, blink LED every second
    {true, 0, 10000,    fcnSerial} // Execute fcnSerial every 10 seconds.
    // Here you can add other tasks.
};
// The number of task in our task list.
const uint8_t nTasks = sizeof(taskList) / sizeof(taskList[0]);

void setup() {
  // Just a standard setup. Nothing is required for task execution.
  Serial.begin(9600);
  while(!Serial) {};
  randomSeed(analogRead(A0));
  Serial.println("");
  Serial.println("--- Task Scheduler ---");
  Serial.println("Runtime in SS:MMMM");
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  // Here you write your processing code (without using delay())
  // --- Start of your code.
  // Some random delays to simulate work
  // Just a bit less than half fcnBlink interval length.
  // You can change BLINK_LEN to test other scenarios.

  delay(random(1, BLINK_LEN / 2));

  // --- End of your code
  runTasks();  // At the end of the loop(), but can be anywhere.
}

/*
 * Check the task list and execute them.
 * Sequence of execution guaranteed: tasks could be delayed,
 * but not omitted or executed of order.
 */
void runTasks() {
  uint32_t now = millis();
  for(uint8_t i=0; i < nTasks; i++) {
    if(taskList[i].runnable) {
      uint32_t diff = now - taskList[i].start; // ms since last execution.
      if(diff >= taskList[i].interval) {
        taskList[i].start = now; // Have to be the same for all task, to keep sync.
        taskList[i].fcn();
      }
    }
  }
}

/*
 * Blink the led.
 */
void fcnBlink() {
  // Called every 25 milliseconds. Turn on the led in the
  // 10 first passes and turn off in the next 30.
  static uint8_t count = 0;
  count++;
  if(count <= 250 / BLINK_LEN) {
    digitalWrite(LED_BUILTIN, HIGH);
  } else {
    digitalWrite(LED_BUILTIN, LOW);
    if(count == 1000 / BLINK_LEN) {
      count = 0;
    }
  }
}

/*
 * Print run time (s) and a row of ten "*"
 */
void fcnSerial() {
  static uint8_t count = 0;
  count++;
  // Print run time in seconds:miliseconds at the start of each line
  if (count == 1) {
    uint32_t now = millis();
    Serial.print(now/1000);
    Serial.print(":");
    Serial.print(now%1000);
    Serial.print(" ");
  }
  Serial.print("*");
  if(count == 10) {
    Serial.println();
    count = 0;
  }
}

thanks for your advice, will study both replies, it looks like a massive jump in knowledge from my code so ill just have to knuckle down and study, cheers :)


text:
Connecting Arduino to the ESP8266
I want to run more stepper motors and would like to know if there is a way to connect the Arduino and the ESP8266 NodeMCU together for more functioning.

Do you want to have more stepper motors than one Arduino can control? Or do you want add the NodeMCU to get remote/WiFi function? Or can you please elaborate and change the question to clarify the question?

Absolutely. I'll use the Arduino UNO and the ESP8266-01 WiFi module as an example:

The ESP8266 works with 3.3V and not 5V, so you need to connect the 3v3 pin on the Arduino to the VCC and CH_PD pins on the ESP8266.
Connect the GND pin on the Uno to the GND pin on the ESP.
Connect the RESET pin on the Uno to GND. Grounding the RESET pin
effectively causes your Arduino to work as a dumb USB to serial
connector (which is what we want to talk to the ESP8266).
Connect the CH_PD pin on the ESP8266 to the 3.3V line
Connect the RXD pin on the Arduino Uno to the RX pin of the ESP8266.
Connect the TXD pin on your Arduino Uno to the TX pin of the
ESP8266.

Normally, when you want two things to communicate over serial, you'd connect the TX pin of one to the RX of the other (send --> receive). In this case, however, the Arduino isn't talking to the ESP8266; the computer is talking to the ESP8266 via the Arduino.


text:
ESP8266 error: espcomm_upload_mem failed while uploading sketch
First of all, I would like to apologize for posting this error once again to this community. However, I have been studying articles for last many days to resolve this error. Unfortunately, I did not get any solution which could resolve my problem.
Below is the error which I get when uploading a sketch (even the example sketch):
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed
Here are the connections:
Vcc - 3.3V
RST - 3.3v
CH_PD - 3.3v
Tx - Rx
Rx - Tx
GPIO0 - GND
GND - GND
I tried various combinations like Tx to Tx, Rx to Rx, pulling off GPIO0. Pulling off reset and ch_pd. Supplying external power source, supplying power directly from Arduino using 3.3V. Supplying power from Arduino 5V using an LD33V regulator. I have even tried uploading the code using USB to TTL. But every time I get exactly the same error.

Which OS you are working with?

Well, first of all you should make sure that the voltage on both Tx and Rx pins of the ESP8266 is 3.3V (the Tx and Rx voltage on Arduino is 5V). Personally, I've never succeded in using an Arduino to program the ESP (even though there are plenty of examples of this setup in the web). After a while, I just gave up and bought a converter to do the job for me (it's totally worth it).
Even so, I got this error a few times. You must keep two things in mind:

In operation mode, the CH_PD pin must be connected to 3.3V, but it won't do any harm to let it connected during the flashing, so I just soldered a wire between these two pins to make things easier.
In flashing mode, GPIO0 must be connected to GND. It won't work otherwise. I strongly recommend you using a usb converter for this, and only connect it to your computer once GPIO0 has been set to GND. This has solved this issue for me, in fact I even soldered a switch on my converter between GPIO0 and GND.

Hope this answers your question.
EDIT: Here are some photos of the setup

tried ur ways too. nothing worked :(

Have you plugged to the device to the USB port AFTER you connected GND and RST? Are you trying to supply power with the arduino, or are you using a converter? If you're using a converter, which one is it?

If you are using the arduino, also keep in mind that you must connect Tx with Tx and Rx with Rx, since you're just using it as an interface between the computer and the ESP8266.

Oh, I just noticed. I said RST and GND, it's actually GPIO0 and GND. Sorry for the mistake. It should work now. I editted the answer so others can see the right setup.

It didn't. I made a check on the voltage too. It was absolutely fine. I tried it to connect to external power supply. but didn't work. still the same error

i attempted to upload code via both ways. arduino and usb to ttl converter. and changed their connections as per the requirement.

Please verify you're choosing the right board -Generic ESP for ESP-01.


text:
How to vibrate Adafruit Feather 32u4 Bluefruit LE device?
I have 11 Adafruit Feather 32u4 Bluefruit LE devices. I want to vibrate my devices using a signal through an app. Is there any signal (Code from app like 0x56-NeoPixel checking, 0x43-clear color) or any sketch? Please provide me.

I can't find any device called "adafeuit feature 32u bluefeature le". Did you mean "Adafruit Feather 32u4 Bluefruit"?

If it is that Feather device how do you expect it to "vibrate"? What have you added to it that can vibrate?

If you can't even spell the board name correctly you have no hope of success with Arduino. Either start using your brain or give up.

The Adafruit Feather you are talking about is a small format Arduino compatible with BlueTooth Low Energy, USB and battery connector. It doesn't have any way to vibrate without adding external hardware.

Now, having Bluetooth in the package means that it can comunicate with an Android Phone, and can send/receive commands, post results, anything you need.
We don't provide sketchs for particular projects. You must learn how to program Arduino and Android. Follow the examples and tutorials widely available in the Web.

Altermo - Thanks for your feedback, And Yes i added external hardware for vibrate and  i found sketch code for vibrate my device.


text:
Adafruit Motor Shield and Bridge Library for Yun Shield
I am using the Leonardo board with the Adafruit Motor Shield v2, 2 steppers and the Yun Shield. The yun shield and steppers all run harmoniously, however, as soon as I do Bridge.begin() and anything that accesses the Yun shield Bridge library to access the console, the steppers stop running. Is this to be expected and are there any solutions?
Thanks

Looking at Bridge.begin() description here
 you can see this is blocking function.

begin() is a blocking function. Once you call Bridge.begin(), nothing else will happen in your sketch until it has completed. This process takes approximately three seconds.


text:
Data from RC522 to firebase real time database
#include<ESP8266WiFi.h>
#include<SPI.h>
#include "MFRC522.h"
#define RST_PIN D3
#define SS_PIN D4
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
}

void loop() {
  if ( !mfrc522.PICC_IsNewCardPresent() ) {
    delay(50);
    return;
  }

  if ( !mfrc522.PICC_ReadCardSerial() ) {
    delay(50);
    return;
  }

  Serial.print(F("Card UID: "));
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println();
}

void dump_byte_array(byte *buffer, byte bufferSize) {
  for ( byte i = 0; i< bufferSize; i++ ) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

I am able to get the unique ID of the RFID tag & card. But now the problem is that how can I send the unique ID from ESP8266 to the firebase realtime database.
The hexadecimal values that are generated are they unique? or they are something else? Because in some youtube videos I saw people using only numbers as a unique ID from RFID to distinguish between 2 cards or tags.
The wifi connection and firebase auth all are set peoperly ony the unique id number is the problem.

The "UID" of the card is supposed to be unique. Most RFID chips also have blocks of readable/writable space, but some systems do only use the UID from the chip as the complete identifier.
It may be that you come across RFID chips that have utilized random bytes as the UID, in which case there is a chance of duplication. Depending on the number of possible cards to be used in your system, this may or may not be a big worry for you. If it is a big worry, you may want to use the actual memory on the RFID chips to store your user's ID data.
Regarding HEX versus numbers -- Hexadecimal is just one way to represent numbers.
Your code:
Serial.print(buffer[i], HEX);

tells the print command to take the byte at buffer[i] and print its value in Hexadecimal format. You could replace HEX by DEC to see the base-10 (decimal) value instead. The actual bits underneath would be the same -- it's just one way to display/represent the underlying number.
One byte (8 bits) of data can be represented in decimal as the numbers 0 through 255. The same byte can be represented in Hexadecimal as 0x00 through 0xFF. ('0x' is one way to denote that what follows are hexadecimal values.) Each 'digit' in hex represents 4 bits of data (0-15 in decimal), so 2 hex digits can represent 16^2 values (256 decimal), hence 0-255 as the 1-byte range of decimal values.
(That explanation assumes un-signed types.)

After converting HEX to DEC in the code I get this value 75 201 248 102. So can I transfer this value to the database and consider as a unique value? My project is for education purpose I have 9 cards and 2 tags I only want this 10 to have unique identity that's it.

You can store the value as integer, HEX, DEC, string -- the UID of the card can generally be considered unique and all you are doing is comparing if the UID that is read from the card exists in the database or not. Yes, you can consider the UID in Decimal representation to be unique for your case.

Thanks for the idea to get value in decimal it will be very for me to play with RFID now. Now I have to do is append the values in a variable and push the data to database. Thanks for giving your valuable time.


text:
Triggering actions in Android smartphone via Bluetooth from Arduino
Am working on a wearable using Arduino Micro and I am thinking it would be cool if I can trigger some events in my smartphone using Arduino. Say for example a button press in my wearable should trigger events like opening music player, reducing/increasing volume or opening some Android Apps.
Sorry for providing just a rough view of the idea. So I want to know to perform similar actions listed above, Do I need to create a Android app for it? I don't find any readymade app that fits my requirement. Or Is there any feasible way to achieve what I need without having to break my head with Android developing?
Thanks in advance.

Been there, done that. You have to learn how to program Android. And keep your development environment updated (zillion of MB each time). And Android is ... peculiar ... you rotate your phone and your app restart. And Google change things every other weeks. Things like that. Arduino is stable.

So it's going to be one tough road isn't it? Any advice on where to get started or which IDE I should choose. Any tips ? :-P

Here is where I learnt Java: https://docs.oracle.com/javase/tutorial/.

For the volume there are standard Media Control bluetooth commands. The simplest way of doing those may be to hack wires into a cheap Media Keys BLE device ($5 or so on eBay).

@Majenko Any link to those commands ?


text:
Using Multiple identical sensors - Beginner
I'm trying to make an interactive installation where I have 6 pressure pads that each control an Air Fan. The pressure sensors ideally will be on chairs.
I would like the changes in pressure to change the speed of the Air Fans.
What is the easiest way for me to do this? Can I do it with just an Arduino?
I haven't bought anything yet as I'm assessing what the best route is.

If you have selected the pressure sensor, please provide details about it -- the type/model affects how this question could be answered.

well i'm not entirely sure what's best but I was thinking just a PM1?

When you say PM1, do you mean a pressure pad, something like this?

yeah that's what i was thinking

In order to better focus your question and generate useful answers, I suggest you edit your question and include that information.   Try to make your question Arduino-specific, and show what you are working with.

Yes one Arduino have enough in and out-put to make your project fly.
The sensor that would detect pressure sensor is called "Force Sensitive Resistor".
Example: http://www.ladyada.net/make/midisense/forcesensors.html
They need some amplifier circuitry that could adapt the sensors low output signal to an Arduino analog input.
And to make six digital output that uses PWM to control the FAN's is also quite straight forward. but may also be subject to some driver circuit.

If you mean this kind of sensor:
The sensor is a simple microswitch with mechanical pressure switching point, which means your Arduino just needs to monitor 6 digital inputs. That is entirely possible.
The sensors would have one side connected to ground, and the other to a GPIO pin on the Arduino, with a pull-up resistor to 5V. Your code should just check each of the 6 GPIO inputs. If the pressure sensor is tripped, the input would be LOW, otherwise HIGH.

This indicate "I would like the changes in pressure to change the speed of the Air Fans." that the OP is asking for an analog answer.

What is the easiest way for me to do this?

you have to figure out how those sensors output their pressure measurements. if it is analog, you will need 6 analog pins, or have to a way to mux 6 analog inputs.
if it is digital, you will have to figure out how - 6 parallel output or 6 serial output; 6 GPIO digital or 6 numerical digital, ......
basically, do your homework first so others can help you help you.


text:
Breaking out of while loop using IR remote input
I'm trying to control a series of LEDs using an IR remote. I have a problem when I try to play a sequence with the LEDs where they all light up in a line and turn off accordingly. I loop through the sequence and I am trying to make it so the instant I press a button on the remote it breaks out of that sequence. The issue lies in the Flash(); function, I think. What can I do?
#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

int recvPin = 11;
IRrecv irrecv(recvPin);
decode_results results;

#define BUTTON_ON 0xF076C13B    // codes for different buttons on the remote
#define BUTTON_OFF 0xFF9186B7
#define BUTTON_R 0xE5CFBD7F
#define BUTTON_G 0x8C22657B
#define BUTTON_B 0x2A89195F
#define BUTTON_FLASH 0x35A9425F

int rLED = 5;
int gLED = 4;
int bLED = 3;
int stR = LOW;  // intital state of red LED
int stG = LOW;  // intital state of green LED
int stB = LOW;  // initial state of blue LED
int flash = false;

void setup() {
  Serial.begin(9600);   // Status message will be sent to PC at 9600 baud
  pinMode(rLED, OUTPUT);
  pinMode(gLED, OUTPUT);
  pinMode(bLED, OUTPUT);

  irrecv.enableIRIn();
}

void Flash() {    // flashing function
  while (flash == false) {
    digitalWrite(rLED, LOW);
    digitalWrite(gLED, LOW);
    digitalWrite(bLED, LOW);
    digitalWrite(rLED, HIGH);
    delay(75);
    digitalWrite(gLED, HIGH);
    delay(75);
    digitalWrite(bLED, HIGH);
    delay(75);
    digitalWrite(rLED, LOW);
    delay(75);
    digitalWrite(gLED, LOW);
    delay(75);
    digitalWrite(bLED, LOW);
    delay(75);
    stR = LOW;
    stG = LOW;
    stB = LOW;
    if (results.value == BUTTON_OFF)    // attempting to make it so when i press the OFF button on the remote,
    {                                   // the loop breaks/stops and I can go back to pressing any button on
      break;                            // the remote
    }
  }
}

void loop() {
  if (irrecv.decode(&results))
  {
    if (results.value == BUTTON_ON)
    {
      digitalWrite(rLED, HIGH);
      digitalWrite(gLED, HIGH);
      digitalWrite(bLED, HIGH);
      stR = HIGH;
      stG = HIGH;
      stB = HIGH;
    }
    if (results.value == BUTTON_OFF)
    {
      digitalWrite(rLED, LOW);
      digitalWrite(gLED, LOW);
      digitalWrite(bLED, LOW);
      stR = LOW;
      stG = LOW;
      stB = LOW;
    }
    if (results.value == BUTTON_R)
    {
      digitalWrite(rLED, !stR);
      stR = !stR;
    }
    if (results.value == BUTTON_G)
    {
      digitalWrite(gLED, !stG);
      stG = !stG;
    }
    if (results.value == BUTTON_B)
    {
      digitalWrite(bLED, !stB);
      stB = !stB;
    }
    if (results.value == BUTTON_FLASH)
    {
      Flash();    // calling flash func
    }
    irrecv.resume();
  }
}

Replace delay with millis in Flash().
You do this by making every delay it's own state and give each state a number. Then inside flash you check which state you are in to set the LEDs and how long you have been in it to trigger the next state.
boolean flashing = false;
int flashingState = -1;
long nextFlashingState = 0;

void Flash() {    // flashing function
  if(!flashing ){
    flashingState =-1;
    return;
  }

  long ms = millis();
  switch(flashingState ){
  case -1:
    flashingState =0;
    nextflashingState = ms+75; //init "timer"
    //fallthrough
  case 0:
    digitalWrite(rLED, LOW);
    digitalWrite(gLED, LOW);
    digitalWrite(bLED, LOW);
    digitalWrite(rLED, HIGH);
    if(nextflashingState < ms){
        flashingState =1;
        nextflashingState +=75;
    }
    break;
 case 1:
    digitalWrite(gLED, HIGH);
    if(nextflashingState < ms){
        flashingState = 2;
        nextflashingState +=75;
    }
    break;
 case 2:
    digitalWrite(bLED, HIGH);
    if(nextflashingState < ms){
        flashingState = 3;
        nextflashingState +=75;
    }
    break;
  case 3:
    digitalWrite(rLED, LOW);
    if(nextflashingState < ms){
        flashingState = 4;
        nextflashingState +=75;
    }
    break;
  case 4:
    digitalWrite(gLED, LOW);
    if(nextflashingState < ms){
        flashingState = 5;
        nextflashingState +=75;
    }
    break;
  case 5:
    digitalWrite(bLED, LOW);
    if(nextflashingState < ms){
        flashingState = 0;
        nextflashingState +=75;
    }
    break;
  }
}

I used state -1 as the init state to start the timer, the case block will fall through to the next case. The millis() function returns the number of milliseconds since the arduino booted up (it overflows every ~1.5 months). So when I start a timer I set the the nextFlashingState to the time when it should start the next state.
Then in loop you call it every time.
void loop() {
  if (irrecv.decode(&results))
  {
    if (results.value == BUTTON_ON)
    {
      digitalWrite(rLED, HIGH);
      digitalWrite(gLED, HIGH);
      digitalWrite(bLED, HIGH);
      stR = HIGH;
      stG = HIGH;
      stB = HIGH;
    }
    if (results.value == BUTTON_OFF)
    {
        flashing =false;
      digitalWrite(rLED, LOW);
      digitalWrite(gLED, LOW);
      digitalWrite(bLED, LOW);
      stR = LOW;
      stG = LOW;
      stB = LOW;
    }
    if (results.value == BUTTON_R)
    {
      digitalWrite(rLED, !stR);
      stR = !stR;
    }
    if (results.value == BUTTON_G)
    {
      digitalWrite(gLED, !stG);
      stG = !stG;
    }
    if (results.value == BUTTON_B)
    {
      digitalWrite(bLED, !stB);
      stB = !stB;
    }
    if (results.value == BUTTON_FLASH)
    {
        flashing =true;
    }
    irrecv.resume();
  }

  Flash();
}

Thanks for the answer! I don't really understand your code, however, I uploaded it and it doesn't seem to do what I wanted it to do. When I press the flash button on the remote, it still flashes endlessly, but now when I press something on the remote the lights do kinda respond to it but keep flashing endlessly.

it will stop flashing when you press off. If you add flashing =false; to the other if blocks then flashing will stop when that button is pressed

Alright, thanks, it works! I wonder how I will make it work with more complicated sequences but for now I do wanna understand what you did there in the void Flash() function and anything else you added cause I am a beginner and if you could possibly refer me to some website where I can learn more about this I would greatly appreciate it :)

@EdD I edited my answer to explain a bit how you would go about replacing delay with millis


text:
Midi Timecode Fails to Send
I have an ATMEGA 2560 platform running HIDUINO and a sketch based on the stock MIDI library. I'm intending to use it to convert Linear Timecode (LTC) to MTC. Got a long way through the project - LTC decoding working fine, timer configuration OK, and Midi output working fine. It's just that as soon as I try and generate MTC messages, they are being dropped before they land on the computer USB interface.
Equipment to hand: Macbook Pro running El Cap/Reaper and Protools., ATMEGA2560 MEGA R3 (With 16u2 for HIDUINO) and small audio interface circuit.
Using Timer 4 for LTC Decoding and Timer 5 for MTC generation (4 messages per LTC Frame).
Midi Monitor on the OSX box.
Sees Note on/Note off packets quite happily, but no MTC messages are registering.
I do note the TX LED is active during MTC Message generation, indicating that the sketch is actually generating messages and sending them to the 16u2 chip.
Specifically, my question is how do I get the MTC messages through HIDUINO into the computer?
https://pastebin.com/pAXyq04s

The code should be included inside the post, not via a link.

The HIDUINO library supports only some MIDI message correctly; most System Common and System Real-Time message are buggy, and SysEx messages are not handled at all.
Try some other library, e.g., mocoLUFA.

Already there. sysEx much better in mocoLUFA but still no System Common. Working on modding mocoLUFA as we speak.

If you clone my fork of the code, I have got this working.
https://github.com/mwr9uk/mocolufa
I have generated a pull request to merge it with mainline.

Is this really an answer?  Please add some more explanation

Yes. The OP experienced the problem of MTC messages not being passed through Hiduino. A subsequent poster suggested using MocoLUFA which also doesn't pass System Common messages, including MTC. I have added that support in a fork in the code of MocoLUFA as I needed it too. This will solve the OP's problem.


text:
Bluetooth HM-10 in central mode bonding with another bluetooth device
I have a bluetooth HM-10 configured in central mode. I have successfully connected it to another bluetooth device (a hexiwear bluetooth wearable). The problem now is that the hexiwear requires me to provide a 6 digit pin before it will bond with my HM-10.
Would anyone know the AT command that I could use to send the 6 digit pin from the HM-10 to the hexiwear?
Thank you.

The manual for the HM-10 can be found here.
Page 11 has the AT command you are interested in: AT+PIN:
AT+PIN123456
OK+Set:123456

By default the PIN is 000000.
(The manual is quite vague about the role of that command, so I assume since it is the only reference to PIN codes that it does what you require).

Thanks for the response. APIN command sets the PIN for the HM-10. My HM-10 is running central mode and I am trying to connect to a hexiwear (www.hexiwear.com) in peripheral mode. I am able to connect the hexiwear by sending AT+CON. After successful connection, the hexiwear pops up a 6 digit pin that I am required to now send from the HM-10. This is where I am stuck because I do not know if there's a AT command that lets me send a pin from central to peripheral.

Have you tried setting both devices to use the same pin?

Not yet, this requires me to hack my peripheral device because the pin it sends is a random number. But I will hack it and report back again soon. Thank you.


text:
Broadcasting parallel data from Arduino using router
I'm looking to read data from sensors using an ArduinoUNO in a greenhouse and then access the data wirelessly through a router. Hopefully through a webpage. No need for internet access, just local network access is good enough.
Preferably the only components involved would be the Arduino, the circuit, and a router with OpenWRT/DD-WRT to host the webpage and broadcast the network.
Pretty new to Arduinos in general, would this be possible? And how? The following 2 links from instructables.com seem to be the most relevant, can anyone give their input on how similar/different is this to my project?
http://www.instructables.com/id/PART-1-Send-Arduino-data-to-the-Web-PHP-MySQL-D3js/
http://www.instructables.com/id/Getting-Arduino-data-to-a-web-Page/

with an esp8266 you can run them as hotspots, no need for a router. otherwise, the router will be the same as any other wifi-providing box that happens to have a downed internet connection; p2p/lan use is still fine

Would the esp8266 allow me to host a web page on it?

yes, there's several ways to serve an html page from the esp, mere string building for example. the SPIFFS file web server makes it simple to host static assets, and you can make a quick API from just a few lines of C. fwiw, i've had much better luck pulling data from an esp webserver than with always-on connections like websockets or mqtt, likely because a web server does nothing while waiting, which uses no resources like bandwidth and power

Use a NodeMCU (ESP8266 based) because it have WiFi included. It can work as a light web server. You can serve HTML, but not large files (like many .js).
Instead of HTML you can use websockets to get only data from NodeMCU and all the other files (html, js, images) from another bigger server. Websockets is fast, but you still have to deal with .html, .css, .js and other files in your webserver.
If you want something even easier and lighter, take a look at MQTT, which was developed with IoT in mind.
There is lot of MQTT client for Android/Iphone/PC/Mac. You use your client to send data and commands to your NodeMCU. No need to program anything here; you simply construct a visual interface by adding controls (buttons, meters) to a blank slate. No brains job.
You will need a broker, a server that acts as a relay, receiving commands/data from your Android and resending it to your NodeMCU. And your NodeMCU can publish temp, humidity, light levels and other data to your broker. You can use multiple client at once. There is no limit.
Your broker can be an public Internet broker (many) or a private one in your LAN. There is many brokers available for different platforms. You can run one in your smartphone or any old PC. Mosquitto is a free one.
Depending on your configuration, you will be even able to access your green house from Internet and look at your girls from far away.


text:
PWM output maximum current
i made a project with arduino in wich I used arduino to activate 18 n-ch mosfet with PWM. I used the softPWM library to use PWM in 18 output pins, I used a nano v3.
The question is about the maximum current a single pin (and a group) can handle. A raw info can be found here http://www.pighixxx.com/test/wp-content/uploads/2014/11/nano.png and it's a 20mA/pin and 200mA/group but it's not explained if that current is a peak current or an average current.
Increasing the load resistor will case a smaller peak current but will increase the time in wich the mosfet is resistive (hence it will heat up the mosfet). Considering that the pwm frequency is lower than the one defined by the resistor-mosfet, the average drained current is related to the PWM frequency and to the mosfet capacitor (NOT to the load resistor).
Is the current defined as maximum peak current or as continuous current (and which is a typical peak time for the CPU)?
Mr google gives me different and contradictory informations, i found people that uses PWM without load resistors and people that limit the peak current to 20mA. In my project i limited the maximum current to 50mA so I'm sure to have the worst performance i can have keeping the risk of burning my small friend.
Thanks

What is the PWM frequency? If it's quite small, you can afford that, for a certain amount of time, the MOSFET is not fully ON/OFF.

I set a 250Hz frequency to trimmer leds and a 256 resolution hence the load must be faster than 15us. I used an IRLZ44N (1700pF) that with a resistor of 100ohm means a tau=1.7E-7s that is 90times less than the previous one. If I use a 330ohm resistor the value is 26times less. Note that 250Hz is the minimum to avoid flickering

If we were talking about DACs, a DNL error <1/4 LSB would be good for many applications. We can use a similar thinking here. You want the turn-on+turn-off faster than 15us. Let's suppose 4 times faster (similar error of the DAC example). So you can increase the resistors accordingly. The problem is, the slower the transition, the larger the power dissipated. Even if half the LED power were dissipated on the MOSFETs during the 15/4 us transition, the average power dissipation on the MOSFET would be 1/2048 of that of the LED (+Ron*I^2). It's up to you to decide if it's acceptable.

if you're using mosfets, the supply capability of the gpio isn't important. you would still have actual spikes of 50, but the accumulated heat would be that of only 20ma on avg

@dandavis That's the point of the question: could i have a spike of 200mA to charge the 1700pF or not? Higher the current shorter the time, if it's all related to heating the resistor should not matter. But is it true? Can i load a 8uF capacitor with a 250Hz PWM? (8uF -> 40uC -> 0.02C/s -> 20mA)


text:
Advice on cabling, packaging and connectors for 12v light project
My project is to have a 12V solar LED strip lighting system throughout my apartment. This has 6 individual lights, with 5 white and 1 RGB = 8 channels.
I've got the whole setup working on my breadboard. Now it's time to transfer it to a "live" setup. Since it's my first such project, I'm looking for any and all recommendations on cabling and connectors to deal with reliability, isolation, modularity, aesthetics and of course safety.
Schematically, it all looks something like this
solar panel------\
                  charge controller--5v regulator--arduino--mosfets x 8--\__lights
12v battery_fuse_/                  \____________________________________/

So I have questions such as:-

should I use a prototype shield, or a discrete pcb?
do the MOSFETs (RFP30N06LE) need a heatsink, and any recommended unit?
what connectors are recommended?
any suggestions on box/packaging for the above?
wire gauge? Maximum run is 4m to the furthest light.

And any other hints, tips and suggestions greatly appreciated. Bonus appreciation for amazon links to the parts :-)
update
The breadboard is simply the mosfets, each with a current limiting resistor on the gate. The lights range from 8W to 40W. I will generally have them dimmed using PWM.

Can you share what you have on the breadboard, and particulars about the current draw, etc?  Those are the kinds of details you'll need to attract useful answers.

if the proto board isn't warm it's fine if not mobile. 2. not unless way under-driven or over-loaded (small binder clips can double TO220's dissipation) 3. "terminal connectors" or solder. 4. dollar-store decorative box/container/lunchbox, or box-store outlet box 5. 18AWG or lower (thicker) is fine; aka "alarm", "doorbell", "speaker", "18/2"

@SDsolar question updated. thx

generic DC connector advice:
avoid the use of connectors which connect serially, like headphone jacks. you make strange combinations while plugging in
avoid connectors which do not latch, like headphone jacks
in a system like yours, with stages and signal processing in between, use different connectors for each phase, so you can not get it wrong
use connectors that can not be connected backwards for DC. I prefer:
Hopkins 47965 2-Pole Flat Extension for raw solar power.Not because    it's a great connector, but because it's common in low power solar

Anderson Power Poles for regulated DC power. you can secure them
together with a tie wrap; you can't connect them backwards without
doing things that are obviously counter intuitive.
Fuel injection    connectors from Autozone for signal wires. they got
a million of    them, they are made for DC at useful current levels
Trailer    connectors for multiple lead serious power.
XLR connectors can be    found from 3 to 6 pins, and you can't jam a
5 pin into a 6 pin, so    you can't cross connnect

keep things dummy proof.


text:
Arduino 101 accelerometer drift or calculation error?
I want to calculate the displacement of the Arduino 101 board compared to the starting point (only in the x direction so far).
In below data I'm swinging the board multiple times in circles around my laptop and then putting it back at the origin a few seconds later.
Regardless if 1ms-100ms between the loops, the numbers show no sign of the board returning to the origin. I've calibrated the accelerometer x-axis as closely as possible.

Am I doing something wrong in deriving the acceleration/velocity/distance, or is this the level of compounding error to expect?
If so, can combining gyro data correct acceleration (thought it mainly worked the other way around)?
I have a GPS meant for correcting position but was hoping any drift wouldn't be this quick.
EDIT: I was incorrect re. use of gyro data; the attitude of the board, which was not consistent in my swings, will effect the acceleration output. Gyro data can be used to calculate and "cancel out" this gravitational impact, and get a more accurate (linear) acceleration (http://www.cl.cam.ac.uk/research/dtg/www/files/publications/public/abr28/ojw28_thesis.pdf). Will report back in a few days.
Code:
#include "CurieIMU.h"

float gravity = 9.80665; // to convert G forces (1 m/s2 = 0.101972 g; 1 g = 9.80665 m/s2)
long t1; // create object for first time reference, set time just before the loop later on

// Variables that are dependent on value from last loop
float vx, vy, vz;
float imu_x, imu_y, imu_z;

void setup() {
  Serial.begin(9600);
  while (!Serial);  // wait for serial to open

  Serial.println("Initializing IMU device...");
  CurieIMU.begin(); // start accelerometer / gyro
  CurieIMU.setAccelerometerRange(2);  // accelerometer range to 2G - might need to be greater later on (18 m/s2 highest possible now)

  /*

  // Auto-calibration to ensure accelerometer doesn't drift
  CurieIMU.autoCalibrateAccelerometerOffset(X_AXIS, 0); // 89.69999 creates both positive and negative spikes
  delay(1000);
  CurieIMU.autoCalibrateAccelerometerOffset(Y_AXIS, 0);
  delay(1000);
  CurieIMU.autoCalibrateAccelerometerOffset(Z_AXIS, 1);
  delay(1000);

  */

  // Hardcoded accelerometer offsets after testing
  CurieIMU.setAccelerometerOffset(X_AXIS,89);

  // Fetch the offsets from the IMU
  float x_offset = CurieIMU.getAccelerometerOffset(X_AXIS);
  float y_offset = CurieIMU.getAccelerometerOffset(Y_AXIS);
  float z_offset = CurieIMU.getAccelerometerOffset(Z_AXIS);

  Serial.println("Current x_offset, y offset, z offset");
  Serial.print(x_offset, 6);
  Serial.print("\t");
  Serial.print(y_offset, 6);
  Serial.print("\t");
  Serial.println(z_offset, 6);
  delay(5000);

  t1 = millis(); // set the first time reference

  Serial.println("ax_g (g), ax (m/s2), t1 (ms), t2 (ms), td (ms), tds (s), vx (m/s), imu_posx (m)");

}

void loop() {

  // Fetch G forces
  float ax_g, ay_g, az_g;   //scaled accelerometer values
  CurieIMU.readAccelerometerScaled(ax_g, ay_g, az_g); // read accelerometer measurements from device, scaled to the configured range

  // Convert G force to m/s2
  float ax = ax_g / gravity;
  float ay = ay_g / gravity;
  float az = az_g / gravity;

  // Calculate time since last loop
  long t2 = millis();
  float td = t2 - t1; // time delta in ms
  float tds = td / 1000; // delta in seconds for easier logic

  // Calculate current velocity: velocity (m/s) = velocity (m/s) + acceleration (m/s2) * deltaTime (s)
  vx = vx + ax * tds;
  vy = vy + ay * tds;
  vz = vz + az * tds;

  // Calculate position: position (m) = position (m) + velocity (m/s) * deltaTime (s)
  imu_x = imu_x + vx * tds;
  imu_y = imu_y + vy * tds;
  imu_z = imu_z + vz * tds;

  // Print the values
  Serial.print(ax_g, 6);
  Serial.print("\t");
  Serial.print(ax, 6);
  Serial.print("\t");
  Serial.print(t1);
  Serial.print("\t");
  Serial.print(t2);
  Serial.print("\t");
  Serial.print(td, 6);
  Serial.print("\t");
  Serial.print(tds, 6);
  Serial.print("\t");
  Serial.print(vx, 6);
  Serial.print("\t");
  Serial.println(imu_x, 6);

  // Reset start values for next loop
  t1 = millis();

  delay(1);

}

I don't think millis is going to be accurate enough, try micros instead and grab it only once per loop.

This is dead reckoning and is very difficult.  When (few) cars do this (after loosing their GPS signal) they usually count the number of wheel rotations and turning direction.  Just consider if you stopped moving your Arduino.  Then your acceleration would go to zero but your integral calculation of velocity may not due to noise or round off error.  If this happens, the integral of  your velocity (position) would continue to change.

@ratchetfreak thanks, will try in combination with the edited conclusion above

Do you have to use 9600 baud?  That's quite slow, and is probably introducing 70ms of that 100ms delay.  Why not use 115200?  Also, did you try using doubles instead of floats - although I guess this would only help with minor drifts.

The Arduino 101 contains the Intel® Curie™ Module, this module contains an Inertial Measurements Unit or IMU for short among other sensors and peripherals
The IMU of this module is Bosch BMI160 which is a low cost MEMS IMU, this IMUs typically suffer from systematic errors and random/stochastic errors, the following diagram summarize them:

If we take the bias error as an example of those errors, an uncompensated accelerometer bias introduces an error proportional to time (t) in the velocity and proportional to t^2 in the position. For example, consider a case where accelerometer bias is 10 m/s^2. If this bias offset is not removed from the measurements, it can generate a 500 m error in position after 10 seconds and 12.5 km error after 50 seconds. Let us back to our IMU, if we read the data sheet the Zero-g error "or bias" is 40mg for the 8g sensing accelerometer and Ta = 25 Celsius with normal VDD and the IC has been assembled on board. If we just consider this 40mg bias error "dropping other error sources" it is 0.392266 m/s^2 so after 10 seconds the position offset will be 1.96133 meter even if you don't move the Arduino.
I suggest you read "MEMS-Based Integrated Navigation" book here it will give you a good vision about MEMS based inertial sensors and basic navigation concepts.


text:
How to flash/blink I2C LCD backlight without delay function?
Since I am an using I2C LCD backpack, I'm unable to call in for pinmode to set variables like #define BACKLIGHT_PIN 13. I know lcd.setBacklight(HIGH); and lcd.setBacklight(LOW); controls the I2C LCD backlight, but if I use delay in the loop it slows down the whole loop.
How do I flicker the LCD backlight without using delay? I tried for example to blink without delay, but I don't know how to assign a global variable to lcd.setbacklight so as to control it.
I want to use an if statement to warn the user that so and so has happened, eg:
#include <Ticker.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

//Ticker flashBacklight(toggleBacklight, 100);
// when I use ticker here am getting not declared in scope
const int buttonPin = 3;
int buttonState = 0;
// pls declare flashBacklight, long flashBacklight = 100; ??
// pls declare toggleBacklight

void toggleBacklight() {
  // lcd.setBacklight(!lcd.getBacklight());
  // !lcd.getbacklight() spelling mistake ? or it is setbacklight?
}

void setup() {
  lcd.begin(20, 4);
  lcd.setBacklight(HIGH);
  pinMode(buttonPin, INPUT);
 }

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    // if button goes high the back light must keep on flashing until it's released
    flashBacklight.start();
    //flash the lcd backlight
  } else {
    flashBacklight.stop(); // Stop flashing the backlight
  }
  flashBlacklight.update();
}

But delay slows down the whole loop, so how do I flash the backlight without it? Thank you.

Besides the standard 'compute a target millis() and compare' standard, which can get clunky when you have to handle more than 1 repeating or delayed event, there are also more than one decent library that abstract the concept, but also add features.
One example is the Ticker library.
With these methods, you create a callback function and pass that function name into the object constructor, along with the timing parameters.
So you might:
[various #include, #define, etc.]

Ticker flashBacklight(toggleBacklight, 100); //call toggleBacklight() every 100ms

// Create the callback function, which just toggles the backlight each call.
void toggleBacklight() {
  lcd.setBacklight( !lcd.getBacklight() );
}

setup() {
  [...]
}

loop() {
  // Start or stop the ticker based on your own situation. Once started, it will call your callback function at the specified interval until stopped.

  if (warningSituation) {
    flashBacklight.start();
  } else {
    flashBacklight.stop();
  }

  flashBlacklight.update();
}

Another related library is SimpleTimer
EDIT
Your code example, updated:
#include <Ticker.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void toggleBacklight();

Ticker flashBacklight(toggleBacklight, 100); //when i use ticker here am getting not declared in scope

const int buttonPin = 3;
int buttonState = 0;
                      // pls declare   flashBacklight   , long flashBacklight = 100;   ??
                      //   pls declare toggleBacklight

void toggleBacklight() {
 // lcd.setBacklight( !lcd.getBacklight() );  // !lcd.getbacklight() spelling mistake ? or it is setbacklight?
}
void setup() {
   lcd.begin(20, 4);
 lcd.setBacklight(HIGH);
 pinMode(buttonPin, INPUT);
 }
void loop() {
      buttonState = digitalRead(buttonPin);
   if (buttonState == HIGH)          // if button goes high the back light must keep on flashing untill its released
   {
    flashBacklight.start();          //flash the lcd backlight
  } else {
    flashBacklight.stop();           // Stop flashing the backligh
 }
   flashBacklight.update();
  }

can you show me a example of flashing with button press example ? am getting compiler error "not declared in the scope " so if u can show me   its complete usage it would be easy for me to learn , i want to put the code here,but if i do it exceed character left, how to put the code here?

I linked to the Ticker library -- it has an example of how to use it. If you are using Arduino IDE, you will need to install the library, and #include it's header file. If you want to put a big block of code in, you can edit your original question, I believe.

oh.. ty library and all those installed correct,problem is global variable declaration..pls check the original question and pls help fill the gaps ..ty

Yes sir, its global variable declaration.. pls see the above update code...

You should move the flashBacklight function definition to before the Ticker Use. I will update my example soon. I don’t know which LCD library you are using. At least one has getBacklight(), but if yours doesn’t, you can keep track in another global.

am using lcd library by  F. Malpartida , and yes i think it dosent have getBackligh() , i had preveiously   "class LiquidCrystal_I2C' has no member named 'getBacklight'" compiler error...

You will need to alter the pin / bit tied to the backlight led.
To do that you will need to be able to read the state of all the pins on the i2c expander.
That can be done by reading back the pin state from the i2c expander or to hold the pin state in a buffer.
Once you know the pin state, you can OR or NEG it to clear or set the pin.

well, this is easy method reading the state of A and k On the lcd pin, but wish to learn by using i2c and also saves digital pin, as of now every pins on my uno is used and nothing to spare :( ....

" nothing to spare" - in that case, the answer is simple. you essentially want to change the state of a pin without having a pin connected to it.

with that said, you can re-use one of the lcd pins, recognizing that those pins' state is only used when the state of the EN pin is going through a state change. So any other times, you can change the other pines freely without messing up the lcd display.

ok ok, i under stood your point, for instance i define  #define BACKLIGHT_PIN 2 when warning triggers pin A goes high and low , if i keep the pin A which is connected to digital pin 2 and digital write (2,high) and Low i can control its backlight, this way i must keep the pin connected always right? now from i2c point of view, lcd.setBacklight(HIGH);  sets backlight high, how do i declare lcd.setBacklight(HIGH);  to global variable and control it?

You record the timestamp when you want the LED to turn off again and then check that against millis in the loop()
  if ( level 1 > level 0)
  {

     NewTone(4,1000,50); // initiate alarm
     blinking = true;
     lcd.setBacklight(HIGH);
     lcdToggleTime = millis();// this is a global
     lcdOn = true;
  }else {
     blinking = false;
     lcd.setBacklight(LOW);
  }

  //at the start or end of loop(); make sure it's always checked.
if(blinking){
      if(millis() - lcdToggleTime>+100) {
         if(lcdOn)
             lcd.setBacklight(LOW);
         else
             lcd.setBacklight(HIGH);
         lcdOn = !lcdOn;
         lcdToggleTime = millis();// this is a global
     }
}

The background should turn on and off and on and off... just like the blink-without-delay example. When a value is added to millis(), then the rollover problem is introduced. See the blink-without-delay how to use millis(): https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

@jot fixed the code

if (millis() > lcdToggleTime) will not work properly across a
millis() rollover. The “Blink without delay” tutorial uses the idiom
if (millis() - lcdLastToggle > 100), which is rollover-safe.


text:
How to keep a 24 hour maximum and minimum temperature
I am keeping a simple weather station to monitor humidity and temperature in my greenhouse. I have a ds18b20 and dht probes.  everything works great and I even used a little trick to hold my maximum and minimum values, but I would like them to reset every 24 hours. Is there anyway i can code the arduino to reset itself. i tried several examples of connecting digital pins to the reset pin and i couldn't get any of those to work.  i tried to reset the values of my max and min to 0 and 99 respectively after my millis() reached the equivalent of a day, but they just stuck at 0 and 999. I understand fully why it does this i just don't know how to fix it. all i want to do is reset my minimum and maximum temperatures after 24 hours.
//       Green HAUS Version 1 by Kent Scipione 9/3/2017
//       Monitors temperature and humidity
long timenow;
long day = 86400000; // 86400000 milliseconds in a day
long hour = 3600000; // 3600000 milliseconds in an hour
long minute = 60000; // 60000 milliseconds in a minute
long second =  1000; // 1000 milliseconds in a second

#include <OneWire.h>
#include <DallasTemperature.h>
#include <SPI.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
#define ONE_WIRE_BUS 10
double temp;  // sensor is precise to .1 degree.
//Double gives smoother serial graph, byte doesn't overflow oled screen
Adafruit_SSD1306 display(OLED_RESET);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

#include <Adafruit_Sensor.h>
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

int maxtemp=0;
int mintemp=999;

void setup() {

  Serial.begin(9600);
  Serial.println("green HAUS Version 1 by Kent Scipione 9/3/2017");
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.display();
  display.setTextColor(WHITE);
  sensors.begin();
  dht.begin();

}

void loop() {
  timenow = millis();
  sensors.requestTemperatures();
  temp = sensors.getTempFByIndex(0);
  int humid = dht.readHumidity();
  float dtemp = dht.readTemperature(true);
  if (temp > maxtemp) {
    maxtemp=temp; }
  if (temp < mintemp) {
    mintemp=temp; }

  if (timenow >= day){
      digitalWrite(4, HIGH);
      pinMode(4, OUTPUT);       //*************************this is the part where I'm trying to reset the mintemp and maxtemp**********

    }

  Serial.print("Probe Temperature: ");
  Serial.println(temp); Serial.println("*F");
  display.setCursor(0,0);  //refreshes display
  display.clearDisplay();
  display.setTextSize(1); display.print("Probe "); display.println(temp);  //line 1 of text
  display.print("DHT  "); display.print(dtemp); display.print("  "); display.print(humid); display.println(" %");  //line 2 of text
  display.print("HIGH "); display.println(maxtemp);           //line 3 of text
  display.print("LOW  "); display.println(mintemp);   //line 4 of text
  display.display();

}

Thank you so much for your help this is driving me mad haha

At first glance, a small typo in your reset section -- you have set the pinMode to OUTPUT after you try to write. You should call pinMode() before you try to call digitalWrite().

if(millis()>day) ...

Consider using #define for your constants day,hour, minutes, seconds rather than variables. While on the subject.... if you're not going to keep decimals for your temperatures then you can use byte (or unsigned byte depending on if you'd ever have negative degrees F) rather than int for your min,max and current temperatures saving a few more bytes. Finally dtemp isn't used so you can delete that line.

You should also keep a timestamp of the last time you reset the min and max otherwise the arduino will keep thinking it's a new day:
//add to globals
unsigned long lastDay = 0;

and inside loop()
  if (timenow-lastday >= day){

      maxtemp=0;
      mintemp=999;
      lastDay = timenow;
  }

unsigned long. long will fail after about 25 days.

But when it rolls over it will still work correctly so it doesn't matter that much

You'll find unsigned long rolls over ok when compared to another unsigned long that's rolled over. A signed long won't when compared to an unsigned long in the >= comparison in the if loop.


text:
Allocation, initialization and scope
I realized I don't fully understand how Arduino code handles variable lifetime. My tendency is to keep variables in the narrowest scope (which I realize isn't as important in Arduino code, but, habits...). But how inefficient is this?
Given these possible variations:
 const int c1 = 2, c2 = 7, c3 = 9;

 void functy();

 int foo[3] = {c1 | c2, c3, c2 | c3};

 static int foo[3] = {c1 | c2, c3, c2 | c3};

 const int foo[3] = {c1 | c2, c3, c2 | c3};

  ....

In case 1, foo is both allocated and initialized each call.
In case 2, foo is allocated only once, but is it initialized on each call?
In case 3 I assume that allocation and initialization are done only once? Is that true?

Here's a pretty definitive list for you:
// Allocated once in the global area and assigned during
// program startup
int foo = 1;

// May not even be allocated - the compiler will most likely
// optimise it out.
const int foo = 1;

// Allocated once and assigned during program startup. Cannot be
// accessed from outside the file.
static int foo = 1;

// The static here has no real effect.
static const int foo = 1;

void function() {
    // Allocated in the stack each call and initialised each call.
    // Only accessible from inside this function.
    int foo = 1;

    // Allocated in the global area and initialized on the first call
    // of the function. Only accessible from inside this function.
    static int foo = 1;

    // May not be allocated at all. Only accessible from inside
    // this function.
    const int foo = 1;
}

Note that non-simple const values, things like arrays and strings, depending on the architecture (i.e., if it's a Harvard architecture or not) may be copied into a block of global RAM for simpler access. See PROGMEM in the Arduino Reference Manual for more information.

Thanks, that does seem to cover it. But in case 3 (const array) I assume the compiler can't optimize it away if later in the function the array is accessed through a passed-in variable index. In that case, is the memory allocated and initialized at compile time?

Yes. If it is PROGMEM then it is stored only in flash and special instructions are used to access it. If it's not PROGMEM it gets copied into the global ram area at boot time and that ram address is used instead.

JimMack, Arduino use gcc with LTO (Link Time Optimization), that means a further overall optimization. The Arduino Uno uses an Atmega microcontroller which has 32 registers. Although the gcc compiler does not use all those 32 registers for maximum optimization, locally declared variables might stay in registers and might not exist on the stack. I think the list by @Majenko is not "definitive" but rather "how it is supposed to work in theory".

@Jot That's pretty definitive. Pretty as in "fairly" (not totally), not pretty as in cute.


text:
Efficiency of a cast vs a shift
I'm using a supplied library which uses a number of (non-sequential) outputs to latch a multiplexer. The code looks (in part) like this:
 digitalWrite(_S0, (chan & 1));
 digitalWrite(_S1, (chan & 3)>>1);
 digitalWrite(_S2, (chan & 7)>>2);
 digitalWrite(_S3, (chan & 15)>>3);

Those masks seem a little odd, but it would work. More natural to me would be:
 digitalWrite(_S0, (chan & 1));
 digitalWrite(_S1, (chan & 2)>>1);
 digitalWrite(_S2, (chan & 4)>>2);
 digitalWrite(_S3, (chan & 8)>>3);

But overall, would it be more efficient to do this?
 digitalWrite(_S0,       (chan & 1));
 digitalWrite(_S1, (bool)(chan & 2));
 digitalWrite(_S2, (bool)(chan & 4));
 digitalWrite(_S3, (bool)(chan & 8));

...or is shifting already pretty efficient?
I've actually re-written the code to build a mask and use PORTx to latch it all at once, so this is really an academic question, but I'm still curious.

The digitalWrite calls are the slowest parts in here. It takes about 50 (or more) instruction cycles (if I remember it correctly), so few more or less cycles won't make so big difference.

@KIIV - Sure, that's why I replaced all this with an array of bitmasks and a single PORTx access. It's probably 20x faster. I was just curious about efficiency in general.

I tried compiling your three snippets with avr-gcc 4.9.2 at the -Os
optimization level (standard with Arduino) but without -flto. The
results were:

The first snippet generated inefficient code: the ands and shifts were
translated in assembly quite literally, the shifts were done on
16 bits even though chan was declared uint8_t, and the last
shift was even implemented as a loop roughly equivalent to
uint16_t tmp1 = chan & 15; uint8_t tmp2 = 3; while (--tmp2) tmp1 <<= 1;
The second and third snippets were translated identically and
efficiently, using the bst (bit store) and bld (bit load)
instructions to copy the relevant bit of chan into the second
argument of the digitalWrite() call.

Personally I would just write
digitalWrite(_S0, chan & 1);
digitalWrite(_S1, chan & 2);
digitalWrite(_S2, chan & 4);
digitalWrite(_S3, chan & 8);

as digitalWrite() expects an integer as its second argument, and it
interprets it just like the (bool) cast does. If you want to be sure
to always call digitalWrite() with either 0 (LOW) or 1 (HIGH),
then use either your second of third form. The first form seems formally
equivalent to the second, but since it is not an usual C idiom, the
compiler could not catch the optimization opportunity.

Thanks for the analysis. I can see how the (bool) cast would be redundant in this case. Also very interesting that the compiler knows 'idioms'.

If you look at the assembly code the compiler produces, you can see it compiles to the exact same thing - when using a constant.:
void setup() {
  ....
  digitalWrite(_S1, (chan & 2)>>1);
 282:   84 e0           ldi r24, 0x04   ; 4
 284:   0e 94 6b 00     call    0xd6    ; 0xd6 <digitalWrite.constprop.0>
 ....
  digitalWrite(_S1, (bool)(chan & 2));
 29a:   84 e0           ldi r24, 0x04   ; 4
 29c:   0e 94 6b 00     call    0xd6    ; 0xd6 <digitalWrite.constprop.0>

However, using a variable produces different results:
void loop() {
  digitalWrite(_S0, (chan & 1));
 2a2:   c0 91 00 01     lds r28, 0x0100 ; 0x800100 <__data_start>
 2a6:   d0 91 01 01     lds r29, 0x0101 ; 0x800101 <__data_start+0x1>
 2aa:   6c 2f           mov r22, r28
 2ac:   61 70           andi    r22, 0x01   ; 1
 2ae:   83 e0           ldi r24, 0x03   ; 3
 2b0:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S1, (chan & 2)>>1);
 2b4:   6c 2f           mov r22, r28
 2b6:   66 95           lsr r22
 2b8:   61 70           andi    r22, 0x01   ; 1
 2ba:   84 e0           ldi r24, 0x04   ; 4
 2bc:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S2, (chan & 4)>>2);
 2c0:   c2 fb           bst r28, 2
 2c2:   66 27           eor r22, r22
 2c4:   60 f9           bld r22, 0
 2c6:   85 e0           ldi r24, 0x05   ; 5
 2c8:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S3, (chan & 8)>>3);
 2cc:   c3 fb           bst r28, 3
 2ce:   66 27           eor r22, r22
 2d0:   60 f9           bld r22, 0
 2d2:   86 e0           ldi r24, 0x06   ; 6
 2d4:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>

 ....

  digitalWrite(_S0,       (chan & 1));
 2a2:   c0 91 00 01     lds r28, 0x0100 ; 0x800100 <__data_start>
 2a6:   d0 91 01 01     lds r29, 0x0101 ; 0x800101 <__data_start+0x1>
 2aa:   6c 2f           mov r22, r28
 2ac:   61 70           andi    r22, 0x01   ; 1
 2ae:   83 e0           ldi r24, 0x03   ; 3
 2b0:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S1, (bool)(chan & 2));
 2b4:   be 01           movw    r22, r28
 2b6:   76 95           lsr r23
 2b8:   67 95           ror r22
 2ba:   61 70           andi    r22, 0x01   ; 1
 2bc:   84 e0           ldi r24, 0x04   ; 4
 2be:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S2, (bool)(chan & 4));
 2c2:   be 01           movw    r22, r28
 2c4:   76 95           lsr r23
 2c6:   67 95           ror r22
 2c8:   76 95           lsr r23
 2ca:   67 95           ror r22
 2cc:   61 70           andi    r22, 0x01   ; 1
 2ce:   85 e0           ldi r24, 0x05   ; 5
 2d0:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S3, (bool)(chan & 8));
 2d4:   be 01           movw    r22, r28
 2d6:   23 e0           ldi r18, 0x03   ; 3
 2d8:   76 95           lsr r23
 2da:   67 95           ror r22
 2dc:   2a 95           dec r18
 2de:   e1 f7           brne    .-8         ; 0x2d8 <main+0xc0>
 2e0:   61 70           andi    r22, 0x01   ; 1
 2e2:   86 e0           ldi r24, 0x06   ; 6
 2e4:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>

Your test is not really significant. The compiler noticed that you were always calling digitalWrite() with 0 (i.e. LOW) as its second argument. It then generated a specialized variant of digitalWrite() that sets an output to LOW and it translated your code into something like digitalWriteLow(3); digitalWriteLow(4); digitalWriteLow(5); digitalWriteLow(6);. In order for the test to be significant, you should make sure chan is not a compile-time constant. Alternatively, compile without the -flto flag to force the compiler into creating a non-specialized translation of your code.

Sorry, I should have specified that chan is a passed-in variable. Using a constant chan would make this trivial, as you say.

@EdgarBonet Fair assessment. I did make it a const. Will update...

Your updated test is flawed again. The compiler computed chan & 2 while translating (chan & 2)>>1, and it stored this intermediate result in the r11:r10 register pair. Then, when translating (bool)(chan & 2), it used the fact that chan & 2 was already in a the register file, which made that translation shorter.

@EdgarBonet Thanks for your input. The answer turned out to be more complex than I initially assumed.


text:
Building mocoLUFA under OSX & Linux
I am attempting to build mocoLUFA under OS X el Capitan 10.11.6.
[Editor: mocoLUFA (MIDI firmware for Arduino Uno)]

I am using the specified LUFA version (LUFA101122) and I have tried building with both brew avr-gcc and also Crosspack-AVR.
The problem I am facing isn't with the build or the install. It's just that as soon as I install the hex file, I get no midi messages at all.
What does work - the OSX machine recognises the MIDI device and the MIDI device appears in DAW's, however MIDI Monitor registers no messages at all.
I have tried downloading a custom-built mocoLUFA and I am able to install this and it works fine. I see midi messages coming across from my sketch.
Crosspack-AVR installs avr-gcc 4.8.1.
My question is - what is the correct build environment in order to achieve a working mocoLUFA under OSX? I have tried both mocoLUFA and dualMoco and I get the same result with each.
My purpose for this is to modify mocoLUFA so that it can support sending MTC over USB. At present, it appears that mocoLUFA does not support System Common messages.
UPDATE: Built fresh Ubuntu VM. Installed avr-gcc, avr-libc, LUFA-100807 and mocoulfa. Same result. hex builds fine, no response from the atmega16u2. TX light flashing, sketch on the 2560 running, but no midi messages down the usb cable.

This is Franco, from Yaeltex, the guys who put up that site for custom MocoLUFA compiling.
Our site works on an Ubuntu server, and the build environment can be seen at the bottom of the site, which is as follows:

Ubuntu Server Setup

avr-gcc: avr-gcc (GCC) 4.9.2
avrdude: Version 6.3, compiled on Mar 15 2016 at 21:26:45
LUFA: 100807
dualMocoLUFA: custom Yaeltex based on 2013/09/22

On the other hand, I use Windows 10 to build locally in my computer, and I have a similar setup with sligthly older versions of avr-gcc and avrdude:

Windows 10 Server Setup

avr-gcc: avr-gcc (GCC) 4.3.3
avrdude: Version 5.10, compiled on Mar 15 2016 at 21:26:45
LUFA: 100807
dualMocoLUFA: custom Yaeltex based on 2013/09/22

Here is a link to the fork we made to mocoLUFA, it has minor changes, that were very useful to us and our hardware.
Regarding your problem, I am really lost on the cause of it, but we can start with some questions to get closer to a solution.

What kind of MIDI messages are you trying to send/receive?
Can you share the code you are using?
Are you using Arduino MIDI Library (Last version is v4.3.1)?
If not, are you sure you are using 31.250 bps as baud rate?
Do you have something else connected to TX or RX lines in your circuit?

Let's start with these. Cheers!

Midi Messages are currently sysex, although eventually will be MTC Quarter Frame msgs.
Arduino MIDI library is 4.3.1
OLED display on pins 20 & 21 (i2c) however "your" hex file works fine with this connected anyway, so I discount any effect of this.
I'll share code to a pastebin as my sketch is actually moot in relation to this question.
https://pastebin.ca/3867422

I note that my OSX box does not recognise the midi device at all when I change HW_CDC_BULK_{IN|OUT}_SIZE to 16

I see that you are reading the MIDI messages from your iPad. If so, it is to be noted that LUFA reports 500mA for power requirements. So you could try self powering your USB-HUB.
Source: http://morecatlab.akiba.coocan.jp/morecat_lab/MocoLUFA.html