Thanks for everyone help here.

I have resolved by few steps.

1) File -> preference -> Board manager URL as like below. Basically URL are seperated by commas.
http://arduino.esp8266.com/stable/package_esp8266com_index.json,https://mcudude.github.io/MightyCore/package_MCUdude_MightyCore_index.json

2) Deleted the tmp file (package_index.json.tmp) which is in the path C:\Users\SIMBU\AppData\Local\Arduino15\

This helped me to resolve the issue.


How to listen for an incoming serial string inside loop with long delay?

void loop() {
  static unsigned long prev = 0;
  unsigned long now = millis();

  if (now - prev >= 10000L) {
    serialRoutine();
    dataLoggingEvery10Second();
    prev = now;
  }
}

This will executed at time 10s, 20s, etc. I


How to write array of functions in arduino library?

This was a bit fiddly to get right. I got inspiration from How do I create and use an array of pointer-to-member-function?

Based on my post about Function pointers / function callbacks / function variables I modified it to work with class functions:

class foo {

  public:

   void doAction0 ()
    {
      Serial.println (0);
    }

    void doAction1 ()
    {
      Serial.println (1);
    }

    void doAction2 ()
    {
      Serial.println (2);
    }

    void doAction3 ()
    {
      Serial.println (3);
    }

    void doAction4 ()
    {
      Serial.println (4);
    }

   // typedef for class function
   typedef void (foo::*GeneralFunction) ();

   // array of function pointers
    GeneralFunction doActionsArray [5] =
    {
      &foo::doAction0,
      &foo::doAction1,
      &foo::doAction2,
      &foo::doAction3,
      &foo::doAction4,
    };

};  // end of class foo

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Starting"));

  // test instance of foo
  foo bar;

  for (int i = 0; i < 5; i++)
    {
    // get member function pointer from array
    foo::GeneralFunction f = bar.foo::doActionsArray [i];
    // call the function
    (bar.*f) ();
    }  // end of for loop

}  // end of setup

void loop () { }

This compiles OK and prints:

Starting
0
1
2
3
4

Amended answer

I was wondering why you needed to specify bar in this line above:

    foo::GeneralFunction f = bar.foo::doActionsArray [i];

The reason is that the code above had the array as non-static, and thus a copy belonged to each instance of the class. This doesn't make a huge amount of sense, so the modified code below makes the array static and const. That is, the array should be the same for every instance of foo and also never change.

Modified code below:

class foo {

  public:

   void doAction0 ()
    {
      Serial.println (0);
    }

    void doAction1 ()
    {
      Serial.println (1);
    }

    void doAction2 ()
    {
      Serial.println (2);
    }

    void doAction3 ()
    {
      Serial.println (3);
    }

    void doAction4 ()
    {
      Serial.println (4);
    }

   // typedef for class function
   typedef void (foo::*GeneralFunction) ();

   static const GeneralFunction doActionsArray [5];

};  // end of class foo

 // array of function pointers
const foo::GeneralFunction foo::doActionsArray [5] =
  {
    &foo::doAction0,
    &foo::doAction1,
    &foo::doAction2,
    &foo::doAction3,
    &foo::doAction4,
  };

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Starting"));

  // test instance of foo
  foo bar;

  for (int i = 0; i < 5; i++)
    {
    // get member function pointer from array
    foo::GeneralFunction f = foo::doActionsArray [i];
    // call the function
    (bar.*f) ();
    }

}  // end of setup

void loop () { }

This will also save RAM, as the array of function pointers only exists once, not once per instance of the class.


GPS timestamping of digitized voltages from geophones

To tackle the time resolution and accuracy issue you could:

Attach the 1PPS signal to an interrupt pin
In the interrupt routine record the millis() value at the time the 1PPS signal is activated
In the main loop do a non-blocking read of the GPS data to find and build up the time string as it is sent from the GPS (shortly after the 1PPS is triggered).

You now know what the millis() count was the last time a 1PPS pulse arrived, and you know the current time to within a second. The 1PPS pulse will be at HH:MM:SS.000 (or as near as damnit) so if you subtract the current millis() from your recorded 1PPS millis() value it gives you the number of milliseconds since the 1PPS pulse. Add that to the current time, and you have 1ms accuracy in the time: HH:MM:SS.iii.


Using an Arduino board to program an AVR

Do I have to use all the stuff from arduino?

A = No!

Can I use my own compiler for an arduino board? (GNU-GCC / AVR)
Can I use my own IDE for an arduino board? (Eclipse / Atmel Studio)
Can I still program through serial then? (Does the bootloader care which

Of Course! I use Eclipse IDE and I programming boards with Arduino bootloader directly in C/C++ using avr-gcc and avrdude.
Configuring Eclipse
First, let's download a plug-in for integrating AVR GCC and Avrdude + Eclipse IDE
To install the plug-in, point to the menu "Help> Install new software":

We will set a new location to download the plugin. Click the "Add ..." and type: AVR - Eclipse and the URL: http://avr-eclipse.sourceforge.net/updatesite

Now select the plugin that appeared in the list and click "Next":

Next, next, "I Acept the terms...", restart...
Now we install the plug-in, we will set it up. Point to the menu "Window> Preferences." Click in "AVRDUDE". The following screen:

On the next screen "AVR DUDE" let's set our recorder. Click "Add" to "Programmer configuration". Search for "Arduino".

Or, if you prefer, you can program making use of avr libraries in own Arduino IDE. Try to upload the following code into an Arduino board! While a blink costs almost 1,056 bytes of memory using an Arduino Uno, the following code uses only 164 bytes and does the same thing :)
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clr_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define tst_bit(Y,bit_x) (Y&(1<<bit_x))
#define cpl_bit(Y,bit_x) (Y^=(1<<bit_x))

#define LED PB5

int main( ){
    DDRB = 0xFF;

    while(1){
        cpl_bit(PORTB,LED);
        _delay_ms(200);
    }
}

If you use Linux, you can take a sudo cat/dev/ttyACM0 to detect what lies serial and echo "string" >> /dev/ttyACM0 to send data.


The Arduino itself is open, and you can use it to make commercial products.

Note however, that for commercial products, a lot of additional requirements may be needed (regulations, safety, certifications), especially since it will be used in public places among (many) other people. You don't want students to be injured/die because of a badly designed device.

Not that I think you might not capable, but it might be something to keep in mind, that your project is maybe more than just creating some software and adding some packages and sell them.


9 DoF Sensor Accelerometer Readings Inconsistent

In 'FULL_RES' mode the number you get is amount of 4mg units.

So 1 is 4mg, 2 is 8mg, -4 = -32mg.

Also note that your current code doesn't interpret the first bit (so the 13th from the right) as the sign bit, so you'll never get negative values. (Question related to this)

PS I think it is actually more like 3.9mg.


How to you initialize a reset on a sht30 digital thermometer?

You need to give a brief LOW pulse, not a long HIGH pulse:
In setup:
pinMode(reset_pin, OUTPUT);
digitalWrite(reset_pin, HIGH);

When you want to reset:
digitalWrite(pin_reset, LOW);
delay(1);
digitalWrite(pin_reset, HIGH);


How get assembler/preprocessed code for library

You can get the generated assembly by passing the -S option to
avr-g++. The makefile you are using has a rule for that, so you would
just type

make build-*/my_file.s

to get the assembly for my_file.cpp.

For the pre-processed C++, you use the -E option. There is no rule for
that in the makefile, so you will have to write yo own, or manually
invoke the compiler. At a minimum:

avr-g++ -mmcu=my_mcu -E my_file.cpp > my_file.i

You may want to add -DF_CPU=... -DARDUINO=... just like the makefile
does when compiling the same file.


MQTT on nano with Ethernet shield not working

Thanks to Juraj pointing me that UIPEthernet is just a replacement for the Ethernet library, I finnally found this article Which works just fine.


Which sensors to choose to detect movement direction

The PIR sensors can work in your case. They are passive and detect only moving objects that emit IR radiation. So anything that's hotter than background like people, cats, dogs but not doors.

The raw sensor looks like this:

But it's usually available as a part of an IC that includes a plastic lens that focuses IR rays from broader area on the sensor.

Remove that lens (or not) and add something made of cardboard to limit the area that sensor sees and you have a directional sensor that detects moving hot things.

Technically you can completely hack the raw sensor and get info if the hot object is moving left or right. Read this article and look at the sensor response graph.


Arduino Nano- Programer not responding after upload WDT

If the WDT program is running when you try to upload a new one, it may be blocking the bootloader. Try holding the reset button while you click the the IDE's upload button, releasing the reset once you see avrdude launch. It may take a few tries to get the button-dance just right.

Update:

  what is avrdude ?

It is the program on your PC that uploads the compiled image to the Arduino. You'll see it running in the lower pane of the Arduino IDE.


No. If Arduino ATmega microcontroller supports more than a single UART, then only the first one is available through the standard USB connection. Other UARTs use their own pins that you have to connect to on the board. Mind you these pins are TTL logic serial and need a converter for RS232 or similar. It is possible to use a second (third, ...) TTL-serial to USB cable to access the port on your PC.


HD44780 display incorrectly black-on-blue instead of white-on-blue

This answer is just to complement @smajli's answers posted (and accepted) before.

The problem lies in that the contrast pin has to be fed negative voltages when the module is powerered via a 3.3V supply to be able to show text in the correct white-on-blue setting and not on the faint black-on-blue.

@smajli correctly showed how the negative voltage may be generated from the normal positive supply and a pulse generator. However, in my scenario, the pulse generator was connected to the +3.3V rail instead of +5V and the pulses where generated via the ESP8266's PWM feature. Using a duty cycle of 50% it generates about -2V. I'll not reproduce his schematic here, though, but below is a photo of it assembled and in action.

The updated code is exactly the same, with only the PWM generation added inside the setup() function:

  pinMode(D8, OUTPUT);
  analogWrite(D8, 512);   // 10-bit!

Finally, the photo below illustrates the final result.

Again, thanks again to @smajli for the previous insights and answer.

P.S.: Keen readers will notice the module used now is NOT the same used when I asked the question originally. It is another generic HD44870 module, but without the I2C interface, working in 4-bit mode. However, the exact same problem (black-on-blue text) occurs when the contrast pin is set to anywhere between +3.3V and GND and is promptly solved when using negative voltage.


http://playground.arduino.cc/Main/Waterlevel

The above link had a nice approach.

The principle is the same as traditional pneumatic level gauge, excepted that the dial indicator is replaced by a pressure transducer, and the manually-operated pump is replaced by an aquarium air pump.

When the pump is on, air flows through the weighted PVC pipe to the bottom of the tank, where bubbles appear. At this moment, the air pressure in the PVC pipe is equal to the hydrostatic pressure at the bottom of the tank. As the water pressure at the bottom of the tank is directly proportional to the water level, the same goes for the air pressure in the PVC tube. The air pressure is then converted to an analog voltage by the pressure transducer. This voltage can be read easily by the arduino.

A big advantage of this method with regards to other existing techniques is that no electronic or metallic parts needs to be placed in the tank, where the environmental conditions (mainly humidity) are not favorable. This avoids any risk of corrosion.


It should preferable also have the ability to simulate an Arduino.

As said in the comments, only simulating the Arduino is mostly not enough, because you would also need to simulate all the connected components. Just simulating the Arduino is a rather hard task. You can find Arduino simulators, but they always only support a rather small collection of additional hardware (mostly things like switches, LEDs, buzzers, ...). I guess the proprietary libraries, that you use, are for connecting to some extra devices (maybe are also proprietary), which will be rather complex. These devices will most likely not be supported by any of the Arduino simulators.

Also: Arduino is a beginner and fast prototyping platform. The ones, that do professional things like designing a product (which are mostly the ones, that need such test suites), will fastly move away from the Arduino platform to program an abstraction layer lower directly on the AVR platform. So why would those people need a test suite for Arduino?

Simulating electronic circuits can be really difficult, so you won't see a program, that can handle all of your circuit, including the complex parts like sensors with communication interface. That means, that you can only test your circuit and the corresponding code (which interacts with the circuit) in the real hardware. Some IDEs (like PlatformIO) might give you the possibility, to write test sketches, but you would still need to upload them to the real hardware and observe the results yourself.

Code, that is independent from the Arduino hardware, could be unit tested on the PC, but that is mostly not the case, since Arduino/microcontrollers are so hardware near. Of course, you could write mocking code for the Arduino parts, but that is often even more tedious, than just using the hardware.

As no real Arduino testing framework exists, you are down to writing own testsketches and using a good IDE (not the Arduino IDE) to organize them.


I am facing a problem of firing multiple interrupts on nodemcu 1.0 on single rising edge pulse.what is problem and what are the solutions?

The signal is probably "bouncing" between HIGH and LOW instead of performing a clean edge, just like it happens with buttons.

Two simple solutions:

Hardware solution: use a schmidt-trigger instead of a comparator
Software solution: define a dead-time for the signal aquisition (disable the interrupt when the desired edge has been detected and enable it again after "dead-time")


How can I pass a long as parameter and get a char array in return?

As with many things in C there are many ways of skinning this particular cat.

All of them rely on you first having made a character array to store the result in - you can't "return" an array from a function.

The simplest, though non-standard, way is to use ltoa(), which is an avr-libc specific function (not part of the standard libc functions):

long myLong = 12345L;
char myCharArray[10]; // Enough room for the answer + 1 NULL char

ltoa(myLong, myCharArray, 10);

The 10 in that function call defines the base to represent the number in - base 10 in this case: decimal.

Another way, which is more portable, is to format the string using snprintf():

snprintf(myCharArray, 10, "%dl", myLong);

In this case the 10 is the maximum length of string to prevent it overrunning the 10-character array we made.

A pure Arduino way of doing it would be to use the dreaded String class:

String myString = String(myLong);
myString.toCharArray(myString, 10);

Again in this example the 10 is the length of the buffer we are copying in to.

And there are more. You could do it manually, character by character using division and modulus operators, for example.


Arduino Timer 1 Library manipulate Timer value

When you look into TimerOne.h, which is the header file for the TimerOne library, you can see at line 55 the method

void setPeriod(unsigned long microseconds)

which can be used to set the period of the timer at any time in your program. The method TimerOne.initialize() also calls this method to set the timer period.


Arduino UNO not showing up in USB devices on Ubuntu 18.04

I can't comment yet but have you updated your board manger for UNO on unbunto?

tools > Board > Board Manger > Search UNO

Kind of dumb to have to do that but it happen to me before and this was the solution I did.


How to use RTC memory in NodeMCU to count awakes from deep sleep?

The simplest trick is to use more than one memory location. Have one, as you have now, as a counter, and then have one or more as a "This has been configured" flag.

Ideally you want the flag to have a very low probability of occurring randomly, so using a combination of a number of memory locations would improve that.

For instance, if you read memory locations 1-4 and look for four specific bytes, that gives you about a 1 in 4 billion possibility of it happening randomly.

If you don't see those four bytes, you set the counter byte to 0 (or whatever you want your initial value to be) and set the other 4 memory locations to contain your 4 flag bytes.

Using 8 bytes for your flag would give you in the order of 1 in 1.8x1019 chance of it occuring randomly.

These "flag byte combination" are often called "magic numbers" and are used all over the place to identify either what something is, or if something is valid.


The USB does not go to pins 0 and 1.  The UART goes to pins 0 and 1 - that is a totally different interface.

The USB is connected to dedicated USB pins on the chip.  If you look at the Leonardo schematic you can see it is pins 3 and 4 on the chip. Note that that is not pins D3 and D4 on the board, but the third and fourth pins anti-clockwise from the "pin 1" dot on the main chip.


How can I make push buttons react to being pressed instantly?

You have a few options, including using interrupts. But I believe the most important thing is: "do not use delay()" and you might not even need to use interrupts...

Have a look on this nice post from Nick Gammon: http://www.gammon.com.au/blink with some tips about non-blocking coding.

Also a very simple "Blink LED" example: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


How to use web data from GSM Sim900 to be used as input for Arduino?

You should read the manual.
More specifically the "Sim900 AT reference".
I've found it on a russian server (https://www.google.nl/url?sa=t&source=web&rct=j&url=http://wiki.amperka.ru/_media/%25D0%25BF%25D1%2580%25D0%25BE%25D0%25B4%25D1%2583%25D0%25BA%25D1%2582%25D1%258B:gprs_shield:gprs-shield_sim900_at_commands.pdf&ved=0ahUKEwinze2Tp7fQAhWBMSYKHQFkBh0QFghEMA0&usg=AFQjCNGKd5Uohe7CmcJcIc1Am-SKdRsWXg&sig2=XIsvvkLWHs60sTo7FZ7tWw) but you may want to try and get it directly from the manufacturer.

In the datasheet, it will explained what values are allowed with the "at+httpread" command. You can actually specify which part you want to read. This is usefull when your Arduino can't parse the complete page.

If you have control over the page, you may also generate a device-friendly page consisting of key-value pairs, instead of it being a whole HTML page.


I understand Arduino should be somewhat simpler [than PIC].

The whole Arduino platform (boards, core library and IDE) makes it super
easy to get started and do simple things. However, if you want to
“push the limits” and use the full potential of the MCU, you may have to
dig into low-level programming, and this has a steep learning curve.

The 250V mains will be half-rectified with an IN4004 (?) transistor
(together with a 1K resistor and 0.22uF cap), and that will go into a
4N35 optocoupler.

1 kΩ seems way too low to me: your resistor will dissipate on
average 31 W, and it will burn unless it is a heavy-duty power
resistor. You should choose a resistor that limits the current to a
value low enough to avoid overheating, but still high enough to reliably
turn on the optocoupler. If these two constraints end up being
incompatible, you will need a step-down transformer in addition to (not
instead of) the optocoupler.

A digital (?) GPIO pin from the Arudino goes into the base of the 4N35
and emitter goes to GND.

The base of the optocoupler is typically left floating. You connect the
Arduino input to the collector, using either the internal or an external
pullup resistor, and you ground the emitter.

I believe the Arduino can reliably be powered by USB.

Yes, powering through USB is fine. The Arduino itself draws very little
power. Only when it is powering something else you may worry about
power limits. Here it would seem your Arduino will only be sourcing a
very small amount of current into the output transistor of your
optocoupler, so you will be fine.

How stable is the clock on the Arduino?

Terrible. Most Arduinos are clocked off a ceramic resonator. These
are typically specified with 0.5% frequency tolerance, but their
frequency is constantly fluctuating, and is also strongly dependent on
ambient temperature. This makes those Arduinos grossly unsuited for any
job requiring precise timings. I would recommend you get an Arduino
sporting a real quartz crystal, like the Leonardo or the Micro. A quartz
crystal can be quite inaccurate, but at least its frequency is stable.
It's orders of magnitude more stable than a ceramic resonator. C.f.
for example this article about the Arduino clock frequency
accuracy.

I presume I'll need to debounce the result from the optocoupler?

If the capacitor after your half-wave rectifier is well dimensioned,
your signal should be clean and not need debouncing. The Arduino digital
inputs all have Schmitt triggers which clean up the input noise as
long as it is not excessive. If you really need debouncing (check with a
scope if you can), well... there are no provisions for doing so in the
Arduino core library, but there is a Debounce tutorial among the
examples shipped with the Arduino IDE, and there are a few third party
debounce libraries floating around the Web.

How simple is it to write some software (in C#) that will recognise
the Arduino connected via USB, and communicate with that device in
particular?

As stated in other answers, your Arduino will be seen by your computer
as a virtual serial port. I don't know C#, but any decent programming
language should allow you to easily read data from a serial port.
Measuring method:
You will time one or several periods of the input signal. There are
several ways of doing so. In roughly increasing order of complexity and
accuracy:

You continuously monitor the digital input, in a loop, and whenever
you see a transition from LOW to HIGH you record the current time
using micros().

You use an interrupt pin as the input and you have the interrupt
handler record the time with micros().

You use the input capture facility of your 16-bit timer running at
the full CPU speed.

The methods using micros() have a resolution of 4 µs. Both will
give you some software-induced jitter because they depend on the timing
of your program execution. The advice given by GuitarPicker: “Keep your
code predictable, using as few conditional branches as possible that
might alter how long your code takes to run each cycle” is relevant only
to the first method. The interrupt method is immune to your main loop
timing, but it is still affected by the CPU processing other interrupts.
The input capture method will give you single-cycle resolution and
accuracy, with zero software-induced jitter. That would be my first
choice, but it requires digging into the MCU datasheet and doing some
low-level programming.

Addendum: Here are some tentative answers to a comment posted by
Ozzah to his own question:

I probably want 4 decimal places if possible.

If you want 10−4 absolute accuracy, you may need to
calibrate your clock, even if it is a crystal. If you only require
10−4 stability (variations of the frequency), then even a
ceramic resonator may be (barely) up to the task, if you don't mind
recalibrating it every few weeks, and assuming your indoor temperature
doesn't vary by more than ≈ 10°C.

I want the highest resolution and best tolerance possible.

Then a quartz crystal is definitely a plus. It's roughly 100 times
more stable than the ceramic resonator.
But if you really want the “best”, you may as well follow Milliways'
advice and get a GPS reference. Some options, in increasing order of
price and accuracy:

A simple GPS module for the Arduino. Make sure you get one with a
1PPS output (a “one pulse per second” reference signal). You may want
an external antenna for better reception.
A GPSDO (GPS disciplined oscillator). This is typically a lab-grade
frequency standard consisting of an OCXO (oven-controlled crystal
oscillator) disciplined by a feedback loop into tracking GPS time. It
gives the same long-term stability as the simple GPS module but has
far better short-term stability.
A rubidium-based GPSDO. This is similar to the above but has also a
rubidium atomic frequency reference. Still better short-term
stability. Now we are talking about stabilities in the
10−11 to 10−12 range. Provably overkill for
your use case.

From the software point of view, I would recommend you start with the
interrupt method, just to get a prototype working easily, and then go to
the input capture method, as it will give you the best accuracy. It
should be possible to be cycle-accurate with the interrupt method, but
that would require some non-trivial tweaks.
Note also that the Arduinos based on the ATmega32U4 (Leonardo and Micro
at least) have two 16-bit timers with input capture capability. You
can then time both the mains signal and a 1PPS reference in parallel. If
your Arduino has only one 16-bit timer (like the Nano), you would have
to time one of the signals with the interrupt method.

I'm trying to find a way to determine which Arduino boards use
crystals for the MCU clock and which use ceramic resonators. From what
I can see, they all have a crystal, but presumably that's for the USB
interface?

Yes, the USB/serial interface is clocked off a crystal more often than
the main MCU. The Arduinos that do not have a separate USB/serial
bridge (like those based on the ATmega32U4) seem to have the main MCU
clocked off a crystal.

How can I get a list of Arduinos that use crystals?

It's often stated in the product page. E.g., the page of the Arduino
Micro states
(emphasis mine): “It has 20 digital input/output pins (of which 7 can be
used as PWM outputs and 12 as analog inputs), a 16 MHz crystal
oscillator, a micro USB connection, an ICSP header, and a reset
button.”
Arguably, the info is not very prominent, and a compiled list would be
useful. I think this could be a very good question to ask in this site.


As it turns out, the culprit was the power supply on the board.

The clone came with AMS1117 based regulator for the 3.3V which it did indeed generate (3.27 measured). Using it, the reception of the RF device failed (although it could transmit data). Also had 10uF and a 0.1uF capacitor hooked up in parallel to Vdd and Gnd of the NRF24L01+, as recommended. I therefore suspected something to do with the SPI configuration.

Finally, having powered the 3.3V to the Rf device from another genuine Arduino solved the problem. Not sure if it was the 3.3V rail from the clone possibly having excessive noise which may be causing the issue, as I did not see a reasonable drop in 3.3V output of the clone while in operation.


WiFi.begin doesn't work with ArduinoJson's const char* output

I found the solution myself. I switched from using struct Network network = {n["ssid"], n["password"]}; to declare the struct and const char pointers to using char arrays and strcpy

struct Network network;
strcpy(network.ssid, n["ssid"]);
strcpy(network.password, n["password"]);

Seems like the pointers were getting freed or something right at the same time that I tried to use the value to connect to the network?


Standalone ATMEGA328: Verification mismatch on random byte on -subsequent- uploads only

I got some help from someone today. I oversaw a small detail when using the Arduino IDE with an ISP programmer: Hold shift when uploading to target the MCU at the end of the line rather than the MCU in the programmer.

So yeah, I hold shift when clicking upload and everything works great now. Sometimes it's the simplest things you'd never expect.


Reading file from SPIFFS in nodemcu using ArduinoJson

Your code at the top:

struct Config {
  String ssid = "";
  String pass = "";
  bool hFlag = false;
};

defines a variable "type". It's like making a new int or bool, but yours is called struct Config.

After making the type, you need to create declare an instance of it.

struct Config cfg;

Then, you refer to the one you created:

  // Copy values from the JsonObject to the Config struct named cfg
  cfg.ssid = root["ssid"];
  cfg.pass = root["pass"];
  if (whichFile)
  {
    cfg.hFlag = root["hFlag"];
  }

Note that a particular issue with ArduinoJSON and Strings is that you may get an error like:

error: ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::JsonObjectSubscript<const char*>')

There is an ArduinoJSON FAQ entry that states

  Most of the time you can rely on implicit casts.

  But there is one notable exception: when you convert a JsonVariant to
  a String.

  For example:

String ssid = network["ssid"];
ssid = network["ssid"];

  The first line will compile but the second will fail with the
  following error:

error: ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::JsonObjectSubscript<const char*>')

  The solution is to remove the ambiguity with any of the following replacement:

ssid = (const char*)network["ssid"];
ssid = network["ssid"].as<const char*>();
ssid = network["ssid"].as<String>();


Arduino Mega 2560 Only Powers on with USB

Looking at this Arduino Mega 2560 schematic, if IC1 or IC2 failed (assuming only one or the other is installed for a given board), then you would only be able to power the board using the USB port.

Looking at this ramps 1.4 shield schematic it is assumed that the RAMPS 1.4 shield is providing 12 volts through D1 to the Arduino Mega 2560.  And that testing included using a known good Arduino Mega 2560 board with the RAMPS 1.4 shield board with good results.  Thereby eliminating the possibility that D1 on the RAMPS 1.4 shield is damaged.

If these assumptions are correct, this reinforces the likelihood that either IC1 or IC2 has failed on the Arduino Mega 2560 board.


How to send Multiple decoded IR signals in one script

I'm not 100% certain what you are asking, so sorry if there is superfluous info in here.

Given that:

void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0x10676897, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

Sends a single command twice as one burst I think what you want to do is this:

void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(106722DD, 32);
        delay(40);
        irsend.sendNEC(10676897, 32);
        delay(40);
        irsend.sendNEC(10678877, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

If that works it could be generalised into:

// New function to send 'items' codes which are held in the array 'data'
void sendMulti (const uint8_t& items, const uint32_t* data)
{
    for (int i = 0; i < 2; i++)
    {
        for (uint8_t itemIndex = 0; itemIndex < items; ++itemIndex)
        {
            irsend.sendNEC(data[itemIndex], 32);
            delay(40);
        }
    }
    delay(5000); //5 second delay between each signal burst
}

void loop () {
    static const uint8_t MaxItems = 3;
    uint32_t  data[MaxItems] = {106722DD, 10676897, 10678877};

    sendMulti(MaxItems, data);
}

Then you could move onto reading the codes from serial or a network, etc.


It seems like the problem occurs when brightness is a lot higher than potValueConverted.

For example, lets say our brightness=100, potValueConverted=50, this triggers the latter "if" condition, i.e.

  brightness >= potValueConverted

and at the next iteration, brightness = 105 (or 95), both of which will satisfy the condition for fadeAmount to flip its polarity, thus resulting in the brightness value oscillating between 105 and 100 (or 100 and 95).
This results in the LED getting stuck at the same level of brightness.

a quick hack fixes this problem (as far as I can tell)

 if (brightness <= 0 ) {
    fadeAmount = 5;
  }
 if (brightness >= potValueConverted +5 ) {
    fadeAmount = -5;
  }

**note the +5 for the second if statement is to ensure that the brightness value does not become negative.


WiFi connections being lost on connection reset

WifiServer class has a bug that is now resolved. It causes a phenomenom described like follows:

  When I send message to client via WifiServer.avalible, the user is disconnected from server - I can connect to it again, so server is not stopping.

And latest comment on topic is that it is corrected in latest commits.


You're looking for this I think? How to set up an Arduino on a breadboard.


The 2 techniques described in the question are commonly referred to as "polling" and "interrupt".  Either will work.  Polling is suggested for beginner programmers and when time is not important. Such as scanning an array of human controlled buttons. Whereas interrupts are usually reserved for when time is of the essence.  Such as synchronizing a camera's release switch with a strobe flash.

Also, consider polling as a simple to understand, easy to test sequence of events that will always happen in the expected order.  While interrupts can happen at any time and all interruptible code has to be written to tolerate being interrupted.

Often, debouncing is the more difficult problem when combining mechanical switches and microprocessors.  A good fundamental exercise is to write your own debounce program.  However, an Arduino debounce library is already available.


Getting all data of my JSON object from Serial.read() at once

I was going to put this as a comment, but maybe it belongs as an answer:
For what it's worth, ArduinoJSON seems to be able to deserialize directly from a stream, i.e. Serial, which may obviate the question as asked.  Presumably it knows where to stop deserializing, because it knows when it has received an entire JSON object; being a proper JSON parser, it can probably work this out better than you can without, you know, writing a JSON parser.
The following was just thrown together, now the author is here you should probably just follow their direction, but here's the code anyway:
#include <ArduinoJson.h>

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  Serial.setTimeout(30000);
}

void print_transmission_counter( {
    static unsigned long received_object_counter;
    Serial.println(F("\n\n\n\n"));
    for (int i = 0; i < 30; ++i) {
        Serial.write('-');
    }
    Serial.write('[');
    Serial.print(received_object_counter++);
    Serial.println(']');
}

void loop() {
    static StaticJsonDocument<256> json_doc;
    static bool led_state;

    print_transmission_counter();

    const auto deser_err = deserializeJson(json_doc, Serial);
    if (deser_err) {
        Serial.print(F("Failed to deserialize, reason: \""));
        Serial.print(deser_err.c_str());
        Serial.println('"');
    } else  {
        Serial.print(F("Recevied valid json document with "));
        Serial.print(json_doc.size());
        Serial.println(F(" elements."));
        Serial.println(F("Pretty printed back at you:"));
        serializeJsonPretty(json_doc, Serial);
        Serial.println();
    }

    // Just give some visual indication that the loop is progressing
    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
}

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


ESP 01 lost its firmware when it disconnected

You have io 0 puled LOW so the esp-01 firmware starts in flashing mode and the firmware starts immediately after flashing (no reset).

Remove io 0 to ground connection and add a pull-up for io 0 over a 10kOhm resistor if you want the esp-01 to start normally.

Note: powering the esp-01 from the 3.3 V pin of Uno (150mA max) could be insufficient for esp8266 WiFi operations at top transmit power (according to specs it can draw to 170 mA).


Does the map() function works on an ATtiny85?

The map function uses integer arithmetic, and since the ATmega series and the ATtiny series use the same 8-bit AVR instruction set, there should be no difference when using it, and you are good to go from that aspect.

Consider that there are many other differences regarding I/O pins, storage etc. - that you might want to consider. Here is a good source for a basic comparison between the ATmega based Arduino to ATtiny85.


Combining code for multiple sensors in a single program

In general:

All #defines and #includes get put from all separate sketches, at the top.

Globals and function definitions (except for setup() and loop()) get mixed together below the #defines and #includes.

All code in the separate setup()s get put in the combined setup().

All code in the separate loop()s get put in the combined loop().

You have to be aware that any loop() from the separate programs that include a delay() will likely have to be refactored to use the same kind of scheduled execution method as the Blink Without Delay example from Arduino. delay() stops the whole program while it twiddles thumbs, which means your other sensors aren't being read or managed during that time.


avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x17

Welcome to the community! I'm not able to comment yet so i'll answer here.
Try changing the connection to other USB port.
If that doesnt work check this question, the solutions can be similar (Juraj is right in the comments) :
avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program

Good Luck!


Error while boot loading Atmega 2560 using Arduino Mega 2560

You wired the whole thing backwards. The proper wiring is

Your board - Arduino
     MISO  -  D50
     MOSI  -  D51
     SCK   -  D52
     Reset -  D53
     Vcc   -  5V
     GND   -  GND

This is kind of obvious from the picture: you would normally use the ISP
connector of the target board.


Arduino non-blocking software PWM LED fader not working

As @ott-- has mentioned, because of the int datatype, _fadeStep/_fadeSteps will always evaluate to 0.

Here's the updated code along with some timing tweaks:

float fadeSteps = 150; // How many steps to take until full brightness

class Led{
  public:
    Led(int pin, float fadeStep=0);
    void setup();
    // void updateFadeDirection();
    void updateBrightness();

  private:
    int _pin;
    unsigned long _currentTime;
    unsigned long _startTime; // Very beginning of fade period
    unsigned long _fadePeriod; // How long to fade on and off
    float _fadeStep; // current fade step i.e. 1/255
    int _fadeDirection; // low to high or high to low?
    unsigned long _T_on; // Amount of time to turn LED on
    unsigned long _T_fadeStep; // Amount of time per step increment of brightness
    unsigned long _stepTime; // Start of current step period

    bool _evaluated;
};

Led::Led(int pin, float fadeStep){
  _pin = pin;
  _fadeStep = fadeStep;
}

void Led::setup(){
  pinMode(_pin, OUTPUT);
  _startTime = micros();
  _fadePeriod = 2000000; //microseconds(us)
  _fadeDirection = 1;

  _T_fadeStep = _fadePeriod/2/fadeSteps; // i.e. 2000000us/100steps = 20000us/step of brightness
  _T_on = (_fadeStep/fadeSteps) * _T_fadeStep; // i.e. 20/100 * 20000us = 4000us on

  _stepTime = micros();
}

void Led::updateBrightness(){
  _currentTime = micros();
  if (_currentTime - _stepTime > _T_on){
    digitalWrite(_pin, LOW);
  } else {
    digitalWrite(_pin, HIGH);
  }

  if(_currentTime - _stepTime >= _T_fadeStep){
    _fadeStep += _fadeDirection;
    _stepTime = _currentTime;
    _T_on = (_fadeStep/fadeSteps) * _T_fadeStep;
  }

  if(_fadeStep >= fadeSteps-1) {
    _fadeDirection = -1;
  } else if(_fadeStep <= 1) {
    _fadeDirection = 1;
  }
}

Led LED0(0);
Led LED1(1,fadeSteps/5);
Led LED2(2,2*fadeSteps/5);
Led LED3(3,3*fadeSteps/5);
Led LED4(4,4*fadeSteps/5);

void setup() {
  LED0.setup();
  LED1.setup();
  LED2.setup();
  LED3.setup();
  LED4.setup();
}

void loop() {
  LED0.updateBrightness();
  LED1.updateBrightness();
  LED2.updateBrightness();
  LED3.updateBrightness();
  LED4.updateBrightness();
}

Some refactoring is needed to be more modular, but will fade (using software PWM) LEDs asynchronously on every digital OUT port on an attiny85. Can also set the starting brightness so that you can make an LED fading chaser.


The starter kit would get you everything you need to do a whole set of projects. Alternatively there is a PDF on the Arduino site with a whole set of projects in it. You could go through it, put together an inventory of the parts you need, and order those parts from an electronics supplier like Mouser, DigiKey, Jameco, etc, and save some money.

The starter kit is probably worth the extra money, though, because it has everything you need, plus an organized set of lessons that teach you the various skills you'll need.


how to compile arduino sketch from termnial without using arduino ide

As a contributor to Sloeber, an Eclipse Plugin dedicated to Arduino and other micro controllers, I can tell you it's all a matter of using the correct version of gcc and provide the correct options.

Even if that might seem simple, it's not like that, so my advice is to download Sloeber and look at the build console output where we print all the statements used to fulfill the build task: you can infer a lot from that.

As Sloeber is also open source, you can also inspect how we create those build commands for the different boards and tool chains.


It's not strange at all.  Serial doesn't block while it sends.  When you call write that pushes the byte into the send buffer and that's all.  Then the code moves on to the next instruction, the delay(950) and during that time the serial data is actually being sent.  It takes about 1 millisecond for that to happen.
This solution works as long as the send buffer doesn't have anything else in it that's slowing you down and as long as you don't change the baud rate.  If either of those things happen then you need to recalculate that time.
A better solution would be:
  Serial1.write(sw_binary_train_1);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_2);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_3);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_4);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_5);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_6);
  Serial1.flush();
  delay(37);

The flush blocks until the send buffer is empty again.  That way you don't have to account for that time and all you need the delay for is the time between transmissions.
Even better would be if those things were in an array so you didn't have to keep repeating yourself.  Anytime you catch yourself putting numbers on variable names what you really want is an array so that you can use those numbers in the program:
for (int i=0; i<6; i++){
  Serial1.write(sw_binary_train[i]);
  Serial1.flush();
  delayMicroseconds(950);
}
delay(37)

looks much better.


What is the datatype of the pinMode function?

pinMode(pin, Mode); is a void. It doesn't return anything. It simply sets a pin as an OUTPUT or an INPUT.
It says it in the link you posted.

Returns
None

That means that the function doesn't return any value.


Converting ESP32 SPI code to Arduino for MAX6921 IV-18 driver board

So it turns out that I got a few things wrong.
UPDATE: Working code is now on my GitHub if anyone is interested.
Firstly, I misunderstood the example code and made a mess of the bits to send to the MAX6921. To work out the correct mapping, I went and probed each pin of the IV-18 and noted the connection to the pins / outputs of the MAX6921 which gave me this table:

BIT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

IV-18
G9
G8
G7
G6
G5
G4
G3
G2
G1
A
B
C
D
E
F
G
DP

MAX6921
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Note that the MAX6921 value is the OUTPUT number and not the PIN number
This then gave me the correct order for each bit to send, as noted in the top row of the table.
The next mistake was trying to send all 24 bits in one go. Instead, I broke each byte into a separate SPI.transfer() call which finally let me display the segments in the grid position that I expected.
For example, to display "HELLO", my loop function has this:
void loop() {
  //             XXXXXXXDP                 GFEDCBA1                  23456789
  SPI.transfer(0b00000000); SPI.transfer(0b11101100); SPI.transfer(0b10000000); delay(1);
  SPI.transfer(0b00000000); SPI.transfer(0b11110010); SPI.transfer(0b01000000); delay(1);
  SPI.transfer(0b00000000); SPI.transfer(0b01110000); SPI.transfer(0b00100000); delay(1);
  SPI.transfer(0b00000000); SPI.transfer(0b01110000); SPI.transfer(0b00010000); delay(1);
  SPI.transfer(0b00000001); SPI.transfer(0b01111110); SPI.transfer(0b00001000); delay(1);
}

I have setup TIMER1 to use instead of the loop/delay code, so hopefully I can finish converting the rest of the example code to Arduino.


How to detect the direction of a rotary encoder?

I have a page about rotary encoders - in that I show how you can detect encoder changes (and direction) using one interrupt pin and another pin, like this:

// Wiring: Connect common pin of encoder to ground.
// Connect pin A (one of the outer ones) to a pin that can generate interrupts (eg. D2)
// Connect pin B (the other outer one) to another free pin (eg. D5)

volatile bool fired;
volatile bool up;

const byte encoderPinA = 2;
const byte encoderPinB = 5;

// Interrupt Service Routine for a change to encoder pin A
void isr ()
{
  if (digitalRead (encoderPinA))
    up = digitalRead (encoderPinB);
  else
    up = !digitalRead (encoderPinB);
  fired = true;
}  // end of isr

void setup ()
{
  pinMode (encoderPinA, INPUT_PULLUP);     // enable pull-ups
  pinMode (encoderPinB, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (encoderPinA), isr, CHANGE);   // interrupt 0 is pin 2

  Serial.begin (115200);
}  // end of setup

void loop ()
{
static long rotaryCount = 0;

  if (fired)
    {
    if (up)
      rotaryCount++;
    else
      rotaryCount--;
    fired = false;

    Serial.print ("Count = ");
    Serial.println (rotaryCount);
    }  // end if fired

}  // end of loop

In the main loop you just need to test the boolean fired to see if the encoder changed, and up to see if it went up (otherwise it went down).

  I receive random of these values ...

I think with your code you need to detect a change - that is, if the encoder pin is now HIGH but was previously LOW.

Solution for 4 encoders

  The problem is I am working on four encoders ...

I have reworked my code to use pin-change interrupts instead of external interrupts.

// Wiring: Connect common pin of encoder to ground.

volatile bool fired;

const byte ENCODERS = 4;

typedef struct
  {
  int aPin;     // which Arduino pin for the "A" side
  int bPin;     // which Arduino pin for the "B" side

  // values below are calculated at run-time
  volatile byte * aPort;  // which processor port the A side is plugged into
  volatile byte * bPort;  // which processor port the B side is plugged into
  byte aBitMask;   // which bit in the A port
  byte bBitMask;   // which bit in the B port
  byte whichInterrupt;  // which pin-change interrupt port (0, 1, 2)
  byte oldValue;   // old value of A port (to see if it changed)
  int count;       // current encoder counter
  } encoder;

 volatile encoder encoders [ENCODERS] =
  {

 // A   B  pins  (eg. D4 and D8, D5 and D9 and so on)

  { 4,  8 },
  { 5,  9 },
  { 6, 10 },
  { 7, 11 },

  };  // end of encoders

void checkForPinChange (const byte which)
  {
  for (byte i = 0; i < ENCODERS; i++)
    {
    if (encoders [i].whichInterrupt == which)
      {
      byte newValue = *(encoders [i].aPort) & encoders [i].aBitMask;
      if (newValue != encoders [i].oldValue)
        {
        bool up;
        byte bPort = *(encoders [i].bPort) & encoders [i].bBitMask;
        if (newValue)
          up = bPort;
        else
          up = !bPort;
        fired = true;
        if (up)
          encoders [i].count++;
        else
          encoders [i].count--;
        encoders [i].oldValue = newValue;
        }  // end of if value has changed
      }   // end of if this is the right interrupt number
    }     // end of for each encoder
  } // end of checkForPinChange

// handle pin change interrupt for D8 to D13 here
ISR (PCINT0_vect)
 {
 checkForPinChange (PCIE0);
 }  // end of PCINT0_vect

// handle pin change interrupt for A0 to A5 here
ISR (PCINT1_vect)
 {
 checkForPinChange (PCIE1);
 }  // end of PCINT1_vect

// handle pin change interrupt for D0 to D7 here
ISR (PCINT2_vect)
 {
 checkForPinChange (PCIE2);
 }  // end of PCINT2_vect

void setup ()
{
 Serial.begin (115200);
 Serial.println ("Starting ...");

 PCIFR  |= bit (PCIF0) | bit (PCIF1) | bit (PCIF2);   // clear any outstanding interrupts

 for (byte i = 0; i < ENCODERS; i++)
    {
    pinMode (encoders [i].aPin, INPUT_PULLUP);
    pinMode (encoders [i].bPin, INPUT_PULLUP);
    // convert pin number to port, mask, etc. for efficiency

    // Input port
    encoders [i].aPort = portInputRegister (digitalPinToPort (encoders [i].aPin));
    encoders [i].bPort = portInputRegister (digitalPinToPort (encoders [i].bPin));

    // Which bit in the port to test
    encoders [i].aBitMask = digitalPinToBitMask (encoders [i].aPin);
    encoders [i].bBitMask = digitalPinToBitMask (encoders [i].bPin);

    // Which interrupt number (0, 1, 2)
    encoders [i].whichInterrupt = digitalPinToPCICRbit (encoders [i].aPin);

    // activate this pin-change interrupt bit (eg. PCMSK0, PCMSK1, PCMSK2)
    volatile byte * ICRmaskPort = digitalPinToPCMSK (encoders [i].aPin);
    *ICRmaskPort  |= bit (digitalPinToPCMSKbit (encoders [i].aPin));

    // enable this pin-change interrupt
    PCICR |= bit (digitalPinToPCICRbit (encoders [i].aPin));

    } // end of for each encoder

}  // end of setup

void loop ()
{
  if (fired)
    {
    for (byte i = 0; i < ENCODERS; i++)
      {
      char buf [10];
      sprintf (buf, "%5d", encoders [i].count);
      Serial.print (buf);
      }
    Serial.println ();
    fired = false;
    }  // end if fired

}  // end of loop

The code is general enough to handle 1 to x encoders (eg. 10 encoders) - within reason! You need to have 2 pins spare per encoder (the third pin goes to ground). One of the pins needs to be capable of pin-change interrupts (on the Uno that is all of them).

The code sets up to detect an interrupt on the "A" side of the encoder and tests the value on the "B" side to see if it was turned clockwise or counter-clockwise.

I am getting results like this (with 2 encoders connected):

   16  -19    1    1
   17  -19    1    1
   18  -19    1    1
   19  -19    1    1
   20  -19    1    1
   21  -19    1    1
   22  -19    1    1
   23  -19    1    1
   23  -20    1    1
   23  -21    1    1
   23  -22    1    1
   23  -23    1    1
   23  -24    1    1
   23  -25    1    1

The other two are showing as "1" (that is, not turned yet).


Small Baseball Scoreboard using 2 to 3 breadboards

Actually, you can very easily verify this yourself:

Per item (1602LCD, 7 segment LCD and LEDs check how many pins you need and what type, like e.g. I2C or SPI for the 1602 LCD). The 7 segment displays can have many or less pins, depending on the 'controller', See the reaction of CrossRoads below.
Count them together. If it fits on the Arduino you want to use OK. The Uno is cheapest, so if it fits on it, you use that, otherwise you can go to the Mega.
As alternative, and you need 'generic pins, called GPIOs' (not SPI/I2C) for some, you can use multiplexers like 74HC595 to reduce the number of GPIOs needed, at the cost of some speed (not critical for your project), and some more programming work.
In some cases you can use a MAX7219 driver IC, see (again) the remark of Crossroads below.


I had downloaded PinChangeInterrupt through Arduino

Sketch > Include Library > Manage Libraries... > Filter your search... > PinChangeInterrupt > Install

I thought this is all I needed but I was wrong. This differs from the popular PinChangeInt library. Ultimately the file names where slightly different which is why my file was showing as missing. I found this out by manually looking at the file names in the library I was trying to used and comparing them against my includes.


Using N mosfet to switch ESC to BLDC phases

This is covered fairly well in an EDN.com “MOSFET pair makes simple SPDT switch” article.  You would use two of the SPDT circuits to make a DPDT.  Attach switch commons to yellow and blue, and attach the “switch points” of one circuit to motor yellow and blue, and those of the other vice versa.  Attach both control pins to one Arduino IO pin.  The picture below comes from the referenced article, which shows the circuit in use for a primary-power vs secondary-power application.   See the article for details.


Timer for how long button is not pressed

I would start a timer when the button changes state. Then you timeout if
the button is released and it hasn't changed state for too long:

void loop()
{
    static int lastButtonState;
    static unsigned long buttonChangeTime;
    int buttonState = digitalRead(buttonPin);
    unsigned long now = millis();

    // Record time when button changes state.
    if (buttonState != lastButtonState)
        buttonChangeTime = now;

    // Timeout if button is not pushed for too long.
    if (buttonState == LOW && now - buttonChangeTime >= interval)
        Serial.println("Timeout.");

    lastButtonState = buttonState;
}

Don't forget to update lastButtonState on each iteration.


I had exactly same situation.
I initially started to inspect on FIFO overflow of MPU6050, then experimented setting different clock speed for I2C communication, tried to tweak with pullup resistors as recommended.
Finally, here is the solution which worked for me. Basically, I just disconnected INT pin from MPU6050.

Now the schema is:
(MPU) -> (Arduino)

AD0 -> GND
SDA -> A4 (No pullup)
SCL -> A5 (No pullup)
GND -> GND
VCC -> 3.3V

I used this code as an example:
https://github.com/jarzebski/Arduino-MPU6050/blob/master/MPU6050_gyro_pitch_roll_yaw/MPU6050_gyro_pitch_roll_yaw.ino

from this library:
https://github.com/jarzebski/Arduino-MPU6050


Distance Measurement - between 6 points, individually moving in (almost) any direction within 1m

You may try to implement some kind of ultrasonic transponders. The
emitter sends a code addressing a specific receiver. Upon recognizing
its address, the receiver replies after a short, fixed delay. The
emitter measures the time it took the response to reach it, and from
there computes the distance.

You may need some kind of omnidirectional transducers (e.g. this
models) if you want the measurement to work in any
direction. And also a protocol to avoid several emitters talking at the
same time.

This seems to me like a very complex project though.


Can the Arduino interface with a fingerprint sensor on my mobile?

You'd need an app on your mobile to read the sensor and communicate the result to your Arduino in a secure way that cannot be spoofed by an intruder. That secure communication over an open channel (WiFi, I assume?) is not trivial to do right, so that would be a weak point in your security.

Blynk, an app+server+Arduino library combination provides an authentication token to pair with your Arduino in a relatively secure way. You quickly make (drag-and-drop) a control panel for your Arduino system with it. It doesn't offer fingerprint sensing directly, but if you keep your Blynk authentication token a secret, keep your Blynk app+token on your mobile, and the mobile is fingerprint-locked, you'd have essentially the same thing, and the pieces already exist. You'd only need to code the smart-home parts for the Arduino.


How to load scal factor external to the code?

As written in the comments you coulduse eepron, but in your scenario it has one big disadvantage: Everything has to be written at compile time (aka when you programm the Nano, you have also to fill the eeprom with the relevant values), so e.g. if you have a temperature depending factor you want to change while on the field...
I would go for a SD-card reader:

Cheap to get (2$)
Easy to handle in code (read from a file is a standard function)
using a PC compatible file systen FAT enables reading/writing onto the SD card on a PC/other device without recompiling your code.
If you switch sensors for whatever reason, just write a new scale.txt file to the SD-card, insert and reboot the nano to get the new values
you could still use eeprom as a fallback scenario

As a tip (also mentioned in the comments by Delta_G) int for something like 0.01 is not what you want - define as float and watch out for the "conversion trap" when using with other variables not defined as float.


Servo sg90 is small and can be powered from your computer or laptop connected to the Arduino. The problem does not lie there, but maybe about your connection. Make sure about these things:

Brown is connected to GND
Orange is connected to VCC
Yellow is connected to digital PWM pins.

You could use this code that I am hooking up, with several servos and using external supply but if you try doing the same make sure all the motors are properly grounded.
#include<Servo.h>
Servo ServoBase;
Servo ServoLeft;
Servo ServoRight;
void setup(){
  ServoBase.attach(6);
  ServoLeft.attach(5);
  ServoRight.attach(3);
}

void loop(){
  ServoBase.write(140);
  ServoLeft.write(120);
  delay(1500);
  ServoBase.write(40);
  ServoLeft.write(30);
  delay(1500);
}


Use timer0 without affecting millis() and micros()

So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions,

Yes. A few ways, depending on your level of comfort:

You can declare the stock Arduino Timer0 OVF "weak" and write your own where you can insert your ISR. But you have to handle the interaction between the millis() / micros() related variables.
You can modify the stock Arduino Timer0 OVF to insert your own ISR.

And – if that can be done – what would be the restrictions of such an ISR (e.g. I suppose I could not use all the timer/interrupt modes...)

The stock ISR would look like this:

ISR(TIM0_OVF_vect) {
    ...
    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;

    //insert your isr here
    _mytmr0_isrptr();
}

Where _mytmr0_isrptr() is a function pointer to your own ISR handler.
The simplest is probably to use the output compare interrupts. You can get it to behave like a virtual timer and can do lots of other stuff.

Obviously, you can think of tons of other ways and this is just a starting point.

  What are those interrupts? How can I use them? –

Timer0 has three interrupts associated with it: overflow and compare channel A and channel B. The overflow interrupt is already being used by the timing functions millis() and micros(), as shown earlier.

The compare channel A/B interrupts are unused. And this discussion is about using them for timing purposes.

The general ideal is demonstrated in blog post Using Spare Output Compare Channels as Timers – the Collection.

The task there is more complicated than what you are trying to do here, but the basic ideal is the same. To do what you wanted here it is much simpler than that.

If you still cannot figure it out, I can provide you with code pieces to get you started.


embedXcode: Link Error using an Arduino library (Servo.h) within a header file

I ended up contacting the developer of the embedXcode plugin. He was very helpful and provided the fix within a day. The cause of the issue is apparently the Arduino IDE has changed its library structure in the latest release.

The next version of embedXcode (release 4.1.4.) will include a fix for this, however if you can't wait until then you need to open ArduinoAVR_165.mk (located in the Makefiles group in Xcode) in your project and add the following line:

avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/$(BUILD_CORE),$(APP_LIBS_LIST)))

After you add this line, the file should look like this:

# Two locations for Arduino libraries
#
APP_LIB_PATH = $(APPLICATION_PATH)/libraries
APP_LIB_PATH += $(APPLICATION_PATH)/hardware/arduino/$(BUILD_CORE)/libraries

avr165_20 = $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%,$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/utility,$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src,$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/utility,$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/$(BUILD_CORE),$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/arch/$(BUILD_CORE),$(APP_LIBS_LIST)))

Note that each project has its own ArduinoAVR_165.mk file, so you will have to make this change in each project until you update to the new release.


You are using a Leonardo. Pins 0/1 aren't Serial, they're Serial1.  Serial is the built-in USB connection.

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

void loop() {
   Serial1.print("test");
   Serial1.print("\n");

}


I would make sure first that their claim ofb8v max is right. Look up the datasheet for the regulator and go from there.

If you have to go with 8v max, put a diode or two, or an led in serial should work most of the time.

For those where such an approach doesn't work, wire up an external regulator.


A possible implementation of the protocol using serial read/write of binary data (command and response).

void send(Stream& ios, uint8_t cmd[6])
{
  uint8_t sum = 0;
  for (int i = 0; i < 6; i++) {
    uint8_t c = cmd[i];
    sum += c;
    ios.print((char) c);
  }
  ios.print((char) sum);
}

bool recv(Stream& ios, uint8_t res[6])
{
  uint8_t sum = 0;
  uint8_t c;
  for (int i = 0; i < 6; i++) {
    while (!ios.available());
    c = ios.read();
    sum += c;
    res[i] = c;
  }
  while (!ios.available());
  c = ios.read();
  return (sum == c);
}

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

  uint8_t cmd[] = { 0xB4, 0xC0, 0xA8, 0x01, 0x01, 0x00 };
  uint8_t res[6];
  send(Serial, cmd);
  recv(Serial, res);
}

void loop()
{
}

Cheers!


How do I stop a servo motor at the current position when using a serial port? I want it to remain in one position when receiving "0"

Are you sure the mouse is not sending a continuous stream of 1s? If that were the case then, because of buffering, all the 1s will serviced before the servo stops. For example, a sequence of 11111 followed by a 0 will cycle the movement 5 times before it stops and prints the 0.


I'm missing something on the bus operation. Pretty much whenever I get NAK'd I know I need to redo the operation. On the i2c bus it should be an ACK'd or NAK'd on every byte.

Usually you send the address of the device then the command. So the master initially sends the address, which is ACK'd and then the master sends the command that it wants executed. Your diagram has the slave answering when it's the master that's required to give it an operation?

Here's a good document on it... :)

Philips I2C Document


There are functions which can get you the registers and bit numbers from a pin number built into the Arduino API.

uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
volatile uint8_t *reg = portModeRegister(port);

if (*reg & bit) {
    // It's an output
} else {
    // It's an input
}


Can I connect and control 12 Arduino's over USB/serial to my laptop?

From a technical standpoint, USB can host up to 127 devices, so 12 Arduino boards is certainly not pushing the limit. Having 12 serial ports shouldn't be an issue in either Linux or Windows.

From a practical standpoint, you will have to find a powered USB hub which can support that many devices, or plug multiple hubs together. I'll leave that up to you as shopping recommendations are off topic.

In terms of the hub you use, you need to make sure you don't exceed its maximum current rating. The Arduino boards draw typically around 60-100mA alone. 12 of those and you will need at least 1.2A rating. The hub you mentioned says that it cannot exceed 2A. Depending on what other circuitry you attach to your Arduino boards you may need an external power supply for the boards.


OpenOCD with FT2232H on Arduino Mega (ATmega2560)

The chip seems to support it:

  Multi-Protocol Synchronous Serial Engine (MPSSE) to simplify synchronous serial protocol (USB to JTAG, I2C, SPI or bit-bang) design.

You'll have to play with the drivers,
and check to see that Arduino brought all the JTAG pins out to header pins.


How to get elapsed seconds since Jan 1, 1970?

An arduino does not have a real time clock (RTC) built in. Every time it restarts it will reset the millis counter.

You will need to add a RTC peripheral that you can poll to find the current date and time.


Probably the first time because you received the character '1' or '0'.
The second character is probably a '\0' or '\d', an end-of-string or end-of-line character.

You can easily check this by printing the value of each received character, like

Serial.println((int)(BluetoothData));

You probably see the value for '0' (48), '1' (49), end of string '0' of end of line '13' or maybe '10' (new line).


Flashing ESP8266 over WiFi whith samrtphone?

ESP8266 OTA can be performed through a web browser as detailed in the ESP8266 OTA information page.

Since a smartphone has a web browser I can see no reason why you can't use that.


You should read something about C arrays and how they work.

Anyway, if you use:

  Change(tabel1);

// ...

void Change(char * tabel)
{
  tabel[0] = 'n';
  tabel[1] = 'b';
}

It'll change passed array because it's passed as pointer to the first element of tabel1.


Programming arduino via bluetooth module issue

I wrote the tutorial you were following so maybe I can help. When I was building the circuit initially I used some of the other tutorials out there on Arduino Bluetooth programming which don't have a lot of the extra resistors and capacitor.  However, I couldn't get any of those to work reliably.  Using a circuit simulator and some trial and error, I ended up with the circuit shown in the tutorial which worked for me.

While there "doesn't seem to be a need for" some of the extra passives, if your circuit doesn't work without them, perhaps there is a need for them after all? ;-) Now, I have heard from other people that they were able to leave out certain bits so it seems that there is some variability in the hardware. But we're talking four passives to ensure reliable operation, so why leave them out?

Anyway, a couple of points:

Pin 32 on the HC-05 becomes active upon Bluetooth connection.  We configure the pin to be active low so we can use it to auto-reset the Arduino upon serial connection to emulate what happens with the normal USB connection.  You can leave out the connection to pin 32 only if you want to have to manually reset the Arduino to program it.
The 115200 baud rate is the rate for programming the Arduino and is set by the Arduino bootloader.  It is possible to re-flash the bootloader with a different configuration if you needed to for some reason.
So, the programming baud rate is fixed in the bootloader, but the communication baud rate is configurable in software using Serial.begin(). However, the HC-05's baud rate has to be the same as the Arduino's, so you need to stick with the same baud rate for both programming and communication (115200 by default).
There are two resistors involved with the reset, R3 and R2.  I believe R2 is only necessary for 5V Arduinos to act as a voltage divider with R3.  However, R3 should be included for any voltage Arduino. See this Atmel design note - "The reset line has an internal pull-up resistor, but if the environment is noisy it can be insufficient and reset can therefore occur sporadically ... This pull-up resistor makes sure that reset does not go low unintended." R3 should be 4.7k or greater; most designs stick with 10k.
The capacitor C1 is necessary because Pin 32 stays low the entire time Bluetooth is connected.  If you connect RST to Pin 32 directly, the Arduino will just stay reset until the Bluetooth connection drops and nothing will work just as if you held down the reset button and never let go.

With C1 in place, when Pin 32 goes low it will momentarily discharge C1, pulling RST low and resetting the Arduino. C1 will immediately begin charging through R3 back up to VCC which will restore RST to high, bringing the Arduino out of reset.  The values of R3 and C1 affect the timing of the reset and must be chosen appropriately.
Don't forget R1.  I can't remember the reason it is helpful, but it has something to do with the Arduino/Atmel UART.  I found the recommendation for adding it one day on an Atmel discussion board and it has solved a non-working circuit for me many times.

Hope that helps!


How can I identify GPS sattelites in TinyGPS++?

There is a bug in TinyGPS++ as it only counts GPS satellites. See https://github.com/mikalhart/TinyGPSPlus/issues/52

PRN numbers are used to identify satellites:

  GPS = 1 to 32

  SBAS = 33 to 64 (add 87 for PRN number)

  GLO = 65 to 96


No, the settings for the colors are stored in RAM on the individual devices so they need to be reprogrammed every time they are powered on.

On the other hand, it is possible to use a much smaller device such as a surface-mount ATtiny85 to program them, and light_ws2812 runs on said device just fine. And once they have been programmed it is possible to put the MCU in deep sleep so that it consumes almost no power.


Writing to flash memory fails with Optiboot

The bootloader which ships with Arduino IDE is version 4 which was already in the Uno from factory. To use the do_spm function you need Optiboot 8 build with this support enabled. It is not enabled in the default builds, because it doesn't fit in the usual Optiboot size for Uno.

The hex file of the bootloader is here. Simply replace the hex file in AVR boards package with this one.


It is most likely caused by the fact that a correct version of MenuSystem library is not properly installed.
Check whether you can add the library to your sketch.

EDIT: added that also the version should be correct


How can i change by esp8266 baudrate, as I accidentally changed the baudrate to something else(which I dont remember)?

I encountered a similar situation where I accidentally set the baudrate to 8000 with the AT commands.
Thankfully I remembered the baud rate I set, so I used PuttY to create a serial communication with the port with the weird 8000 baud rate and changed the baud rate back to 9600.
The method can be found here: http://flower-platform.com/2015/12/16/esp8266-with-at-commands-connect-from-pc-with-putty/
The AT command I used to change the baud rate:
AT+UART_DEF=9600,8,1,0,0


Push to 2D array (log) but last value pushed is everywhere

It is easy - in your log you store POINTERS to strings.

And you then create variable on the stack (ouch) and put its address to the log.

Then you leave the function (loop) (so that variable is forgotten and can be overwritten by anything). I will not say it is luck, that nothing uses the stack enought to make a problem before the loop is called again, as it disguise the problem. The POINTER in log_lines[0] points to UNALLOCATED place (where the variable msg once was).

Then the loop allocates variable msg (at the same place, as its previous run by the chance) so the POINTER stored in log_lines[0] (still pointing to the same place) points to the variable msg (and its content). By pure (bad) luck.

Then you overwrite the variable msg with a new value, so the log_lines[0] point to that new value.

Then you move the content of log_lines up, so the log_lines[1] now points to the variable msg (and its NEW value) as well as log_lines[0].

Then you assign log_lines[0] with address of variable msg (which it accidetally already contains)

Then you wonder, why variable msg accesed via log_lines[1] is exactly same as the (same) variable msg accesed vial log_lines[0] and why it contains the last (NEW) value, which you assigned into it.

Some of possible solutions are:

1) allocate place on heap (memaloc it) in the addToLog function, copy the text into it and store pointer to THIS place (and do not forget deallocate   last log_lines before overwriting it - if it is not null (as untinitialized values are all 0)) which could lead to (relativelly) expensive heap manipulations and possible memory fragmentation.

2) allocate log_lines as array of char arrays of given len, copy the content of each line in another loop inside addToLog and then copy(and possibly truncate) the text to the log_line[0]

3) keep static index of last used log_line and in addToLog just increment it (wrapping around the len of the array), then overwrite the line pointed by index with (truncated) text and in printLog just start cycle on the index and climb (wrapping around len of the array) until you are again at index (which you would not print again and stop)


There is a nice example for Arduino here.

Connecting 2 Arduinos by Bluetooth using a HC-05 and a HC-06: Pair, Bind, and Link

The Uno works the same way as the board in the example.

Arduino 1

Arduino 2


Adjusting variables in code without reprogramming?

If the number of choices is limited (device types, a few selections of sample rate), you might consider a bank or two of DIP switches.


How to use Aiduino module to connect to computer network?

An Arduino is completely incapable of doing such a difficult task. It's literally impossible because the processor isn't strong enough, it has no built in network capabilities that support NAS, it has no USB software built in, and so on and so on.

But you can use a Raspberry Pi. They are cheap for their capabilities, they do require quite some programming to get it to work but there's a huge community that has guides for everything. Best of luck :)


First, depending on the degree of reliability you need, you may not actually have to do this yourself, as the bluetooth implementation will already invisibly-to-you add, verify, and remove a packet and checksum framing around your data.  But let's assume you want to add your own as well.

A packet is a batch of data to be transmitted as a contained unit.  It may or may not contain exactly one useful message, but it is quite convenient if it does, and since you will be doing your own packetization (at this level) you can make sure that it does.  So basically you will transmit something that has a structure, for example:

Hi, I'm a packet
attention HAL
"Open the pod bay doors"
The bytes in this message should add up to xx if you ignore the overflow
That was a packet

There are countless ways you could implement this, but your life will be a lot easier if you make both the messages and the packet structure human readable, so that you can watch on the serial monitor, and perhaps even type manually.  So let's say you did something like

M1=200/BF\n

For simplicity sake, instead of having a "Hi I'm a packet" header, we just use the newline character '\n' to mark the end of a packet, and assume that whatever comes next is the start of a new packet.  Further, since bluetooth is already creating a one-to-one link, you don't need to address who you are talking to.

Now we have a message, for example "M1=200" meaning "drive motor 1 at PWM level 200" (out of 255).

I'm somewhat randomly choosing the '/' character to mark the division between the message body and it's checksum.

"BF" might be the low two hex digits of adding up all the previous bytes in this message (it's not, I just picked something random).

And finally you have your newline to mark the end of a message and the end of a packet, since in this scheme we've decided that 1 packet = 1 message.

For extra fun, if the robot itself is not dangerous, you can make a test mode where the receiver will accept messages with no '/' and checksum, and only check the checksum on those where it is present.  This would allow you to manually type messages into a terminal when you are experimenting.  Or you can make your own specialized terminal program which calculates and appends a checksum each time you press return


The problem you get is that read() does not wait for a byte to be available, it just returns -1 if there is no byte available; converted as an unsigned byte that becomes 255.

In ISO-8859-1, which I guess is the encoding that your serial monitor is using, 255 translates to ÿ, so this is exactly what you observe.

Fixing this problem is straightforward, just check that a byte is available on SoftwareSerial before reading it:

void loop()
{
    if (GPS.available()) {
        Serial.write(byte(GPS.read()));  //as of Arduino 1.0
    }
}


You are requesting 80 String objects.

Each String object allocates memory to store its data. When you provide a string constant that string constant data's length is used for the allocated data size (including the NULL character at the end), and the string constant data copied in.

On top of that you have a bunch of other data that is needed for the String class to do its work. The total size of a String object is 6 bytes.

So the memory you need for your array of Strings can be calculated as:

Let C be the total number of characters in all the string constants
Let N be the number of String objects in the array
Let T be the total number of bytes.

T = N * 6 + C + N

With no string constant data that would be:

T = 80 * 6 + 80

That's 560 bytes already, before you even start thinking about putting in the string constant data.

Also you may like to add to that the fact that the compiler may (though I am not certain on this) be also copying the string constants into RAM first because they aren't forced into PROGMEM with the F() macro.

So since you only have 2KiB of RAM to begin with, and a quarter of that is instantly gobbled up with your array, you can see how things might not be too happy.

Oh, and the String's internal storage is allocated at run time, not compile time, so the compiler can't know that it'll overflow - only when you run the program will it overflow and things go horribly wrong.

So you need to ask yourself "Why do I even want an array of String objects?" and the answer is most certainly: "Under no circumstances do you ever want an array of String objects". In fact I am a strong advocate of never using String objects ever, for any reason whatsoever.

If your data is constant there is absolutely no reason to store it as String objects. It's constant. It should remain constant. Copying it into a String object means it's no longer constant and wastes many many resources.


Everytime, that you want the LEDs to change, you need to call the FastLED.show() function. You are doing that only once after you set the values multiple times. Also you need 2 delays in total (1 for the LED being on, 1 for it being off).
The workflow for blinking an LED would be:
Set LED to on
Call show function
Delay
Set LED to off
Call show function
Delay

You need to translate that to code.


TI ADS7250 Read From SPI and SPI1 Simultaneously

You can't use the normal SPI library for communicating with this device properly. Well, you can, but you will only be able to use one channel - the other will be completely ignored.
SPI only works on one MISO pin - you need two.  There are two other types of "SPI" that are used by devices, most notably SPI flash chips: DSPI and QSPI (dual SPI and quad SPI). You want DSPI.
Unfortunately the Arduino doesn't do DSPI, so you will have to "bit bang" it, which means manually manipulating the IO pins to create your own SPI signals in software.
Now... on to the datasheet:
The important part is the timing diagram on page 9. From that you can see that you just send 32 clock pulses and the chip responds, after 15 pulses, with the data.
So if you just do 4 8-bit transfers back-to-back then you get the data. It doesn't matter what you "send" in those transfers since the MOSI pin isn't connected to anything.
As far as speed goes, 24MHz is the maximum speed that it will run at. The actual speed is dictated by the Arduino and how fast you manipulate the SCK pin. That can be as slow as 1x10-1000Hz if you really want.
Data should be read on the falling edge of SCK.
So you could write a little routine that looks like:
uint32_t resa = 0;
uint32_t resb = 0;

pinMode(SCK, OUTPUT);
pinMode(SDI_A, INPUT);
pinMode(SDI_B, INPUT);
pinMode(CS, OUTPUT);
digitalWrite (CS, HIGH);

digitalWrite (CS, LOW);
for (int i = 0; i < 32; i++) {
    digitalWrite(SCK, HIGH);
    digitalWrite(SCK, LOW);
    resa <<= 1;
    resb <<= 1;
    resa |= digitalRead(SDI_A);
    resb |= digitalRead(SDI_B);
}
digitalWrite (CS, HIGH);

Serial.print("A: "); Serial.println(resa);
Serial.print("B: "); Serial.println(resb);

So for 32 iterations you pulse the clock HIGH then LOW, then shift each result 1 bit to the left, and then add in the newly read bit into the lowest bit position.
You could speed up operation by using direct port manipulation and avoiding the slow digitalWrite() and digitalRead() functions.


Make sure that you are giving it enough power, seaching and registering to a network needs a current peak of 2amps, if the model you are using has a built-in regulator plug it to a stable 5v 2amp source of power and try AT+COPS? again, it should work; you can try with the computer power supply it has a 5v 2amp source.


How to connect a a three state switch (ON-OFF-ON) to arduino?

As stated by st2000, it's not common practice to have two separate programs running on one microcontroller.

The solution is simple, use the switch to "switch between" behavior.

if(switch is on){
  //Automatic
}else{
  //Bluetooth
}

You should also use functions, to make your code more readable.

This might work:

#define echopin  8 // echo pin
#define trigpin 9 // Trigger pin
#define switchPin 10

int maximumRange = 30;
long duration, distance;

void setup() {
  Serial.begin (9600);
  pinMode (trigpin, OUTPUT);
  pinMode (echopin, INPUT );
  pinMode (4, OUTPUT);
  pinMode (5, OUTPUT);
  pinMode (13, OUTPUT);
  pinMode (6, OUTPUT);
  pinMode (7, OUTPUT);

  pinMode(switchPin, INPUT_PULLUP);
}

void loop ()
{
  if (digitalRead(switchPin)) { //If the switch is pressed.
    automaticLoop();          //Do the automatic control.
  } else {                   //If not pressed.
    bluetoothLoop();          //Do the bluetooth control.
  }
}

void measureDistance() {
  digitalWrite(trigpin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigpin, HIGH);
  delayMicroseconds(10);

  duration = pulseIn (echopin, HIGH);

  distance = duration / 58.2;
  delay (50);
  Serial.print("Distance is: ");
  Serial.println(distance);
}

void automaticLoop() {
  measureDistance();

  if (distance >= 30 ) {
    digitalWrite(4, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    delay (200);
  }

  else if (distance >= 15 && distance <= 25) {
    digitalWrite (4, HIGH);
    digitalWrite (5, LOW);
    digitalWrite (6, LOW);
    digitalWrite (7, LOW);
    delay (1000);
  }
  else if (distance < 15) {
    digitalWrite (4, LOW);
    digitalWrite (5, LOW);
    digitalWrite (6, HIGH);
    digitalWrite (7, HIGH);
    delay (1000);
    digitalWrite (4, LOW);
    digitalWrite (5, HIGH);
    digitalWrite (6, LOW);
    digitalWrite (7, LOW);
    delay (1000);
  }
}

void bluetoothLoop() {
  //Code for bluetooth.
}


What is the best arduino board for a robotic arm?

If you are hoping to drive the arm straight from the Arduino, that's not going to work.

What you should do is:

Define the maximum weight and size of the load your arm will carry.
Define expected precision and speed of the movements.
Count the Degrees of Freedom (DoF) your arm will need (1 DoF = 1 simple joint)
Figure out size and materials of each part of the arm
Calculate the torque required at each joint (yes, you need some basic physics calculation)
Identify the motors you want to drive (DC are inexpensive but not very well suited for this, without lots of additional control logic & HW - stepper motors are better, but they still do require some additional effort - servos are the easier way but they are a bit more expensive)
Define the requirements for both the micro controller and the power supply, based on the previous choice.

If you can refine your question, based on the few points I sketched, you will get ahead much faster and with less risk later on to have to backtrack and re-design something.

You might have already answered some of those steps, then I suggest you list here your choices.

Similarly, if you are referring to some link you found (instructables, etc.) please post it.

As reference, hobbyking has an extensive catalog of motors and power supplies. You can find the same items also on ebay, but hobbyking can be used at least as reference for various specs (power, torque, weight, etc.).


What is the overhead time of using Serial library compared to coding it up in AVR C (not using Arduino code)?

There's no reason to doubt the Arduino hardware. We need to put some figures on what you are experiencing, such as the baud rate and buffer sizes.

I would expect with this sort of hardware flow-control that you would potentially send a byte or so more than expected, because it takes a finite time to react to the flow-control signal. This is to be expected, particularly as the hardware has a buffer, so it can be starting to send a byte at the moment you get the signal to stop sending.

I expect you would have a leeway (say of 10 bytes) where you expect the sender to stop sending within that time.

  A problem can arise if the Arduino API is providing more latency than the path under test

I'm not sure what you mean by this. However the HardwareSerial class has a 64-byte buffer (if you are using a Uno) which means you potentially have put 64 bytes into it, before noticing that the sender wants you to stop sending.

This is probably what you are experiencing. See HardwareSerial.cpp:

// Define constants and variables for buffering incoming serial data.  We're
// using a ring buffer (I think), in which head is the index of the location
// to which to write the next incoming character and tail is the index of the
// location from which to read.
#if (RAMEND < 1000)
  #define SERIAL_BUFFER_SIZE 16
#else
  #define SERIAL_BUFFER_SIZE 64
#endif

For this test you might want to edit that file and reduce that number, substantially.

Alternatively, use SoftwareSerial. I don't think that buffers writes (as it doesn't have hardware to do them in the background) so that would reduce the latency to a single byte.

  I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial API.

It's not an overhead, it's a design issue. If you do what I suggested it should work fine.

  What I mean by Arduino API overhead is the fact that the actual hardware interface is substantially abstracted away from the register level implementation ...

Well, not really. When you write a byte it puts it into a circular buffer, as you would expect. When the hardware is free to output another byte (generally called by an interrupt) it outputs it. What else could it do?

However you are absolutely free to address the hardware registers yourself and not use HardwareSerial.

To keep things simple though, what you really need to do here is not buffer because that makes reacting to the flow-control flag somewhat slow. And here is how to do it:

Serial.write ('a');  // or whatever
Serial.flush ();  // wait until everything is sent

Now you have thrown away the buffering, and you can just send at the rate that the hardware can (probably slightly less).


Possible error in CAN-Bus shield schematic?

No, it's not a mistake. It's related to this statement on their Wiki:

  When you use more than two CAN Bus Shield in one net, you should take the impedance into consideration. You should either cut P1 in the PCB with a knife, or just remove R3 on the PCB.

If you look closely at the pads of P1 you will see a small trace joining them together. That is the "rogue" green line you found. By cutting that trace you disconnect the termination resistor. You can then re-connect the termination resistor by soldering the pads together again.


How do you change the state of an image on a TFT display when the associated pin changes state?

It's quite silmple: just draw a box over the image the same colour as the background.

Either that or draw a different image over the top of the existing image.


Interrupt fires a random number of multiple times for one pulse

Firstly, unless the processor pin is a Schmitt trigger, increasing capacitance will only make the problem worse by allowing any noise to be interpreted as multiple high-low transitions.  For a CMOS logic input the area around the transition point of 1/2 VDD typical is actually an area of linear operation, not digital.

A Schmitt trigger introduces hysteresis such that when the signal is interpreted as a high level, it must go low by more than the hysteresis to be interpreted as a low level again.  This is accomplished with a bit of positive feedback added to a buffer where the output transition from low to high then pulls the input that much higher or a transition from high to low pulls the input that much lower:

The red line represents the typical CMOS threshold and the green lines represent the thresholds defined by the hysteresis of the Schmitt trigger.  The hysteresis defines the noise immunity of the input.  Most processors have pins that are equipped with a Schmitt trigger or and external device like a 74HC14 can be used.

Another way to deal with this type of noise is to lock out any transitions within the expected pulse-to-pulse transitions:  Once triggered, no more transitions are allowed until the lock out time expires.


What options do I have to wirelessly connect my computer to an arduino?

How about using wifi?
The esp8266 costs as low as 3$ and has good range.
here's a quick tutorial
What you'll need to do is send a command to the esp8266 and in turn it'll communicate with the arduino via Serial (or Software Serial) and tell it what to do.


How to convert numbers from Serial port input to HEX String?

You have the number. It's made up of two nibbles, each representing 4 bits (1 hex character).

If you want to do a manual conversion take the first nibble (AND with 240) add it's value to "0" then do the same for the lower nibble (AND with 15).

OR

What I would do is use:

char HexString[3];
sprintf(HexString,"%02X",HexInt);

since you're not dealing with floats, you're good to go.

OR

edit: I recalled a printf function that we put together once before, I don't know if it would work with SoftwareSerial, so you might have to play around with it a bit, but as a 3rd option, you could try the following. I don't have access to an Arduino or compiler at the moment, otherwise I'd have a play with this right now.

Before your setup:

// Function that printf and related will use to print
int serial_putchar(char c, FILE* f) {
    if (c == '\n') serial_putchar('\r', f);
    return Serial.write(c) == 1? 0 : 1;
}

FILE serial_stdout;

In your setup, add:

// Set up stdout
fdev_setup_stream(&serial_stdout, serial_putchar, NULL, _FDEV_SETUP_WRITE);
stdout = &serial_stdout;

in your loop, change your assignment to:

HexString = printf("%02X",HexInt);

from: https://arduino.stackexchange.com/a/480/304


Do I need 3 voltage dividers to control ESP8266

For ESP 3.3V power supply, I'd recommend a distinct 3.3V regulated supply.

Of course, the Arduino UNO already has a 3.3V output but it may not supply enough current to the ESP (current consumption can go up to almost 200mA): UNO 3.3V pin is limited to 50mA. So do not use it or you may roast your UNO.

Using resistors to output 3.3V from Arduino 5V might be possible (the UNO 5V pin can provide ~400mA) but it would be a big waste of energy because you'd have to use low resistor values to be able to supply 200mA for instance.

You might possibly use a 7833 regulator with additional caps to provide 3.3V from Arduino 5V pin (or Vin directly if your UNO is powered through the DC power jack, not USB)

For ESP RX a voltage divider is foreseeable but it may trigger issues due its switching response time, which may be too slow when transmitting data at high baud rates. I recommend using a MOSFET based level shifter:

The advantages of this circuit are:

it has the fastest switching response time
it can work in both directions (3.3V -> 5V and 5V -> 3.3V)

You can also buy some cheap ready-made breakouts using this circuit and offering several level shifters.

For ESP TX, I'd also recommend the same level shifter circuit as for RX (if you can make one, you can make two).


What bootloader is present by default on Arduino Uno?

It is defined in the file "boards.txt" (arduino-1.8.7\hardware\arduino\avr\boards.txt).

For example the Arduino Uno is called "Arduino/Genuino Uno" and it has the bootloader: uno.bootloader.file=optiboot/optiboot_atmega328.hex

You can find that hex file in the folder arduino-1.8.7\hardware\arduino\avr\bootloaders\optiboot.

The official Arduino boards are shipped with the newest bootloaders.
Sometimes the bootloaders are improved or changed. That is mentioned in the Release Notes.
For example the latest change to a bootloader is that the Arduino Nano has now the same optiboot bootloader as the Arduino Uno.

When buying a Arduino clone board, anything is possible.

Some companies make there own Arduino-compatible boards with their own bootloaders.


Creating an array with the length coming from a library

There is absolutely nothing wrong with putting it in the header.

  §9.4.2/4 If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.

Since you're just using it as a simple constant "integral" value there is nothing wrong with putting it in the header.


How to use the ESP32 WROOM GPIOS above #18 with arudino ide?

Found the answer, albeit a simple one. This is my first go around with arudino so it will look ridiculous to those who program microprocessors (including myself)

You need to declare the pin to be an output before use. The inconsistent thing is, this only happens sometimes. For some of the pins you don't need to use pinMode for them to work.

  pinMode(relayPin1, OUTPUT);


Can I control a cellphone's lcd (+touch screen)?

No. For two reasons:

You will struggle to find the pinout of the TFT (or even identify the model). It will have most likely been custom made for the phone.
The Arduino doesn't have a GPU to drive it. Arduinos need a TFT with built in GPU since they lack the resources to drive one directly.


Local variable usage in SRAM not counted

Why is the local variable not counted?

Let us start with the function availableMemory(), what does it do?

int availableMemory()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

It returns the amount of memory between the top of stack (address of local variable v) and the heap end.

The answer lays in how the compiler works. One strategy that is used is function in-lining. This forces the functions test(), printAvailableMemory(), availableMemory(), etc. to be unfolded into loop() (which actually also gets unfolded into main()).

A common frame with the local variables is created and the variable for the top of the stack becomes one of them. You need a tougher test case to see how the stack top changes, e.g. tell the compiler not to in-line a function.

int availableMemory() __attribute__ ((noinline));

To check this generate the assembly listing for your sketch.

Cheers!


From the datasheet, working voltage for MH-Z19 is 3.6V to 5.5V, so 3.3V is not enough. (Although the interface runs at 3.3V).

Also, the Uno might not run reliably at 16MHz and 3.3V.

Edited image from datasheet page 303.