if(Serial) not working correctly on micro or pro micro

1) have i got an out of date bootloader?

No. This has nothing to do with the bootloader.

  2) if so how do i check?

See above.

  3) is this intended behavior and if so why?

In a manner of speaking, yes - see below.

  4) is this a bug in the arduino bootloader or libraries?

No. Elsewhere.  See below.

  5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?

Yes, you can, but only once you understand exactly what is going on.

The problem with USB serial (AKA CDC/ACM) communication is that there is no way of knowing if the port has been opened by the computer or not.  That functionality was just never designed into the protocol.

However, there are two virtual modem signals that the computer can assert that the CDC/ACM device at the other end can examine - one is the equivalent of DTR and the other the equivalent of RTS.

The Arduino's CDC/ACM code examines those, and if either are asserted then it assumes the CDC/ACM port is open. If neither are asserted then it assumes the port is closed.

Now comes the tricky part:  You have little or no control over when those signals are asserted or not.  There are three separate factors that decide what happens:

The software being run can manually control the signals.  The Arduino IDE does this to ensure boards that use DTR to reset (like the Uno, etc) actually do reset.
The drivers on the computer can decide to automatically control the signals when the port is opened or closed
The operating system itself can control the signals when the port is opened or closed.

Some software will control the RTS/DTR signals properly, some won't. Some drivers will control the signals for you, some won't. Some operating systems (such as Linux) will, unless otherwise instructed, default to automatically controlling the modem lines properly. Others, like Windows, won't.

So the only way you can be sure that these signals are being controlled properly is to manually control them from your own software used for debugging, or to find a specific terminal emulator that controls the lines properly.


When Raspberry Pi is preferred over Arduino

The claim that the Pi is more "powerful" is a bit misleading. What does "powerful" really mean? And is it relevant to making a weather station?

I made a temperature and humidity sensor as described here using an Atmega328P (the processor that is in the Arduino Uno). The estimated average power consumption is 42 µA which has allowed it to run from 3 x AA batteries for a couple of years before they needed replacing. I think you'll find that the Pi with its more "powerful" processor and extra components would not be able to do that.

I see from a quick search that the Pi consumes 80 mA to 240 mA when idle (depending on the model). This would make a Pi-powered weather station eat through batteries 2000 times as quickly. Perhaps that would be a consideration.

The Pi is really a Unix PC on a board, which means it goes through the normal boot sequence with a possibility of errors occurring during booting. To see what those errors are you need to connect up a keyboard and screen, or connect via a network to it from another PC.

I don't want to run down the Pi - it's a nice cheap Unix computer on a small board. But the Arduinos (many of them) are somewhat simpler to program. You don't need to worry about the operating system for a start. For a weather station, taking a reading every 5 minutes, who cares if the Pi can take the reading "50 times faster"?

Speed of recovery from sleep

I have an answer about letting serial data wake an Arduino - after some experimenting I was able to get the Atmega328P to wake from its deepest sleep (260 nA - yes 0.260 µA!) within 6 clock cycles (750 ns). I doubt you could achieve that on the Pi, either the low power consumption, or waking up in under a microsecond.

This was fast enough to detect the start bit in serial data at 9600 baud, process the start bit, and then the rest of the incoming byte without losing data.


A USB host shield or mini board depending on your Arduino board should work.

https://github.com/felis/USB_Host_Shield_2.0

https://www.circuitsathome.com/usb-host-shield-hardware-manual/


NC is "Normally Connected" - this contact is connected to COM ("common") if coil of the relay is not powered - the relay is disconnected.

NO "Normally Open" is connected to COM when the coil of the relay is powered - the relay is connected.

Some relays have the coil powered when the signal from MCU is LOW.

If the coil of the relay doesn't click, but the signaling LED lights up, then VCC is not connected. Check if you plugged the wire really to 5 V on Arduino side.


How to reset ATmega328P fuses using USBasp programmer?

Its possible you may have disabled the SPIEN or the RSTDISBL fuses. The only way to check and fix is to use a High Voltage Programmer like the STK500, STK600 or AVR Dragon and see. I have the AVR Dragon and it saved me a few times.

Also, do a search for AVR Fuse Doctor. Its a homemade fuse repair device. Pretty cool. But save yourself some time and invest in a programmer/debugger that has HVPP (high voltage parallel programming) and HVSP (high voltage serial programming). You won't regret it.


The simplot library (referenced below) is an excellent example of how to use the scope which works as advertised.
Firstly, readers should note that there are two different Arduino plugins for Eclipse ("Eclipse C++ IDE for Arduino" and "Arduino Eclipse plugin named Sloeber V3"). Only the latter has a scope and a seriel monitor that allows data to be sent.
Getting simplot and the scope to work, however, can be a problem depending on the platform. On a Mac, with the latest version of Eclipse (Neon.2 Release Candidate 2) and the Sloeber V3 plugin, the default path to the Private Library is Users/yourname/Arduino/libraries. Unfortunately, this path doesn't (necessarily) exist.
One could spend hours trying to figure out how and where to import a library when the critical library folder doesn't exist.

The solution (at least on a Mac):

Create a folder (arbitraily) named "Users/yourname/Eclipse/libraries".
Include this folder in Eclipse - Preferences - Arduino - Private Library Path
Download jantje's entire Github Arduino Library, unpack it and move the "simplot" folder into your Private Library Folder. "simplot" should now show up in the libraries.
Use: Arduino - Add a Library to the Selected Project
Or build a project using the simplot.ino example.

It should work beautifully.


How to make universal remote controller?

As you've stated in your question, the TSOP-15 is a receiver. That means it detects infrared signals rather than sending them out.

To make a remote control with that code, you need a simple infrared light emitting diode.

It's also important to note that you need to know what signals to send. Different TVs will have different IR codes, depending on the manufacturer. That information can be detected using your receiver module along with your TV's proper remote control.


The simplest method is just a voltage divider - just as if you were interfacing a 5V logic signal output with a 3.3V input. However it may not work.

A voltage divider will only really be of use if the output of the pH sensor is low impedance. If it's not then you will need a very high impedance voltage divider, and the analog input of the ESP8266 isn't high enough impedance to support a very high impedance voltage divider - it will skew the results horribly.

So you may need to buffer the output of the pH sensor through an op-amp first.

If you use a unity gain non-inverting buffer you can then use a voltage divider to reduce the output voltage.

simulate this circuit – Schematic created using CircuitLab

Alternatively, as others have suggested, use an external 5V ADC chip and logic level conversion to communicate with the ESP8266.


when i compile this code it always 'sendCommand' was not declare in this scope..plzz help

In loop you have three opening braces and one closing brace. This won't end well:

void loop() { // run over and over
  if (esp8266.available()) {
    if (esp8266.find("+IPD,0,")) {
      delay(10);
      esp8266.find(":");
      delay(10);
      char letter = esp8266.read();
      Serial.print(letter); //for monitoring purposes
      //Gets the value/char from android app
    }

Two more closing braces would fix it.


Assuming the brown board in your drawing is stripboard, I have to as the question:
What is this?

If those five wires in that column are all ground, that link is basically short circuiting your MOSFET via the green wire next to it, thus rendering your whole circuit pointless.  The LEDs will just be on full brightness permanently since the current just flows from the input power, through the LED strip, through the red/white wire, through that little white link wire, then through the green/white and/or the brown/white wires to ground.


Why don't these sketches produce a similar output?

The different time implies different (number of) instructions being executed.  This is most probably due to the crappy GCC compiler optimizations.

In the former sketch, probably the compiler manages to use only registers, which are very fast. In the second one, the compiler THINKS it needs 8 more bytes, and there are no registers left, so it uses the stack (internal RAM) to store some variables, which is slower. (still, the optimizer should realize that in fact it don't need more bytes, because a and b are not used after the first println()). To access to a SRAM location, you need a LOAD/STORE operation, which takes a longer time, with respect to an operation between registers (beside having to load the memory address to X, Y o Z).
Probably, the compiler is even crappier, because, instead of putting the rarely-used variables a,b,c,d on the stack, it puts i (which is always incremented) or other variables used in digitalRead().

Still, to explain where is the trouble (i.e. where compiler fails in optimizing the register allocation/usage), you should disassemble the object code. Use for instance Atmel Studio, which still uses GCC, but has a good debugger, disassembler and cycle-exact analysis.

Still, this is very strange, perhaps optimizations were not enabled the platform.txt of your arduino?

EDIT:
Using Arduino 1.8.0, I tested the two sketches and analyzed the lss (generated using avr-objdump). The compiler optimizes a lot more the first code. Instead of making a CALL to digitalRead() (as it happens in the second sketch) it probably recognizes that such function is called only once on the code. Therefore it makes a rjmp to it. At the end of that function, there won't be a RET but a branch to the point where i is computerd and checked (actually i is not incremented, actually gets decremented and checked against 0).

In other words, even if the two codes are equal (except that the second sketch runs the same code twice), they are compiled (optimized) differently.


The WS2812B chips are very sensitive to timing. They rely on pulses being just the right length for things to work.
It is common if the timing is off that you just end up with white.
Since you have a blank chip that you have never put a bootloader on the fuses will be set wrongly for your configuration. By default a chip comes configured for the internal 8MHz oscillator. That means that everything will be running at half the speed.
You need to set the fuses to use the 16MHz crystal so that it matches the F_CPU setting of 16000000 in the board configuration. Either that or use a board configuration that expects to run at 8MHz.


How do I connect this string of LEDs to my Arduino Uno?

Connect the negative ( or cathode ) to ground ( 0V )
and the postive ( anode ) to the output pin of the controller.

Firstly connecting that many LEDS directly to a single micro pin is not a good idea. Usually you would need to go through a buffer/driver first which can deliver the correct power to the LEDS.

I'm not that familiar with the UNO but unless that board has a driver circuit on it you might need a few extra components.

What are the specs of the LEDS?


Can't upload code to an Arduino LilyPad using FTDI

Does the Loopback test work? Connect Lilypad's Reset to Gnd, connect D0 to D1, open the serial monitor, see if typed text is echoed back.  If, you have FTDI problems that you need to resolve.


Which Arduino-compatible microcontroller for 2 continuous analog audio recording and 2 digital pin snapshots every second?

My question therefore is would a ATmega328P or ATmega2560 be suitable for such requirements

No. Not in the slightest.

Your primary requirement of sampling audio at, basically, CD quality (or better) requires the use of a proper CODEC chip - and to drive that you require a microcontroller that has I2S. None of the 8-bit AVR chips have that.

On top of that you will need a LOT of memory. Far far more than an 8 bit Arduino has.  Two channels of 16 bit audio at 44100Hz (CD quality) requires 176400 bytes per second.

You will need double that.

To both continuously record and save the data you will require DMA to do the recording.  The DMA reads the incoming data from I2S and stores it in one buffer. When that buffer is full you generate an interrupt and switch to a second buffer. You can then save the first buffer to SD - assuming that it can be done in under a second.  Note that SD cards, when controlled by SPI as they generally are on microcontrollers, are generally quite slow.

So with all that in mind:

  I do like the idea of working on a AT91SAM3X8E chipset, but I'm afraid this might be an overkill for such a small project

Overkill? No. Not suitable since it is not up to the task. Yes, it has I2S. Yes, it has DMA. But it doesn't have anywhere near enough memory.  You need for the audio alone 350 kilobytes (the SAM3X8E has up to 100 kilobytes) - not to mention memory required by the SD card's buffers.

So you're looking for a microcontroller that has full I2S support, DMA, and around half a megabyte of memory.  And those aren't small and cheap like the Arduino's 8-bit AVRs.


Large(ish) strings failing to send over WiFi101 using WiFiServer

As per my notes the WINC1500 has a limit of 1500 bytes per transmission.  But some of this is always taken up by TCP overhead so the payload buffer must be smaller, that's why you see numbers like 1460.

From:
http://ww1.microchip.com/downloads/en/appnotes/atmel-42739-tcp-client-and-server-operation-using-atwinc1500_at14596_applicationnote.pdf

  2.2.2 TCP Packet Size

  A packet is sized as per the lowest MTU (Maximum
  Transmission Unit) on the path, which is typically 1500 bytes (for
  Ethernet) of data including TCP (20 bytes) and IP headers (20 bytes).
  The packet size is defined in main.h as :

#define MAIN_WIFI_M2M_BUFFER_SIZE 1460

  The application then defines a socket buffer of this size in main.c as:

static uint8_t gau8SocketTestBuffer[MAIN_WIFI_M2M_BUFFER_SIZE];

This means that HTTP responses over ~1400 bytes need to be chunked which means split up into multiple calls.

FYI chunked Transfer-Encoding is superseded in HTTP/2:
http://undertow.io/blog/2015/04/27/An-in-depth-overview-of-HTTP2.html

Info on HTTP chunked encoding:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding

Transfer-Encoding: chunked

  Data is sent in a series of chunks. The Content-Length header is
  omitted in this case and at the beginning of each chunk you need to
  add the length of the current chunk in hexadecimal format, followed by
  '\r\n' and then the chunk itself, followed by another '\r\n'. The
  terminating chunk is a regular chunk, with the exception that its
  length is zero. It is followed by the trailer, which consists of a
  (possibly empty) sequence of entity header fields.

https://www.httpwatch.com/httpgallery/chunked/

https://gist.github.com/CMCDragonkai/6bfade6431e9ffb7fe88

  Transfer-Encoding

  The use of Transfer-Encoding: chunked is what allows streaming within
  a single request or response. This means that the data is transmitted
  in a chunked manner, and does not impact the representation of the
  content.

  Officially an HTTP client is meant to send a request with a TE header
  field that specifies what kinds of transfer encodings the client is
  willing to accept. This is not always sent, however most servers
  assume that clients can process chunked encodings.

  The chunked transfer encoding makes better use of persistent TCP
  connections, which HTTP 1.1 assumes to be true by default.

  Chunked data is represented in this manner:

4\r\n
Wiki\r\n
5\r\n
pedia\r\n
e\r\n
 in\r\n\r\nchunks.\r\n
0\r\n
\r\n

  Each chunk starts with its byte length expressed as a hexadecimal
  number followed by optional parameters (chunk extension) and a
  terminating CRLF sequence, followed by the chunk data. The final chunk
  is terminated by a CRLF sequence.

  Chunk extensions can be used to indicate a message digest or an
  estimated progress. They are just custom metadata that your layer 7
  receiver needs to parse. There's no standardised format for it.
  Because of this, it's probably better to just add your metadata (if
  any) into the chunk itself for your layer 7.5 application to parse.

  For your application to send out chunked data, you must first send out
  the Transfer-Encoding header, and then you must flush content in
  chunks according to the chunk format. If you don't have an appropriate
  HTTP server that handles this, then you need to implement the syntax
  generator yourself. Sometimes you can use a library to provide an
  abstract interface.

Possible fix on Arduino platforms is to use StreamLib library or roll-your-own chunking system.

Update:  I hacked together a sketch and confirmed this works.  Next issue was the buffer must be null terminated, BUT this is stripped out before transmitted over TCP so the HTTP chunk size is the buffer size -1.


Serial doesn't initialise on Arduino Mega 2560 when not powered via the USB port

Ok i found the issue and the solution.

For some reason it seems that while the MCU is running Setup(); hardware or software serial don't work properly.

In my case i have code that set the SIM module to SMS mode and to send those messages to the serial port.

For some reason it doesn't send them (or probably the module is not ready to accept them).

Connecting the USB cable reset the arduino and run setup() when opening the serial monitor setting the module in the correct mode.

Adding this code in the main loop solves this issue even though i have them powered both by the same step down converter.

edit: That turns out 1 hour later after debugging more is not exactly a proper solution to the issue.
 That command to set into SMS mode only works when you are connected to the network.

I have a check for that and a reset function.

So now at Setup() i wait 10s for the module to boot up so it is ready to open a serial port, then i check if it is connected to the network before i send the commands to set into SMS mode.

Example:

// Initializing serial commmunication
Serial.begin(57600);
delay(10000);

while (ini){
    Serial3.begin(57600);
    delay(1000);
    Serial3.print("AT+CGREG?\r");
    delay(100);
    netStatus = Serial3.readString();
    if (netStatus.charAt(22) == '5' || netStatus.charAt(22) == '1') {
         digitalWrite(LED_NET, HIGH);
         ini=false;
         }
    else {
        digitalWrite(LED_NET, LOW);
        digitalWrite(resetPin, LOW);
        delay(2000);
        digitalWrite(resetPin, HIGH);
        delay(30000);
        }
}
  Serial.print("SIM800 ready...");

  // AT command to set SIM800 to SMS mode
  Serial3.print("AT+CMGF=1\r");
  delay(100);
  // Set module to send SMS data to serial out upon receipt
  Serial3.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);


SD test is taking long answer when it fails

The SD library builds on the sdfatlib library, in which SD_INIT_TIMEOUT is defined as 2000 ms, which gives your 2 second timeout. You could try lowering that number to get a faster response, although that may run the risk of timing out even when a card is present.

Four different timeout periods are defined in the sdfatlib source:

/** init timeout ms */
uint16_t const SD_INIT_TIMEOUT = 2000;
/** erase timeout ms */
uint16_t const SD_ERASE_TIMEOUT = 10000;
/** read timeout ms */
uint16_t const SD_READ_TIMEOUT = 300;
/** write time out ms */
uint16_t const SD_WRITE_TIMEOUT = 600;

The 300 ms read timeout is faster, as @Paul suggests in his comment, so you could just use a card read as the test rather than an initialisation, or try setting the init timeout to 300 instead. A read test would be simpler, as it doesn't involve modifying library files. It might not cope with a re-inserted card, though - I suspect that requires reinitialisation each time.

Note: the version of sdfatlib included with the SDlib in my Arduino install appears rather older than the current version. The included version defines the timeouts in Sd2Card.h, while the latest has is in SdInfo.h. The snippet above is from the older, included code.


The problem lies in your for cycle.

If (state == 1) you are switching the red colour ON.
If (state == 2) you are switching the blue colour is ON. So at this moment, you have red AND blue colour on, not only blue. I assume the output colour is purple-ish.
If (state == 3), you activate red (which is already ON), blue (which is also already ON) and also green (which changes state from OFF to ON) so you get white colour. At this moment you went through all three possible conditions.
Then you go back to (state == 1). All colours are already activated, so from this moment you get only white...

Solution:

for (int i = 0; i < NUM_LEDS; i++) {
  if (state == 1) {
    leds[i].red = 100;
    leds[i].blue = 0;
    leds[i].green = 0;
    Serial.println("Red");
  }
  if (state == 2) {
    leds[i].red = 0;
    leds[i].blue = 100;
    leds[i].green = 0;
    Serial.println("Blue");
  }
  if (state == 3) {
    leds[i].red = 100;
    leds[i].blue = 100;
    leds[i].green = 100;
    Serial.println("White");
  }
}


Checking a jumper between two pins on Arduino

First of all, welcome here. Usually questions should contain, well, only one question ;)

In any case the usual circuit with buttons (a jumper can be seen as a button) are these ones:

simulate this circuit – Schematic created using CircuitLab

In the left case, usually the arduino pin is "pulled down" by the resistor when the button is not pressed (or the jumper is not present), so it will read "LOW". When the button is pressed, the arduino will see a "HIGH" value, since the button is "stronger" than the resistor and is able to force its value. The resistor is called "pull-down".

In the right case, the voltages are inverted. You read a "HIGH" value when the button is not pressed, and a "LOW" value when it is. The resistor is called "pull-up" for obvious reasons.

The resistor is needed because you need to have a "weak" component that can pull the arduino pin to a voltage value; it needs to be weak, so the button can override it.

The arduino, however, as a very common feature, called "internal weak pull-up" on the digital pins. This means that internally there is already the possibility to enable a weak resistor pulling the voltage to +5V. For this reason, what you need is to just connect the jumper to ground and read it.

simulate this circuit

You will need, in your setup, to set the pin as INPUT_PULLUP, and then check the value you read:

const byte jumperPin = 2;

void setup() {
  pinMode(jumperPin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(jumperPin) == LOW)
  {
    // Jumper is inserted
  }
  else
  {
    // Jumper is not inserted
  }
}

This is what the DigitalInputPullup example is for...

Regarding your other question, there is a connector on every board named ICSP (of if there isn't, you should have access to the ICSP pins from somewhere else). This connector is used to flash the bootloader again (or to flash a program with an external programmer). You will need a atmel programmer to restore the original bootloader and "unbrick" it.

Luckily any arduino board can be used for this task; you will just need to download on another board the sketch ArduinoISP (already included in Arduino IDE) and you can use it to flash. There is plenty of tutorials online to do it. So to "unbrick" it you will just need another arduino board


help with input in a Simon arduino uno game

The problem in your code is there:

int simonIn() {
    int ret = -1;
    for(int i = 0; i < 4; i++) {
        if(simonIn(i)){
            ret = i;
        }
    }
    if(ret != -1) {
        simonOut(ret);
        delay(500);
        simonClear();
        delay(100);
    }
}

This method never returns any value, so that means the caller will just tke whatever is in the stack at that time:

            int input = simonIn();
            while(input < 0 || input > 3) {
                delay(50);
                input = simonIn();
            }

input could be anything there.

So the fix should be easy:

int simonIn() {
    int ret = -1;
    for(int i = 0; i < 4; i++) {
        if(simonIn(i)){
            ret = i;
        }
    }
    if(ret != -1) {
        simonOut(ret);
        delay(500);
        simonClear();
        delay(100);
    }
    return ret;
}

It's surprising you did not get a warning from the compiler on that one, which IDE do you use?

Finally, regarding your code, I would also advise you the following improvements:

break down the loop() code further into functions that do ONE thing, e.g. showSequence(sequence), checkInput(seuquence), readSimonInput() (this last function would only return a value between 0 and 3 included. That would make your code much clearer.
use the right types for your variables: I see you abuse usage of long where int or byte, or you mix different types for the same data, thus forcing the compiler to cast data on some function calls.
avoid hardcoding constants in your code, e.g. you could define the number of buttons, the first pin of buttons, the first pin of LEDs, the various delays.


I want to play a sound based on my ultrason sensor reading

#define buzzerPin = 10 shouldn't have an = in it.

With the = pinMode(buzzerPin, OUTPUT); will turn into pinMode(= 10, OUTPUT); by the pre-processor. Which would give the error, complaining about an = token, you got.


As I said in my comment, it is all about computing an approximation of
sqrt(1-x). Assuming the typical resonance frequency is between 175
and 235 Hz, then we have

  (4 × 150 µs + 300 µs) 175 Hz ≤ x ≤ (4 × 300 µs + 300 µs) 235 Hz

i.e.

  0.1575 ≤ x ≤ 0.3525

This range is small enough to try a simple polynomial approximation. A
linear approximation is just a bit too crude for 8 bit resolution.
Playing with quadratic polynomials, I found this approximation which is
good to 3.1e-5 in the relevant range:

  √(1−x) ≈ 0.9983795 − x (0.480515 + x 0.1955)

This can be easily implemented in fixed point by scaling everything by a
factor 216 = 65536. One has to take care that any
product of two such fixed point numbers must be computed in
32 bits, and the result subsequently divided by 65536. Which gives
the following implementation:

/*
 * Compute a fixed point approximation of f(x) = sqrt(1-x).
 * Valid for x in [.1575, .3525].
 * Argument and result scaled by 2^16.
 */
uint16_t f(uint16_t x)
{
    return 65430 - x * (31491 + x * 12812UL / 65536) / 65536;
}


Problems when attaching a second ultrasound sensor (HC SR04)

It turns out I had an extra "}" after the void loop function. The code worked as expected after removing it


Create a device to detect object and voice alert what kind of object it is

The Arduino is not the ideal platform for you since it is more "lightweight" and can't really meet the demand that your application is expecting.

A platform like for example Raspberry Pi that has a full-blown operating system and a lot of tools that fulfils your application needs.


5v relay module and suitable bulb adapter

There is no such thing as a "suitable" bulb holder.

Bulb holders are bulb holders. They hold a bulb. They have wires connected to them. They come in different shapes and styles, and that shape and style has nothing at all to do with how they work or how you connect them.

You pick a bulb holder that is the right kind for your project - be that a ceiling rose + pendant combination, a wall mount angled, a table lamp, a standard lamp, a chandelier from Ikea...

If you are looking for something that is identical to that drawing then you may be sadly disappointed. That's a drawing. A representation. The actual device you choose to use is whatever device you deem is the right one for your design.


First of all DON'T PANIC, it's more than probable your Arduino is not broken.
Start running the following checks:

is any other software using the same serial port? serial ports cannot be concurrently opened by multiple processes...
disconnect the board, reset your PC, wait until the boot process is completed and then connect again: does your OS recognize the COM port? (Windows emits a sound, GNU/Linux logs a few lines...)
check the COM port matches, may be your board is no more recognized as COM3 but as COM4, depending on multiple factors
if you have anything wired to your board, disconnect everything, unplug the board and then re-connect the board alone, with nothing connected to its pins: you might have a short somewhere or using pins 0 or 1 (marked as RX & TX, they are also used for communication)
is your USB cable connection flaking? it might seem stupid, but if you have multiple cables running around your PC it is indeed possible to pick the wrong one or loose it from the socket...
are you using a cheap cinese clone? There are clones using counterfeited USB chips which get banned by Windows automatic updates, but a workaround exists even for that

While it is possible to brick the Arduino boards via software, there are very little possibilities you did it because it involves using tools completely hidden to the Arduino occasional user / newcomer.


How to break out the due power supply and USB connectors?

so 1 - yes. the VIN pin has a common trace with the barrel jack, you can verify with a multimeter in continuity/beep mode. ive actually put power out through the barrel jack on a mega.
2- i cant find a clear schematic for the due at the moment, but on the mega the rx/tx pins are also common with the usb pins, thus they are not usable while plugged into usb


Is there any way to catch the response of SIM800L after sending the at command?

for a polling serial read I use this method :
bool tSim8_sendCommand(uint8_t sim_cmd[])
{
    uint8_t simOK[2] = {0}, i=20;
    tSoftSerial1_write(sim_cmd);
    tSoftSerial1_write("\r\n");
    while (i--)
    {
        simOK[0] = simOK[1];
        simOK[1] = tSoftSerial1_readChar();
        if(simOK[0] == 'O' || simOK[1] =='K')
        {
            return true;
        }
    }
    return false;
}

the variable i i the while loop, is used just for retries, so the program doesn't get trapped in an infinite loop. the code is self-explanatory. the incoming characters are "pushed" into an array till the array reads "OK".
for a non-blocking one, it's a bit complicated as you have to define state-machines and concurret loops. here is a method I use for finding out if the last transmission was OK:
void tsim_phase_ok_routine(uint8_t inChar)
{
    if(tsim_aux_buff[0] == 'O' && tsim_aux_buff[1] =='K' && tsim_aux_buff[2] =='\r')
    {
        tsim_status_flag |= (1<<PHASE_OK);
        tsim_status_flag &=~(1<<PHASE_CON_ERR);
        return;
    }
    else
    {
        tsim_aux_buff[0] = tsim_aux_buff[1];
        tsim_aux_buff[1] = tsim_aux_buff[2];
        tsim_aux_buff[2] = inChar;
        err_timeout--;
    }
    if(!(tsim_status_flag & (1<<PHASE_OK)) && !err_timeout)
    {
        tsim_status_flag &=~(1<<PHASE_OK);
        tsim_status_flag |= (1<<PHASE_CON_ERR);
    }

}

I define "PHASES" to find out which phase is sim800 in. the whole function would be written in RX interrupt service routine and the input character would be fed to it.


Your code isn't checking for a button.  It's checking the value in val.  That only gets updated once per loop.  Let's say the code enters the first if statement because the val is LOW and the LED is also LOW.  This sets the LED to HIGH.  Now the next if statement, val is still LOW and now LED is HIGH so that one is true as well.

I think what you want is to use "else if" so it will skip the rest once it finds a true one.

void loop() {
  val = digitalRead(buttonPin);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if ((val == LOW) && (digitalRead(ledPin) == LOW)) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
    Keyboard.press(KEY_LEFT_CTRL);
    Keyboard.press('r');
    delay(100);
    Keyboard.release(KEY_LEFT_CTRL);
    Keyboard.release('r');
    delay(500);
  }
  else if ((val == LOW) && (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, LOW);
    Keyboard.write(32);
  }
  else if ((val == HIGH) && (digitalRead(ledPin) == LOW)) {
    digitalWrite(ledPin, LOW);
  }
  else if ((val == HIGH) && (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, HIGH);
  }
}


Light sensor acting up when used with other code

I'd prefer to delete this question because I'm so embarrassed by the answer. I didn't notice I had Serial.println(distance); in my function. The odd numbers were coming from my rangefinders and being printed in between my light readings.


To expand upon what was previously mentioned in comments, there are a number of things that need to be done before you can program an ATmega via a serial  connection:

you need to have a bootloader flashed on the chip
you need to provide a clock source (internal or external) matching the fuse settings and the rate expected by the bootloader
your programming software must use the same baud rate as the bootloader is expecting
you need to have reset the chip recently enough before starting the upload that the bootloader has not timed out - either manually or via a small capacitor to your logic level serial connection's DTR or RTS line

You commented that your chip came from Sparkfun and was sold as having a bootloader.  The programmed ATmega328p's they list claim to have the Uno's bootloader, so most likely these need to be programmed at 115200 baud like an Uno.  You instead said that you had selected the Duemilanove setting, which would mean you were trying to use a baud rate of 57600.


Off topic for Arduino, but you could put a collar with an Apple iBeacon on your pet and implement an iOS app that would wake up and display a local notification (optionally including a sound) when your pet comes near.

You could probably do something similar using BLE, but Apple's iBeacon has the concept of geofences based on proximity to one of their iBeacons, including distance ranges from "immediate" (about a meter) to far (30+ meters, if memory serves). That's actually somewhat tricky to do using vanilla BLE.

I think in order for this to be practical you will need to put some sort of transmitter on your pet. The RFID chips that vets put into pets require that the sensor be within a few mm of the chip, so that probably wouldn't work. (From what I've seen you have to wave a wand directly over the chip on the pet's skin in order for it to be detected.) There are other RFID technologies that should work. I found this link from a Google search, for example:

https://skyrfid.com/RFID_Range.php


Communication between Arduino and iOS device

There are cables that let you plug in to the 30 pin connector and get a connection.

You could also use a BLE shield and write code for both platforms that communicate via BLE, or a WiFi shield.


Arduino Nano - programmer is not responding

For me the problem was the selected "processor" type.

I had to change it to 328p (old bootloader).

Also, raise the IDE's verbosity, in order to have a nice progress bar when loading the sketch.

My specs:

OS: Linux Mint 18.3
Linux kernel: 4.13.0-37-generic
Arduino IDE: v1.8.5
board: the cheap and common Nano Chinese clone
USB to serial chip: CH340


You can use a different type of buttons on with your Arduino, there are some that keep the state or just push button.

The most used are the "arcade" style or the push button on a breadboard.

Just remember to have a pull up/down resistor and add some code to avoid debouncing when the button has been pressed.
https://www.arduino.cc/en/Tutorial/Debounce

If you want some more custom, you can use a normal push button and add small piece of wood/plastic/metal into the hole and having low friction you will be able to press the button with a nice look and feel.


The 5V/3.3V switch is fed into the "VCCIO" pin which sets the voltage of communication and nothing else.  The 5V pin of the header is connected straight through to the USB port's 5V pin.

You can either take a separate 3.3V feed from the 3V3OUT pin of the FT232RL (limited to 50mA) which is easiest to take from the 3.3V side of the switch's pins (on the underside, either or both of the two pins with no visible trace connecting to them - the lowest two in your top picture), or you can re-wire the header so it takes its voltage from the output of that switch (the middle two pins).  It looks like it would be a case of cutting the left hand portion of the long fat trace at the top edge of the back (on your top picture) then soldering a wire from the 5V pin on the header to the center pins of the switch.  That should make the output power switchable between 5V and 3.3V.


Arduino code for continuous rotation for 3 servos with Bluetooth

pins 0 and 1 are used by the arduino for serial communication. You cant use pins 0 & 1  and then use software serial as well.

If you do want to use softwareserial try this code https://gist.github.com/emil01/afedff4c3ba4625ebc75 Here i am using pins 2 & 3.

If you do not want to use software serial you can try this code https://gist.github.com/emil01/9a89800e383ec7f95b3f

In your code

  if (bluetooth.available() >= 2 )
  {
   unsigned int servopos = bluetooth.read();
   unsigned int servopos1 = bluetooth.read();

You are performing 2 consecutive read functions, this is not ideal as there can be data loss. A more ideal solution would be send a string with known string terminators and then parsing this string to get your required data.

For e.g. you could send

  S1:90\nS2:180\n

from this string you can clearly figure out the start and end of the string and accordingly manipulate the data for your need


Stop multiple presses in vex bumper (Unexpected bumper output)

Because this problem was so infuriating and strange, I managed to do a workaround which the program refused to take a sudden addition to button counts after taking a first one. This enabled me to use the button without multiple extra counts.

string last;
float buttonPresses = 0;
float time = time1[T1];
bool isFirstTime = true;

task main()
{
    ClearTimer(T1);
    clearDebugStream();
    while(SensorValue(go) != 1) {

        string presses = buttonPresses;
        if(presses != last) {
            writeDebugStreamLine(presses);
        }
        last = presses;

        if(SensorValue(bump) == 1 && buttonPresses < 6) {
            if(isFirstTime || time1[T1] - time > 50) {
                isFirstTime = false;
                wait1Msec(15);
                while(SensorValue(bump) == 1){time = time1[T1];}
                buttonPresses++;
            }
        }

    }
}

If you want extra probability against multiple extra "presses" you can widen the interval of tolerance (in this case the 50 value) to something larger, but it makes it less accurate at registering quick taps.


I think i worn out all of my Arduino Uno memory

To check if you really cannot upload anymore (assuming it's not a software error), try the following sketch

https://www.arduino.cc/en/tutorial/blink

This will blink the BUILTIN led.

There is very low chance to wore out your memory, you can write lots of times to it (like 10,000 times guaranteed, in practice mostly more).

But there can be another hardware problem, but first check if this simple sketch works.

Also (based on jsotola's comment), remove shields/wires.

Especially wires/shields using RX/TX since these pins are (somehow) used for loading a sketch.


It isn't worth it for something done once, if you only do it in setup. However if you need to toggle the mode frequently yes it can be done. You sadly haven't said which pins, but assuming they are D2 to D6 (digital pins 2 to 6) on a Mega you can do this to set output mode:

  DDRE |= bit(PE3) | bit(PE4) | bit(PE5); // D5, D2, D3
  DDRG |= bit(PG5); // D4
  DDRH |= bit(PH3); // D6

For input mode you have to "and" in the ones-complement of the bits like this:

  DDRE &= ~(bit(PE3) | bit(PE4) | bit(PE5)); // D5, D2, D3
  DDRG &= ~(bit(PG5)); // D4
  DDRH &= ~(bit(PH3)); // D6

The exact register names are in the datasheet, and the mappings to the pins on your board are in the schematic (available from the Arduino site). The relevant part is this:

The bit numbers are in grey on the left (eg. PE4) and the board pin numbers are in green on the right (eg. 2 is digital pin 2).

The bit macro works similarly to the _BV one you mentioned in your question. It shifts 1 left the required number of bit positions to be in the right place.

A somewhat simpler and more portable solution is to use the digitalWriteFast library which you can download from:

https://github.com/NicksonYap/digitalWriteFast

This uses various compiler tricks to detect if you are using a constant for pinMode and digitalWrite and converts them into the appropriate register manipulation. You just install the library and add Fast to the function names, eg.

pinModeFast (2, OUTPUT);
digitalWriteFast (2, HIGH);


Can you use an input pin instead of ground in Arduino circuitry?

An input pin can only sense the voltage that is applied to it - whether it is above or below a pair of thresholds.

In your existing circuit when the button is not pressed the voltage sensed by the pin is 0V because it is connected to 0V (also known as Ground) through the resistor. When you press the button the input pin is connected directly to +5V, so the pin senses 5V.

If you remove the resistor or the connection to ground the pin can still sense 5V on it when the button connects it to 5V, but when you release the button the input pin then isn't connected to anything at all. It's not connected to 0V, so it can't sense what voltage is there - there simply isn't any voltage connected to it (no voltage isn't the same as 0V).

In this case the pin is said to be "floating". It's neither HIGH (5V) nor LOW (0V), it's just dangling around not knowing what it's doing.

If you want to get more technical and look at the mechanics of it, it's helpful to know that the gate of a MOSFET (which is what the input pin actually is) looks to all intents and purposes like a small capacitor.  When you connect the input pin to +5V the capacitor is charged up (current flows into it from 5V to charge it). When you connect the input pin to 0V it discharges (current flows out of the capacitor down to 0V). When charged you have a HIGH and when discharged you have a LOW.

However when a charged capacitor has no connection it (for a certain amount of time, due to self discharge) keeps hold of its charge. So if you charge it with +5V and then disconnect it you will still get +5V on the capacitor. That is until it discharges through internal leakage currents.

Those leakage currents though are so small and the capacitor is so sensitive that the input pin acts like a radio antenna. It picks up noise from the surrounding area (electromagnetic waves) which can charge and discharge the capacitor pretty much at random. So at times you may see the input as HIGH and at other times as LOW, purely depending on chance. And the longer your wires the more noise it will pick up.

The worst source of noise is the 50/60Hz mains hum that is all around you. You can see this in reality if you graph the voltage on a disconnected ADC pin and bring your hand close to it - you act like a capacitively coupled antenna and you can see the mains waveform on your graph.

It's the same on a digital input pin, except that it converts it to a square wave as it passes the thresholds (you might like to look at schmitt triggers for more detail about how it does that).

So adding the pull down (or pull up if you prefer) resistor is critical to making the input pin see what you want it to see, and not just random noise.

Since the input is like a capacitor selecting the right value of resistor can be quite important in some situations. For a simple button like this there's nothing to worry about, but for something like a rotary encoder where the input signal may change more rapidly the resistor value does become more of a concern.  Have too high a value and the gate will take too long to discharge (or charge if it's a pull up resistor). Too low and too much current could be wasted through the resistor when the button (or encoder) is active (potentially damaging the button if it's a low current sensitive device).


How do I reset an ESP8266 with an FTDI and no reset button?

Pull the reset pin up by connecting it to 3.3v with a 10k ohm resistor, then to reset the ESP you temporarily ground the pin, bringing it down to 0v/GND.
I'd recommend putting in a button for that :)


OOP vs procedural programming on arduino

Your assumption is quite wrong:

The majority of libraries use OOP.
The majority of in-built device drivers use OOP.
The core is filled with many OOP helper objects and classes.
99.99% of all sketches use those OOP objects.

The sketches themselves may not be written as a class or set of classes for a number of reasons:

There is no point
The programmer doesn't know how

When a sketch is just stitching together calls to objects defined through libraries and making a few decisions there is little point in making the sketch itself an object. It's just a waste of time.  In general if the sketch gets too complex to manage it gets broken down into smaller units - i.e., libraries - which are very often written as classes.

The moment you do Serial.begin(9600); you are using OOP.


byte BoolArrayToByte(bool boolArray[8])
{
  byte result = 0;

  for(int i = 0; i < 8; i++)
  {
    if(boolArray[i])
    {
      result = result | (1 << i);
    }
  }

  return result;
}


Send one bit out per clock pulse received using direct port manipulation?

Example bit-banged SPI using port manipulation:

bitBangedSPIfast.h :

#include <Arduino.h>

class bitBangedSPIfast
  {
  // addresses of output ports - NULL if not applicable
  volatile byte * const mosiPort_;
  volatile byte * const misoPin_;
  volatile byte * const sckPort_;

  // bit masks for above
  const byte mosiBit_;
  const byte misoBit_;
  const byte sckBit_;

  // addresses of data direction register ports
  volatile byte * const mosiDDR_;
  volatile byte * const misoDDR_;
  volatile byte * const sckDDR_;

  // bit masks for above
  const byte mosiDDRBit_;
  const byte misoDDRBit_;
  const byte sckDDRBit_;

  // delay for clock being high
  unsigned long delayUs_;

  public:
    // constructor
    bitBangedSPIfast (
          // output ports
          volatile byte & mosiPort,
          const    byte mosiBit,
          volatile byte & misoPin,
          const    byte misoBit,
          volatile byte & sckPort,
          const    byte sckBit,

          // data direction register ports
          volatile byte & mosiDDR,
          const    byte mosiDDRBit,
          volatile byte & misoDDR,
          const    byte misoDDRBit,
          volatile byte & sckDDR,
          const    byte sckDDRBit,

          const unsigned long delayUs = 1)
       :
         mosiPort_ (&mosiPort),
         mosiBit_  (1 << mosiBit),
         misoPin_  (&misoPin),
         misoBit_  (1 << misoBit),
         sckPort_  (&sckPort),
         sckBit_   (1 << sckBit),

         mosiDDR_     (&mosiDDR),
         mosiDDRBit_  (1 << mosiDDRBit),
         misoDDR_     (&misoDDR),
         misoDDRBit_  (1 << misoDDRBit),
         sckDDR_      (&sckDDR),
         sckDDRBit_   (1 << sckDDRBit),

        delayUs_ (delayUs) { }

    void begin ();
    byte transfer (byte input);

  };  // end of bitBangedSPIfast

bitBangedSPIfast.cpp :

#include <bitBangedSPIfast.h>

void bitBangedSPIfast::begin ()
  {
  if (mosiPort_)
    *mosiDDR_ |= mosiDDRBit_;    // output
  if (misoPin_)
    *misoDDR_ &= ~misoDDRBit_;   // input
  *sckDDR_ |= sckDDRBit_;        // output
  }   // end of bitBangedSPIfast::begin

// Bit Banged SPI transfer
byte bitBangedSPIfast::transfer (byte c)
{
  // loop for each bit
  for (byte bit = 0; bit < 8; bit++)
    {
    // set up MOSI on falling edge of previous SCK (sampled on rising edge)
    if (mosiPort_)
      {
      if (c & 0x80)
        *mosiPort_ |= mosiBit_;
      else
        *mosiPort_ &= ~mosiBit_;
      }

    // finished with MS bit, get read to receive next bit
    c <<= 1;

    // read MISO
    if (misoPin_)
      c |= (*misoPin_ & misoBit_) != 0;

    // clock high
    *sckPort_ |= sckBit_;

    // delay between rise and fall of clock
    delayMicroseconds (delayUs_);

    // clock low
    *sckPort_ &= ~sckBit_;

    // delay between rise and fall of clock
    delayMicroseconds (delayUs_);
    }  // end of for loop, for each bit

  return c;
  }  // end of bitBangedSPIfast::transfer

Example usage:

#include <bitBangedSPIfast.h>

bitBangedSPIfast bbSPI (PORTD,  5, PIND,  6, PORTD, 7,    // MOSI port (D5), MISO pin (D6), SCK port (D7)
                        DDRD,   5, DDRD,  6, DDRD,  7);   // MOSI ddr  (D5), MISO ddr (D6), SCK ddr  (D7)
const byte mySS =  8;  // slave select

void setup (void)
  {
  bbSPI.begin ();
  pinMode (mySS, OUTPUT);
  }  // end of setup

void loop (void)
  {
  char c;

  // enable Slave Select
  digitalWrite(mySS, LOW);

  // send test string
  for (const char * p = "Hello, world!" ; c = *p; p++)
    bbSPI.transfer (c);

  // disable Slave Select
  digitalWrite(mySS, HIGH);

  delay (100);
  }  // end of loop

Reference

SPI - Serial Peripheral Interface - for Arduino


Graphical programing language for Arduino

The most full featured Scratch-like environment for Arduino, to my knowledge that is close to your listed criteria is http://www.mblock.cc/

It's currently in beta development for enabling bluetooth uploads and supports a range of "extension" plugins.  I believe you can also add functionality by writing your own extensions if you have sufficient programming knowledge.

The software has more features if you use their mblock hardware, while offering a reduced set of commands for other boards such as the Uno.

I'm sure you can add library's to your code but at the expense of the scratch-like interface.  A children's visual design tool being able to provide graphical API to libraries written by an open source community is quite a coding challenge.  You can get a feel for this by trying to use any reverse engineering C++ to UML diagram tools.

I recommend perhaps using one of these scratch tools to build simple firmware as a learning tool with the idea of progressing to an actual programming language soon after.

In any case I hope you find what you're looking for among these options for your project.

http://www.mblock.cc/
http://s4a.cat/
http://blog.minibloq.org/p/documentation.html
http://blog.ardublock.com/engetting-started-ardublockzhardublock/
https://www.visuino.com/


Pair of nRF24L01s ping/pong example sketch works, but using my own code fails after first successful transmit

Comparing your rx against the example, i would suggest not having the while done statement. You could also throw in a few serial.write debug lines in both sketches, to log different parts of the code, to find where its getting stuck.


Reading values from SQL Arduino ethernet

I would make a small http REST API on your SQL server. The Arduino could use the API to get the data.
The API can easily be done in php, ruby or whatever.


Cannot correctly access element in array when given index

You can't access arrays that are in PROGMEM as if they were normal variables. The compiler can't tell the difference and just interprets it as a RAM address, which is wrong.

Instead you have to use pgm_read_byte to get the data:

char characterBuffer = pgm_read_byte(alphabet + correctIndex);


So, you are confusing the object String of Arduino with a string of C (char array), to solve your problem, I've changed your code in two parts:

String titles[] = {"entry one", "entry two", "entry three", "entry four", "entry five"};

void setup(){
  Serial.begin(9600);
  Serial.println("Storing numbers in an array");
}

void loop(){
  for (int x = 0; x < 5; x++){
    if (Serial.available() > 0){
      Serial.println("Enter a word... ");
      titles[x] = Serial.readString();
      Serial.println(" ");
      Serial.println(titles[x]);
    }
  }
}

So, in order to use Seria.readString(), you have to use String objects to receive the data from Serial port:

String titles[]

Instead of:

char* titles[]

The second change is related to Serial.println(chartitles[x]), I didn't understand what you mean with this code, so I changed in order to print the String that was read.


Connect your fifth wire to ground. Set the four inputs to INPUT_PULLUP. The four inputs will default HIGH, and be pulled LOW when connected to the ground wire.


errors corrected

#include <Wire.h>

byte ADDRESS_SLAVE = 0X08;
byte REGISTER_XY = 0X1F;
byte READ_LENGTH = 8;

void setup()
{
 Wire.begin();
 Wire.setClock(400000); // set I2C 'full-speed'
 Serial.begin(9600);
}

void loop()
{
   Wire.beginTransmission(ADDRESS_SLAVE);
   Wire.write(REGISTER_XY);  // set register for read
   Wire.endTransmission(false); // false to not release the line

   Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH); // request bytes from register XY
   byte buff[READ_LENGTH];
   Wire.readBytes(buff, READ_LENGTH);
   for (int i = 0; i < READ_LENGTH; i++) {
     Serial.println(buff[i], HEX);
   }
   Serial.println();
   delay(1000);
}

if you read only one register of the device, you can setup the device in setup() and in loop() only read the data from the register:

#include <Wire.h>

byte ADDRESS_SLAVE = 0X08;
byte REGISTER_XY = 0X1F;
byte READ_LENGTH = 8;

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

  Wire.begin();
  Wire.setClock(400000); // set I2C 'full-speed'

  Wire.beginTransmission(ADDRESS_SLAVE);
  Wire.write(REGISTER_XY);  // set register for read
  Wire.endTransmission();
}

void loop() {
   Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH);
   byte buff[READ_LENGTH];
   Wire.readBytes(buff, READ_LENGTH);
   for (int i = 0; i < READ_LENGTH; i++) {
     Serial.println(buff[i], HEX);
   }
   Serial.println();
   delay(1000);
}


Serial.read has garbled data after a Serial.write

I've finally found that when the MCU  to which Arduino is talking to was initialized, it would send spurious data to the Serial - I guess it would start first with a lower baud rate, and then switch to the programmed baud rate of 115200.

To fix this, I had to flush the Arduino serial RX before sending any data. So:

byte streamReadResponse;
Serial1.begin(115200);
Serial1.setTimeout(9000);
while (Serial1.read() >= 0)
           ; // do nothing
Serial1.print(cmd);
Serial1.print('\r');
Serial1.flush();  //wait for all the data to be sent to the serial
streamReadResponse = Serial1.readBytesUntil('>', data, dataLength);


Send multiple int values from Python to Arduino using pySerial

I guess I'll answer my own question for anyone else having this issue. What I did was:

Python:

# write to arduino as raw binary
bge.arduino.write(struct.pack('>BBB',45,90,180))

Arduino:

#include <Servo.h>

Servo servo0;
Servo servo1;
Servo servo2;

// create array
int incoming[2];

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

  servo0.attach(3);
  servo1.attach(5);
  servo2.attach(6);
}

void loop(){
  while(Serial.available() >= 3){
    // fill array
    for (int i = 0; i < 3; i++){
      incoming[i] = Serial.read();
    }
    // use the values
    servo0.write(incoming[0]);
    servo1.write(incoming[1]);
    servo2.write(incoming[2]);
  }
}


Arduino Uno data logger shield recording nonsense time

Where are you brining the power onto the Arduino board? If you bring it in through the external power connector you need to account for the voltage needed to run the regulator. You might be running into problems with low voltage and some part of your system that is sensitive to it.

You could try bring the power in on the 5 V pin, but then you are taking responsibility for the quality of the power supply.


How to communicate with arduino uno when arduino motor shield connected to arduino uno?

Communicate with what? A PC? The usb serial port should still work fine, and anything connected to the RX/tx pins (D0 and  D1)
If your concern is that there is no longer a socket on the top of this shield that you can plug wires into, well you can solder on some wires to the top of the board, or you could get a screw shield board to go between the arduino and motor shield which would make all the pins available. I have also use small gauage wire wrapped around the shield pins and then just insert the shield onto the arduino making kind of a wire wrap connection between the boards.


Arduino Uno with 6x 5V solenoids + 9V battery - Not enough power?

I'm using a 9V battery connected to the DC input

Well, there's your problem. Those 9V PP3 batteries are barely enough to power the Arduino by itself. Add anything like motors and solenoids and you're going to have problems. Big problems.

Ditch the PP3 battery. It's only suitable for very low current devices, like smoke alarms. For anything more you need at least multiple series AA batteries.

Also the solenoids must be powered direct from your power source (or through their own regulator if needed), since the Arduino's on-board regulator will go into thermal shutdown quite quickly with 9V in and a large current draw.


Simple answer is no.

There are about 10 similar sensors, each detect specific kind of chemicals


Software serial conflict with WiFi on ESP8266

As noted, there are conflicts between Wifi and SoftwareSerial. The attempt in the question to disconnect WiFi is a step in the right direction, but not enough. You have to actually turn off the WiFi. The challenge is to reliably shut down the WiFi and then start it up again. This has been discussed extensively in the ESP8266/Arduino Git repository here and is referred to by some as "Issue 644".  An sample implementation of the code to reliably is presented here.

Here's what the on/off functions look like. I strongly urge you to go to the code linked above and copy from there rather than here, though.

extern "C" {
#include "user_interface.h"
#define WIFI_RETRIES 25

int conn_tries = 0;
bool WiFiOff() {
    WiFi.disconnect();
    WiFi.mode(WIFI_OFF);
    WiFi.forceSleepBegin();
    yield();

    /*
     * It can take a while for the ESP to disconnect, so we need
     * to give it a couple of seconds before returning a fail.
     */
    while ((WiFi.status() == WL_CONNECTED)
           && (conn_tries++ < WIFI_RETRIES)) {
        delay(100);
#ifdef DEBUG
        Serial.print(".");
#endif
    }
    if (WiFi.status() != WL_CONNECTED)
        return (true);
    else
        return (false);
}

/*
 * Turn the WiFi back on again with forceSleepWake().
 * NOTE:-  =Your= SSID and password must be in the
 *         user_config.h file.
 */
bool WiFiOn() {
    conn_tries = 0;

    WiFi.forceSleepWake();
    WiFi.mode(WIFI_STA);
    wifi_station_connect();
    WiFi.begin("corazon_del_bosque", "");

    /*
     * It may take a while for the ESP to re-connect, depending
     * upon external factors (e:- has the access-point moved out
     * of range since we were last connected?).  This loop will
     * give us a reasonable time to re-connect without blocking
     * permanently.
     */
    while ((WiFi.status() != WL_CONNECTED)
           && (conn_tries++ < WIFI_RETRIES)) {
        delay(100);
#ifdef DEBUG
        Serial.print(".");
#endif
    }
    if (WiFi.status() == WL_CONNECTED)
        return (true);
    else
        return (false);
}

I'm using this code in my program via the Arduino IDE. The author used it in PlatformIO. Other build systems may have other requirements.


Writing a float to a BLE characteristic. What data format?

Two solutions came to my mind if am gonna do your thing,
1) convert the number to a string char by char and send it as it is then unpack it as char by char , for example 5.3 -- > "5.3" it will be received then you have to decompose it 5 and . and 3 (inefficient solution because of conversion of types will be alot)

2) calculate the number of decimal digits and send it with the number something like:
5.3 ---> 53 and one decimal point, you would send it as
53:1 and then unpack it and reconstruct it

the second solution would be better for me since i have to send it as 2 things
number: decimal point
and then reconstruct it, this library will ease the reconstruction of decimal point sent by 53:1 (if you want to send floats in two directions)
SimpleSerialExtractor


DS18B20 Temperature Sensor return as float function returning null 50% of the time

You have intermittent communication problems.

Your address search occasionally fails and getTemp() returns false. In C++ (and many other languages) false will be implicitly cast to (int) 0, (float) 0.0f, and so on.

Your getTemp() function  also is difficult to debug because the multiple return statements have different meaning.

After the delay(250); you do a return false; in order to skip the rest.

In the example at https://www.pjrc.com/teensy/td_libs_OneWire.html the meaning of the return statement(s) is different. There the return happens within the void loop() function, where it simply means to interrupt the current execution (without returning a value) and continue with the next loop.

While it is generally okay to have multiple return, it can sometimes be problematic and I recommend to avoid it.

If you want to clean this up while still preserving the ability to detect a fault, you have a couple of options (order from most to least recommended):

do the setup/checking in a different function (and only call the second one if the first one succeeded), i.e. if (isReady()) { Serial.println(getTemp()); }
set a separate error variable, i.e. error = true; return 0; (and then check error later)
define a 'default' value that you interpret as an error (and never expect to be a temperature), i.e. return NAN; // not a number


Trying to start a timer to change lights when a button is pressed

You must first declare your timer functions. I have placed them above so they are visible when you call the timer. Also in the loop() you want probably to call timer.
I have changed the code to reflect what I told above. I do not have ability to test this, so please try. There may be some syntax errors, but I think you can handle it.

#include <TimeAlarms.h>
#include <Time.h>
#include <TimeLib.h>

int redPin = 2;
int yellowPin = 3;
int greenPin = 4;
int buttonPin = 5;

void YellowTimer()
{
    setLights(LOW, HIGH, LOW)
}

void RedTimer()
{
    setLights(HIGH, LOW, LOW)
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) ;
  pinMode(redPin, OUTPUT);
  pinMode(yellowPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // set timers in seconds, yellow = 24 hours, red = 48 hours)
  // http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
  Alarm.timerOnce(86400, YellowTimer);
  Alarm.timerOnce(172800, RedTimer);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(buttonPin))
  {
      setLights(LOW, LOW, HIGH)
      Alarm.timerOnce(86400, YellowTimer);
      Alarm.timerOnce(172800, RedTimer);
  }
  delay (1000);
  }

void setLights(int red, int yellow, int green)
{
  digitalWrite(redPin, red);
  digitalWrite(yellowPin, yellow);
  digitalWrite(greenPin, green);
}


Arduino IDE Serial Monitor - how to send NUMBERs - not charcters of numbers

I think the comments on your question are quite clear. The important point: any asynchronuous protocoll must include the info either how many bytes are transmitted or which byte is the last one. In "raw data", where each value (0-255) can be a legit data value, there is no way to use bytes for meta data. That's why typically only encoded data is transmitted: you have a small range of byte values that can contain the actual info (alphabet and digits) and you have a bunch of values that are free to be used as meta data. E.g. the commonly used \n as endbyte has the int value 10. How would you transmit the int value 10 in that case?

"I don't want to implement some silly translation from character value to int" - it's not silly, that's the way to go! What about float, boolean or negative values (8-bit, 16-bit, etc.)? You may even want to transmit structured data like python dictionaries. The only way the achieve this is using some kind of parser which knows the protocol.


How to filter a blank line received over serial - ESP8266

inData.trim();
if( inData.length() > 0 ){
   Serial.println("Got: " + inData + "\n");

::trim() removes all leading and trailing whitespace characters including newlines. A line of [zero or more whitespace] + [newline] will get trimmed to the null string. If the result isn't null, then append the stripped off newline and print it. Note that this will flatten any indentation or vertical spacing that was supplied in the incoming text.


What are (or how do I use) the power saving options of the Arduino to extend battery life?

Note: I wanted to point out that, even though my answer was accepted, the reader (you) should really read Anindo's answer first if you really want to save energy with any Arduino board. Once you address those items in your design, then you should read my answer and worry about how to set the MCU into low power mode.

Having said that, there are several techniques to make an Arduino save power. I'll list a few and then point you to a page that explains them all in more detail.

While the controller isn't doing anything important (between one read of a sensor and the next, for example), you can put the controller into one of the sleep modes below, with the command set_sleep_mode (SLEEP_MODE_PWR_DOWN). Next to each mode is the approximate power consumption of each mode.

SLEEP_MODE_IDLE: 15 mA
SLEEP_MODE_ADC: 6.5 mA
SLEEP_MODE_PWR_SAVE: 1.62 mA
SLEEP_MODE_EXT_STANDBY: 1.62 mA
SLEEP_MODE_STANDBY : 0.84 mA
SLEEP_MODE_PWR_DOWN : 0.36 mA

Disable brown-out detection (the circuitry that turns off the controller when low voltage is detected).
Turn off ADC (analog to digita conversion)
Use the internal clock

Then, when you put the controller to sleep, you need to use one or more mechanisms below to wake up the controller and do something with it:

Wake up with a signal
Wake up with a timer

This is a summary I made from -

Nick Gammon's article: Power saving techniques for microprocessors.

That article applies mostly to ATmega328P, but the technique applies to other Arduino compatible controllers as well. As TheDoctor said well, you will need to check the datashet to make sure your controller suports any of those techniques and how to do it more precisely.


No. The HC-05 has to be paired. It runs on Bluetooth 2.x which requires pairing.  What you want is BLE (or Bluetooth 4.x) which has various "beacon" facilities.


What is the variable pot exactly for in arduino sensors boards?

If the resistance is higher, your LDR (light sensor) will respond in smaller increments or decrements to the same light changes. Analog inputs have 10 bit (0-1023) resolution, which is fine, but LDRs can be tricky (their sensitivity varies), so a pot is useful for prototyping the resistance you need to wire it up with in your project.


Using Capacitance-to-Digital converters AD7150 or AD7747 to measure fluid levels

Sounds like a fun project. Why not try the EVAL-AD7150EBZ is a fully featured evaluation board for the AD7150. The evaluation board can be operated in standalone mode ( either battery-powered or with external power supply) or connected to a PC via a standard USB interface. When operated with a PC, software is provided enabling the user to perform detailed analysis of the CDC's performance. This software includes the technical note describing the operation and set up of the evaluation board. Also how you package the sensor will have a big impact on how it works.


I have some details about running motors etc. from Arduino pins at Driving motors, lights, etc. from an Arduino output pin.

Quite possibly what would work for you is a MOSFET - as Majenko suggested - connected up like this:

In this case you connect the positive side of your 12V supply for your pump to the pump, and the MOSFET sinks current to ground, when you require the pump on.

Don't forget the diode D1 which prevents damage from the inductive load of the pump generating high-voltage spikes.


Arduino UNO Low-Power Consumption (Multiple Ultra-Sonic Sensors)

You did not specified, what kind of ultrasonic sensor you want to use so I assume use of "standard" ultrasonic Arduino modules (like hc-sr04), which need 4 pin (VCC, GND, TRIGGER and ECHO). Since Arduino Uno has got 20 IO pins (6 analog and 14 digital), you can use 10 pins as outputs for TRIG signals and 10 as inputs for ECHO signals and thus connect up to 10 ultrasonic modules to one Arduino Uno.
In general, Arduino Uno is not designed for low-power applications. If you want more specific answer, you should ask more specific question...
Working temperature of Arduino Uno is -40 to 85 °C.
One of the options is using a terminal shield with screw terminals, e.g something like this.


Plug your Uno into the Mac using a known good USB cable.
Go to the Apple menu -> About This Mac -> More Info -> System Report
Under the USB selection (on the left) please confirm whether or not you see something like this:

You can also open a Terminal window and type:
system_profiler SPUSBDataType

Amongst other things you should see:
USB:

    USB High-Speed Bus:

      Host Controller Location: Built-in USB
      Host Controller Driver: AppleUSBEHCI
      PCI Device ID: 0x3b34
      PCI Revision ID: 0x0006
      PCI Vendor ID: 0x8086
      Bus Number: 0xfd

        Hub:

          Product ID: 0x2514
          Vendor ID: 0x0424  (SMSC)
          Version: 0.03
          Speed: Up to 480 Mb/sec
          Location ID: 0xfd100000 / 2
          Current Available (mA): 500
          Current Required (mA): 2

            Communication Device:

              Product ID: 0x0043
              Vendor ID: 0x2341
              Version: 0.01
              Serial Number: 9314036423335121A0B1
              Speed: Up to 12 Mb/sec
              Manufacturer: Arduino (www.arduino.cc)
              Location ID: 0xfd130000 / 8
              Current Available (mA): 500
              Current Required (mA): 100

Note the "www.arduino.cc" entry.
In your Arduino IDE you should see the Arduino as a tty.usbmodemfd131 (or some similar number).

If you see all that it should work.
If not, please state in what way it differs.

Programmer -> AVRISP mkll

The Tools > Programmer menu selection is only used when you do Tools > Burn Bootloader or "Upload Using Programmer. It is completely ignored when doing a standard "Upload". You should be doing an "Upload" (Command-U) not an "Upload using programmer" (Shift+Command+U). So it makes absolutely no difference what you select from the Tools > Programmer menu.


Gas Sensor output voltage to concentration

I would like to convert the voltage to concentration in ppm?
Is there any way??

the datasheet for those devices would have the answers for you. Generally, you read the datasheet BEFORE deciding on using them or not. not that otherway around.


After you drive the pin low, you immediately go to the beginning of the loop and set the pin high (if you have an oscilloscope, you might see a very short downward pulse).
So, add another delay after digitalWrite(devicePin, LOW).


Can't open "COM1" on Linux with Trinket Pro

[  881.092161] usb 2-1: Product: USBtiny
[  881.092163] usb 2-1: Manufacturer: Adafruit
[ 1004.305143] usb 2-1: USB disconnect, device number 5
[ 1019.935505] usb 2-1: new low-speed USB device number 6 using xhci_hcd
[ 1020.106524] usb 2-1: New USB device found, idVendor=1781, idProduct=0c9f

The USB Tiny ISP device which this logs shows being connected to your system is not a USB serial device.  Therefore, it will not have any /dev/ttyXXX device associated with it.  Instead it should be used with the -c usbtiny argument to avrdude.

Adafruit documents their products fairly well, and this is no exception.  The Linux section of the user guide is at https://learn.adafruit.com/usbtinyisp/avrdude#for-linux

That guide goes on to explain that you will typically need to create a udev rule to allow an ordinary user account to access the device.  Depending on Linux installation, typical contents might be

SUBSYSTEM=="usb", SYSFS{idVendor}=="1781", SYSFS{idProduct}=="0c9f", GROUP="users", MODE="0666"

or

SUBSYSTEM=="usb", SYSFS{idVendor}=="1781", SYSFS{idProduct}=="0c9f", GROUP="adm", MODE="0666"

The above linked guide will more comprehensively explain how all of this works.

Note that the above pertains to the USB Tiny ISP programmer shown in your dmesg output.  According to the Adafruit page on the Trinket Pro, the Trinket Pro "bootloader looks just like a USBtinyISP" therefore, you would talk to it in the same way as the USB Tiny ISP that your system reports finding, ie, without using a /dev/ttyXXX device, but rather by specifying -c usbtiny in the avrdude command line, or using an Arduino IDE board configuration which does so.

Your error message suggests that avrdude is not being run with the correct command line options.  You may want to turn on verbose mode to see what is being run - it would especially helpful if you did that on both the working and the non-working Linux systems.


How do i fix the "A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header"

ESP32 only works with 3.3 V serial do not switch the FTDL voltage to 5 V

Watch out for the serial connections too

U0R-->TX

U0T-->RX

If you mixed it up it won't work!

First of all you need to connect two pins only when uploading
It is all ready fixed for you need to press the rest button when uploading
and seeing these dots as below image.

ESP32-CAM on-board RST button Press and hold until you see uploading

After a few seconds, the code should be successfully uploaded to your board.

I hope this helped for you!

You can reffer to this link for more info

https://randomnerdtutorials.com/esp32-cam-take-photo-display-web-server/


Change sagservo.write(-45); to sagservo.write(0);.


Shift register on Attiny85 programmed by Arduino

The ATtinyX5 does not have any analog-only pins; all 5 pins are usable as digital I/O (all 6 if you know what you're doing, but if you need to ask how then you're not ready to do so).


Are these lcd and motor-shields stackable?

No, it doesn't look like it.

The LCD board uses digital pins 4-10 and analog 0

The motor board uses digital pins 3-12 if all motors are used.

If you need to stack boards look for boards that use I2C since they can share a single data bus.


Daisy chaining of multiple blocs of 4x(8x8) MAX7219 matrix

All is OK changing the proposed statement
define HARDWARE_TYPE MD_MAX72XX::PAROLA_HW
to
define HARDWARE_TYPE MD_MAX72XX::FC16_HW


I finally found where the problem was, i had made a error on the reading of the schematic of the evaluation board. I thought that the pin J1-9 was already wired in intern but it was wrong. I wired it to the VCC output of my board and it work perfectly now.


Arduino Video Feed (Building Zumo Robot)

As Duncan wrote in the comments, an Arduino is way not up for the task of handling video (even still images can be a problem due to memory.

So you need to go with a small single board computer, like the Raspberry Pi Zero, that can be seen on one of your images. It has a Mini HDMI output, where you can connect a display. I don't know, if there already is software on the Arduino and Pi, because I don't know this robot. You have to make sure, that this software doesn't conflict with the software, that you would write.

How to connect 2 displays is more tricky. The Zero is not capable of running 2 displays independendly. If the displays should show the same, I think there are Y-cables for HDMI. If only one display has to show something at a time, you could use a HDMI switch (and you can even hack that, to trigger it from the Zero or Arduino). If you really need both displays independently and simultaneously you need to either use a Raspberry Pi 4 (which supports 2 displays via its 2 Micro HDMI outputs) or add another Raspberry Pi Zero.

The video then is of course not read from the Adafruit SD breakout board, but from the Pi's SD card. Even if the Arduino was fast enough for video, these breakoutboards are using SPI to connect to the SD card, which is inherently slow. If used in a computer the SD card is connected via a parallel interface.

  How to learn any other programming for the Arduino

There are tons of tutorials and courses online, so you just need to google. We can only help with specific problems here. And the video part will be on the Pi, so no Arduino question. You might want to learn Python to code on the Pi.


Variables not initialized in Class Constructor

First, I would do what Edgar Bonet suggested, call the normal constructor:

MB_GFX_SPI mbGFX (Period, numCathodeLeds, numAnodeLeds, CathodeSSPin, AnodeSSPin);

Second, I'm not keen on what you are doing in the constructor for a variable which appears to be at global scope (mbGFX).

See What's the "static initialization order fiasco"?

Basically you cannot assume that constructors in different compilation units are called in any defined sequence, you also cannot assume that the system has been initialized yet (ie. init() called).

Thus, things that address the hardware (eg. clearScreen(0);) may not work properly, or at all.


EPS8266 ESP-01: LED manipulation seems to interfere with serial communication

I would bet that the built-in LED pin is also the TX pin for the serial interface.

Check here, LED Pin section: http://www.esp8266.com/wiki/doku.php?id=esp8266_gpio_pin_allocations

  LED Pin

  GPIO1, which is also TX, is wired to the blue LED on many devices.
  Note that the LED is active low (connected to Vcc and sinks through
  the chip to ground) so setting a logical value of 0 will light it up.
  Since GPIO1 is also the TX pin, you won't be able to blink the LED and
  perform Serial communications at thew same time unless you switch
  TX/RX pins.

This would be confirmed if the LED blinks when serial communication is active.

If this is the case you would have to add your own LED on a different pin, or switch the RX/TX pins.


cast from 'char*' to 'char' loses precision

By adding strings together you are actually adding together the addresses in memory where those strings are.

Instead you need to create a new empty buffer and fill it with the contents of the other strings.

char buffer4[32]; // <-- Enough room for both strings and a NULL character

strcpy(buffer4, mqtt_topic);  // Copy in the first string
strcat(buffer4, buffer2); // concatenate the second string


How do I use two PulseIn() functions simultaneously in Arduino?

You can't. pulseIn() is a blocking function that waits for a pulse to arrive before returning.

Instead you will either have to use interrupts or (where available) Input Capture peripherals.

However, using multiple ultrasonic sensors at the same may not make sense. Unless you take great care with your physical design you will get interference between the two.  Echoes from one bouncing around will trigger the other.  For this reason it is normal to not trigger both at once, but to use them sequentially, in which case pulseIn() is still perfectly fine to use.


The membrane keyboard you have linked (first link) in your question should be water resistant, if not water proof.

We use something similar at my work. You can have the keypad stuck to the outside of the enclosure and then have a rubber seal (or silastic) sealing where the ribbon cable enters the enclosure.

You will notice that the ribbon cable pretty much exits the bottom of the keypad. The better ones to get, if you can find them, are the ones where the ribbon cable exits the keypad further away from the edge (see example image below). That way the adhesive backing of the keypad seals the cable entry into the enclosure.

As far as hooking it up to an Arduino - no problems at all. A 16 key matrix keyboard has 8 connections, 4 for each row and 4 for each column. Every time you press a key, the row and column are shorted together.

The way I would connect it up is to have the rows connected as inputs and the columns as outputs. One by one I would turn one of the columns on (HIGH) and see which input(s) are reading a HIGH. If it is I know that that key (row and column) is pressed. This method will handle multiple keys pressed at once.

There is an walk-through tutorial posted at instructables.com.

The more expensive keypad in your second link and this one both have the option of connecting by PS2. There is an Arduino page on connecting and controlling a PS2 keyboard here.


Why I cannot change array values even if a statement is successfully called? TFT Touch Screen

It's because you are defining a new array every time, not modifying the existing one.

int matrix[2][3]={{25,150,265},{45,100,155}};

That line doesn't assign new values to the existing matrix array, instead it creates a new array called matrix which only exists within the current scope - that is, within the {...} defined by the if that it is within.

Instead you either need to assign values directly to the existing matrix array on a slice-by-slice basis (you cannot use {...} to assign them in bulk):

matrix[0][0] = 25;
matrix[0][1] = 150;
... etc ...

Alternatively, since the values are static, you can pre-define the different matrices in the global scope and then switch between them.  This can be done with the right kind of pointer. For instance:

int textMatrix[2][3] = {{260,140,20},{40,150,95}};
int (*matrix)[3];

void whateverTheFunctionIs() {
    if (whatever...) {
        matrix = textMatrix;
    }
}

In that example matrix is a pointer to an array of pointers, which is basically what a 2D array is internally.  It starts off by not being assigned to anything at all - it's just "dangling in the breeze".  When the if in your function is triggered the address that the matrix pointer points to is changed to that of the textMatrix 2D array, so any access to matrix[x][y] will be identical to accesses to textMatrix[x][y].


You can use the function millis(), that returns the number of milliseconds since the Arduino board began running the current program (unsigned long). This number will overflow (go back to zero), after approximately 50 days.

The code below uses the millis() function, a command that returns the number of milliseconds since the Arduino board started running its current program, to blink an LED.

/* Blink without Delay

 Turns on and off a light emitting diode(LED) connected to a digital
 pin, without using the delay() function.  This means that other code
 can run at the same time without being interrupted by the LED code.

 The circuit:
 * LED attached from pin 13 to ground.
 * Note: on most Arduinos, there is already an LED on the board
 that's attached to pin 13, so no hardware is needed for this example.

 created 2005
 by David A. Mellis
 modified 8 Feb 2010
 by Paul Stoffregen

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
 */

// constants won't change. Used here to
// set pin numbers:
const int ledPin =  13;      // the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

Source: http://arduino.cc/en/Tutorial/BlinkWithoutDelay


Why does my LED turn off automatically after about 18 seconds on its own?

Again, figured this out. I simply forgot to put in board_init(); Also, since board_init() already calls ioport_init(), I had to disable that.

Now I have this:

int main (void)
{
    /* Initialize the SAM system. */
    sysclk_init(); // Initialize the System Clock
    board_init();  // Initialize the board

....


There are two purposes of such capacitor:

first it supply power for short peaks in demand, so effectively enabling the 12V power source supply much more current for short time, than it can support over long time and so the driver have more stable power and works generally better. Also it protects the driver from noise of other parts.
the other is protect all other parts from voltage drops and noise caused by the driver. It is recomended to have capacitors as near as possible to any IC/driven circuit for this reason.

So basically - if you have good power source, you can often get away even without such capacitors. But if you power also logic from the same source, it is already better to have some capacitors on power lines where posssible. Escpecially if you expect some noise around (like having motors near or lines to motors in paralel with other lines ...). Depends how much you care and how critical you see the project. Hobby project just for fun can go even without capacitors and be all good. Good industry projects have capacitors always everywhere.

I had project, where it worked even without capacitors (laser printer), but now I would place some there in any case near each driver, just to be sure. 100uF is really good capacity, enables for lot power. But if you use any other value (which you have more ready), it should not hurt too. It is not about if it would work or not, it is more about if it ensures, that it would work flawlessly even in bad conditions even under unexpected conditions and would not have "sometimes strange problems, which disapear spontaneously during debugging".

Also note, that for improving power are good high capacity electrolytes. For preventing noise are much better ceramic (which are fast, even if they have a lot smaler capacity) and so many people put both there (like 100uF electrolyte and 100nF ceramic in paralel).

Short answer: Do as you want, it would probably work anyway. I personally would place big+small capacitors near each driver.


WeMos D1 ESP-Wroom-02 Mother Board ESP8266 - where is reset pin for deep-sleep

This support page has the instructions for enabling deep sleep:
Support for WeMos D1 ESP-Wroom-02 Nodemcu
edit by Guy: in short, solder/connect pins as shown circled in red:


Attiny85 not recognized at windows startup

I don't have enough reputations to make a comment so I will drop my 2 cents here.

There should be more elegant way to do this but as a fast solution I would recommend two things:

If it is possible, add a push button to your board to reset the MCU manually when the PC is booted up.
You can make a software reset after powering up the board by a certain time (e.g. 10 sec) by using watchdog timer.


How do I read the fuse bits from within my sketch?

You can use the boot_lock_fuse_bits_get function from <avr/boot.h>.

#include <avr/boot.h>;

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

    cli();
    uint8_t lowBits      = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
    uint8_t highBits     = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
    uint8_t extendedBits = boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS);
    uint8_t lockBits     = boot_lock_fuse_bits_get(GET_LOCK_BITS);
    sei();

    Serial.print("Low:  0x");
    Serial.println(lowBits, HEX);
    Serial.print("High: 0x");
    Serial.println(highBits, HEX);
    Serial.print("Ext:  0x");
    Serial.println(extendedBits, HEX);
    Serial.print("Lock: 0x");
    Serial.println(lockBits, HEX);
}

void loop()
{
}


what to write instead of delay() in interrupt function?

what to write instead of dely() in interrupt function?

Nothing. An interrupt service routine (ISR) should not do any things, that take long. That will block any other things from happening, for example Serial communication (which is done by interrupts in the background).
delay() does not work in an ISR, because it relies on the millis() counter to increment. But that is done in another ISR. While one ISR is running, no other can run at the same time. Thus delay() waits forever, that the millis() counter increments.
What to do instead?
Instead you should only use the ISR to set a simple flag variable, for example of type boolean (because it should be a single byte type). Then in your main code (meaning inside loop()) you check for this flag. When it is set by the ISR, you execute the corresponding code and reset the flag. Be sure to declare the flag variable as volatile, so that the compiler knows, that is can change at any time.

That said, you should really ditch all the delay() calls. Instead use a non-blocking coding style involving millis() like in the BlinkWithoutDelay example, that comes with the Arduino IDE. There are tons of tutorials and explanations about that on the web and this site. Just search for it. Using a non-blocking coding style is needed, if you want the code to be responsive while doing long timed things.
Also you should look into Finite State Machines (FSM). Thats a very powerful principle, that will come in useful. It fits exactly on a traffic light project. I have once wrote a longer explanation about FSMs in my answer to this question, though you can also google something like "Arduino fsm". You basically divide the behavior of the project into individual states. The current state is hold by a variable. By changing that variable you transition between states. For example padcontrol() could change the state variable to the state for the pedestrian light. I strongly suggest, that you learn that principle to structure your code. I can attest, that it is really helpful.


Yes, but the configuration side of things will not be part of the gamepad HID.  You will need to set up a second communication channel - be that serial or raw HID - to do the configuration.


Millis() does not back to zero after woke up from deep sleep mode

Store millis() at boot, and if (resetCause == "Deep-Sleep Wake") zero out the stored copy of millis().


Clock generator up to 8 MHz using pin 3 arduino nano

The MCU Timer Outputs are hardwired to specific pins. Arduino Nano (ATmega328p) pin 3 is the MCU pin PD3 and may be connected to Timer 2 output logic, OC2B with Output Compare Register 2B (OCR2B). Waveform Generator Mode and Timer Clock prescale are the same as above.

 pinMode(3,OUTPUT);

 TCCR2A = ((1 << WGM21) | (1 << COM2B0));
 TCCR2B = (1 << CS20); // prescaler = 1
 TIMSK2 = 0;
 OCR2B = 1;

Cheers!


Shared memory only makes any sense in two combined situations:

You have a kernel arbitrating processes, threads and memory allocation, with process isolation
You have multiple threads or processes in your application

You certainly don't have number 1 unless you can install an operating system on the Teensy 3.1 (some RTOS may provide a SHM analogue).

As for 2 yes, it could be said you have two threads. But you don't have any form of process isolation, so what one "thread" can access the other "thread" can access.

Both the ISR and the loop() function have access to the exact same memory. Any global variables are accessible to both. You may need to inform the compiler that a variable is modified in one thread and read in another though. The simplest way of doing that is to make the variable volatile by prepending the volatile keyword to the definition.


Powering arduino uno from Car's reverse light?

Power the Arduino in parallel with the bulb.  Take the V+ wire running to the reverse light and the frame ground.  The frame ground is any bare metal surface of your car will be grounded, just connect a wire to your frame.  Or you can just splice the light bulbs ground wire.  When powering the circuit in parallel you do not have to worry about the amperage draw of the light.  By a barrel jack connector like this connector from spark fun you can buy these cheaper elsewhere just a 2.1mm barrel jack connector.  Connect the positive and negative respectively, and connect the 12v into the Arduino's barrel jack.

As a side note the bulb should be getting 12V not 10V it's not a huge problem, but it is a slight issue that could later be a problem or be caused by an electrical bug.  If everything works don't scramble to fix it, but be aware it exists.


"Bad request" error (HTTP) while posting to PHP server using Arduino and ESP8266

The URI path in the HTTP request must start with a /.

It should be:

String uri = "/esp.php";


For Loop function to iterate through outputs after interrupt

Original code is updated with final version. A motion sensing interrupt iterates over multiple voice playback output pins and sleeps at low power for rest of time.


Unable to receive data when using multiple SoftSerial on Arduino Nano

You cannot receive on more than one SoftwareSerial port. It's sad, but that's the way it is.

You can manually select which port you are listening to at any time with the softwareSerials[x].listen() function, but only one can ever listen at a time.

SoftwareSerial is a fudge at best and should only be used for one port and even then only if you really have to.


For simulating different gates with the same program, an option is to
use the serial port to tell it what gate you want it to simulate. Here I
am also using a function pointer (called gate) to represent the
selected gate:

/* Wiring. */
const int inputA    = 2;
const int inputB    = 3;
const int outputA   = 11;
const int outputB   = 12;
const int outputRes = 4;

void setup()
{
    pinMode(inputA,    INPUT_PULLUP);
    pinMode(inputB,    INPUT_PULLUP);
    pinMode(outputA,   OUTPUT);
    pinMode(outputB,   OUTPUT);
    pinMode(outputRes, OUTPUT);
    Serial.begin(9600);
    Serial.println(F("Type 'a'(for AND), 'o' (OR) or 'n' (NAND)."));
}

/* Available gates. */
bool AND(bool a, bool b)  { return a && b; }
bool OR(bool a, bool b)   { return a || b; }
bool NAND(bool a, bool b) { return !(a && b); }

/* The gate we want to test. */
bool (*gate)(bool a, bool b) = AND;

void loop()
{
    // Select the gate through the serial port.
    switch (Serial.read()) {
        case 'a': gate = AND;  Serial.println("AND");  break;
        case 'o': gate = OR;   Serial.println("OR");   break;
        case 'n': gate = NAND; Serial.println("NAND"); break;
    }

    // Simulate the gate.
    bool a = !digitalRead(inputA);  // input is in negative logic
    bool b = !digitalRead(inputB);
    digitalWrite(outputA, a);
    digitalWrite(outputB, b);
    digitalWrite(outputRes, gate(a, b));
}

Here is another version, that uses an enum instead of a function
pointer to identify the gate. The constants and the setup() are the
same as before, then:

void loop()
{
    // The gate we want to test.
    static enum { AND, OR, NAND } gate;

    // Select the gate through the serial port.
    switch (Serial.read()) {
        case 'a': gate = AND;  Serial.println("AND");  break;
        case 'o': gate = OR;   Serial.println("OR");   break;
        case 'n': gate = NAND; Serial.println("NAND"); break;
    }

    // Simulate the gate.
    bool a = !digitalRead(inputA);  // input is in negative logic
    bool b = !digitalRead(inputB);
    digitalWrite(outputA, a);
    digitalWrite(outputB, b);
    bool res = false;
    switch (gate) {
        case AND:  res = a && b;    break;
        case OR:   res = a || b;    break;
        case NAND: res = !(a && b); break;
    }
    digitalWrite(outputRes, res);
}


How to code an arduino to execute a particular code using a slide switch

Your switch wiring for D12 is wrong. You connect your inputs directly to ground and that can never change, regardless of the position of the switch.

You effectively have:

simulate this circuit – Schematic created using CircuitLab

However you are over complicating things.  A SPDT switch is nothing more than two buttons, only one of which can be pressed at one time.  If one is pressed the other must be released.

You can completely ignore half the switch and treat the other half as a button: if the "button" is pressed then the switch is in one position. If the "button" is released then it's in the other position.

Unless it's a "center off" switch, in which case it has 3 positions, not 2, and the middle one has nothing connected.

If it is a simple 2-position SPDT switch then just disconnect the D12 wire and remove the right-and resistor in your drawing. Then read D13 to determine the position: HIGH is one position and LOW is the other.

If it's a 3-position "center off" switch then move the D12 wire 4 holes to the left so that it connects to the switch-resistor junction, not ground. Then you will need to read both D12 and D13 - which ever one is HIGH is the one that is activated, and the switch is in that position.

Then it's a simple "if / else" (2 position) or "if / elseif / else" (3 position center-off) structure to decide which code to run.