What is the meaning of the preceding character on several library defines?

I looked into one of these libraries, namely the SparkFun CAN-Bus
Arduino
Library.
The macro appears to be used inside other macros that require two
arguments, for example RESET(P_MOSI);. Given the following
definitions from the library:

#define RESET(x) _XRS(x)
#define _XRS(x,y) PORT(x) &= ~(1<<y)
#define PORT(x) _port2(x)
#define _port2(x) PORT ## x
#define P_MOSI B,3

the call RESET(P_MOSI); expands to

PORTB &= ~(1<<3);

PORTB is the name of an IO port of the MCU which controls the outputs
of the pins. It is actually a macro from
avr-libc that expands to something
like:

(*(volatile uint8_t *)(0x05 + 0x20))

where 0x05 is the IO port number of the register (the number depends
on the particular AVR chip) and 0x20 is an offset needed to get the
memory-mapped address from the IO port number. When the compiler does
constant folding, RESET(P_MOSI); resolves to

*(volatile uint8_t *)0x25 = 8;

which is then compiled into

cbi 0x05, 3

a single assembly instruction (Clear Bit in Io port) that executes in
two CPU cycles and sets to zero the bit 3 of IO port 0x05.

The same end result could be achieved in a much simpler way:

#define P_MOSI 11  // assuming digital 11 = PB3, as in the Uno
#define RESET(x) digitalWrite(x, LOW)

However, the function digitalWrite() is very slow, mostly because it
has to map an Arduino pin number to a port address and a bit number, and
it does it at run time. The SparkFun approach, though somewhat
convoluted, is way more efficient, because the mappings are performed
at compile time.


Lockup while evaluating Wire.requestFrom function (Arduino)

The Wire library has an issue in the lines you posted, that if an interrupt is lost, it will stay in that loop forever. There are two things you could do to fix this:

Stop the interrupt from being lost (ie. fix electrical problems)
Use a library that has a time-out.

For the electrical issues, I would make sure you have pull-up resistors from SDA and SCL to +5V - typically 4.7k (for each one), but that would depend a bit on whether the device already has them. Also make sure you have decoupling capacitors on the Vcc lines as appropriate.

For the software side, there is an alternative library (master only) at
Arduino I2C Master Library.

I haven't personally needed to use that library, as with pull-up resistors and short cable runs, I haven't had problems with the Wire library. However if things are marginal you may well find that it helps.


Is there a limit on how much current a pin can sink?

am I going to fry my board?

Pretty likely outcome. Here's why:

The Arduino Uno uses the atMEGA328 microcontroller, which has an absolute maximum rating of 40 mA source or sink per GPIO. Also, the total current through the supply or ground rails (i.e. the total of all current OP wants the GPIO pins to sink, or source) is rated to a maximum of 150 200 mA.

Realistically, the current graphs in the atMEGA328 datasheet do not even go all the way to 40 mA, hence it is safest to restrict the current to perhaps 20 mA total per GPIO.

In other words, whether a GPIO is used as source or sink, the limits remain pretty low, and in practice, should be kept much lower than the absolute maximum ratings. Even below absolute maximum, running a microcontroller to too high a temperature reduces its life expectancy.

Solution:

Use either BJTs, MOSFETs, or some driver IC such as the ULN2003 to actually drive the current through the LEDs.


How does input from IR receiver to Arduino UNO board work?

You confuse the different technologies here.

PWM is only an output, not an input. So every pin marked with the PWM symbol can OUTPUT a PWM signal. Reading a signal is a totally different task with different hardware involved.
The IR receiver does not output a PWM (meaning Pulse Width Modulation) signal to the Arduino. It ouputs the demodulated IR signal.

So here is what happens: The remote a code, that consists of different periods of "light on" and "light off" (giving pulses of different length, which encode the data from binary format). Since you want to seperate the remotes signal from any other IR signal, that might roam through the air, the remote also modulates the pulses with a special frequency (often this is 38kHz, but might be another frequency around that). This means that every pulse will be chopped into shorter pulses at the specified frequency. This translates to something like: "light on and off with 38kHz for duration x" --> "light off" --> "light on and off with 38kHz for duration y" --> ...

The receiver module senses the IR light comming in and will electronically discard all signals, that don't have the special frequency, and does the demodulation on this. The outputted signal does not have the 38kHz frequency in it anymore. Just the pulses of different length, that encode the data, meaning

The Arduino then reads the length of the pulses (that only consists of sequences of 0V and 5V) and decodes them into a number. This number represents the pressed button.

A proper library for the Arduino can read the different data protocols used in common IR remotes.


Arduino UNO capacitive sensor not working

As found on the Capacitative Sensor Library page (emphasis added):

  Use a 1 megohm resistor (or less maybe) for absolute touch to activate.
  With a 10 megohm resistor the sensor will start to respond 4-6 inches away.
  With a 40 megohm resistor the sensor will start to respond 12-24 inches away (dependent on the foil size). Common resistor sizes usually end at 10 megohm so you may have to solder four 10 megohm resistors end to end.
  One tradeoff with larger resistors is that the sensor's increased sensitivity means that it is slower. Also if the sensor is exposed metal, it is possible that the send pin will never be able to force a change in the receive (sensor) pin, and the sensor will timeout.
  Also experiment with small capacitors (100 pF - .01 uF) to ground, on the sense pin. They improve stability of the sensor.

The two emboldened points suggest that for a touch-piano, it would likely be advantageous to use a lower value resistor such as 1MΩ. Because the sensitivity increases as the resistor value increases, you want to use the lowest possible resistor value to reduce jitter & interference among your signal wires.

Also, later on the page:

  The grounding of the Arduino board is very important in capacitive sensing. The board needs to have some connection to ground, even if this is not a low-impedance path such as a wire attached to a water pipe.

Ensure the Arduino is not run from a battery or unplugged laptop. For capacitative sensing to work, a stable ground connection is needed (via a DC plugpack or USB wall-wart is fine).

As a general note, try testing with only one capacitative connection first, then when that works, re-add the others.


Why is putting a delay() inside of an ISR cause wonky behavior with the Arduino. Whats going on under the hood?

The first problem is that delay() is a busy loop monitoring millis(). The value that millis() returns will not change inside an ISR as interrupts are turned off inside an ISR; this is why ISRs must be as short and fast as possible, or they will interfere with other interupts

So if you call delay() within an ISR your poor AVR is now deadlocked! It is waiting for something to happen that can now never happen.

A second problem is that if your ISR takes too long, you can miss other interrupts; millis() and micros() can miss ticks and become inaccurate!


Using Browser window to display sensor values in realtime

The most obvious way? Not what is the best way? It is a subjective question. The most obvious way would be to do it in a way you know how to. I am sure there are at least 20 ways to do this.

The way I know, and that I would do it is write a PC service that establishes serial communications with the Arduino, transfers data using JSON, and presents a web server I could connect TCP to.  Knowing C# and using existing code I have, it would take less than 15 minutes.


Scan function should do the job.

int tv, ar;
char color[10];
sscanf(value, "%d;%d;%s", &tv, &ar, color);


(Duplicate of this.)
In your example, neither definition of MAX_ARRAY_LEN will use program space nor RAM.  If you were to use the definition somewhere, it will certainly use program space in the instruction that uses that constant:
for (int i=0 i<MAX_ARRAY_LEN, i++)
  Serial.print( my_array[i] );

In this case, a CPU instruction will load the constant 3 into a register.  So you can say that the 3 "used" a byte in the CPU instruction, and is part of the program size.  Most people ignore that, because a loading a variable into i uses both RAM and program space.
The primary advantage of using const instead of #define is that the former allows additional compiler type-checking.
C++ has introduced another keyword, constexpr, which tells the compiler that an entire expression can be evaluated at compile time and reduced to a single constant value.  Read all about it here.
To answer your comment, #define's are not stored anywhere.  They are a simple string substituion that happens before the compiler processes the C++ code.
When you build your sketch, the source files are processed in several phases.  First, there's a preprocessor phase that consumes all the lines that start with '#'.  The results of the preprocessing are sent to the C++ compiler.  The compiler will see all the included files inline, and all #define's will be substituted.
UPDATE
For example, #define XXX 3 will cause the preprocessor to replace all occurrences of XXX in the C++ file with 3.  The C++ compiler will never see XXX, it only sees 3.  You could do a search and replace with your editor, and the C++ compiler would not know the difference.  (Well, there are a few more tricks the preprocessor can do for you, but you only asked about defining a numeric constant.)  The generated code would be identical.
There is no "global space" for #define symbols.  There is a "dictionary" in the preprocessor that is used to perform the substitution, but that is ephemeral.
PROGMEM is not related to #define or const at all.  It is an attribute of a variable that indicates it is to be stored in FLASH, not RAM.  I think the key is that #define is just string substitution, but const is a C++ attribute of a C++ variable.  All of these are equivalent:
#define MAX_ARRAY_SIZE 3
const uint8_t maxArraySize = MAX_ARRAY_SIZE;
int array[ maxArraySize ] = { 1,2,3 };

#define FOO 1,2,3
int array[] = { FOO };
const uint8_t MAX_ARRAY_SIZE = (uint8_t) sizeof(array)/sizeof(array[0]);

#define MAX_ARRAY_SIZE goofyNameThatMeansNothing
const uint8_t MAX_ARRAY_SIZE = 3;
int array[ MAX_ARRAY_SIZE ] = { 1,2,3 };

#define BAR = { 1,2,
int array[] BAR,3};
#define MAX_ARRAY_SIZE sizeof(array)/sizeof(array[0])

I hope that last 2 goofy examples help illustrate what a #define is... string substitution.
The PROGMEM attribute is a separate thing.  It can only be added to C++ variables, and it now requires the variable to also be const.  Extending the above, you could do this:
#define MAX_ARRAY_SIZE 3
const uint8_t maxArraySize = MAX_ARRAY_SIZE;
const int array[ maxArraySize ] PROGMEM = { 1,2,3 }; // a flash array, not RAM

#define FOO 1,2,3
const int array[] PROGMEM = { FOO };
const uint8_t MAX_ARRAY_SIZE = (uint8_t) sizeof(array)/sizeof(array[0]);

#define MAX_ARRAY_SIZE goofyNameThatMeansNothing
const uint8_t MAX_ARRAY_SIZE = 3;
int array[ MAX_ARRAY_SIZE ] PROGMEM = { 1,2,3 };

#define BAR PROGMEM = { 1,2,
const int array[] BAR,3};
#define MAX_ARRAY_SIZE 14

Again, in that last goofy example I used PROGMEM in the #define BAR, but it's just some characters as far as the #define is concerned.  And the last define is just plain wrong, but it will compile.
Because there is no validation of a string substitution, it is usually better to use a const type var = value; that can be validated by the compiler, both when it is defined and again when var is used in some context.
UPDATE 2
You say,

with the const type comes the PROGMEM

Not really.  const is the "read-only" attribute, and the compiler enforces that.
PROGMEM tells the AVR compiler that, if storage is required for this variable, put it in FLASH memory (a special address range) instead of RAM (a different address range).  Because of the AVR architecture, you must access FLASH differently, with special instructions.  The avr.pgmspace.h include file has some routines (macros and inline assembler) for reading from those address spaces.
I emphasized the "storage space required", because the compiler can optimize away the storage.  The literal 3 constant MAX_ARRAY_LEN does not need any storage space.  For this example program:
const int MAX_ARRAY_LEN PROGMEM = 3;

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

  Serial.println( MAX_ARRAY_LEN );
}

void loop() {}

This is the generated code:
  Serial.println( MAX_ARRAY_LEN );
156:    50 e0           ldi r21, 0x00   ; 0
158:    63 e0           ldi r22, 0x03   ; 3
15a:    70 e0           ldi r23, 0x00   ; 0
15c:    82 e2           ldi r24, 0x22   ; 34
15e:    92 e0           ldi r25, 0x02   ; 2
160:    f7 c2           rjmp    .+1518  ; 0x750 <_ZN5Print7printlnEii>

The compiler knows that storage is not required.  The value "3" is pushed directly onto the stack at program location 0x158.  It did not go to RAM nor FLASH (PROGMEM) to load a 3 into a register, and then push that register's value onto the stack.
The compiler knows the value, so it uses the "immediate" form of the instruction to push the 3.
However, for this program:
const int MAX_ARRAY_LEN PROGMEM = 3;

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

  Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
}

void loop() {}

The following code is generated:
  e4:   03 00           .word   0x0003  ; ????
     .
     .
     .
  Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
 158:   50 e0           ldi r21, 0x00   ; 0
 15a:   64 ee           ldi r22, 0xE4   ; 228
 15c:   70 e0           ldi r23, 0x00   ; 0
 15e:   82 e2           ldi r24, 0x22   ; 34
 160:   92 e0           ldi r25, 0x02   ; 2
 162:   b5 c2           rjmp    .+1386      ; 0x6ce <_ZN5Print7printlnEji>

Because I took the address of MAX_ARRAY_LEN, the compiler knew that it had to have storage... in order for it to have an address.  The compiler dutifully locates it in the program space, at 0xE4.  You can see that address being pushed onto the stack at 0x15A.
Without the PROGMEM attribute, the following code is generated:
  Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
 156:   50 e0           ldi r21, 0x00   ; 0
 158:   60 e0           ldi r22, 0x00   ; 0
 15a:   72 e0           ldi r23, 0x02   ; 2
 15c:   84 e2           ldi r24, 0x24   ; 36
 15e:   92 e0           ldi r25, 0x02   ; 2
 160:   b5 c2           rjmp    .+1386      ; 0x6cc <_ZN5Print7printlnEji>

This is a RAM address, 0x200.  Long before setup, a 3 is copied from the program space into RAM.  It is using both program space and RAM.
But this is only because I took the address of MAX_ARRAY_LEN.  In almost all cases, you will be using these as scalar values.  The compiler will not allocate any storage space for them, and the PROGMEM attribute is irrelevant.
You have another question:

Is there any performance hits when reading from Flash vs SRAM?

Yes.  Reading from flash takes twice as many CPU cycles.  It's always a juggling act.  If you need to squeeze every cycle out, make sure your constants do not even need storage space (i.e., don't take their address).  And if it's a PROGMEM array or structure, consider using a cached value (i.e., loaded into a RAM array or structure).  Sometimes you don't have a choice.  If you are out of RAM, you will have to load them from PROGMEM every time you need them, with a small penalty.  RAM, SPEED, SIZE... pick two.


Can I send data from one MKR1000 to another MKR1000

WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.

If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.

client socket

if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

server side

WiFiClient client = server.available();
if (client && client.connected()) {
  String request = client.readStringUntil('\n');
  Serial.println(request);
  client.print("response\n");
  client.stop();
}


How safely write to SD or Eeprom on Arduino power off

I think a "small" capacitor here is not going to do the job as you need to keep power stable until the write is completed.  You need to determine:

How much power am I using?
How quickly can I detect a power outage?
How much time do I need to keep power on the Arduino to complete the write operation(s) I want to complete.

Then you will be in a position to calculate how much capacity you need and whether a capacitor or battery is more appropriate.


Error with Sparkfun MP3 Shield and Arduino Due playing music files

The library is written for the Uno, not the Due. It relies on two instructions that are only available in the AVR compiler.

Newer versions of the core provide a pair of macros, interrupts() and noInterrupts() that should be used in place of sei() and cli() respectively, which should be provided by the Due's core as well to make it cross-platform. However that library has never been updated to work with those macros.

You could replace the sei() and cli() calls in the library with interrupts() and noInterrupts(), however that may not make it work, since it was written with the Uno and other AVR based chips in mind.


Serial.read() returns an int not a String. https://www.arduino.cc/en/Serial/Read

Use an int for incoming (as the example). Or even better use a char and skip all the strings.

Cheers!


Without circuit information and part numbers, one can't say for sure what the problem is.  However, the symptoms suggest that your LEDs turn on when you pull some pin low, rather than when it goes high.  This can happen if, for example, the LED anodes are wired (through a resistor) to V+ and the cathodes are connected to a drive pin.  If, however, the cathodes are connected to  ground through a transistor, positive-logic should apply, rather than negative logic.


Because first the bootloader is executed and takes 2 seconds (or more on a Leonardo) to time out when it doesn't receive a proper response from the computer.


How to save a hex file into Arduino Flash to send it via Serial?

If I understand your question correctly, you need to integrate this data into a .ino script.  Probably as a byte array. Then the script can read the array and Serial.write its content.

You could write a small tool in Python or else on your computer, that takes the text file and converts it into a .h header. Include that into your .ino script. Or use your favorite text editor to format the data into C++ code, and copy/paste that into your script.


Level logic converting for level shifting is different from powering a device.

Logic level is the state of a digital input/output. No voltage (or very little of it) is considered LOW.   Over the threshold voltage is HIGH. On a 3.3V system, if you set pin to HIGH, it has 3.3 V.  On a 5 V system, HIGH is 5 V.

A digital input pin reads HIGH once the threshold voltage is surpassed. If the input pin is for 3.3 V and doesn't have 5 V tolerance, feeding 5 V as HIGH could destroy it.  That is why you need level converter from 5 V to 3.3 V.

If the input pin is for 5 V and the threshold voltage is higher then 3.3 V,  3.3 V input will not be read as HIGH.  That is when you need level converter from 3.3 V to 5 V.

You must consult the 3.3 V device datasheet and check if the input pins are 5 V tolerant.   You should also check the digital pin threshold voltage on a 5 V device in case you want to communicate with it using 3.3 V.


I assume that you are using the Arduino core for the ESP8266 (https://github.com/esp8266/Arduino)

  Am I right that ic2 will not work?

I am not certain, but I get the same impression as you.  It seems that the Expressif SDK only supports master mode.

  If I am right is there an approved way to do ESP to ESP serial comms.

There is no "approved way", but there are many ways you can do it.  A direct serial link will give you a simple pipe of data - what you put in at one end comes out the other.  It's up to you to decide how you format and interpret that data.

My ICSC library may help you with that - I use it to connect an ESP8266 to an BeagleBone Black through serial: https://github.com/MajenkoLibraries/ICSC


Can I compile a sketch for my attiny85 without an arduino board?

Why wouldn't you be able to?

The compiler runs on the computer, not on the Arduino board. You don't need a board to be connected to compile either. If you enable verbose output during compile in the Arduino IDE settings it will tell you where it puts the resulting .hex file, after which you can use avr-dude to upload it to the target MCU.

If you want to use Arduino libraries you'll need to use an core for ATTiny devices (e.g. ATTinyCore). But either way you don't need an Arduino board to compile.

I'd also echo what @Marcus says, for the small devices you are better off completely ditching the Arduino stuff (it's such badly written, bloated, and inefficient), and simply starting with a nice clean C file.

There is nothing stopping you using the Arduino IDE or the avr-libc tools which it uses. If you add your own main() function in a C file and don't put anything in the .ino file you will be able to compile without any of the bloat.


How can I build a simple "Smartwatch" with Arduino Pro Mini and Display?

If your goal is to make a watch you'll need a RTC (Real Time Clock) this can take the form of breakout board, or you can build the circuit yourself. The RTC is needed if you want the mini to display the time. The mini (in fact, most micros) have no internal clock (though they may have a crystal that can simulate time keeping, but this isn't as useful if you want the time)

It sounds like you want an OLED display. They come in watch-like sizes. There are a few small ones. None are touch displays. I have seen larger touch displays. Maybe combine an OLED with a clear capacitive surface?


Ok,

I don't know, why your memory is leaking, but anyway, your program won't work safely.
You defined an array (fullPath) inside the local scope of your function. You return it, which means, you return a pointer to this array. But at the same time, this array gets invalid, because you leave the local scope of your function.

Better define that string outside the function and give it as a parameter to the function. Then you aren't in danger of accessing an invalid pointer. Furthermore your memory leak won't appear.


Using an Arduino and multiplexer for writing to multiple outputs

According to the analogWrite() documentation, apparently the trouble are that you have swapped the args.

The syntax are analogWrite(pin, value), so, the piece

//read the value at the SIG pin
analogWrite(testValue, SIG_pin);

may work if you simply change to

//read the value at the SIG pin
analogWrite(SIG_pin, testValue);

That with respect to code, and i hope it helps you. At the other hand, the circuit, may be a bit dangerous (and can damage the Arduino or the mux) to use LEDs without a current limiter series resistor (330 - 1K Ohm would be nice values, 1/4 W). At least, by a light sight in a datasheet of the CD74HC4067, shows max currents of +/- 25 mA per pin. Similar currents can be driven by the Arduino (Atmega 328P).

So, all depends on the internal construction of the 4067, if are a transparent mux, maybe just with a single resistance in the SIG_pin in that range of resistances, would be fine.

Edit - Some Circuit Troubleshooting

There are some other little tests that you can do after that change in code:

Open the wire that goes from the Arduino to the common of the mux, then place at the output of the same Arduino pin, a LED-resistor series. Then change in program only the value of testvalue at the beginning of the code and check if the led changes their intensity according to that. That would be an Ok for that pin of the Arduino.
Reply the previous step to each of the channel pins. According to the code, you should see an increasing 1 Hz, 4 bits counter (rather, a BCD counter) in thet formed 4 led array. That would be an OK for the channel selection pins.
Remove the leds and connect back the opened lines.

Any fail in steps 1 or 2 may indicate that the pin are damaged but you can use another analog pin and other pins for the channels respectively. But if at step 3 it doesn't works, may be a damaged 4067 or a little hidden bad connection...


Well if it doesn't work then it doesn't work so a safe bet is that chip is damaged.
I found this document. It states:

VBUS pad and jumber can be used to provide 5V to VBUS. By default VBUS is connected to 3.3V; certain USB devices may have issue with
this.

So I deduce that this is connected directly to 3.3V rail of the chip. Providing 5V without opening the jumper (cutting the trace) is the same as putting 5V at the 3.3V pin.

3.3V. Power pin of the shield. Do not supply 5V to this pin - MAX3421E won't be able to detect devices on VBUS and may also be
damaged!

Apparently the "proper" way of doing things is to actually unsolder that jumper or cut the trace.
Sorry.


How do I convert code between Arduino platforms?

The most detailed one seems to be Baldengineer's, but Arduino, SparkFun, and Adafruit have their own as well, although more limited.

As always, the best source for information about them is the datasheets for both the MCU(s) used as well as for the boards themselves.

And note that different macros are predefined for each MCU and feature (e.g. __AVR_ATmega328__ and __AVR_HAVE_MUL__); it is possible to test for their existence in order to customize behavior.


Can an Arduino Pro Mini interface with a full-sized WiFi shield?

I would like to know if they can be connected and, if so, how.

Yes.

  but can we place the shield on the breadboard

No, the pins are misaligned and won't plug in.

  and use jumper wire to connect the necessary pins so the Mini can use the WiFi

Yes - connect the jumper wires directly to the WiFi shield pins.

  If so, how would we know which pins are used,

Read the manual or schematic for your WiFi shield. It probably uses the SPI pins plus a few more.

  and would we need to provide additional power?

It will need a power connection, yes - though "extra" power? Not sure what you mean.


Send AT commands to ESP8266 from Arduino Uno via a SoftwareSerial port

Does anyone know if what I am trying to do is possible?

Absolutely possible :)

  And if it is, what am I doing wrong?

SoftwareSerial isn't capable of 115200 baud rate (despite "allowing" this as a setting).  Some reports suggest as high as 57600 is workable, though in my experience 9600 is best for reliability.  How to change the baud rate on the ESP8266 will depend on the firmware version.  I've had success with AT+IPR=9600.  You only need to run this command once (it's a persistent setting).  I'd suggest, based on your description, that this is the most likely culprit that's causing the "garbage" output you describe.

A couple of other notes:

The ESP8266 runs on 3v3, not 5v, so you shouldn't have it directly connected to the digital pins—you need to run through a logic level converter.  Running 5v can fry your ESP8266.
The Arduino's 3v3 output has insufficient current to support the ESP8266 reliably (50mA Arduino vs up to 300mA for the ESP8266 by some accounts)—try running the ESP8266 off a separate supply.  It probably won't affect simple commands like AT but when you try to connect to a network etc. it may cause unexpected device resets.
As noted by others, you need to send \r\n — so make sure your Serial window is set to send both (this is a drop-down in the serial window)


There is a chance that this arrangement could damage the servo and possibly the Arduino.  The problem is that, depending on the internals of the servo, it could try and draw power for the servo through the data pin when the button is not pressed.  This would both over-stress the internals of the servo and the internals of the Arduino's GPIO pin.

What you could do to mitigate that is to connect the servo's switched power to another GPIO pin of the Arduino, which is set as INPUT.  That will then tell the Arduino when the button is pressed and when it's not pressed. Then you use that information to attach and detach the servo in your code so it is only being actively driven when the button is pressed.


I cannot get my code to play music in a or manner. I have to open one switch then the other. Music should play with either door open

First of all, you have to find out how your magnetic switches work. Are they opened or closed if you attach a magnet to them? Do they behave the same or is one closed and the other opened if you attach a magnet?
Your code above is written for active LOW switches i.e. if the respective door is closed the switch is opened and therefore the logic level of the pin is HIGH. The level is LOW if the door is opened (activated; hence active LOW).
In order your code had a chance to work, the switches must be connect the right way: on one side connect them to GND and on the other side to the respective Arduino pin. If this is not the case, the code must be changed or the switches must be conneted the right way. You did not show us your schematic, so I can not check it for you.
Here is some code to try: But first find out if the switches you use are LOW or HIGH active. I also have no access to an IDE at the moment, so I can not try out the code. Take it as a hint on how to do it.
And one tip from a guy that does the job for 30 years now: Don't comment variables if their names say it all:
//  this sort of comments makes the code unreadable --V
const int ringDoor=2;                          //Ring door

I know it is a common behavior in the Arduino community, but don't write comments after a statement. In your code above I did realize that there are comment for the if statements only when I copied the code in my answer. Comments are only usefull if they say something new and can be read without problems.
#include <SD.h>
#include <TMRpcm.h>
#include <Stepper.h>
TMRpcm tmrpcm;

const int stepsPerRevolution = 2048;
const int ringDoor = 2;
const int necklaceDoor = 7;
const int relayPower = 22;

Stepper myStepper = Stepper( stepsPerRevolution, 8, 10, 9, 11 );

void setup()
{
  Serial.begin( 9600 );
  if ( ! SD.begin( 53 ) )
  {
    Serial.println( "failed!" );
    return;
  }

  tmrpcm.speakerPin = 46;
  myStepper.setSpeed( 5 );
  pinMode( ringDoor, INPUT );
  pinMode( necklaceDoor, INPUT );
  pinMode( relayPower, OUTPUT );

  digitalWrite( ringDoor, HIGH );
  digitalWrite( necklaceDoor, HIGH );

  digitalWrite( relayPower, LOW );
}

void loop() {

  // the following code works if both switches are LOW active
  // (i.e. LOW if the door is open)
  // if the "ringDoor-switch is HIGH active change
  // digitalRead( ringDoor ) == LOW to
  // digitalRead( ringDoor ) == HIGH
  // if the "necklaceDoor-switch is HIGH active change
  // digitalRead( necklaceDoor ) == LOW to
  // digitalRead( necklaceDoor ) == HIGH
  // and
  // digitalRead( necklaceDoor ) == HIGH to
  // digitalRead( necklaceDoor ) == LOW

  if ( ( digitalRead( ringDoor )     == LOW ) ||
       ( digitalRead( necklaceDoor ) == LOW ) )
  {
    // one of the doors is open
    digitalWrite( relayPower, HIGH );
    tmrpcm.play( "music.wav" );
    if ( digitalRead( necklaceDoor ) == HIGH )
    {
      // only the ring door is opend
      myStepper.step( stepsPerRevolution );
      delay( 500 );
      myStepper.step( -stepsPerRevolution );
      delay( 500 );
    }
  }
  else
  {
    digitalWrite( relayPower, LOW );
  }
}


Passing a long string from SoftwareSerial to Serial

The output of the logic analyser is pretty clear. The problem will be a buffer overflow. One question is whether it is the receive buffer or the send buffer.

My best guess is the receive buffer: What could go wrong with your code is that the interrupts used by SoftwareSerial take precedence over the ones used by HardwareSerial. So maybe that's the reason why nothing is sent before the full message is received.

The SoftwareSerial library has a debug flag (_DEBUG) which you can enable to pulse a pin as an overflow indictator.

What I would try is to swap Software- and HardwareSerial (i.e. use SoftwareSerial for the communication with the PC). If the problem is as described above it should then vanish because the HardwareSerial does not block interrupts (nor the program flow) while receiving a byte.


Follow black and white line simultaneously

It depends a bit on your precise requirements. Currently you are following the black line (meaning sensing black in the middle and white on the sides). Instead you could follow the border of that line. To do this you would have to control the motors in a way, so that in at the middle of the sensors there is a high contrast (black at the right, white at the left, or vice versa). It will not follow the exact same path as before, but a bit to the side.


Bad Communication with Multiple I2C Devices

I would like to know why when one device is bad (or not powered) on
  I2C, it screws up the other devices.

The I2C lines need to have a pull up resistor to provide the high. The master device, and the slave devices, ground the line to provide a low, but they release the line, and not drive it at all, in order to provide the high.

Consider switches a and b to be inside the I2C device. When the switch a is open point A will be at 5 volts. When switch a is closed, point A will be at 0 volts.

Now if you had a second set of R resistors on the same line, but powered from their own 5 volt power supply, the same voltages will be seen at A when switch a is open (5 volts) and switch a is closed (0 volts).

But now if we kill the supply feeding the second set of R resistors (sorry that I can't show them in a picture) instead of pulling up to 5 volts (because we killed the 5 volts) the resistors will be pulling down due to whatever other loads there are on the killed 5 volt supply. And just for argument sake, let's say the killed 5 volt supply was at 0 volts.

So if one set of resistors is pulling up to 5 volts (the still powered pair) and one pulling down (the killed pair) then the voltage at points A and B will not be as high as the 5 volts we would see when the switches are open.  If all the resistors R were the same value, and the killed supply was at 0 volts, then the highest voltage at A or B would be 2.5 volts. And that is not a good high.

So the additional device, that is not being powered, has disrupted the communitations, preventing true highs. Lows are not affected as the switch will pull the line low.

I don't know the values of all your pull up resistors, and don't know how low the dead supply goes, so I can't say what the new lower highest voltage is. But it seems that it is low enough to make the communications stop working.

And the resistor are not the only thing that can be disgusting the high. The unpowered chip can be providing unexpected current paths. Most port pins have an internal diode to Vcc. And since the chip has no power on Vcc the current on the I2C lines can follow that path to ground.

Also, I think you have drawn the resistors wrong. If they were in series with the SDA and the SCL pins there would be no communications because the 1k resistors doesn't allow the SDA line to be pulled low enough. I think those resistors are pull up resistors. Maybe you can take another look and confirm the connection.


Boost an audio signal for analog read - Envelope Detector

it sounds like what you are wanting to do is to detect a minimum threshold of sound so that your speaker power source can be turned on when an audio signal is playing.

You need to amplify your signal while also avoiding voltages that exceed the maximum input specification and also don't go negative. One way to accomplish this is with an operational amplifier (op-amp) circuit. A specific type will accomplish all three requirements. An op-amp that is powered by a single-sided supply, for example +5V and ground, will prevent negative voltages and limit the maximum voltage exceeding what the Arduino can take.

For your application, you don't really care about making a high-quality audio amplifier. You care about not distorting the signal (music) that you are monitoring and detecting a threshold level. Op-amps are good because they have high impedance inputs (they don't draw much (or any) current from your music signal) and they work with few external components.

A classic text for learning about electronics is Horowitz and Hill. Alternatively, you can find references for circuit designs on-line with appropriate searches. For any op-amp that you buy, you can get a datasheet that tells you how to use it. The following reference goes into detail (maybe too much) about single supply op-amps.

Circuits (and search terms) that you might find useful are op-amp follower, single supply, bias, and capacitive coupling. You'll need to purchase components. A good supplier is DigiKey. DigiKey has an on-line catalog that allows you to do a parametric search to identify the components that you need. You'll need a breadboard, resistors, capacitors, and the op-amp in a dual-inline package (DIP).

One search filters the list of possibilities from tens of thousands to a reasonable number. The LM833 Datasheet here is a reasonable choice.

Test equipment, like a single generator and oscilloscope can be very helpful when building amplifiers. You might be able to digitize your amplified signal with your Arduino if you don't have access to test equipment.


EEPROM programmer works with serial monitor but not with pySerial

I figured out the problem. The for loop was writing one byte at a time, which probably wasn't fast enough and caused a timeout in the arudino. The code is now:
page = 0
for x in range(128): # 128 pages in 32K eeprom
    datalst = []
    for i in range(256):
        datalst.append(data[(page * 256) + i])

    ser.write(datalst)

    #wait until receive 's' from arduino
    while True:
        if ser.in_waiting > 0:
            suc = ser.read(size=1)
            if suc == b's':
                print("Success")
                break

    page += 1

I also changed the data types in the arduino sketch to use the ones in stdint.h which solved an unrelated bug. Let me know if I should post the full code for both.


Given the time scale of the measurements, performance is not an issue.
And since you are not computing in real-time, as the samples are being
measured, you can apply the definition of cross-correlation as is, and
compute it in a double loop. The only difficulty is figuring out that
cross-correlation may not be the proper tool for the job... and finding
the right one! My assumption is that you want to estimate a rotation
angle between the two measurements.

The mathematical definition of cross-correlation assumes infinite
arrays. In practice, cross-correlation is often used to locate a short
pattern inside a long signal. In this case, the computation is done only
for shifts where the pattern completely overlaps the signal. Then the
length of the result is

length(result) = length(signal) − length(pattern) + 1

In your case, since your pattern is a previously measured signal, this
would give a single-sample result, which is useless.

You could instead compute the integral for all shifts where there is
any overlap between the pattern and the signal. This is equivalent to
zero-padding the signal. This has the drawback of biasing the result: if
your signal and pattern are both featureless (positive constants), you
will find a very nice peak at zero shift!

You can remove this bias by subtracting the average from both the signal
and the pattern, and correlating (signal − avg(signal)) with
(pattern − avg(pattern)). This still carries a bias for “big”
features. Imagine for example that, after removing the averages, you
have

pattern = [  0,   0, −20, +20,   0,   0];
signal  = [−50, +50,   0,   0, −20, +20];

You would expect your correlator to find a good match between the
[−20, +20] of the pattern and the [−20, +20] of the signal. The
correlation is, however, much better with the [−50, +50] of the signal.
You may try to alleviate this by computing a normalized
cross-correlation instead, but you will at best make both matches
equally good.

My suggestion is that you completely forget about correlations and
instead think in terms of “goodness of fit”. Correlations are good for
finding scaled and shifted copies of a pattern inside a signal. You are
looking for shifted only copies, with no scaling. Your question should
be: if you shift the pattern by some amount, how well does it fit the
signal? What amount of shift gives the better fit? The canonical answer
to all “goodness of fit” questions is to minimize the RMS difference
between the two: you compute the sum

S = Σ(signal − shifted(pattern))²

Then the RMS difference is

RMS(difference) = √(S/N)

where N is the number of samples involved in the sum. The most likely
shift is the one that minimizes this error. In practice, you do not need
the square root, you just minimize

RMS(difference)² = Σ(signal − shifted(pattern))² / N

You can implement this formula as-is, it's completely straightforward.
Just beware that N depends on the shift, as it's the length of the
overlap. And avoid going to very small overlaps (i.e. large shifts).

Now, if you expand the square inside the sum, you may find that, after
all, this is not so far from a cross-correlation... And BTW, all this
has nothing to do with Arduino.


is it possible to power esp8266 with button cell

No. It has to wake up to do something and turn on the wifi. At that moment it requires too much power for a button cell. It needs about 150mA, mostly for wifi.

The BLE (Bluetooth Low Energy) is specifically designed for low power usage. Also some RF modules (433MHz, 868MHz, 915MHz) can be used with a small battery.


Using Serial.write() to send a uint32_t send one byte x4 or send 4 bytes x1

Unless you are using very high baud rates, (at least higher than
115.2 kb/s), it should make no difference.

The reason is that either version of your code should run faster than
the UART. Serial.write() doesn't wait for the bytes to be sent out the
wire. Instead, it just stores those bytes in a ring buffer that belongs
to the HardwareSerial library. When the UART is ready to accept an
outbound byte, it triggers an interrupt. The corresponding ISR takes one
byte from the ring buffer and handles it to the UART. Since the UART
itself is double-buffered, all this happens while the previous byte is
being sent.

The end result is that, with either version of your code, you end up
with a continuous byte stream. The start bit of the second byte comes
right after the stop bit of the first byte, and so on. The stream
doesn't pause until the full message is sent. That is, unless you have
somewhere in your program overly long critical sections that can impose
excessive latency to the whole process.

Side note: if your MCU is little endian (most Arduinos are), you
could also avoid one copy and just do

Serial.write((byte *) &dCodedIR, 4);

Addendum: The details may depend on the MCU you are using. On an
Uno, or similar AVR-based boards, the UART has no knowledge of the
software ring buffer. It rises the UDRE0 (data register empty) flag
whenever it is ready to accept an outbound byte in its sender data
register. When there is data in the buffer, the software enables the
data register empty interrupt, which is tied to the UDRE0 flag.


How shiftOut function works internally? (explanation on source code)

I'll assume bitOrder == LSBFIRST.

i is the bit number, i.e. the “index” of the next bit to write
1 is 00000001 in binary
<< is the shift left operator. It returns its first argument shifted left by as many positions as indicated by the second argument
1<<i is binary 00000001 shifted left by i positions, i.e. something like 0...010...0, where the single 1 is in the i-th position counting from the right (rightmost being position 0)
& is the “bitwise and operator”, where any_bit & 0 is zero and any_bit & 1 is any_bit
val & (1 << i) is 0...0(i-th bit of val)0...0 in binary, where the i-th bit of val is in the i-th position of the result
!! is a double negation: it converts zero to zero and any non-zero value to one
!!(val & (1 << i)) is either 0 or 1, and is exactly the i-th bit of val


It sounds like a blown protection diode MBR0520 in between USB and +5V of the nano.


Send data to Programmable Power supply from Arduino by RS232

First you will need a TTL to RS-232 adaptor. These are most commonly known as the "MAX232" and is available as a little module.
This will convert the 0-5V TTL signal the Arudino produces into the ±10V signal that RS-232 uses. There's plenty of tutorials online about how to use them.
Then you need to generate the signal. Yes, for the Arduino UNO the SoftwareSerial library is what you want.  Again there's plenty of tutorials on using it.
To actually send the instructions it may be something like:
#include <SoftwareSerial.h>

SoftwareSerial PSU(10, 11); // RX, TX

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

void loop() {
    for (int i = 0; i < 11000; i += 100) { // I'm working in millivolts here.
        PSU.print("VSET1:");
        PSU.println(i / 1000.0, 2); // Convert millivolts into volts with 2 DP
        delay(10); // 10ms delay
    }
}

I haven't tested it, but that should give you 0-11v rising at 0.1v per 10ms.


Code working well on Arduino Uno is not working with Mega 2560

It's not working because code you write is code that will work only on ATmega328. Every ATmega328 chip will run this code without any problem.
If you want that Mega does same task as Uno, then you have to rewrite whole code and use Arduino functions(such as pinMode, digitalRead etc..) or read ATmega2560 datasheet and use ATmega2560 registers. Also Search for ATmega2560 pin layout, you'll need it if you want use registers.


How does the motor shield determines how much voltage to supply to a motor?

Can i connect 6v DC motor and 12v DC motor to adafruit motor shield v1, and an external 12v power supply?

No.

  how does it determine how much voltage needs to be supplied to a motor?

It doesn't. It supplies whatever voltage you supply through the power input.

You must match the power supply to the motor. The motor shield is merely a switch that turns the power on and off in the right way to change the speed and direction of the motor.


Power consumption

The Arduino boards use a fair bit of power compared to other embedded systems with similar functionality.

There are three main factors:

The NCP1117 (datasheet) 5V linear regulator in the Arduino UNO
R3 (schematic) has a quiescent current of around 6mA.
The ATMega328P (datasheet) draws around 5mA @ 8MHz and 5V, and probably more than double that at 16MHz.
user2973: The ATMega16U2 used for USB communications also draws approximately 13mA.

LEDs and other peripherals also draw some current. In your circuit, the LCD backlight is probably drawing 4mA as well.

When dropping 9V to 5V via a linear regulator, almost half of the power is lost by the regulator due to its 4V drop. Duncan comments that this nearly doubles the quiescent power draw from 9V as well as the power needed for every mA of 5V, since 4/9ths of the power gets wasted as heat by the voltage regulator. An efficient switching regulator would put out 5V with little wasted energy, effectively reducing the current draw seen by the battery by 4/9ths.

A duracell 9V battery (datasheet) drops from 9V to 7V in around 7.5 hours with a 50mA current draw. Therefore, a rough guess is that your circuit draws around 25mA, which sounds about right based on the description of your circuit.

Note, alkaline battery life is non-linear with respect to current. For very small currents (<1mA) the life of an Alkaline approaches that of a lithium battery.

Getting current down

Here are some tips to get the current consumption down:

Regulator: Replace the regulator with one with a low quiescent current, or better yet, a switching regulator (also with low quiescent current). A switching regulator uses 'pulses' of current and some external inductor and capacitors to give a reasonable steady voltage output. It doesn't waste energy like with the voltage drop of linear regulator and efficiency in the high 90% are possible.

There are buck (step down) converters that take the battery as input, then connect directly to 5V and GND, bypassing VIN and the regulator. This one from Pololu both steps up and down, and has 0.1mA quiescent current.
Alternatively, you could use some 1.5V alkaline batteries, and a boost (step up) converter to get the voltage up to 5V (e.g. this product from Sparkfun). It seems boost converters are more commonly stocked.
Finally, you could buy a rechargeable lithium battery with charging shield. This advantage of this is not having to buy new batteries, and for a tiny bit bigger than a 9V battery the lithium one has much greater capacity. A really cool product is the seeeduino stalker waterproof kit that includes a charging circuit, battery, solar panel and other goodies.

ATMega328P: Rather than using delay for timing and spinning in loop endlessly waiting for something to happen, re-write your code so that it goes to sleep in between sensor reads, etc. There are a few low power libraries out there that use the watchdog timer for periodic wakeup from sleep which are handy. You can get the current consumption of the ATMega328P below 0.1mA during sleep.
LCD: Turn off the backlight, or even the entire LCD. Add a button to the design that the user can push to activate the LCD and have it turn off after a set amount of inactivity.
Peripherals: Most peripheral chips also have a sleep mode that drastically reduces their power consumption. Remove power LEDs and other indicators that are not necessary.
ATMegu16U2: user2973 comments It seems this chip is quite power hungry (user2973). It could be removed to save power and just use the UART instead, but that seems like overkill. There are Arduino Pro boards that are just the bare bones Arduino without the USB interface that could be used instead of the UNO.
Batteries: Other alkaline cells have much greater capacity. For example, a 1.5V AA has over 2000mAh for low currents. Using AA cells plus a boost converter can increase the time before battery replacement. Use D cells (16000mAh) and it will run for quite a while. :D

Summary

With appropriate power supply and coding you can get a reasonable amount of life out of a battery. Using the above principles, I have made an Arduino derivative board that measures a few sensors and stores the readings to an SD card every half a second. It can last for about 4 months on 2 AA batteries, so it is definetly possible to have low power and remain in the Arduino ecosystem.

The chip I used for the low power in my board is the LTC3525-3.3V. It takes an input voltage as low as 0.8V and boosts up to 3.3V and a 5V version is also available. I designed a PCB for this chip as there was no ready-made breakout, and in the datasheet there are reference designs. The main critera for choosing this chip was it still had high efficiency at very low currents. Some other converters need a small minimum current draw.

The biggest consumer of power on the board ended up being the micro SD card. It can vary between 0.1mA and 1.5mA of idle current depending on the manufacturer. I have found Verbatim and Lexar cards to consume the least amount of power. I will this EE.SE question up to date with the results of my micro SD card power consumption tests.


What is the point of a adafruit data logger

Are you referring to this?

That is a shield that has an SD card interface (with appropriate level-shifting for the SD card) plus a real-time clock.

The rest is "prototyping" area for you to install your own devices.

  In order to play an audio file, I was suggested to get an Adafruit data logger

I don't see how this helps play audio files, however you might read the audio file from the SD card. Then you need to send it to a DAC (digital-to-analog converter) to convert the digital information to analogue.

The Adafruit data logger is fine for recording data (for example, temperatures) but I don't see why someone would recommend it for playing audio files (apart from the SD card interface).

  my question is still, why data logger?

Better ask the person that recommended it, eh?


Weight scale with Arduino: calibration step

It may be that in this application (beehive monitoring) it is not required to re-calibrate your load sensors before each use.  When a person is observing a scale to measure their own weight they will be sensitive to the scale reading zero before each use.  Even though being, say, a lb off is likely less than a 1% error when measuring their total body weight.  This site talks about load cell calibration and "recommends a yearly recalibration interval".  They also talk about temperature compensation.
As temperature and humidity will be monitored.  And nonlinear load sensor response to weight can be compensated in software, consider testing your setup under different conditions to determine what considerations need to be taken into account to provide the desired accuracy.

This image is from https://www.futek.com/load-cell-calibration-services


Detecting ground distance through rubber

It may be easier to suggest a solution if you were to "describe the goal" of your project.

If this is just a science experiment, I like your idea of accelerometers.  What you need then is to take the next step and understand dead-reckoning in order to determine the height of the ball.

In other words, the integral of acceleration is velocity.  And the integral of velocity is position.  That means the integral of the integral of acceleration is position. As you may or may not know, for each integral you add a constant. The current speed for the first integral operation and the current position for the second.  But we can assume we can detect hitting the ground.  And, at that point, our position is X = 0 and our velocity is also 0.

That said, dead reckoning is difficult to use mostly because of the accumulated errors.  However, you may have more luck as you get to "reset" your values each time you detect impacting the ground.


I2C is 8-bit data bus, where address can be 7 bit or 10 bit, you can't send more than 8 bit at a time, if you want to send data more than 8 bit you will be sending them like this, for example let you need to send 16 bit data then you send 8 bit LSB first and then 8 bit MSB or vice versa as per your configuration.

Secondly I had noticed you code and noticed many errors, the major one is that you hadn't followed the rules of I2C protocol in your code. I am here attached a link for sample program of arduino i2c slave and master. Go through it you will get your answer.


Handling multiple patterns at the same time is certainly possible with a platform like Arduino, and there are a number of ways you could go about it.

One method I would consider is writing functions which effectively represent each pattern mathematically. You'd just pass it the total time that's elapsed in your program so far, and it will do the appropriate action for that specific moment in time. It will return immediately afterwards (no delays or anything).

To do that, you'll first need to know how long a single cycle of the pattern lasts. You can then use the modulo operator to figure out how far through the current cycle you are. From there, all you need to do is have some if conditions to determine what to do at any given time.

Here's what it might look like for your "5 seconds on, 5 seconds off" pattern:

function pattern5on5off(unsigned long totalTime)
{
  // Calculate how far through the current cycle we are
  const unsigned long cycleTime = totalTime % 10000;

  // If we're in the first 5 seconds of the cycle then turn the light on.
  // Otherwise, turn it off.
  if (cycleTime < 5000)
    digitalWrite(3, HIGH);
  else
    digitalWrite(3, LOW);
}

Admittedly, constantly calling digitalWrite() when you don't technically need to isn't very efficient. It shouldn't cause any harm though, and is fairly easy to optimise if necessary.

To use the above example in a sketch, you'd just need to call it in loop(), and pass the number you get from millis(); e.g.:

void loop()
{
  const unsigned long totalTime = millis();

  pattern5on5off(totalTime);

  // call other patterns here...
}

Other patterns will be more complex, but follow the same principle. You'd just to use appropriate if statements to express your logic.

The vital thing to remember is that the function represents a specific moment in time. It should never pause or delay the program, otherwise it will prevent the other patterns from running.

Edit: Timing on the first cycle
As jfpoilpret noted in the comments, the very first cycle will start at a random point. This is because the first time you call millis() in loop(), it won't start at 0 (the device will already have been running for a short time before loop() gets called). It's easy to resolve though, if necessary.

You would do it by offsetting the totalTime value by the whatever value you got on the very first time around loop(). For example:

unsigned long g_startTime = 0;

void loop()
{
  unsigned long totalTime = 0;

  if (g_startTime == 0) {
    // This is the first cycle.
    // Store the start time so we can compensate later.
    g_startTime = millis();

  } else {
    // This is not the first cycle.
    // Compensate for the start time.
    totalTime = millis() - g_startTime;
  }

  pattern5on5off(totalTime);
  // etc..
}


Can I connect an Arduino Uno Wifi to Arduino Cloud?

If you sign in to Arduino Cloud the very first thing it asks you is which board you are using. One of the options is the Arduino WiFi Shield 101. That is a shield that you can attach to any Uno-footprint board (including the Uno) to give it encrypted WiFi.

Another option is the Yun shield which turns your Uno into a kind-of Yun.

There are many many other "clouds*" that support Arduino, and many that if you are a reasonable programmer should be simple enough to make work with Arduino, since 99.99% of them all work through some form of HTML-based interface.

* Cloud: n. An idiotic buzzword used to describe pretty much any website these days.


CC3000 gets wrong address when connecting to wireless AP

I realized that I was using firmware v 1.34 on the board, which is what it was configured with when I got it, and decided I would try to downgrade it to one of the fir;ware sets supplied by adafruit to see if that would work.

The firmware modifying program didn't actually compile on the desktop version of the arduino ide, so I decided to use codebender instead.

I'm not sure whether or not I should be disappointed or relieved, but downgrading the firmware actually made it work. I used the file titled driverpath_1_11, which I believe the libraries refer to as firmware version 0x113 or 0x118, which identifies itself as firmware version 1.24, which somehow actually worked.

The solution is here: https://codebender.cc/sketch:318229

The pins have been changed to correspond with the fixed pings used by the tinyduino.


You need to use Serial.print instead of Serial.write.


I have not used the RF24 libary, but below are the register settings that should be written during void setup() to use the ACK_PAYLOAD functionality (N.B. nRF24L01+ only, does not exist on nRF24L01.  Check you are using the right version of the radio!)

TX:

0x00 CONFIG = PTX mode
0x0B RX_PW_P0 = Number of data bytes in pipe 0
0x1C DYNPD = 0x01. Enable dynamic payload on pipe 0 (set DPL_P0 bit)
0x1D FEATURE = 0x06 (set bits EN_DPL and EN_ACK_PAY).

RX

0x00 CONFIG = PRX mode
0x0B RX_PW_P0 = Number of data bytes in pipe 0
0x1C DYNPD = 0x01. Enable dynamic payload on pipe 0 (set DPL_P0 bit)
0x1D FEATURE = 0x06 (set bits EN_DPL and EN_ACK_PAY).
Finally, load an initial payload using the W_ACK_PAYLOAD instruction 0xA8, i.e. SPI.transfer(0xA8); SPI.transfer(payload);.


Set Arduino digitalRead reference voltage

You could try not digitalRead, but analogReadVoltage. Analog Read Voltage

From Arduino examples:

/*
  ReadAnalogVoltage
  Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

 This example code is in the public domain.
 */

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float voltage = sensorValue * (5.0 / 1023.0);
  // print out the value you read:
  Serial.println(voltage);
}


There are several alternatives. The best choice for you depends on the
time resolution you need and the maximum duration you may want to
measure:

millis() is good for slow things. It has a resolution of 2 ms
(it increments by steps of 1 ms most of the time, but 2 ms
occasionally) and can measure durations as long as 49.7 days.
micros() is the easy choice for when you want more resolution for
faster things. It increments in steps of 4 µs and is limited to
about 71.6 minutes.
For very fast things, you can get single-cycle resolution if you
configure Timer 1 to count at the full CPU speed, assuming you
don't need the timer for something else. But beware the timer will
roll over roughly every 4.1 milliseconds.
You could also use Timer 1 with the prescaler set at ÷8 in order
to expand the measurable range to 32.8 ms, at the cost of a
degraded resolution.

Here is a table summing up the available methods, sorted by resolution:

method        data type  resolution  max. duration
--------------------------------------------------
millis()       uint32_t        2 ms     49.7 days
micros()       uint32_t        4 µs     71.6 min
Timer 1 (÷8)   uint16_t      0.5 µs     32.8 ms
Timer 1 (÷1)   uint16_t     62.5 ns      4.1 ms


Keyboard.println missing characters when I print long strings

I'd bet the issue is overflowing the keyboard buffer of the device you're talking to. On Windows, you can change a registry value to make the buffer larger:

http://www.windowsnetworking.com/kbase/WindowsTips/WindowsNT/RegistryTips/Hardware/KeyboardBufferSize.html

(and in fact, the Windows keyboard buffer is 100 characters by default.)

The reason the capitalization is becoming strange is because the device missed the shift-down or shift-up event, so it's using whatever it would use if the shift key wasn't pressed or released.

The best solution is to avoid sending so much: break it down and send a little at a time as Gerben said.


Does Leonardo need a separate power supply?

Power steering is performed by the assembly labelled "+5V AUTO SELECTOR" at the bottom of the page. The voltage at VIN is halved and then compared with the board's 3.3V output in order to determine whether or not to enable USB power via T1.


Use JYETech 2.4 Inch LCD Display Screen Module with Arduino?

That display is an ILI9341 based one. On the DSO138 it connects the data pins D0-D7 to PORTB of the STM32.

You need to connect those 8 pins to 8 pins on the Arduino, along with the RS (Register Select) and CS (Chip Select) pins. The RD pin can be connected to 3.3V and the WR pin to GND, since you only really want to write to the screen (if you do want to read from the screen then you will want to connect RD and WR to two IO pins as well). Reset can be connected to a GPIO or to 3.3V, depending on if you want to do a hard reset at any point or not.

LED-A can connect to 5V, and each of the LED-K* pins should connect to ground through a resistor each. The size of the resistor will set the backlight brightness (try 100Ω to start with).

Then it's just a matter of finding a library that works with the ILI9341 in 8-bit parallel mode (u8glib maybe? I don't know, I never use Arduino to drive a TFT).

Note that since this is a 3.3V device you should really use a level shifter for all the digital signals.


Project wont compile when I place functions below function calls

You need to declare your function before you use it.  So either the whole function body needs to be before the usage, or you must add a function prototype declaration.

void myfunction();

myfunction();

void myfunction(){
  return 0;
}


It is not an exclusive property of millis(). Any counter with a limited number of digits eventually returns to zero. For example, a 4 digit tally counter returns to zeros after 9999.

Under the hood, the variable for millis() is of type unsigned long, which is 32 bits on the Arduino. In this case, the 32 bits (binary 0's and 1's) are similar to the digits (0 thru 9) on the tally counter.

The maximum is 11111111 11111111 11111111 11111111. Once there, millis() returns to zero when you add 1.  The maximum (32 "ones") is 2^32 - 1, which equals 4294967295 in the decimal number system. The maximum value for the counter is, therefore, 4,294,967,295 milliseconds.   Converted to days you get approximately 49.71 days.


What are the different types of high-speed serial data transfer protocols, and how do they work (ex: baudrate, synchronous vs asynchronous, etc)?

Basically there are two kinds of serial: Asynchronous and Synchronous.

With asynchronous, which is what serial as in UART and RS-232 are, it's all down to how accurate a system's clock is.  Both ends of the line have to agree on the same speed (baud rate) and any deviation from that causes transmission errors.  The more accurately the two ends can agree on their baud rates the faster you can transfer data.

Note that on many systems (Arduino included) when you ask for one baud rate you actually get a slightly different baud rate.  That's due to the way that the internal UART hardware works - it divides the system clock into finer and finer bits to get as close to the requested baud rate as possible.  Lower baud rates are easer to get close to, but higher ones are much harder.  So it's "safer" to use a lower baud rate which gives more reliable communication to a greater variety of devices.

http://en.wikipedia.org/wiki/Universal_asynchronous_receiver/transmitter

The other kind of serial, synchronous, uses an extra wire for the transmitting (or master) end of the connection to send the clock to the receiving (slave) end.  The receiver uses the incoming clock to know precisely when it should look at the data line to receive a bit of data.  This is how things like SPI and I²C work, and very high baud rates can be achieved.  Speeds in the tens of megahertz are common.

http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
http://en.wikipedia.org/wiki/I%C2%B2C

Some synchronous systems (such as Ethernet), instead of providing the clock as a discrete wire, encode the clock into the data stream.  This keeps the number of wires to a minimum yet allows high speed data transfer.  The down side is that this usually means the maximum speed you can run at is actually slightly lower since the effective size of the data being transmitted is increased.

http://en.wikipedia.org/wiki/Clock_recovery


Use a switching regulator such as the LM2596. You can get a ready board from eBay for about US$1.

Just set the output voltage to 5 V and feed the Vcc input of Arduino; this bypasses the onboard regulator.

The benefit is that unlike the linear onboard regulator, a switching regulator is very efficient which means less consumption and less generated heat on the regulator. An additional benefit is that it can withstand a higher input voltage (about 35 V for the specified regulator), just in case the circuit is used in a vehicle that has 24 V batteries.

The regulator has already several protections like for short circuiting, overheating, etc.


How to know if arduino activated its short breaker?

It sounds like connecting your Laser to the 5 volts power supply did draw too much current, thereby the 5 volts dropped to very low voltage.

The Arduino didn't "protect" itself.  The Arduino simply shut down because of voltage being too low. Then, upon reapplication of 5 volts the Arduino re-started as normal.

You don't mention any details about the Laser.  But if your Laser is simply a Diode, the Laser diode would draw a lot of current, resulting in the 5 volts power source giving reduced voltage.

If your Laser is a "laser module" with a built in driver, perhaps you connected the Laser backwards to the 5 volts.

EDIT 11/20/2015 :  IF you are using the Arduino UNO ,  : The  PolyFuse only protects from 500 mA overload on the USB connector.  Schematic for the UNO shows that 5 volts for USB is called "XUSB". The  PolyFuse connects from "USB VCC" to the XUSB.  When you connected your Laser to the +5 and ground, the  PolyFuse was not involved. (Unless of course you did connect to the USB 5 volts (XUSB), and didn't tell us that.

HOWEVER,  if you powered your UNO from the USB port, then the  PolyFuse WAS involved and did shut you down as others have commented.


Arduino crashed my computer when I plug in the USB cable

It could possibly be that there is a fault that is causing a short circuit. This short circuit could be in the board itself or the USB cable that connects the Arduino. The USB port on the Mac should have protection to protect against a short circuit. Your comments have indicated that you have tested for a short and found none - but this is helpful for others that are looking for a solution.

In your comments you mention that you solved this by changing the positive rail of your potentiometer from 3.3V rail to the 5V rail.


ESP8266-01E is not responding after successful flash

SOLVED
My module is esp8266-01S, i need to set the SPI MODE to DOUT, BAUDRATES=115200, SPI SPEED 40MHz and the software is NODEMCU FLASHER.
The important keyword is "DOUT".
I have been flash many times but with not DOUT SPI METHOD. I thought change it will not fix that. I was using QIO SPI MODE but it doesn't work.


I've done some more search on the interwebs and found someone (in Spanish) describing the same problem. That person owns an oscilloscope and could confirm that there is some bouncing on the data signal both going up and down.

The hardware solution presented is to place a 100 nF capacitor between the signal pin and ground.

I've tried it and it works.


The "Unusable 10" is explained in AltSoftSerial library

  The "Unusable PWM" pins can be used normally, with digitalRead() or
  digitalWrite(), but their PWM function controlled by analogWrite()
  will not work properly, because AltSoftSerial uses the timer which
  controls that pin's PWM feature.

Pin 10 on Uno is SPI slave select if the Uno is SPI slave (then it is an INPUT).

If the Uno is SPI master, this pin must be set as OUTPUT. For this reason it is usual to use pin 10 as slave select for the (first) SPI slave. SPI shields have this pin hardwired as slave select for the (first) SPI device on the shield.


It does warn of some deprecations and such in the firebase libraries :
In member function 'const String& FirebaseArduino::error()' warning: returning reference to temporary [-Wreturn-local-addr] return error_.message().c_str();

i also get some depreciation like
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'bool FirebaseObject::isNullString(const String&) const':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:67:57: warning: 'const char* ArduinoJson::Internals::JsonVariantCasts<TImpl>::asString() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:28): use as<char*>() instead [-Wdeprecated-declarations]
   return variant.is<const char *>() && variant.asString() == NULL;
                                                         ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'ArduinoJson::JsonVariant FirebaseObject::getJsonVariant(const String&) const':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:87:26: warning: 'ArduinoJson::JsonObject& ArduinoJson::Internals::JsonVariantCasts<TImpl>::asObject() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:23): use as<JsonObject>() instead [-Wdeprecated-declarations]
     json = json.asObject().get<JsonVariant>(start);
                          ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/throw_out_of_range.cpp:6:28: warning: unused parameter 'str' [-Wunused-parameter]
 void __attribute__((weak)) __throw_out_of_range(const char* str) {
                            ^
In file included from /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:1:0:
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.h:82:79: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
   const void AddToJson(const FirebaseCloudMessage& message, JsonObject& json) const;
                                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:80:60: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
     const FirebaseCloudMessage& message, JsonObject& json) const {
                                                            ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'int FirebaseRequest::sendRequest(const string&, const string&, char*, const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:76:1: warning: no return statement in function returning non-void [-Wreturn-type]
 }
 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'void FirebaseStream::startStreaming(const string&, const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:89:48: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   analyzeError("STREAM", status, path_with_auth);
                                                ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'String FirebaseArduino::push(const String&, const ArduinoJson::JsonVariant&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:79: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
                                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:7: warning: unused variable 'status' [-Wunused-variable]
   int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
       ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::set(const String&, const ArduinoJson::JsonVariant&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:94:65: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "PUT", path.c_str(), buf);
                                                                 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::getRequest(const String&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:101:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "GET", path.c_str());
                                                            ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual void FirebaseArduino::remove(const String&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:147:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "DELETE", path.c_str());
                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual const String& FirebaseArduino::error()':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:201:33: warning: returning reference to temporary [-Wreturn-local-addr]
   return error_.message().c_str();
                                 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:47:50: warning: 'bool HTTPClient::begin(String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:156) [-Wdeprecated-declarations]
     http_.begin(url.c_str(), kFirebaseFingerprint);
                                                  ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:51:80: warning: 'bool HTTPClient::begin(String, uint16_t, String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:157) [-Wdeprecated-declarations]
     http_.begin(host.c_str(), kFirebasePort, path.c_str(), kFirebaseFingerprint);
                                                                                ^
Compiling library "ESP8266HTTPClient"

to fixed that, go to Preferences in Compiler Warnings choose as Default. it ignored all warning in depreciation, don't forget to update your library to get Firebase Fingerprint has changed on 2 Aug 2018.
Uploaded your sketch again, your should be get data like


Can I set pin 13 to output 5v, then put arduino mini pro to sleep?

Given the absence of clarity on the driving state of pins during sleep, consider connecting Pin 13 to an SR Latch or the gate of a MOSFET.

An SR Latch will hold it's output high or low until a high is presented on the Set or Reset inputs, so connect Pin 13 to the Set input, with a pull-down resistor -- even if the MCU in sleep mode allows the voltage output to drain away to 0v, the SR Latch will maintain it's output.

A MOSFET gate has a non-trivial capacitance which can hold a charge if the gate's driver goes high-impedance, thus holding the gate open after the driver is disconnected.


ATtiny85 - report error "Device reports version as: 2.2"

It sounds like you have a newer board than the version of Micronucleus in the Arduino package.

As I discovered here you basically need to upgrade micronucleus in your Ardino installation, which you can download from here

Download the zip file from Github and extract it.  Then in a terminal (if you're not already in one) go to the directory you extracted.
Build the executable by typing "make"
Copy the compiled executable to ~/.arduino15/packages/digistump/tools/micronucleus/<version>/

where <version> is the currently installed version number (e.g., 2.0a4).  There should already be a micronucleus executable in there that you would replace with your newly compiled one.


The following code can do what you want (source), all that is needed is to combine it with the sensor code. The default behaviour is to create an access point when it can't connect to the eeprom stored WiFi station but you can modify it to trigger with a button/jumper or any other way you prefer.

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>

ESP8266WebServer server(80);

const char* ssid = "test";
const char* passphrase = "test";
String st;
String content;
int statusCode;

void setup() {
  Serial.begin(115200);
  EEPROM.begin(512);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.println("Startup");
  // read eeprom for ssid and pass
  Serial.println("Reading EEPROM ssid");
  String esid;
  for (int i = 0; i < 32; ++i)
    {
      esid += char(EEPROM.read(i));
    }
  Serial.print("SSID: ");
  Serial.println(esid);
  Serial.println("Reading EEPROM pass");
  String epass = "";
  for (int i = 32; i < 96; ++i)
    {
      epass += char(EEPROM.read(i));
    }
  Serial.print("PASS: ");
  Serial.println(epass);
  if ( esid.length() > 1 ) {
      WiFi.begin(esid.c_str(), epass.c_str());
      if (testWifi()) {
        launchWeb(0);
        return;
      }
  }
  setupAP();
}

bool testWifi(void) {
  int c = 0;
  Serial.println("Waiting for Wifi to connect");
  while ( c < 20 ) {
    if (WiFi.status() == WL_CONNECTED) { return true; }
    delay(500);
    Serial.print(WiFi.status());
    c++;
  }
  Serial.println("");
  Serial.println("Connect timed out, opening AP");
  return false;
}

void launchWeb(int webtype) {
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("Local IP: ");
  Serial.println(WiFi.localIP());
  Serial.print("SoftAP IP: ");
  Serial.println(WiFi.softAPIP());
  createWebServer(webtype);
  // Start the server
  server.begin();
  Serial.println("Server started");
}

void setupAP(void) {
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
     {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
     }
  }
  Serial.println("");
  st = "
";
  for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      st += "
";
      st += WiFi.SSID(i);
      st += " (";
      st += WiFi.RSSI(i);
      st += ")";
      st += (WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*";
      st += "
";
    }
  st += "
";
  delay(100);
  WiFi.softAP(ssid, passphrase, 6);
  Serial.println("softap");
  launchWeb(1);
  Serial.println("over");
}

void createWebServer(int webtype)
{
  if ( webtype == 1 ) {
    server.on("/", []() {
        IPAddress ip = WiFi.softAPIP();
        String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
        content = "<!DOCTYPE HTML>\r\nHello from ESP8266 at ";
        content += ipStr;
        content += "
";
        content += st;
        content += "
<form method='get' action='setting'>SSID: <input name='ssid' length=32><input name='pass' length=64><input type='submit'></form>";
        content += "";
        server.send(200, "text/html", content);
    });
    server.on("/setting", []() {
        String qsid = server.arg("ssid");
        String qpass = server.arg("pass");
        if (qsid.length() > 0 && qpass.length() > 0) {
          Serial.println("clearing eeprom");
          for (int i = 0; i < 96; ++i) { EEPROM.write(i, 0); }
          Serial.println(qsid);
          Serial.println("");
          Serial.println(qpass);
          Serial.println("");

          Serial.println("writing eeprom ssid:");
          for (int i = 0; i < qsid.length(); ++i)
            {
              EEPROM.write(i, qsid[i]);
              Serial.print("Wrote: ");
              Serial.println(qsid[i]);
            }
          Serial.println("writing eeprom pass:");
          for (int i = 0; i < qpass.length(); ++i)
            {
              EEPROM.write(32+i, qpass[i]);
              Serial.print("Wrote: ");
              Serial.println(qpass[i]);
            }
          EEPROM.commit();
          content = "{\"Success\":\"saved to eeprom... reset to boot into new wifi\"}";
          statusCode = 200;
        } else {
          content = "{\"Error\":\"404 not found\"}";
          statusCode = 404;
          Serial.println("Sending 404");
        }
        server.send(statusCode, "application/json", content);
    });
  } else if (webtype == 0) {
    server.on("/", []() {
      IPAddress ip = WiFi.localIP();
      String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
      server.send(200, "application/json", "{\"IP\":\"" + ipStr + "\"}");
    });
    server.on("/cleareeprom", []() {
      content = "<!DOCTYPE HTML>\r\n";
      content += "
Clearing the EEPROM
";
      server.send(200, "text/html", content);
      Serial.println("clearing eeprom");
      for (int i = 0; i < 96; ++i) { EEPROM.write(i, 0); }
      EEPROM.commit();
      WiFi.disconnect();
    });
  }
}

void loop() {
  server.handleClient();
}

The configuration access point ssid and password are set in

const char* ssid = "test";
const char* passphrase = "test";

The default IP is 192.168.4.1. When you open it from a browser you see a screen which lists the available WiFi stations (ESP8266 scan result), the signal strength and an asterisk on locked stations. There are also two text boxes where you enter the ssid and password of the station you want to connect to and submit:

Note that there is a link to a similar library in the comments of the source link, that didn't work for me but you can try it.


Motor does not work for a specific case when programming with L293D motor driver shield

On an UNO only certain pins are capable of PWM.  Pin 12 is not one of them.  When you try to call analogWrite with pin 12 it will recognize this and will simply call digitalRead for you with HIGH or LOW depending on whether your input is greater than 127.
With most motor controllers you can use one pin as a direction pin and the other as a PWM pin.  So to go one direction you set pin 12 HIGH and do inverted PWM on 11 (if those indeed go to the same motor I didn't look at your shield).  To go the other direction you write LOW on 12 and PWM on 11.
The motor turns when one pin is HIGH and the other is LOW.  When you set pin 12 high then PWM pin 11, whenever 11 is LOW in the PWM cycle it is turning the motor on and when it is HIGH it is turning it off.  So to make it run you might have to PWM 0 for go and 255 for stop.  Sometimes your PWM is on the enable line and then you still use 255 for go and 0 for stop.  It just depends on how things are wired.
When pin 12 is set to LOW then the motor is on when 11 is at the high part of the PWM cycle and off when it's low so you use 255 for go and 0 for stop.  But the whole time pin 12 doesn't have to change.
Now I am not 100% sure that this is the case with your particular motor controller, I'm more of a coder than a hardware guy.  But I've written enough code for motor controllers to know that you usually either need two direction lines and one PWM line or one direction and one PWM.  If that's not the case here then we can let someone else work on why.


Writing and reading an ID to/from an Arduino reliably

I'd go with #2. If you are concerned that you will eventually burn-out your EEPROM (100.000 write cycles per ATmega328 ds), try writing a macro, which will dictate at which upload you want new ID to be written in EEPROM.
Heck, instead of writing all of these onboard, why don't you maintain an offline lookup database and encode things yourself? It would still require writing to EEPROM but you could encode your information in a couple of ints.


Large values are changed by Arduino when viewing with `Serial.print()`

Floating point numbers doesn't have infinite precision. But you can always change your equation to use smaller numbers (preferably integers or longs as floating point is extremely slow)

For example on AVR Freaks they mentioned precision about 6 or 7 digits. It makes sense as 24bits signed number range is from -8388608 to 8388607


The absolute accuracy of the ADC in the ATmega328P when its clock is within its optimal range is given in the datasheet as 2LSB. This means that the actual value could be anywhere between 728 and 732.

Of course this depends on the accuracy of VCC, since it is being used as the ADC reference. This is why supply voltage measurements should be performed using the internal bandgap voltage instead.


Is it possible to create a standalone exe which can burn the code into a Teensy 3.1?

Yes, it is perfectly possible.

You will need three things:

The HEX file you want to program
The programming utility for your chosen board (would be in the IDE folder somewhere - not sure what Teensy uses off hand)
A text editor.

Then, using the text editor, you create a .BAT file which executes the programming utility with the right parameters to program the board.

It can help to do an upload in the IDE in verbose mode so you can see exactly what command and parameters are being executed.


Cannot send two arguments from a WebClient

Solved!

Changed the following lines:

client.println("Content-Type: multipart/form-data");
client.print("Content-Length: ");
client.println(63);
client.println();
client.println("sale[itemId]=123456789012341234&sale[machineId]=123456789012341234\r\n");
client.println();


Powering 24 volt solenoid valve with Arduino uno

Since the solenoid requires higher current than the arduino can provide you can use an alternative power source for the solenoid (maybe a couple of batteries) and switch it with a TIP120 transistor.


Error: request for member 'RGB' in 'redLed' , which is of non-class type 'int'

Probably you didn't spot commas:

    analogWrite (redLed,   RGB[0]);
    analogWrite (greenLed, RGB[1]);
    analogWrite (blueLed,  RGB[2]);

The function analogWrite takes two arguments, separated by commas. You were missing some brackets as well.


Arduino - Function -> return Cstr instead of string

You cannot work with c-strings like with Strings. You need to use the standard c-string functions (like sprintf(), strcpy() and siblings) or directly access the char array.
This gives the following problems with your code:

See this line:
  char* received = "";

Here you create a pointer to a constant empty string. But this will NOT create a buffer, where you can put data. If you want to define a buffer to put the data in, you need to define an array:
  char received[30] = "";

where 30 is the size of the array and thus the buffer has space for 29 characters (30 minus the one character, that is needed for the terminating null character). Now you could use a counter variable to save the current position in the buffer and set the array elements to the received character:
  int position = 0;
  ...
  received[position] = ch;
  position++;

Then, when you reached the end of the buffer or you received end of line, you would end the data in the buffer with the null character:
  if (ch == '\n' || ch == '\r' || position == 29) {
      if (ch == '\r')
      {
          //get rid of the \n
          myFile.read();
      }
      received[position] = '\0';

Now you have the second problem: When defining a variable inside the function, it will become invalid, when you exit the function. You try to return a pointer to char, which will point to a non-valid memory location. Thus you cannot simply return an array, that was created inside the function (outside of dynamic allocation). Here commonly an external buffer is provided to the function by reference as a pointer. The function will then write into that buffer and does not need to return it.
  //defining the array outside of the function, for example at global scope
  #define BUFFER_SIZE  30
  char received[BUFFER_SIZE] = "";
  ...
  void readLine(char *buffer, int size) {
      ...
      // Here you can use buffer as a simple char array
      buffer[position] = ch;
  }

Here I also provide the size of the array as parameter, so that the function can make sure not to exceed that (because that will give you bad and difficult to troubleshoot problems). Then, when the function has run, the read data is now in the received character array. This way you don't need to use multiple buffers and also don't need to copy data between buffers.


make Arduino tell when the Python program stops reading from the Serial (crash, etc)

There is no way to know if the connection has closed or not, you can only know if the connection was working at some point in the past.

Your communication protocol as shown is only half duplex (i.e., it's only one way - the Arduino sends to Python but never the other way around) which simplifies things somewhat.

There are a number of strategies you can employ in your case, and any number of them can be combined to create a system as robust (and complex) as you like.

First you would need to make your protocol full duplex.  This is, you need your Python program to be able to send information to the Arduino.  Since you aren't doing that at the moment the implementation of it can be in any way you like.

One method you can use is called Keepalive.  In this system the Python program will periodically send an "I am here" message to the Arduino.  The Arduino receives these messages and remembers when the last one was (hint: use the millis() function).  If a message hasn't been received for more than a pre-defined timeout period the link is assumed to be dead.

Another method which is good if you are sending data very regularly from the Arduino to the Python program is to use a system of acknowledgements.  In this situation every bit of data sent to the Python program is followed by the Python replying with an "I got that" message.  If the Arduino doesn't get that response after sending its data within a certain timeout period (can be much shorter than for a keepalive timeout) then the link is assumed to be dead.

Wrapped around both these methods you can add an "I have arrived" and an "I am leaving" message.  These are sent by the Python program when it starts and just before it's about to exit so the Arduino knows when the link should be alive and when it shouldn't.  If it gets an "I am leaving" message then it knows that it shouldn't care whether it gets any acknowledgement or keepalive messages, so it doesn't need to think about timeouts. Only after it has received an "I have arrived" message should it start caring.

So for instance your protocol, with all these things implemented, might look like this (>> = message from Arduino to Python, << is message from Python to Arduino):

>> 1
>> 1
>> 1
>> 0
>> 0
>> 1
<< A    - I have arrived
>> 1
<< Y    - Yes, I got that
>> 1
<< Y    - Yes, I got that
>> 0
<< Y    - Yes, I got that
<< K    - keepalive - we know the link is alive and working.
>> 0
<< Y    - Yes, I got that
>> 1
<< Y    - Yes, I got that
(Program crashes now.)
>> 1
*no Y received - assume connection is closed*
>> 1
... etc ...

In this instance the 0 and 1 are what you are sending at the moment.  A is an "I have Arrived" message, Y is a "Yes I got that" message, K is a "Keepalive" message, and if the program had exited cleanly an L would have been an "I am Leaving" message.

Keeping the messages simple (single characters) means it's really easy for the Arduino to parse those messages and work out what is going on.

There is a certain amount of balancing act to be performed when implementing your system between how often you are sending data and how long you are willing to wait for a valid response or message to flag the connection closed.

Expanding your existing example program to incorporate these messages might look like:

unsigned long lastKA = 0;
unsigned long lastSent = 0;
boolean isConnected = false;

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

  pinMode(7, INPUT_PULLUP);
}

void loop() {

    // Check the timeouts if we are connected
    if (isConnected) {

        // First check to see if the Keepalive timeout has passed
        if (millis() - laskKA > 5000) { // 5 second keepalive timeout)
            isConnected = false;
        }

        // If we have sent data...
        if (lastSent > 0) {
            // ... check that we got a response in time
            if (millis() - lastSent > 100) { // 100ms Y timeout
                isConnected = false;
            }
        }

    }

    // If we are connected then send some data
    if (isConnected) {

        int val = digitalRead(7);
        if (val == HIGH) {
            Serial.print("1");
        } else {
            Serial.print("0");
        }
        Serial.println("");  // new line

        // and set the timer for the response
        lastSent = millis();
    }

    // Now process incoming messages.
    if (Serial.available()) {
        int c = Serial.read();

        // If the message is an A then turn on the connection and
        // treat it as a Keepalive as well.
        if (c == 'A') { // Arrived
            isConnected = true;
            lastKA = millis();

        // If it's a Leaving message then turn off the connection.
        } else if (c == 'L') { // Leaving
            isConnected = false;

        // If it's a Keepalive then reset the timer.
        } else if (c == 'K') { // Keepalive
            lastKA = millis();

        // A Y acknowledgement will disable the sent timer.
        } else if (c == 'Y') { // Yes
            lastSent = 0; // Cancel the sent timer
        }
    }
}