Why can't I connect more than one Arduino Uno + Ethernet Shield to my network?

It would be most helpful to see the code you're using and to know more about the configuration of your network and the symptoms of the conflict – for example where is the web site running?

Some things to try:

Simplify your network. Eliminate everything but the Arduinos and the web server. See if that changes anything.
Run the command arp -a (assuming you've got a machine running something UNIXish). It will show you the MAC and IP addresses of hosts on your network. Look to see if the Arudinos are still there and if there are any devices that conflict with them.
Try to ping the Arudinos. Do they respond?
Use WireShark or tcpdump to monitor traffic on the network. Look for traffic to or from the Arudinos (by IP addresses and by MAC addresses).
Add some debug code to the Arduino sketch so that you can watch what they are doing (send it out the serial monitor). See if what goes on the wire matches what you expect (monitoring with tcpdump).


The zero-value, the "null character", indicates the end of the string. For strings, you allocate some maximum space, in your case 96 bytes:

char serial_message[96];

When storing variable-length strings in that, you need to indicate where the string ends. That's what the zero value does in a null-terminated string. (Note that 0 is really binary 0x00 here; it's not the ASCII character 48, 0x30.) So, the 96 bytes allow for a string of at most 95 characters, followed by the terminator. When printing, it prints the memory contents until it finds that null character.


Using Arduino UNO to retrieve ATMega328P-PU chip signature

There is a nice explanation here about Atmel chip signatures.

It sounds like you already know this, so for others looking for help:

It says that there are different signatures in the Atmel chips you mention.  That you can over ride the Avrdude program using an "-F" switch.  Or you can change the Avrdude configurations to use the "other" Atmel chip (however, the consequences if any were unknown by the author).

This may be an obvious step, but double check to make sure the IDE's target board settings are correct.

You may also want to check the communications between the programmer and the target.  You might look into dropping the speed.  But the better way is to scope the lines to see if data is being sent to the target and if the target is talking back.  From that you can infer if the problems is a bad connection or if the chip has been damaged.

If you want to dig further using software tools you could look into driving Avrdude for your self.  There is a easy to read tutorial here and what appears to be an everything you wanted to know and more document here.

In the 1st tutorial (from ladyada.net) we see a test which they purposely try the wrong signature:

  Just for kicks try running this command avrdude -c usbtiny -p atmega8
  -U flash:w:test_leds.hex

  You'll see that it stops at step 2, once the signature is different
  than the expected one it stops. This is because code that is compiled
  for an attiny2313 wont run on an atmega8 (this is true of most
  microcontrollers, the .hex files are not cross compatible)

But more interestingly, Avrdude prints out the signature read back from the target!  So, if you run the same test, you could tell if Avrdude is able to communicate at all with the target.  That is, you may see all zeros or all ones or even an alternate message from Avrdude. Which could be an indication that the target is not talking.


Error Compiling on raspberry Pi - no error details provided in IDE

It's not printIn, but println (as in "print line").


Operating HB100 backpack with Arduino Due

The articles and tutorials I've read on the subject say that the HB100 module produces a very weak signal which needs to be amplified before your Arduino can read it. They recommend building an op amp. This post on the Arduino forums, for example: http://forum.arduino.cc/index.php?topic=61989.0

BUT looking at your picture and linked article, I find that your device already includes the signal amplification and filtering you need in the backpack board. I found the store page for this module, which has a more noob-friendly explanation. From what I gather:

VCC: provide the module with a 5v supply.
VOUT: analog reading of the amount of return signal being received. My guess is you could use this with analogRead() to get a rough estimate of the size or distance of the object being read. If you want only the speed reading, you don't need this pin.
FOUT: digital output of the speed that the sensor is reading. Thanks to @sachleen's link, you can use either pulseIn() or FreqCounter library to measure the frequency and then convert it to a MPH or KPH speed.
GND - ground, aka common, aka -.

So connect VCC to 5v, GND to ground, and FOUT to an input pin on your Arduino. If you use pulseIn(), frequency f = 1 / t, t being the return value from pulseIn(). If you use the FreqCounter library, it no doubt has documentation on its usage.


I noticed that it is very hard to use classes with the default IDE.
Each file will be in a different tab, but normally each class has a header (.h) and implementation (.c) file, so 2 extra tabs per class.

If you have just 3-4 classes you can use the default IDE.

However, if you want to use more, you have to use e.g. Eclipse or Visual Studio, whatever IDE you like best.

Search for Eclipse/Arduino, I think there are multiple options.

Myself I use visualmicro ... it is free except you cannot use the debugger option.

I used several classes in my sketch and don't think the compile time was 30 seconds; it might be depending also on the amount of include files.

Also a complex program is not necessarily a program with many classes. I would say, that if you put too much functionality in one class (or one single sketch), you get a complex program.


Just use diode logic.

The resistor is probably not needed because the Arduino has an internal pullup resistor.

This assumes that the two reset inputs are active low

simulate this circuit – Schematic created using CircuitLab


Arduino zero programming port recognized as EDBG USB port

I don't have one of these to test with, but in looking at the driver installation instructions, I would expect it to say "EDBG Virtual COM Port" before a driver is installed and "Atmel Corp. EDBG CMSIS-DAP" after the driver is installed.
The "Arduino Zero Programming Port" is something I expect only appears in the Tools/Port menu in the IDE, despite what it says in the article.  You can see this name given in the boards.txt file.  And this makes sense to me, given that the EDBG firmware is Atmel's not Arduino's and there appears to be no indication in the driver directory, the content of the INF files, to suggest that they they're providing their own customized driver for the programming port.  So I would trust what you see in the images, suggesting it should say CMSIS-DAP without mention of "Arduino Zero" at all.  So far as I can tell, you're not doing anything incorrect driver-wise, but I'm also not seeing everything.
In any case, it appears you should have the VID (03eb) and PID (2157) in the device properties that boards.txt instructs the IDE to look for:
arduino_zero_edbg.name=Arduino/Genuino Zero (Programming Port)
  1 arduino_zero_edbg.vid.0=0x03eb
  2 arduino_zero_edbg.pid.0=0x2157

However, your error mentions PID=2111.  I looked this up in a USB VID/PID database, and it mentions the an ATMEL Xplained board, which is not a completely unrelated thing, but this VID:PID are not mentioned in the driver information or boards.txt for the Arduino Zero.
I did find this one mention that the Xplained USB PID was used on the M0 Pro which is a different beast from the Zero.
In any case, I would not worry about not seeing something like "Arduino Zero Prog. Port" in device manager itself for the programming port.
Make sure you are using Zero and not M0 Pro.  If you have the M0 pro, in which case properties in Device Manager may show PID as *2111, I'm not sure what to suggest except that maybe you should install Microchip Studio since this seems to be the only way I can find to get the Xplained EDBG drivers.  Some work may still be required after that to get it to work in the IDE.
If you have a Zero and not M0 Pro installing Microchip Studio may also install the EDBG driver for it as well, although this really shouldn't be necessary.


Is there any arduino microphone that can record heart sound?

First, there is no such thing as an Arduino microphone. There are boards specifically for Arduino which have a microphone, but also these are just generic 'electronic sound sensors'.

In principle any microphone would be a valid choice, but you have to test what are the requirements (distance to heart, environment noice). You also could use piezo sensors for vibration checking possibly.


Built-in capacitive touch detection with SAMD21 development board (Arduino Zero Compatible)

You have three options for the silicon-based PTC (peripheral touch controlller).

LibrePTC - My own library that targets the SAMD11 but should work with some modifications for other SAMD architectures. The README file has lot of information on how the PTC works and how to specify designs for it.
Adafruit FreeTouch - Works only with the SAMD21. Given the high quality of the register documentation, I suspect they may have had inside help from Atmel but I haven't been able to reach Ladyada, their primary contributor, to learn more.
QTouch, which is Atmel's library available in closed source only but is extremely feature-rich. Arduino team decided not to allow closed source stuff in their IDE so its been banned from official distributions. However, it is possible to hack it into the Arduino IDE and I've used it successfully that way. However this requires esoteric modification to boards.txt that are beyond the scope of this answer.

The PTC hardware peripheral on the SAMD chips works on self-capacitance using "Y" lines specified in the data sheet. See the README on LibrePTC for details. Some chip variants have more pins broken out. For instance, the SAMD21G has fewer available Y pins than the SAMD21J, although the J series is not as readily available in breakout boards as of the summer of 2017 and it has limited Arduino IDE support. I personally prefer the SAMD11 because it is cheaper ($1.00) and has way more available Y lines in the QFN package.

As of August 2017, I intend to attempt a merge between the Adafruit and LibrePTC libraries but no guarantees when this will happen. I don't have access to insider documentation so my library was 100% reverse engineered through trial and error.


I2C and RS485 are such vastly different protocols with such vastly different signalling needs that they cannot share the same cables.

Further, I2C is not designed for connecting with long cables - it's meant for use between chips on a PCB.

The simplest "Arduino" solution would be to create a new RS485 device on your RS485 bus using another MAX485 and a small Arduino (micro, nano, etc) that responds to MODBUS RTU instructions and controls the relay board for you.


For capacitance as small as pF, The RC time constant method yields dirty results on an Arduino board.

You can use the Arduino pins built in small capacitance (which is in Pf itself) to create a "capacitance divider" circuit and calculate much like you would resistance from a voltage divider circuit.

See this excellent post by Nethercott for reference
Arduino capacitance meter


You have correctly determined the root of the problem, both shields are trying to use the same pins. To work around this we need to know which pins are being used, and for what.

The Ethernet Shield documentation reveals the following:

  The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.

https://www.arduino.cc/en/Reference/Ethernet

The documentation for Sparkfun's EasyVR library isn't as explicit, but one of the examples gives us another clue:

#if defined(__SAMD21G18A__)
  // Shield Jumper on HW (for Zero, use Programming Port)
  #define port SERIAL_PORT_HARDWARE
  #define pcSerial SERIAL_PORT_MONITOR
#elif defined(SERIAL_PORT_USBVIRTUAL)
  // Shield Jumper on HW (for Leonardo and Due, use Native Port)
  #define port SERIAL_PORT_HARDWARE
  #define pcSerial SERIAL_PORT_USBVIRTUAL
#else
  // Shield Jumper on SW (using pins 12/13 or 8/9 as RX/TX)
  #include "SoftwareSerial.h"
  SoftwareSerial port(12, 13);
  #define pcSerial SERIAL_PORT_MONITOR
#endif

#include "EasyVR.h"

EasyVR easyvr(port);

EasyVR-Arduino/examples/TestEasyVR/TestEasyVR.ino

This block of code is determining how to set up the serial communication. The first two if statements are for different boards, but the third one sets up the software serial connection... and it says there are two options, pins 12/13 OR 8/9! If there are two options, there must be a way to switch it on the board itself.

And sure enough! Check out that white box labeled "SW Serial Pins". Jackpot!

Here's what the manual has to say:

  On the bottom side of the board there are two SMD resistors that you can move to select the two pins of
  Arduino that the EasyVR will be connected to when in Software Serial mode (Mode Jumper on SW).

  RX – Software Serial Receiver pin

  D12 – Use digital pin 12 as serial receiver (default)
  D8 – Use digital pin 8 as serial receiver

  TX – Software Serial Transmitter pin

  D13 – Use digital pin 13 as serial transmitter (default)
  D9 – Use digital pin 9 as serial transmitter

  The choice of pins 12-13 is maintained for backward compatibility with the previous hardware revisions of
  the EasyVR Shield. However those pins may also be used for the SPI interface, so another choice of pins 8-
  9 is provided. If you want to use different pins make sure the receiver pin supports change interrupts.


How can I get my LCD display to display Chinese and Japanese characters?

Displaying Kanji or Chinese characters is way beyond the ability of an LCD that displays 5 pixel by 7 pixel characters.
To understand the limitations, take a piece of graph paper and draw out a set of 5x7 rectangles. See if you can define ANY recognizable Japanese or Chinese characters on your graph paper.
Maybe a couple of characters? (Then again, maybe not.)
You need a display with a lot more resolution, like an OLED graphics display. You are also struggling against a microcontroller that doesn't have support for Unicode. It's just not up to the job. You'd be much better off with a Raspberry Pi and a screen like a smart-phone color LCD screen. Install Linux and you can have native support for Unicode.
As others have pointed out, hiragana or katakana would be more practical, and there are some low-res LCDs that support those characters.


Why am I getting only around 40% the range of my ADS1115 using an Arduino Uno?

Your readings are correct because you have the default gain set. You have incorrectly assumed that you can convert the ADC reading from your 16-bit ADC to Volts by dividing by 2^16 - 1. Your ADC has gain settings to have more accurate readings for certain voltage intervals. If we look at the example sketch, we see

 void setup(void)
{
  Serial.begin(9600);
  Serial.println("Hello!");

  Serial.println("Getting single-ended readings from AIN0..3");
  Serial.println("ADC Range: +/- 6.144V (1 bit = 3mV/ADS1015, 0.1875mV/ADS1115)");

  // The ADC input range (or gain) can be changed via the following
  // functions, but be careful never to exceed VDD +0.3V max, or to
  // exceed the upper and lower limits if you adjust the input range!
  // Setting these values incorrectly may destroy your ADC!
  //                                                                ADS1015  ADS1115
  //                                                                -------  -------
  // ads.setGain(GAIN_TWOTHIRDS);  // 2/3x gain +/- 6.144V  1 bit = 3mV      0.1875mV (default)
  // ads.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV      0.125mV
  // ads.setGain(GAIN_TWO);        // 2x gain   +/- 2.048V  1 bit = 1mV      0.0625mV
  // ads.setGain(GAIN_FOUR);       // 4x gain   +/- 1.024V  1 bit = 0.5mV    0.03125mV
  // ads.setGain(GAIN_EIGHT);      // 8x gain   +/- 0.512V  1 bit = 0.25mV   0.015625mV
  // ads.setGain(GAIN_SIXTEEN);    // 16x gain  +/- 0.256V  1 bit = 0.125mV  0.0078125mV

  ads.begin();
}

Your ADC has a default gain of 2/3, or 0.1875mV per count. You say when you connect 3.3V to the pin, you get a reading of 17625. Thus we have

17625 * 0.1875 / 1000.0 [V]
= 3.3046875 [V]

Which is a correct reading. A reading on a floating pin (nothing attached) is irrelevant. Use the correct factors from above to convert your read ADC value to voltage.

Side note: In line

avgV1=cumV1/10;

You have the float avgV1 on the left and cumV1 (a long) divided by 10 on the right; this will do a integer division. Make sure to divide by 10.0f if you want a floating point average.

Side note 2:

These factors do make sense. If you apply positive 6.144V on the 2/3rd gain setting, you will read the maximum positive value of a int16_t, i.e. 2^15-1 = 32767 (solve above formula for the count). If you apply -6.144V, you get -32768; thus the full 16-bit number space is used. On differnt gain settings it analogous.


In all practicality; put a known boot loader on it. Because if it is a problem version you will need to replace it anyways.

The Mega uses STK500 protocol. Which only shows a command to read its type (or signature) and not its version of firmware.

It is a good exercise, but not really worth the time to go deeper into it, as programmers are cheap and or you can use another Arduino as the programmer.


Dallas Temperature Sensor DS18B20 not showing correct Result with Ethernet Shield

The Solution was actually much simpler. Apparently the Ground on the voltage I/O ports wasn't the right place to connect the ground terminal of the sensor. rather The Ground of the Digital I/O should be connected. Mistake retrieved by trail and error!! Its working just fine now.


Pro Mini 5v with Adafruit motor shield v1 power sharing problems

I would check each motor without the motor shield to see if the motors are ok. Check the motor shield motor supply, should be around 12 volts with 8 AA cells. You might run a simple test program to see if the motors run full power forward and full power backward with the motor shield. Check the servo with a simple program like the Arduino Knob program. I suspect the Pro Mini 5 volt regulator is overloaded, causing the buzzing sound, but you have to find out why. One possible reason is that you are dropping from 12 volts to 5 volts via the pro mini linear regulator, creating all kinds of heat. The additional load of even a small servo might push the power dissipation spec over the edge.


It's easier to follow if you indent it properly. I'll do that, and add comments as I go:
void loop() {
    if ( Serial.available() > 0 ) { // If there is something in the serial RX buffer

        static char input[inputLength]; // Create a working string to store data in
        static uint16_t i; // This is the current index in that working string

        char c = Serial.read(); // Read the next character from serial

        if ( c != '\n') // If it's not a "line feed" character...
            input[i++] = c; // then store it in the input string and increment i

        else { // Otherwise...

            input[i] = '\0'; // Terminate the string with a NULL to make it valid C
            i = 0; // Reset the index to 0 ready for next time

            uint16_t array[80]; // Create an 80-int array (temporary)
            uint16_t j = 0; // And an index variable

            if ( !strncmp(input, "SEND", 4) ) { // If the string starts with SEND
                char* p = input + 4; // create a "pointer" to the string that starts 4 characters in

                while ( (p = strchr(p, ' ')) != NULL ) // While there is a space somewhere in the string
                    array[j++] = strtol(p, &p, 16); // convert the first portion to a number, store it in the array, and advance the pointer to the next space.

                ir_start(array); // Send the array through IR
                Serial.println("WURKS"); // Tell us it worked
            }
        }
    }
}

So you see it receives data through serial and stores it, byte by byte, in input until it receives \n at which point it looks to see if it starts with SEND, then effectively "cuts off" the SEND by only considering everything after the SEND. Then it slices the remainder of the string up by looking for the next space each time and convert each portion to an integer which it stores in an array.
It then sends that array.


Swap two arrays (using pointers, not copy)

Figured it out. Though using new works, I wanted to keep the buffers out of the heap. The following declarations work with the swap code:

uint8_t a1[10];
uint8_t a2[10];
uint8_t *array1 = a1;
uint8_t *array2 = a2;

uint8_t *tmp = array1;
array1 = array2;
array2 = tmp;


How to properly run 4 DC motors with an Arduino?

With out knowing the demands of the motors (how much current they need under a given load) it is difficult to answer your question.  But, in most Arduino designs:

Motors are powered independently of the Arduino.  And when Arduino Uno is powered through its USB port it should be realized that most common USB power sources are only obliged to offer up to 500mA of current.
The motor's power source likely needs to be capable of providing several Amps. A common 9 Volt battery only contains about 500mAh and will likely drain in 10s of minutes if it works at all.

Consider the power pack used in common portable electric power tools.  This should give you a perspective of the type of power you will need in order to create a robot with multiple motors.


Is it bad practice to multitask without timing constraints

Like often, the answer is: It depends.
Generally it is non-blocking programming, when you do only short things on each loop. What exactly can be considered short depends on the situation, meaning, what else you want to do.
For example: You are reading an analog value on every loop. The analogRead() will take about 100us (reference). I assume, that your sensor value is rather slow (so the time of signal above 150 would be rather long). Also you are reading a button with digitalRead(). The read takes about 3.6us (reference). So in total you have a loop of - lets say - 150us (with overhead and loop() iteration included). But the event, that you want to catch - the button press - will be in the ballpark of 100ms, which is a factor 667 greater, than the total time of your loop() (when no event happened). So in relation to the shortest event (the button press) all the reads can be considered non-blocking. (Though you could still get blocking through the code inside the if statements. Thats on you to investigate)
Non assume, that you don't have a button, but a digital signal, and you want to sense pulses down to 80us. Then your analogRead() would take too long and you could miss a pulse event. In this case analogRead() might be considered blocking.
So, to check if you are really using non-blocking code, you would need to ask yourself: Am I giving every code part enough time to execute right and to catch all the intended events? If yes, then you are non-blocking. If no, then you are blocking.

As a side note: Often polling is described as bad, but it really depends on the situation. In your case you poll the inputs sequentially, so every input gets polled at the same (total) rate at which your loop() runs. You are doing nothing else, so why should you lower the processing time by not use polling? The saved time cannot be used better on a microcontroller (in contrast to a PC, where the saved CPU time could be given to a different program).


MPPT using preassembled 'adjustable' buck/boost IC

No.

The switching frequency of the LM2596 is 150kHz, but the sampling frequency of the Arduino is only 10kHz (on a good day).  You won't be able to adjust the PWM quickly enough to fine-tune the LM2596 output voltage.  The LM2596 uses the 1.23V feedback voltage to change what it's doing.  But the feedback voltage will only change as fast as the Arduino can change the PWM feeding it (and that the RC smoother will allow).

It will be like pushing a shopping cart backwards, blindfolded.  By the time you feel the directional change in the cart, it will have steered off course by quite a bit.  Then you have to compensate wildly to bring it back on course.

The same would probably happen here: the LM2596 would begin adjusting the output voltage to make the feedback voltage come back towards 1.23V.  But the Arduino doesn't respond in time.  The Arduino has to do an ADC conversion, do some calculations, change the PWM, which eventually changes the RC output voltage, which is the feedback voltage.  So the LM2596 changes some more... and even more.  Eventually the feedback voltage does change, but by this time the output voltage has changed significantly.

Another way to look at is that the LM2596 is like another "processor", trying to optimize its own function, output voltage instead of MPPT.  It's running much faster than the Arduino, so there's no way the Arduino can trick the LM2596 into doing what it really wants, MPPT.


Why connect a diode between the reset pin of Arduino and 555 timer?

It's called a "Wired Or" arrangement.

The Arduino's RESET pin has a pullup resistor in it (10KΩ). That keeps the RESET pin normally HIGH. To invoke a reset that pin needs pulling low, and that is done from a number of sources:

The RESET button
The DTR pin (through a 100nF capacitor) of the USB interface chip
The 555 watchdog circuit above

The critical one there is the DTR pin.  That, because it's a brief pulse with quite a high output impedance, needs the reset pin to be easy to pull down. If you connected the output of the 555 directly to RESET it would be constantly trying to pull the RESET pin up to 5V with quite a low output impedance. The DTR circuit would have no chance of overcoming it.

So by adding a diode in there you get Wired Or, using an arrangement direct from the 1950s - DRL - Diode-Resistor Logic.  When the output of the 555 is HIGH the diode is reverse biased (or neutrally biased) and doesn't conduct, so the RESET pin's own resistor pulls the RESET pin up.  However, when the output of the 555 is LOW the diode can then conduct (it's forward biased) and that pulls the RESET pin LOW.


How do I use an Arduino as a USB output device for a 2x16 display?

HID's generally are input devices to your computer, if you do want your computer to send data to the device you will need an application to do it.

So your best bet is to have a windows app to communicate with your arduino using a virtual com port ( as it does already) and send data as you require


Can I read using an analog pin on an arduino Mega whether or not there is a high (5v) voltage on a wire from another board's digital pin?

Yes of course you can. Better to use digitalRead() than analogRead() however.

You just need to tie the grounds of the 2 Arduinos together, and set up the pin on the Arduino you want to sense the input as INPUT or INPUT_PULLUP. Then do a digitalRead on the pin. It will return LOW if the other Arduino is setting the pin LOW, and HIGH if the other Arduino is setting it HIGH.

And, as Juraj points out in their comment, CMOS devices like Arduinos respond to voltage, not current. Their inputs are capacitive. They react to a voltage potential, not current. (When you initially change a CMOS input from one state to another a small amount of current flows in to change the state of the capacitor and after that the only current that flows is a very tiny amount of leakage current through the capacitor on the input.)


After following the advice left by Majenko, I went to https://www.arduino.cc/en/Guide/Linux and followed the instuctions at the bottom of the page:

If you get an error Error opening serial port ... you need to set serial port permission.

Open Terminal and type:

ls -l /dev/ttyACM*

you will get something like:

crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).

Now we just need to add our user to the group:

sudo usermod -a -G dialout <username>

where  is your linux user name. You will need to log out and log in again for this change to take effect.


ESP8266 Nodemcu create custom PWM with 1.25us resolution

According to §1.7 (Pulse-Width Modulation) of espressif.com's ESP8266 technical reference document, “PWM frequency range is adjustable from 1000 μs to 10000 μs, i.e., between 100Hz and 1 kHz.”  That range is shown in other sections of that reference, and in other ESP8266 documents as well.  I don't know whether that range reflects any hardware limitations, or whether the PWM APIs enforce such limits or can be operated outside them.

Depending on what your intent is, you might instead consider use of UART capabilities.  For example, if you set the UART data rate to 2.5 MHz and transmit a 110110110... binary pattern synchronously, you will have 800 ns high alternating with 400 ns low.  [I've seen references to use of USARTs on ESP8266's but don't know with certainty whether synchronous protocol actually is supported.]

The I2S subsystem mentioned in §1.5 and described in §10 of the technical reference document also may be able to generate a bit stream as desired.  As noted in §10.2.1.5 one six-bit field selects an input clock prescale factor, and another six-bit field is used as the frequency divider of the communication clock signal.

Edit 1: As noted in cranphin's comments, cnlohr's esp8266ws2812i2s github page provides code that uses the I²S subsystem and DMA to drive WS2812 LED units.  Using DMA (direct memory access, ie transfer of memory data under control of a subsystem other than the CPU) means that once the CPU has set up a data buffer for a new display, it can turn actual transmission of the buffered data over to I²S / DMA and then go on with unrelated tasks while transmission occurs.  Note, cnlohr's page links to a youtube video that illustrates and briefly explains the process.


Issue with Indenting the Serial Print data in the Serial Monitor

Columns with lines?

The sprintf function can fill data with spaces to align them. However, the Arduino sprintf function does not support floating point variables. The dtostrf function has already a fixed output width by itself.
The sketch below is a combination of UTF-8 characters and the dtostrf and sprintf functions.

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

  Serial.println();
  Serial.println("┏━━━━━━┳━━━━━━━━┳━━━━━━━━┓");
  Serial.println("┃  raw ┃   °C   ┃   °F   ┃");
  Serial.println("┣━━━━━━╋━━━━━━━━╋━━━━━━━━┫");
}

void loop() {
  int raw = random(0, 1024);
  float c = random(-1000, 1000) / 10.0;
  float f = random(-500, 1500) / 10.0;

  char buffer_c[20];
  char buffer_f[20];

  dtostrf(c, 6, 1, buffer_c);
  dtostrf(f, 6, 1, buffer_f);

  char buffer[80];
  sprintf(buffer, "┃ %4d ┃ %s ┃ %s ┃", raw, buffer_c, buffer_f);
  Serial.println(buffer);

  delay(500);
}

The strlen() function can not be used before printing a floating point number to the serial port, since its length is determined while printing characters to the serial port. The final number of bytes that is written is the return value.
There is a way to use that return value, by using a dummy write to a dummy serial port. After that the number of spaces to align the floating point number can be calculated.

That reduces the code size from 6160 to 4708 for an Arduino Uno.

class DummyClass : public Stream
{
  int available() {return 0;}
  int read() {return 0;}
  int peek() {return 0;}
  void flush() {return;}
  size_t write(uint8_t) {return 1;}
  using Print::write;
};

DummyClass Dummy;

const int width_r = 4;
const int width_c = 6;
const int width_f = 6;

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

  Serial.println();
  Serial.println("┏━━━━━━┳━━━━━━━━┳━━━━━━━━┓");
  Serial.println("┃  raw ┃   °C   ┃   °F   ┃");
  Serial.println("┣━━━━━━╋━━━━━━━━╋━━━━━━━━┫");
}

void loop() {
  int raw = random(0, 1024);
  float c = random(-1000, 1000) / 10.0;
  float f = random(-500, 1500) / 10.0;

  int i;
  Serial.print("┃ ");
  Spaces(width_r - Dummy.print(raw));
  Serial.print(raw);
  Serial.print(" ┃ ");
  Spaces(width_c - Dummy.print(c,1));
  Serial.print(c,1);
  Serial.print(" ┃ ");
  Spaces(width_f - Dummy.print(f,1));
  Serial.print(f,1);
  Serial.print(" ┃");
  Serial.println();

  delay(500);
}

void Spaces(int n)
{
  for(int i=0; i<n; i++) {
    Serial.print(' ');
  }
}

I advise not to use this "Dummy" trick. It is mere a coding exercise. I can not find a problem with this trick, but I'm not 100% sure that it is okay.


Syntax for declaring more than one serial pins of Arduino mega?

If you mean the built in serial ports then just user the other objects that are pre-declared as per:

https://www.arduino.cc/en/Serial/Begin


Connecting GSM Dongle to Intel Galileo-Gen 2

Try updating the firmware. I'm not sure if this affects also ACM type serial ports, but the initial version of the firmware was not even creating standard /dev/ttySx, rather some weird proprietary interface.
Luckily this was fixed later on. So, in case you are still running the FW that the board came with, chances are you are having these weird serial ports.


How to turn two LED's on and off with one button?

Just use the return value of digitalRead (which is 1 or 0) as the input to digitalWrite:

int btnVal = digitalRead(3);
digitalWrite(4, btnVal);      // On when button is HIGH
digitalWrite(5, 1 - btnVal);  // Off when button is HIGH

Or using boolean instead:

bool btnVal = digitalRead(3);
digitalWrite(4, btnVal);      // On when button is HIGH
digitalWrite(5, !btnVal);     // Off when button is HIGH


Extend battery life with a power-controlling microcontroller?

Switching off power to the board only makes sense if you're using a full Arduino. Once you strip the Arduino down to the bare MCU and decoupling capacitors (or start with a basic breakout board instead), disabling unused peripherals and sleeping the CPU has much more of an effect since you no longer need to supply power to an external monitor chip.

Naturally this may involve creating your own board for the MCU. Fortunately Atmel has the basics of that covered.


Arduino mini, and atmega328 in general use less than 10mA with default arduino code. Turning down unused component (ADC and so on), using deep sleep and optimizing pbc would lover this consumption a lot, in the land of uA


Rechargeable USB "AA" Batteries. Has anyone used them?

Those "batteries" are actually a 3.7V¹ ~750mAh Lithium rechargeable cell with a 1.5V switching regulator and 5V charge circuit built in.

In about the same space as one of those, if you throw away the charge circuit and switching regulator, you can get a single 18650 Lithium rechargeable cell at 3.7V¹ (nominal) and three times the capacity. Two of those plus a small 5V switching regulator² would give you more power capacity and longer run time in a smaller space than the equivalent voltage of these strange "batteries".

¹ Nominal

² Use a good one with a Li-Ion battery protection circuit and maybe a built in 2S charger too for convenience


Wrong documentation for Mega2560 SPI Pins?

The image is incorrect, unfortunately.
The SPI pins are below:
PB0 - #SS
PB1 - SCK
PB2 - MOSI
PB3 - MISO


How to write a script if water sensor comes into contact with water for more than 2 mins and LED lights up

Should the LED be latched (stay on forever, once it's on), or go out if the sensor later detects no water? I'll assume the latter. Here's an (untested) state machine that should give you a good start. It keeps track of whether water was already seen, when it started, and whether it is seen now. There is some redundant switching of the LED; removing that (if desired) "is left as an exercise for the reader".

#define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
#define led 4                      //Grove LED to Digital Pin 4

#define TWOMIN (2*60*1000L)

bool isWater, wasWater = false;    // true => currently/were seeing water
uint32_t WaterStart_ms = 0;        // time first saw water

void setup() {
  pinMode(watersensor, INPUT_PULLUP);  // pullup for testing w/a button
  pinMode(led, OUTPUT);
}

void loop()
{
  // Is there water?
  isWater = !digitalRead(watersensor);     // read sensor

  if ( isWater ) {
    if ( !wasWater ){
      // First water: note the time
      WaterStart_ms = millis();
      wasWater = true;
    }
    else {
      // Water continues; time to light LED?
      if ( (millis() - WaterStart_ms) >= TWOMIN )
        digitalWrite(led, HIGH);
    }
  }
  else {
    // No water; LED off
    wasWater = false;
    digitalWrite(led, LOW);
  }
  delay(300);
}

Update:

Added wasWater = true; at line 27. The delay(300) at line 40 isn't necessary. Ran correctly when I tested it with a button (also negative logic) for the sensor.

  the light lights up randomly.

See if your sensor gives solid responses (try printing its output in loop() ). If it dithers around transitions, you may need to wait for some number of readings in a row that are opposite to the previous sensor state before you accept its new state as real.


RFID system for proximity detection with data logging

Consider using two basic XXMhz transceivers:

-Master loops through used ID's and transmits them one at a time.
-If a belt receives an ID other than it's own, it remains quiet.
-If a belt receives it's own ID, it transmits "Marco" (quietly) to the other belts.
-For a receiver to hear the very quiet signal, it will need to be very close.
-The RSSI signal can be monitored for signal strength to determine close(enough) proximity.
-If sufficient proximity is detected, the event is reported to the Master.
-If it receives no response, it informs the Master.
-Master proceeds to the next ID.

In this setup, you only need to provide networking (WiFi/Ethernet) to the master. (cheaper)

So that each belt can identify the others, "Marco" could be the transmitter's ID, but you'll need to add some sort of "protocol" so the belts know if the ID they hear is from the Master or another belt.

If ID is only 7 bits, the "protocol" could be as simple as a bitmask:

Server = Send(ID &  (1 << 7)); //1XXXXXXX
  Belt = Send(ID & ~(1 << 7)); //0XXXXXXX

Belts only reply to their ID if MSB is 1

This example has excessive range for your purpose (250m); these radios will be screaming at each other and the RSSI signal is unlikely to provide meaningful data.
http://www.seeedstudio.com/depot/nRF24L01Module-p-1394.html

Using RFID, you are wanting (very)long range from an (intentionally) short-ranged system.
Using ISM, you are wanting (very)short range from an (intentionally) long-ranged system.

Neither is 100%, but both should work.


Can the TimedAction library be used to call functions of an object

You can't. The TimedAction class doesn't support the function prototype required for your undefined class (it has to match your class, so can't be written).

You have to call a normal function which then calls the class function, or you have to have your class function as static so it doesn't include the class in the function prototype.

class foo {
    public:
        static void runMe() {
            // blah blah
        }
};

TimedAction funtionTimed = TimedAction(1000, foo::runMe);

However, TimedAction is pretty simplistic and you don't really need it.  You can just write a function to only run every so often:

class foo {
    private:
        uint32_t _runMeTimestamp;
    public:
        void runMe() {
            if (millis() - _runMeTimestamp < 1000) return;
            _runMeTimestamp = millis();
            // blah blah
        }
};

foo myFoo;

void loop() {
    myFoo.runMe();
}

Those two lines of code, plus a variable to store the timestamp in, are all you need to make a function run at periodic intervals.


The ESP typically runs on 3.3 Volt, not 3.0 Volt.

Secondly, it looks like the board has a voltage regulator, all power goes through the voltage regulator. If that's the case the voltage you need to supply must be lower that the drop-out voltage of the regulator (which is typically around a volt).


Change format preferences for Arduino IDE in Linux

It happened, that my formatter.conf was in /usr/share/arduino/lib/. So I copied it to /home/<user>/.arduino15/ folder and made changes that I needed. And also:

  Copy it in the same folder of file "preferences.txt" and modify the copy. This way, you won't lose your custom formatter settings when upgrading the IDE.


Can the Arduino (Nano) bootloader be updated via itself and the Arduino IDE or is an ISP required?

On ATmega328p and similar ATmega MCUs with bootloader support, the application is not allowed to write to flash. Only code running in bootloader area of the flash memory is allowed to write to flash. Bootloader area is at the end of the flash and the beginning is set with the BOOTSZ fuses.

The write to flash page is done in two steps. First step is deleting the contents of the flash page, second step is write the new data to the flash page. In bootloader area* it is allowed to first prepare the data to temporary buffer page, then delete the flash and write the data in one step. So in theory the bootloader could overwrite itself with a function running in the last flash page. But I don't know about bootloader which would do it.

To write a bootloader an ISP programmer is necessary. Or other Arduino with the "Arduino as ISP" sketch.

*note: the read-while-write area at the end of flash has the size of the largest bootloader area possible and is not determined by BOOTSZ.


Driving servos and LEDs from a hardware PWM may help. They will maintain a steady state even if there are interrupts. They may be a little less responsive to changes if there are interrupts.

Are you doing too much when the sensor interrupts? Typically a sensor makes multiple measurements and may be filters the results. When it is ready it interrupts. In the interrupt it should do as little as possible. Typically sending a message via global to a polling function that is not running in an interrupt. For example it may set a flag and the poling function reads the result. Reading the result in the interrupt would be bad.


Help with simple gradually brighter flickering led

Before using millis() you can try to create the thruster effect with delay().

I think 40Hz update rate for the led should be enough.
The sketch starts with a random value between 5 and 15 and ends with a random value between 80 and 256.
The part in the middle that gradually increases between those values is a mathematical problem.

// Led mimic spacecraft thruster.
//
// Update rate 40Hz for the led.
// That is a delay of 25ms.

#define RATE 40  // update rate of led in Hz
const int ledPin = 9;   // it must be a PWM pin !

void setup () {
  pinMode(ledPin, OUTPUT);

  Serial.begin(9600);

  randomSeed(analogRead(A0));
}

void loop() {
  int n;

  Serial.println("10 seconds low brightness");
  n = 10*RATE;
  for(int i=0; i<n; i++) {
    analogWrite(ledPin, random(5,15));
    delay(1000/RATE);
  }

  Serial.println("5 seconds gradually brighter");
  n = 5*RATE;
  for(int i=0; i<n; i++) {
    //   random start: from 5 to 80     (75 increase)
    //   random end  : from 15 to 256   (241 increase)
    //   The calculation is with long, it might not fit in a 16 bit integer

    int random_start = 5 + int((long(i) * 75) / long(n));
    int random_end   = 15 + int((long(i) * 241) / long(n));
    analogWrite(ledPin, random(random_start,random_end));
    delay(1000/RATE);
  }

  Serial.println("10 second full thrust");
  n = 10*RATE;
  for(int i=0; i<n; i++) {
    analogWrite(ledPin, random(80,256));
    delay(1000/RATE);
  }

  analogWrite(ledPin,0);
  delay(2000);
}


Since you're using a Grove Display, I believe it will be using I2C.

For better debugging, try using the actual I2C pins on your Pro mini, which are A4 and A5.

  I2C: A4 (SDA) and A5 (SCL). Support I2C (TWI) communication using the
  Wire library.
  https://www.arduino.cc/en/Main/ArduinoBoardProMini

I2C may need pull-up resistors on your data lines.

(https://en.wikipedia.org/wiki/I%C2%B2C)

It can also be nice to use "verified to be working" code, like example code from the manufacturer.

/*
 * TM1637.cpp
 * A library for the 4 digit display
 */
#include "TM1637.h"
#define CLK 39 //pins definitions for TM1637 and can be changed to other ports
#define DIO 38
TM1637 tm1637(CLK,DIO);
void setup()
{
    tm1637.init();
    tm1637.set(BRIGHT_TYPICAL);//BRIGHT_TYPICAL = 2,BRIGHT_DARKEST = 0,BRIGHTEST = 7;
}
void loop()
{
    int8_t NumTab[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};//0~9,A,b,C,d,E,F
    int8_t ListDisp[4];
    unsigned char i = 0;
    unsigned char count = 0;
    delay(150);
    while(1)
    {
        i = count;
        count ++;
        if(count == sizeof(NumTab)) count = 0;
        for(unsigned char BitSelect = 0;BitSelect < 4;BitSelect ++)
        {
            ListDisp[BitSelect] = NumTab[i];
            i ++;
            if(i == sizeof(NumTab)) i = 0;
        }
        tm1637.display(0,ListDisp[0]);
        tm1637.display(1,ListDisp[1]);
        tm1637.display(2,ListDisp[2]);
        tm1637.display(3,ListDisp[3]);
        delay(300);
    }
}

You will need to adapt the pin numbers.

But after these steps it should work just fine.

Source: http://wiki.seeed.cc/Grove-4-Digit_Display/


I want to transmit I2C data...

A little vague.

Transmit to what device? How fast is your data rate (100kHz, 400kHz)? Your only transmitting and not reading anything back? What is the idling voltage of your I2C bus (to then ask if you have chosen correct pull-up resistor values for your intended bus speed)?

You mention that the Wire library doesn't support core clock speed changes without some hacking, but don't talk about the speed you intend to run the microcontroller or how fast you intend to use the I2C. I can guess 400kHz, since you brought up speed, but that's not a great way to answer a question.

I have using the Wire library on an Arduino UNO at I2C bus rate of 100kHz and it's worked fine for my needs. I got bytes in and out.

At this point, the best suggestion I'd have is that if one of the above libraries you listed does not support a feature you'd like, fork it, and add support for your feature yourself. If you're only transmitting to one slave device, then you shouldn't need to worry about bus arbitration, like the TinyWire does. Adafruit is okay for the most part, but they seem (to me) slow to fix bugs and maintain code. But don't let the code's age get to you. I2C was created back in 1982, and you're still using it... :-P

Here's how I would approach choosing a library:

Define features you need
Look for a library which has most of those features
Add any new features you need
Possibly share your added features with the community with a Pull Request


Based on your experience with the system and the source of the Nanos, the best and quickest test I can think of is to swap in a another Nano to find out whether if the problem remains or disappears.


Considering that you used resistors to lower the 11.5V to an cough - cough "very normal and regulated 5V", that most certainly is the problem.

The "right and cheap" way to lower such high voltage and connect them directly to your 5V (just assuming, since you said that you used resistors to protect the Arduino) is actually to use a voltage regulator. Any cheap 7805 should do the job. The Arduino actually has its own voltage regulator on it, if you connect it though the Vin pin.

The "true and efficient" way to step down some voltage is actually to use a step-down converter. The way this is better then any normal regulator is that a regulator will lower your voltage by creating heat when the step-down converter will do it in a more efficient process.

The USB of your PC might also be the problem. There is a fuse on the Arduino and one in almost all USB ports of decent PCs. If the voltage spike is high enough, it might have burned the port. That is quite a rare event, but still possible.

Need anymore help, just comment. I'll be happy to help you!


Connecting Seeeduino XIAO 3.3 V out to dual H-bridge driver module (L298N) with TTL compatible inputs

Am I correct to assume that I do not need to step-up the logic signal (from 3.3V to 5V) for this to work, but can connect straight to the input?

You are correct. The input has to be above 2.3V to register as HIGH and below 1.5V to register as LOW. You have 3.3V for HIGH and near 0V for LOW, which fits those criteria perfectly.


To my knowledge, there is not a "python to ATMega architecture" compiler out there.

However, it's not true that MicroPython only runs on PyBoard. There are versions for installation also on the ESP8266 and ESP32 chips, and so the popular NodeMCU and Wemos D1 development boards, or any of the other similar products with those processors, can easily run Python code. Many of these are available at a very low cost from the usual retailers/sources.

Be aware that MicroPython is somewhat limited compared to the full version due to the limited RAM available on these boards.


Rotate Robot head according to Sound level

A couple of years ago, I completed a MOOC on FUN called Binaural Hearing for Robots (it doesn't seem to have run since, but it may be worth keeping an eye on it to see if they open registration again. At least some of the resources seem to be archived here). Interestingly, localising sound turns out to be easier with three microphones than with two.

You scan the three inputs in sequence, and when the sound is directed to record the time-difference between the three sensors. The technique you're looking at to localise the source is called trilateration.

Once you have a direction relative to the robot head, you can use a simple servo to turn the robot head to that direction.

I did play around with this a little bit, using three KY-038 microphone modules like this that I picked up cheap on eBay:

Connect them to your Arduino something like this:

I can't find my code (it was pretty untidy anyway since I was just playing around while I was working on the course), but a lot of Arduino sound-localisation projects have been published online with examples easy to find on Instructables, Hackaday, and many other sites.


The odd voltages might suggest that the servo isn't actually (fully) connected to the Arduino. As it's a diagram of the breadboard layout, not a photo, I can't say for sure, but on some breadboards the +ve/red and -ve/black rows are sometimes split in the middle. i.e. if you were to connect the Arduino's +5v to one end of the breadboards red row, and the servo to the other end, they might not be joined (same applies for -ve/black). Just a thought; apologises in advance if I’m stating the obvious.


Servo8Bit and ATTiny13(A)
I had a look at the Servo8Bit and had pretty much the same thoughts on this as Edgar Bonet in his comment:

Servo8Bit relies on an 8-bit timer, and the ATtiny13A does have an
8-bit timer. It should not be too hard to port this library to that
micro. Study the source code, then study the datasheet of the tiny13A
(mostly the chapter dedicated to the timer). You should then be able
to easily see what changes are needed.

Ignoring the timing differences between the ATTinyx5 and ATTiny13(A), I just went ahead and saw if I could get it to compile.  And yeah, it's pretty easy to compile.  This mostly consists of adding 0 to some hardware register names.  The bad news is:

Sketch uses 1486 bytes (145%) of program storage space. Maximum is 1024 bytes.
Global variables use 31 bytes (48%) of dynamic memory, leaving 33 bytes for
local variables. Maximum is 64 bytes.
Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it.
Error during build: text section exceeds available space in board

So, yeah, that was a bit much to hope for, I guess.  The library does use ISRs to support a number of servos kind of like the more common servo library that you'd use on an UNO.  I haven't looked into chopping it down to size; I expect that will be impractical.
PWM... sort of.
Prior to considering modifying Servo8Bit, I kind of thought it made sense to just use the timer counter directly to produce a waveform.  The problem is the conventional servo signal is 20ms long, and does all of its control in a 1ms window.  If you try to fit the whole 20ms frame into a single 8bit timing interval, what you end up with is pretty crappy angular control.  So, doing it is a bit painful without a 16-bit timer counter.  But, I guess that's the game.
So, the below is a crude and barely tested attempt at it.  The code that follows is state machine inside the OCR0B overflow vector that schedules the rising an falling edges is "normal" mode.  Just to warn you, I don't actually have an ATTiny13(A) on hand.  And in fact I don't happen to have a servo hand either.  But I do have an ancient storage scope and an ATTiny85 and the ability to compile for ATTiny13(A), and a calculator for working out the 8 MHz vs 9.6 MHz difference.
So here's what I came up with, which I think (but don't know) will work if you compile and upload using MCUDude MicroCore, ATTiny13(A) with the 9.6 MHz internal oscillator chosen.
It's only designed to operate 1 servo.  Extending it to two should be easily doable.  Going beyond that you're likely run into problems.
Code:
// +---------------------------------------------------------------------------------------+
// |                                                                                |
// |                                 +-------------+                                       |
// |                                 |             |                                       |
// |                                 |      A      |                                       |
// |  PCINT5 ADC0 dW  /RESET  PB5 *--|-1    T    8-|--* VCC                                |
// |                                 |      T      |                                       |
// |  PCINT3 ADC3      CLKI   PB3 *--|-2    I    7-|--* PB2  SCK   ADC1 T0         PCINT2  |
// |                                 |      N      |                                       |
// |  PCINT4 ADC2             PB4 *--|-3    Y    6-|--* PB1  MISO  AIN1 OC0B  INT0 PCINT1  |
// |                                 |      1      |                                       |
// |                          GND *--|-4    3    5-|--* PB0  MOSI  AIN0 OC0A       PCINT0  |
// |                                 |      A      |                                       |
// |                                 |             |                                       |
// |                                 +-------------+                                       |
// |                                                                                |
// +---------------------------------------------------------------------------------------+

#if !defined(__AVR_ATtiny13__) && !defined(__AVR_ATtiny13A__)
#error This code is written specifically for ATTiny13(A) devices.
#endif

#if F_CPU != 9600000
#error  This code is written specifically for 9.6 MHz
#endif

//
//
//
#include <avr/io.h>
#include <avr/interrupt.h>

//
//
//
constexpr uint8_t TCCR0A_config(
  int com0b // two bits
) {
  return
      (    0 << COM0A1) // normal
    | (    0 << COM0A0) //   port operation
    | (com0b << COM0B0) // bits 5 AND 4
    | (    0 <<      3) // reserved
    | (    0 <<      2) // reserved
    | (    0 <<  WGM01) //  lower two bits
    | (    0 <<  WGM00);//     of Normal (mode 0);
}

//
//
//
constexpr uint8_t TCCR0A_config_for_go_low()  {return TCCR0A_config(0x2);}
constexpr uint8_t TCCR0A_config_for_go_high() {return TCCR0A_config(0x3);}

//
// 50 Hz (hobby servo frame frequency); period 20 ms
//
// In the below you'll see the numbers 150 and 300 and 3000.
// The reason for these numbers is that I've chosen to to use a /64
// timer prescaler.  At 9.6 MHz, with a /64 prescaler, 1 millisecond
// is 150 timer timer counts.  There's as fixed 1 MS high in the servo,
// followed by 0 to 1ms variable portion.  The number 150 helpfully
// fits within the 8-bit timer registers and also gives a reasonable
// number of increments to the servo control.  For 180 degrees, 150 increments
// is 1.2 degrees.
//
// The maximum high time is the fixed 1ms high time and the maximum
// variable high time, totalling 2 MS, or 300 timer ticks, that's what that
// number is about.
//
// 3000 is the number of timer ticks for a full 20ms signal frame,
// that is 20 * 150 = 3000.
//
//
// Deriving the 150 figure:
//
//  At 9.6 MHz and /64 prescaler
//
//        1 second         64 mcu_cycles   A_MS_DURATION timer_counts
//  -------------------- X ------------- X ---------------
//  9_600_000 mcu_cycles   1 timer_count    0.001 seconds
//
//
//       1      64    A_MS_DURATION
//  --------- X -- X  -----
//  9_600_000   1     0.001
//
//
//     64       A_MS_DURATION
//  --------- X -----------
//  9_600_000      0.001
//
//
//     64 x A_MS_DURATION
//  --------------------
//        9_600
//
//
//  A_MS_DURATION
//  -------------
//      150
//

static constexpr uint8_t  ONE_MS_WORTH_OF_TICKS    = 150;
static constexpr uint8_t  MAXIMUM_HIGH_PERIOD      = ONE_MS_WORTH_OF_TICKS * 2;
static constexpr uint16_t TWENTY_MS_WORTH_OF_TICKS = 3000;
static constexpr uint16_t MAX_WASTE_CYCLES         = 0x80;

static volatile uint8_t g_pulse_width = ONE_MS_WORTH_OF_TICKS / 2;  // default to mid-range.

ISR(TIM0_COMPB_vect) {
  static uint8_t l_pulse_width; // this caches g_pulse_width
                                // and is updated from g_pulse_width
                                // only between frames

  //
  // The ISR is a state machine with four macro states.
  //
  enum class t_signal_generator_state : uint8_t {
    timing_to_variable_high_period,
    timing_to_set_pulse_width,
    calculate_time_to_start_of_next_pulse_and_waste_a_bit,
    timing_to_start_of_pulse
  };

  //
  // Macro state variable
  //
  static t_signal_generator_state g_signal_generator_state =
    t_signal_generator_state::timing_to_variable_high_period;

  // low_time_remaining is an extended state variable
  // for the timing_to_start_of_pulse state
  static uint16_t low_time_remaining;

  switch (g_signal_generator_state) {
    case t_signal_generator_state::timing_to_variable_high_period:
      // We just went high at the OCR0B value that triggered this interrupt
      // and we need to retrigger ((MAXIMUM_HIGH_PERIOD==300) - 256 == 44)
      // timing cycles later such that there are 256 timing cycles left of the
      // 2ms (maximum) high part of the frame.
      OCR0B += (MAXIMUM_HIGH_PERIOD - 256);  // 2ms worth of timer nicks minus the resolution of our timer

      // We're remaining HIGH as we head into the variable portion of the HIGH period.
      g_signal_generator_state = t_signal_generator_state::timing_to_set_pulse_width;
      break;
    case t_signal_generator_state::timing_to_set_pulse_width:
      // We're retrieving the global variable which holds a (potentially new) value from 0 to 150
      // representing a span of 0ms to  1ms (the full range of the servo), but
      // we're starting out the variable pulse a head of time, part way through the always-on first ms.
      // There are (150 - 44) timer cycles, that's 1 ms worth of timer cycles
      // where the timer remains high to finish out first millisecond of HIGH.
      // So we add this to the requested variale pulse width time.
      l_pulse_width = g_pulse_width + (ONE_MS_WORTH_OF_TICKS - 44);

      // Set adjust pulse width
      OCR0B += l_pulse_width;

      // We'll be going low and the end of the variable high period.
      TCCR0A = TCCR0A_config_for_go_low();

      g_signal_generator_state = t_signal_generator_state::calculate_time_to_start_of_next_pulse_and_waste_a_bit;
      break;

    case t_signal_generator_state::calculate_time_to_start_of_next_pulse_and_waste_a_bit:
      // We just went low at the OCR0B value.

      // Calculate remaining timer cycles to the beginning of the next pulse
      // accounting for the MAX_WASTE_CYCLES we're about to waste in this state.
      low_time_remaining = (TWENTY_MS_WORTH_OF_TICKS - 44 - MAX_WASTE_CYCLES) - l_pulse_width;
      OCR0B += MAX_WASTE_CYCLES;

      // We will remain LOW since the pulse is done and we've not finished out the 20ms period
      g_signal_generator_state = t_signal_generator_state::timing_to_start_of_pulse;
      break;

  case t_signal_generator_state::timing_to_start_of_pulse:
      // Continue retriggering the timer until we've used up 20ms total,
      // in increments of not more than MAX_WASTE_CYCLES.

      if (low_time_remaining > MAX_WASTE_CYCLES) {
        low_time_remaining -= MAX_WASTE_CYCLES;
        OCR0B += MAX_WASTE_CYCLES;
        // We'll need to wast more, so we're remaining LOW.
      } else {
        OCR0B += low_time_remaining;
        low_time_remaining = 0;

        // This is out last round through this state to finish out the 20ms
        // window, so we'll be returning to HIGH.
        TCCR0A = TCCR0A_config_for_go_high();

        g_signal_generator_state = t_signal_generator_state::timing_to_variable_high_period;
      }
      break;
  }
}

//
//
//
void servo_init() {
  const auto SREG_saved = SREG; cli();

  DDRB |= 1U << 1;  // Servo data pin attached on Attiny PB1 aka (OCR0B)

  // select no clock source / stop counter
  TCCR0B &= ~(
      (1U << CS02)
    | (1U << CS01)
    | (1U << CS00)
  );

  // reset counter
  TCNT0 = 0x00;
  OCR0B = 0x80;

  TIMSK0 =
      (0 <<      7) // reserved
    | (0 <<      6) // reserved
    | (0 <<      5) // reserved
    | (0 <<      4) // reserved
    | (1 << OCIE0B) // we *ARE*  using output-compare B interrupt
    | (0 << OCIE0A) // we aren't using output compare A interrupt
    | (0 <<  TOIE0) //             nor overflow interrupt
    | (0 <<      0);// reserved

  TIFR0 = 1U << OCF0A;

  TCCR0A = TCCR0A_config_for_go_high();

  TCCR0B =
      (0 << FOC0A) // We're not doing any
    | (0 << FOC0B) //   output compare forcing.
    | (0 <<     5) // Reserved.
    | (0 <<     4) // Reserved.
    | (0 << WGM02) // High order bit of Normal mode (0)
    | (0 <<  CS02) // Clock source
    | (1 <<  CS01) //    prescaled
    | (1 <<  CS00);//      by 64.

  SREG = SREG_saved;
}

//
//
//
void setup() {
  servo_init();
}

//
//
//
void loop() {
  for (g_pulse_width = 0; g_pulse_width < 150; ++g_pulse_width) {
    __builtin_avr_delay_cycles(F_CPU >> 5);
  }
  for (; g_pulse_width > 0; --g_pulse_width) {
    __builtin_avr_delay_cycles(F_CPU >> 5);
  }
}

//  vim:sw=2:ts=2:et:nowrap:ft=cpp:

On the scope, this produces servo signal that should sweep a servo on pin OCR0B (PB1).  Something like 4 to 5 seconds going one way and same going back.
If I put an ATTiny13A on an order sometime and manage to dig out a servo myself, I'll actually test it.  It may be a very long time before I can do that though.  But the results on the scope look good.  Admittedly everything is scaled by 9.6/8.0.  It should be accurate on a ATTiny13(A).  I verified that it compiles for it.  The workings of the thing are explained in the code as I can.
For comparison:

Sketch uses 490 bytes (47%) of program storage space. Maximum is 1024 bytes.
Global variables use 10 bytes (15%) of dynamic memory, leaving 54 bytes for local variables. Maximum is 64 bytes.

That's still a good chunk of what little code space you have, but it should be enough to read a switch and potentiometer.  This is using the timer the device has, so millis()/delay() usage are kind of out-the-window, I think, I didn't try to see what happen when you call them or study their code in MicroCore.  You could recreate your own millis() by making a timer overflow interrupt and it would overflow at about 1.7 ms intervals.  As you can see, I just used __builtin_avr_delay_cycles to keep things simple.
If you, or anyone else, gets it working on at ATTiny13 before I try it myself, I'm curious to know that it worked (or didn't).


Adafruit Micro-SD breakout not initializing on MEGA 2560

The non-analog ground line attached to the micro-SD was pulling down my voltage. Just hardwired to different ground and problem solved! (Check your voltages).
From what I could gather. the ground pin on the MEGA inline with the digital pins was a different ground source (digital ground). I literally took the ground lead from the SD board and just touched it to the housing of the USB connector on the MEGA and my voltage came back.


Arduino Mega: which Digital pins are already used for something?

Don't worry about the led on pin 13, it just sits there but doesn't block anything.

You can still use the pin as a normal IO pin.

You didn't mention whether your 30 inputs are digital or analog, so let's have a look at digital input first.

I have never used the MCP23017 mentioned by Martynas, but the linked article looks very interesting and I'll definitely order one of these amazing chips!

Another option might be using 8 bit PISO (parallel in - serial out shift registers, such as the 74HC165. Consider this as the complement to the 75HC595 for output. These shift registers are dirt cheap (around 0.3 €), are available as DIP (important for breadboarding) and can be run via SPI.

Advantages:

it's fast to read in 8 digital lines into a byte (why would one want to use more than a bit for the state of a digital input?)
the shift registers can be daisychained, subsequent calls of ShiftIn allows to read all (digital) input states into a corresponding data structure (array of bytes, etc.) using just three pins on your Arduino.


How to add additional millisecond delay to microsecond delay generator

You could count timer compare matches.  The following illustrates the principle, maybe not accurate as written but I am sure the counter loop will be precise enough for your needs, considering you want to use an Arduino.  Depending on the time resolution you want, you may be able to run other code while the software counter is active.

The following can count to several seconds, depending on values of OCR1A and counter_target.

unsigned int state, pulse_delay;
byte counter[3]={0,0,0}; // 24 bit counter, you can make it longer in principle

byte counter_target[3]={0,0,0}; // defines length of delay you want

void setup(){
state=0;
TCCR1A=0;
TCCR1B=0;
}

void loop(){
switch (state){
case 0: // idle state machine // you other code here
counter_target[0]=0; // For example
counter_target[1]=0;
counter_target[2]=1; // corresponds to (1+65536)*pulse_delay/clock_scaler
// when you are ready to start counting
state=1;
break;

case 1: // setup timer
counter[0]=0; // Zero the 24-bit counter
counter[1]=0;
counter[2]=0;
OCR1A = pulse_delay; // number of pulses to count = 1+OCR1A
OCR1B = OCR1A+1;
ICR1  = OCR1A+1;    // Just to make sure these don't cause compare match
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
state=2;
TCCR1A = B00000011; // Fast PWM mode 15 on UNO, OCR1A=TOP
TCCR1B = B00011001; // Clock prescaler 1
break;

case 2: // Counting up
loop_until_bit_is_set(TIFR1,OCF1A);
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
counter[0]+=1; // Increment counter by 1
if(counter[0]==0x00){counter[1]+=1;
if(counter[1]==0x00){counter[2]+=1;}} // etc

if(counter[0]==counter_target[0] && counter[1]==counter_target[1] && counter[2]==counter_target[2]){state=0;}  // Check if we have reached the target delay
break;

}
}


What are a few good ways to connect multiple I2C busses?

In an ideal world you would have your other sensor on a separate I2C bus. It can be done with software, but chances are you will have to re-write the library that supports it to use bit-banged I2C.
Yes, you could use an I2C MUX to share the single hardware I2C channel, however that will both be awkward and the results will be sub-optimal anyway.
Most I2C MUX chips, including the TCA9543A, are controlled themselves by I2C, so you can't really use them in your environment, since you really need to switch it to isolate your main bus from the MCU before you switch it from slave to master, which you can't do until after you have switched it from slave to master. If you switch to master before isolating the bus you risk a collision with the main master on the bus and everything going horribly wrong.
These MUX chips are really designed for allowing one master to talk to multiple slaves that share the same addresses.
And on top of that when you've isolated the bus the main master will no longer be able to communicate with that slave board, which will either cause the whole bus to lock up or other strange and unwanted things to happen.
So have another go at using software I2C to communicate with your sensor. Most I2C communication to sensors is pretty straightforward and follows the same rough format, so it really shouldn't be too hard to implement.
Either that or consider replacing the ATMega328P with a more capable microcontroller that has multiple I2C busses.


How to Create a reference to an External Print object

If your class is only writing to the stream you probably want to have your class take a Print object instead of a Stream object.

The Adafruit library inherits from Print.


Oil Pressure / Water Pressure / Boost Pressure ( Turbo Engine )

You math checks you to me.

When you code it, You will probably read a voltage using an analog pin (or external ADC) that will return an integer between 0 being 0 volts, and 1024 = vin volts. vin will be 5 if you don't wire up the vin pin, and 1024 could be different if you use an external ADC.

Anyway you should be aware that the raw readings will probably not be 0-5, and they dont have decimal points. You will need to first convert the reading into the voltage with something like this:

float voltage = ((float)reading)/1024.f;

notice that the datatype float is used (enables decimal points) and that the constant being divided by is also a float so that the calculations will definitly happen between floating point numbers.


Yes. As long as it connects the the arduino clone via USB and can maintain a stable power output then it's suitable.


Does ATmega328 on Uno need to be burned?

If you bought an Arduino Uno the bootloader comes pre-programmed.

"The ATmega328 on the Uno comes preprogrammed with a bootloader that allows you to upload new code to it without the use of an external hardware programmer. It communicates using the original STK500 protocol (reference, C header files)." - from the oficial page.

Might want to take a look at this discussion if you're confused.


Arduino Uno + Ardumoto + BT robot works from USB but not from baterries

Are you powering the motors with a separate supply, and not direct from the Arduino? Motors should be powered separately and the power only switched by the Arduino. Otherwise, their current draw could be pulling down your battery voltage. And even with USB power, they could be drawing more current than spec'd for either the USB power source or the Arduino's regulator or output pins. The chip itself is spec'd for a maximum current of 40mA per pin and 200mA total.


Arduino Uno board works but Arduino Uno + Wifi is not being detected

What you have there is a cheap Chinese clone. It uses the cheap CH340G USB chip instead of the proper ATMega16u2 that real Arduinos use.

Install the right drivers and it should start working.


Error on UNOr3--> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory ioctl("TIOCMGET"): Inappropriate ioctl for device

This could be any number of different problems.  Here are several common causes:

You have multiple USB serial port devices connected to your computer. Try using the command ls -l /dev/ttyUSB* to check if your computer thinks there are more than one terminal USB device.  Disconnect all of them, then only connect the Arduino Uno.  Then repeat the check.
You do not have permissions.  This is tricky to check as Linux offers a flexible but complicated root, group and user permission paradigm.  You should NOT make a habit of this, but, for a quick check, you can try running the Arduino application as root and check if you can upload a sketch to the Arduino Uno.
You have a counterfeit FTDI chip on your Arduino Uno that has been rendered useless by certain versions of the Windows FTDI Driver.  The USB IDs can get reset to useless values.  I believe the current FTDI Windows Driver no longer does this.
You did not install the Linux FTDI driver.  A driver is a program to abstract the hardware from the application.  In this way, different hardware can be treated the same by the application, simplifying the application.  However, the wrong driver/hardware combination may not work as expected.


Arduino Serial Monitor only returning Null Characters

First, change all Serial.write to Serial.print I think that might be half your problem.

Next,

  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);

The way you are doing this will probably put the HC-05 into 9600 baud mode. You can fix this one of two ways:

Change BTSerial.begin(38400); to BTSerial.begin(9600);

Or, as jfpoilpret suggested, tie the Key pin directly to VCC.  The reason is that in order to go into 38400 baud mode, there must be voltage on Key at the time the module is powered up.  By the time the digital write in your code happens, it's too late.

If for some reason you'd like to have digital control over the Key pin rather than directly wiring it to VCC, yet you'd like the module to operate at 38400 baud, you can simply change the default baud rate by issuing the appropriate AT command - I believe it's AT+UART= off the top of my head.

Also, I'm not sure, but jfpoilpret might be right as well about how your serial read/write handling is done within loop() but here is code that I know works:

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX
char myChar;

void setup()
{
  ...
}

void loop() {
  while (BTSerial.available()) {
    myChar = BTSerial.read();
    Serial.print(myChar);
  }

  while (Serial.available()) {
    myChar = Serial.read();
    Serial.print(myChar); //echo
    BTSerial.print(myChar);
  }
}


Play sound with speaker inside interrupt while a timer runs

Andrew,

I think I see what you're trying to accomplish. I would try something like the following, and I'll explain afterward:

boolean timerRunning = false;
unsigned long start_millis;
unsigned long end_millis;

boolean tripped() //was int Start()
{
  dist = echo1();
  if (dist < 25 && dist > 0) {
    return true;
  else
    return false;
}

void loop()
{
  if(tripped())  //check for < 25cm
  {
    //if tripped and timer not running, start
    //keeping track of time
    if(!timerRunning)
    {
      timerRunning = true;
      start_millis = millis();
      end_millis = start_millis + half_hour;
    }
    //if timer already running, print millis
    else
    {
      Serial.println(millis()); //or Serial.pringln(millis()-start_millis);
                    // for time since timer started
    }
  }
  else  //not < 25cm, not tripped
  {
    //if not tripped and timer running, time for sound
    if(timerRunning)
    {
      timerRunning = false; //might as well stop timer
      alert();
    }
    //if timer not started and not tripped nothing to do
  }

  //finally, lets check time, if past half hour, stop tracking
  //elapsed time
  if(timerRunning)
  {
    if(millis > end_millis)
    {
      timerRunning = false;
    }
  }
}//end void loop()

In general, you don't want to block the loop() from looping. Some of the Arduino functions do their processing outside that loop (the interrupt pin possibly too).

I know I'm not using the interrupt, but for a couple reasons. First, it looks like the pin can only change if you call your echo1() function, as you have to trigger the ultrasonic transmitter. Secondly, the state of the pin will not reflect the distance, only that it's receiving sound. As an aside, for what it looks like you were trying to do, you would have wanted to attach the interrupt and detach the interrupt only when the timer started or ended, as opposed to in the setup. Otherwise it could interrupt at any time, such as everytime the echo1() was called.

Hopefully my code comments help explain the flow. Basically I'm keeping track of the state of things, mostly with 'timerRunning'. Based on whether the timer is running and the ultrasonics are tripped (measuring less than 25cm), the appropriate actions are taken. The only way to stop the timer is the elapsing of half an hour, or the alert condition.

Double check my math, but i think there are 1,800,000 milliseconds in half an hour, so you will want to change your constant. Also, I don't know how long you plan on having your device run, but the millis() function will rollover back to 0 after about 50 days. Your end time will end up calculating out to less than the current time and the timer will not be able to run properly (will immediately stop) for that last half hour until rollover. Just something to keep in mind.

Hope this helps and good luck!


Error "avr-g++: error: CreateProcess: No such file or directory" When Compiling Script

Turns out that McAfee's Host Intrusion Prevention had decided to start blocking avr-g++.exe. Not sure why it did so all of a sudden, but it's an easy fix once you know where to look. Anyone finding this in the future should be sure to check their antivirus logs to see if the compiler's executable is being blocked.


Why to store a function parameter value in a class private variable?

The reason is that _Display will be used probably after its construction.

So you pass the byte during construction, and afterwards the value is available during the object's lifetime.

In C you probably will do this by:

Passing the variable (byte DisplayType) in each function where the value is needed (you can use this way in C++ too but it's cumbersome in both C/C++ to pass the variable in all functions needed).
Storing it in a global variable (static for that .c file); this is the typically C method.

* Added explanation *

Such a variable is called class variables and are mostly made private. The reason is that other objects cannot change the value directly. The only way to change a variable is:

By initializing it in the class constructor (like in your example).
Within the class itself (by any method).
By a typical Set method (like SetDisplayType). This method can check if the value passed is within a range, and there is only one entry point in this class to change it.

To retrieve the value, typically a GetDisplayType method should be created which is public. The variable itself is private.


How do I combine a variable and characters into a string with Arduino?

You're thinking backwards. Instead of building up one string and comparing it to another, you should instead be splitting down the string you are being sent and dealing with the different parts of it separately.

Say you are being sent the string 32,read\r. Instead of making another string 32,read\r and comparing it to what you have received you should instead be splitting the incoming string up.

That way you then have a string containing 32 which can be converted to an integer, and a string containing read. It now becomes very simple to do your comparisons without messing with building strings in RAM wasting precious memory.


Create New Serial Class Inheriting from Stream

The Stream class has pure virtual methods which must be implemented in derived not abstract class.

The pure virtual method from base class Print is:

virtual size_t write(uint8_t) = 0;

The pure virtual methods from Stream are:

virtual int available() = 0;
virtual int read() = 0;
virtual int peek() = 0;

additionally add in your class the line

using Print::write;

to pull in overloaded methods write(str) and write(buf, size) fromPrint

Here I have an example of a simple class derived from Stream.

EDIT: Most of your question seemed to focus on wrapping some Stream implementation. Now I see that you maybe want to enhance the SoftwareSerial class and add a new method in the inherited class. It is simple:

MySerial.h

#ifndef _MYSERIAL_H_
#define _MYSERIAL_H_

#include <SoftwareSerial.h>

class MySerial: public SoftwareSerial {
private:
  int param;

public:

  MySerial(uint8_t receivePin, uint8_t transmitPin) :
      SoftwareSerial(receivePin, transmitPin, false) {
    param = 0;
  }

  void resend(char c) {
    write(c);
  }
};
#endif

MySerial.ino

#include "MySerial.h"

MySerial mySerial(6, 7);

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

void loop() {
  if (mySerial.available()) {
    int c = mySerial.read();
    mySerial.resend(c);
  }
}


ESP8266 Blink sketch - does not blink / or stays constant

You should connect Vcc to 3.3V, because that's how the ESP8266 is powered.
RST is active-low reset and should be pulled to 3.3V


Consider copying the Arduino Uno reference design.  This is part of that schematic showing the MOSFET used to turn on / off the USB power when the barrel jack power source is active:


Pass Color to a function without using a specific Adafruit_NeoPixel

Looking at the library at https://github.com/adafruit/Adafruit_NeoPixel/blob/master/Adafruit_NeoPixel.h, you can see that the Color method is static (see line 307):
static uint32_t   Color(uint8_t r, uint8_t g, uint8_t b) {
  return ((uint32_t)r << 16) | ((uint32_t)g <<  8) | b;

This means instead of
strip[0].Color( 0, 255, 0)

You can use:
Adafruit_NeoPixel::Color( 0, 255, 0)

Your call to everyother will be:
everyother(Adafruit_NeoPixel::Color( 0, 255, 0),
           Adafruit_NeoPixel::Color( 255, 0, 0),
           500);

And since everyother is now not a good name, you can think of a better one, e.g. fillLeds (always start a method name with a verb).
Offtopic:

A subroutine is barely used anymore, I think the last time I heard it, is from the Basic programming language
A function is now used instead
But when a function is inside a class, it's not called a function, but called method.


Trouble reading from multiple analog ports

Case 2 is missing the ~ and does not clear off the low 4 bits

  ADMUX &= 0b00001111;

should be this to clear off the MUX selection bits:

ADMUX &= ~0b00001111;

Also, you have no default case.  I would agree that by design the bits can only contain the values 0-3, but what happens if it ends up 4?

The bit manipulation is hard to follow.  I would implement like this:

ISR(ADC_vect) {
  uint8_t nextMux;

  //Save current conversion's ADC value
  analogpin = ADMUX & 0b00001111;
  switch (analogpin) {
    case 0:
      TPA = ADCW;
      nextMux = (1<<MUX0);
      break;
    case 1:
      TPB = ADCW;
      nextMux = (1<<MUX1);
      break;
    case 2:
      TPSA = ADCW;
      nextMux = (1<<MUX0)|(1<<MUX1);
      break;
    case 3:
      TPSB = ADCW;
    default:
      nextMux = 0;
  }
  // set mux for next conversion
  ADMUX &= 0b11110000;
  ADMUX |= nextMux;

  //Start next conversion
  ADCSRA |= (1<<ADSC);

  return;
}

I like the consistent pattern of this because it makes errors easy to see.  With respect to code space, a few bytes should be saved.  Execution time wise, it adds one |= to the case 3.


Three or more Arduino slaves sending bytes to 2 different I2C devices

As soon as an Arduino starts writing data, it is a Master. Do you use Arduino Mega 2560 and Arduino Uno and Nano boards ? In theory those ATmega microcontrollers can handle collisions in a multi-Master bus, and in theory the Wire library handles collisions as well. However, everyone tries to avoid that, because it causes a lot of problems. You would even have to program a complete new layer in the code to re-transmit data until it was received without collision.

Select one Arduino board as Master, and use the Master to read and write data. If you want to transfer data from one Slave to the other Slave, then use Master to read the data from one Slave and write the data to the other Slave.

It is possible to use other busses between the two Slave Arduino boards.


How to pulse a signal at 100ms to 500ms?

Okay, so pulsing is apparently easy enough. If I just do:

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

It will start recording, then turn off about a second later, start again about a second later, and then repeat. I somehow managed to get a 5 second recording as well. I'm not really sure how this is supposed to work. I need to test some more.

EDIT: Turns out the schematics were right. If I do something as simple as:

digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(1000);

It will turn on the video recording and turn off whenever it gets HIGH again.


Reading a 10 pin 7 segment (2 digits) sing Arduino 1. Please Help!

Your display is multiplexed, so you will need to monitor not only the segment lines but also the digit lines.

First figure out if your display is "common anode" or "common cathode" as the logic in one case will be inverted from that of the other.

For your test case, you can write the driving and reading arduinos to the display in the same way, but configure all the connected pins on the reading one as inputs.

The tricky part is going to be detecting when the segment select has changed, but you could do it by storing the current value of each select pin, and then reading the new value.  If you see that the old value was inactive and the new value active, then wait a tiny amount of time and read all of the segment lines.  You want to wait long enough to make sure that the data lines have been driven to match, but no so long that you get the data for the next digit instead.  If you have access to a scope, you can find the best value, but you could also experiment by making the delay short until you get wrong data, making it long until you get wrong data, and then picking an intermediate value.

You may find it easiest to read all 7 or 8 segment lines into a single byte value, and then compare it to each element in the lookup table you used in the driver code until you find a match.

If you don't know the exact wiring of the segments on the unknown target board, consider printing the bytes to the serial monitor as you cause the displayed values to change (cup of ice water, cup of hot water...) and taking notes of the segment values vs. the digits you see display.  It will be a puzzle, but one you should be able to figure out.


Webserver on Arduino: How to 307 temporary redirect

You need to make a decision on what to respond with depending on what the request is you have received.

If you receive a "command" URL (which you already check for by looking for certain sub-strings) then you need to respond with the 307 response. If you don't receive a "command" URL (so anything except the things you are specifically looking for) then you respond with the homepage.

A slight re-formatting of your decision code to use else if instead of just if would make it easier:

if (c == '\n') {
  Serial.println(readString); //print to serial monitor for debuging
  // homepage(); << This is now moved elsewhere.
  //controls the Arduino if you press the buttons
  if (readString.indexOf("?resetcount1") > 0) {
    count1 = 0;
    redirect();
  } else if (readString.indexOf("?resetcount2") > 0) {
    count2 = 0;
    redirect();
  } else if (readString.indexOf("?resetcount3") > 0) {
    count3 = 0;
    redirect();
  } else if (readString.indexOf("?resetcount4") > 0) {
    count4 = 0;
    redirect();
  } else if (readString.indexOf("?togglerelay1") > 0) {
    toggleRelay1();
    redirect();
  } else if (readString.indexOf("?togglerelay2") > 0) {
    toggleRelay2();
    redirect();
  } else if (readString.indexOf("?togglerelay3") > 0) {
    toggleRelay3();
    redirect();
  } else if (readString.indexOf("?togglerelay4") > 0) {
    toggleRelay4();
    redirect();
  } else { // If none of them match then send the homepage.
    homepage();
  }
}

redirect() is as simple as:

void redirect() {
  client.println("HTTP/1.1 307 Temporary Redirect");
  client.println("Location: /");
  client.println("Connection: Close");
  client.println();
  client.stop();
}


SoftwareSerial read until available is empty only works with delay

Serial does not transmit data as one bunch, but byte by byte. There can easily be some little delays introduced, especially, when transmitted via a packaged protocol like bluetooth, long enough, for the Arduino to not see any new data in its buffer. Also the transmission needs some time, depending on the baudrate. When you read faster from the buffer, than you receive, you will encounter an empty buffer after every byte.
Now with that information look at your code:
void loop()
{
    while (ble.available() > 0)
    {
        data += (char)ble.read();
    }

    if (ble.available() <= 0 && data.length() > 0)
    {
        ble.println(data);
        //do stuff
        data = "";
    }
}

Let's assume, the Arduino receives one byte, then a little pause happens, then the next data is received. The code will go into the while loop and read the received byte from the serial buffer. To stay in the while loop, the next byte has to be received in the execution time of the code inside of the while loop. That is incredible short. So after one byte there is nothing more inside the buffer, thus the while loop exits, because ble.available() returns zero. Then the if statement is executed, also rather fast. Most likely, ble.available() will still return zero. But you already put a character into the buffer, so the if statement is executed.
The delay solves your problem because then you read way slower than you receive. The data is mainly received while the delay runs. Then the rest of your code can read, what was already received and put into the buffer.
**What to do instead of delay(): You need to make sure, that you always read a full message. There are different ways, depending on your requirements. If your messages always have the same length, you could wait, until the specified number of characters was received, and only then read them. But that will fail, if you for some reason (for example a reset of the Arduino) receive a partial message, which would cause a misalignment. You could clear the receive buffer, when you read a full message, that might help, if your data transmissions don't happen to often.
You could try to parse the incoming data according to the message format (which needs to stay constant for this purpose), like:
Read a number.
If it has a colon following it, it is a new message.
Then read number
    read comma
    read number
    read comma
    read number
Repeat.

For this purpose it would be fitting to read every byte, that gets received, and write then into your own circular buffer. You can then continuously add newly received characters at the end, while removing the already parsed messages from the start of the buffer.

You see, these ways have caveats and might be convoluted. The easiest way would be to add a delimiter/terminator to your messages, though from your question it sounds, as if this is not possible for you currently.
Note:

None of the above is specific to SoftwareSerial. It's the same for hardware Serial.
I suspect the code worked your ESP, because you had some other code there, which introduced a big enough delay (just like your delay() call)


How to communicate from Python to Arduino Softserial

That is all me, look for an answer for ages, finally post a question, to end up finding the answer in the following hour...

this is because Arduino takes TTL as input and not RS-232...

similar here :
https://electronics.stackexchange.com/questions/42584/arduino-uno-weird-characters-sent-to-com-softwareserial


The first argument of setPixelColor is is the number of the led. In your case 0, so the first led.

Instead use a for loop to set all the leds from 0 until (excluding) 24 (which is stored in NUM_LEDS).

void loop()
{
  for (int led = 0; led < NUM_LEDS ; led++)
  {
    strip.setPixelColor(led, 255, 255, 255);
  }
  strip.show();
  delay(1000);

  for (int led = 0; led < NUM_LEDS ; led++)
  {
    strip.setPixelColor(led, 255, 255, 255);
  }
  strip.show();
  delay(1000);

To make the code better (shorter, but more important more maintainable, and reducing code duplication), create a separate function:

void loop()
{
  setLeds(255);
  setLeds(0);
}

void setLeds(int intensity)
{
  for (int led = 0; led < NUM_LEDS ; led++)
  {
    strip.setPixelColor(led, intensity, intensity, intensity);
  }

  strip.show();
  delay(1000);
}


Is digitalWrite(pinnumber,LOW) different from ground pin

Yes, it is different.

First: Never run a motor directly from IO pins - you will damage your Arduino. Not only can a real Arduino not supply enough current, but motors generate a lot of back-EMF that will kill an Arduino.

Secondly a pin doesn't connect direct to GND or VCC - it is connected through a MOSFET that performs the switching.  That MOSFET has an ON resistance, which causes a voltage drop across it determined by the current being sourced or sunk through the pin.

You can read more about GPIO pins here.


Why is timer0 the fastest timer in the arduino?

Timers 1 and 2 are configured by the Arduino core library to run the so
called “phase correct PWM” mode. In this mode, the timers count
forward from 0 to 255, and then they count backwards to zero. Timer 0 is
configured by the same library in “fast PWM” mode, where it counts
from 0 to 255 and then overflows back to zero in a single timer cycle.

You can, if you want, configure timers 1 and 2 in fast PWM mode. For
doing this, you will have to access their I/O registers directly. C.f.
the datasheet of the relevant microcontroller for details.

A couple of links:

the datasheet of the
ATmega328P
microcontroller describes all the possible configurations of the
timers (sections 15, 16 and 18 for timer 0, 1 and 2, respectively)
the source code of the Arduino init()
function
to see how Arduino core configures them.


Charlieplexing 30 LED sections with a max of 27 LEDs at the same time?

I would consider 74HC595N's. These are shift registers, which can control 8 'outputs' using less pins on your Arduino.

These are very cheap (buy them per 10) and you can daisy chain 4 of them, having 32 outputs, using only 5 pins of your Arduino. This would fit perfectly with your 30 sections.

Each of the 30 outputs can be used to control a transistors to control one LED sections.

See for an example for using shift registers with the Arduino: ShiftOut

Also you might need this: ULN2803 darlington drivers for each output (4 total).


Adding a custom board to the Arduino IDE

The simplest clean way to add your board using an existing core is to add the variant to your sketches folder's hardware subfolder. Only boards.txt and files for the board variant are added.

In your sketches folder create a 'hardware' folder. In this folder create a folder with the name of your boards package and a subfolder with the architecture name and a subfolder for variant and a name of the variant. for example hardware/my_boards/samd/variants/samc21x

In your variant folder (variants/samc21x) put the files for your variant based on variant files of the closet variant in the referenced hardware package. In your case perhaps a mkrzero would be a good example.

In your package's root (hardware/my_boards/samd/) add boards.txt file with entries for your board.

For boards.txt take the options for a similar board in referenced package. Change the names and settings and prefix build.core value with the name of the vendor of the referenced package. For arduino/samd it would be arduino:. For example samc21x.build.core=arduino:arduino

My custom and customized boards definitions https://github.com/jandrassy/my_boards


Problem with LCD keypad shield and Arduino Uno R3

I do not have an answer... but it might be power consumption problem, ou voltage stability problem. I use a LCD shield with an RFID card reader (contactless card reader like you can find in the subway). When I plug the thing to a 9v battery the contrast is higher than when I connect it to an USB cable.


Please explain the void loop() section of the sketch

The transmitter transfer date array of [60] like: 523 | 487, here " int commands[30];" just 30, is it OK?

If you have a maximum of 59 characters (59 printable characters plus the NULL at the end equals 60), and each number is separated by a | character, then the maximum possible numbers you can have, if they are all single digit, is 30. So yes, an array of 30 integers is fine.

  " if(char(buf[i]) == '|') / commands[column] = message.toInt();", seems just convert the date before '|'?

Yes. It takes whatever has been placed in message and converts it to an integer, then empties message ready for the next number.

  what is the result of " message += char(buf[i]);"? Thanks

It adds the current character from the buffer (pointed to by i) to the end of the message string.

It's not the best way of doing it, and it can make a mess of your heap causing your Arduino to crash after a while.

Personally I would use strtok() directly on the buffer:

int i = 0;
char *part = strtok(buffer, "|");
while (part) {
    command[i] = atoi(part);
    i++;
    part = strtok(NULL, "|");
}

This of course assumes that buffer is properly NULL terminated.


I believe that is the dual op-amp that is used for both monitoring VIN to enable/disable the USB power, and as a buffer for the LED on pin 13.

In the schematic it's U1, and is an LM358.