Determining which section of code uses the most flash

Moving strings to PROGMEM will only exacerbate the problem, since PROGMEM is the 32k flash.

You can easily get your "symbol table" from the compiled .elf file by using avr-objdump -t <.elf file>.

It results in a list something like this:

... scrolls past ...
00000338 g     F .text  00000076 init
000000d4 g       .text  00000000 __ctors_start
000000e2 g       .text  00000000 __do_copy_data
00800110 g       .bss   00000000 __bss_start
000008a2 g     F .text  00000022 main
00000126  w      .text  00000000 __vector_4
00000000  w      *ABS*  00000000 __heap_end
00000126  w      .text  00000000 __vector_9
000003ae g     F .text  000000d0 delay
00000126  w      .text  00000000 __vector_2
00000126  w      .text  00000000 __vector_21
00000126  w      .text  00000000 __vector_15
00000083 g     O .text  0000000a port_to_output_PGM
00000154 g     F .text  0000002e setup
008001c3 g       .stab  00000000 __heap_start
000000d6 g       .text  00000000 __dtors_start
000000d6 g       .text  00000000 __ctors_end
000008ff  w      *ABS*  00000000 __stack
0000008d g     O .text  0000000a port_to_input_PGM
00800110 g       .data  00000000 _edata
008001c3 g       .stab  00000000 _end
00000126  w      .text  00000000 __vector_8
000000bf g     O .text  00000014 digital_pin_to_timer_PGM
00000a08  w      .text  00000000 exit
00000702 g     F .text  00000052 _ZN14HardwareSerial4readEv
000009b8 g       .text  00000000 __udivmodsi4
00000a08 g       .text  00000000 _exit
00000126  w      .text  00000000 __vector_14
00000126  w      .text  00000000 __vector_10
000002a8 g     F .text  00000090 __vector_16
00800100 g       .data  00000000 __data_start
00000480 g     F .text  00000076 __vector_18
00000126  w      .text  00000000 __vector_20
00000108 g       .text  00000000 __do_global_ctors
... etc ...

The lines you are interested in are .text sections.  The first big number is the HEX location in memory.  The second one is the important one - that is the size.

You can see from that snippet that the function delay is located at address 0x3ae and is 0xd0 bytes in size.

If you're on Unix or OSX you can employ the more advanced searching tools that are at your disposal.  For instance, to just list the "global" .text entries:

$ avr-objdump -t <elf file> | grep '\.text' | grep ' g '

Which for my test program results in:

00000079 g     O .text  0000000a port_to_mode_PGM
00000918 g     F .text  00000040 _ZN5Print7printlnEv
00000a00 g       .text  00000000 __tablejump__
000006c2 g     F .text  00000040 _ZN14HardwareSerial4peekEv
000008c4 g     F .text  00000054 _ZN5Print5writeEPKhj
000000d4 g       .text  00000000 __trampolines_start
00000a0c g       .text  00000000 _etext
000006a0 g     F .text  00000022 _ZN14HardwareSerial9availableEv
0000012a g     F .text  0000002a loop
00000774 g     F .text  00000080 _ZN14HardwareSerial5writeEh
00000126 g       .text  00000000 __bad_interrupt
000000d4 g       .text  00000000 __trampolines_end
00000200 g     F .text  000000a8 digitalWrite
00000592 g     F .text  0000010e _ZN14HardwareSerial5beginEm
00000182 g     F .text  0000007e pinMode
00000097 g     O .text  00000014 digital_pin_to_port_PGM
000000d6 g       .text  00000000 __dtors_end
00000754 g     F .text  00000020 _ZN14HardwareSerial5flushEv
0000051c g     F .text  00000076 __vector_19
00000990 g     F .text  00000026 _ZN5Print7printlnEPKc
000000f8 g       .text  00000000 __do_clear_bss
000000ab g     O .text  00000014 digital_pin_to_bit_mask_PGM
00000000 g       .text  00000000 __vectors
000009fc g       .text  00000000 __tablejump2__
00000338 g     F .text  00000076 init
000000d4 g       .text  00000000 __ctors_start
000000e2 g       .text  00000000 __do_copy_data
000008a2 g     F .text  00000022 main
000003ae g     F .text  000000d0 delay
00000083 g     O .text  0000000a port_to_output_PGM
00000154 g     F .text  0000002e setup
000000d6 g       .text  00000000 __dtors_start
000000d6 g       .text  00000000 __ctors_end
0000008d g     O .text  0000000a port_to_input_PGM
000000bf g     O .text  00000014 digital_pin_to_timer_PGM
00000702 g     F .text  00000052 _ZN14HardwareSerial4readEv
000009b8 g       .text  00000000 __udivmodsi4
00000a08 g       .text  00000000 _exit
000002a8 g     F .text  00000090 __vector_16
00000480 g     F .text  00000076 __vector_18
00000108 g       .text  00000000 __do_global_ctors

From that I can see that the function _ZN14HardwareSerial5beginEm is the biggest and takes up 0x10e bytes.  That strange named function is a "C++ Munged" name.  It actually corresponds to HardwareSerial::begin() and is the parent class name for Serial.begin().


Bluetooth module HC-05 not finding mobile phones, only PC

Bluetooth maybe on, but some phones are "invisible" until you put them in "other Bluetooth devices can find me" -mode.

Current iPhones are visible when Bluetooth is on but, Androids for example, (at least 7.0 upwards) are visible only when you have the Bluetooth settings screen open.


When does the pulsein() function start counting?

According the official Arduino Reference: PulseIn

Fragment:

  Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
  HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then
  waits for the pin to go LOW and stops timing. Returns the length of
  the pulse in microseconds. Gives up and returns 0 if no pulse starts
  within a specified time out.


OK, I have solved this by sending DSR pulse as seen on code below:

mySerial.DtrEnable = true;
mySerial.Open();
Thread.Sleep(1000);
mySerial.DtrEnable = false;


Getting random values on Arduino Duemilanove 328

Why do you think it should show 0 when not connected to anything?

Does the antenna of your radio give a zero signal just because the end isn't connected to anything?  An Arduino's input pin (either analog or digital) is just the same.  If it isn't connected to anything then it just picks up noise - be that radio transmissions, induction from nearby mains wiring, neutrinos from Alpha Centauri...  Basically if it's not connected to anything then there is no way you can possibly know what the value should be since there is no set value.

In order to read 0 on the ADC the ADC has to be connected 0V.  That means connect it to ground.


How can i connect 4 stepper motors and 3 sensors to an Anduino?

Take a look at the Ramps V1.6, it is what I use. It plugs onto the AT Mega board.

https://reprap.org/wiki/RAMPS_1.6

The 1.6 has a few improvements. I like the solder in power connectors rather than the plug in ones. More reliable.

Because I already had the AT Mega board I decided to try the ramps. There are better boards now, with 32 bit processors. But as a starting point the Ramps combo is the simplest to get going and it does the job.

Other boards may work out a little better, but the firmware is a bigger issue. Still in development.


The problem is that serial.write will block if the buffer is full.

Only until the bytes get sent out through the TX pin.

  If I skip writing if the buffer is full, a receiver will only get old data on the first connect.

No it won't. There is no "old" data.

  How can I replace data in the buffer or make sure there is only one dataset in the buffer?

You don't need to.

You are showing a fundamental misunderstanding of how serial works.  When you send data it just twiddles the TX pin in the right way with the right timing. If there is something connected to it that understands that twiddling at the speed it's being twiddled then it interprets it as serial data. If there's nothing to see that twiddling it still twiddles.  The "blocking" is only if you try and send more data than the serial port can physically send out in the time you're sending it.

If a serial port transmits in a forest and there is no one there to hear it, yes, it still makes a noise.


Arduino how to get amount of elements in an array?

numElements = (sizeof(array) / sizeof(array[0]));


The pubchannel and subchannel can be defined as any values in char variable.

Here is the right code:-

const char * pubkey = "publisher key from your account";
const char * subkey = "subscriber key from your account";

const char * pubchannel = "demo_keyset";
const char * subchannel = "demo_keyset";

Then the error disappeared


What is the capability of AVRISP and USBASP on ATMega48, 328, 2560?

Yes.
Yes.
Depends on the specific hardware. See the documentation for the exact variant you have.
See 3.
No. They have their own protocol that you must use instead. They are selectable from the Programmer menu in the IDE though. However, you must unprogram the fuse bits outside of the IDE.
No. They are low-cost tools meant to be used for programming only. You will need an Atmel-supplied debugger in order to use Atmel Studio's debugging features.


Arduino MotorShield code running but not motors

Turns out the pins connecting the shield to the Arduino are quite loose and didn't "touch" the Arduino.


How to calculate the RZERO value in MQ135 sensor, I have already burned it for 24 hours?

From the datasheet here --->MQ135 datasheet, It is the value of Sensing resistor at 100 PPM of Ammonia(NH3) or from the graph in Fig. 3, you can use gases that has y intercept as 1 and appropriate concentration, i.e you need atleast some known parameter to get it. The legend in the graph is also not clear (as far as getting the values from the Log - Log graph, there are tutorials in youtube).

I'm also in need of solution to this, so far this is what I read on the internet... You need a chemistry lab to do it !!!


Create own apache web server on Arduino Uno... just like you can on a raspberry pi?

You can only make a very, very, very basic webserver, that won't be able to handle more than a few requests per second.

You also need to add something like an ethernet shield, and probably an SD card reader. Which would make it about the same price as a Pi.

It's possible, but very limited, not practical in most cases, and not that much cheaper.


How to write to the second line of a display?

Line 1 starts at address 0x00 | 0x80 0b10000000 and ends at 0x13 | 0x80 0b10010011
Line 2 starts at address 0x40 | 0x80 0b11000000 and ends at 0x53 | 0x80 0b11010011
Line 3 starts at address 0x14 | 0x80 0b10010100 and ends at 0x27 | 0x80 0b10100111
Line 4 starts at address 0x54 | 0x80 0b11010100 and ends at 0x67 | 0x80 0b11100111

That 0x80 0b10000000  is the HD44780 command for set DDRAM address. The other bits 0b1xxxxxx define the address.

You'll find more details at Arduino with HD44780 based Character LCDs


The vendor name is not stored on the device, rather it is indicated only by the first three octets or OUI part of the MAC address which is either stored on the device, or in your case set up by software.  Turning this back into a name on another computer which sees its traffic is done by the help of a local or network-sourced OUI lookup table.

Apparently the table your computer is consulting doesn't have an entry for the OUI 0xDE, 0xAD, 0xBE.

And that's not surprising as this is clearly a dummy value put in as a placeholder - read all 6 octets as if they were a word and you'll see it says "dead beef feed" - a variation on a classic magic "illegal" value.

Technically, this is actually a legal value for use on a local network as the 2's bit of the leading octet is turned on, indicating that it is a "locally administered" address, rather than one guaranteed to be unique in all the world as you would expect a proper piece of network hardware to have.

If you find the table your computer is doing OUI lookups in, you could add a DE:AD:BE entry to it.


An optoisolator is good for digital signals, but won't transfer an analog signal accurately.

Instead, you could put ADCs on the different circuits and optoisolate their communication with a master Arduino.


Is it possible to power this 12V Wind Speed Sensor with a 5V battery?

If you have a circuit diagram for your 13,000mAh 5V battery, check whether there are internal connections at higher than 5V.  Because 5V is not a common battery voltage, there probably are cells in a higher-voltage series connection, being converted to 5V output via a step-down (buck) circuit.
An item like a “5V DC to 9V DC Converter DC-DC Isolated Power Supply Module” as in picture below [from ebay seller bidcenter] might do the job.  Also available are less-expensive not-potted adjustable boost regulators.


simply, using strcpy, and using a char with a given length, works

RTC_DATA_ATTR char ssid["dedicated length"];

strcpy(ssid, cSsid->getValue().c_str(), "dedicated length");


I have one of these TFT LCD shields, but mine is a ILI9335. It has taken me nearly 2 weeks to find a working Library and code for my 9335 driver and I am now setting about creating sketches based around my working Library.
  Library - TFTLCD using st7783 controller
Unfortunately most sellers of these shields (excluding good reputable companies) do not adivise of which Driver is onboard the shield and it becomes difficult to locate a working Library for the driver of the purchased shield.

ALSO, check that the Libraries you have are working for your version of Arduino IDE. Some of my libraries would not compile in v1.0.5 but will in v1.6.3 (and vice versa)
If there is no Library specific to your 6767 Driver (and I must say I have not seen one in my searches for the 9335 Driver) then you may have to download as many different Libraries to locate a sketch that works for yours.
Once you have a working Library then it is just a matter of modifying it for your purposes.

Good luck in finding a working solution for your shield.

Lance..


How to avoid Multiple definition of 'Blynk' error?

The Blynk "simple" header files are not ready to be included into multiple cpp files. They are meant to be included only in the main ino file. The reason is that the variable allocations are in headers file, which is bad practice for  C and C++. The h files should contain only declarations. The right way would have

extern BlynkWifi Blynk;

and the lines which are now in the h file should go in a cpp file. Then every cpp file that includes the .h will know about the variables but the variables would be allocated only once.

The fix is to change the library or to copy the BlynkSimpleEsp8266.h include to your project as for example MyBlynk.h and change the Blynk variable in MyBlynk.h to extern and add a MyBlynk.cpp file with variables allocation

#include "MyBlynk.h"

WiFiClient _blynkWifiClient;
BlynkArduinoClient _blynkTransport(_blynkWifiClient);
BlynkWifi Blynk(_blynkTransport);


Perhaps this is not exactly what you are looking for, but from your examples it seems like using navigational commands from the keayboard/mouse would accomplish a lot of what you are requesting.

Android has USB HID support from honecomb, so you should be able to create a sketch to emulate a keyboard and mouse based on the IO data and it should work with your android device just by plugging the USB cable (if emulating a mouse, it will display the mouse cursor as soon as it is connected).


Voltage from batteries in series operating on 3 ATTiny, 3 Buttons, and 3 Piezo buzzers

If you connect the AtTiny chips in parallel, they will all receive the full voltage from your battery. If you exceed the current output of your battery the voltage will droop.
If the AtTiny chips need 3.5V and you give them 6V instead, it will likely destroy the chips.
The short answer: Don't try to drive microcontrollers directly from batteries. You should get a 3.5V switching power supply. Then you will be able to drive all 3 chips cleanly from your battery. (Switching power supplies are very efficient. They don't waste much power at all.)
Note that button cells produce very small total power (in milliwatt/hours) so they won't drive your processors for very long before they are exhausted. I suggest using 4 AA batteries and a switching regulator instead. The 4 AA batteries would give you a 6V VIN to your voltage regulator, but a lot more total power.


This to be possible with only 1 Arduino depends in your sensor. It is most likely not possibpe without another microcontroller (not nesessarily an Arduino) because of the following reason.

Most bluetooth modules on the market (linke the HC-05 vor HC-06) are bluetooth serial modules, meaning that they build a serial connection over bluetooth and provide the corresponding two pins (RX and TX). Yet most sensors don't implement an UART interface (the Serial interface in Arduino), but only give an analog or digital output voltage. With much work you might be able to tweak the firmware of the bluetooth chip for reading and sending a digital value, but this would be more work, than the price of a second microcontroller would justify.

So I would try to add a small microcontroller (like an ATTiny85) to the sensors side. It can measure the sensors output voltage and then send it via Serial to the bluetooth module. You might also want to use another Arduino here, though this might be an overkill. Maybe a really small version.

After some thinking I had the idea, that it might be possible to send an analog voltage from the sensor through a audio bluetooth module without using another Arduino. Though I'm not sure if this really would work and which module you need for that.

All in all I still would go for the extra microcontroller and serial interface bluetooth, because it is much easier for a beginner.

EDIT:

Above I mentioned using Serial on an ATTiny85, which is not directly possible, since it does not have a full UART hardware (but only a USI). Though you can use the standard SoftwareSerial library on it. If the rest of your code isn't to big, it should still fit in the small memory of the Tiny.


What happens if I don't open the USB serial port of Arduino Pro Micro / Leonardo?

As far as I can see from CDC.cpp it attempts to see if the USB is available and if not, do not write anything but set the "write error" flag.

size_t Serial_::write(const uint8_t *buffer, size_t size)
{
    /* only try to send bytes if the high-level CDC connection itself
     is open (not just the pipe) - the OS should set lineState when the port
     is opened and clear lineState when the port is closed.
     bytes sent before the user opens the connection or after
     the connection is closed are lost - just like with a UART. */

    // TODO - ZE - check behavior on different OSes and test what happens if an
    // open connection isn't broken cleanly (cable is yanked out, host dies
    // or locks up, or host virtual serial port hangs)
    if (_usbLineInfo.lineState > 0) {
        int r = USB_Send(CDC_TX,buffer,size);
        if (r > 0) {
            return r;
        } else {
            setWriteError();
            return 0;
        }
    }
    setWriteError();
    return 0;
}

This is the same test as is done in operator bool() without the 10 ms delay.

// This operator is a convenient way for a sketch to check whether the
// port has actually been configured and opened by the host (as opposed
// to just being connected to the host).  It can be used, for example, in
// setup() before printing to ensure that an application on the host is
// actually ready to receive and display the data.
// We add a short delay before returning to fix a bug observed by Federico
// where the port is configured (lineState != 0) but not quite opened.
Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

Judging by the comments above, this may not be the most reliable thing in the world.


How best to power down an Arduino for ~5 minutes at a time?

Yes, if you want to wake an ATMEGA (the chip in the Arduino) spontaneously (no outside trigger) from Power Down mode at periodic intervals, the you will need to rely on an interrupt generated by the watchdog timer, which has a maxim timeout of 8s.

Your goal should be to wake, increment and check the timer, and get back to sleep as quickly as possible since the amount of time you are awake will dominate your average power usage while asleep.

Some things to keep in mind...

The arduino uses a power regulator which always draws current. If you are going for long battery life, you will need to replace or eliminate this regulator. Much better to have an ATMEGA connected directly to a battery.
Turn off as much of the chip as possible before going to sleep. Take a look at the power control registers.
Make sure you are not driving any unnecessary loads with the GPIO pins when sleeping.

BTW, common wisdom has been that it is best to wake up and run at as fast a clock speed as possible to get your work done and get back to sleep as quickly as possible. However, Jack Ganssle recently published an article that makes a great case for doing the opposite. You will actually get longer battery life if you wake up to a slow clock speed, since this means you can run down the battery to lower voltage (this assumes you don'y need higher voltages for some other part of your circuit). Lots of other great info for designing long running battery-powered systems here...

http://www.ganssle.com/tem/tem275.html

Here is another relevant article about long running Arduinos...

http://www.openhomeautomation.net/arduino-battery/


How do I see underlying code and definitions inside Arduino IDE on MacOS X El Capitan

The simplest way is to look at the source on Github:

https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/cores/arduino

Can you set a breakpoint? No. The Arduino IDE and the bootloader don't support such functionality. To do that you need a real IDE (like Atmel Studio) and a hardware debugger.


You call SPI.transfer() four times, each time saving the returned value to a variable after proper bit shifting.

uint32_t val;
val = SPI.transfer(0xff);  //0xff is a dummy
val |= (uint32_t)SPI.transfer(0xff) << 8;
val |= (uint32_t)SPI.transfer(0xff) << 16;
val |= (uint32_t)SPI.transfer(0xff) << 24;

I assume the least significant byte is received first. Make sure the SPI mode is the right one, as indicated in your datasheet.

If the slave can't handle being deasserted between bytes (which is what SPI.transfer() will do at the end of the transaction), then you can either try st2000's hardware SPI approach or use bitbanged SPI with shiftIn().


How to measure direction the car is coming to garage door?

It is very hard to determine position accurately there is a new project on kickstarter called Pozyx, you can look at that but that's expensive, to be honest this sounds like a job for hanging tennis balls or strings or something like that. But if you have a lot of money to blow and you just want a project go for it, you may be able to do this with ultrasonic sensors but I reckon that would be painful. Anyway good luck


You can download the Arduino IDE for Linux from the Arduino site.

As mentioned in Where are the hex files compiled by Arduino?, in the Arduino program: go to Arduino -> Preferences and then select Show verbose output during -> compilation.

  Finally, when you are compiling, the program will show you lots of
  data. At the last lines, you will find the path to the .hex file
  (Every time the path changes!).

If you want to upload this .hex file to your ATmega328P (the micro controller inside Arduino Uno), avrdude can do that for you.

Here, are few useful links:

Setup Avrdude on Linux
Programming your chip
Choosing a Programmer
Uploading your .hex file


Controlling multiple stepper motors non-simultaneously

Like @chris! suggested, you could include two Stepper variables. So in the line where you were initializing the variable, you could instead have:

Stepper steppermotor1(stepsPerRevolution, 8, 10, 9, 11);

Stepper steppermotor2(stepsPerRevolution, 4, 5, 6, 7);

and then continue on with the code for speed, rotation and so on for each motor.


Two Arduinos get out of sync after a few seconds

What is the reason for this drift and how can I eliminate it?

two solutions:

1) try using crystal oscillators;

2) try driving on arduino with the other arduino's clock output.


Minimum value I2C-pull up resistor for arduino

The full datasheet of the atmega328p can be found here: https://www.microchip.com/wwwproducts/en/ATmega328P.
It is called "ATmega328/P AVR MCU with picoPower Technology Data Sheet".

In section "32.7 Two-Wire Serial Interface Characteristics" in table 32-10 on page 372 it shows different voltage levels for the input.

On page 110 it says: "When the TWEN bit in TWCR is set (one) to enable the 2-wire Serial Interface, pin PC4 is disconnected from the port and becomes the Serial Data I/O pin for the 2-wire Serial Interface. In this mode, there is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation".

I wrote here before that the i2c (the twi hardware inside the microcontroller) did not use the digital pin hardware. However, the i2c pins can still sink a lot of current. Thanks to @Berkay for noticing the same behaviour of the sink current as a normal digital pin.

According to the datasheet the atmega328p of the Arduino uno might not use the digital pin hardware for i2c. It is not known if the same mosfet circuit is used with the same (large) sink current. Perhaps the chip uses a similar mosfet circuit with added slew rate for the output and added spike filter for the input. Perhaps the same mosfet of the digital pin is used after all.

In the Arduino sketch, calling Wire.begin turns on the dedicated i2c hardware in the atmega328p chip. The sink current and voltage levels are according to the i2c specifications.
As you can see in the i2c tutorial by Nick Gammon, the Arduino can sink more than 3 mA.

When the pullup resistors are too low, for example for a sink current of 4 mA, the Arduino uno can handle that, but the slave might not.

When all the pullup resistors are combined, the required sink current can be calculated. The maximum is 3 mA to meet the i2c specifications. To compensate for wire capacitance the i2c bus speed can be lowered.

The i2c bus is not ment to go into a cable, it is not ment for long wires. A cat6 cable is 46 pF/m. That means your 800 pF is for 17 meters cable? That is not what the i2c bus is for. It is for 17 centimeters. The rule of thumb is maximum 50 cm for a normal 100 kHz to 400 kHz i2c bus.


Arduino controlled relay for certain duration of time

you need to update the timeElapsed variable inside the while loop:

 unsigned int interval = ftime*1000; //ftime in ms
 unsigned long startTime = millis();
do
  {
      digitalWrite(Relay1, LOW);
      timeElapsed = millis() - startTime;
  }
  while(timeElapsed < interval);
digitalWrite(Relay1, HIGH);

Another way is to create a state machine make startTime a global and update the logical state (and the pin) when the time is elapsed.

unsigned long startTime;
bool relayLOW = false;

void loop(){

    if(relayLOW && millis() - startTime > interval){
        digitalWrite(Relay1, HIGH);
        relayLOW = false;
    }
    if(!relayLOW){
        bool closeRelay= //decide if relay needs to be triggered
        if(closeRelay){
            startTime = millis();
            digitalWrite(Relay1, LOW);
            relayLOW = true;
        }
    }
}


Arduino mini being programmed with CH340G

First of all you should connect the DTR (not the DSR) pin to the reset terminal WITH a 100nF capacitor. See this page or the arduino uno schematics to see how to put the capacitor (it's simply in series with the signal.

However I suggest you to start programming WITHOUT the autoreset; once you are sure that you can program it then try soldering that capacitor to program the arduino without having to hit the reset button.

As for when, watch the IDE status: when it stops compiling and shows the "Uploading" string, press the reset button on the board. You will usually have a couple of seconds to press it.


FIFO overflow - reading IMU MPU6090 and GPS uBlox NEO-6M at once

When I try to read data separately it works, but together it stuck every second (probably reading of gps data) and MPU6050 serial monitor sending FIFO overflow error .

Yes, you have to be careful about the loop structure and "blocking" to "wait" for a new GPS speed report.  SoftwareSerial also blocks everything else during each received character time.

Just check for GPS characters and update the speed if a complete sentence was received, then do "other things" (e.g., use the IMU data).  Here is a NeoGPS version of your example:

#include "NMEAGPS.h"
#include <NeoSWSerial.h>

static const int RXPin = 7, TXPin = 4;
static const uint32_t GPSBaud = 9600;

float gps_speed = 0;

NMEAGPS gps;

// The serial connection to the GPS device
NeoSWSerial ss(RXPin, TXPin);

void setup(){
  Serial.begin( 9600 );
  ss.begin(GPSBaud);
}

void loop(){

  // Read GPS characters and see if a new fix is available
  if (gps.available( ss )) {
    gps_fix fix = gps.read();

    //  A fix is available once per second, but the GPS may not know
    //  the speed value, perhaps because the satellite reception is
    //  poor or the unit is just starting.  Check the valid flag.

    if (fix.valid.speed) {

      // Update the gps_speed.  Other parts of your
      //   program can use it whenever they want.
      gps_speed = fix.speed_kph();
      Serial.println( gps_speed );
    }
  }

}

NeoGPS is smaller and faster than other libraries and can be configured to only parse the fields you really use.

Your original sketch uses 6884 bytes program space and 349 bytes of RAM.
The NeoGPS version can be as small as 4802 bytes program space and 150 bytes of RAM. Significant savings!

For the software serial library, I would suggest using AltSoftSerial on pins 8 & 9, if you can move the GPS.  It is much more efficient, and does not disable interrupts for long periods of time: SoftwareSerial will block for ~1ms, and eternity for a 16MHz Arduino.  This is probably interfering with the IMU interrupts.

If you can't move the GPS to pins 8 & 9, you might try another library I maintain, NeoSWSerial.  It is much more efficient than SoftwareSerial, and it works on any two pins.  NeoSWSerial will "play nicer" with the IMU interrupt code, but it can still be affected if the IMU interrupt code takes too long.  NeoSWSerial should not affect the IMU interrupt code.  I used it in the above sketch, along with a debug print.


You can Use wheel encoders. You can even make your own wheel encoders with general parts like photoTransistor and lasor or led light. you can make your encoder or print it out in paper. The use little math to calculate the distance. It will give you measurement with good level of precision.

Basic principle:

more information at

wheel Encoder

another encoder


There are some instructions at:
Pygamer setup
That need to be followed in order to permit the Arduino IDE to work with the Pygamer.  It's not clear that you have followed any or all of these instructions.
I recommend that you carefully follow ALL the steps and then start with the simple example to test that you are building and uploading properly.
Then move on to the Adafruit example that uses the Arcada library.


RTClib library dependency on Wire library

Not getting too formal here, The arduino IDE looks at which libraries are included in the top level sketch when deciding what libraries to include in the compilation.

It would make sense for only RTClib.h to include Wire.h yes, but the IDE does not get the information to add Wire to the compilation list that way. It is a quirk of the IDE that makes implementing libraries that use other libraries a bit more painful.


Can I use arduino's 3.3 V output directly to esp8266?

You should search for this data yourself, but since you are saying you are a newbie I'll tell you how to find this.

First of all you should search for a document called "datasheet". On a datasheet the producer writes all the relevant data about his product.

In your case, you should search for the electrical characteristics of the ESP8266. For instance here you have one of the datasheets. On page 13, there is the "Power consumption" chart, which says that the worst case has a typical current of 170mA. I suggest you to raise it a bit; let's say you need 250mA for the ESP.

Now, the arduino. You should search for the schematic of the board or read the part number of the 3.3V regulator. Since it's easier from the schematic and they released it on the web, you can see that the part number of the 3.3V regulator is LP2985. Searching for it on google will lead you to the texas instruments webpage, with the datasheet. Here you can see that the maximum output current is 150mA, so below the required current. Answer: you can't with arduino.

As for the FT232 cable, you should search for it because there are different models. Search on google and pick the first link pointing to the ftdi website.

As an example, the TTL-232RG has this datasheet. On page 9 they say that the TTL-232RG-VSW3V3-WE has an output current of 50mA, so you can't use it. The TTL-232RG-VREG3V3-WE, on the other side, has a maximum output current of 250mA, so you can use it.

If you have further questions, just ask here ;)


"Does not name a type" error with Serial.print

If you move this code into loop(), the sketch will compile.

String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
String lilyPad = codeWrite(6, HIGH, LOW, LOW);
String thermistor = codeWrite(8, HIGH, HIGH, LOW);
Serial.println(thermistor);
delay(1000);

EDIT:

The sketch should look like this:

void setup() {
  Serial.begin(9600);
  pinMode(4, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
  String lilyPad = codeWrite(6, HIGH, LOW, LOW);
  String thermistor = codeWrite(8, HIGH, HIGH, LOW);
  Serial.println(thermistor);
  delay(1000);
}

String codeWrite(int pin, char output1, char output2, char output3)
{
  digitalWrite(pin, output1);
  int A = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output2);
  int B = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output3);
  int C = digitalRead(pin);
  delay(11);
  String code = String(A) + String(B) + String(C);
}

The issue is the code can not be outside of a function.


Reading text from sd card is returning weird characters?

The text file is not ASCII, it is UTF-8. You will either have to convert it to pure ASCII, or write (or obtain) a conversion routine to approximate the UTF-8 characters using ASCII on the Arduino.

Maybe this can help you.


Try this:

unsigned long pressureOnTime; //millis() time when pressure switch is first turned on

const unsigned long ledOnAfterTimeThreshold = 300000; //5 minutes * 60 sec * 1000 mSec
int pressureThreshold = 1; //minimum analog reading from pressure sensor considered to be "on"

const int fsrAnalogePin = 0;
const int ledPin = 11;

int ledState = LOW;
int pressureState = LOW;

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

void loop() {
    checkPressureSwitch();

    //do other stuff here
}

void checkPressureSwitch() {
    if( analogRead(fsrAnalogePin) >=  pressureThreshold )
    {
        handlePressureOn();
    }
    else
    {
        handlePressureOff();
    }

    digitalWrite(ledPin, ledState);
}

void handlePressureOn() {
    if ( pressureState == LOW )
    {
        //pressure switch was off, but is now on
        pressureOnTime = millis();
        pressureState = HIGH;
    }

    else if ( millis() - pressureOnTime >= ledOnAfterTimeThreshold )
    {
        ledState = HIGH;
    }
}

void handlePressureOff() {
    ledState = LOW;
    pressureState = LOW;
}


Assembly for loop repeating 2 times when it's only suppose to do it once

The problem is that the register r17, which you use as a PWM timing
ramp, overflows twice every time you enter pwm_pre_loop:

when you increments it past 127, it overflows to −128
when you increment it past 255, it overflows to 0.

When using a counter the way you are using r17 here, you usually have
it overflow only once per cycle: either you consider it holds a signed
number which overflows from 127 to −128, or you consider it holds an
unsigned number which overflows from 255 to 0. I guess the latter is
more common. Your code is confused about that register's signedness:

The instruction brge (named “Branch if Greater or Equal (Signed)” in
the instruction set datasheet) tests the S (sign flag) bit of the
status register, which is useful for signed comparisons.
The instruction brlo (“Branch if Lower (Unsigned)”) tests the carry
flag, which is used for unsigned comparisons.

You should decide once on the signedness of the counter, and then use it
consistently. Since here unsigned makes more sense, you can just replace
brge by brsh (“Branch if Same or Higher (Unsigned)”).

Or better yet, remove the second test, which is redundant:

pwm_loop:
    lds r16, value
    cp r17, r16
    brsh off  ; if (r17 >= r16) goto off;
    rjmp on   ; else goto on;

Note by the way that you can name your RAM variables. And you can use
some of the other available registers instead of the RAM.


Why are MOSFETs only giving 8.1V for LEDs, not 12V?

By my calculations you are sinking 6 amps:

72 W / 12 V = 6 A

I have some doubt that the Arduino board is designed to handle that amount of current through its ground plane. Try running a separate ground wire to the MOSFET sources.

I would also be concerned about the gauge of wire you are using, and whether the prototyping board can handle that amount of current.


How to rotate 3 servo motors when 6 led lights are lit using EMG signals

Apart the problem you have (that the constants are not defined), what you are asking can be easily solved by looking at the servo library.

The servo library tells you that

You have to include the servo library header: #include <Servo.h>
You have to add a variable to hold the object: Servo myservo;
You have to attach the object to a pin: myservo.attach(SERVO_PIN);
Finally you can move the motor to any position (0 <= x <= 180) with the syntax myservo.write(val);

In your code, then, you have the variable litLeds which tells you how many leds are there. Particularly if you have 6 (or more) leds light you will move to 90°, while with 0 (or less - even if this is meaningless) you reset to 0. So the complete code is

#include <Servo.h>

int finalReading;
byte litLeds = 0;
byte multiplier = 1;
byte leds[] = {8, 9, 10, 11, 12, 13};
Servo myservo;

void setup(){
    Serial.begin(9600); //begin serial communications
    for(int i = 0; i < NUM_LED; i++){ //initialize LEDs as outputs
        pinMode(leds[i], OUTPUT);
    }
    myservo.attach(SERVO_PIN);
    myservo.write(0);
}

void loop(){
    for(int i = 0; i < 10; i++){    //take ten readings in ~0.02 seconds
        reading[i] = analogRead(A0) * multiplier;
        delay(2);
    }
    for(int i = 0; i < 10; i++){   //average the ten readings
        finalReading += reading[i];
    }
    finalReading /= 10;
    for(int j = 0; j < NUM_LED; j++){  //write all LEDs low
        digitalWrite(leds[j], LOW);
    }
    Serial.print(finalReading);
    Serial.print("\t");
    finalReading = constrain(finalReading, 0, MAX);
    litLeds = map(finalReading, 0, MAX, 0, NUM_LED);
    Serial.println(litLeds);
    for(int k = 0; k < litLeds; k++){
        digitalWrite(leds[k], HIGH);
    }
    if (litLeds >= 6)
        myservo.write(90);
    else if (litLeds <= 0)
        myservo.write(0);

    //for serial debugging, uncomment the next two lines.
    //Serial.println(finalReading);
    //delay(100);
}

Please note that some defines are missing (e.g. the MAX, NUM_LED and SERVO_PIN)


Arduino Gesture Sensor error:No such file or directory

SparkFun made a poor choice for the folder structure of that repository. Likely this has caused you to incorrectly install the library. Please follow these instructions:

Download the latest release from https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor/releases. Currently it is https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor/archive/V_H1.0_L1.4.2.zip.
Unzip the downloaded file.
Rename the folder APDS-9960_RGB_and_Gesture_Sensor-V_H1.0_L1.4.2/Libraries/Arduino to SparkFun_APDS9960. This is not absolutely necessary but "Arduino" is not a very descriptive name for a library folder and the Arduino IDE works best when the library folder name matches the primary header file name so this is best practices.
Copy the SparkFun_APDS9960 folder to {sketchbook folder}/libraries. You can find the location of the sketchbook folder at File > Preferences > Sketchbook location.
Restart the Arduino IDE if it's running (not necessary with recent versions of the Arduino IDE).

Note that the folder structure of this library requires Arduino 1.6.x or newer.

UPDATE: I submitted a pull request to put the library in an appropriately named folder. This won't change the instructions above until the next release but it does remove the need to rename the folder if you are cloning the repository or downloading from the tip of the repository rather than a release.


Ok, i found out the location.
In Win 7, it is C:\Program Files (x86)\Arduino\libraries


How to set CS pin on Beetle BLE/Bluno Beetle to Adafruit SD Card Breakout - Initialization Failed!

The ICSP header labels on the Wiki page are wrong. In the schematic here the ICSP header has the same pinout as other Arduinos. The legend doesn't match the picture on the Wiki page but is true:

ICSP1: Atmega 328P
ICSP2: CC2540

The ICSP header is the inner one. Is right on the pictures.
At pin 1 on board the corner of the white square around pins is skewed. The pins are from left to right first row Eeset, CLK, MISO, second row Ground, MOSI, 5 V.

pdf schematic for the board


Reproduce simulated temperature data with Arduino

You can use an array to go through the times.
Create a struct with the fields time and temperature (you should think about saving time as unix epoch, meaning seconds since 1970, so that you save memory).
struct SetPoint {
    unsigned long time;
    float temperature;
};

Then you can declare an array of type SetPoint to hold the tubles of time and temperature:
#define DATA_SIZE  720
SetPoint data[DATA_SIZE] = {
    {<time1>, <temp1>},
    {<time2>, <temp2>},
    ...
    };

In the above, you need to replace <timeX> and <tempX> by your data. Then declare a position variable, which the element index, which will be invoked next:
unsigned int pos = 0;

We are starting with the first element (index 0) and compare its time to the current time. If it is equal (or current time is after the elements time), we will set the thermostat to the elements temperature and increment the position variable. Something like this:
if(pos < DATA_SIZE && current_time >= data[pos].time){
    set_thermostat(data[pos].temperature);
    pos++;
}

Note: I used the variable current_time here as standin for your way of getting the current time, and the set_thermostat() function as a standin for your way of setting the thermostat. Also I inserted a check into the if statement, to prevent the code going further, when it reached the data array end.

That said, depending on the used board you can easily get into memory trouble here. An Arduino Uno does not have enough memory to save 720 of the data points above. float and unsigned long both take 4 bytes each, so 8 bytes per element, which makes 8*720 = 5760 bytes. The Uno only has 2048 bytes total in RAM. There are enough boards, which have more RAM. The ESP32 for example would have way enough (though there are many others; the ESP32 is just the first to get into my mind here).
Or you can add an SD card module to your build and save the data points in a file. That would also make it way easier to get the data in your project or change the data. It would just involving writing the corresponding file on your SD card.
Then the workflow would be a bit different. Lets assume you save one data point per line as text:

Open file and read one line. Close file.
Parse read text into 2 variables (time and temperature)
Use these variables for the if statement from above
if the time of the loaded data point was reached, open the file again, read the next line and parse it into the variables
The if statement now uses the next datapoint

and so on. If there is no line left to read, you could go into an infinite loop, stopping the code from running further than your data.
There are ready to use SD card modules to buy out there, and you can find many tutorials about how to use them online.

As Edgar Bonet correct stated in the comments, you can greatly reduce the needed RAM, when assuming regular intervals (3h in your case). Then you don't need to save the time for each data point. You only need the one start time for the series. Also above I used float for the temperature (as I assumed, that at this point it would be the easiest for you). But since temperature settings for thermostats are mostly working only down to the 1 digit after the decimal point, you can save memory space by using a different representation. For example you could save the temperature as a single byte signed integer with the unit of 0.1°C and a reasonable offset (for example 25°C being zero). So some example values would be:
Temp | value
------------
18°C | -70
20°C | -50
22°C | -30
25°C | 0
27°C | 20
35°C | 100

That would give you the precision of one digit after the decimal point and a range from 12.3°C to 37.8°C. When changing the factor of 0.1°C, you can also change the range (and precision with it) as you really need it.
So with the above you would only need 720 byte for the actual data, which is good for the Uno.
BUT: I would still suggest looking into the SD card reader. You will have more work building the project, but you won't have the same hassle with including or updating the data. That can come in especially handy, if you want to use to further use the device after the 3 months. Just loading new data on it (maybe even way more data, like for a full year) is easier with an SD card.


Unstable reading from pushbutton on digital pin

At the moment, your resistor isn't doing anything useful. When your switch is open, the pin is still 'floating', which means it's ending up with random stray readings from nearby electromagnetic fields.

You basically need two connections coming from your Arduino pin. One goes through a resistor straight to ground. The other goes through your switch straight to +5V.

In that case, the resistor is acting as a pull-down, because it holds your pin at Ground whenever the switch is open. You could swap over the ground and +5V, and it the resistor would function as a pull-up instead.

This question deals with the same kind of issue:

Button state changing randomly


Is setting AVR TWCR for mega328p TWEN in each function necessary?

The big difference is interrupt driven or busy wait implementation of the TWI hardware module protocol. Enabling interrupts is necessary in an interrupt driven implementation while busy wait should not enable interrupts.

A busy wait implementation is much simpler but it cannot be asynchronous. An interrupt driven implementation can be asynchronous and even power down the rest of the MCU during the TWI communication. It should be noted that the Arduino Wire class is interrupt driven but synchronous.

Cheers!


Michael's answer was good, as usual. Let me give you some more background though:

In C/C++ (And in most modern languages) variables have a "scope", or an area where they are defined.

Global scope:

Variables declared at the top level of your program have global scope, and exist for the life of your program. These variables are usually created on the .data or .bss sections.

Local scope

Variables declared inside a function have local scope. Unless they are static, they get created when the function is entered, and get discarded when the function exits. These variables are created on the stack as part of the function's stack frame.

Object scope

In C++ and other object-oriented languages, instances of objects have their own scope, "instance variables". Every instance of an object has its own set of instance variables. (Think of cars, and a car radio. You and I might own the exact same model of car, but if I set my car's radio station and you set your car's radio to a different station, each instance of the car has a different setting for the radio station.)

Static variables:

Static variables are variables that are declared "statically." That means that they are only created once and persist, even if they are declared inside a scope like a function or a class instance. These have the lifespan of a global variable but can be declared inside a function or in an object.

Loop is a function, so variables declared inside of loop() are local variables. They get created anew every time the function is called, and discarded every time the function exits.


To toggle LED you can do:

uint8_t BITval=1; //initialization B00000001

void toggle()
{
 digitalWrite(RED_pin,BITval&1);    //Bxxxxxxx1
 digitalWrite(BLUE_pin,BITval&2);   //Bxxxxxx1x
 digitalWrite(GREEN_pin,BITval&4); //Bxxxxx1xx

 BITval=BITval<<1;
 if (BITval== B00010000) //reset BIT value
    BITval=1;
}

And assuming you want to do bitRead() to read input from active-low push button which is connected to PORT-x, PIN-y

you can do:

if (bitRead(PORTx,PINy))==0)
toggle();


In my understanding all ic in general can be hardwired but at a cost which is that some greater expense is incured say time or additional accessories also the datasheet and instruction set are a big must


Updating a sketch to work with IDE 1.6.6

If I change prog_uchar to unsigned char in both max7456.h and max7456.cpp the hello world example sketch compiles.

In Max7456WriteTable change

Max7456::getCARACFromProgMem(i,currentChar); //Because the table is too big for ram memory

osd->sendCharacter(currentChar,i); //We send currentChar at address i.

to

Max7456::getCARACFromProgMem(tableOfAllCharacters, i,currentChar); //Because the table is too big for ram memory

osd->sendCharacter(currentChar,i, 0); //We send currentChar at address i.

0 is probably the wrong value, but at least it compiles.


Arduino Ping sensor with NewPing library

The main example sketch has this:

  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.

Your serial monitor is set to 9600 baud (bottom RH corner). Change that to match the setting in the sketch.


You have your SDA and SCL pins connected backwards.

SDA is A4
SCL is A5

You have it the other way around.


Missing bytes sended through serial from C# app

There's two basic things wrong here.

First is your way of opening the serial port and immediately sending data.  The Arduino is reset when you open the serial port and the bootloader runs. This takes a second or so, and during that time any data that you send is lost.

Secondly you're not checking for a flag of "W" but instead you're assigning "W" to the flag, which always succeeds.

The line

if (flag = 'W') {

should read

if (flag == 'W') {

To get around the first problem you can either just put a delay (however you do that in C#) after opening the port and before sending the "W", or you could implement a "Are you there?" handshake to look for the Arduino.

One example would be to add an extra flag of (say) "?" to which the Arduino simply responds "Y".

The PC then sends "?" and, if it doesn't receive "Y" within a certain timeout it loops sending "?" again.

Once it receives "Y" then it knows the Arduino is there and ready to receive data, so you can send the "W" command and the data.


data type error on sensor data to ethernet client

The code you posted is performing incompatible casts and by thus is sending garbage to client.println.

There is no automatic conversion in C/C++ from an array of integers (int inp[]) or longs, to a C style string char *. A C Style string should end with null terminator \0, and the one in your code doesn't. For example, in this line:

char *output = (char *) &inp[0];

The inp[0] contains the first integer. The expression &inp[0] contains the address of that integer in memory.

Thus the cast to (char *) will yield a malformed C style string, since it will not end with a null terminator, and more important, will not contain the data you expect it would (this cast is saying - "hey, compiler, note that the address of that int is actually the address of a C style string").

You can, however, utilize the String type constructor that receives int/long, and send the duration in order, something similar to:

        void getData()
        {
            ... // rest of the code here
            client.println(String(cmOne));
            client.println(String(cmTwo));
            ... // etc.
        }


Questions Concerning Arduino Compatible Boards

The Bluno is identical to the Uno, except the USB-to-serial chip, also supports BT. So it won't be a problem.


Unusual use of << operator... not a bit shift?

What exactly is << doing in this case?

It's directing the data into an output device (stream).

http://www.cplusplus.com/doc/tutorial/basic_io/

Yes, it's confusing using the same symbols for more than one thing...

  Moreover, F seems to never be defined prior to this.

F() is a macro. It's defined by the Arduino core in WString.h:

#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))


Using two pins to sum maximum available current

40mA is the absolute maximum current allowed. The recommended steady-state current is 25mA, so you'd need three or four IO pins to remain safe.

Theoretically, yes, that should be possible. However in practice doing such things is problematic.  You have to ensure that there is no point at which the sensor is being powered by less than the required number of IO pins, which means turning them all from off to on at the same time (doing them one at a time means you start with the full load through just one pin then start sharing it around). That means ensuring that all your pins are on the same port and using direct port manipulation to control all the pins at once.

It is far better, more reliable, and simpler to program, to just slip a simple p-channel MOSFET in there with a pullup on the gate to control the 5V power to the sensor. Pull the gate low and the sensor gets all the power it needs.


You are perfectly right, a class would help simplify your code. Here is
a tentative class that should work for what you are doing:

class Motor
{
public:
    Motor(const char *_name, Adafruit_DCMotor *_motor,
          unsigned long _runTime)
    : name(_name), startNow(false), running(false),
      runTime(_runTime), motor(_motor) { }
    void start() { startNow = true; }
    void update();
private:
    const char *name;
    boolean startNow;
    boolean running;
    unsigned long startTime;
    unsigned long runTime;
    Adafruit_DCMotor *motor;
};

Most of this is almost copy-paste from your actual code, except for your
runMotorX variables that I renamed startNow, which seemed more
appropriate.

Beware that the name of the motor is copied as a pointer. Thus you
should better call the constructor with a literal string (like
"the name") as a first parameter. Otherwise it would be more
appropriate to allocate memory and copy the characters themselves, but I
like to avoid dynamic memory allocation on an Arduino if I can.

Now, all the code that you have in loop() for each motor would be the
Motor's update() method:

void Motor::update()
{
    if (startNow) {
        Serial.print("Run ");
        Serial.print(name);
        Serial.println('!');
        startNow = false;
        motor->setSpeed(255);
        motor->run(FORWARD);
        startTime = millis();
        running = true;
    }

    if (running && (millis()-startTime > runTime))
    {
        Serial.print(name);
        Serial.println(" Time Elapsed!");
        motor->setSpeed(0);
        motor->run(RELEASE);
        running = false;
    }
}

With this class, your code would now look like:

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Motor m1("Motor 1", AFMS.getMotor(1),  5000);
Motor m2("Motor 2", AFMS.getMotor(2), 10000);
//etc etc etc up to 10 Motors

void setup()
{
    Serial.begin(9600);
    AFMS.begin();
    m1.start();
    m2.start();
}

void loop()
{
    m1.update();
    m2.update();
}

Of course, when you get to 10 motors, this would still be annoying
repetition. You can simplify further by putting the motors in an array
and looping through it:

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Motor motors[] = {
    Motor("Motor 1", AFMS.getMotor(1),  5000),
    Motor("Motor 2", AFMS.getMotor(2), 10000)
    //etc etc etc up to 10 Motors
};
#define NUM_MOTORS (sizeof motors / sizeof motors[0])

void setup()
{
    Serial.begin(9600);
    AFMS.begin();
    for (unsigned int i = 0; i < NUM_MOTORS; i++)
        motors[i].start();
}

void loop()
{
    for (unsigned int i = 0; i < NUM_MOTORS; i++)
        motors[i].update();
}


Flash Arduino Micro code on Atmega32U micro controller

To get your chip to respond to the Arduino environment over USB you need a booloader (some extra code) to be running on the Atmega32.

To install the bootloader you can use another Arduino as a programmer to the ICSP pins (or any other AVR ICSP programmer).
This procedure and description from Sparkfun for the Arduino Pro will help you.

This may help you understand the ICSP aspect, again from Sparkfun.


On the page that you cite they say

If, say, you need MORE blinky, you can chain these together.

For the second shield, connect the DIN connection to the first panel's DOUT.
Also connect a ground pin together
and power with 5V.
There you go!

You can chain as many as you'd like although after 4 or more panels you may run low on RAM if you're using an UNO. Watch your power usage too, you may need a 5V 10A power supply for so many of these!

Related:

They also say:

There is a single data line with a very timing-specific protocol. Since the protocol is very sensitive to timing, it requires a real-time microconroller such as an AVR, Arduino, PIC, mbed, etc. It cannot be used with a Linux-based microcomputer or interpreted microcontroller such as the netduino or Basic Stamp.

Our wonderfully-written Neopixel library for Arduino supports these pixels! As it requires hand-tuned assembly it is only for AVR cores but others may have ported this chip driver code so please google around.

An 8MHz or faster processor is required.


EEPROM can't store string. It stores numbers.  put() takes a type and stores that type as numbers.
The char[] isn't a string - it's a number. More specifically it's a memory address for where the string data is stored.
All you're doing is storing that memory address, not the data itself.
Instead you need to iterate over your string. You should also store the length of the string if it's going to be variable.
For example:

void storeString(const char *str) {
    EEPROM.write(0, strlen(str)); // Store the string length
    for (int i = 0; i < strlen(str); i++) {
        EEPROM.write(i + 1, str[i]);
    }
}

void getString(char *str) {
    int len = EEPROM.read(0);
    for (int i = 0; i < len; i++) {
        str[i] = EEPROM.read(i + 1);
    }
}


Binary to decimal using bitwise operators

You cannot do what you are trying to do. There is no direct correspondence between some number of bits and a decimal digit.

With hexadecimal, every 4 bits corresponds to exactly 1 hex digit. That is why hex is used for computers.

One hex digit represents exactly 4 bits. Every time you add another hex digit, you add 4 bits.

Two hex digits corresponds to exactly a byte. 00h to FFh represents a value from 0 to 255.

There is no such direct correspondence between binary and decimal. If you have 4 bits, it takes 1 or 2 decimal digits to represent it (0-15) If you have 8 bits, it takes 1, 2, or 3 decimal digits to represent it, but there are 3 digit decimal values (values > 255) that you can't represent with 8 bits.

Binary  Hex Decimal
0000    0   0
0001    1   1
0010    2   2
0011    3   3
0100    4   4
0101    5   5
0110    6   6
0111    7   7
1000    8   8
1001    9   9
1010    A   10
1011    B   11
1100    C   12
1101    D   13
1110    E   14
1111    F   15

You simply cannot convert a binary number to decimal using bit shifting and masking.

As @Kwasmich says in their answer, the closest you're likely to come would be to convert your binary value to BCD (Binary coded decimal) where each 4 bits holds a decimal digit. You could convert THAT to decimal character output using masking and shifting.


I need to send 20V to the inputs of my machine. How is it possible

You need some form of power supply for that. It is not possible to
send 20 V from the Arduino directly.

  I know that my company does it without external power supply

Then you misunderstood something about either the electrical interface
of the machine, or about how your company connects it to the Arduino.

One possibility is that the machine inputs are 20 V logic with
built-in pull-up resistors. This kind of input is normally meant to
be driven by an open collector output. If this is the case, then you
can drive those inputs from the Arduino through a transistor (either an
NPN or an N-channel MOSFET) with no external supply.

But this is only a guess. What you really need to do is read the
datasheet of the machine and see how those inputs are meant to be
driven, at the electrical level. It may be more efficient to find
someone at your company who knows already and can explain that to you.


HLW8032 UART sends random data ( Registers Overflow often)

First of all I swaped UART0 to GPIO15 (TX) and GPIO13 (RX), (Luckily the Tx of HLW8032 is connected to GPIO13 in my hardware design and This is the UART0 RX pin after swap). Then I analyzed the data coming and the results were the same as of that SoftwareSerial i.e the registers overflows.

Then I used an HLW8032 Library (Which I've forked and will make changes for improvements) which only works on HardwareSerial, and the values are perfect. The way the library reads Serial is quite different.

So in short my issue resolved using two things:

I swaped UART0 to GPIO15 and GPIO13 using Serial.swap()
Used a library for the HLW8032

Thanks to @Juraj who provided the useful link about Serial Swap in ESP8266.

  Serial uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX). Serial may be remapped to GPIO15 (TX) and GPIO13 (RX) by calling Serial.swap() after Serial.begin. Calling swap again maps UART0 back to GPIO1 and GPIO3.

#include "HLW8032.h"

HLW8032 HL;

void setup()
{
    HL.begin(Serial,4);
    Serial.begin(4800);
    Serial.swap();
}

unsigned int V;
void loop()
{
    HL.SerialReadLoop();

    if(HL.SerialRead == 1)
    {
    V = HL.GetVol();
    }
}

With this I can't print and see my debug prints on  GPIO1 (TX) and GPIO3 (RX), but at least without changing a bit in the hardware, my design works fine.


You are saving a String object in EEPROM, which is useless. A string
object does not store the contents of your string. Instead, it just
stores:

the memory address where the actual contents (the characters) is
stored
the amount of memory allocated for this contents
the number of characters that actually make the string

This is what you are storing to, and retrieving from EEPROM. So you get
the correct number of characters (third item in the list above), but the
memory address now points to uninitialized RAM.

I suggest instead storing in the EEPROM a raw C string, i.e. an array of
8 chars (7 printable chars plus the terminating NUL). You could achieve
this by just changing the declaration of serial_number:

char serial_number[8];

For checking the validity, I would just check that it starts with "SN-"
and the last char is a NUL:

if (memcmp(serial_number, "SN-", 3) == 0 && serial_number[7] == '\0') {
    ...
}

You could do a more stringent validation though, and check that the
other 4 chars are within the valid set.

Edit: to build serial_number with random chars:

strcpy(serial_number, "SN-");
for (int i = 3; i < 7; i++)
  serial_number[i] = serial_characters[random(0, 36)];
serial_number[7] = '\0'; // terminating NUL


In the loop:

// attempt to connect to Wifi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

Can you add Serial.print(status); before the delay so you can see if any of these arise:

WL_IDLE_STATUS = 0
WL_NO_SSID_AVAIL
WL_CONNECT_FAILED
WL_CONNECTION_LOST
WL_DISCONNECTED

They are defined in wl_definitions.h


You could do a checking routine. For example, if you are detecting motion you can connect the vcc pin of the HC-04 to a digital pin and turn it on and check for changes once every 10 seconds.


Shift Register 74HC595 circuit working weirdly

I presume that you are referring to this tutorial, and this code.

The clockPin of Arduino should be connected to pin 11(SH_CP) of 595, dataPin to pin 14(DS), and latchPin to pin 12(ST_CP).

Swap the values of clockPin and latchPin in your code, and you should be good to go.

// SH_CP; 11
const int clockPin = 10;
// DS; 14 (not 15)
const int dataPin = 8;
// ST_CP; 12
const int latchPin = 9;


It could be the ESP8266, try physically separating the DHT11, but I'm guessing that that will only help slightly.

Do you have some way of reliably calibrating the sensors? If not, then even if you are getting consistent readings, you'll have a hard time knowing how accurate your readings are.

While they're typically more expensive, it might be prudent to buy an infrared temperature sensor. If you have the budget, replacing the DHT11s with IR temperature sensors might just be a better solution, I saw that Sparkfun's MLX90614 was accurate within +/- 0.5 degrees Celsius. If you don't have the budget to replace your DHT11s, or don't want to be wasteful, perhaps you just buy one IR temperature sensor to use as a sanity check. These should be more reliable than DHT11s and you could even write a sketch to calibrate them based on the IR temperature sensor's readings.


Why does my servo execute an action in the beginning when the odds are almost 0?

Recognise that, despite the name, random() does not produce a truly random number. Because a computer is basically determinate, every time random() is called it produces results in a fixed sequence - it is possible that this sequence includes 0 or 1 straight away.

If you want it to start at a different point, you need to "seed" the random number generator by calling randomSeed() and passing in an integer. Note that it can't be the same integer every time - that would just move the sequence to the same point every time. The Arduino reference for random() suggests reading an unconnected analog input with analogRead() (which would produce different numbers at different instances in time) to "seed" the random number generator with a new starting position.

randomSeed(analogRead(A0)); // Seed random() with random starting point


I've just sorted things out.
There is two interfaces - ISP and JTAG. ISP is busy with programmer everytime, but JTAG is free.
So, I have found pinout of JTAG interface and achieved GND.
There is pinout:

(source: digital-circuitry.com)


Using an esp8266, how can I create a circuit to measure 2 different analog inputs (not simultaneously) with only one ADC pin available (A0)

There's two basic solutions, both of which require the addition of an external chip:

Use an analog multiplexer to select the different devices to connect to the ADC input
Use an external (I2C or SPI) ADC chip. These can give you higher resolutions than the internal ADC and many more inputs (depending on the chip you choose).

My recommended solution would be to get an external ADC chip.


The i2cdevlib has that declared in this file: https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/examples/MPU6050_DMP6/MPU6050_DMP6.ino

That is the "dmp" example.
Inside the MPU-6050 sensor is a "dmp" and a FIFO buffer. The "dmp" is a processing unit that collects the sensor data, does some calculations and puts the data in the FIFO buffer. After that the Arduino is signalled with a interrupt.

In the Arduino, in the interrupt routine, the flag 'mpuInterrupt' is set. In the loop() that flag is checked and the amount of data in the FIFO buffer is read. When there is enough data, that data is read and used in the sketch.

Since the variable 'mpuInterrupt' is used in a interrupt routine and in the loop(), it is made 'volatile'. That tells the compiler that the variable can change at any moment, so the compiler can keep that in mind when creating binary code for the loop().


Long term stability of bluetooth connections

Bluetooth communication works with fixed time intervals that both communication partners have to agree during the advertising and connection phases. Such an agreement could be: "While connected, lets' meet every second. If one does not show up during 3 meetings, let's leave the connection state".

From this you can see that timing is a very important factor in bluetooth communication. So both communication partners need a very accurate clock. No two clocks have exactly the same speed, one is always lagging the other.

It could be that one or multiple of the clocks of your HC-05's do have too much clock drift, so the connection will be lost. Maximum clock deviation allowed for a bluetooth clock is ±40 ppm (i.e. ±40 parts-per-million!) over the entire temperature range.

You could check this theory with multiple HC-05s. If individual modules lead to individual connection lengths, then this could be your problem.


The simplest method is to keep it as a fixed format string with line termination.

Read one line in from serial into a character array (aka C string) and then chop it up.  As long as the string is in the correct format you can easily chop it around.

For instance, assume you chose the format YYYY-MM-DD HH:MM:SS\n which is quite common and easy to use, you may have data like this:

char *indata = "2015-08-22 17:23:48\n";

(\n is the new-line character)

Using simple char pointers you can get each substring quite easily:

First slice the string up into the component parts by replacing the separator tokens with character 0:

indata[4] = 0;
indata[7] = 0;
indata[10] = 0;
indata[13] = 0;
indata[16] = 0;

Then you can assign pointers to each segment:

char *year = indata;
char *month = indata + 5;
char *day = indata + 8;
char *hour = indata + 11;
char *minute = indata + 14;
char *second = indata + 17;

Or if you want it as integers, you can pass it straight to atoi:

int year = atoi(indata);
int month = atoi(indata + 5);
int day = atoi(indata + 8);
int hour = atoi(indata + 11);
int minute = atoi(indata + 14);
int second = atoi(indata + 17);

In fact, if passing it direct to atoi() you shouldn't need to even do the first stage, since it will stop parsing at the first non-numeric character.

There are more flexible ways of parsing the string too, using strtok(), but that is somewhat more advanced.

Note that this method is highly intolerant to invalid strings being passed, so you may want to first ensure that a) the string is the right length, and that b) there are the right separator tokens in the right placed, to validate that the string is properly formatted before proceeding.


If Watchdog timer is the cause of reset that means there is at least one place in your code that runs too long without allowing subsystems to do the background tasks. It might be possible the part of your code causing the problem is:

while(!Serial) ;

Instead that loop use:

while(!Serial)
  delay(100);

so the background tasks will get the chance to be exectuted during the while loop.

EDIT:
In fact you can completely remove that while loop as it is not necessary. There is a possibility !Serial is always true so the loop never ends. And I suggest you using 74880 instead of 115200 so you can see the debug messages sent automatically by ESP8266.
END OF EDIT

However, if that is not the part of the code that causes the problem (and I think it is not) then the problem might be for loop where you list networks. You can check if that is the problem by adding a small delay inside the loop as follows:

for (int thisNet = 0; thisNet<numSsid; thisNet++) {
  delay(1);
  Serial.print(thisNet);
  Serial.print(") ");
  Serial.print(WiFi.SSID(thisNet));
  Serial.print("\tSignal: ");
  Serial.print(WiFi.RSSI(thisNet));
  Serial.print(" dBm");
  Serial.print("\tEncryption: ");
  Serial.println(WiFi.encryptionType(thisNet));
}

If the problem will still exist then you can add a few more delay(1); statements through the code.

Instead of delay you may use yield(); which is the same as delay(0);.


How to properly reverse DC motor direction with 2 limit switchws

void loop() {
  tilt_up();
}

void tilt_up()
{
...
  if (digitalRead(sw2State == LOW)) {
    tilt_down();
...
  }
}

...

void tilt_down()
{
...
  if (digitalRead(sw3State == LOW)) {
    tilt_up();
...
  }
 }

You are recursing here. loop calls tilt_up which eventually calls tilt_down which calls tilt_up and so on until you - rather quickly - run out of RAM.

Rewrite so that you are not doing that.

Also see what @MikaelPatel told you in your other question. You have the brackets in the wrong place.

  if (digitalRead(sw2State == LOW)) {

should be:

  if (digitalRead(sw2State) == LOW) {


Why does a light bulb activate an infrared sensor? Is there a way I can filter this out?

Yes, a light bulb will put out some infrared light.

Decoding remote control signals isn't that hard - there is a tutorial at instructables - http://www.instructables.com/id/The-Easiest-Way-to-Use-Any-IR-Remote-with-Ardiuno/?ALLSTEPS

This also means you can tell the difference between different buttons.

P.S. - when posting in this forum, it helps to include your code and your wiring.


Sparkfun CCS811 Air Quality Sensor is just not workin

You need to solder those headers to the breakout. Just inserting them into the plated-through-holes doesn't give a reliable connection.


What sensors can measure 3-axis acceleration?

The acceleration sensor i found was sensors that measured the gravity on 3-axis of the sensor

Gravity is acceleration.

An accelerometer measures acceleration - or more accurately, it senses the resistance to acceleration (inertia) and equates that to acceleration.

By holding an accelerometer still you are causing it to resist the pull of gravity, and it's that "resistance" that it measures - a constant 9.8m/s²

If you let the accelerometer freefall it won't be resisting gravity any more, and will measure 0 for the Z axis.

So you simply have to "ignore" gravity, by removing that constant 9.8m/s² ("1g") of acceleration from the Z axis.  And you do that by simply subtracting it.

It is normal to calibrate an accelerometer by keeping it at rest and reading the "idle" values. Those values are then subtracted from the readings to give you the actual value.


Go for the manufacturer of this board website i.e. www.gravitech.us. You can get the eagle files and all the data you need. Alternatively, you can download the eagle file of nanov3 directly using this link: http://site.gravitech.us/Arduino/NANO30/ArduinoNano30_Eagle.zip


How to Set RTC in ES32 using NTP server?

this snippet from setup() sets on esp32 the NTP for internal RTC and uses epoch seconds to set time to TimeLib library.
  configTime(gmtOffset_sec, daylightOffset_sec, "pool.ntp.org");
  time_t now = time(nullptr);
  while (now < SECS_YR_2000) {
    delay(100);
    now = time(nullptr);
  }
  setTime(now);

The ESP32 examples library in IDE examples folder has example SimpleTime.


Why it shows d2 was not declared in scope

Arduino pins are defined only by a simple number, with the exception that the analog pins are also named as 'A0' through 'A8' (or however many analog pins the specific processor has). Thus, D2 is not defined. If you mean to refer to Arduino pin 2, its name is just '2'. So:
#define ONE_WIRE_BUS D2  ->  #define ONE_WIRE_BUS 2


WiFiSSLClient will not connect to servers with LetsEncrypt certificates

The solution is to update the certificates the WIFI 101 Firmware Updater tool (in the Arduino IDE).

Install the FirmwareUpdater sketch, as described on the Arduino site.
Select Tools -> WiFi 101 Firmware Updater. Click on the Add domain button at the bottom, enter your domain and click Upload Certificates to WiFi module.

Upload the sketch to your Arduino. It should now connect to the server.


What design patterns can I use to handle user input and display updating?

The answer depends on exactly how the sketch is meant to respond to the user interaction.

External interrupts
If the interaction depends on responding very accurately to the rising or falling edge of an input event (as in your example), then an external interrupt may be the way to go, if possible.

This is particularly important if the input event might be shorter that the duration of a call to loop(). If that happens, consecutive attempts to poll the input could completely miss the state change. It's quite rare for a user input event to be that short though, unless loop() is quite slow to execute.

External hardware to get help that though, e.g. by having an input which latches until it is read and reset by the microcontroller.

Improving polling frequency
External interrupts often aren't possible (e.g. because the chip only supports a limited number), or they are simply overkill/unnecessary for a given application.

In those cases, it may still be possible to improve the timing precision when using polling. One option is to split up all the different parts of the main loop into separate functions. On each successive iteration of loop(), it will call the next function, and then wrap round to the first. In between each of those functions, it can poll the button. Here's a simple example:

unsigned int g_section = 0;

void setup() { }

void pollButton()
{
    //...
}

void runSection0()
{
    //...
}

void runSection1()
{
    //...
}

void runSection2()
{
    //...
}

void loop()
{
    // Poll the button on every pass:
    pollButton();

    // Execute the next section of the main code:
    switch (g_section)
    {
    case 0: runSection0(); break;
    case 1: runSection1(); break;
    case 2: runSection2(); break;
    }

    // On the next iteration, run the next section:
    if (++g_section > 2) g_section = 0;
}

One important issue with this approach is that it's very difficult to make each of those runSectionX() functions take the same execution time. That can result in the button being polled inconsistently from one iteration to the next. If it's fast enough though, then it shouldn't be too big of a problem.

Display update
Updating a display is unfortunately often quite slow, compared to many other operations. That means you need to be quite careful where you do it. Inside an Interrupt Service Routine often wouldn't be appropriate, as that could introduce other timing issues in your sketch.

Realistically, you'd have to do it in the main loop. If you absolutely have to run it quickly though, then it can be included in the faster polling example I've given above -- i.e. update the display on every iteration, the same as polling. You have to be careful to avoid partial updates though.


How to pass rx/tx led outputs to a shield

The TX/RX LEDs on the Uno are not connected to the main MCU but are instead connected to the USB communication chip, be it a FTDI or ATmega16U2. You would need to solder wires to the appropriate connections on the board and then connect them to the shield in question.


Triggering the push button on the analog input of the L293D motorshield

As noted in Nick Gammon's comment, digitalWrite(btnleft, INPUT) (etc.) would make a lot more sense than does analogWrite(btnleft, INPUT) (etc.).

Edit: INPUT is a constant defined in wiring.h (as in following extract), and is intended for use in pinMode() calls that set an IO pin's mode to one of INPUT, OUTPUT, or INPUT_PULLUP.  It's inept to use it in a call of either digitalWrite() or analogWrite().

    #define HIGH 0x1
    #define LOW  0x0
    #define INPUT 0x0
    #define OUTPUT 0x1
    #define INPUT_PULLUP 0x2

Note that digitalWrite to an input-mode pin leaves the pin in input-mode, while an analogWrite to an input-mode pin changes the pin to output-mode.

When you want a pin to be input-mode with pullup, it is simpler to use INPUT_PULLUP as the mode parameter, rather than using two separate calls.  That is, instead of saying pinMode(pin, INPUT); followed by digitalWrite(pin, HIGH);, just say

pinMode(pin, INPUT_PULLUP);


No change in acs 712 readings after connection to load

For such light and low-voltage loads you wouldn't normally use a mains rated high current amplifier like this.

Instead you would just use a simple shunt resistor in the low-side of the circuit:

simulate this circuit – Schematic created using CircuitLab

The voltage dropped across the resistor (and hence the voltage you will read on A0) is proportional to the resistance of the resistor and the current flowing round the circuit.

You want the resistor to be small enough that it doesn't overly affect the operation of the circuit, yet large enough that it drops a voltage you are able to sense at enough resolution.

For example the 1Ω resistor above, with 333mA round the circuit (3W at 9V) would drop (V=IR) 0.3 * 1 = 0.3V.

While that's not a very high voltage it's small enough to not really affect the circuit, and you can increase the sensitivity of the Arduino by using the 1.1V internal reference instead of relying on the default 5V external Vcc voltage:

analogReference(INTERNAL);

Or on the Mega2560:

analogReference(INTERNAL1V1);


OSC is such a simple format that I ended up ditching libraries entirely, and just parsing the UDP packets directly with a state machine.  Just learn the wire format of the bytes and parse the state machine explicitly.

It's just a trivial function calling format.  The message starts with a 32-bit padded zero terminated string (important!) for the method name.  I am not sure if the type tag is mandatory but it was always being sent (ie: ",iff"), then the binary values corresponding to what type tag says - like bigendian int32,float32,float32.

This was related to OSC generated by ChucK, SuperCollider, and CSound.

Real optimizations would come just from the design of the protocol itself.  You will need to assume that any UDP packet can be dropped.

You are sending motor changes as diffs from current position, so you need to handle packet drops somehow.  (ie: Do you have a TCP-like mechanism?  Do you change the design to send absolute motor positions so that position reports are idempotent and subject to re-broadcast?  Do you ack message receipt individually, or do you periodically poll the device for its current state?)


_delay_ms() is much slower than expected (by a factor of 6) on TinyAVR 0/1 (ATTiny1604)

Your toolchain is not broken. In the ATTiny804/1604 datasheet, page 77, it shows the CPU clock is divided from the 20/16 MHz oscillator by a prescaler (the ATTiny1614 datasheet shows the same clock prescaler in page 80. So it's a feature found in both tinyAVR 0/1 microcontrollers).

Source: Microchip ATTiny804/1604 datasheet, fair use.
The datasheet says...

10.3.3 Main Clock After Reset After any Reset, CLK_MAIN is provided by the 16/20 MHz Oscillator (OSC20M) and with a prescaler division factor of 6. Since the actual frequency of the OSC20M is determined by the Frequency Select bits (FREQSEL) of the Oscillator Configuration fuse (FUSE.OSCCFG), these frequencies are possible after Reset:

16 MHz ---> 2.66 MHz
20 MHz ---> 3.3 MHz

By default, the division factor is 6. It means the CPU is actually running at 3.333 MHz when the OSCCFG fuse is programmed to 20 MHz.
Solution
Use the correct F_CPU
If a slower CPU is not a problem to you, you can simply report the correct CPU frequency to the compiler by change #define F_CPU 20000000UL to #define F_CPU 3333333UL.
Or disable frequency division
Alternatively, you can disable the frequency division and run the CPU at its 20 MHz full speed.
#define F_CPU 20000000UL

int main(void)
{
    /* Set CPU clock to 20 MHz */
    _PROTECTED_WRITE(CLKCTRL_MCLKCTRLB, 0);

    /* your code */
}

But don't overclock the CPU
Nevertheless, you should note that 20 MHz operation is only guaranteed by Atmel at 4.5 V and above. If you are running the microcontroller at a lower voltage, such as 3.3 V, you are overclocking the CPU by putting it outside the safe operating area designated by Atmel. See datasheet page 473.

Source: Microchip ATTiny804/1604 datasheet, fair use.
Although an overclocked microcontroller will probably work, and in a hobby project, you are unlikely to see any issue. But still, at this point there is no guarantee of stability from the manufacturer. For example, the microcontroller is officially rated at 105°C, but an overclocked microcontroller may start crashing. Increased power consumption is also likely. The worst possible problem could be mysterious malfunction under certain rare conditions. Thus, if reliability and stability is important, you should not overclock the microcontroller.
At 3.3 V, given a 20 MHz system clock, the CPU should only operate at 10 MHz by setting the prescaler to 2x. And at 1.8 V, at 5 MHz with a 4x prescaler.
/* Set CPU clock to 10 MHz */
_PROTECTED_WRITE(CLKCTRL_MCLKCTRLB,
                 CLKCTRL_PDIV_2X_gc | CLKCTRL_PEN_bm);

/* Set CPU clock to 5 MHz */
_PROTECTED_WRITE(CLKCTRL_MCLKCTRLB,
                 CLKCTRL_PDIV_4X_gc | CLKCTRL_PEN_bm);


Do all serial ports on an Arduino MEGA 2560 have the potential to "brick" attached items when being flashed?

In the Sparkfun example the Arduino Uno is used. The Uno has only one hardware serial port, and that is used to upload a sketch and for the serial monitor. Pin 0 (RX) and pin 1 (TX) can be overriden for something else. However, then you must know what you are doing, and connect and disconnect modules as required.

The Arduino Leonardo and (Pro) Micro use a USB CDC implementation and have a unused hardware serial port at pin 0 and 1.

The Arduino Mega 2560 uses the hardware serial port at pin 0 and 1 to upload a sketch, just as the Uno. However, the three other hardware serial ports are not used, and you are free to use them.

If you use an unused hardware serial port for the OBD-II, there is no risk at all. You can use that port and nothing else messes with that port.

If you use a serial port that is also used to upload a sketch, or a software implementation of a serial port, you probably are going to make a mistake some day, and there is a risk to send the wrong data to the wrong hardware.

[ADDED]
I see that the example code in the SparkfunHookup Guide uses the Arduino Uno and SoftwareSerial on pin 2 and 3. That is independent of the hardware serial port. The SoftwareSerial is something that should be used as a last resort, since it almost completely takes over the Arduino board. It's good to have SoftwareSerial, but try to avoid it.
If you do want to use an Arduino Uno, perhaps the AltSoftSerial can be used. The AltSoftSerial works okay for 9600 baud as long as no other code uses too much time in interrupts and no one else uses TIMER1.


The shield is very different to the real Yun when it comes to serial communication.

Typically the Atheros's UART is mapped to pins 0/1 of the shield for communication with the board it is plugged in to. Those pins are also the pins you use to communicate with the PC, so the normal YunSerialTerminal sketch can't be used.

Instead you will have to lift those pins out of the socket they go into (depending on the shield you may just be able to bend them slightly) and then manually connect them (along with ground) to an external USB to UART adaptor (e.g., FT232) to use for the communication.  Nothing needs to be installed into the Arduino board since that is now just being used as a power supply.

See this answer for which pins to use to run the shield stand-alone.


The code fails to generate the values I want, when both trigger pins 2, 3 are high or low. Why?

To send anything to serial you need to initialize it first with:

void setup()
{
    Serial.begin(115200);
    //other code
}

And you are using wrong quotes for the string.
They should be double quotes " not single ones '.

Also you could simplify your code, if you removed the third if, since it's just checking the already known state at that point.

You should also read the button state only once, save them into a variable and then just compare those variables.

bool button1_state = digitalRead(2);
bool button2_state = digitalRead(3);
if (button1_state && !button2_state) {
    infra();
}
else if (!button1_state && button2_state) {
    red();
}
else {
    Serial.println("help");
}


Making three led's blink at different times in Arduino

Using a 220k Ohm resistor will lead to approximatively 20µA to light the LED. This is not enough to light the LED, you should replace the resitor by one of value 330Ohm (220 to 470 could be OK depending of the LED)


Arduino Leonardo as USB Keyboard with WiFi module

Its always very unlikely that someone will have done exactly the same project as you, which is why you need to break it down.

You want to talk to an Arduino over Wifi.
You want he PC to send commands to the Arduino.
You want to make the Arduino act as a keyboard.

I know each of those three parts in on this site, so that should help answer a lot of questions on how to do it, but obviously some of the solutions may conflict so you'll have to discard them.

You can use an ESP8226 - the Arduino talks to it via serial (software serial).
You will need an application (c# will be easiest for Windows) that will send data to the Arduino.  You need to design and implement a protocol, using REST may be a good idea.
I've never done it and don't know how, but I think I read there is a HID Library (Human Interface Device aka Keyboard or rat) and that makes thinks easier.

As to what hardware you could use there may well be performance constraints, that affect what hardware you can use.  I suspect the lower spec Arduiano's may introduce a lag that may not be acceptable.  Since you want to do it over Wi-Fi, you might want to have a look at the ESP8226, which can be programmed like an Arduino and has native Wi-Fi.  I'm not sure if you can use it as a HID though.


WatchDog on Arduino Nano - does not recover

This works on an Uno R3.

The sketch restarts every 4 seconds when wdt_reset() is commented out.

Please copy the code and try it.

  #include <avr/wdt.h>

  void setup() {
    pinMode(13,OUTPUT);
    digitalWrite(13,LOW);

    delay(50);
    digitalWrite(13,HIGH);    // flicker the LED to identify when setup() is running
    delay(50);
    digitalWrite(13,LOW);
    delay(50);
    digitalWrite(13,HIGH);
    delay(50);
    digitalWrite(13,LOW);
    delay(50);
    digitalWrite(13,HIGH);
    delay(50);
    digitalWrite(13,LOW);
    delay(50);

    wdt_enable(WDTO_4S);

  }
  void loop() {
    digitalWrite(13,HIGH);
    delay(500);
    digitalWrite(13,LOW);
    delay(500);
    //wdt_reset();
   }


Which type of sensor should i use to get RPM of an engine?

I would think something like this would benefit you greatly. If your vehicle was produced after 1996 it will have an OBD port near the steering wheel that allows you to read diagnostic information from the car. This diagnostic information always includes error codes (think: Check engine light), and often includes operating information like speed and engine rpm.


To print the serial number in hex Serial.println accepts a format parameter:

Serial.println(cid.psn, HEX);

The cid variable is a struct so you can access the the other fields via the structure. But if you really want to access the raw bytes you could cast cid to a pointer then access the individual bytes:

uint8_t *rawcid = reinterpret_cast<uint8_t*>(&cid);
Serial.println(*(cid+3), HEX); // print the 4th byte

Be aware that casting like this can be tricky and you will likely shoot yourself in the foot more than once.


Are there different revisions of Arduino Uno SMD?

The only difference with the SMD Uno is the fact you can't remove the chip. There are also 2 extra analog comparators not connected to anything.

The SMD boards are compatible with the thru-hole boards, but they have SMD components, which apparently make them easier to make and cheaper. As I said before, the two extra analog inputs (A7 and A6) are left unconnected on the official boards.

Here is my Uno R3:


analogRead returning 0 constantly when connected to joystick

Follow these steps to identify the problem.

Disconnect A0/A1 from Arduino and use a multimeter to check the voltage coming from the joystick X and Y. If it swings from 0 to 5V....the problem is in the Arduino. Check your code and connections. Maybe your wires are damaged?
If the voltage is not changing at X and Y pins, disconnect power from the joystick and use a multimeter to check the joystick potentiometer. Check all three terminals in each axis of the joystick. If R is the measured resistance between the two outer pins, then the resistance between the central pin and each of the outer pins should vary from 0 to R depending on the position of the joystick.
If there is no problem at all with the joystick readings by potentiometer then the problem has to be on the Arduino side.


You have to divide this project in separate steps:

Use a GPS to get the coordinates
Send the GPS coordinates via the nRF24L01 to the 'controller'

Possible limitations:

GPS only works outside; otherwise use gyro/compass etc as addition
Range limitations
Power limitations

If you don't want to use GPS, you might be able to use 2 nRF24L01s which send a signal at exactly the same time, track it with a third one (attached to the object), calculate the difference in times and based on that calculate the distance to both other nRF's and calculate the position. You might even need a third sender.

Of course this is quite tricky, like synchronization of time between messages and the need for multiple nRF's, also at different distances/directions to be reliable.


Both v and vref are integers, which means that integer division will be performed. if v is ever less than vref then the result will be 0. Multiply first, then divide.


Different boards operate internally at different voltages. This is dictated by the main chip on the board.  That main internal operating voltage is also the voltage at which the IO pins operate.
Most "old" Arduino boards operate at 5V.  This includes, but is not limited to:

Arduino UNO
Arduino Mini
Arduino Leonardo

Newer more powerful boards, many made by other companies, operate at 3.3V. Again, this includes such boards as:

Arduino DUE
Arduino MKR1000
Teensy boards (v3.0+)
chipKIT boards
ESP8266 & ESP32 boards

Some boards come in variants that give either voltage - the most notable being the Pro Mini boards from Sparkfun.  These come in both 5V and 3.3V variants and it is important to pick the right board for your needs.
In general, though:

If it's 8-bit and runs on an ATMega chip it's likely 5V unless otherwise stated
All 32-bit boards will be 3.3V unless otherwise stated.


Arduino Uno (or Teensy 3.2) programmatically powering an external USB connection

I'm not aware of any off the shelf "shields" which would accomplish this goal.  Since you do not seem to want your Arduino device to play either the USB host or client role, but rather to interrupt power to a difference device, a traditional USB shield is probably not going to help.

Rather it would be useful to look at how the small minority of USB hubs that implement software control of downstream power on a port-by-port basis do it - USB allows for this, but doesn't require it, and most hub ICs have output pins to drive power switches, but don't include them.

Switching the 5v USB VBUS needs to be a done with a "high side switch" - a P-channel MOSFET would be an obvious candidate, but it has been historically harder to find good ones.  Some time ago I ordered a few Richtek RT9701GB USB power switch ICs - apparently they are actually more effective N-channel FET's packaged with surrounding circuitry to make them usable on the high side - but that project was shelved so they remain untried.  If you are up for creating an extremely simple surface mount board to hold them (or can find one already made) they might be worth a try.

At the crude end you could probably use a relay board. There are hubs sold with mechanical power buttons that can be very useful when debugging USB-based embedded systems as you can power cycle them without constant unplugging, and this would be a sort of automated version of that.

It's an interesting question however, if removing the power to a USB peripheral while the data lines remain connected is proper.  This is problematic in the simplest design of an ESD protected input, as the built in protection diode means that the data signal ends up trying to power the unpowered IC, something it isn't usually rated to do, but actually USB circuitry may be more complicated.  An original USB "A" connector is made with the power and ground pins longer than the data ones, in the intent that they connect first.   Pragmatically, I've seen numerous USB devices survive data connection without power - but it could be interesting to read the specs (both USB and of the data sheets of particular devices implementing it) and see what they say about this.

Another tactic could be to get one of the hubs with buttons, take it apart, and wire a relay across one of the buttons.

Or, if you did get one of the rare USB hubs that actually includes controllable downstream power switches, an investigatory dive into the depths of your computer's USB stack should theoretically yield a way to control them from software there, potentially eliminating the need for the Arduino/Teensy.