I would do that based on the clock. This lets you run each one independently.

On the off-chance that your project runs that long, the clock rolls over (resets) every 50 days.

I'm going to assume the 55 in your code should read 255.

I would do something like this (this is a code snippet, but should get you started):

const int phase_milliseconds=2500; // each phase lasts 2.5 seconds.
const phase_progress_length=256;   // each phase goes from 0 to 255
const phases=4;                    // numbered from 0 to 3, will repeat forever.

// This is the time since your Arduino turned on
unsigned long time=millis();
// how far we are through the current phase?
int progress= time%phase_milliseconds)*phase_progress_length/phase_milliseconds;

// which phase are we in?
int phase=(time/phase_milliseconds)%phases;

if (phase==0) { // first step
         leds[0] = CRGB(progress,0,0);
         leds[1] = CRGB(0,progress,0);
} else if (phase==1) { // second step
         leds[0] = CRGB(255-progress,0,0);
         leds[1] = CRGB(0,255-progress,0);
} else if (phase==2) { // third step step
         leds[0] = CRGB(0,progress,0);
         leds[1] = CRGB(progress,0,0);
} else if (phase==3) { // fourth step
         leds[0] = CRGB(0,255-progress,0);
         leds[1] = CRGB(255-progress,0,0);
}

Since this is time based, it doesn't matter much how often it runs, you don't need a delay (you can still put one in if you like). You can extend this to more steps.

Also note that I rattled this off, off the top of my head, so there may be errors.


Sampling stereo audio at greater than 40 Hertz using arduino

If you are only interested in getting a reading of the sound intensity,
then 8 kHz may be enough. You can also convert the signal to mono
using a pair of resistors. If you want the Arduino to do other stuff
while taking the analog readings, then you should forego analogRead()
and access the ADC directly. This is more involved that typical Arduino
programming, as it involves configuring the ADC at low-level, in “free
running mode”. In this mode the ADC operates in an autonomous way, and
send you an interrupt every time a sample is ready.

I have written a program that does something similar: it samples an
analog input at 9.6 kHz (104 µs per sample) an periodically
sends the reading through the serial port: sound-meter.ino. You can
probably adapt it for driving LEDs instead of the serial port.


I have a page about a breadboard Arduino which is basically an Atmega328P processor (same as in the Uno, inter alia) on a breadboard.

Also a wire-wrapped Arduino.

You can go pretty minimalistic with a ATtiny85 mounted on a button battery like this:

  Is it possible to shrink the arduino(make a custom arduino), and all of its shields on to one board?

Ah there you might be asking a bit much. There are hundreds, if not thousands, of shields people have designed for it. Certainly you can make up your own board to meet a specific purpose.


You are resetting the timer on the first phase [write(15)] instead of after the last phase [after write(65)]! The previousMillis = currentMillis should be only after the last phase, before the loop repeats. Not only that, but the time at which each phase executes needs to be different. Currently every if() statement is set to run after interval has elapsed. If, for example, you wanted interval to be the delay between each phase, you could use interval*1 on the first phase, interval*2 on the second, and interval*3 on the third. For example:

   if (currentMillis - previousMillis <= interval * 1) {
        // Runs from interval*0 to interval*1;
        myservo.write(15);
   }
   else if (currentMillis - previousMillis <= interval * 2) {
        // Runs from interval*1 to interval*2;
        myservo.write(35);
   }
   else if (currentMillis - previousMillis <= interval * 3) {
        // Runs from interval*2 to interval*3;
        myservo.write(65);
   }
   else {
        // Runs once after interval*3;
        // *or* runs on first iteration when previousMillis is zero;
        previousMillis = currentMillis;// Reset the loop;
   }

To put the above logic in English:

write(15) while time is between 0 and 1 intervals;
write(35) while time is between 1 and 2 intervals;
write(65) while time is between 2 and 3 intervals;
reset the loop once time reaches 3+ intervals.

Note the use of else if instead of simply if on consecutive statements. This prevents more than one code block from running on the same iteration of the loop().

Edit: I highly recommend having a small delay (like 1ms) somewhere in the loop(), such as at the end. It would be a bad idea to constantly run the write() function when the value is the same as on the last call.

On the other hand, if your starting value is indeed 150 and the loop should start only after interval*1, you may want to iterate from interval*2 through interval*4:

   if (currentMillis - previousMillis <= interval * 1) {
        // Runs from interval*0 to interval*1;
        // Do nothing; servo is set to either 150 or 65 during this time;
   }
   else if (currentMillis - previousMillis <= interval * 2) {
        // Runs from interval*1 to interval*2;
        myservo.write(15);
   }
   else if (currentMillis - previousMillis <= interval * 3) {
        // Runs from interval*2 to interval*3;
        myservo.write(35);
   }
   else if (currentMillis - previousMillis <= interval * 4) {
        // Runs from interval*3 to interval*4;
        myservo.write(65);
   }
   else {
        // Runs once after interval*4;
        // *or* runs on first iteration when previousMillis is zero;
        previousMillis = currentMillis;// Reset the loop;
   }


Using a pushbutton to power Arduino on and off

You can use the button as a switcher for the Arduino power. Just wire up the button between the battery + out and the Arduino's Vin port.


What's the difference between all the Software Serial Libraries? Which one is Arduino Nano compatible?

This answer lists the 4 basic choices:

HardwareSerial, always the best.  Simply use the pre-defined Serial variable.  On some Arduinos, there are extra HardwareSerial ports, called Serial1, Serial2, etc.  The Nano only has Serial.
AltSoftSerial, the best of the software serial libraries.  Only one instance is allowed, and it is must be used on one of the Input Capture pins (pins 8 & 9 for a Nano).
My NeoSWSerial is next best.  It works on any two pins, but only at baud rates 9600, 19200 and 38400.
SoftwareSerial is the worst choice.  It works on any two pins, but it is very inefficient.  It disables interrupts for the entire time that a character is being sent OR received, and it cannot do both at the same time (unlike all the other serial choices).  This can interfere with other parts of your sketch, other device communications, or with libraries.

If you could use a slower baud rate, you could keep your debug prints on Serial, and use either AltSoftSerial or NeoSWSerial for your device.

But if you have to use 115200, the only reliable choice is Serial.  Although AltSoftSerial and SoftwareSerial allow that baud rate, they may not send/receive data correctly.

In that case, I would suggest using Serial for the 115200 device.  Unless you are using an ISP, you will have to disconnect the device to upload a new sketch over USB.

Then use AltSoftSerial or NeoSWSerial for your debug statements.  You will need a TTL Serial-to-USB adapter (aka FTDI) on the selected pins to connect to the PC.  The Serial Monitor or other Terminal emulator program will read from that USB COM port.


How to restart void loop if condition is met

When programming with arduino IDE, you declare 2 functions, setup() and loop().

Before compilation, arduino IDE basically expands to :

int main(void)
{
    /* run the Arduino setup */
    setup();
    /* and the event loop */
    while (1) {
        loop();
    }
    /* never reached */
    return 0;
}

So, from here you can see that setup() is called once at startup and then, loop() is called in an infinite loop.
Il you return from within your loop function, it will be called again.


One way to do this is to use the millis() function.

millis() returns the current value of a timer that is incremented once per millisecond (hence the function name). You can compare the value of millis() at some past time with the current value to determine how many milliseconds have passed. By having multiple compare registers you can have multiple independent delays operating. (There is also micros() which increments at the 1 uS rate (with a "granularity" of 4uS on some processors).

This code is an example only. It MAY run but has not been tested and probably contains silly mistakes which do not affect its example purposes.

A function ToggleLED(n) is assumed which toggles the specified LED n from 1->0 or 0->1  as required.

LED1 will flash 200 mS on, 200 mS off, ...
LED2 will flash 333 mS on, 333 mS off, ...

The two loops are essentially independent.

unsigned long delay1; delay2;

void setup(){

int FlashTime1 = 200; / LED 1 will have a 200 on 200 off cycle
int FlashTime2 = 333; / LED 2 will have a 333 on 333 off cycle

delay1 = millis() + FlashTime1;  / Init LED timers
delay2 = millis() + Flashtime2;
}

void loop()
{
  if (millis() == delay1){ / Not until delay expired.

    ToggleLED(1);
    delay1= millis() + FlashTime1; / Reinit flash timer}

  if (millis() == delay2){

       ToggleLED(2);
       delay2= millis() + FlashTime2;}

}


Memory allocation on Arduino Due never returns NULL

Why
This is a partial answer, for now, mostly with regard to:

Why does malloc() never return NULL?

So, the Due appears to use Newlib as its libc implementation; that is the systems C (standard and some non-standard) runtime that includes malloc(), or the greater part of malloc() anyway.  The Newlib malloc() relies on an  sbrk() function which is implemented by the specific system, the Due in this case.
This name and basic idea comes out of Unix; you can read about the interplay between malloc and sbrk some without it having to be in connection with Newlib or the Due specifically.  In short, sbrk extends the area that malloc has to work with and malloc divides that area into requested chunks.  Here is Newlib's documentation for sbrk and a sample implementation.
The Due (SAM) core for Arduino implements sbrk as:
extern caddr_t _sbrk ( int incr )
{
    static unsigned char *heap = NULL ;
    unsigned char *prev_heap ;

    if ( heap == NULL )
    {
        heap = (unsigned char *)&_end ;
    }
    prev_heap = heap;

    heap += incr ;

    return (caddr_t) prev_heap ;
}

This is a kind of degenerate implementation of _sbrk that just blindly says, "You want more memory, sure here you go" without limit.  If you look at the sample sbrk implementation for Newlib, you'll see it just calls abort() instead of a proper failure that would result in malloc returning NULL, which is admittedly not great, but at least it's not pretending that everything is fine.
There should be a condition somewhere in this code that check so see if there's any more space to be had and sets errno = ENOMEM and effectively does return -1 if there is not.
I modified this code to allow me to set a variable from the sketch that could force the next call to _sbrk to fail as described above.  And sure enough, on the next call to malloc() it returned NULL because _sbrk had indicated failure.
So the _sbrk implementation provided by the Due/sam core should be changed so that malloc fails when appropriate.  That said, I'm not precisely sure how that should be done.  So I'm going to hold off on making specific recommendations about it.  Maybe I look into it more I'll come back and update this with something more useful, addressing your other question of:

How do I find out that the memory is exhausted?

In rough terms though, the answer going to be that you modify that function so it returns -1 with ENOMEM under the right conditions.

How
This is the previously mentioned update with some details on the how:

How do I find out that the memory is exhausted?

So I've made something to give you an idea what the condition would look like.  I'm not strictly recommending you use it; for one thing it's barely been tested.
From the ATSAM3X8E's family datasheet:

SRAM0 is accessible over the system Cortex-M3 bus at address 0x2000 0000
and SRAM1 at address 0x2008 0000. The user can see the SRAM as
contiguous thanks to mirror effect, giving 0x2007 0000 - 0x2008 7FFF
for SAM3X/A8

The stack pointer starts near the top of memory 0x2008 7FFF and grows
downward.  The _end symbol marks the end of the mutable static storage
duration variables or the beginning of the heap.  Somewhere closer to
0x2007 0000; the fewer of these variables the closer.
On this system, which has a fairly common layout, the heap grows up with positive increments to sbrk as the stack pointer grows down with stack frames (local variables, return addresses etc).  So, "the end" of memory happens when the heap would otherwise allocate over the stack or the stack runs into the heap as your pushing things onto it.
So a typical thing to do is to check to see whether or not the sbrk's argument would cause the edge of the heap to get "too close" to the stack.
In the the /.arduino15/packages/arduino/hardware/sam/1.6.12/cores/arduino/syscalls_sam3.c, I've include some extra headers:
#include <errno.h>
#include <stdlib.h>

And put the following as a replacement _sbrk():
size_t __malloc_margin = 4 * (size_t)1024;
extern caddr_t _sbrk (int incr) {
    static const unsigned char *       heap      = (unsigned char *)&_end ;
    /****/ const unsigned char * const prev_heap = heap;

    if (incr > 0) {
        // Extra checks for stack growing

        if (incr >= 96 * (size_t)1024) {
            // The Due only has 96K of ram,
            // so any request for 96K or greater
            // is a failure out of the gate.
            errno = ENOMEM;
            return (caddr_t)-1;
        }

        unsigned char *stack_ptr;

        asm volatile(
            "mov %[sp_out], sp"
            : [sp_out] "=r" (stack_ptr)
            :
        );

        if (stack_ptr < heap) {
            // We're already in real trouble.
            abort();
        }

        if (stack_ptr - heap  <  incr + __malloc_margin) {
            // Not enough memory considering safety margin.
            errno = ENOMEM;
            return (caddr_t)-1;
        }
    }

    heap      += incr ;
    return (caddr_t) prev_heap ;
}

__malloc_margin was used as a variable name just because it's the name that avr-libc uses for the same purpose, namely to tune the minimum distance between the stack and heap during an allocation that the break to increase.  By the way, you can see this same kind of check happen in avr-libc's implementation of malloc (which also takes sbrk's role.)  Why is __malloc_margin 4K ?  No really scientific reason.  It's about 4% of memory, so it's not large, and it's not completely inconceivable to me that someone would try to put local variable(s) approaching 4k in a stack frame on a system that has 96kb total memory.  4K may not be an appropriate default though; more thought should go into that.  Having it in a variable like this allows it to be tuned at runtime; usually there would be a header that provides an extern declaration for it.
I may add more later to explain, but it short if the break is being increased, this sbrk looks to see if the new break would get within __malloc_margin of the stack pointer on a request, an if it would it returns the -1 value and errno = ENOMEM to cause malloc to behave correctly from the user's perspective.
Before anyone bothers to mention: Yes, I know you can take the address of a local to get a stack pointer value.  Yes, the check to see if the single allocation is larger than 96K is probably unnecessary.  Yup, it has Due specific stuff in it even though it's not strictly a Due; there are probably identifiers that could be used instead.  It should probably abort() if sbrk tries to go below 0 sized heap.  It's just a somewhat working illustration of what should be in _sbrk().  More thought and at least one change should be put into it before general use.
Regarding abort()
It occurs to me in some cases abort() may be an appropriate way to handle this.  If you believe that you can characterize the system (or the sketch if you like) at runtime so well that malloc() failing can be regarded as a major oversight, then calling abort() in sbrk() could make sense.  Or at least providing the option to do that.
In the comments you asked:

What does abort() exactly [do] on the Due?

Well, Newlib documentation says:

Before terminating your program, abort raises the exception SIGABRT
(using ‘raise(SIGABRT)’).

and then further down:

Supporting OS subroutines required: _exit and optionally, write.

The SIGABRT and _exit parts are more or less standard behaviour.  So it will call your signal handler for SIGABRT if you have one.
So then what does _exit do?  It loops forever.
I called abort() in a sketch and dumped the following via an arm version of the binutils objdump with -dS command-line options.
Here's the relevant abort() code:
00081b98 <abort>:
   81b98:   b508        push    {r3, lr}
   81b9a:   2006        movs    r0, #6
   81b9c:   f000 fb5c   bl  82258 <raise>
   81ba0:   2001        movs    r0, #1
   81ba2:   f7fe fec5   bl  80930 <_exit>
   81ba6:   bf00        nop

bl <raise> would in turn call your signal handler.  and bl <_exit> calls exit which displays as:
00080930 <_exit>:

extern void _exit( int status )
{
   80930:   e7fe        b.n 80930 <_exit>

00080932 <_kill>:

    for ( ; ; ) ;
}

It appears the optimizer has combined some things here, but essentially _exit has an instruction that jumps (branches) to itself, equivelent to for(;;);.
I half-expected the abort(); code to disable interrupts before calling _exit().  If you do plan on abort() in your _sbrk() that might be something to think about.  You may also want to provide a global flag that can be inspected from SIGABRT that allows the signal handler to do something diagnostically appropriate specifically for _sbrk() failures.
Perhaps sbrk should set a flag in a no-init data section and then set the watchdog timer and let it expire (or provide the SIGABRT handler with the information to do that).  Lots of things to consider.


Trying to draw a bitmap to an LED matrix only draws the left half

'pixelGrid[]' are longs but your temp inside the for() loop, 'data', is an int. Thus, it gets only half the data. Easy mistake to make (and they can be so hard to spot when you know perfectly well what you meant... :)

Update:

  By switching the int to long, I've successfully unlocked a seventeenth
  column! Unfortunately, it looks like all the pixels are bunched up in
  that seventeenth column.

Another error of the same kind (I missed it the first time around):
Change (1 << x) to (1L << x). The original expression is calculated as int and the result is widened in the assignment to 'data' (and I think there was compiler bug int the code that did that, besides). The corrected expression is calculated as a long in the first place, which is what I think you intended.

Update 2:

From your question Edit 2:

  I'm guessing regular numbers default to 16-bit unsigned ints.

You are correct - ints of unspecified size default to 16-bits in the Arduino gcc compiler used by the Arduino IDE (and just about everywhere else in the Arduino domain that I know of). The language standard leaves the compiler writer free to choose the size of an int that best fits the target-machine's architecture. 16-bits is the most common, but by no means the only - size implemented in most compilers. For this reason, most compilers' pre-processors implement specific-sized data types, and application writers - you & I - are advised to use these wherever data-size matters. For the Arduino's gcc compiler, there are predefined types such as int8_t (signed 8-bit int), uint32_t (unsigned long int), etc.
int is an ok "I don't care, just as long as it works" option. When you do care - specify.

(If my answer helped you, please upvote it or select as best answer. The latter has the important function on this site of marking the question as "completed" so it doesn't keep re-appearing as an unanswered question.)


Arduino Pong game Circuit Board Troubleshoot

The + and - along the bottom of the picture aren't connected to anything.
It also looks like this board has a separate left and right side.

So just make sure everything is connected along the sides.


When connecting together several circuits that have different supply
voltages, common practice is to make them all have a common negative
supply rail. This is called “common ground”. As explained in Majenko’s
answer, you would need an NPN transistor for that.

If you want to use a PNP instead, then you could forget the common
practice and do everything “backwads”: if you connect together the positive
ends of the power supplies, you will have a “common VCC”
instead of a common ground. Relative to the Arduino ground, your
9 V battery will have one pole at +5 V and the other at
−4 V.

The wiring is the following:

connect the emitter to +5 V (Arduino +5 and battery +)
connect the base to an Arduino output through a resistor
connect the collector to the motor
connect the other end of the motor to the battery −
put a free wheeling diode in parallel with the motor.

Edit: Below is an ASCII art rendering of the circuit. Beware that
the motor is ON when the Arduino output is LOW.

+-----------+
|         5V|-----------------+-------------------+
|           |                 |                   |
|  Arduino  |                 |                   |
|           |    ,-----.  B |< E                 ___ +
|        D13|----|     |----|    PNP              _
+-----------+    `-----'    |\                   ___
                              |C                  _
                              |                  ___
                              +---------+         _
                              |         |        ___ 9 V batt.
                              |         |         _
                             ---        |        ___
                              ^       motor       _
                             / \        |        ___
                             ---        |         _  −
                              |         |         |
                              |         |         |
                              +---------+---------+


Arduino crashing during serial print for no obvious reason

This code looks wrong:

  command = malloc(26);
  command = "AT+CIPSSEND";
  strcat(command, number);
  strcat(command, ",");
  strcat(command, length_of_payload);
  send_wlan_chip_command(command);

First you allocate 26 bytes, then a new string is created, which you strcat to it. This happens in memory that is not allocated (or overwrites other data).

Instead of

  command = "AT+CIPSSEND";

use

  strcpy(command, "AT+CIPSSEND");

Also check that 26 bytes is enough, change it to 128 bytes to be sure (check the correct amount you need later).


How to connect HC-06 BT module without pins?

The small green PCB is the real HC-06 board. The blue board has 2 functions:

It breaks out the contact pads of the HC-06 to the bigger pins.
It has a voltage regulator on it so that you can provide it with 5V power, which then get's converted to 3.3V for the HC-06 (which is a 3.3V device).

The next steps depend on what Arduino board you have:

If you have a 3.3V Arduino Board, you can directly connect the pads on the HC-06 (by soldering pins or wires to them) to the corresponding Arduino pins:

Arduino <--> HC-06
  3.3V  <--> 3.3V
  GND   <--> GND
  TX    <--> RX
  RX    <--> TX

Also you can connect a fitting LED to the LED pin. I spontaneously cannot find data about the max current of this pin. But I guess it is in the range of 10 to 20 mA. Use a corresponding combination of an LED and a resistor.
If you have a 5V Arduino, you need to consider the voltage difference. On the Uno and Nano you have a 3.3V regulator on board. The regulator itself is rated for 150mA, but since it is not cooled, the limit is more like 50mA (see this forum thread). This datasheet of the HC-06 states, that it draws at max 30-40mA, so you can get away without an extra 3.3V regulator, just by connecting the both 3.3V pins on Arduino and HC-06. If the voltage regulator overheats despite being under 50mA, you need to buy an extra 3.3V voltage regulator, that can handle the current.

Don't forget to use a voltage divider on the Arduino-TX --> HC-06 RX line to divide the Arduinos 5V down to 3.3V. This line isn't even regulated by the blue breakout board, so you would need this voltage divider either way.

Ground connection and the LED are the same as in the first case.

So all in all you can still use the HC-06, just with a little bit less ease than with the blue breakout board.


pin going high not allowing analog read to change

The description you give for the desired behavior is very unclear and
hard to follow. I am going to rephrase what I think I understood in
terms of a finite state machine, which is the correct way of
describing this kind of systems. Please, review the description below,
as chances are I did not completely understand what you really want.

Let's say the system can be in any of these three states:

In the V_LOW state, the input voltage is below the threshold X and
the output is LOW. If the input raises above X, we set the output
to HIGH and transition to the V_HIGH state.
In the V_HIGH state, the input is above the threshold X and the
output is HIGH. If the input falls below X we go back to the
V_LOW state. If we remain in V_HIGH for three seconds, we switch
the output to LOW and go to the TIMEOUT state.
In the TIMEOUT state, the input is above the threshold, yet the
output is LOW. When the input falls below X we go to the V_LOW
state.

Below is a state graph for this machine. The states with a gray
background have the output LOW, whereas the state with a white
background has the output HIGH. Each possible transition is drawn as
an arrow, labeled by the condition that triggers the transition:

Is this the behavior you have in mind? If no, try to describe the
behavior you want in terms of a finite state machine, as I have done
here. If yes, then I suggest you follow chrisl's advice and implement
some hysteresis, by having different thresholds for going into and out
of V_LOW.

Anyhow, below is a translation of the FSM above in C++. It may not be
the most efficient way to write it, but I believe it is straightforward
enough to not require any additional explanation:

void update_output()
{
    static enum { V_LOW, V_HIGH, TIMEOUT } state;
    static uint32_t time_entered_v_high;
    int V = analogRead(A0);

    switch (state) {
    case V_LOW:
        if (V >= X) {
            digitalWrite(pin, HIGH);
            state = V_HIGH;
            time_entered_v_high = millis();
        }
        break;
    case V_HIGH:
        if (V < X) {
            digitalWrite(pin, LOW);
            state = V_LOW;
        } else if (millis() - time_entered_v_high >= 3000) {
            digitalWrite(pin, LOW);
            state = TIMEOUT;
        }
        break;
    case TIMEOUT:
        if (V < X) {
            state = V_LOW;
        }
        break;
    }
}

Edit 1: Here is how to implement the hysteresis: you need to choose a
second, lower threshold, for going back to the state V_LOW. Let's call
it Y, which is smaller than X. Then, both on the diagram and the
code, replace every instance of “V < X” by “V < Y”. That's it. There is
absolutely nothing more to change.

Edit 2: Addressing the updated question. Now the output should go
HIGH when the input is out of a defined range. I'll add hysteresis
right away by using four thresholds
V0 < V1 < V2 < V3:

the input is in range if it is within
[V1, V2)
the input is out of range if it is not within
[V0, V3)
the ranges [V0, V1)
and [V2, V3) provide hysteresis.

Note that for consistency I like to have all the intervals closed on the
same side. I will also rename the states V_LOW and V_HIGH to
IN_RANGE and OUT_OF_RANGE respectively. Here is the updated code:

void update_output()
{
    static enum { IN_RANGE, OUT_OF_RANGE, TIMEOUT } state;
    static uint32_t time_exited_range;
    int V = analogRead(A0);

    switch (state) {
    case IN_RANGE:
        if (V < V0 || V >= V3) {
            digitalWrite(pin, HIGH);
            state = OUT_OF_RANGE;
            time_exited_range = millis();
        }
        break;
    case OUT_OF_RANGE:
        if (V >= V1 && V < V2) {
            digitalWrite(pin, LOW);
            state = IN_RANGE;
        } else if (millis() - time_exited_range >= 3000) {
            digitalWrite(pin, LOW);
            state = TIMEOUT;
        }
        break;
    case TIMEOUT:
        if (V >= V1 && V < V2) {
            state = IN_RANGE;
        }
        break;
    }
}


Use a resistor between GPIO16 and RST. I usually use a 470 Ohm resistor. Shorting the pins with a wire does not work.

https://www.esp8266.com/viewtopic.php?t=14350#p64510

Maximum deep sleep is about 71 minutes. 3600000 microseconds = 3.6 seconds, not 1 hour. 1 hour in microseconds is 3600000000UL.

As mentioned in the comments, waking from deep sleep on the ESP8266 is a hardware reset so execution begins at the start of the setup function.


Fast PWM working with int main(void) but not with void setup()

If you don't define your own main(), your program will be linked with
the main() provided by the Arduino core library, which roughly looks
like this (I am simplifying a little bit):

int main(void)
{
    init();      // Arduino core initialization
    setup();     // user's initialization
    for (;;)
        loop();  // user's main loop
}

The core's init() function configures Timer 1 for 8-bit phase
correct PWM at 490 Hz, which means that, by the time your setup()
runs, the timer's control registers are not in their default state
anymore, and some of their bits are already set to 1. If you then
update these registers using the |= operator, you end up with a mix of
the core's configuration and your own.

This can be fixed either by zeroing these registers first or, more
simply, by setting their values with the = operator, which has the
effect or setting every bit of those registers to the value you want.

The following works whether you use or not the Arduino core library:

#ifdef NOCORE
int main(void)
#else
void setup()
#endif
{
    DDRB   = _BV(PB5) | _BV(PB6);
    TCCR1A = _BV(COM1A1)
           | _BV(COM1B1)
           | _BV(WGM11);
    TCCR1B = _BV(WGM12)
           | _BV(WGM13)
           | _BV(CS10);
    ICR1   = 0x7fff;  // TOP
    OCR1A  = 0x3fff;  // 50% of ICR1
    OCR1B  = 0x3fff;  // 50% of ICR1
}

#ifndef NOCORE
void loop(){}
#endif

Note that:

The control registers are set (=) rather than just modified with
|=
The mode is set before the output compare registers. This is because
setting the output compare registers does not work well when the timer
is in an 8-bit mode.


Strange behaviour on splitting char array and converting the chunks to int

In this piece of code you have a strange mix of upper bounds:

  for(int i=0;i<3;i++){
    _red[i]=control[i+offset];
  }
  offset=4;
  for(int i=0;i<sizeof(green);i++){
    _green[i]=control[i+offset];
  }
 // strncpy(_green,control+offset,3); // same result
 offset=7;
 for(int i=0;i<sizeof(_blue);i++){
   _blue[i]=control[i+offset];
 }
 offset=10;
 for(int i=0;i<sizeof(_white);i++){
   _white[i]=control[i+offset];
 }
 offset=13;
 for(int i=0;i<sizeof(_brightness);i++){
   _brightness[i]=control[i+offset];
 }

The first looks correct at 3.  The second loop has an upper bound of sizeof(int) which is 2.  The third loop seems to be sizeof(char) which is 1.

Unfortunately non of those values match up with the results you are getting.  What I would try is refactoring whats inside you function to this.

int Convert (char* buffer, char const* control, const int& offset, char const* name)
{
    int value = 0;
    for (index = offset; index < offset; ++index)
    {
        buffer[index-offset] = control[index];
    }
    buffer[4] = '\0';
    atoi(buffer);
    Serial.print(name);
    Serial.print(" = ");
    Serial.print(buffer);
    Serial.print("  Value = ");
    Serial.println(value);
    return value;
}

And then call it to populate your values:

void changeColor(char control[16])
{
    char buffer[4]; // You can reuse this buffer, unless you wanted to have separate ones.
    const int red    = Convert (buffer, control, 1, "red");
    const int green  = Convert (buffer, control, 4, "green");
    const int blue   = Convert (buffer, control, 7, "blue");
    const int white  = Convert (buffer, control, 4, "white");
    const int bright = Convert (buffer, control, 4, "bright");
}


What could cause interrupts from MCP23017 suddenly stop working?

I think I figured out whats wrong: you need to reset the interrupt handling of the MCP in setup() (by reading from both INT pins). Otherwise the MCP may start in a state where it does not generate new interrupts, because it waits for the old ones to be handled...


The argument passed to RSSI() must be an integer indicating the array index of the SSID of the WiFi network whose RSSI you want to get. To get that integer, you must first scan for networks.

char ssid[] = "greenNet";
byte num_ssids = 0;
long rssi = 0;

num_ssids = WiFi.scanNetworks();
for (byte net = 0; net < num_ssids; net++){
    rssi = WiFi.RSSI(net);
    Serial.print(WiFi.SSID(net)); Serial.print(": ");
    Serial.println(rssi);
}


Custom Arduino board beeps and process freezes while I'm uploading a sketch to it. Why?

What is making the upload process pause?

Well, given all the comments made under your question, this is definitely a tricky one. You might want to try to add a decoupling capacitor as suggested by @jfpoilpret, though your schematics look alright to me… (maybe ask a review of it on EE SE).

I'd also advice you to copy the avrdude command from Arduino IDE output (you'll find it at the top), and run it in the command shell with lower bitrate:

avrdude -v -v -v -v -C "C:\arduino-1.0.3\hardware/tools/avr/etc/avrdude.conf" -P COM1 -patmega328 -U… -B3 -b115200

the higher the -B value is the lower your bitrate is. and -b to the correct baudrate for your bootloader (are you sure this is 115200? it's more common to see 57600).

Did you also set fuses correctly? You might as well want to check the values of the fuses to see if the clocks are correctly set up:

avrdude -U lfuse:r:-:i -U hfuse:r:-:i -U efuse:r:-:i

which will output the values of the fuses. Then to make the values readable, put the values at the bottom of the form on the fuse calculator site, after choosing the Atmega328P MCU from the dropdown list.

Double check that:

you have enough size for the bootloader (usually the more you give it the better it is) ;
you have correctly set up the cristals configuration for your design (which may not be compatible with default Uno settings as setup by the Arduino IDE), checking if you correctly set up the external crystal at 16MHz…

  Why is the buzzer beeping when the process pauses?

It's because when the processor does not have the output set up, the values within the registers are in an undefined and unpredictable state. Which means that usually it keeps the last value it had before a reset, or changed state because of some electrostatic weirdness, or is giving some weird PWM output because of the influence of a clock nearby.

So basically, there's something wrong happening when you're uploading your code and that wrong thing has an indirect effect on the audio. I wouldn't worry much about that stuff, but more about the cause of the pausing.

Sadly, I don't have a direct answer for you, but at best a few paths you should investigate more. HTH


This behavior is expected: INPUT_PULLUP means the pin is pulled up via the internal pull up, i.e. it will read as high if not connected externally.

With your push button you connect it to ground (0 volts), thus bringing it to low level and it will read as low. Therefore, in your code, you need to check for low level (LOW) to check if the button is pressed (as you found out by changing the code).


Start by changing it to Serial.write("3", 1);

Does that help, you're missing the second parameter to the Serial.write call, which is the number of characters (bytes) to write.


how to convert the following code into one using direct port manipulation

It is better to use interrupts instead of pooling pins.
but this is related to your arduino controller.
what is you arduino core controller?
if you can select I prefer "Nano 33 IoT " which has 9 pins (2, 3, 9, 10, 11, 13, 15, A5, A7) available for interrupt.
this page may be usable:
https://playground.arduino.cc/Main/PinChangeInterrupt/


Button circuit draws all power away from LEDs

As per your statement, wire from the positive to a row, with a wire leading from there to another row, back to ground.

That describes a short circuit between V+ and ground.

Remove either the ground wire or the positive wire.


Where does the Arduino core include the name of the sketch?

Compilation doesn't start with the Arduino.h or the core files; rather, it starts with your own sketch, "whatever.ino". Your .ino file includes Arduino.h into the compilation which makes references to core modules. That compilation leaves many references to to be satisfied, and itself satisfies several - setup() and loop(), for two. At link time, the linker is told to read not only your compiled module(s), but also the compiled core files, from which it can extracts the modules required to satisfy references made by your compiled code. Then it combines your module, and those modules required by it, into the load file that avrdude uploads to the Arduino.


Possible to use the hardware serial port for peripheral on ATmega32u4 when using USB for programming?

I have a Teensy 2.0 with a ATmega32u4 and I can use both, with the USB as Serial.* and the hardware UART as Serial1.*

For the Arduino Pro Micro it is the same.  See Arduino Pro Micro, get data out of Tx pin?

For Teensy, see https://www.pjrc.com/teensy/td_uart.html


How can I see the mySerial.print( ) through the serialmonitor on IDE?

Not the most scientific of approaches, and fundamentally flawed at any rate.

You've toggled the input twice over the period of one second, hardly an emulation of any serial port transmission and so one is letting you know there's been a change of state, the other is letting you know that it hasn't received any valid data.

In any case, when you attempt to read the port both will/should correctly give you nothing as a result because there was never anything there to begin with, nor is there anything coming in at the time.

If you want to test serial port comms like this, you are going to have to make a sketch for each scenario and use a real device to test it (like your actual serial port thru the Arduino IDE). Run some test, print the results and upload your second sketch and do it again.

You could even get a bit fancy and have a bit of fun with this and send a command to the arduino to turn off one serial port and turn the other one on, but that's got nothing to do with what you asked, so I won't be writing the code for that here ;)


What's the simplest way to get arduino functionality?

If you what you're looking for is the cheapest option with the fewer components possible, then you can use a regular ATMega328p chip, with a few passive components attached to it.

You just need to program it with an Arduino Bootloader once, in order to be able to program it easily, but you can use any existing Arduino to do that. After doing this once, you can program it with any FTDI-type USB to Serial converter.

Here's an Instructable that explains the whole process.


How do I connect a PS4 controller connected to an Arduino that's connected to a laptop to another Arduino?

this is possible, but the processig bridge can add a lot of delay if not correctly handled, also wifi has a low range, almost 100m by default hardware.

zigbee module has better range (xbee pro are up to 1km) and are microcontroller friendly, you use the as you are using a serial, they will hide their complexity once you set them up, and this can be done by PC.

That mens less code, that mena less error and more ram/flash/cpu so you can do a smarter robot :)

zigbee use the serial protocol to communicate, exactly as you do with the pc. Also arduino can use, with the library SoftSerial, any pin as Serial. So you can keep the HardwareSerial to communicate with pc, and any 2 free pin to communicate with the xbee. So you can use the arduino stand alone, only with the controller, and when needed connect the pc. Then arduino can act as a bridge between xbee and pc, so pc can excange data with the rover. But even without pc your project will be fun.
The same apply for bluetoot or 400/800mhz rxtx module, but not for wifi shield


You should never drive relays direct from an Arduino.  You always need a driver circuit since each OP pin can only reliably provide up to 25mA.

Every relay needs (at least) an NPN transistor and a flyback diode.  Follow the myriad of examples for controlling one relay on an Arduino and multiply it by 12.

You might like to make things smaller and more manageable by using a paur of ULN2303 chips with 6 darlington drivers in each instead of using 12 discrete transistors.


can homemade arduino be powered up with battery?

First, of course, you'll need a battery with enough capacity, and voltage enough greater than 5v (assuming you want to run your home-built at 5v - typical, but you could run it lower, say 3.3v) to give enough run-time before the battery discharges to where it can no longer supply the system. Note that the 9v, so-called "Transistor battery" is not capable of supplying much current. A battery pack of off-the-shelf alkaline batteries or rechargables, or a Lithium Polymer rechargable battery will do much better.

You'll need a low dropout voltage regulator to reduce the battery voltage to your chosen Arduino supply voltage. National Semiconductor's LM1117 would be a good choice. The diagram below from NS's datasheet shows a simple-to-make voltage regulator. Its input is your battery; its output will be the supply voltage to the chip and any accessory circuitry.


Does setting a value always mean setting a Arduino pin?

Note that this is just a C/C++ integer declaration, assigning a value to a variable, like any variable (irrelevant if it is for pin numbers).
You don't have to use a variable, there are similar variations:
Variable
int pinNumber = 13;

in begin:
pinMode(pinNumber, OUTPUT);
digitalWrite(pinNumber, HIGH);

Const
Preferably I like to use a const:
const int PIN_NUMBER = 13;

Or even better, since it always is a low value:
const uint8_t PIN_NUMBER = 13;

And use it with capitals.
pinMode(PIN_NUMBER, OUTPUT);
digitalWrite(PIN_NUMBER, HIGH);

#define
#define PIN_NUMBER 13

pinMode(PIN_NUMBER, OUTPUT);
digitalWrite(PIN_NUMBER, HIGH);

The reason variables are used, is that when you want to use another pin number, you only need to change it in one place, making the sketch better maintainable/adaptable.
I don't know what happens when you give an illegal number (you can try it out yourself).


How can I measure if a battery is there?

You could add a pulldown to the analog pin. If the ADC reads a value below e.f. 10, you could consider this the state when there are no batteries.

From the signal perspective a pullup would be better, because without batteries you would read 5V which is unambigous as it can not be provided by the batteries themselves. But in general I don't think that applying higher voltage to the batteries is good practice, even though you could limit the current with a reasonably high resistor.


The following code block does not make sense:

for (int i = 0; i <= sizeof(OutData); i++) {
    Serial.write(OutData[i]);
    byte data[] = OutData[i];
    crc.clearCrc();
} // I added this bracket for you.

It is formally wrong to create an array this way. The compiler does not have any way to know, how big the array should be. I think the declaration with [] works only, when you initialize the array, but you are simply assigning 1 byte value to it. byte is not the same as array of byte. So this cannot work. To make it formally correct, you can either change data to a simple byte variable (not an array), or define the size of the array via byte data[3]; and then assigning the OutData[i] value to one of it's elements in the next line;
Above I added the closing curly bracket for you after the first for loop. It seems, that you forgot it, thus you would get more errors due to imbalanced brackets.
You are create a variable/array inside your for loop, that is not used anywhere. As soon as the current for loop iteration is finished, the variable/array is out of scope and will vanish. You have to declare it outside of the for loop (either inside the loop() function or globally), so that you can use it in the following code.
It seems, that you try to copy the data from the OutData array into the  data array to output the values in the later code and calculate the CRC value. I don't see, why you are doing this. Is there a reason, why you could not do this directly with the OutData array? I don't see the need for copying the data in an extra array.
The following line can easily be a problem:

OutData[6] = distance;

distance is defined as an int, which is a 16bit/2byte signed number. OutData is defined as an array of byte, which is a 8bit/1byte unsigned number. pulseIn() returns an unsigned long (32bit/4byte unsigned number). Since you have configured a timeout of 26000, you won't get in conflict there, but easily, when trying to assign the distance value to an element of OutData. You can get distance values up to 448, but a byte can only hold numbers between 0 and 255. So you will get an overflow and thus garbled data. You will have to send both bytes of distance to always get the full value. (You can easily google how to get the individual bytes of an int; The Arduino framework even has defines for this, lowByte and highByte, I think).


What is a cheap way to interface a USB keyboard to an Arduino Uno?

The cheapest way is to get a plain PS/2 (or PS/2-USB convertible) keyboard instead of USB1.1 (I hope you mean the standard LS keyboard, since USB2.0 HS keyboards hardly exist), and interface it to GPIOs in accord with known solutions.

The Arduino Uno is designed around Atmega8u2 and ATmega328P chips, which can act as USB device only, FS and LS. To interface it with a dedicated USB keyboard (which is a USB device), the you need to have the Arduino as a USB host. Probably it is possible to emulate some limited hardware host functionality for LS mode (1.5Mbps) over GPIOs, but it will be a remarkable effort.


Activating a defined macro in a class from main.cpp

You cannot not, but also you should not try to define a macro in a cpp file and use it in another cpp file.

Instead, you have to define it in a h (header) file, which is included in both cpp files.

Why would you define it in main.cpp or main.h anyway if you don't use it in those files?

You have mainly three options:

Define it in gyro.h so you include it in gyro.cpp where you use it. You can later use it in other files as well.
Define it in gyro.cpp so you can use it only in that file. This prevents the macro being used in other files (which can be safer).
Define it in a separate file, e.g. euler.h and include this header file everywhere you need it.

See also Juraj's comments below.


Arduino program only works when run as root

The easiest solution is to add yourself to the dialout group.

First make a note of the output from id. Save it in file (not in /tmp as that gets cleaned out on a reboot). If you look at the output, you'll notice that your user is signed up for several groups and those groups represent extra privileges on the system. By default your Arduino is assigned to the group dialout because it registers as a serial interface and in the old days these were often used to ... dial out, using a modem.

To add yourself to the dialout group, issue the following command:

sudo usermod -a -G dialout $USER

Don't forget the -a flag (for appending groups rather than replacing) or you will have entirely different problems. This is the reason for making a copy of the id output to a file, so in case you do mess up at least you know what your user was configured like before.

Then log out and log in and it should work from that point.

Optionally you can double check the output for id against the output you saved before.


No.

That is because millis will be equally affected by any frequency change (due to temperature) as the benchmark code. You would need an external clock source that is precise enough.

Note that temperature doesn't have that big an impact on crystal oscillators. Somewhere around 10ppm between -20 and +20 degrees C. The crystal itself is probably already 50ppm precision to start with (higher precision ones are more expensive).


I am not aware of anything like that, no.  The problem is what you are seeing as characters are a complete corruption of the data. Only some part of it may have been interpreted as a valid bit sequence, and even then you can't know what bit it was.

However, there is one magic character in UART communication: U

What is special about that character is its binary pattern.  It is ASCII character 85, which in HEX is 0x55, or binary it's 0b01010101.  Add to that the start and stop bits, and invert it for the UART logic (1 = LOW, 0 = HIGH) and the signal that gets sent out of the UART looks like:

____start_____     _____     _____     _____     _____
    |   |  0  | 1 |  0  | 1 |  0  | 1 |  0  | 1 | stop
    -----     -----     -----     -----     -----

And yes, that's a pretty good square wave.  The frequency of that square wave will be exactly half the baud rate - so a frequency of 4800Hz will be a baud rate of 9600 baud.

This effect is cleverly used for a system called Automatic baud rate detection whereby a receiver waits for a U character to determine the baud rate to use.  Most modern microcontrollers have this facility available.

If you can't get the frequency of a block of U characters you will have to examine the waveform with an oscilloscope.  It should be possible to identify the individual characters in the data stream as distinct blocks in the waveform.  From that you can then work out the width of one symbol and thus the baud rate.  It's best to use a DSO for this since you can then capture a short burst and use the markers to measure the time between different points in the waveform.  A logic analyser will also do the job quite well, and will most likely be able to decode the waveform and calculate the baud rate for you.

If you have neither of those it would be possible to program an Arduino to capture the time between transitions of an incoming signal and allow you to plot them in Excel to give you a waveform you can examine to determine the baud.

Another option is just to keep trying different baud rates (there's relatively few "standard" baud rates) until you see the right text coming in.


Is it possible to change and save I2C address programatically?

As far as I can see in the datasheets of the 2 mentioned chips, they don't provide a way to change the address programmatically over the I2C bus. They only have address pins, which have to be tied to Vcc or ground for setting the address. Most ready to use boards with such chips already have pullup or pulldown resistors for this. If you use the blank chips, you absolutely need to tie the address pins to a fixed value. Normally this is done semi-permanently.
You can also connect the address pins to Arduino output pins to dynamically change the addresses.
There is no other way to change the addresses but to use the address pins.


Personally I think using an ESP as a interface for an Arduino is backwards and the Arduino ought to act as the interface to your devices for the much more powerful ESP.

I think you had a board that was configured to work as a interface between serial and Wifi, not as a normal board.  I'm pretty sure that you have now shagged it totally by trying to write programs to it.  However you might be able to recover it if you can find the original program and upload that to it.  You don't need the ability to program and ESP-8266 in the IDE to use this board, you can not upload sketches to it, you can't access the GPIOs.

I think you should just be able to slide the switch to "program" power the board up and type AT commands via a terminal emulator to set the board up and then power down, slide the switch back to UART and away it goes.  As to the Tx and Rx pins, that depends on weather its saying "this is the Rx pin" or "this is the Rx connection", you'll get it right second time :)

If you want a ESP8266 try AliExpress they cost between £1 and £2 and I've never had any problems, probably because they were made in China.


The specified minimum voltage for the motors is 2.5 volts higher than the logic supply.

You need to use a separate supply for the motor that is higher than the logic power.


How can i provide enough power on an UNO to use the HC-12 wireless module?

There two options I have found that work well.

First is a simple wall-wart that provides 12 Volts to a barrel connector, like for a CCTV camera.

Or, if I want to run the Uno from a separate higher-amperage USB charging port I have found that there are "USB A Male to CCTV male" cables that work.

Doing the latter means the Uno is running at 5V instead of utilizing the on-board regulator to drop a higher-voltage input, which only matters if your circuit expects to find more than 5 Volts on the Vin pin (although that is not supposed to be an output pin, of course).

Through thorough experimentation I've proven that both methods work.

The best part is that the Uno can easily tolerate having both CCTV-style power and also being plugged into the laptop for programming and testing (like using the serial monitor).

Lesson learned:  The HC-12 simply will not work without auxiliary power, and it is safe to provide such power while also plugging the serial port into a laptop.


ESP32 Alexa Integration; Cannot correctly control more than one device

Try this library , in past i have used 5 device at a time

fauxmoesp


Digital to Analog converter with DAC5311, Any suggestion?

Classical +/- 1 problem

If you do this calculation by hand uint16_t temp = int(voltage * pow(2, 8) / max_VOLT);
you will get temp=256 and this is a value you can not convert with a 8 bit DAC.

Try uint16_t temp = int(voltage * (pow(2, 8)-1) / max_VOLT); instead.

(or event better for a µC uint16_t temp = (uint16_t) (voltage * (255 / max_VOLT));)


Arduino MKR1000 and DHT11 not giving correct output for temperature and humidity

I have the identical sensor so I've got two suggestions for you.

I don't see the 5k ohm pull-up resistor on either of the pictures you've uploaded. You could try adding it first and see if that solves the problem.

There are several versions of the DHT11 library for Arduino out there. This is the one that worked for me: https://github.com/adidax/dht11. Have a look at this answer for a sample sketch: Arduino Uno Sensor DHT11 Failed to read from DHT sensor.

EDIT: Connect the sensor data line to digital pin 3 on your Arduino MKR1000.

// 5k ohm pull up resistor is used on the data line.
// Sensor operates at 5VDC.
// Data line connects to Arduino Uno pin 3.

#include <dht11.h>
dht11 DHT11;
#define DHT11PIN 3

// Sensor calibration. Start with 0 for each.
const int HumidityCorrection = -10;          // -10 worked with my sensor.
const int CelsiusTemperatureCorrection = 2;  // 2 worked with my sensor.

const float FahrenheitTemperatureCorrection = CelsiusTemperatureCorrection * 1.8;

// Update the serial display every 60 seconds.
const float UpdateSerialDisplay = 60000;

// Celsius to Fahrenheit conversion.
double Fahrenheit(double celsius){
  return 1.8 * celsius + 32;
}

void setup(){
  Serial.begin(9600);
  // Minimum wait for good data recommended is 1 second.
  delay(2000);
  Serial.println("DHT11 TEST PROGRAM ");
  Serial.print("LIBRARY VERSION: ");
  Serial.println(DHT11LIB_VERSION);
}

void loop(){
  Serial.println("");
  int chk = DHT11.read(DHT11PIN);
  switch(chk){
    case DHTLIB_OK:
      //Serial.println("OK");
      break;
    case DHTLIB_ERROR_CHECKSUM:
      Serial.println("Read sensor: Checksum error");
      break;
    case DHTLIB_ERROR_TIMEOUT:
      Serial.println("Read sensor: Time out error");
      break;
    default:
      Serial.println("Read sensor: Unknown error");
      break;
  }

  Serial.print("Humidity: ");
  Serial.print("\t");
  Serial.print(DHT11.humidity + HumidityCorrection);
  Serial.println(" %");

  Serial.print("Temperature: ");
  Serial.print("\t");
  Serial.print(DHT11.temperature + CelsiusTemperatureCorrection);
  Serial.println(" C");

  Serial.print("Temperature: ");
  Serial.print("\t");
  Serial.print(round(Fahrenheit(DHT11.temperature) + FahrenheitTemperatureCorrection));
  Serial.println(" F");

  delay(UpdateSerialDisplay);
}


Arduino IDE get stuck while uploading sketch

Is the motor driver connected to the Arduino while you program it?

When the Arduino is reset, the output pins on the Arduino are driven high. If too much current is drawn though any of these pins, then the voltage supply to the ATMega328 may drop, and the ATMega328 gets stuck in a brownout.


Problem stacking ADS1292r ECG shield and Wifi shield on Arduino Uno

As a generic answer to these sorts of problems (same pin needed by different libraries), I have had success with slightly bending the pin of the top shield to the side to that it doesn't make direct contact with the board underneath (ie doesn't plug into the header socket).

Assuming the shields are all stackable, you can run a jumper wire from the top of the pin to any other pin which is permitted by the configuration. If not, you may have to solder a wire.

In your example, put the WiFi shield on top with its D4 pin bent to the side (with ECG shield between Uno and WiFi shield) , and run a jumper between the tops of D3 and D4 (ie on the WiFi Shield). Thus the SD Card select would now be set to D3 instead of D4, and no other connection is made to D4 on the WiFi shield.

I can't verify that you won't have trouble with other pins (eg it looks like both shields use D7).


Irregularly triggering an ISR using timers

However on an oscilloscope I see the pin toggle each 1ms.

That's what you expect. You set up the timer to fire every 1 ms. Since the ISR is called some time after that (and that is what toggles the pin) you will see the pin toggle every 1 ms.

I've reworked your example a bit to make it clearer, and to toggle the pin when we start the timer, and again when the ISR fires:

uint32_t timestamp;

void setup()
  {
  pinMode(9, OUTPUT);
  // Timer2 for counting
  TCCR2A = bit (WGM21); // CTC mode, clear timer on compare match
  OCR2A = 99;           // ticks, before ISR is called

  // counting time[s] = (OCR+1)/(F_cpu/prescalar)
  // 99 = 400us | 124 = 500us
  timestamp = micros();
  }  // end of seupt

void loop()
{
  uint32_t now = micros();
  if (now - timestamp >= 1000)
    {
    timestamp = now;
    TIFR2 = bit (OCF2A);   // clear any pending interrupt
    TCNT2 = 0;             // make sure counter is zero
    TIMSK2 = bit (OCIE2A); // enable timer compare interrupt
    TCCR2B = bit (CS22);   // start timer: Prescalar 64
    PINB = bit (1);        // toggle pin 9
    }  // end of if
}  // end of loop

ISR(TIMER2_COMPA_vect)
{
  PINB = bit (1); // toggle pin 9
  TCCR2B = 0;     // stop timer
}  // end of TIMER2_COMPA_vect

You can see from the scope output that the timer is started every 1 ms (as expected) because Cursor 1 is at -1 ms. The width of the pulse is 400 µs, as expected.

  In my example I do not have to set so many settings each time I want to start the timer.

I took out the cli and sei so I saved you two lines. Don't forget to count them!

If you leave the timer running, it may well have reached the counter again (even though not generating an interrupt). Thus this line is important (even more so for you):

TIFR2 = bit (OCF2A);   // clear any pending interrupt

Also, if you leave the timer running, you may have a race condition. Say the timer is just about to tick over and generate the interrupt. You clear the flag (as shown above), but one machine cycle later the timer reaches the counter and sets it again, just before you get a chance to zero it. With the timer running, there could be combinations of when you enable interrupts, zero the flag, and clear the pending interrupt flag, that could occasionally work against you. Having the timer stopped is much safer.

Now if you are worried about the number of lines you need to start it (I wouldn't be) then you can move this line into setup:

TIMSK2 = bit (OCIE2A); // enable timer compare interrupt

Since you stop the timer in the ISR it doesn't matter if the interrupt is still enabled. Now you just have three lines to start the timer:

TIFR2 = bit (OCF2A);  // clear any pending interrupt
TCNT2 = 0;            // make sure timer is zeroed
TCCR2B = bit (CS22);  // start timer: Prescalar 64

I think we've agreed that clearing the compare flag is important, so this isn't any lengthier.

  looking at your divisioning of the time axis, and from code, it is clear, that there is a 600us break, not 1ms!

Yes, there's a 600 µs break, because you start the timer every 1 ms, and it runs for 400 µs, thus there will be a 600 µs break.

  I seek to call an ISR routine after a fixed time of 400us.

That's exactly what my posted code does. The pin goes high at the time you desire, in loop, and it goes low 400 µs later. That's what you wanted: a 400 µs interval.


4.7v as HIGH on digital output instead of 5v

Also depends on what your driving via this output. Standard TTL is:

But CMOS will be a bit different:


I may be missing something, but couldn't you just modify your setLocked function?

void setLocked(int locked) {
  if (locked) {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  } else {
    digitalWrite(redpin, LOW);
    digitalWrite(greenpin, HIGH);
    delay(500);
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  }
  return;
}


Connection of Seeeduino GPRS with relay module

Have you checked out these two websites:

https://www.pubnub.com/blog/2015-02-17-connect-arduino-gsm-gprs-shield-to-the-internet/
http://www.seeedstudio.com/wiki/Seeeduino_GPRS.

They both go over many examples of how to connect the Seeeduino GPRS and even provides some sample code that you could run to test the connections if you are still unsure. As for the relay module, it depends on which one you are using, the LCD can be easily connected following this tutorial: https://www.youtube.com/watch?v=85LvW1QDLLw. Hope this helps.


If the encoder only gives +1 pulse per 90 degrees, you aren't going to get better than 90 degree accuracy out of it.

In the example code at the link, the val{x,y,z} are measured analog variables of some other thing that are sampled at each encoder lcoation:

  My project is a data loger where three analogue inputs are sampled
  each time a rotary encoder pulse steps clockwise. On an Arduino, time
  is of the essence to get this data sampled and saved somewhere (I have
  not included the 'saving somewhere' part of this project yet.) In
  order to save some processor cycles, I have slightly redesigned the
  interrupt system to maintain a pair of boolean states outside of the
  interrupt loop.

These are not directly related to the positioning of the encoder, and there is no reason to think they provide angle information.


Arduino std::map returning random values

You get random values because if the key is not found in getKey, then there is no return statement.

You attach the \n to the key in serialEvent(), then the key for getKey is "key1\n" and it is not found.

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    if (inChar == '\n') {
      stringComplete = true;
    } else {
      inputString += inChar;
    }
  }
}

If you have CR/LF set in Serial Monitor, then the \r character is send too and the parsed key is "key1\r\n".

There are obsolete things in your code, like the this->* or Uno::. Make the map std::map<String, int> keys;, because now you mix pointers and ints.


Graphing force sensor data routed through HX711?

Include the Time library in your sketch, then print the time and your sensor output as a comma separated list. Your output to the serial monitor can then be written to .csv file using PuTTY, which you will need to download in order to collect data (I used online tutorials to figure out writing to a file with PuTTY). Once in a .csv, you can open the file in Excel to graph the data.


SIM800L module just repeating data sent via serial

You are asking it to repeat the data you sent. It working AS you wanted it to work in your program.

You asked it to see if there is anything sent and if there was, then print it. That's whats it's doing.


Trigger external interrupt on Arduino Uno R3 with an LED and a button

Pin 2 is pulled up by internal R then pulled up when button is pressed?
Connect button to GND.


Writing elegant applications for Arduino

On a multiprocess system, like your typical desktop, you usually have
way more processes than logical CPUs. When programming such systems you
therefore have to avoid burning more CPU cycles than needed. Instead,
when your program has nothing to do, it should just sleep, and leave
the CPU available for other processes.

On an Arduino, you only have one single program running at a time. It is
then not that useful to keep the CPU idle. Also, the power dissipation
is so low that you will not notice the microcontroller getting even
slightly warm. The extra complexity of getting into and out of sleep
mode is therefore not that useful. Only when running on batteries do you
care about saving every possible milliamp: then learning about sleep
modes starts getting useful.


ESP8266 timer to trigger actions (logic issue)

For time-keeping on a long-term basis, you are going to run up against clock drift and offsets from tick-tracking. You may be better off using a real-time-clock (RTC) such as the DS1307. This and RTCs like it are often available in breakout boards with a coin-cell battery holder built in.

You would still get the time from your HTTP or NTP source, but the RTC will be much better at keeping the "right" time as you would expect a wristwatch or desk clock to do, versus using the MCU for counting milliseconds.

You can use Ticks or millis() to set up a periodic read of the RTC every second or every 10 seconds, etc. Avoid using the MCU clock for long-term real-world time keeping.


Can someone help me decipher the code for the arduino? I am totally lost

Not really a physics question, but I will answer anyway.

loop() is the standard Arduino function which contains code that the microprocessor runs repeatedly (as opposed to code in setup() which is only run once).

light = analogRead(5); takes an analogue voltage reading from pin 5, encodes it as an integer value (either 10 or 12 bits depending on the Arduino model) and stores the result in the variable light.

Serial.println(light); outputs the value of the variable light to the Arduino's serial port. This is a standard way of outputting data from the Arduino so that it can be displayed on a connected computer.

analogWrite(3, light/4); outputs the value of light/4 as a phase-width modulated (PWM) signal to pin 3. Although Arduino output pins are either on (5 volts) or off (ground) at any point in time, PWM signals allow the Arduino to switch an output pin on and off rapidly so that the average voltage seen on that pin is an intermediate value. The duty cycle of the PWM signal which determines the average voltage on the pin is encoded as an 8 bit integer, so light is probably divided by 4 here to convert it from 10 bits to 8 bits.

So the Arduino will repeatedly read an input voltage from pin 5, output an integer representing this voltage to the serial port, and create a PWM signal on pin 3 that has an average voltage the same as that of the input voltage.

See the Arduino language reference page for more information.


How to extend my Sketch for Multiple Inputs and Outputs

I'll show you the long but simple way. Just follow this logic in your setup and loop and you'll be ok. If you still don't understand and want more, tell me and I'll add more code for you.

Do something like this:

const int buttonPin1 = 2;    // the pin the button is connected to
const int buttonPin2 = 3;
const int buttonPin3 = 4;
const int buttonPin4 = 5;

const int ledPin = 6;        // the pin the led is connected to
const int ledPin = 7;
const int ledPin = 8;
const int ledPin = 9;

int ledState1 = HIGH;         // the current state of the output pin
int buttonState1;             // the current reading from the input pin
int lastButtonState1 = LOW;   // the previous reading from the input pin
long lastDebounceTime1 = 0;  // the last time the output pin was toggled
long debounceDelay1 = 50;

int ledState2 = HIGH;         // the current state of the output pin
int buttonState2;             // the current reading from the input pin
int lastButtonState2 = LOW;   // the previous reading from the input pin
long lastDebounceTime2 = 0;  // the last time the output pin was toggled
long debounceDelay2 = 50;

int ledState3 = HIGH;         // the current state of the output pin
int buttonState3;             // the current reading from the input pin
int lastButtonState3 = LOW;   // the previous reading from the input pin
long lastDebounceTime3 = 0;  // the last time the output pin was toggled
long debounceDelay3 = 50;

int ledState4 = HIGH;         // the current state of the output pin
int buttonState4;             // the current reading from the input pin
int lastButtonState4 = LOW;   // the previous reading from the input pin
long lastDebounceTime4 = 0;  // the last time the output pin was toggled
long debounceDelay4 = 50;


You can pass in a variable into a function. Something like this:

void runCurl(int verdi) {
    ...
    String myUrl = "student.cs.hioa.no/~s180343/updatedb.php?verdi=";
    myUrl += verdi;
    p.addParameter(myUrl);
    ...
}

You call the function like this, now:

runCurl(1);
runCurl(2);
runCurl(someVar);

and so on. Since it's already in your main loop() function, you just need to set pass in a different number based on whatever it is you're trying to do.


if/else on digitalRead not executing on 'else' portion

(Heh... before even seeing the code I guessed you'd done this...)

You are comparing a pin number, not the results of digitalRead(), and then passing the results of that comparison to digitalRead():

if (digitalRead(LED_BUILTIN == LOW))

It should read:

if (digitalRead(LED_BUILTIN) == LOW)

Note the order of the brackets:  LED_BUILTIN is passed to digitalRead(), and then the result of calling that function is compared to the value LOW.


Dual power supply using Arduino uno and nano

No, because both 5V terminals are +5V.

If both boards are powered by completely isolated power supplies then you could connect the +5V of one to GND on the other. One will then have all its signals and logic negative to your ground level, but normal compared to its own ground level. Managing it though and keeping things separate (no shared ground between two sets of peripherals, etc), would be tricky. And the moment you plug one into your computer the whole lot could go up in smoke.


Cannot open file with underscores using the SD library

[The SD library] uses short 8.3 names for files.

source


XBee using Serial rather than SoftwareSerial--how to fix

You will need an xbee breakout board Xbee breakout board or this one from Sparkfun to do that...

Make sure you check if the board comes with headers as they are not always included. Note also that the xbee socket is not a standard size - which is why you need the breakout board - it converts the XBee pin to a standard size. Here are the 2mm headers required for xbee and regular 0.1" headers required for connection to a breadboard or jumper wires etc.

Actually, I used leonardo for the very reason that you asked about in your question. Leonardo has two serial ports, one is for the usb connection you are familiar with on Uno, but it is not connected to pins 0 and 1.

The other is a completely independent serial port that is wired to pins 0 and 1 on leonardo.

So on Leonardo, you can do Serial.println("Debug msgs"); and Serial1.println("xbee messages"); (note the digit 1 in Serial1). Of course other platforms such as Mega also can be used in the same way.

I am assuming you already have some sort of an XBee shield that allows you to plug the XBee directly into your Uno. The beauty of the Leonardo is that you can continue to use that sheild. The XBee will "automatically" be connected to Serial1.

FWIW, i had all sorts of trouble with s/w serial. I couldn't get it to work with my XBees at all. I could never work out why it did not seem to work.

As soon as i moved to leonardo, it worked like a charm.


"Active LOW" relay board Pin configuration

That relay module is driven by optocouplers. You are just driving and LED, and that is connected though a resistor to VCC.

In the past it was common to use active low for driving things since an N channel MOSFET could typically sink more current than a P channel one could source. Also in the days before CMOS there was really only low-side (sinking) switching, so active low was the norm.

These days it's not necessary, but it's still common because that is how it's always been.

So yes, active low is both common and accepted.


Sharing the hardware UART between the terminal and the ESP generally does not work well. You'll be much better off to add a SoftwareSerial port on another pair of pins to talk the the ESP.


What does it take to compile Linux on Arduino, if at all possible?

Linux is a very complex operating system, but it may be able to fit on an Arduino. Things to consider:

There is no current AVR port of the source code.
You would have no graphics, instead access the terminal over UART.
The filesystem driver would have to be rewritten to access internal flash or an external SD card.
It would be extremely slow! The ATmega328 would run at 16 MHz, or about 20 MHz max (overclocked). Most Linux machines run at a minimum of 400 MHz, and more with graphics.
You would probably need some extra RAM, probably a good idea to use an ATmega2650 (the one in the Mega), which has 16 times the RAM of the Uno. You could also use a Due (6x as fast as the Uno, more RAM).
You may have to write special USB drivers for OTG (on the Due) or MAX3421EE (Mega ADK, USB host shield).

In short, it would take a lot of time and effort, and probably would be too slow for everyday use. If you really want Arduino Linux, check out the Yún.


Battery Solution for ESP8266 and HC-SR04

A time a go when searching for some circuit to provide power to ESP and also being capable of charging batteries I came across this reply here. Is intended for usb charger/Li-Ion batteries but maybe it could suit your needs too and be adapted. In the output the circuit presented there, you could use some LDO like  MCP1825S (or even the MCP1825 with extra information possibilities). Never test the circuit yet, so can not provide any good answer about how long it provides juice to ESP.


Cheapest Arduino wireless solution for home automation

If you want to go for cheap just use a ESP8266 no arduino needed.


Show examples of the error - and install ESPexeption decoder to analyse the stack trace this will at least show why the wdt was caused
So the only thing as of now I can recommend
There is an issue with bearssl:

It's a WDT error caused by an extended SSL negotiation.

Change the core frequency to 160MHz (if not already done) and try again.
Use instead of LWIP1.4 (memory hog) low-mem LWIP2.0 with your program.
Since SSL negotiation can take 5 seconds even at 160MHz for some websites be sure by adding a yield() not to trigger a wdt reset

So without code/ trace and error messages its hard to guess


How to pass a filename to a function? What type of variable is the filename?

String literals are of type const char *. Ordinary char *s can be passed to it though; the const means that the compiler will make sure that the function doesn't attempt to change the contents.

void setFileParameter(const char *filename, int value)
{
   ...
}


Hook Arduino up with thermal printer and power both externally

Setting up the power supplies

As Gerben already stated in the comments, a 9V block battery isn't capable of supplying enough current for the thermal printer, so you cannot simply use one of them (these are meant for low power applications, like a smoke alarm). There are many different types of batteries, that you can use for this. Probably some kind of LiPo or LiIon pack would be suitable. (I'm sure you can find information about pros and cons of different battery types on the web). But the easiest way for you would be an USB power bank, that can supply at least 2.5A. A power bank incorporates mostly a LiIon pack and also already the mandatory smart charging electronics (to charge and discharge correctly and also to monitor the charge level), and - every important - a 5V voltage regulator. You can supply the 5V from the USB power bank directly to the Arduino and thermal printer in parallel. If you need to switch them on and off together (and the power bank doesn't already incorporate some kind of switch), you can use a simple switch between the positive lead from the power banks USB port and the positive leads for Arduino and printer.

  Finding a good button compatible with an arduino

Every normal button is compatible with Arduino. A button is nothing more as a switch, that automatically opens again, if you are not pressing it. Just two pieces of conductive material, that get's pressed together, if you press the button. A normal button has 2 pins (you might see more pins on the button, but mostly some of these are electrically connected together, so that you effectively have only 2 pins). Connect one pin to ground and the other to a digital input pin of the Arduino. Then in your sketch use pinMode(pin_number, INPUT_PULLUP); in your setup() function. This will enable the Arduinos internal pullup resistor, which pulls the pin to HIGH, if the button isn't pressed. If you press the button, the pin will be pulled to LOW. Keep this inverted logic in mind (LOW means pressed, HIGH not pressed).

There are also many button examples for Arduino on the web, since using a button is the second thing to learn with Arduinos (after blinking an LED). Button example code via digitalRead() is also incorporated into the Arduino IDE (look for examples in the menu).

  a sketch of the whole setup

Even, if someone wanted to write the code for you (and this is not a free coding service, so you cannot expect someone to simply do it), you haven't given us enough information, what behavior you want. But please don't add that here, to get this free code. What you are asking (single power source and button) is not difficult. Surely - currently you don't know much about this stuff, but it's not rocket science and there are many many Arduino tutorials on the web to help you. About the code for the thermal printer: Adafruit always provides dedicated guides for the devices they sell. There you can find a description, how the device works and is connected and used. They also provide example code and in most cases complete Arduino libraries, that hide most of the complexity of a task.

You should start by connection the Arduino to the power bank. Then you should go on and get the button going (you can write a sketch to turn the onboard LED on and off with it to learn how it works). Then you can connect the printer. Try adafruits example code. If it works, you can extend your sketch with the printers code.

Note: Some power banks turn of the power completely, if only a small current is flowing out of if. With such a power bank your Arduino might turn of as the power bank cuts the power. It normally does not draw enough current for the power bank. I think this shouldn't happen, when the printer is connected, but this depends on the current, that it draws (considering the minimal current, that it draws while idling), and the current, that is the minimal limit for your specific power bank.


There is no Wire.write(address) in the Wire library. The function write() takes data and puts it into the library internal write buffer. It does nothing on the I2C bus.

For master write operation (sending from master to slave) the following commands are necessary:

Wire.beginTransmission(address);
Wire.write(data);
Wire.endTransmission();

Only the last of these commands does something on the I2C bus. It generates a Start condition, sends the byte consisting of the address (that we set in the beginTransmission() statement) and the direction bit, which is always 0 here, because these commands are meant for master write operation. Then it sends the data and ends the transmission with a stop condition. You cannot control, which value the direction bit has. The parameter of beginTransmission() is only meant to be 7 bit long. If you provide a bigger address, the function will simply cut the highest bit and issuing a write operation anyway.

For master read operation the action on the I2C bus happens inside the requestFrom() function. It sends a Start condition, followed by the address and the direction bit set to 1 (again you cannot control the value of the direction bit here). Then it reads the bytes, that are coming from the slave until all requested bytes were received. Then you can read the bytes from the library internal buffer with the Wire.read() function. Again this function does nothing on the I2C bus. It only interacts with the libraries buffer.


The ESP8266 doesn't know what a "LOW" interrupt is.  You will have to change your code to use FALLING, RISING or CHANGE interrupts only.


No, you don't want a vector, for a number of reasons:

There is no "vector" unless you add extra (unsupported) code.
Vectors use dynamic memory. Arduinos don't work well with dynamic memory.
It's pointless anyway.

Just allocate an array big enough to contain enough timestamps. In a 10 second period, if you get more than 100 beats, the person you are measuring the heart rate of is most likely in a noticeably "unfortunate" state. That's 600bpm. That's entering panicked mouse territory.

Even with that extreme number of beats an array of 100 32-bit values is only 400 bytes.


WS2812B LED strip + Arduino First Pixel keeps dying/breaking

I finally found the solution:

The soldered pin connections at the cable was leaking current. This was due to the soldering flux remaining around the pins. Rinsing the connection with water carefully solved the problem.

Just scraping, and wiping with tissues between the connections is apparently unreliable. The flux is water cleanable, said the cup. Of course by taking care not to make anything wet besides the connection, and drying careful afterwards. Perhaps it failed after a minute or so because the flux started flowing due to heating up.

Thank you for your tips. You help me keep improving myself.

Any more tips on cleaning soldered connections are welcome.


A more elegant way to deal with timers without using delay()?

For excact timing there is feature called ADC Auto Trigger mode. For example millis() are usually counted by timer 0 overflow (on AVR based Arduinos) every 1024us (I suppose it's because of PWM - otherwise it could be set exactly to 1ms). So if you don't mind that little offset, you can configure
ADC with Timer 0 Overflow and use every 20 measure only.
But don't forget that analogRead on another pin changes ADC channel and you will get something else if you don't check it.

As an auto trigger source can be used one of these:

Free Running Mode
Analog Comparator
External Interrupt 0
Timer/Counter 0 Compare Match A
Timer/Counter 0 Overflow
Timer/Counter 1 Compare Match B
Timer/Counter 1 Overflow
Timer/Counter 1 Capture Event

For ATMega328 it can be something like this:

void setup() {
    Serial.begin(57600);

    // ADC setup is done by arduino framework, but it's possible to change it slightly (for ATMega328) :
    ADCSRB  = _BV(ADTS2); // ADTS2..0 = 100, Timer 0 overflow as trigger source
    ADCSRA |= _BV(ADATE); // enable auto trigger mode
    ADCSRA |= _BV(ADIF); // reset conversion interrupt flag (by writing log 1)

    analogRead(A0); // dummy read to set correct channel and to start auto trigger mode
}

int8_t sample_count = 0;
int8_t sample_index = 0;
uint16_t  samples[] = {0, 0, 0, 0, 0};
uint16_t sample_sum = 0;

void loop() {
    if (ADCSRA & _BV(ADIF)) {
        ADCSRA |= _BV(ADIF); // reset ADIF flag by writing logic 1 into it (mentioned in datasheet)
        if (++sample_count == 20) {
            sample_count = 0; // reset sample_count, as we wan't every 20th

            sample_sum -= samples[sample_index];
            samples[sample_index] = ADC; // read value
            sample_sum += samples[sample_index];

            if (++sample_index == 5) { // reset index and count and send average
                sample_index = 0;
                Serial.println(sample_sum);
            }
        }
    }
}


Where do I find the enclosures for an Arduino and a bunch of sensors?

I think your problem is that you are looking specifically for Arduino enclosures. Such a search tends to lead you to boxes for just an Arduino and nothing else - maybe with the headers poking out the top.

Instead, you should be looking more generically. There are thousands and thousands of "project enclosures" from many manufacturers (Hammond is a big name in these).

You take a generic project box of the right size and shape for what you want to create and in a material suitable for your needs, and cut / grind / drill / glue it to be what you want.

Most electronics suppliers will have an "Enclosures and Housings" section on their website. Have a browse through your favourite.

As far as air vents go, one good trick I have used is to simply drill holes (with a steady hand so you get them lined up nice and straight) and glue some fine mesh on the inside.  One good source of fine mesh is to go to your local smoking supplies reseller (tobacconist) and buy some "pipe meshes" (the flat ones, not bowl shaped ones) - also available from low-cost online resellers of any old junk (eBay, etc), which look like this:

(Also available in brass).  They typically come in different mesh sizes to suit your needs.


For a 5V logic output to a 3V3 logic input, you can use a resistive divider to lower the voltage.
When unloaded, a 3V3 logic output is just enough to drive a 5V logic input. Check the AVR datasheet for the exact voltages (0.6 × Vcc = 3V, found under DC Characteristics in the datasheet).

In other words, with a little bit of special care it may just work.

To construct a more reliable and bidirectional solution, use a level shifter. There are several listed on this page but other manufacturers make similar devices.

This document describes how a MOSFET can be used to bidirectionally convert logic levels between different supply voltages.


This is actually pretty simple:

if (s == "digitalWrite(8,LOW);") {
    digitalWrite(8,LOW);
}

Obviously, it will not work is s contains any other string... If you
want something more general, that is able to interpret a wide range of
possible commands, you will have to define a language, and write an
interpreter for that language. From the example you give, it seems you
would like your language to look like C++. This is most likely a bad
design choice. If you want an interpreter that understands the whole C++
language: forget it. You will never fit something this big into an
Arduino Uno.

Here is, for inspiration, a very simple interpreter I
wrote that understand the following commands:

mode <pin> <mode>: pinMode()
read <pin>: digitalRead()
aread <pin>: analogRead()
write <pin> <value>: digitalWrite()
awrite <pin> <value>: analogWrite()
echo <value>: set echo off (0) or on (1)

You can use it a basis for writing your custom interpreter. Otherwise
you can do a Web search for “Arduino interpreter”: you should be able to
find interpreters implementing a wide variety of languages, including
compact binary languages (Firmata), Forth (another one),
Lisp, Basic, and even a C-like language.


Code for ESP32 without Development Board

Welcome to Arduino Stack exchange. There are a lot of discussions and half-completed, or project-specific models available for the ESP32 simulator. My sincere advice is to go ahead and buy real hardware. By the time you take to set up the simulators (download the repo, set environment variables, connect GDB debugger or other), you would have received the ESP32 hardware itself.
Why you should go for real hardware?

An emulator can never match the timing of real ESP32 hardware. if you
have any timing-related issue, you cannot fix it using an ESP32 emulator
Real issues in hardware (bounce/debounce of switches, surge current and brownout voltages, rise time and reflections etc - won't appear in the ESP32 simulators
EMC issues due to floating inputs, Port pin current limits or even self-heating of components are not considered in most the simulators
A code running on the emulator can't always run on the real hardware without modifications, especially when it involved multiple threads and priorities

Still, other options are available online but it depends on your comfort

ESP32 simulator from mireq - ESP-IDF contains a small amount of hardware-specific code, FreeRTOS and few multi-platform libraries. This project uses FreeRTOS port for POSIX, LWIP for TCP/IP layer and mbedtls for cryptography functions.
In addition, several useful APIs from esp-idf are implemented eg. logging. With this project, you can write a program, which will be runnable and testable on Linux.

ESP32 machine emulator - The purpose of this package is to enable you to test-drive (TDD) your MicroPython code in an IDE running on your computer. It seems a lot of people are test-driving python, but not many are test-driving MicroPython. That’s understandable, since many MicroPython projects are simple, and emulating real hardware in a test environment is difficult.

Bridges - Pretend your PC a Raspberry Pi or an ESP32 to connect I2C / SPI / GPIO / UART peripherals.

Note You should also check when is the last time the projects were updated. THe latest ones and active ones are always a better choice as they are expected to have better usability, and stable simulations.


What is arduino_debug.exe for IDE 1.5.6r2?

Windows binaries can either be Window or Console applications. A Window application can NOT produce text output. Text output is the easiest way to gather error messages related to bugs.

Hence, arduino_debug.exe should be used by Windows users that have found a bug in the Arduino IDE and wish to contribute submitting an issue on github.


Why is Serial.write() slower than memcpy()?

If you take a look into the implementation:

size_t HardwareSerial::write(uint8_t c)
{
  _written = true;
  // If the buffer and the data register is empty, just write the byte
  // to the data register and be done. This shortcut helps
  // significantly improve the effective datarate at high (>
  // 500kbit/s) bitrates, where interrupt overhead becomes a slowdown.
  if (_tx_buffer_head == _tx_buffer_tail && bit_is_set(*_ucsra, UDRE0)) {
    // If TXC is cleared before writing UDR and the previous byte
    // completes before writing to UDR, TXC will be set but a byte
    // is still being transmitted causing flush() to return too soon.
    // So writing UDR must happen first.
    // Writing UDR and clearing TC must be done atomically, otherwise
    // interrupts might delay the TXC clear so the byte written to UDR
    // is transmitted (setting TXC) before clearing TXC. Then TXC will
    // be cleared when no bytes are left, causing flush() to hang
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
      *_udr = c;
#ifdef MPCM0
      *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << MPCM0))) | (1 << TXC0);
#else
      *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << TXC0)));
#endif
    }
    return 1;
  }
  tx_buffer_index_t i = (_tx_buffer_head + 1) % SERIAL_TX_BUFFER_SIZE;

  // If the output buffer is full, there's nothing for it other than to
  // wait for the interrupt handler to empty it a bit
  while (i == _tx_buffer_tail) {
    if (bit_is_clear(SREG, SREG_I)) {
      // Interrupts are disabled, so we'll have to poll the data
      // register empty flag ourselves. If it is set, pretend an
      // interrupt has happened and call the handler to free up
      // space for us.
      if(bit_is_set(*_ucsra, UDRE0))
    _tx_udr_empty_irq();
    } else {
      // nop, the interrupt handler will free up space for us
    }
  }

  _tx_buffer[_tx_buffer_head] = c;

  // make atomic to prevent execution of ISR between setting the
  // head pointer and setting the interrupt flag resulting in buffer
  // retransmission
  ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
    _tx_buffer_head = i;
    sbi(*_ucsrb, UDRIE0);
  }

  return 1;
}

It basically answers all the questions.

If the buffer is empty and it's not sending anything, it'll send the character directly so it's synchronous (but sending the character will be much faster than overhead of function callbacks and so)

No, you cannot use memcpy, as it just replaces buffer, but it does nothing else, like actually start the data register ready interrupt nor proper setting of head/tail counters (it's round buffer, so there can be scenario you'll overwrite something outside of buffer)

And write function is called for each character separately (all other specialisation of write are using this one)

Also if the buffer is full, it'll wait until there is a space for another character.


What's the difference between different Ethernet Shields?

Clearly the 'best' one is the one that meets your requirements (or is the most expensive - that's always the best, right?).

You say you need an ethernet shield - can you explain why? Without that information, it's almost impossible to tell you which is the most suitable.

If you are looking at IoT applications, it may be that an Ethernet shield isn't the 'best' thing for you. If you just want access to the local IP network, you could use any of those. If you want the 'best' library of functions to support your application, that may affect which module you use.

For me, I think the best module is the cheapest one that gives me connectivity: http://www.aliexpress.com/item/Hot-Sale-ENC28J60-Ethernet-LAN-Network-Module-For-Arduino-51-AVR-STM32-LPC/32254842414.html

The W5100 is also a good choice, but only if it is under $7


Accidentally plugged in Arduino Uno before installing software, now it's not recognized by Windows 10, only powered by usb port

You do not need to install drivers in Windows 10 (unless you have a CH340G based Chinese clone, in which case it wouldn't have detected before installing the drivers).

Windows 10 has its own CDC/ACM drivers built in - something every other operating system has had for years and Windows has only just caught up with them. That is why it detected COM3 fine before.

It should have worked fine without installing drivers. It may have been the IDE with the wrong port selected or something else interfering with the port that was stopping you using it.

Uninstall the Arduino drivers and revert to using the Windows built-in ones and work on diagnosing why it wasn't working with those.


How can I interrupt a delay() when a button is pressed?

You can use the millis function to check the current 'time'. If you store this, and later call this function again, by subtracting you can see how much time has been passed. so instead of delay(500) you use if (millis() - timeStamp >= 500) { ... to continue your code.

As others said in comments,  you also need to debounce to prevent multiple button triggers.

Edit: Debouncing

There is not a library for debouncing (at least not one on the Arduino site), but you can easily copy the needed code from the following sketch:

Arduino Debounce


Stepper Motor Control - one step at a time

This program drives a unipolar or bipolar stepper motor.
The motor is attached to digital pins 8 - 11 of the Arduino.

The motor will step one step at a time, very slowly. You can use this to test that you've got the four wires of your stepper wired to the correct pins. If wired correctly, all steps should be in the same direction.

Use this also to count the number of steps per revolution of your motor, if you don't know it. Then plug that number into the oneRevolution example to see if you got it right.

#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0;         // number of steps the motor has taken

void setup() {
    // initialize the serial port:
    Serial.begin(9600);
}

void loop() {
    // step one step:
    myStepper.step(1);
    Serial.print("steps:");
    Serial.println(stepCount);
    stepCount++;
    delay(500);
}


Controlling multiple fans using arduino uno

One PWM pin can control only one fan (or one group of fans). You can't have one PWM pin outputting different values to different fans, since one pin can only have one value. (Yes, there are ways of multiplexing it through time slicing but that is both hard and not a good idea).

You need one PWM per fan if you want individual control of each fan's speed. That means a maximum of 6 fans on an Arduino.

To get more you would either have to use software PWM (which can introduce jitter which may not be a problem with simple fans), or an external PWM controller.  Or add more Arduinos.

If all you want is potentiometer control of the fans you can do it without using an Arduino. A pair of op-amps (it can be a single dual op-amp chip), one acting as a triangle wave oscillator, and the other as a comparator, will generate PWM for you.  Here's an example:

  Image by ElectroBOOM (watch his videos sometime, they're hilarious)


basic_insert with WAMP server doesn't connect with MySQL database

I figured it out.  I needed to set up a User (IP  server) in the database.
In phpMyAdmin I created a new user (esp) and set the Host name to the IP address of the ESP8266.  In the sketch I changed the user from "root" to "esp".


Conversion between boolean and int went wrong

Let me the first one to say that 1. Boolean to int conversion shouldn't be this complicated and 2. Much simpler ways to do what you are trying to do.

Like this.

If (bool) boolint |= mask;
  Mask = mask << 1;
  ...

You get the idea.