Only some ports on the Atmega2560 support pin-change interrupts, specifically ports B, E (bit 0), J (bits 0 to 6) and K.

Looking at the reference schematic that means that these pins on the board are supported:

     Chip
Name  Pin  Pin on board
-----------------------

Port B

PB0 - 19 - D53 (SS)
PB1 - 20 - D52 (SCK)
PB2 - 21 - D51 (MOSI)
PB3 - 22 - D50 (MISO)
PB4 - 23 - D10
PB5 - 24 - D11
PB6 - 25 - D12
PB7 - 26 - D13

Port E

PE0 - 2 - D0 (RXD0)

Port J

PJ0 - 63 - D15 (RXD3)
PJ1 - 64 - D14 (TXD3)
PJ2 to PJ6 - not connected on board

Port K

PK0 - PK7 - (89 - 82)  - A8 - A15

Thus you can see that D10 to D12, which you say works, are in that list. Other random ones would not be.

SoftwareSerial

You can see confirmation on the page for SoftwareSerial where it says:

  Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

This is because SoftwareSerial uses pin-change interrupts to detect incoming serial data, and thus the disclaimer on that page about which pins it will work with.

Atmega2560 pin-outs

  PinchangeInt should work on any digital pin

Note that the Atmega328P (as used in the Uno) has less ports, and all are available for pin-change interrupts on that board.


The line:
HX711 scale;

is called the "instantiation of the object". It creates a new object called scale which is an instance of the HX711 class. It is this "object" that is your interface to the HX711 physical device.
To use two of them you first need to have two objects - one for each HX711. You can name them whatever you like.  For example:
HX711 scale1;
HX711 scale2;

The line:
scale.begin(DOUT, CLK);

is where it tells the HX711 object which pins the HX711 chip is connected to. In this case DOUT and CLK which you have defined as 3 and 2 respectively.  You could just as well have written:
scale.begin(3, 2);

Each object has to be "begun", so you would need a begin for each object you instantiate:
scale1.begin(3, 2); // DOUT = 3, CLK = 2
scale2.begin(5, 4); // DOUT = 5, CLK = 4

Now for every operation that you did on scale you would instead do on your two new objects:
scale1.set_scale(calibration_factor);
scale2.set_scale(calibration_factor);

etc.
And when you want to take a measurement you just select which object to read from:
Serial.print(scale1.get_units(), 1);

or
Serial.print(scale2.get_units(), 1);

You can add a third by creating and using scale3 in exactly the same way as scale1 and scale2.


Conditions with GSM module SIM900 doesn't execute

I’ve solved the condition problems by making the condition with the ASCII code of ON and OFF.

I replaced:

if ( msg == “ON”)

with

if(msg.indexOf("ON")>=0)

and replaced:

else if (msg == "OFF")

with

if(msg.indexOf("OFF")>=0)


Trying to read from AD5934 using Arduino on I2C

I think you should re-see AD5934x datasheet.

To read data from AD5934, we have three ways:

read single byte
read block
using pointer command

If you want to read multi byte, you can refer to my way:

unsigned long GetRegisterValue(unsigned char regAddr, unsigned char len)
{
    unsigned long regValue = 0;
    unsigned char index;
    unsigned char wrData[2] = {0,0};
    unsigned char rdData[2] = {0,0};

    for (index = 0; index < len; index++)
    {
        wrData[0] = 0xB0; //assign pointer cmd
        wrData[1] = regAddr + index;
        I2C_Write(AD5934_ADDR, wrData, 2);
        rdData[0] = 0xff;
        I2C_Read(AD5934_ADDR, rdData, 1);
        regValue <<= 8;
        regValue += rdData[0];
    }

    return regValue;
}


Buffering data from EthernetServer clients

Well, I asked on the #arduino IRC channel, and realized my stupid mistake. I was setting the buffer to "" inside the loop.


Is there a way to read real-time port selection on Arduino IDE when using third-party toolchain and uploading program?

After someone from Github gave me a link, I think I ve found the way to read the real-time port selection even using third party uploading program.

The key is command line argument in the "Platform.txt" file located under "arduino15" folder. If you have the same issue as mine, try look up this link, where you will find loads of useful information:
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification

PS: rmb, after you change the command lines in the txt file, always close and restart your arduino IDE before those changes you made take effect.


How to program Esp8266 remotly via wifi?

The firmware update over WiFi is called OTA update. OTA stands for "over the air".
The esp8266 can OTA update itself. The Arduino library for this is called ArduinoOTA and it is bundled with the ESP8266 Arduino boards support package.
See the example for ArduinoOTA library in IDE Examples menu.
Other MCU have the self update option too. ESP32 has it of course, then for SAMD boards Arduino made WiFi101OTA library. For ATmega I made the ArduinoOTA library based on the WiFi101OTA library so it supports SAMD too. And it doesn't have to be WiFi. Cable works too.
The OTA update stores the uploaded firmware in free part of the flash and after successful upload it moves the firmware to target location and resets the MCU.
For any Arduino with SD bootloader OTA update is possible, because the library only has to store the uploaded firmware to the SD card and reset the MCU.
For small ATmega ftp bootloaders exists. Here the bootloader waits for network upload.
Update over a second MCU solutions are for MCU with less flash, mostly for the ATmega328p. The ESPLink firmware and the WiFiLink firmware for ESP8266 can flash attached ATmega328p over RX/TX. The ESP8266AVRISP can flash ATmega wired over SPI.
ArduinoIDE supports OTA upload. It creates a network port based on MDNS record propagated by the ArduinoOTA library or firmware with OTA support.

Other update way is to download the new firmware from a server or upload it over a web page. ESP8266 has for this ESP8266httpUpdate and ESP8266HTTPUpdateServer libraries. For SAMD, ATmega and other boards my ArduinoOTA library has examples on how to store and apply the update received as download or upload.


How to serve multiple connections with an ESP8266 and an Adruino?

I might not have understood what you are trying to do, but if it is to use the ESP8266 to allow the Nano to connect to WIFI and act as a web server then I believe you are doing this the hard way.

The ESP8266 is an 80 or 160MHz microprocessor with 64KB Program Ram + 96KB data RAM.  You are using a 16/32MHz microprocessor to generate pages and pass them to it.  I would recommend that you investigate using the Arduino IDE to program the ESP8266 in "Arduino C" it comes with a set of examples that include webservers (which is what I think you are trying to do).  Keep the Nano if the ESP8266s 10 digital and one analogue ports aren't enough to interface to you hardware.


After some extensive testing with several modules (not just blindly trusting the documentation), here's what I found.

Short answer : maximum 10 AP connections for the ESP32 running ESP-IDF 4.0 (updated around 1st of march 2020), and no, it can't be increased (easily).

Details :

The maximum number of AP connections is defined somewhere in libnet80211, and can't be modified since I have no access to the source code.
when the 11th station tries to connect, libnet80211 prints I (39682043) wifi: max connection, deauth!, more or less like the ESP8266 for the 5th station
Changine the ESP_WIFI_MAX_CONN_NUM (defined in esp_wifi_types.h:258) from 10 to anything else ends up in unpredictable behavior (I'm labelling this as unpredictable since without the libnet80211 code, it can't be reliably assessed).

I'm not giving up on increasing the number of stations yet, so maybe there'll be an update to this answer.


Does receiving data with SPI stop the main loop?

Some (complex) processors have dedicated hardware to handle the I2C or SPI transaction.  Other (simpler) processors do not.  In such processors with no supporting hardware the bus must be emulated using software.  This takes time away from other processor activities.

You will have to determine if the processor in your Arduino (and there are many different types of Arduinos which use many different processors) has hardware to support I2C and / or SPI bus transactions with out help from the software.

Note: Even in cases where there is hardware to handle I2C and / or SPI transactions, badly written software can still trip up the processor and make it unavailable for other purposes.

Note: Even in cases where there is no hardware to handle the I2C and / or SPI transactions, well written software can handle a moderate demand from tasks while also handling serial bus processing.

[Comments based on Arduino board type added later to answer:]

You are using an Arduino Mega 2560 which uses the Atmel ATmega2560 processor (one of several described in the linked-to specification).  Searching the ATmega640 documentation shows matches for "TWI" (Atmel's equivelent to Philips' I2C) and SPI.  So, if the I2C or SPI driver software has been well written for the ATmega2560 processor, it should be using the processor's hardware.   Which makes the I2C or SPI feature more (but not entirely) immune to what ever else you have the processor running.

At this point it would be prudent for you to check if you are using such a driver.  Make sure you are not using a driver which "emulates" these protocols in software.  Also, make sure, if there is a hardware restriction, that you are using the pins on the processor designated for the type of bus used.  Some driver may be extremely flexible allowing you to designate a pin with out hardware support and automatically implementing the protocol in software.

[Comments based on code added later to answer:]

You are your self implementing what might be handed off to built in processor hardware in software.  Specifically you are emulating the PWM hardware feature in software.  It is likely that even the most efficient I2C or SPI code (even with supporting hardware) will effect such sensitive software.

It would take a fair amount of work to make this software "work better".  In general, you should consider not using delays and implementing a call-back paradigm based on a timed interrupts.

Alternatively, you might investigate why the Arduino PWM driver does not give you enough resolution.  The hardware may in fact provide more resolution than the driver permits.  Re-writing the PWM driver may be easier solution.


The Atmel datasheet, page 305, Section 29.5 "System and Reset Characteristics" provides some useful information for the reset pulse. It says that the worst-case minimum pulse width is \$2.5\:\mu\textrm{s}\$. It then goes on to say that the ramp rate has to be contained between two boundaries; no faster than \$10\:\frac{\textrm{kV}}{\textrm{s}}\$, but also no slower than \$10\:\frac{\textrm{V}}{\textrm{s}}\$. So there are some restrictions that should be managed by any reset system.

There are some nice reset circuit ICs available which provide a manual reset input as well as a control line. I'd probably use one of those about a circuit I cared about. Okay. Actually, I'd make my own out of a PIC10LF320 in a SOT-23-6, which also includes a brown-out circuit of its own, which I'd probably also re-purpose, as well.

But let's look at this circuit. DTR is normally held HIGH (I believe) and is pulled LOW in order to initiate a reset. Assuming that the two MCUs are running on different power rails (or the same, doesn't matter), \$C_5\$ is charged up to the difference between the ATmega328's rail (via \$RN_1\$ and the DTR output line's HIGH value.) If there is no difference, the voltage will be nearly zero. But if the rails are different, then there will be a small voltage across \$C_5\$ that represents this difference.

When DTR is pulled LOW, that end of \$C_5\$ is also pulled down to that voltage (close to ground.) For the first moments, this also means that the other side of \$C_5\$ is similarly pulled downwards, too. If there was some voltage rail difference, then that's the voltage that appears at the reset pin of the ATmega328. Depending on the voltage differences between the MCUs and the reset pin requirements of the ATmega328, this could be a problem. The datasheet says that it may be required to be as low as \$600\:\textrm{mV}\$, though the typical only requires to be pulled down to \$1.3\:\textrm{V}\$. But if no difference in the rails, then hopefully near-ground appears at the reset pin of the ATmega328. I'm going to assume there is no difference, here, so that we at least have a good chance it works okay.

Now, as soon as \$C_5\$ is yanked down by DTR, \$C_5\$ begins charging up through \$RN_1\$, starting at a rate of about \$500\:\mu\textrm{A}\$. The time constant is \$1\:\textrm{ms}\$. So the voltage will rise rapidly. Assume that we only just barely achieved the required \$600\:\textrm{mV}\$ at the start (the capacitor held a slight charge.) Then we'd cross over the minimum rising threshold of \$1.1\:\textrm{V}\$ within about \$100\:\mu\textrm{s}\$. This is well more than long enough for the earlier mentioned minimum reset pulse width of \$2.5\:\mu\textrm{s}\$. So the spec is met here.

Now, let's go the other direction. Let's say that now DTR is held LOW for a long enough time that it charges up to about \$5\:\textrm{V}\$ through \$RN_1\$. Now, DTR is driven HIGH. What happens? Well, the other side of \$C_5\$ will now be at about \$10\:\textrm{V}\$ (the \$5\:\textrm{V}\$ charge on \$C_5\$ added to the DTR HIGH voltage value.) This is rapidly discharged, safely, via \$D_2\$. That's why \$D_2\$ was added. Otherwise, this voltage would be presented to the RESET pin of the ATmega328 and would have to be discharged via any internal protection diodes present there (which may themselves have additional specifications that must be met.)

What's interesting here is that the RESET pin in particular is called out in the datasheet on page 299. It says that it can support up to \$13\:\textrm{V}\$ worst case. So, technically, that might mean that \$D_2\$ isn't necessary to avoid driving protection diodes in the CPU. But it is still a good idea for an entirely different reason. This is to discharge \$C_5\$ rapidly (it would be very slow, via \$RN_1\$), so that it can be used for another reset very soon after being used.

Note on the reset pin:

As Majenko added in a comment, there is a high voltage programming mode for Atmel devices like this. I frankly don't fully apprehend it, as I haven't read a datasheet on the topic. But I did find out from an Atmel video that the PC6/RESET line, which normally acts like a /RESET line, can be changed into operating like a general purpose I/O port by changing the RSTDISBL fuse, which makes the general I/O function available. The bad thing about that is that the ISP programming mode NEEDS the /RESET line to do its job. So you can't program the device anymore, if you set up that fuse. This then forces you to use the parallel programming mode that is entered using the high voltage programming mode. I would guess that entering this mode uses the /RESET pin again, but this time places a high voltage on it that is detected in order to put the device into its parallel programming mode instead of the ISP programming mode.

I can't readily find a specific programming document on the details of using this mode to program their devices. Microchip publishes them. But it appears, cursory examination only, that Atmel does not. They document how to use the mode with their tools, such as the STK500 (which I have.) But not how to design your own tool. I'm guessing, for now, that this is a matter of non-disclosure for Atmel. And given that they have it available for so many different devices, I can see why they might want to avoid having to support it.

The details on this pin are starting to get complicated-sounding. But pins cost money and silicon is cheap. So Atmel, like other companies, try to come up with methods to use their scarce pins to provide as much versatility as they can to sell devices.

That's it.


Would rewriting my code in C help reduce RAM usage?

The simplest approach to reducing RAM usage of the program shown is to get rid of the three 128-byte pixel arrays.  They are not needed for the program to function.

Instead of writing

pixelsArray1[i]=analogRead(A1)/4;
pixelsArray2[i]=analogRead(A2)/4;
pixelsArray3[i]=analogRead(A3)/4;

write

if (analogRead(A1)/4 == 0 && analogRead(A2)/4 == 0 && analogRead(A3)/4 == 0) ++foundZero;

where foundZero is initialized to zero before the loop.  After the loop, you say something like

while (foundZero--) {
  digitalWrite(1, HIGH);
  delay(2000);
  digitalWrite(1, LOW);
  delay(2000);
}

to toggle pin 1 as many times as there were three zero pixels.

Note, the timing of the if (...) ++foundZero; statement may differ from pixel to pixel because the && evaluation may short circuit.  If the timing matters, save data in temporary variables, or check if the sum of the three is zero, etc.


Pressure transducer / sensor (0.5 - 4.5V) innacurate analog pin readings

I tried same setup with arduino uno and the problem is gone. It also works on micro as long as gnd and 5v pin is connected to uno. Uno measured voltage is 4.88V and micro 4.60V could a voltage difference this small cause this? What else could this be?

Reinstatement of incorrect edits by Annonomus Person
(AP: Please do not edit answers in such a way that you entirely change their meaning. In the current discussion "the board" is meaningless. We are trying to distinguish between symptoms seen in two different 'boards', an Arduino Uno, and an Arduino Micro.)

Looks to me like the problem is with the Arduino Micro's 5V supply then.

If you are powering the Micro from an external supply (not USB), then 4.6V on the Micro's "5V" output would indicate that the 5V regulator is not operating within its expected range.

If you are powering from USB, then the regulator is not in play. The 4.6V would indicate a problem with the USB's 5V supply.

Likely possibilities:, either the upstream supply is inadequate, or the micros and whatever is attached to it is drawing too much current.

I suspect that the transducer output is fluctuating in a way that's too rapid to be seen by your meter, but which is sampled by the Arduino Micro, giving your varying result numbers.

Either the "4.6V" is inadequate to run the transducer, causing erratic transducer output, or the 4.6V itself is fluctuating, with similar results at the trans output.

And you might also check the ground between micro and transducer -- are you sure that's wired correctly?


Minimal example of Task Scheduler Blink?

#include <TaskScheduler.h>

// Scheduler
Scheduler ts;

/*
   Approach 1: LED is driven by the boolean variable; false = OFF, true = ON
*/
#define PERIOD1 500
#define DURATION 10000
void blink1CB(); // <-------------------------------------------|
Task tBlink1 ( PERIOD1 * TASK_MILLISECOND, DURATION / PERIOD1, &blink1CB, &ts        , true );
//           (     500 * 1UL (ms)        , 100000 ms/ 500    , function , just put it,  ?   )

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  ts.execute();
}

inline void LEDOn() {
  digitalWrite( LED_BUILTIN, HIGH );
}

inline void LEDOff() {
  digitalWrite( LED_BUILTIN, LOW );
}

// === 1 =======================================
bool LED_state = false;
void blink1CB()
{
  if ( LED_state )
  {
    LEDOff();
    LED_state = false;
  }
  else
  {
    LEDOn();
    LED_state = true;
  }
}


You invoked the builder, but not an upload to the board. The builder created a hex file.You should use avrdude for upload.

Or use Arduino IDE which does it with a click on a button


Using the Serial object pulls HardwareSerial0.o into your program
linkage. This file defines, among other things, the ISRs (interrupt
service routines) associated with the serial port. ISRs are defined
using the ISR() macro from the acr-libc. This macro creates a
function prototype and assigns some attributes to the function,
including the used attribute which tells the linker that it
should consider the function to be used, even if it cannot spot a single
call to it within the compiled program. The ISR cannot then be removed,
and it in turn keeps lots of code from the Serial implementation.
Edit: As pointed out by the busybee in a comment, although f()
cannot be removed at link time, it can be removed at compile time if you
give it the static qualifier. This has the added benefit of triggering
a compiler warning:

warning: 'void f()' defined but not used [-Wunused-function]


Does the ESP8266 somehow remember wifi access data?

Yes, normally the last WiFi credentials will be saved in flash and the ESP8266 loads this data on bootup and reconnect to the last known WiFi. See https://github.com/esp8266/Arduino/issues/2843#issuecomment-334250100:

the SDK stores some info, including the wifi credentials, in a sector of the flash.
That sector is kept between flashings to allow for a quick startup after update. On boot, before your sketch is executed, the SDK will retrieve the wifi credentials and attempt a quick connection.

This behaviour can be controlled by using the function WiFi.setAutoConnect(autoConnect) as documented in https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/station-class.rst#setautoconnect. This in turn calls the Espressif SDK function wifi_station_set_auto_connect (API reference)

In short: This is normal behaviour. If you want to make sure that your ESP8266 does not connect to any WiFi unless you tell it do it explicitly, call WiFi.setAutoConnect(autoConnect) at the beginning.
Edit: From within the firmware code, you can use system_restore. The documentation says that it would reset WiFi related data. This should destroy previous settings. The function can be included from https://github.com/esp8266/Arduino/blob/master/tools/sdk/include/user_interface.h within Arduino-ESP8266. I have not tried this myself nor can I say that it actually erases security-critical information from flash though.

Or, as you also have found out, hard-erasing the entire flash will purge the WiFi data with absolute certainty. This can be achieved by using esptool.py with the erase_flash option, e.g. python esptool.py -p COM6 erase_flash. Then you can flash the new firmware which will not use previous WiFi settings (but will probably open up the default access point again).
Then there's also ESP.eraseConfig which erases only the relevant flash sectors.


From experience, I know the following

Using two SPI devices sometimes does not work, especially with fake SD breakout cards. Not sure about an Adafruit, but try to use only one SPI device at the same time (to check if it works better). For my project (initial setup), I had to use a SD logger extension board instead.
Sometimes it depends on the SD card which will work. Try to use older non SDHC/XDHC cards (smaller storage normally).
Use the most simple (and preferably example circuit) to test each component separately (thus your SD breakout card) before adding others (like the WIFI component). This rules out there is no problem with other components working at the same time.


Are the output pins on the 74HC595 shift register protected against shorting?

In this data sheet it says:

  When the output-enable (OE) input is high,the outputs are in the
  high-impedance state.

However on page 3 you will notice that the *OE pin controls all outputs at the same time.  So if you connect 2 output pins and one is high and the other is low and you hold *OE low ... you will likely burn out the driver for one of the 2 output pins if not the chip its self.

If you add diodes to BOTH outputs you are essentially creating a wired or gate.  (You should add a resistor.  See the examples in the provided link.) This is fine as long as you understand how a wired or gate works.


How to print something when a character touches a character

You check StickMan and Object only X position not check Y position
incase you can check StickMan Y or check StickMan action like this code below.
or try this sim https://www.tinkercad.com/things/1LiyoY5n1mS-copy-of-stickman-rush/editel?sharecode=X6rMj1GjrKoAH95qWKY21z98ttyAs5aOTAKYy6hVJ3c
// Defind it on top
bool stickManIsJump = false;

// Added some code to check StickMan isJump or not
if (mapX > 200) {
  lcd.clear();
  lcd.setCursor(stickManPosition, 0);
  stickManIsJump = true;        /////////////// ADDED
  lcd.write(byte(0));
} else if (mapX < -200) {
  lcd.clear();
  lcd.setCursor(stickManPosition, 1);
  stickManIsJump = false;       /////////////// ADDED
  lcd.write(byte(0));
}

if (stickManPosition == obsticalPosition && !stickManIsJump) {      /////////////// ADDED
  lcd.clear();
  lcd.print("Game Over.");
}


Invoke a method in the main sketch from within a library

The connection between a sketch and a library is not one-way as many suppose.  Things can go quite happily in both directions.

What you are proposing is something I do quite often when developing a library and I need to get some debugging information out of the library. Yes, it's possible to directly use Serial in the library, but that's something I don't like, and often isn't appropriate anyway, as in your situation.

However, doing it the way you propose (and I use) is actually very simple.

You just make your function in your sketch and tell the library to use it.

For example, in your sketch:

void debug(const char *msg) {
    Serial3.println(msg);
}

And in the library add the line:

void debug(const char *msg);

Then at any point in the same file (or translation unit) you can use

debug("I am here");

That is assuming that the file that you are using it in is a C++ file (.cpp).  If it's a C file (.c) then you have to treat things very slightly differently.  You see, C++ makes a mess of the function names (even vanilla functions like that) which means they can't be seen by C files.  So you have to tell the compiler "I'd like this to be usable in a C file, please".

Which you do with a special "extern" wrapper around your function:

extern "C" {
    void debug(const char *msg) {
        Serial3.println(msg);
    }
}

And then debug() is usable in a C file in the same way as above.

However now it won't work in a C++ file...  (round and round we go...)

Simple to fix: add the extern "C" to the prototype in the C++ file:

extern "C" {
    void debug(const char *msg);
}

If you want to include your "extern" in a header file that could be included into either C or C++ files it's very common to use a construct such as:

#if defined(__cplusplus)
extern "C" {
#endif

void debug(const char *msg);

#if defined(__cplusplus)
}
#endif

That will add the extern "C" wrapper for C++ files (identified by the presence of the macro __cplusplus) but omit it for C files.

I have used "const char *" as the parameter for this example, but you can choose whatever parameters are appropriate for your usage.


What is the maximum "wattage" can be pushed into an ATMega328 ADC pins?

This is actually a special case that is undocumented, and in fact not as simple as you would at first think.
The input port itself is not actually what is in question here. Instead every IO pin on the Arduino, be it set to INPUT or OUTPUT, has a set of ESD protection diodes on them. These look like this:

simulate this circuit – Schematic created using CircuitLab
The "IO MODULE" when in INPUT mode can pretty much be ignored, since it is a very high impedance. Just like a (roughly) 10MΩ resistor to ground. Very very little current will flow that way.
D2 is also reverse biased so that direction can be ignored.
So the current will want to flow through D1 to the VCC rail (+5V).  The diodes have approximately a 600mV forward voltage (which is where the VCC + 0.5 comes from).
So we can recalculate, given those parameters, what the current flowing through the diode will be to the 5V rail:

Voltage difference = 12V - 5V - 0.5V = 6.5V
Current = V/R = 6.5/330 = 19.7mA

The recommended maximum (from what I can gather) is only 1mA.  You have 20x that.
So you will need at least 20x higher resistances. 10kΩ in the upper half and 6.8kΩ in the bottom half.  That will give you 4.85V on the output at 12V and limit you to 0.65mA in a failure situation.
It also gives you an output impedance of a little over 4kΩ which is below the recommended maximum of 10kΩ for the ADC input.
You can further protect your input by adding a 5V zener diode and small series resistor on the ADC pin so if the voltage goes above 5V it clamps it and protects the pin.

simulate this circuit


About being sure about returning to position 0 this is not a problem. You are not actually controlling anything with your PWM. You are only sending a signal to the IC inside the servo to tell it where to move the actuator. That IC knows in what position the actuator is located in any moment, usually using some kind of encoder (it's called a closed loop system) and it will make sure that it will move back exactly to 0 whenever you tell it to move to 0.

If you want to make things clearer you can use write method to send value to the servo.

void Servo::write(int value)
{
  if(value < MIN_PULSE_WIDTH)
  {  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
    if(value < 0) value = 0;
    if(value > 180) value = 180;
    value = map(value, 0, 180, SERVO_MIN(),  SERVO_MAX());
  }
  this->writeMicroseconds(value);
}

Any value from 0 to 180 will set a position to which servo will move from MIN to MAX possible position. No need for manual calculation of microseconds.

You have to remember that PWM works constantly. If you write for example LINEAR_1_100.writeMicroseconds(1051) this code will set some timers, counters and prescalers inside the ATmega chip on the Arduino board and the value of PWM will be sent constantly until you change it.

So the delay(2000) doesn't stop the PWM signal, and servo remains in constant position.

The issue is here:

LINEAR_1_100.writeMicroseconds(1800);
LINEAR_1_100.writeMicroseconds(1051);

You set the value of 1800 and then immediatelly set value of 1051, but the ATmega didn't even have the time to send the first value to the servo.
Add a delay(1000) after every call of write or writeMicroseconds to allow the PWM to actually be sent to the servo.


digitalRead() is a function. It takes one parameter (the pin number) and returns the state of that pin.  It's that return value that you want to OR with another. Which means you have to read the state of both pins, separately, and OR the results together:
while (digitalRead(home_limit1) || digitalRead(home_limit2)) {
    ....
}


Short battery life concern with Arduino Pro Mini

A standard alkaline 9V battery has a capacity rating of around 500mAh (milliAmp-hours). That rating is probably based on a current consumption of around 10mA. However, if the current consumption is higher, the apparent capacity drops. At 100mA, most 9V batteries have a capacity rating of about 300mAh, and at 500mA current draw, the apparent capacity drops down to 170mAh.

This means, if you are drawing 100mA of current constantly, a 9V battery will last (0.3Ah / 0.1A) = 3h.

A typical Arduino pro mini will draw current at around 20mA.

500mAh / 20mA = 20h

This is not even counting the motor and driver.

A standard alkaline AA battery has a nominal voltage of 1.5V and a capacity of about 2000mAh, and 3 of them will provide a voltage between 4.5V (fully charged 1.5V x 3) and 2.7V (fully discharged 0.9V x 3)

With that voltage range, you could operate the Arduino pro mini in 3.3V mode, with no linear regulator, at a reduced clock frequency, such as 8Mhz, which will reduce power consumption even more.

Being able to put the chip in power-saving mode, and periodically check for necessary activity will help even more.

See http://www.gammon.com.au/power for a description of many practical methods.

That said, the Arduino is going to be a pretty small contributor to power draw compared to a DC motor, so your overall run time will heavily depend on how often the motor is turned on.


Where can I find the Arduino Mega core code?

Arduino Mega is part of the Arduino AVR Boards core. The location of that core depends on whether you are using the core version included with the Arduino IDE or have updated the core version using Boards Manager(in which case there will be multiple copies of the core installed on your computer but only the updated version will be used). The easiest way to find it is:

Tools > Board > Arduino/Genuino Mega or Mega 2560
File > Examples > EEPROM > eeprom_clear
Sketch > Show Sketch Folder
Move up folder levels until you reach the avr folder.
If there is a version number folder in the avr folder then open that folder.
HardwareSerial.h and the rest of the core files are located in cores/arduino.

Remember that you will need to redo any changes to the core after any Arduino IDE and/or Arduino AVR Boards updates.


Lithium Polymer/LiPo set to power Arduinos

If you can get away with it, I recommend not using a boost converter and instead connecting the battery directly to the supply voltage input (the "5V" pin).

The AVR chips used in most Arduinos (but not the Due or Zero [and the Yún and Tre are a totally different kettle of fish entirely]) can operate with anywhere between 2.7 and 5.5 volts, with the ATmega328P found in the Uno able to run with as little as 1.8V. This is a much larger range than the 3.0-4.2V available from rechargeable Li-ion/Li-poly/LiFePO4 cells.

Naturally you will need to make sure that any external components can run with the reduced voltage as well, but quite a few are able to work with anything from 2.0 to 5.5 volts.


As Ignacio mentions, you should not be stopping and starting the serial ports. Instead just switch between them with .listen():

  Enables the selected software serial port to listen. Only one software serial port can listen at a time; data that arrives for other ports will be discarded. Any data already received is discarded during the call to listen() (unless the given instance is already listening).

  SoftwareSerial::listen() Manual Page

So your code would be written as:

#include <SoftwareSerial.h>

SoftwareSerial Ser1(10, 8);
SoftwareSerial Ser2(16, 7);
SoftwareSerial Ser3(14, 4);
SoftwareSerial Ser4(15, 2);
//Set up (RX, TX) pins^

void setup() {
  Serial.begin(9600);
  Ser1.begin(9600); // open Ser1
  Ser2.begin(9600); // open Ser2
}

void loop()
{

  delay(1000);

  Ser1.listen(); // Select Ser1 for receiving
  Ser1.print(F("AT\r\n"));

  delay(1000); // Give it time to send a response or you'll get nothing!

  while ((Ser1.available() > 0)) { //Read entire string
    Serial.write(Ser1.read()); //Dump it to serial monitor
  }

  //Should Respond with "OK"

  Serial.println(); // Extra line in Serial Monitor for neatness

  Ser2.listen(); // Select Ser2 for receiving
  Ser2.print(F("AT\r\n"));

  delay(1000); // Give it time to send a response or you'll get nothing!

  while ((Ser2.available() > 0)) {
    Serial.write(Ser2.read());
  }
}


ESP8266 Webserver ESP8266WebServer move Handler-Function in separate .h .c file

Move the webserver to index.c and include the webserver type:

ESP8266WebServer server(80);

Add an external reference in index.h and include it:

#include "ESP8266WebServer.h"

extern ESP8266WebServer server;

Index.h is included by both main.c and index.c so it will know about server being an ESP8266WebServer type, but does not allocate memory for it; that is done in index.c

This is called a forward reference.


As a quick update for anyone who runs into a similar issue (granted, a week later)...

I upgraded to 1.6.5 of the Arduino IDE, making sure to set my Arduino application folder appropriately, and the compilation issue has disappeared. I am able to compile and upload projects successfully.


creating HTTP persistent connection, to create 'smooth' data over GSM sending

The ArduinoHttpCliemt library's HttpClient.stop() method does two things. It resets the state of the HttpClient object and stops the underlying Client connection (TCP connection). If HttpClient.stop() is not called, the internal state is not good to call get() or post() again.

The method resetState() is called in HttpClient.stop() to reset the internal state of the HttpClient object. But resetState() is protected. To call it we must modify the library header file.

In HttpClient.h make resetState() public (by moving 'protected:') and then in sketch call resetState() before post(). It will put the HttpClient object into initial state without disconnecting the underlying TCP connection.


Yes, you can. Just be sure, that you connect both Arduinos in parallel to the power source (both power inputs together to the power output of the source and both grounds together to the ground of the source), so that the current for the second Arduino won't flow through the first Arduino. Also use a power source, that is capable oft providing enough current for your needs.


In your diagram, the fixed 1KΩ resistors both tie to +5V at one set of ends, and their other ends tie to A+ and A-.  The strain gauges are from A+ to ground and A- to ground.

In a typical scale, where several strain gauges are similarly loaded, that topology will produce about zero volts between A+ and A-.  By contrast, the following  topology (from: blog.l3l4.com) produces higher voltages for higher loading.  (Diagram uses S+, S- rather than A+, A-)

(I realize your question shows some voltage changes when sensors are separately loaded, so this answer might not be relevant to your current problem.)


Just a word of advice about AGC in general.  There is almost always an issue of attack (how fast the AGC reacts to a sudden increase in signal) and release (how fast it reacts to a decrease).  In most AGC cases you will need to make compromises on these two settings to avoid poor behavior from the AGC... it's not a drop-in solution with pre-determined optimum settings for every purpose.  Depending on the program material, you can get obnoxious artifacts like breathing and pumping for speech and music.  ACG is much better at slow drifting things like signal fade.  I just want you know what you might be getting into...


Having trouble with motor shield running off external power source

Try a decoupling capacitor acorss your TEG : 100µF/35v (+ at the +).
This will avoid micro power drops...
Verify that y hardware driving motor works below 9V.


No sketches will upload to Arduino Uno board; says "access denied"

It sounds like Windows thinks that port is in use and isn't letting the ArduinoIDE access it. If it's the same port your dongle had been using, try plugging the dongle back in, then dismounting it before you remove it. Hopefully that will clear the port for other uses.


PWM Input Pins Never Receive a Value from Working Receiver?

What misled me is the pin numbers. I was referencing this diagram:

I thought that all the pins were numbered sequentially, so that pinMode(9, ...) would set D6 (09 in the diagram). However, this sets D9. Connecting to the correct pin works fine.


With SoftwareI2CLibrary you can specify other pins, I haven't tested it with RX and TX.

I would recommend the USB serial interface is fast (2M baud) in perspective to that we are discussing a Arduino with a speed of 16MHz.


Can Arduino Mega ADK charge connected smartphone?

If you read the documentation, you will see this paragraph:

  NB: Because the MEGA ADK is a USB Host, the phone will attempt to draw power from it when it needs to charge. When the ADK is powered over USB, 500mA total is available for the phone and board.The external power regulator can supply up to 1500mA. 750mA is available for the phone and MEGA ADK board. An additional 750mA is allocated for any actuators and sensors attached to the board. A power supply must be capable of providing 1.5A to use this much current.

So yes (though slowly), if you connect it to a suitable power supply.


Arduino board is turning off when I connect to +5V

Try out this connection. It will helpful.


Clock drift - is the precision of the crystal the only culprit?

The problem is the interaction between the interrupt handler that updates the value for the millis() function and the neopixels show() function.

To maintain the counter for the millis() function a interrupt is triggered approximately every 1.024 ms.

When the show() function is called all interrupts are disabled to get the precise timing needed to send the data to the neopixels.  For a 60 led strip this takes about 1800 microseconds (60 leds * 24 bits * 1.25 us per bit) so at least one interrupt is skipped each time you update the display.

This page has details about how the millis() function works.


Serial.readString() not working becaue of outdated IDE?

Stream::readString() is available since version 1.0.1. See:

the changelog, and
the corresponding commit.


Check if a set of events occur in a limited time period

Here's some pseudocode that might help:

   if millis() - start time >= 2000
         time is up, do what you want with the sequence so far
         maybe a boolean flag here so you only do it once
   if any button is pressed
      if counter == 0
          set start time = millis() // start the timer
          set first in sequence
      else
          add the button to the sequence


It is likely that placing the GSM shield between the Arduino Mega and the NFC shield is interfering with the GSM antenna.  Antennas react in strange and usually less useful ways when large conductors are placed nearby.

You could try reversing the order of attaching the shields, or you could try spacing the shields further apart using "stackable Arduino headers" (you can do a web search for suppliers).  If there is an option for an external antenna, that would be even better.

If you get GSM working, you might still have some trouble with the NFC shield, as it's possible that the GSM transmitter being so close could interfere with the NFD's circuitry - not because they use the same frequences, but just because any conductor so close might pick up electrical noise, and there will be various sensitive circuitry in the NFC electronics.


Signal sampling: losing data every 103 points when it is recorded in SD

It's all to do with writing to the SD card.

You have a buffer of 512 bytes which is one "block" of the SD card.  When you have written to the card enough to fill that buffer up it has to write that buffer to the SD card and empty the buffer so you can start filling it again.

That writing to the SD card takes time - lots and lots of time (relatively), and it can't be doing anything else at the same time as writing to the SD card.

The only way you can get around that is to have your sampling performed within an interrupt - maybe a timer interrupt - so that it can interrupt the writing to the SD card.  However, that's not a simple task.

You would need to implement a system known as ping-pong buffers.  You have a pair of buffers for storing incoming samples within your interrupt routine.  When one buffer is filled up you switch to the other buffer and signal to your main loop() routine that you have filled the buffer.  It's then the job of loop() to save that buffer to the SD card and empty it ready for when the second buffer has been filled up.  The name ping-pong comes from the game of table tennis (also known as ping-pong) as you are switching from one buffer to the other and back again in a constant backwards-and-forwards motion like the ball in a game of table tennis.

Getting the right size of buffers is also critical.  You have to ensure that the time taken to fill one buffer is always going to be longer than the longest amount of time it takes to write a buffer to the SD card, including any flushing of the internal SD card buffer.  The best size is probably going to be to match that internal SD card buffer so every ping or pong you will be doing an entire SD card block's worth of data - so 512 bytes.

That means you have 3 buffers of 512 bytes - your two ping-pong buffers and the SD card's buffer, which is 1536 bytes - not far off the limit of an Uno, so you may struggle with that.  For this kind of thing it is better to use one of the boards with a more meaty chip, like the Mega2560.

Also the line:

delay(0.5);

is meaningless.  delay() takes an integer value, so 0.anything is actually truncated to 0.  To delay for less than a millisecond you should use delayMicroseconds().


If you can transmit raw 802.11, take a look at the code for aircrack-ng, specifically aireplay-ng.c - this software is known to work on arm boards.


I have managed to set MOSI to low by setting bit 26 in PIOA->PIO_PER, PIOA->PIO_OER and  PIOA->PIO_CODR registers. To use SPI again, bit 26 in PIOA->PIO_PDR has to be set (this cancels the effect of PIOA->PIO_PER).


Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega to control speed of a 4-wire cpu fan

I've just tested your setting with older "Alpine 64 GT" CPU Fan and it works as expected. I've just added parsing integers sent from serial monitor, so I don't have to change code anymore.

void analogWrite25k(int value)
{
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;

    // Mode 10: phase correct PWM with ICR4 as Top (= F_CPU/2/25000)
    // OC4C as Non-Inverted PWM output
    ICR4   = (F_CPU/25000)/2;
    OCR4C  = ICR4/2;                    // default: about 50:50
    TCCR4A = _BV(COM4C1) | _BV(WGM41);
    TCCR4B = _BV(WGM43) | _BV(CS40);

    Serial.begin(115200);

    // Set the PWM pin as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    int w = Serial.parseInt();
    if (w>0) {
      analogWrite25k(w);
      Serial.println(w);
    }
}


The GSM takes time to start up.  Your program needs to be far more complex than the simple "Throw commands at it and hope" method you are using.

First you need to query the modem repeatedly until it responds.  This is usually done with the AT command.  A sequence would look like:

Send: AT
(Wait for OK response or timeout)
Send: AT
(Wait for OK response or timeout)
Send: AT
(Wait for OK response or timeout)
Send: AT
(Wait for OK response or timeout)
Recv: OK

Once the modem has booted and is ready to receive commands you can start sending commands.  You shouldn't just "print and delay" though like you are at the moment. Instead you should send the command and then examine the response to see if the command worked ("OK") or failed ("ERR").


Coding force sensitive resistor to give output based on time used?

You'll need to declare a variable to hold the start time (millis()) of when the force has exceeded the threshold.

You'll need to declare a constant to hold the threshold value (with analog data, you likely don't want to have your pressure threshold be "anything greater than 0", because noise and other things like small vibrations will trigger.

Also declare a constant to hold your "hold-off time" in milliseconds.

In your loop(), when you have an analog value that exceeds the pressure threshold, store the value of millis(). Also in your loop(), when the current millis() minus the start value  is greater than the "hold-off time", activate your LED.

For RGB, same setup, but you can set your color based on how much greater the time difference is than the hold-off time.


Arduino Nano /Uno USB is not getting recognized

Assuming that the atmega328p still works fine, you can still use the Nano. I have solved this a few times by just using a FTDI breakout board (remember to set it to 5V, though 3V3 upload works on a Nano), and connecting RX to TX, TX to RX. Press reset before each upload.


What does it mean when there are two addresses listed in the data sheet for a particular register?

One (the lower number) is the IO port address which is used when using the IN or OUT op-code. The other (higher number) is the memory mapped address.

Different methods of access are more programatically efficient depending on how you are manipulating the values. For instance IN and OUT are more efficient at setting or reading the entire register value, but SBI and CBI on the memory mapped address are more efficient when manipulating individual bits.


how to move my robot to the assigned coordinates

Due to my robot I have been thinking about this problem quite a few times but I never got to coding.  So this is a purely my thinking no experience.

The problem is not only calculating where you are and where to go. The robot needs to move so it needs to know whether it needs to turn (left or right; slow or fast) to drive into the correct direction.
So basically you want a method that takes the compass direction the 2 gps locations and returns a speed and turn value.
The speed and turn value will be different for a waypoint and the final destination. I thought to do so by switching to the next waypoint before coming in the "slow down area". This should make that only one algorithm can handle both situations.
I think the algorithm is likely to look like this.
Given the 2 gps locations calculate the expected compass reading.
Given the 2 gps locations calculate the distance
Based on the distance and the difference between the expected and actual compass reading decide on the speed and turn.

As to the last step there is no "one size fits all" for instance a skid driven robot may opt to turn on the spot until it hits the expected compass reading.
If you have a slow turning robot and you are close to the waypoint you may opt to drive backwards first (like parking a car)

I hope this helps


I still suggest using the eeprom.
It is the firmware's job to handle whether or not data in eeprom can be written.
You could implement wrapper functions for the arduino which can only read/write after a defined offset. You can set this read-only data with the .eep-file when you upload your sketch. The eeprom file then may be generated programmatically.

Once you have to flash several individual devices with a final firmware version, there are no benefits in using the arduino ide. You can upload the firmware and the eeprom file using avrdude:

avrdude -P YOUR_PORT -b 115200 -p ATmega328P -e -U flash:w:YOUR_FIRMWARE.hex -U eeprom:w:YOUR_EEPROM.eep

It's up to you how to generate the eeprom file (bash/batch, make, pyhton,...).


Generate a true analog signal using Arduino

I see that MCP4725 uses Wire library with the default clock of 100,000 kb/sec.
At a rough estimation each call to MCP.writeDAC or MCP.getValue will be at least 32 bits long and you use three of them in each loop.
This one:
   Serial.println(MCP.getValue());
   if (MCP.getValue()>threshold)

is redundant, you should store the value in a temporary variable and use-it in both "print" and "if".
With 10us for each bit that means 1060 us for each loop. The analog read also takes 100us to complete. Over all 1160us minimum.  Is the MCP.getValue() really needed?
That means that your maximum sample frequency is 860hz and the maximum bandwidth of 430hz. I doubt that this is an acceptable bandwidth for a microphone.
Even so, the output signal will not look similar at all, you need a higher bandwidth or to limit,  if possible, the bandwidth of the input signal.
In some limits you can modify the MCP4725 library to use fast wire clock four times faster if it suits your requirements. If you also drop the two MCP.getValue() calls that will be again almost three times faster, up to 5khz.
Also you might search for faster ADC on Arduino.
Update after OP microphone amplifier schematic.
The ADC works only with positive voltages. Short the output capacitor of the amplifier!


No. Interrupts are hardware. You cannot "create" interrupts in software.

The closes there is to what you are after is the Analog Comparator (see section 27 of the datasheet).

The analog comparator allows you to trigger an interrupt if a voltage is above (or below) a reference voltage which is up to you to provide.

For anything more complex you would need to use external comparators to trigger on different voltage levels which then trigger external INT pins on the ATMega.


It sounds like you are trying to put a PHP file on an SD card that the ESP8266 will serve itself.

This is not possible, as no one has, and probably never will, port PHP to the Espressif 8266 platform.

Your device can serve .htm .css and .js files because it's just a matter of streaming the file content to the client. But PHP requires that an application on the server run the PHP code, and then send the resulting output to the client.


Arduino Stepper Motor Standing Desk help!

I think this might end up being more of a fun way to electrocute yourself, but let's find out...

Energy required to lift an object with mass "m" an upward distance of "h" in the Earth's gravitational field, on the surface...  E = mgh = m(9.8)h

So, to lift a 50kg desk one meter, we will need 50 x 9.8 x 1 = 490 Joules

How fast do you want to lift it? Let's say we want it to take 10 seconds - that will give us the power level we need. Power is in watts (Joules per second) - so if we want to lift the desk in 10 seconds we need 49 watts - let's call it 50.

Now, to produce 50 watts with a 12-volt battery, that would be 4.2 Amps. This is do-able, and it's not the high power level I expected for lifting a desk. Even if we throw in some efficiency losses, we're well within the safety zone and won't have to get out the high voltage equipment. So, I'm glad I did the math - my initial impression of this task was the joke at the beginning of the post.

So, you need a 50 watt motor... that's easy to find. Hell, why not go way over that and get a 100-watt motor... google that...

http://www.electricscooterparts.com/motors24volt.html - bang! Scooter motors! Nice!

So, that's an example of how you might figure out what parts to get - it all starts with basic physics and ends with Google (or Bing if you're one of those people). I simplified a lot, but you get the idea.

The other part of this task is to figure out the control system. I would probably not use Arduino to do this. I would have three switches - one "directional" switch to run the motor, and two sensor switches to disconnect the directions of the motor at each end of the track. I think that's how automatic power windows in cars used to work, which explains why if you didn't hold the button down long enough, it would immediately instead of continuing to the other end - it was still sitting on the sensor.

Sticking an Arduino in the mix and having it read the sensors would just waste power all day long, but you could do it that way. It's the same idea - just mount sensors on the track, which get tripped when the desk rolls up to that spot. Coding wouldn't be that tricky - when the user activates the "change button" or whatever, check which sensor is currently active, and move the desk the other way until the other sensor activates.

You're going to need a good power supply for that motor - a 24-volt 200-watt power supply if you like to over-engineer like I do. You'll need a relay to control the motor - it needs to handle 24 volts/200 watts. Then you'll need some kind of activation button, and two sensors. You want some kind of sensor that is definitely going to be activated when the desk is in position, or you risk over-running your target, binding the mechanics, and burning the motor, and possibly the office as well. So, I would choose some kind of mechanical sensor, not a light sensor or something like that.

This should get you started on finding those parts...
https://www.sparkfun.com/categories/145 - these are all kinds of buttons and switches - you should be able to find something that you can mount to the track which will activate when the desk runs into it. Search on this site for the other parts - they have the relays and stuff too.

Final warning though - this may be too complicated and dangerous for a first project. At 24 volts and 100 watts, we are getting into dangerous power levels. But, these are common power levels in consumer equipment. So, if you know what you're doing you should be safe. If you don't, I strongly suggest getting an experienced electrical engineer to look at your designs. Also, you probably can't install this device in an office - there is an insurance reason that it hand-cranks, your company isn't just being cheap.

What happens if someone bumps the desk and it becomes active when you're not around? What happens when the power goes out? What happens when the power comes back on? Do we have enough fuses in the right places to shut this system down before it catches fire? You need to consider all that.


NodeMCU not responding AT after blink app

If you replaced AT firmware in esp8266 with Blink and you want it back, download the AT firmware from Espressif download page and flash it with the Espressif Flash Download Tool (Windows) or with esptool.py.


Trouble using proximity sensor as input and LED output

You want 2 independant loops, one for the measurement and one for the dimming effect. The latter one must also be able to run when not measuring.

if(millis()-lastReading>=sampleRate) //this very simple statement is the timer,
{
  distanceVal = proximity1.ping_cm();  //get the distance value in centimeters

  lastReading = millis();

  Serial.print("Distance Reading CM : ");  //print the value to the Serial monitor
  Serial.println(distanceVal);
}

if(millis() - lastFade >= fadeRate) //other timer
{
  lastFade = millis();
  if(distanceVal<20){
    fadeAmount = 5;
  }else{
    fadeAmount = 2;
  }

  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
}


You have asked the compiler to allocate 3 char of memory, and then you ask it to fill that memory with 6 bytes of data (5 characters, plus null-char for termination.)


Using softwareserial with a TFT, how can I use a variable to position cursor?

Just split the print into three parts:

myTFT.print("DS32(32,");
myTFT.print(g);
myTFT.println(",'Hello!',4);");


Arduino Mega 2560 with SIM808 module - Incomplete SMS response

Don't delay.

In the three seconds that you wait between sending the AT command and reading the response the entire response has arrived and been placed in the serial RX buffer - which has overflowed because there's more than 64 bytes in the response. So you lose data.

You should never use delay() when reading from serial, it's dangerous (as you see).

Instead you should be just immediately reading until you see the correct response from the command you sent - which will either be "OK" or "ERROR". Everything before that is the content of the response to your command.


Can I charge a 4.2 V battery with a 5 V adapter?

This question would be a better match to the Stack Exchange Electrical Engineering group.

A 4.2V battery is very likely a LiIon or LiPo battery. I'll call it LiPO below as it's easier to type.

Most cellphones and many small electronic device use a single LiPo battery and use a 5V input to charge them. To do this they have internal control circuitry that ensures the battery's specifications are met. You can obtain suitable control electronics (in many cases as a single IC requiring maybe a few external resistors to configure it) and it makes great sense to use such a control circuit.

In an emergency you can use a 5V source to charge a 4.2V battery IF you know what you are doing and are able to ensure the battery specifications are adhered to. Failing to stay "in spec" may lead to the traditional LiPo "vent with flame" response, and even if there is no apparent damage the battery life can be greatly or very greatly reduced by out of spec treatment.

Key requirements are:

NEVER exceed 4.2V at battery terminals.
NEVER exceed Ichg_max = manufacturers max charging current.
This is usually the same value in mA as the battery capacity in mAh.
ie 1000 mA for a 1000 mAh battery
3300 mA for a 3300 mAh battery etc
When charging, EITHER stop charging when battery potential reaches 4.2V OR if you are able to hold the battery AT 4.2V, then stop charging when Ichg falls (under battery control) to say Ichgmax/4.
If Vbattery is under 3.0 V (which it NEVER should be) charge at no more than C/10 (eg  for a 1000 mAh cell) until Vbattery rises to >= 3.0V. If the battery will not rise to 3.0V under C/10 charge it is dead.

IF you can satisfy ALL these requirements at all times you can charge a LiPo or LiIon battery from 5V without a special charger.


Software serial doesn't work reliably at 115200. You need to use a lower baud rate:

Connect the ESP8266 back to your serial USB to TTL setup.
Send the following command to reconfigure the ESP8266 to do AT communication at 9600 baud: AT+UART_DEF=9600,8,1,0,3
Change line 9 of your sketch to esp8266.begin(9600);. This will cause the Uno to communicate with the ESP8266 at 9600 baud.
Upload the revised sketch to your Uno and connect it back up to the ESP8266.


What are ideal delay times between commands for RF24 lib

Remove all delays except the one after startListening.

You could replace it with a "wait for radio.available to be true OR 50ms to have passed" piece of code. There is no need to wait for 50ms if the message was already received after e.g. 10ms.

Even better would be to use the ACK-package feature of the NRF. With this feature the master already prepares a package for the slave. Then when the slave sends it's message (every hour), the prepared package is included in the ACK (acknowledgement) packet.

As to optimizing it even further. It would be better to optimize the sleep code, then the send code. The sleep part will still use more power in an hour than the sending code, even if it takes 10 second to do so.

As to the lost packages. Try using a different channel. You also might want to get an NRF module with an real antenna, and maybe even an amplifier, for the master.

PS You can remove the serial.print in the deployed version.


When you write String str[i]=in_str; that is wrong. You only write the type when you are declaring the variable, once.

When assigning, you need only write the variable name, not the type: str[i]=in_str;


Taking String Input from NodeMCU Webpage and Printing it on Serial Monitor

Try this. It uses the webserver library. I thought it was cleaner code. I also have a nicer way to include the pure html code.

For your original form go to yourIPaddress/single

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

const char* ssid = "MTS61752";
const char* password = "6900979039";

ESP8266WebServer webserver(80);

//------------------------------------------------
static const char PROGMEM singleLine[] = R"rawliteral(
<!DOCTYPE html>

<title>Single Line Input</title>

<form method="post" action="/save" >
Serial Printer (Put Text here: ):

<input type='text' id='name' name='name' required minlength='0' maxlength='800' size='100'>
<input type="submit" name="clk_action" value="accept">
</form>

)rawliteral";

//------------------------------------------------
static const char PROGMEM INDEX_HTML[] = R"rawliteral(
<!DOCTYPE html>

<title>Clock Settings</title>

<form method="post" action="/save" >
Turn on time:
<input name="onTime" type="text" size="16" value="" >

Turn off time:
<input name="offTime" type="text" size="16" value="" >

<input type="submit" name="clk_action" value="accept">
</form>

)rawliteral";

//------------------------------------------------
void handleRoot() {
  webserver.send(200, "text/html", INDEX_HTML);
}

//------------------------------------------------
void handleNotFound() {
  webserver.send(404, "text/plain", "Page not found ...");
}

//------------------------------------------------
void handleSave() {
  String str = "Settings Saved ...\r\n";

  Serial.print("number of arguments ");
  Serial.println(webserver.args());                    // number of arguments

  if (webserver.args() > 0 ) {
    for ( uint8_t i = 0; i < webserver.args(); i++ ) {
      str += webserver.argName(i) + " = " + webserver.arg(i) + "\r\n";

      Serial.println("Arg "+ String(i)+"="+ webserver.argName(i));
      Serial.println("Arg "+ String(i)+"="+ webserver.arg(i));
    }
  }
  webserver.send(200, "text/plain", str.c_str());
}

//------------------------------------------------
void handleSingleLine() {
  webserver.send(200, "text/html", singleLine);
}

//------------------------------------------------
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  webserver.on("/", handleRoot);
  webserver.on("/save", handleSave);
  webserver.onNotFound(handleNotFound);
  webserver.on("/single", handleSingleLine);

  webserver.begin();
  Serial.println("Web server has started");
}

//------------------------------------------------
void loop() {
  webserver.handleClient();

}


Assuming the 0-5 Volts is supposed to switch the output, in which case you want a program to control your output, then you will want to use a digital output pin to either switch a relay or a transistor that controls the 10 Volts put out to whatever it is that you are controlling.

Perhaps you want PWM which indicates a transistor circuit.  Hard to tell what you want from the way this is worded.

Taking your words literaly, "I need the output to be 10V always" then that simply means hard-wiring to a 10V power supply.   ;-)


First: Your code as 2 problems:

As stated in the comments by PeterPaulKiefer, when you use
  pinMode(LT_R,INPUT);

That is not working as intended by you. LT_R is defined at the top as
  #define LT_R !digitalRead(10)

Thus the compiler will see
  pinMode(!digitalRead(10), INPUT);

digitalRead() will return zero or one, thus you are configuring pin 0 or pin 1 here (depending on the state of the sensor at startup). Instead you need to directly use the pin number (10) or use another define for the pin number itself. Your code only works, because all the pins are configured as INPUT (tristate) at startup of the microcontroller, so that they don't break something with a wrong signal. You got lucky there.

The last two else if statements are never executed:
  else if (LT_M && LT_R && !LT_L) {
      delay(500);
      right();
  }
  else if (LT_L && LT_R && !LT_R) {
      delay(500);
      left();
  }

The conditions here will first evaluate LT_M (in the first statement) and LT_L (in the second statement) respectively. Only if these are true, the rest of the expression will be evaluated. But you already checked for both of them being true above. When they are, the following else if statements don't get executed (thats the logic of if else statements). And if they are false, the code will also not be executed.
When you get to a 90° right corner, the middle and right sensor will trigger. Currently this will lead to the robot just keeping going forward.

So you need to change your code to actually check every every possible combination of the sensor states.
Also keep in mind, that a sharp corner needs way more turning, than a curve. Depending on the width of the line are the distance between your sensors, you might or might not be able to distinguish between those two cases. You should analyze, which sensor states you would have in which situations, write that down and then write code for every state. You could also put all sensor states into one single number, so that it is easier to check for it in the code. Something like this:
byte all_states = digitalRead(2) + 2*digitalRead(4) + 4*digitalRead(10);

Each combination will give you a unique number to work with. Effectively this stores the states of the sensors in one bit of the number each. Bit 0 is for pin 2, bit 1 is for pin 4 and bit 2 is for pin 10. You can also write this with bitwise operators:
byte all_states = digitalRead(2) | (digitalRead(4)<<1) | (digitalRead(10)<<2);

For example: If the right sensor is triggered, but not the others, you would get a binary number 0b00000100, which is decimal 4. If the left and the middle sensor are triggered, but not the right one, this results in 0b00000011, which is decimal 3. Then you could check with a switch statement:
switch(all_states){
    case 0: //No sensors triggered
        break;
    case 1: // Left sensor triggered
        break;
    case 2: // middle sensor triggerd
        break;
    case 3: // middle and left sensor triggered
        break;
    ...
}

You see how it works. The code for each case then goes inbetween of each case and break line.


Analog angle conversion from +70° to -70°

So atan2(y,x) gives the angle CCW from the x axis in radians, limited to [-pi,pi].

If you want it converted to degrees CW from the Y axis, you would do

azimuth=90.0-atan2(y,x)*57.295779;

If you need to constrain it to -70,70 then:

azimuth_constrained=constrain(azimuth,-70,70);


Is there a way to replace an Arduino core function without modifying the Arduino code?

Not sure about the Arduino IDE (I don't have it installed right now) but using UECIDE it's as simple as defining a new digitalWrite function in your code.  When the whole shebang gets linked together the function in your code overrides the function in the libraries.

void setup() {
    pinMode(13, OUTPUT);
}

void loop() {
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(800);
}

void digitalWrite(int pin, int level) {
    // Not gonna do anything!
}

Comment out the digitalWrite function and the LED blinks.  Uncomment it and it doesn't blink any more.


servo.read() starts at negative value, no matter where servo actually is

You seem to be starting from a fundamental misunderstanding of RC hobby type PWM servos.  To put it simply, they do not electronically output any position information.

Until you have commanded a position and the servo loop has had a fair chance to seek to that, the position of the servo is utterly and entirely unknowable.

This is stated in the documentation of the Arduino servo system:

read()

Description

Read the current angle of the servo (the value passed to the last call to write()).

As this explains, the returned value is not the physical position, but rather the last commanded position.

Until you have commanded a position (something your code does not do) the return value of this call is physically meaningless.


The current limit you quote is the maximum current that the main chip on the Arduino can tolerate through its 5V or GND pins.

As the chip itself consumes (round numbers demonstrate the theory) say 50mA that leaves 150mA in total that can be sourced or sunk through IO pins.

If you want to supply 20mA per LED (that is actually overkill - you can use considerably less and have very little difference in brightness) that means you can have, illuminated at any one time, (150 / 20 = ) 7.5 LEDs.

To increase the number of LEDs you can drive at once you can:

Reduce the current by increasing the resistor values.
Use multiplexing so that, although it looks like all LEDs are on at once, only a few are actually on at once.
Use external LED driving circuitry (transistors, LED driver shift registers, etc).

All this pertains purely to the current that passes through the main chip itself.  It does not pertain to any current you draw from the 5V or 3.3V pins.  The maximum current through those pins is limited by the voltage regulator they are attached to, and also by the voltage that you are supplying the board with (the higher the voltage, the more voltage has to be dropped, and so the more heat is generated per mA drawn).

The 5V regulator has around 800mA limit when supplied with 6.5V.  If supplied with 12V the limit is considerably less (since it will get too hot and go into thermal shutdown).  You subtract what you are drawing through the chip (maximum 200mA) and that is how much current you have available.

The 3.3V regulator is driven from the 5V regulator, so any current drawn from the 3.3V pin must also be subtracted from what is available on the 5V pin.


How do I go about building a backend for my Arduino device?

I use emoncms for much of my data processing along with node-red and MQTT all running on a RaspberryPi see Emoncms to get started


Sparkfun Can-Bus Shield example not working

SPI pins are located on different pins in Arduino Mega. You have to wire it correctly with your shield. Some shields uses ICSP (6-pin header) for better compatibility but this one doesn't.

See Arduino SPI Reference for more details (section: Connections)


Execute Code While Refreshing a 7 Segment LED Display

The problem here is that the display is driven using a timer interrupt.  The temperature sensor, being a one-wire device, has to have very careful timing to communicate with it.  As a result it disables interrupt so it has exclusive use of the CPU and can properly predict its timing while it's communicating.  And so the display can't refresh at the same time.

So what can you do?  Well, nothing really.  You can't have perfect timing for the temperature sensor while at the same time interrupting it for displaying the value.

So there's really two main options:

Change the temperature sensor.  Use an SPI or I2C temperature sensor that has a real hardware interface to communicate with it so you don't have to use big-banging.
Change the display.  A non-multiplexed display or a display with its own built in driver (most often with some serial protocol like I2C or UART) would mean you don't have to use interrupts to update the display.

Basically you have two technologies that won't sit together well on the same chip.

Update:

I missed the sevseg.refreshDisplay() function call since the website had scrolled it off the bottom of the code block.  Bah!

Ok, so it's not using an interrupt.  That could be a good thing, or it may be meaningless.  It takes time to do the temperature reading, and it's that getting in the way of the refreshing.

There's a chance you may be able to push the update "into the background" by attaching it to a timer interrupt, but if the OneWire communication does disable interrupts then the problem will still persist (I don't have OneWire to hand to look at the code right now).


I agree with TisteAndii's comment. Your voltage divider is in the wrong place. You are dividing down the 3.3V signal from the HC-06 to be a maximum of 2.269 volts. However the Nano requires at least 3.5V to be considered HIGH.

Plus, you are putting 5V from the Nano into the HC-06 which may damage it.


You can chain as many shift registers as you want.

Most commonly, these displays are multiplexed. Only one digit is lit at a time, cycling though all the digits fast enough, so the eye can't tell. This is however not very good practice for 28 digits, as the brightness will become 1/28th (though you could create groups of digits, and multiplex those groups separately).

There are specialized chips that do this multiplexing for you. E.g. the Max7219. This chip can multiplex 8 digits, with 8 segments. So you'd need 4 of these to light up 28 digits.


How do i wire a switch to control Leds on a arduino nano

The wiring is correct, but inPin in your code is set to 2, which is D4 on the Nano, while you have your signal wires going to D7 and D6 in your schematic.

Similarly, outPin is set to 13 in your code, which is D9 on the Nano, but your schematic shows the LEDs connected to D5 and D4.

I would also put the resistor going from the other pin on the switch to 5V, having the digital input connected directly to GND, but I'm not sure if that will affect power consumption, so it's probably more just a matter of personal preference.


Parse a large json response with ESP8266

Ok, so I was able to do this. Here's the workaround.

Let's say the GET response is a flat string containing large .json file with all the commas and curly brackets. The idea is to read it byte-by-byte and instead fo storing it just find whatever key you need and extract its value.

We want to find the field containing, say, "97.5 FM" from http://data.nba.net/data/10s/prod/v1/20190223/scoreboard.json (that's at the very end), skip 3 bytes (which is just " | ") and then read and Serial.print 4 bytes (which is "1280")*. We would do something like this (of course make sure to connect to wifi and include <ESP8266HTTPClient.h>:

HTTPClient http;
http.begin("http://data.nba.net/data/10s/prod/v1/20190223/scoreboard.json");
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK)
  Serial.println(getValue(http, "97.5 FM", 3, 4));

where the getValue() function is defined as follows:

String getValue(HTTPClient &http, String key, int skip, int get) {
  bool found = false, look = false;
  int ind = 0;
  String ret_str = "";

  int len = http.getSize();
  char char_buff[1];
  WiFiClient * stream = http.getStreamPtr();
  while (http.connected() && (len > 0 || len == -1)) {
    size_t size = stream->available();
    if (size) {
      int c = stream->readBytes(char_buff, ((size > sizeof(char_buff)) ? sizeof(char_buff) : size));
      if (len > 0)
        len -= c;
      if (found) {
        if (skip == 0) {
          ret_str += char_buff[0];
          get --;
        } else
          skip --;
        if (get <= 0)
          break;
      }
      else if ((!look) && (char_buff[0] == key[0])) {
        look = true;
        ind = 1;
      } else if (look && (char_buff[0] == key[ind])) {
        ind ++;
        if (ind == key.length()) found = true;
      } else if (look && (char_buff[0] != key[ind])) {
        ind = 0;
        look = false;
      }
    }
  }
  return ret_str;
}

You can call this getValue() whatever many times you like, but the strings you're looking for need to be only after each other, because the response to GET is read byte-by-byte just once.

There is probably (i.e., most likely) a better way of doing this, but this approach works and it's pretty fast, so...

* This, of course, is just an example, and you can overload this getValue() function definition to, say, read until it gets a curly bracket or whatever.


can i configure 2 (XBee series 2) modules using one explorer

You only need one.
In order to communicate in Point To Point, you must configure each xbee to belong to the same NetworkID (PAN ID). XBees can only communicate with each other if they have the same network ID. Configure one, switch the xbee then configure the other (see here)

There are more advanced configurations that you can use (check this tutorial for extended information).


It is quite complex to work out how "long" it will take to print.  Why?

If there is room in the serial buffer then the text just gets placed in that buffer. Takes almost no time at all to print.
You are printing a variable length string. The longer the string the longer it will take to print if the buffer is full.

However:

Each character consists of 10 symbols (8 data bits plus 1 start and 1 stop bit).
Characters are transmitted at 250000 symbols per second
Thus each character takes 1/(250000 / 10), or 40 microseconds to transfer through the actual wire.

So printing the number 100, which also has \r\n appended to it (characters 13 and 10) would need 5 characters. If the buffer is full it will take about 5*0.00004s = 200µs. If the buffer isn't full, it will take a fraction of that to just copy the data into the serial buffer.


How can I switch a 1.5V buzzer with my Arduino?

You simply need to ground the circuit. In row E on your breadboard just under where you connect the - of the battery, connect that to the ground pin on the UNO. This causes the buzzer to start working.


I have no idea what an apple homebutton is, but the easiest way to add more GPIO pins is to use something like an MCP23017; it connects over I2C and gives you 16 GPIO pins. Use five of them and you have your solution.


Configure input pullup through registers

Credits to GoForSmoke.
Also see Gerben's comment below.
See: https://forum.arduino.cc/index.php?topic=286145.0
byte ddrcMask =       ~
(
        (1 << DDC0) |  // pinMode( 14, INPUT ); // Set to input
        (1 << DDC1) |  // pinMode( 15, INPUT ); // Set to input
        (1 << DDC2) |  // pinMode( 16, INPUT ); // Set to input
        (1 << DDC3)    // pinMode( 17, INPUT ); // Set to input
);

byte portcMask =
(
        (1 << PORTC0) |  // digitalWrite( 14, HIGH ); // Enable the pullup
        (1 << PORTC1) |  // digitalWrite( 15, HIGH ); // Enable the pullup
        (1 << PORTC2) |  // digitalWrite( 16, HIGH ); // Enable the pullup
        (1 << PORTC3)    // digitalWrite( 17, HIGH ); // Enable the pullup
);

byte pincMask = ( (1 << PINC0) | (1 << PINC1) | (1 << PINC2) | (1 << PINC3) );

void setup( void )
{
  // Configure the pins for input
  DDRC = DDRC & ddrcMask;

  // Enable the pullups
  PORTC = PORTC | portcMask;

  // Read all four inputs
  uint8_t Pdat = PINC & pincMask;
}

void loop( void )
{
}


Why does the potentiometer act as an on/off switch in my program?

The answer is very simple. You use pin 12 for LED. Pin 12 can't do analogWrite(). This pin doesn't support PWM on Arduino UNO (Atmega 328)

Pin 3 is not OK either. Use of tone() function disables PWM on pin 3. From reference: "Use of the tone() function will interfere with PWM output on pins 3 and 11".


Replying with a html page in HTTP Web Server using esp01 and ArduinoIDE

Small update, I used the same code for ESP8266 NodeMCU.

Sorry If I am posting this with wrong device number. But I tried that same code and uploaded it to ESP8266, it worked, and I am getting the AP webpage, that I am storing and sending the file. I will post it as an answer as I need to post an image.

The is the page that I get when using the HTML that I wrote:

So, this happened. I am confused as to why it didn't work with ESP01, plus I have to load the code every time I plug in the ESP01.


Modify the call stack of interrupts on Arduino

Arduino is open source, so just modify the ISR to set a global flag when ran. Within func() just check for this flag and return when the condition is met. Little can be offered as little contextual information is given. To modify the stack you would have to work with avr assembly, but either way you must modify the ISR

Something like the following would work, but performance depends heavily on your application.

#define SPI_ISR_RAN 0x00
static volatile uint8_t flagByte;

void loop(){
    func();
}

void func(){
    uint8_t indicator;
    do {
        // Do something

        //Check for SPI condition
        ATOMIC_BLOCK(ATOMIC_RESTORESTATE){ //Atomic access is required
            indicator = flagByte;
        }
    }while( !(indicator & 1<<SPI_ISR_RAN) );

    ATOMIC_BLOCK(ATOMIC_RESTORESTATE){
        flagByte &= ~(1<<SPI_ISR_RAN); //Don't forget to clear the flag!
    }
}

ISR(SPI_STC_vect){
    // Do ISR necessities

    // Set flag when appropriate
    flagByte & 1<<SPI_ISR_RAN;
}


Compilling error not highlighting line in code

The line in error can often be highlighted, however because of the way the IDE plays with your source file this is not always the case.

See my post about How the IDE organizes things.

The IDE adds extra lines to your source, and then tries to hide that with #line directives. This can confuse the way error messages are handled. It is another example of the "helpful" IDE not always being helpful.

In any event, as Igor said, you can look for the line number in the error message and use that to find the error. Failing that, look at the quoted source code and search for that.


Transistor slows motor instead of turning it off

I can't make much sense of your diagram-  but this is the correct way to do it:

simulate this circuit – Schematic created using CircuitLab

R1 is low enough that the base gets 10-15mA of drive, sufficient for a few hundred mA of motor current. D1 protects the transistor Q1 when it turns off (from the motor inductance). The emitter of the NPN transistor should be grounded and then the collector will either be near ground or at the 9V level depending on whether it is off or on.

You may have damaged the transistor you are using (due to breaking it down in reverse across the E-B junction) so I would suggest proceeding with a new one. You didn't mention it, but it probably got quite warm.


Do we need ARM build for arduino while interfacing R-pi and arduino

The ARM build of the IDE is for running the IDE on ARM systems. If you want to run the IDE on the pi then you need the arm build. However if you want to run the IDE on your PC then you need the IDE build that matches the architecture of your pc.

There are a million and one ways of communicating wirelessly between an Arduino and a pi.


Adafruit_NeoPixel define pin for different setups

The “hint of blue on the strip” is a consequence of your second loop in rgbFadeInAndOutStrip1() ending with the test b > 0.  Because of that, the last strip1.setPixelColor() call sets the color to (0,0,1), a faint blue, instead of (0,0,0), off.  Here is some revised code that works ok:

#include <Adafruit_NeoPixel.h>
#include <avr/power.h>
enum { rgbPin1=8, rgbPin2=7, LEDcount=11, ledFadeTime=5};

Adafruit_NeoPixel strip1 = Adafruit_NeoPixel(LEDcount, rgbPin1);
Adafruit_NeoPixel strip2 = Adafruit_NeoPixel(LEDcount, rgbPin2);

void setup() {
  strip1.begin();
  strip1.show(); // Initialize all pixels to 'off'
  strip2.begin();
  strip2.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOutStrip1(0, 0, 255, ledFadeTime); // Blue
  rgbFadeInAndOutStrip2(255, 0, 0, ledFadeTime); // red
}

void fadeStrip(Adafruit_NeoPixel *strip, int bval, int bdir, uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b=0; b<255; ++b) {
    bval += bdir;
    for(uint8_t i=0; i<strip->numPixels(); ++i) {
      strip->setPixelColor(i, red * bval/255, green * bval/255, blue * bval/255);
    }
    strip->show();
    delay(wait);
  }
}

void rgbFadeInAndOutStrip1(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  fadeStrip(&strip1, -1, 1,   red, green, blue, wait);
  fadeStrip(&strip1, 255, -1, red, green, blue, wait);
}

void rgbFadeInAndOutStrip2(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  fadeStrip(&strip2, -1, 1,   red, green, blue, wait);
  fadeStrip(&strip2, 255, -1, red, green, blue, wait);
}

Note, since I ran tests on an Uno rather than a Leonardo, I attached pixel strings to pins 7 and 8 rather than 17 and 18.  I used enum to define constants, rather than declaring constants as variables, and factored some common code into functions rather than reduplicating it.

Following is another program (which I call neocycle6) you can use to test two strips.  Note, it only counts colors down to 1 rather than 0 because I like the effect of leftover pixels glowing faintly.  Also note: the round boards I used have only 7 LEDs each, so I set PixelCount to 7, not 11; this uses pins 7 and 8, not 17 and 18; I don't drive the brightness beyond 77 since the LEDs are so bright anyway; and it doesn't have an
#include <avr/power.h> statement, which you can add if needed.

// Drive 2 sets of 7 ea. WS2812 NeoPixels through sets of colors.
// jw 11 September 2015
#include <Adafruit_NeoPixel.h>

// Select pin# connected to NeoPixels strand, and number of NeoPixels.
enum { PixelPinA=7, PixelPinB=8, PixelCount=7 };
// Create a NeoPixels device structure
Adafruit_NeoPixel pixelA = Adafruit_NeoPixel(PixelCount, PixelPinA);
Adafruit_NeoPixel pixelB = Adafruit_NeoPixel(PixelCount, PixelPinB);

void setup() {
  byte i, j=0;
  pixelA.begin();               // Init. NeoPixel data structure
  pixelB.begin();               // Init. NeoPixel data structure
}

uint8_t c=1, d=1, p=0, v=1;
void loop() {
  c += d;
  if (c>76)
    d = -1;                     // Go down when done going up
  else {
    if (c<2) {                  // Set up for next pixel
      d = 1; p = (p+1)%PixelCount;
      if (!p) ++v;              // Rotate the weights to next color
    }
  }

  pixelA.setPixelColor(p, c*(v&1), c*((v&2)/2), c*((v&4)/4));
  pixelB.setPixelColor(p, c*((v&2)/2), c*(v&1), c*((v&4)/4));
  pixelA.show();               // Show updated colors
  pixelB.show();               // Show updated colors
  delay(9 + 300/c);            // Ramp small numbers more slowly
}


On Atmel (now Microchip) AVR microcontrollers, the sbi, cbi, sbis, and sbic assembly language instructions can only address the 32 IO ports at addresses between 0x20 and 0x3f. The Atmega168 and 328 (used in Arduinos prior to the Leonardo) has WAY more than 32 IO registers, so only a subset of them can be addressed by sbi and cbi (the AVR instruction set was nailed down YEARS ago, when 32 IO registers seemed like more than enough).

As a result, operations that set or clear a single bit in those 32 IO registers can be performed by a single instruction which executes in two clock cycles, but the same operations on the remaining IO registers require a full-blown load-operate-store sequence that takes at least three cycles to execute.

From what I recall, AVRlibC had multiple macros that did almost the same thing, but had different use cases:

One would compile to the fastest and most efficient instruction(s) available for that particular IO address.
One would always compile to sbi/cbi, and would throw a compiler error if you tried to access a register outside of 0x20-0x3f
One would ALWAYS compile to the load-act-store sequence, without regard to whether or not it could have used sbi/cbi instead.
One would always compile to the load-act-store sequence, but would throw a compiler error if you tried using it on an address between 0x20 and 0x3f.

Basically, the choice enabled you to decide between optimized (but variable) performance, uniformly-slow (but deterministic) execution time, or the fastest-possible (but deterministic-at-compile-time) variant [which required that the programmer be aware of whether the register in question was within or above 0x20-0x3f].


Need library help for Arduino USB host shield

The photos on Amazon show a clone of the circuit@home board so the same library should work. You may be running into the problem mentioned in the following page.

https://esp8266-notes.blogspot.com/2017/08/defective-arduino-usb-host-shield-boards.html


char ArrayBuffer[][4] = {};         // holds four characters, must be

declared as global to loop()

in

loop()
{
byte Index = 0;                    // initialize array index
if(Serial.available())             // have data in Serial buffer
{
byte Count = Serial.readBytes(ArrayBuffer[Index],4); // read       //4             //characters     into array buffer , returns actual number //of        characters //read and times out if less than 4 characters are //currently in Serial buffer
 Serial.println(ArrayBuffer[Index]); // print buffer to monitor
}while(++Index != 4);              // read 4 by 4 characters from incoming stream
}

...
continue with loop - process ArrayBuffer as required
}

This is one way to get the incoming stream from Serial buffer into for individual buffers, however, it is better, less chance of misdirecting the data into wrong buffer (index)  to read the entire buffer at once instead of using he readBytes four times.
Just my opinion, your mileage will vary.

PS what is the trick to format the code and text correctly ?
This is a mess.
I cannot get the code block to indent, I can get only the first ( four spaces line.


Is it possible to infer the length of a neopixel string using 1-wire protocol?

Each pixel "peels off" the first data word before passing on the rest, so the payload gets shorter and shorter as you move down the chain.  Although the data wire may look continuous it isn't - the signal is electrically re-driven from each unit to the next.

For the RGB ones, they are logically three monochrome pixels of different colors, so they peel off three words rather than just one.

At any point in the chain you can determine how many logical pixels potentially remain to be updated, by counting the words you are passing on.  You can't of course tell if they are actually there, or if there are further pixels for which no data is being provided.  And you can't tell how many pixels preceded, other than to bound it by the amount of gap time from the previous update you received.


Programing in Assembly for the Digispark

I've been given a digispark and am looking to write straight assembly code for it. Anyone know how to get started with this? I've been successful in getting the Arduino IDE set-up but would really like to avoid writing assembly in-line...

The Arduino IDE build support assembly files (.S). Nerd Ralph has written a  blog on the subject. There you will find all the details and how to write both inline and pure assembly files. He is really god at digging out all the details and sharing his findings.


Atmega2560V, trying to burn bootloaders of MegaCore

I removed 8Mhz from board and followed this instructions LINK, and burnt bootloaders using -F override check, then i returned 8Mhz oscillator to Atmega2560V and see device signature and it's automatically appears 0x1e9801 rather than 0x1e9803


The nano can run an IMU just fine, but unfortunately no accelerometer based IMU short of some fancy missile guidance tech is going to be able to track position as accurately as you seem to want.

Since the Gyro and Magnometer only help with rotational orientation, the accelerometer is the only source of info on linear motion, and it has to be integrated twice to get position or distance. This site has a great explanation:
http://www.chrobotics.com/library/accel-position-velocity

As their table shows, even with an angular error of only .1 degrees, after 1 minute your position could be off by 62 meters with a standard quality accelerometer.

As far as IMU's go, the MPU 6050 (accl, gyro) and MPU 9150 (Accl, gyro and mag) are pretty standard in the hobby area, and sparkfun has some breakouts. The AltiIMU from Pololu has similar features and comparable cost. If you don't want to do the sensor processing the UM7 from chrobotics works well, but is significantly more expensive.


Can Arduino post multiple sensor data to one Google Spreadsheet?

Not directly but with addon service like Pushingbox, temboo and so on it can.

If you google on your topic there are a ton of ways to do it!


Input audio from jack to Arduino, and output by

The simplest solution: it really depends. There are a couple of things to consider:

Bluetooth would probably be the least professional to impliment. The easiest way to do this is with an app. You can impliment it into your application with this:

  Let your own Android application receive data from Arduino by listening to the "primavera.arduino.intent.action.DATA_RECEIVED" intent. This intent will contain the "primavera.arduino.intent.extra.DATA" byte array with the received data. Call getByteArrayExtra("primavera.arduino.intent.extra.DATA") to retrieve the data. Send data to Arduino from your application by broadcasting an intent with action "primavera.arduino.intent.action.SEND_DATA". Add the data to be sent as byte array extra "primavera.arduino.intent.extra.DATA".

Still, that's pretty unprofessional IMHO. There are probably other ways to do this, but Arduino Uno Communicator is the easiest by far that I've seen. The main advantage of Bluetooth is it works without a router and it's very cheap (as far as wireless). I can't remember if it's the HC4 or HC5 chip that is commonly available, but [one of those] can be picked up for around $6. Just connect via serial and issue AT commands.
WiFi would be the most professional. First of all, people hear Wifi and they think Ohh! Shiny! I'm going to buy it! That's just what I've observed in the past, but it may not always be true. WiFi can be done with the TL-WR703N router. This blog post outlines how you can even connect it directly to the Arduino. You can also use an ethernet shield (or equivalence, I've seen breakout ethernet boards built for ~$5). Either way, it's a great way to add 5V WiFi to your Arduino. The only disadvantage is cost and it only works if you're near a WiFi router. If those aren't disadvantages, go ahead with WiFi; it's a great product.
USB is only useful if you want:

Speed
Stability
Portability (i.e. no WiFi Router)

Speed can be eliminated as a need if you only send data every 300 ms or so, depending on what you're doing. For WiFi, it might be best to only go to a webpage when an even occurs (i.e. button pushed on Arduino). Bluetooth and WiFi are stable enough if you're over short distances (and you couldn't go a long way with wires, anyway), and there's not too much interference (don't try at a football game with 50K cell phones... granted, they will be on different bands if using cell service, but Bluetooth may be on).

As far as portability, for the price of an OTG cable for your phone, you'd be better off buying a Bluetooth module for a dollar extra.

Suggestion: go with WiFi unless you need the portability. Consider figuring out WPS so your users can connect to WiFi with a push of a button. I don't know if the TL-WR703N has support for WPS, via serial or not.

Forgot to mention: I don't know everything about your app, but WiFi might have too much latency/overhead for near-instant response. As far as wireless, Bluetooth would have much lower latency AFAIK. (As you can tell, there's no perfect solution here :-))


1.8 - 5.5V (max)

The datasheet (http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Summary.pdf) will tell you that input Voltage is: 1.8 - 5.5V

That's max of 5.5V so don't use 9V battery without a voltage divider.
To power the chip all you need is voltage to Pin 7 and GND to PIN 8.

16Mhz Crystal Most Likely Required

However, to get it to work after removing the chip from an Arduino Uno board you will also need a 16Mhz Crystal on pins 9 & 10.  You will also need two 22pF capacitors on pins 9 & 10, each connected to ground.

I've written this all up with pictures at my blog: http://raddev.us/arduino/post/2018/07/03/arduino-uno-using-your-atmega328p-u-as-stand-alone

Your final circuit will look something like the following (from my blog article):

Without the Crystal you will most likely find that your sketches don't seem to run.

Note: The red LED is connected just as a blink test (more on that in the article).


Wemos D1 mini won't connect to WiFi: status code 6

Apparently, something went wrong with connecting to the router. The router was casting 802.11 g + n, which for some reason, made the esp8266 give a code 6. I have tried 802.11 b, 802.11 b+g+n, 802.11 n, which work all fine.
So I updated the settings that the router now uses 802.11n and the esp8266 can now connect to the internet!