Help to get Arduino UNO with 4 SoftwareSerial transmit only ports

As Chris Stratton suggests, multiple instances of SoftwareSerial may cause issues, particularly with pin-change interrupts.

I adapted SoftwareSerial a while back to have a "send only" version. This can be downloaded from here - 6 KB.

One normal SoftwareSerial and 3 instances of the "send only" may possibly help. I haven't tested it.

Chris's suggestion to modify SoftwareSerial to allow pin number changes on-the-fly may be even better. SoftwareSerial can only write to one pin at a time as it blocks, and thus having 4 instances of it doesn't really achieve anything.

Another possible approach would be to use a multiplexer chip. I have a page about that. You could have a single SoftwareSerial instance, and then use the multiplexer to forward its data to one of (up to 8) pins.

You would need pull-up resistors to keep the other pins high (idle) when not in use at a particular moment.


Almost, you will need two 74157 (or similar chips) to switch 8 pairs of TTL level logic signals down to 8 individual signal.


No, there is nothing "wrong" there. In fact it's the expected results.

The problem here is that pow() returns a float, and some numbers just can't be represented with floating point. When that floating point value is converted to an integer it truncates the decimal portion leaving you with the wrong integer value.

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

    int t = 0;
    for (int i = 0; i < 8; i++) {
        float f = pow(2, i);
        int d = f;
        t += f;
        Serial.print("2^");
        Serial.print(i);
        Serial.print(": float = ");
        Serial.print(f, 10);
        Serial.print(" int = ");
        Serial.print(d);
        Serial.print(" total = ");
        Serial.println(t);
    }
}

void loop() {
}

2^0: float = 1.0000000000 int = 1 total = 1
2^1: float = 2.0000000000 int = 2 total = 3
2^2: float = 3.9999995231 int = 3 total = 6
2^3: float = 7.9999980926 int = 7 total = 13
2^4: float = 15.9999961853 int = 15 total = 28
2^5: float = 31.9999885559 int = 31 total = 59
2^6: float = 63.9999771118 int = 63 total = 122
2^7: float = 127.9999542236 int = 127 total = 249

Instead you should use bit-shifting to perform the same operation on an integer:

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

    int t = 0;
    for (int i = 0; i < 8; i++) {
        int d = 1 << i;
        t += d;
        Serial.print("1<<");
        Serial.print(i);
        Serial.print(": int = ");
        Serial.print(d);
        Serial.print(" total = ");
        Serial.println(t);
    }
}

void loop() {
}

1<<0: int = 1 total = 1
1<<1: int = 2 total = 3
1<<2: int = 4 total = 7
1<<3: int = 8 total = 15
1<<4: int = 16 total = 31
1<<5: int = 32 total = 63
1<<6: int = 64 total = 127
1<<7: int = 128 total = 255


When analogWrite writes 0 or 255 value, it actually disables PWM output and sets the output to 0 or 1 correspondingly (maybe just one of them).
That's because there is just 256 values, but with both fully off and fully on PWM you'll need 257 values to archieve it.
If you're using direct access into OCRx, you have to make a choice if you want to have not fully on pwm or not fully off pwm (by setting polarity with COM2Xx)

Btw, you should clear TCCR2A/TCCR2B as all of the timers are configured by Arduino core to be running and prepared for the analogWrites...


If you run the IDE from a terminal you should get the output to STDOUT in your terminal to do with what you want.


Does the compiled binary of a sketch include uncalled functions from a library?

In general only the functions actually used by your code are included in the final linkage of the binary.
However it's not always possible for the compiler to know what is used and what isn't.
In the case of simple functions and classes there's no problem - the linker is intelligent enough to work it out and only link in the functions that are actually used.
However when it comes to more complex systems with polymorphism or when working with function pointers there are times when the compiler won't really know what is needed and what isn't so sometimes some code gets included that isn't actually wanted.
As the compiler advances those times are getting fewer and farther between, so unless you really have a dire need to reduce your code size there's really nothing much to gain. If you do have that need then you would gain more by reducing the complexity of the code in general and collapsing any polymorphism rather than removing unused functions.
BTW: the "optimize for size" has nothing to do with what code is included / excluded. Instead it controls such things as which function are selected for inline, and what loops are unrolled or not, amongst other things.


How to merge two GPS coordinates without losing decimals

If you want 4 decimal places, you may try something like this:

gps_string = String(gps.location.lat(), 4)
           + " x "
           + String(gps.location.lng(), 4);


Here is my Suggestion: In cases a clear answer could not be seen, you have to remove any weaknesses step by step to further encircle the problem. Since there is now answer for more than a month, I assume this as an appropriate proceeding.

One weakness I see in your coding is, that you are counting your values x, a, b, up to ten and you are printing them bevor reseting them to Zero, so your are printing 'x' even if it is ten. If for any reason in the further handling your display shows HEX values, you will end up displaying an 'A'. Change your Code so that values > 9 are not printed out, than this weakness will be removed.


[Solved]How to make my stepper motor run clockwise and counterclockwise?

Hi here it the reference to the library functions that are available in accelstepper library.

Go through the link, it will provide you the issues with your code and example for your application like @smajli said steps more than 1000 is unreliabe, here you can see setSpeed(float) function where setting negative or positive sign selects the direction and value set the speed of rotation.


No Battery Microcontroller Operation - (Motion, heat, induction etc)

10mA is quite a lot for a coin cell. And of course the duration is really low.

As for wireless power transmission, I highly discourage you. Since you are using coin cell batteries I think that size is a must for you, and for wireless power you will need a really big antenna. If it is a wearable I think that the receiver is on the body too, and so much power is not a good thing.

In my opinion and according to my experience you have two possibilities:

use alkaline batteries (e.g. AAA). Use a step up driver to get 3.3V from 1.5V (since the current you need is low you can use simple charge pump regulators, so with a 10pin TSSOP integrate and three small capacitors you are done) and you will get a really long lasting circuit. Drawback: AAA batteries are a bit large, so probably you'll have to make a bigger receiver
use lithium batteries (usually I use LiPo). You will then be able to recharge the battery with any power supply (I usually use an IC which can charge LiPos with a 5V source - USB - and a couple of other components (two capacitors and a LED with its resistor).

Personally I struggled with coin cells for a long time before giving up and sticking with lipos forever.


This is actually somewhat more tricky than you would at first thing.

First off, the "shock sensor" is merely a spring inside a tube.  This will create lots of triggers while it's being "shocked", which really is messy.

Secondly, you only want those shocks to make it through to the ESP when you are in deep sleep.

Thirdly, you don't want whatever you connect to adversely affect, or be affected by, other circuitry that is connected to the reset pin.

So you first really need to "condition" the output of your sensor so that it gives a clean pulse that can reset the ESP8266. Then you need to "gate" that signal so it can only get through while the board is asleep.

For conditioning the shock sensor signal I would be inclined to use a 55 timer in monostable mode.  You can find a good circuit and description here which looks like this:

Now to gate that signal (which is active high) you need a signal to gate it with.  Since all the GPIOs of the ESP8266 are "dead" while it's asleep you need it to be in a "default on" state and have the ESP8266 drive an "I am awake" signal to disable the output.  So you'd have a pullup resistor on a GPIO to make it default HIGH (to match the trigger pulse for simplicity) and then use pinMode() and digitalWrite() as the first things after waking up (and at the start of setup()) to indicate it's awake by driving it LOW.  Then you combine those two signals:

If the trigger is HIGH and
If the gate signal is HIGH
Then pull reset LOW
Otherwise don't affect reset

So you make a truth table:

Trig | Gate | Res
-----------------
  L  |  L   |  HiZ
  L  |  H   |  HiZ
  H  |  L   |  HiZ
  H  |  H   |  L

The tricky one here is the "HiZ" - This means "High Impedance" - or in effect "Don't affect the reset pin at all".

Apart from that the truth table is that for a NAND gate - if both inputs are HIGH then the output is LOW - otherwise the output is HIGH.  Except we want HiZ not HIGH.

To make that HiZ there's two things you can do:

Use a NAND gate that has an "Open Collector" (or "Open Drain") output, or
Use an AND gate and create your own "Open Collector" that inverts the output by adding a transistor.

For option 1 you can use the 74AC01 which is a "Quad 2 input NAND gate Open Collector".  For option 2 you can use the 74AC08 and any NPN transistor (or N-channel MOSFET with a suitable threshold).

simulate this circuit – Schematic created using CircuitLab


Method to iterate over the bits in a byte sent over serial

In all the examples below, value is the value of the byte

LSB -> MSB - so 00001111 would turn ON the first 4 devices and turn OFF the last 4

for(int i = 0, mask = 1; i < 8; i++, mask = mask << 1)
{
    if (value & mask)
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}

Alternatively, you can do the following, but value will be altered

for(int i = 0; i < 8; i++, value = value >> 1)
{
    if (value & 1)
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}

Working the other way around in each byte:
MSB -> LSB - so 00001111 would turn OFF the first 4 devices and turn ON the last 4

for(int i = 0, mask = 128; i < 8; i++, mask = mask >> 1)
{
    if (value & mask)
    {
        // bit "i" is on
    }
    else
    {
        // bit "i" is off
    }
}

Alternatively, you can do the following, but value will be altered

for(int i = 0; i < 8; i++, value = value << 1)
{
    if (value & 128)
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}


Arduino and MatLab with OWI Robotic Arm Edge -- Issue with I2C

The documentation in MATLAB for scanI2CBus() notes that the return is a cell array of character vectors

They even give the example:

a = arduino('COM9');
scanI2CBus(a,1)

with result:

ans =
            '0x48'

It appears you will need to parse the cell array into the numeric value or otherwise convert it to a number, perhaps using the MATLAB function hex2dec('hex_value')


The TIP120 is a poor choice because of the approximate 10% - 14% voltage drop across it. Try the circuit with a logic level, low Rds MOSFET.

For a more in-depth answer, please see this answer: https://electronics.stackexchange.com/a/388468/165322


Adafruit feather M0 wifi firmware update

USE AT YOUR OWN RISK
Here's what I did... (maybe some steps not necessary, but this worked for me)

1) First run the "CheckWifi101FirmwareVersion" found in the Arduino WiFi 101 library.

NOTE: You need to add in the WiFi.setPins(8,7,4,2); after void setup() {
If it's backlevel (before 19.4.4), then

2) Download the Adafruit WiFi101 Updater on github (
   https://github.com/adafruit/WiFi101-FirmwareUpdater/archive/master.zip
   )

3) Install the "FirmwareUpdater" from the Arduino WiFi 101 Library

Add in the recommended changes (even if it's the defaults)

#define WINC_CS 8
#define WINC_IRQ 7
#define WINC_RST 4
#define WINC_EN 2

and the usual WiFi.setPins(8,7,4,2) after void setup() {

4) Copy the firmware you wish to flash to same directory as "winc1500-uploader.exe"

5) Run the command:

  winc1500-uploader.exe --port [YourComPort] --firmware [YourFirmwareFileName].bin

So for example I did:

  winc1500-uploader.exe --port COM9 --firmware m2m_aio_2b0.bin


Is it possible to program an Arduino Pro Mini using an Arduino Uno R3?

Just hook up the pins (RX, TX, reset, Power, and Ground) to the corresponding pins on your Uno.

You may have to take the ATMega328 out of your Uno for this to work.

Keep in mind that you need to hook it up to the correct power pin! If your pro mini is running at 3.3v then you must hook it up to the 3.3 pin on your Uno.

Check out the ArduinoToBreadboard page for a bit more info. Scroll down to "Uploading Using an Arduino Board". Although it shows you how to program an Arduino on a breadboard, the wiring is the same.


Driving two stepper motors using one stepper motor driver

If we call the motor leads A1, A2, B1, B2 on each motor and control, you could tie the two motor A1's to A1 on the control, and motor B1's to B1 on control.  Then wire a DPDT relay as below.  (Coil not shown.)  Note, DPDT relays are about $4 on ebay, with labels like “DR21A01 DC 5V DPDT Relay Module Polarity reversal switch Board for Arduino UNO”.

simulate this circuit – Schematic created using CircuitLab

Since you have equipment in place and working, it might not be worthwhile to change your setup.  However, even without adding a relay, you probably can power both motor controls and motors with a single power supply, ie could use one instead of two power supplies.  The current draw when a stepper motor is idle is a small fraction (eg 10-20%) of the high current drawn when the motor steps.  If you don't have power attached to a stepper motor, there is only its cogging resistance to keep it from turning; it does not take a large torque to turn an unpowered stepper motor.  If that's a concern, the DPDT relay approach might be unsuitable.


How to make a button work a second time in my code?

The problem is that Message = ""; doesn't actually do anything, because the next time doorsturen is called, it will just load the previous command from the command variable. I'd suggest having the doorsturen function only return the command once, and not on consecutive calls.

String Doorsturen() //Methode om te communiceren via de serial monitor
{
  Command = "";
  if (Serial.available() > 0)
  {
    char readChar = (char) Serial.read();
    NMessage = NMessage + readChar;

    if (NMessage.startsWith("#") && NMessage.endsWith("%"))
    {
      index = NMessage.indexOf("%");
      NMessage = NMessage.substring(1, index);
      Serial.println(NMessage);
      Command = NMessage;
      NMessage = "";
      Bericht = true;
    }
    else if (NMessage.endsWith("%"))
    {
      NMessage = "";
    }
  }
  return Command;
}

see comment in the code

if (alarm == false) {
  if (buttonState == HIGH) {
    //here you set alarm to true
  }
}

...

if (alarm == true) { //now this if statement is true
  if (buttonState == HIGH) {//also buttonState is still high, because it's never updated after you set alarm to true

  }

to fix do this

if (alarm == false) {
   if (buttonState == HIGH) {
    delay(50);
    while (digitalRead(buttonPin) == HIGH) {}
    delay(50);// this is to negate switch bounce, on release, from interfering
    buttonState = false;// add this line
    alarmaan();
    Serial.println("fout");
   }
  }


The '328P uC on the boards is the same die. The 328P in DIP has 4 fewer pins brought out (Vcc, Gnd, A6, A7) compared to the surface mount parts. The boards themselves then bring the pins out to edge connectors in physically different locations.


How much numerical precision can the ESP8266 achieve?

There's not really any difference in numerical precision.  What you do get with 32-bit though is faster operations on larger data types.

For instance, to add two 32-bit numbers together (uint32_t) would take many operations on an 8-bit CPY, whereas on a 32-bit CPU it would just take a couple (only one to do the actual addition - a couple to load/save the values to memory).

One key difference, though, is that (to save space) the AVR system has double precision float values turned off and aliased to single precision float values.  This is purely a software feature and has nothing really to do with the hardware.  On 32-bit systems that is normally not done, so you can use double instead of float to increase precision.

However: While double is more accurate than float, it is still not precise.  All floating point values, regardless of precision, are only ever an approximation.  For that reason it is often preferred to use integer mathematics, and that is where libraries like BigNumber come in handy.  They allow you to (as the name suggests) work with much bigger numbers, which is good when dealing with integers when you want a high precision.

For instance, you could measure distance in km.  Say something is 18.329846283746km away.  You could store that as a single precision floating point value and it would end up as 18.329845428467.  As a double precision it would end up as 18.3298462837, which is closer, but still not right.

So you could represent it as meters instead of km.  So your 18.329846283746km would be 18329.846283746m.

How about if you represented it as mm instead?  18329846.283746mm

Say, why don't we go smaller?  Micrometers? 18329846283.746µm

I don't like that decimal point still.  What's smaller than µm? nanometers of course!  That would be 18,329,846,283,746nm.

Oh look, we have an integer value.  However that integer value is too big to fit in a 32-bit number even, which has a maximum of 4,294,967,295.  You could try using a 64-bit number (uint64_t) if the compiler you have supports it, which on both 8-bit and 32-bit systems would need multiple operations to work with (though less on the 32-bit), or you could use a library like BigNumber to deal with it all for you.

By using that method you start out by stating "I want to work in this fixed resolution and I want 100% precision within that resolution", rather than saying "I want to work with these values and I hope you'll get it vaguely right", which is far from ideal.

Also working with integer values is generally considerably faster than working with floating point values unless the CPU has a floating point unit available to do the heavy work for you.

So the difference between an 8-bit and a 32-bit system has nothing to do with the precision that is available to you, but everything to do with how fast operations at different precisions take to perform.


What is difference between NodeMCU and esp8266?

From https://forum.arduino.cc/index.php?topic=616324.0:

  NodeMcu is the name of the firmware originally for the ESP8266
  microcontroller, with support for the ESP32 microcontroller added more
  recently, that allows you to program these microcontrollers using the
  Lua programming language.

  NodeMCU firmware was developed so that AT commands can be replaced
  with Lua scripting making the life of developers easier. So it would
  be redundant to use AT commands again in NodeMCU.

And ESP8266 is one of the microcontrollers supported by the NodeMcu firmware.

From NodeMcu vs Esp32 vs esp8266

  In the early days of the hobbyist community's adoption of the ESP8266,
  ESP8266 development boards were marketed with the name NodeMcu and the
  term "NodeMcu" started to be associated more with the hardware than
  the firmware. It is common for people with no interest in the Lua
  programming language to buy "NodeMcu" boards and program them with the
  Arduino IDE, which erases the NodeMcu firmware from the board. To make
  things more confusing, multiple companies marketed boards with the
  name "NodeMcu", but with small hardware differences. Over time, the
  NodeMcu boards became less popular in the Arduino world because the
  similarly priced WeMos D1 Mini came out with the same functionality,
  but in a smaller form factor. Now, the "NodeMcu" name is being used to
  market ESP32 boards as well.


SerialEvent handling when using multiple serial ports

The built in serialEvent() function on arduino only responds to serial port 0, called just "Serial" in the code. To respond to messages on "Serial1", use serialEvent1() on the Arduino Due there also exists serialEvent2() and so on.

EDIT: the serialEvent() handlers are not on interrupts; they run sequentially in-between loops. If the loop is blocking they do not get run, and they do not interrupt eachother.


"expected primary-expression before '.' token" in debug code

In short: you have your macro backwards.

Macros are not formed as "Take this set of commands and call it X" but "Make this macro X and have it equate to this set of commands".

Where you have:

#define Serial.println(x) DEBUG_PRINT(x)

it should instead read:

#define DEBUG_PRINT(x) Serial.println(x)

When you call it, because the macro doesn't contain a semi-colon in it, you need to specify the semi-colon as if you were calling a function:

DEBUG_PRINT("Aardvark");

You can omit the semi-colon only if you have a semi-colon in your macro:

#define DEBUG_PRINT(x) Serial.println(x);

and then:

DEBUG_PRINT("Aardvark")

By doing it that way your "empty" macro now does become truly empty when used.  Without the semi-colon in the macro you would have to use:

DEBUG_PRINT("Aardvark");

Which for the empty variant would end up as:

;

Not always desirable, and can cause some problems.

So by adding the semi-colon into the macro you can omit it from the usage of the macro, and your empty variant now becomes:


Let's just deal with character strings.

The truth of the matter is that Arduino programming uses the language C.  C is very common and you can search for help in many places.

There are several ways to deal with strings in C.  In this example we are using an array of pointers to strings:

// let's make our own array of strings
char *states[] = {
    "California", "Oregon",
    "Washington", "Texas"
};
int num_states = 4;

for(i = 0; i < num_states; i++) {
    printf("state %d: %s\n", i, states[i]);
}

The output of this code looks like:

state 0: California
state 1: Oregon
state 2: Washington
state 3: Texas

I grabbed this example from here.

added later...

The method "printf" is normally not used in Arduino land.  So that "for" loop would look more like:

for(i = 0; i < num_states; i++)
{
 Serial.println("state ");
 Serial.println(i)
 Serial.println(states[i]);
}


Sketches not uploading to Micro from Ubuntu 14.04

I have a Micro and Ubuntu 14.04. I have successfully uploaded sketches to the Micro using IDE 1.0.6. Thus that combination should work.

I suggest you get the sketch compiling OK. Then hold down the Reset button on the Micro, start an upload with your other hand, and release Reset when it says "Uploading".

Try typing

lsusb | grep Arduino

I found with a sketch uploaded which opens the Serial port:

Bus 003 Device 087: ID 2341:8037 Arduino SA

If you hit Reset and wait a second, then do the lsusb again you see a different device:

Bus 003 Device 086: ID 2341:0036 Arduino SA

That one (the 0036 one) is the one it will upload to. You might get 0037 rather than 0036 because I reflashed the bootloader to be the Leonardo one, but the concept is the same.


Is it possible to hookup two ultrasonic sensors to one Arduino Uno unit?

Yes, it is certainly possible.  There are a few things you need to be aware of:

1)  The Arduino UNO is 5V by design.  Many sensors (not all, but many) are 3.3V devices.  So connecting them to a 5V pin could damage them.  Since you seem to be just starting out, I'd recommend sticking with 5V tolerant sensors.

2)  The Arduino UNO only has so many pins available....obviously.  Different sensors require different amount of pins to 'work'.  For example, a temperature sensor might work with the SPI interface.  Another sensor might require 8 pins.  So if you start running out of pins, you need to think about other challenges like using shift registers, multiplexers, etc.

3)  Don't be afraid to experiment.  I suggest buying a genuine Arduino UNO to support the project.  Maybe buy some cheap Chinese ones to experiment on...in case you fry on of those.

In theory, the sky's the limit when it comes to "how many".  In real life, if you start going over a handful, dozen, etc. then you might want to rethink your design.


SPI with a level converter in the other end of connection

More than probably your level shifter is not fast enough.
A level shifter uses a mosfet to copy signals from one voltage level to the other, but each mosfet has a latency or, if you prefer, a rise time.
Your board probably doesn't use a fast switching mosfet and so the SPI protocol (which is a quite fast one) is not copied correctly.

On top of that you actually don't need a level switcher for the nRF24 modules: the power pin must be limited to 3.3V, but the signal pins are 5V tolerant.
This means you only need a 3.3V voltage source and all the remaining connections can go directly (and safely) into your Arduino board.

UPDATE: the speed concept still applies, it doesn't matter which side of the connection you are using. A mosfet has a little capacitance which slows down the signal transmission: higher the capacitance, slower the maximum data rate.
The cheap chinese level shifter is not designed for high speed communication, while the Texas Instrument device is clearly designed for high speed.
If you look at the SN74HCT245 datasheet you'll notice the switching speed is reported for 50pF capacitance and ranges from 8ns to 16ns: that's the time needed to build enough charge in the switching circuit.


I copied the SainSmart library to the IDE's library folder, not noticing that there was already a folder named "LiquidCrystal". Apparently the files added to the existing folder are being ignored.

Renaming the SainSmart library before adding it solves the problem.


error: too few arguments to function 'char* itoa(int, char*, int)' byte blockcontent= itoa(order); ^ In file include

itoa requires a minimum of 2 arguments.

Reference: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaa571de9e773dde59b0550a5ca4bd2f00


How do I clear previous values while using strcat() to add strings?

strcat always concatenates to the end of the string. Instead, for your first strcat you should really be using strcpy, which copies one string over the top of the other - that is, it places it at the start of the string, effectively starting a new string.

However, unless you really need the data in a string for some specific reason, you don't need to build a string up - just print each part to serial separately with its own Serial.print function.


Should I use a loop instead of an If statement?

What you are lacking is the else concept:

If a touch pad is pressed, then

Turn the relay on

else

Turn the relay off

Rather than turn the relay off every iteration, you only turn it off if the touch pad is not pressed.

That can be written as:

val_1 = digitalRead(touchPin1);

if(val_1 ==1)
{
  Serial.println("Pad 1 Touched");
  digitalWrite(relayPin1, HIGH);
} else {
  digitalWrite(relayPin1, LOW);
}

If you want your messages to be more meaningful and not spam, then you can remember the previous state and only do things if the state changes:

static uint8_t oldVal1 = LOW;

uint8_t val1 = digitaRead(touchPin1);

if (val1 != oldVal1) {
    oldVal1 = val1;
    if (val1 == HIGH) {
        Serial.println("Pad 1 Touched");
        digitalWrite(relayPin1, HIGH);
    } else {
        Serial.println("Pad 1 Released");
        digitalWrite(relayPin1, LOW);
    }
}


How to run stepper motor at its maximum speed

As this link states:

  Stepper motors are normally used for positioning, and are not known
  for their speed.

However, the link is to an on line stepping motor speed calculator.

As for the size of the step, this is a function of the way the stepping motor is built.  Some controllers / stepping motor combinations can do half steps or micro steps.  Disable these feature for the fewest number of steps per revolution.

These are some of the basic concepts which deal with practical stepping motor applications.  As speed increases, other factors come into play.  For example, resonance and inductance.

In this paper resonance is discussed:

  If a rigidly mounted stepping motor is rigidly coupled to a
  frictionless load and then stepped at a frequency near the resonant
  frequency, energy will be pumped into the resonant system, and the
  result of this is that the motor will literally lose control.

The paper also discusses the effect of the stepper motor's coil inductance:

  An important consideration in designing high-speed stepping motor
  controllers is the effect of the inductance of the motor windings. ...
  The inductance of the motor winding determines the rise and fall time
  of the current through the windings. ...


I'm going to assume you are using the UNO model - or any other board based around the Atmega328p.

According to the datasheet the voltage limits are 1.8v to 5.5, with an absolute maximum of 6v.
You should be fine - but if you are able to get the voltage down closer to 5 volts, I would recommend doing that instead.


Usually by Firmware we understand "a program that was prepared by company that produced the hardware and that is necessary for that hardware to work correctly". I suppose that developers of mBlock are smart enough not to allow people to "brick" their Arduino's. I suspect that ether you updated your bootloader (it's also a firmware) to latest version or simply nothing happened. In both cases your device should be operational. Burning a bootloader onto an Arduino is not as hard as it seems so even if you broke something you should be able to fix it.


I had lots of issues when I first started.  these are all things I tried and at least one of them stopped this problem occurring, but I haven't a clue which.

Close the IDE (if you are using it and open it again)
Disconnect your board, wait 10 seconds and reconnect it.
Check you settings, are you using the correct board, etc.
Use a different cable.
Update your drivers.
Update your IDE/Toolset.
Use a different physical port on your PC.
Load the Blink example, if that doesn't work you serious have issues.
Reboot your PC.
If you can, try a different PC.


Integer goes garbage after iteration. struct pointer manipulation messed up other variables in memory

If you have a Charliplexing board like mine (or even if you made your own) the problem could be electrical. If you turn on a lot of LEDs you may exceed the current consumption allowed and then the processor hangs or resets.

I suggest current-limiting resistors like this:


error: no '' member function declared in class 'SonarSRF08'

Please note that I did not try to run your code on my Mega because I don't have SRFs
However, here is what I tried to recreate your error:

I went to the arduino homepage and downloaded the 1.0.5 version.

I downloaded the zipped library from this page SRF08 Ultra Sonic Range Finder

I imported the library into the arduino IDE. For this, I had to unpack the .zip and rename the folder of the library because arduino complained about non-ascii characters. I just called the enclosing folder "arduinoSRFmaster" without dashes. After that it let me import the library the usual way:

After that I copied your code into a new sketch and hit Ctrl + R to compile and verify. It compiled just fine:

(Picture updated for compiling against MEGA)
Please provide more information, like yor OS, Arduino Version, where you got the SRF Library from etc. if that didn't help.


You are not very much clear but these are the possible reasons for your problem.

You are using a while loop in your setup() function in your code. Your code might get stuck in there that's why you are not able to see pitch and roll. Try removing comment from the Serial.begin function over there.
After Changing baudrate in your code please make sure you are changing it on your serial monitor as well.


How to make "IF "Temperature exceeds" logic to work in same arduino code

The code below will check if the temperature goes above 29 degrees. It also check whether the temperature was below 29 previously, to prevent it from sending an SMS every second, for as long as it's above 29 degrees C.

#include "SIM900.h"
#include <SoftwareSerial.h>
#include "call.h"
#include <DHT.h>
#include "sms.h"

SMSGSM sms;
#define DHTPIN 7
#define DHTTYPE DHT22

CallGSM call;
boolean started=false;
char sms_text[160];

DHT dht(DHTPIN, DHTTYPE);

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");
}

float previousTemperature = 0;
void loop()
{
    float humidity, temperature;
    humidity = dht.readHumidity();
    temperature = dht.readTemperature();
    delay(1000);

    // check if temperature has raised to above 29 degrees
    if(temperature>29 && previousTemperature<=29)
    {
        sendSMS(temperature, humidity);
    }
    previousTemperature = temperature;

    // check for incomming call
    switch (call.CallStatus())
    {
        case CALL_NONE: // Nothing is happening
            break;

        case CALL_INCOM_VOICE : // Yes! Someone is calling us
            Serial.println("RECEIVING CALL");
            call.HangUp();
            delay(1000);
            sendSMS(temperature, humidity);
            break;

        case CALL_COMM_LINE_BUSY:  // In this case the call would be established
            Serial.println("TALKING. Line busy.");
            break;
    }

    delay(1000);
}

void sendSMS(float temperature, float humidity)
{
    String smsText ="";
    smsText = "Temperature: "+String(temperature,1)+"C Humidity: "+String(humidity,1)+"%";
    smsText.toCharArray(sms_text,160);
    //Serial.println(smsText);
    sms.SendSMS("+91**********",sms_text);
}


I'm wondering how long I can leave this running off battery power. Does anyone know how to estimate this?

If your circuit draws 1A @ 12V, a 12V 1Ah battery will power it for approximately one hour. A 9V alkaline typically contains about 565mAh. You can use the datasheets to sum all the power consumption, but its probably easier just to measure it with a multimeter.

  As a side note, if anyone spots a way to improve battery life in my
  sketch / wiring, I'd love to know.

-Check out the ATTiny series (parametric); they are tiny, low-power, and Arduino-compatible; perfect when you only need a couple of pins.

-Use an interrupt to monitor the button's pin; the MCU can sleep until the interrupt fires.

Generally:
1) The interrupt will set a flag so main() knows that something happened, then wake the processor.
2) Main() resumes, checks the flag, turns on/off the LED accordingly, tells the servo where to go, waits for the servo to get there (delay()), clears the flag, and then puts the MCU back to sleep.

-As others have pointed out, delay() is bad. delay() tells the MCU to do nothing (NO-OP) repeatedly, for a period of time. This is different from having nothing to do because it's asleep.


One sample takes 38 I2C clock cycles to write. That's:

1 START
7 Address
1 R/W
1 ACK
8 Byte
1 ACK
8 Byte
1 ACK
8 Byte
1 ACK
1 STOP

At the default 100kHz clock speed that's 100,000/38 = 2631.58 samples per second absolute maximum.

You can increase the clock speed to 400kHz, which would allow you 400,000 / 38 = 10526 samples per second absolute maximum.  That would just about be do-able.

I am unsure what the ESP8266 can support, but the DAC also supports "High Speed" mode - 3.4MHz I2C.  If the ESP8266 supports that you can then run at 3,400,000 / 38 = 89474 samples per second, which is better still.

There's also the matter of the map() function which is just nasty in this situation. You can just bit-shift.

So besides just removing the Serial commands (which will slow things down massively) you should also:

Change the I2C clock to at least 400kHz
Change map() to soundData[indx++] << 4
Consider using a timer to trigger the sending of the samples

But, with all that said. an I2C DAC is really not suited to audio playback. I2C is just too slow and clunky for audio. You'd be better off with an SPI DAC which can run much much faster than I2C. Better still you should investigate I2S on the ESP8266. This is designed specifically for audio, although it's much harder to set up owing to the increased number of special clocks you need to provide ("master" clock, "bit" clock and "l/r" clock). Also the DACs (also known as CODECs) tend to be at least 16 bit or even higher, and capable of proper audio sampling frequencies, like 44100ksps and above.


Library LiquidCrystal_I2C don't work in other class (Composition)

Most likely cause

You are hitting an insidious problem that even experienced C++ programmers frequently miss: order of initialization of global variables. In your case, Display lcd is initialized (i.e., its constructor is called) before main() and subsequently setup() are executed. However, you almost certainly are #includeing whatever library is declaring the LiquidCrystal_I2C class, probably Wire.h, and so on. In many of these classes, a global variable of that type is also defined to make it easier to access stuff. For example, Serial (as in Serial.println("foo")) is really a global variable of the appropriate type of whatever serial implementation your particular core is using.

The problem you are hitting is that the C++ standard does not guarantee the execution order of the constructors of global variables. The order is an artifact of the compiler, the order in which object files were linked, and probably the phase of the moon :)

What is (almost certainly) happening is that the constructor for your class Display is being called, which initializes the LCD and the i2c bus, and then something else calls either the LCD constructor or the i2c constructor and messes things up.

OK, "how do I fix this?" I hear you ask. Simple: make the global lcd variable a pointer, and allocate the instance in begin(), like so:

#include "Display.h"

Display *lcd;

void setup() {
  Serial.begin(9600);
  lcd = new Display();
  // stuff
}

void loop() {
  // more stuff
  lcd->some_method(some_argument);
  // even more stuff
}

Now you are guaranteed that your code will be the last to touch any initialization code that might affect the display or the bus. Just keep accessing the class Display methods through the pointer.

A less likely cause

It is still possible that your constructors are getting executed in the right order, but your hardware does not like being initialized twice (but test that anyway!), so you may have to figure out how to reset the hardware so you can initialize it again. If I understand your posting correctly, the loop never runs, which means that a second initialization probably either causes a exception (which you would not see unless you had some kind of additional debugging channel; in the case of the ESP8266, for example, that would be the output-only Serial1 port, and even then, you'd have to explicitly turn on debugging. Each core has its own debugging stuff, I forget what the real Arduino does.)

Hope this helps.

/ji


What to with reset pin when laying out Arduino PCB?

"Atmel AVR042: AVR Hardware Design Considerations"


how to stop the relay after it is getting on and let the sensor get the result

If all the pumps have to work for pump_periods[i] time on every loop, and you will have a long delay() anyway, you could replace the for loop with:
for (int i = 0; i < jml_pump; i++) { // For every pump:
  digitalWrite(pump_pins[i], 1);     // Start pump i
  delay(pump_periods[i]);            // Wait for pump_periods[i] ms
  digitalWrite(pump_pins[i], 0);     // Stop pump i
}
delay(120000);                       // Wait 2 minutes until mixed

This will block the loop, but you will have a long delay anyway. The pumps will work sequentially, and not at the same time.
Is that what you want?


Arduino serial port eats data for 3 seconds before it sends?

Is this a Leonardo or Yun?  If it is, you have to wait until the Serial object says the USB connection is really ready:

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB
}

Read this.

Because you did't wait, your loop is able to execute 3000 times before Serial actually sends something back to the PC.


when a chip gets hot as soon as the VCC/GND is connected, it means :

The VCC/GND are internally connected due to a previous failure (it
gets hot AFTER the accident).
An output pin, is connected to a supply rail through a very low resistance load (or short circuited). pins usually sink or
source as low as 20mA of current. so if you connect them to a load
less than (3.3/20)*1000 ~= 150 ohms (in your case with 3.3v supply),
you are going to fry the output driver. always be sure that a pin, even if it's defined as an input, has a little resistor (a 220 ohms res).
this accident happens between output/supply or output/output pins.

you may have misconnected TX pin to a wrong pin.


From the datasheet of the hall effect sensor, the thing is only checking for 125usec in every 125msec - so if your magnet whizzes by in <100msec it will miss it.

Obviously you haven't stated the speed your magnet passes your sensor, but as it's only active 0.1% of the time, this seems the likely reason to miss.

Can you put it nearer the shaft/axle ?


You need to isolate your button from the logic output using a diode. For example:

simulate this circuit – Schematic created using CircuitLab

In this method M1's gate is normally pulled up by R2. It can either be pulled down by M2 (switched by the "HOLD" signal) or by the switch via D1.

The BTN input is pulled up by R1, and can be pulled down by the switch. M2 can't pull it down because the diode is reverse biased and blocks current trying to flow from BTN via M2 to ground.

R3 is just a pull-down on the gate of M2 to keep it off when HOLD is floating (the power is off).

If you need to interface the 5V "BTN" signal with a lower voltage-tolerant input pin just use a couple of resistors as a voltage divider to reduce the voltage to within the proper levels for the pin.


Can one supply an Arduino Zero's VIN pin with 5v?

Yes you can. If you look at the schematics on the Arduino website you can see that the 3.3 volt regulator is connected to the 5 volt regulator. That means that if you feed 5 volts straight into the 5 volt pin it will go through the 3.3 volt regulator to supply the main chip.
Note that this is going into the 5 volt pin not the VIN pin which goes into the 5 volt regulator and would thus require a higher voltage than 5 volts.


jsonBuffer is local to the function. When you leave the function the contents of jsonBuffer are lost.

functions just points to the internals of jsonBuffer to get its data (to save memory).

You can either:

Make the jsonBuffer global so it sticks around all the time, or
Have a secondary DynamicJsonDocument or StaticJsonDocument that is global to which you copy your objects once read from jsonBuffer.


How to count the number of times a changing variable reaches a peak value

The counting portion of what you want to achieve is simple - you just increment a variable.  The hard part is knowing when to count.

You need to remember what your value has been doing in the past in order to know if you have had a peak or not.  Also you have to define exactly what a peak is.

The simplest method (I'm not going to spoon feed you code, just help you understand the concepts) is to set a couple of thresholds, and maintain a flag.

You decide upon a value "above which the value enters the peak zone", and another "below which the value leaves the peak zone".  They could be the same value, but don't need to be.

You then have a flag which remembers if you are in the peak zone or not.

If you're not currently in the peak zone and the new value is above the peak zone entry threshold then you have entered the peak zone.  Set the flag to remember that fact.

If you are currently in the peak zone and the new value is below the peak zone leaving threshold then you have just left the peak zone.  Clear the flag to remember the fact that you're not in the peak zone and increment your peak counter now you have left the peak.

It can be very good to have the leaving threshold lower than the entering threshold so that the value has to drop significantly out of the peak zone before it will register another peak.  This is known as hysteresis and is great for getting rid of the noise you may get if the value is hovering around the peak zone entry threshold.


Detect if a chair is occupied using Arduino with some sensors

As has been mentioned in the comments there's many ways of sensing, each with its own pros and cons.

Sensing the presence of something is actually twofold.  First you need to know if there is something there, and secondly you need to try and identify what it is that's there and if it fits your criteria.

With passive sensors of the type used by Arduinos it all comes down to a matter of probability.

If you have force sensors, you know when something is there, but you can't work out what is there, only that it weighs a certain amount.

Using capacitative sensors you can get an idea about what the something is made of - how much does it affect the capacitance, etc.

Using ultrasound and/or infra-red beams etc you can get an idea of the kind of size of the object that is in the chair.

So combining them all together you can work out the likelihood that it is a human if:

It weighs enough to be a human
It has a suitable dielectric response to be a human
It is big enough to be a human

Of course, there's always the chance that it's just a big dog, or a sack of potatoes.

So it's all a case of improving that probability by adding more sensors of different types, until you are almost certain that it is a human.  You will never be 100% certain, of course.


How fast is an Arduino?

Arduino Uno is based on AVR MCU and run at 16 MHz. Due to the processor architecture it can execute almost 1 instruction per clock cycles (62.5 ns). It uses a simple two step pipeline which may require restart if a branch is taken. There are some instructions such as memory access that take more than one clock cycle.

  Can an Arduino Uno calculate the time that an assembly instruction will take in nanoseconds, not microseconds?

It is possible to measure the execution time with a resolution of 4 us with micros(). Please describe what you want to calculate/measure.

For more details on ATmega328p please see the data-sheet, chap. 6.6 Instruction Execution Timing.


Count RISING edges of a wave form by using ARDUINO

I have choosen the values of R and C by experiments. Do you have a suggest for choose these values?

I have a page about switches - somewhat down the page is a discussion of debouncing, including some calculations which show how you can calculate the debounce time. With the switch pin pulled high by the internal pull-up (something you don't appear to be doing), and a 1 µF capacitor, that gives you a debounce of about 35 ms.

Example schematic:

Results on input pin:

(Maths supporting that figure on the above page).

Note that it is important to have a pull-up or pull-down for your switch or it will read random values if not closed.


To use this sketch, you will need the Bounce2 Library, and two N.O. switches connected between GND and the Arduino Digital Pins specified. I'm not sure if there is a limit to the number of Bounce2 objects you can create. Have a look at the Bounce2.h and Bounce2.cpp files.

#include <Bounce2.h>
byte buttonOneState = 0;
byte buttonTwoState = 0;
const byte buttonPin1 = 4;
const byte buttonPin2 = 5;
const byte debouncerInterval = 50;

// Instantiate ONE OR MORE Bounce2 object(s).
Bounce debouncer = Bounce();
Bounce debouncer2 = Bounce();

void setup(){
  Serial.begin(9600);
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  debouncer.attach(buttonPin1);
  debouncer.interval(debouncerInterval);
  debouncer2.attach(buttonPin2);
  debouncer2.interval(debouncerInterval);
}

void loop(){

  // Button 1
  if(debouncer.update()){
    if(debouncer.read() == 0){
      if(buttonOneState == 0){
        Serial.println("Turn Relay 1 ON");
        buttonOneState = 1;
      }
      else{
        Serial.println("Turn Relay 1 OFF");
        buttonOneState = 0;
      }
    }
  }

  // Button 2
  if(debouncer2.update()){
    if(debouncer2.read() == 0){
      if(buttonTwoState == 0){
        Serial.println("Turn Relay 2 ON");
        buttonTwoState = 1;
      }
      else{
        Serial.println("Turn Relay 2 OFF");
        buttonTwoState = 0;
      }
    }
  }

}


It doesn't look like it's true. There is only one SPI module and it has fixed pins which are not duplicated anywhere.

However there are three instances of USART which can be used in synchronous mode as SPI:

USART0: RXD0(PA10) / TXD0(PA11) / SCK0(PA17)
USART1: RXD1(PA12) / TXD1(PA13) / SCK1(PA16)
USART2: RXD2(PB21) / TXD2(PB20) / SCK2(PB24)

Whole table from SAM3X datasheet:

But I'm not sure if the Arduino IDE supports this mode, or you'll have to do it from scratch by yourself.

You can even use RTS as select slave signal:


Output set to 'low' when new variable in buffer

Your problem is in one tricky option for arduino's com connection. When you reopen COM port where arduino is connected your arduino resets automatically.

Here's workaround from arduino.cc:

  DisablingAutoResetOnSerialConnection

  The simple way that doesn't require
  any permanent modifying of your hardware or software configuration
  changes:

  Stick a 120 ohm resistor in the headers between 5v and reset (you can
  find these on the isp connector too). 120 is hard to find so just
  combine resistors. Don't go below 110 ohms or above 124 ohms, and
  don't do this with an isp programmer attached. You can just pull out
  the resistor when you want auto-reset back.

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

Or you can just modify you script to be able to start over without reopening it.
For example use a loop there and some exit command to end that loop:

try:
    while True:
        do_something()
except KeyboardInterrupt:
    pass

https://stackoverflow.com/questions/13180941/how-to-kill-a-while-loop-with-a-keystroke
Replace do_something() with this part of your code:

ser.reset_input_buffer()
ser.reset_output_buffer()
pin_number= int(sys.argv[1])
high_or_low=int(sys.argv[2])

ser.write(struct.pack('>5B',8,1,pin_number,high_or_low,9))

I hope I was clear enough.


The problem (I believe) is that half way through your program you switched from using println() to using print(), thus the commands from that point on aren't being executed until right at the end where you switch back to println(), so the whole of the text you send from point 3 onwards is being run as one single command - which of course is in the wrong format:

  AT+SAPBR=3,1,"CONTYPE","GPRS"AT+SAPBR=3,1,"APN","internet"AT+SAPBR=1,1AT+HTTPINITAT+HTTPPARA="URL","xx.xx.xx.xx/my/web/site"AT+HTTPDATA=100,1000AT+HTTPREAD


How to use capactive touch on Adafruit board in Arduino mode?

Example code for capacitive touch on Trinket M0.  Note: make sure to install the Adafruit FreeTouch library.
// touch - Capacitive touch demo using FreeTouch. Trinket M0 version.
// Note: the pin silkscreened 1 is Analog Pin 0.

#include "Adafruit_FreeTouch.h"

Adafruit_FreeTouch qt_1 = Adafruit_FreeTouch(A0, OVERSAMPLE_4, RESISTOR_50K, FREQ_MODE_NONE);

void setup()
{
  // Initialize A0 as a touch sensor
  if (! qt_1.begin())
    Serial.println("Failed to begin qt on pin A0");
}

void loop()
{
  int counter, result = 0;
  counter = millis();
  result = qt_1.measure();
  Serial.print("QT 1: "); Serial.print(result);
  Serial.print(" (");  Serial.print(millis() - counter); Serial.println(" ms)");
  Serial.println("\n*************************************");
  delay(200);
}

Information about the parameters for the constructor can be found at: https://forums.adafruit.com/viewtopic.php?f=8&p=610501  and are paraphrased below incase the link goes dead.
The parameters for the constructor are:
p - The input pin connected to the sensor.
t - How much to oversample the input.  One of the following:
OVERSAMPLE_1
OVERSAMPLE_2
OVERSAMPLE_4
OVERSAMPLE_8
OVERSAMPLE_16
OVERSAMPLE_32
OVERSAMPLE_64

Oversampling is a process of taking several measurements, finding the average, and reporting that instead of the actual readings. It's way of reducing noise, but also improves the accuracy of the measurement. The average value of noise is zero (if it wasn't, it would be a source of free energy), so the more readings you add together, the closer the noise error in the measurements approaches zero.
There's another side-effect of adding noise to measurements though: it dithers the sensor output around the real input value. If I have a window comparator that only measures "below 1v" and "above 2v", and feed it a signal at 1.1v plus a couple of volts of noise, I can expect to see about ten "below 1v" outputs for every one "above 2v" output. The noise pushes the signals above and below the thresholds, but vanishes if I take the average of a large enough sample. Statistically, getting a 10:1 improvement in resolution like that would take about 64 readings to make the noise error small enough to ignore.
Oversampling takes longer though, so there's always a tradeoff between how much you can do and how long the signal will remain stable.
r - The value of the resistor that will discharge the touch pad.  One of the following:
RESISTOR_0
RESISTOR_20K
RESISTOR_50K
RESISTOR_100K

f - Frequency mode.  One of the following:
FREQ_MODE_NONE
FREQ_MODE_HOP
FREQ_MODE_SPREAD
FREQ_MODE_SPREAD_MEDIAN

For systems that take repeated measurements, there's one kind of noise that doesn't average to zero: noise that occurs at the same frequency as the sampling rate. There are all sorts of videos that show the effect of a camera being in sync with the thing it's recording.. this one is especially nice:   https://www.youtube.com/watch?v=uENITui5_jU
For capacitive sensors, things like induced signal from fluorescent lights can create noise, and if the lamp frequency is just slightly off of your sampling frequency, the touch system will think it looks like a series of touches.
(If you have an oscilloscope, hold the tip of a probe between your fingers and put your hand within a foot or so of a fluorescent light.)
One way to prevent that is to change the sampling frequency. You can shift it up and down in a predictable pattern, hop from one frequency to another, or add some random jitter. Atmel's QTouch library supports all those options, but 'NONE' (fixed frequency readings) is the simplest.


avrdude fuse error when programming ATMEGA328 without crystal

The ATMega328P datasheet has the following table in it:

The top 5 bits of the of the Extended Fuse Byte are default 1 and are reserved.  You're not really supposed to change them, since they might be used in the future for a 328P-like part and setting them to something other than 1 could have unexpected results.  In the 328PB variant bit number 3 is used for "Disable Clock Failure Detection".
The lower three bits of 0xFD and 0x05 are both 0b101.  In other words, taking into account only the bits you should be setting, for the BODLEVELn fuses, they would have the same effect.  But you are being WARNED that you should be using 0xFD rather than 0x05 for the above reason.
The boards.txt that comes in the breadboard-1-6-x.zip has a line that looks like this:

atmega328bb.bootloader.extended_fuses=0x05

You could change this yourself by editing the file, but really for what you're doing I'd recommend MCUdude MiniCore which is comparatively up to date.  If nothing else, its boards.txt file has been written with the correct fuse values.  You can see there for a plain 328P (not PB) which does not support clock failure detection, the CFD bit is just hardcoded to 1 in the file.
The message you're seeing is a "WARNING" through, rather than "ERROR".  The distinction being that warnings don't actually stop you from continuing.  It is likely that if you're having a problem isn't not really because they've incorrectly specified the high-order bits of the fuse.  If it's halting, it may be arduino-builder see a non-zero exit code for avrdude and thinking this means "ERROR" rather than "WARNING", in which case this problem will go away if you edit the boards.txt file (or adopt MiniCore) such that no longer produces the warning.
Unless you've brought the effective system clock below 1MHz, probably lower still, it's not likely that you'll need to change from the default ISP clock rate.  If you do though, that can also be done by editing board package files.


Here the proper answer:

The vast majority of devices are constant-voltage devices. They need a constant operating voltage to work correctly. Microcontrollers are such devices. When operating, they will try to draw as much current from the power source, as they need, but not more. Much like a simple resistor with an applied voltage will draw a specific amount of current (calculable with Ohm's law), complex devices like microcontrolelrs have something like an overall impedance/resistance, that is depending on their specific operation. So also here the device only draws as much current, as it needs. (I wrote about an overall impedance to emphasize the fundamental principle. No one would really specify an overall impedance for such a device, because this would only be a value calculated by the voltage and current needed, not a real resistance.)

This means, that burning parts are not due to the power supply supplying more amps. They get burnt, because something draw too much power trough them.

Let's look at some examples:

Imagine, that you create a short between 5V and ground on your Uno. A short means, that a high current can flow, since the resistance is very low. Now you are drawing a high current from your 5V pin to the ground pin. The Arduino's 5V pin is connected to a voltage regulator (for if you use Vin) and over a diode to USB. Both parts are only rated for a maximum current (depending on the version of the board between 200mA and 1A). The high current, that you draw, will flow through one of these parts, depending on your input source. This part will get fried, because a way to high current will flow through it, just because you draw the current.
A strong motor, that needs more current, than the board is rated for, would result in a similar problem like the short circuit. Indeed every device, that needs more current, than the board is rated for, might result in frying the mentioned parts.

But what happens, if you draw more power from the power supply itself, than it is rated for? The power supply electronic is similar to the Arduino board. When you draw too much current from the power supply, some parts of it might get fried and stop working. Thus, you should not try to draw more current from it, than it can provide. Often power supplies have a protection circuit, that will either lower or directly cut the voltage, if too much current is drawn. This is for the safety of the supply and should not be used for current limiting your own application normally.

So, you should always calculate, what current you expect to need, and then take a power supply, that can provide more current than that. You should consider a significant headroom, so that you can add more parts, if you want to extent your project. For example, if I calculate 2A for my project, I would use a power supply in the range of 3A.

Addition:

Above I wrote about constant-voltage devices. There are also constant-current devices, for example LEDs. An LED has a specific constant forward voltage. Under that voltage it will not conduct current. Over that voltage, the current rises exponentially. The voltage over the LED will always stay the same, as it was designed. This is the reason, why you need to add a current limiting resistor to a LED. But in the vast of devices, LEDs (or in fact every diode) is an exception.


It means there is no proper communication between the IDE and your Arduino. The reason can be many things:

RX/TX UART port used
USB port broken
USB cable broken
Arduino broken
USB port drivers not properly installed
Problem inside IDE
...

To troubleshoot you could try:

Disconnect RX/TX jumpers
Try another USB port
Remove other USB devices
Try another USB cable
Try another Arduino
Try another PC/laptop
Reinstall IDE
Reinstall USB drivers


Calculate sensor unique address with a 8 position DIP Switch

Assuming that your switches are on pins 2-9 on an UNO.  Change pins to match what you actually have.

byte addressVal = 0;
for(int i = 2: i<10; i++){
    addressVal <<= 1;
    addressVal += digitalRead(i);
}

This will check each switch and add a 1 to the end of the byte.  On each iteration it shifts the contents of that byte 1 place to the left.  After it reads all the pins you have a byte with a value 0 to 255 depending on the states of the pins.


Trying to connect FT sensor to Arduino Mega using RX TX

The Serial RX and TX pins of an Arduino are not RS-232 compatible without using some type of circuit to give you the proper voltage levels.

**RS-232 logic and voltage levels**
0 (space)   Asserted    +3 to +15 V
1 (mark)    Deasserted  −15 to −3 V

Connecting the RX/TX pins of an Arduino directly to an RS-232 device may fry your Arduino in addition to just not working for communication.  This circuit given below is an example what you'll need.  There are pre-made adapter boards available for a few dollars.


How to program ATmega4809 from Raspbeery GPIO

The ATMega4809 uses UPDI (Unified Programming and Debugging Interface) for programming, not ICSP like the older ATMega328P. You need a UPDI programmer.
There is a project jtag2updi which you can run on an Uno that turns it into a JTAG to UPDI adaptor which is then compatible with avrdude -c jtag2updi ....


I'm not an expert, but I think I found why it is not working.

The main problem is that you are using always the same byte (0, 3 or 9) for debugging, so you are not noticing that it is not sending four bytes, but only one, and the function gets called four times. This is obvious however from the reply on the serial interface (+1 for adding it in the question, good work).

What you can do is to track how many bytes you sent, and send the successive one. After the bytes are all sent you can reset back the state. The code can be something like

//States
#define NO_STATE 0x00
#define GET_BAT_TEMP 0x03

byte sentData;
byte batteryLevel[4]={3,4,5,6};

byte state = NO_STATE;
void setup() {
    Serial.begin(9600);
    pinMode(13, OUTPUT);
    Wire.begin(SLAVE_ADDRESS);
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);
}

void loop() {
  // delay(100); // Useless, let it cycle at its max speed
}

// callback for received data
void receiveData(int byteCount){
    while(Wire.available()) {
        state = Wire.read();
        sentData = 0;
    }
    Serial.print("Got:");
    Serial.println(state);
}

// callback for sending data
void sendData(){
    Serial.println("Sending...");

    switch (state){
        case NO_STATE:
            //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
            Wire.write(0);
            break;
        case GET_BAT_TEMP:
            //send battery temp
            Wire.write(batteryLevel[sentData]);
            if (sentData < 3)
                sentData++;
            else
                //reset state to none
                state=NO_STATE;
            break;
        default:
            Wire.write(9);
            //send back error code
    }
}

I haven't tested it, so forgive any bugs. But I'm sure  you understood the main point.

Just some remarks: the delay is useless (you are not saving energy or other with it, so just remove it); the serial is ok for debugging, but I think you should remove it from the code you will use (not ok to stop the interrupts for such a long time).

And most important: I hope you considered the 5V vs 3.3V voltage problem on the I2C ;)

In any case, I second Look Alterno: good way to ask a question, with all the information needed.

EDIT: as pointed out in the comments, there exist a function to send all the data together. I'm not sure how it behaves in different conditions (e.g. when less bytes are requested), but if you trust the communication the function can be simplified in

// callback for sending data
void sendData(){
    Serial.println("Sending...");

    switch (state){
        case NO_STATE:
            //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
            Wire.write(0);
            break;
        case GET_BAT_TEMP:
            //send battery temp
            Wire.write(batteryLevel, 4);
            state=NO_STATE;
            break;
        default:
            Wire.write(9);
            //send back error code
    }
}

(and the sentData variable becomes useless)


How to send multiple data from PC to arduino

The approach noted in the question – having an identifying character at the front of each number – is a workable approach.  Other approaches include:
•  always sending numbers in pairs, eg 2000,300 would denote A2000 B300.
•  encoding the A or B as part of the number; eg, the range 0-4999 could denote A delays of 0 to 4999, while the range 5000-9999 could denote B delays of 0 to 4999.
•  sending A delays via decimal digits, and B delays via letter-substitutes for digits; eg DAA could encode a B delay of 300.

One of the easiest-to-parse approaches is to have an identifying character at the end of each number, rather than at the front.  This allows your code to pick up digits until a letter appears, and then dispatch based on the letter.  Here's some example code:

// Sketch that accepts numbers and action code via serial input.
// Silently ignores any numbers not followed by a valid action letter.
// Does not test for number overflow.      - jiw 3 Nov 2016

void setup() {
  Serial.begin(115200);         // init serial port
}

unsigned int val=0;
void loop() {
  char inc;
  while (Serial.available()) { // Get characters
    inc = Serial.read();
    if (inc >= '0' && inc <= '9') {
      val = 10*val + (inc-'0');
    } else {
      switch (toupper(inc)) {
      case 'A':
        Serial.print("Case A got ");
        Serial.println(val);
        break;
      case 'B':
        Serial.print("Case B got ");
        Serial.println(val);
        break;
      default :
        ; // handle blanks, returns, etc
      }
      val = 0;  // Set val to zero after any non-digit
    }
  }
}

Edit 2: This edit incorporates some code suggestions from comments into the answer.

If you need to know whether a number for val1 has been specified -- that is, if you handle items like 500B as well as 300,500B -- you can set/test/clear a flag:

...
case ',':
  val1=val; v1flag=1;
  break;
...
case 'B':
  if (!v1flag) val1=val1default;
  Serial.print("B stuff with val and val1");
  v1flag=0;
  break;
...

To retain when the power is off, you can write a recordData() function, that when called will write selected data to EEPROM if the value has changed.  In setup(), load data from where you stored it. For data validation, you can store in the cell after a value v its complement, ~v.  If when you reload data it fails the validation test, use a default value instead, and write it to EEPROM for future use.

The code snippet shown next, from kaisarGreat's 8 May comment, has several problems to be corrected:

case a :
  WATEREQFORN1 = val;
  EEPROM.put(0, WATEREQFORN1);
case b :
  WATEREQFORN2 = val;
  EEPROM.put(1, WATEREQFORN2);
case d :
  DELAY = val;
  EEPROM.put(3, DELAY);

Logic or syntax problem: Missing break statements at  ends of cases.  This error will allow execution to flow from one case into the next.  While there are situations where that's useful, this is not one.

Logic or syntax problem: Unless a, b, ... are declared constants they won't work as case designators.  Perhaps use 'A', 'B', ... instead.

Style problem:  Variable names in all upper case.  Conventionally, C and C++ programmers use all-upper-case names to designate defined constants or macros.  Contravening that convention can lead to confusion if other people use or maintain the code.  Instead of WATEREQFORN1 consider waterEq1.

Allocation problem:  Presumably the WATEREQ... variables are multiple bytes in length.  EEPROM.get() and put() read and write data types with multiple bytes using several consecutive bytes of EEPROM.  For example, if WATEREQFORN1 is a real and takes 4 bytes, it will occupy cells 0, 1, 2, 3 in EEPROM.

The following code snippet fixes some of those problems.

enum { WaterAddr1=0, WaterAddr2=WaterAddr1+sizeof waterEq1, DelayAddr=WaterAddr2+sizeof waterEq2 };
...
case 'A':
  waterEq1 = val;
  EEPROM.put(WaterAddr1, waterEq1);
  break;
case 'B':
  waterEq2 = val;
  EEPROM.put(WaterAddr2, waterEq2);
  break;
case 'D':
  Delay = val;
  EEPROM.put(DelayAddr, Delay);
  break;
  ...


Default value of global variables is not set

This variable is declared volatile which is generally meaning that it can be modified by an Interrupt Service Routine (ISR).

So it is perfectly possible that this ISR gets called before your setup() function gets called and then it may modify this variable.

In C and C++, variables defined as type variable = xxx; are guaranteed to be initialized before any of your code starts to run.

So this means you must look for the root of the problem somewhere else.

Don't forget that it is perfectly possible that some code gets run before setup() is called.

You may try to search for the code that runs before setup(); unfortunately it can be hard to find out this code:

Indeed, in C++, there are a lot of possibilities for code to execute even before the main() function gets called; for instance, declaring an instance of a class as a global variable, will call the class constructor before main().

So you would have to find out all class instances declared as global variables in all source files, and then check the class constructor that gets called for each instance.

Another way could be to check the assembly produced for your program and find all calls occurring be fore main(), but it can be harder if you can't read assembly.


Arduino Uno: Sensor shield powering multiple servos

two things make servos fairly easy to control:

they take a slow pwm input; generating pwm is fairly easy on a mcu;
they are generally not that sensitive to the duration of the off state: I have tried from 5ms to 40ms (the longest) and they are fine with that.

so if you combine the two attributes together, it is easy to control multiple servos with from one timer interrupts.

I wrote a few pages on this recently:
1. driving multiple servos on AVR Timer2: https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-avr-timer2/

driving multiple servos on PIC: using TIMER0 (https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-pic-timer0/) or TIMER1 (https://dannyelectronics.wordpress.com/2017/02/07/driving-multiple-servos-with-pic-timer1/).

The following is a combination of the two: driving 8 servos independently on PORTB with TIMER1 and another 8 servos independently on PORTD with TIMER2.

the user code is quite simple:

//set up servo controller 1
srvo1_init();                           //reset the servo module
srvo1_setpr(1, 1000);                   //for 1ms
srvo1_setpr(2, 1200);                   //for 1.2ms
srvo1_setpr(3, 1400);                   //for 1.4ms
srvo1_setpr(4, 1500);                   //for 1.5ms
srvo1_setpr(5, 1800);                   //for 1.8ms
srvo1_setpr(6, 2000);                   //for 2ms
srvo1_setpr(7, 2500);                   //for 2.5ms
srvo1_setpr(8, 4000);                   //for 4ms

//set up servo controller 2
srvo2_init();                           //reset the servo module
srvo2_setpr(1, 1000);                   //for 1ms
srvo2_setpr(2, 1100);                   //for 1.1ms
srvo2_setpr(3, 1200);                   //for 1.2ms
srvo2_setpr(4, 1300);                   //for 1.3ms
srvo2_setpr(5, 1400);                   //for 1.4ms
srvo2_setpr(6, 1500);                   //for 1.5ms
srvo2_setpr(7, 2000);                   //for 2ms
srvo2_setpr(8, 4000);                   //for 4ms

Once it is set-up, you can just leave it alone and no addition attention is required. You can change the duration of course, or disable / re-enable output on a given channel.

Total CPU drain is about 150K ticks in a second for 16 channel controller.

works on Arduino as well.

edit: if you port the code to TIMER0 (easily done),  you can control 32 servos independently.

and if you combine this code with making timers out of the output compare functionality, you can shrink them all on one timer.


Script stops functioning after calling irsend() function in irlibrary!

Apparently you should be calling irrecv.enableIRIn() after sending, not irrecv.resume(). Sorry for suggesting the wrong thing on IRC before :-)


C++ Namespace/scope problem when trying to attach arduino interrupt

You can't.

Simply because a class member is not the right format of function for attachInterrupt.

You can only use normal functions with attachInterrupt, so the normal method is to have a normal function outside your class which then calls the member function within your class.  How you arrange it so that it knows where your objects are is up to you.

If you have only one object then assign it to a global pointer in your library using the constructor
If you have lots of instances then create a linked list within your class in a static context and add each object to it in the constructor, then iterate through that list when the interrupt fires.


Arduino SD Card open file modes append / overwrite

You only need to open the file with FILE_WRITE and use file.seek(EOF) to go to de end of the file. After that you can write whatever you want that will be appended to the end of the file.

File outputFile = SD.open(LOG_FILE, FILE_WRITE);
outputFile.seek(EOF);
outputFile.println("Appended to the EOF");


I doubt there are any standards for this. The reason is that 'hardware' solutions are very much more flexible than PC solutions (which by default have a keyboard, mouse and monitor) and not much more.

Hardware solutions on the other hand can have any kind of different displayed, touch screen, sensors of all kinds, leds/lights, hardware/mc controlled motors, relays, communication means etc.

The only user interface solutions are probably the libraries which can be used for some hardware, e.g. display driver drivers, led drivers, sensor libraries etc.

Especially to combine multiple hardware items (like on a PC the mouse, keyboard and monitor) gives a user interface 'experience'. Since hardware solutions have many more different hardware options, there is not a clear 'solution' for combining so many different hardware.


There's a new version of the avr-gcc package that's currently available in the updates-testing repo that should fix the problem. You can install/update it by enabling the updates-testing repo, or grabbing the rpm from koji (https://koji.fedoraproject.org/koji/buildinfo?buildID=1013122)


First: Why are you including, declaring and initializing the library's tfmini object, if you then don't use it for reading the sensor?
Your problem will be, that you can only listen to exactly 1 SoftwareSerial interface at a time. If you listen to the first interface and the sensor on the second interface is sending something, you will miss that data.
I suggest, you switch the Uno for a board with more hardware Serial interfaces (which work via hardware, thus can work in parallel). The Arduino Mega for example has a total of 4 hardware Serial interfaces.
Though you might get away with the Uno when working with the external trigger mode. The TFMini library has an example named SingleReading. It sets the SingleScanMode in setup(). Then it issues an external trigger and then reads the sensor. I suggest trying the following: In your code you initiate all 3 TFMini objects with their respective SoftwareSerial object. Then in loop() you go through these 3 items, first calling listen() on the corresponding SoftwareSerial object. Then you issue the external trigger on the corresponding TFMini object and read the data from it. Then you go to the next SoftwareSerial interface and call listen() on it, and so on. The idea is, that with an external trigger you can control, when you will get a valid data frame. I'm not sure, if the sensor will also send some data between the triggers, but that data should just be discarded without any problem.
Note: I cannot test this idea, because I don't have the corresponding hardware. You will have to test that yourself.


If flashing with AVR In System Programing (ISP) the bootloader is not needed. Only the flashing over Serial needs a bootloader.

The ISP erases the flash including the bootloader. To be able to use the serial flashing after ISP, the hex with_bootloader can be used.

I flash AVR over WiFi with esp8266's core AVRISP library and I use the hex with_bootloader to have the option of flashing later over USB.

Your Android app will use the serial flashing utilizing the bootloader. The bootloader doesn't delete itself. So you should use the hex WITHOUT bootloader.


How to shorten this code (because my sensor reads slowly)?

Your slowness is because on every single iteration of loop() you are updating the entirety of the display.  That's bad and wasteful.
You need to do two things:

Only display static information (the labels) once. Do that in setup().
Only display the variable data if it actually changes.

The first is simple: move any static text to setup(). That means things like lcd1.print(F("dscnt="));. It never changes, and the display doesn't "forget" it, so doesn't need constantly reminding.
The second is slightly harder. You need to keep two copies of the data. One that is the data at this moment, and one that is the data that is being displayed. Then you compare one with the other and for any items where they differ display them and update your saved copy.
So something like:
if (d[0] != d_saved[0]) {
    d_saved[0] = d[0];
    lcd.setCursor(8, 0);
    lcd.print(d[0]);
}

You can of course make that easier to program with a loop:
for (uint8_t i = 0; i < 4; i++) {
    if (d[i] != d_saved[i]) {
        d_saved[i] = d[i];
        lcd.setCursor(8, i);
        lcd.print(d[i]);
    }
}

Of course d_saved[4] needs creating in either the global scope or as a local static variable and initialising with some suitable "can never be" values (like -1 or something) so that the first time through it will always be different from the real values and display everything properly.


"Broken Pipe" when uploading to Arduino UNO

As with any communication error, try these:

Disconnect and reconnect the USB cable.
Use a different USB cable.
Press the reset button on the board.
Restart the Arduino IDE.
Make sure you select the right board in Tools ► Board ►, e.g. If you are using the Duemilanove 328, select that instead of Duemilanove 128. The board should say what version it is on the microchip.
Make sure you selected the right port in Tools ► Serial Port ►. One way to figure out which port it is on is by following these steps:

Disconnect the USB cable.
Go to Tools ► Serial Port ► and see which ports are listed (e.g. COM4 COM5 COM14).
Reconnect the USB cable.
Go back to Tools ► Serial Port ►, and see which port appeared that wasn't there before.

In extreme cases, you may need to burn the bootloader.

Answer adapted from here.


What is the frequency of PWM output on Arduino

The PWM signal is generated by timers on the AVR chips. Each timer can generate a PWM signal on two or three different pins. Each pin can have it's own duty cycle, but they share the PWM frequency. You can change the frequency of the PWM by changing the clock source for the timers. By default they use the CPU clock divided by 64, ie. they have their prescaler set to 64 by Arduino initialization code.
  To confuse things more there are two different PWM modes: fast PWM and phase correct PWM. In fast PWM the timer counts to 255, then overflows and starts over from 0 (256 different states). In phase correct PWM the timer counts to 255, then changes direction and counts downwards to zero, changes direction and so on (510 different states).

The Arduino Mega has 5 timers, timer0 - timer4. Because timer0 is also used for the millis and micros functions it uses fast PWM, whereas the other timers are configured for phase correct PWM. This results in different frequencies on different pins:

Pin 4 and 13, controlled by timer0:
16 Mhz / 64 / 256 = 976.56 Hz
Other PWM pins, controlled by timer1-4:
16 Mhz / 64 / 510 = 490.20 Hz

The calculation is: Clock / Prescaler / PWM mode number of states

The situation is the same for all other Arduino boards I know of, except they have less timers that connect to different pins.

You can change the PWM frequency by changing the timer prescaler. See this page: http://playground.arduino.cc/Main/TimerPWMCheatsheet

It is also possible to make the timers count to a different value than 255. On the 8 bit timers you will loose an output pin, but on the 16 bit timers you can use the Input Capture Register to define a TOP value. The input capture functionality is a feature rarely used in the Arduino community so you likely won't miss it.

The Arduino libraries only allow you to use 8 bit resolution, even on the 16 bit timers. If you want the higher resolution, you will have to write your own analogWrite, or use a library made for the purpose.
On the Arduino Mega timer0 and timer2 are 8 bit, while the rest are 16 bit.

By changing the mode of the 16 bit timers to make use of the full resolution, in combination with changing the prescaler and the TOP value, you can achieve a very wide range of PWM frequencies.

The maximum frequency you can achieve is clock / 4, by setting the prescaler to 1 and TOP to 3 in fast PWM mode - a lower value isn't allowed. This will give you a 4 MHz PWM with 2 bit resolution. It can be on 0%, 25%, 50%, or 75% of the time. A higher TOP value will give you a higher resolution at a lower frequency.

For a longer explanation read this article or refer to the datasheet.

Changing the prescaler, PWM mode, or TOP value for timer0 will mess with millis() and micros().


How do I make a Servo Stop if it Hits Resistance?

You could either:

Use a limit-switch to sense that the servo has completed it move. If it doesn't complete it a reasonable time, return it to its original position. Or,
Measure the motor current by putting a low value resistor inline with the ground side of the motor's power supply. With one of the A/D pins, measure the voltage on the motor side of the resistor, which increases with motor current. You'll need to have figured out how much current the motor draws when operating normally. If the motor stalls, your controller could sense that by seeing that current increase. Pick a value (try 150%, for example) of over-current as an indicator that the motor is stalled, and return it to its original position.

The first way is easier to implement but possibly lets the motor stall while you wait for the expected move time to expire. The second way lets you detect stalling and take action immediately.


SMS Receiving problem - Arduino Uno and SIM900A GSM Module

Instead of using At commands use the GSM library of Arduino it easier to understand and implement.
the code to recieve SMS

    #include <GSM.h>

    // PIN Number for the SIM
    #define PINNUMBER "" //sim pin incase the sim is kept locked

    // initialize the library instances
    GSM gsmAccess;
    GSM_SMS sms;

    // Array to hold the number a SMS is retreived from
    char senderNumber[20];

    void setup() {
      // initialize serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.println("SMS Messages Receiver");

      // connection state
      boolean notConnected = true;

      // Start GSM connection
      while (notConnected) {
        if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
          notConnected = false;
        } else {
          Serial.println("Not connected");
          delay(1000);
        }
      }

      Serial.println("GSM initialized");
      Serial.println("Waiting for messages");
    }

    void loop() {
      char c;

      // If there are any SMSs available()
      if (sms.available()) {
        Serial.println("Message received from:");

        // Get remote number
        sms.remoteNumber(senderNumber, 20);
        Serial.println(senderNumber);

        // An example of message disposal
        // Any messages starting with # should be discarded
        if (sms.peek() == '#') {
          Serial.println("Discarded SMS");
          sms.flush();
        }

        // Read message bytes and print them
        while (c = sms.read()) {
          Serial.print(c);
        }

        Serial.println("\nEND OF MESSAGE");

        // Delete message from modem memory
        sms.flush();
        Serial.println("MESSAGE DELETED");
      }

      delay(1000);

    }


What component can I use with an Arduino to measure the capacitance of objects?

You can use the Arduino to measure capacitance using an RCtime approach (Google that for code examples), which requires that you have a known resistance for reference.  You should also have some known capacitors to make sure you have everything calibrated properly.
But it sounds like what you really want is more like "dielectric constant".  You can use
the same setup to measure that, by creating a standard reference capacitor consisting of two conductive plates of known area that you sandwich your unknown dielectric material between.  The value of capacitance is related to the surface area of the plates and to how close together they are... closer gives more capacitance.  Look up the formulas for this.
This is a standard Physics 101 experiment.
The problem is that unless you get very thin sheets of the material, you are not going to get a very high capacitance, which will make it hard to measure.  This is not going to be a trivial project.


In the 1 sensor program all the delays added together account for
62ms between samples.
In the 3 sensor program the sample code contains delays which likely
exceed 12ms (delays plus code execution).  So each sensor will not be
sampled faster than once every 36ms.
After you removed 1 sensor from the 3 sensor program, you increased
the sampling rate to about every 23ms.
It is likely a minimum amount of time is necessary between samples in
order for the HC-SR04 to recover.


Can Atmel Studio 6 Simulator simulate SPI?

No Atmel Studio cannot simulate SPI.

The fact that you are using SPI makes me think that you are using the MAX7456 IC or even the SparkFun On Screen Display Breakout which uses this same IC.

You can generate composite video just by using a few resistors and an Arduino.

I have found a number of sites on Google who have used the Arduino to output PAL composite video to display the Pong game on an old TV.

http://searle.hostei.com/grant/AVRPong/index.html
http://www.makeuseof.com/tag/how-to-recreate-the-classic-pong-game-using-arduino/
http://www.instructables.com/id/2-player-Pong-using-Arduino/
http://forum.arduino.cc/index.php?topic=8708.0
http://apcmag.com/arduino-project-7-build-a-retro-gamebox.htm/
http://electronics.divinechildhighschool.org/Home/electronics-spring-2012-1/arduino-pong


error: espcomm_upload_mem failed when uploading a sketch

The ESP8266 has two "modes". "Run" mode and "Flash" mode.  In "Run" mode the firmware installed onto the ESP8266 executes. The default firmware is the AT firmware that allows you to control the device with AT commands through serial.

Note that the site you link to has erroneous information about CH_PD that should be talking about GPIO0.

In "Flash" mode you get to upload new firmware (AKA a "sketch") to make the device do something different.

The basic programming sequence is:

Switch the device to Flash mode (connect GPIO0 to GND)
Upload the sketch using the IDE
Switch the device to Run mode (connect GPIO0 to 3.3V).

Because of these extra steps many people choose to invest in a small USB interface board designed specifically for programming the ESP8266 to make their life easier. These generally have a switch on them to set whether GPIO0 is connected to GND or 3.3V.


can I give the 9v input power for arduino mega 2560 using vin pin?

Yes!

  The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may become unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

  The power pins are as follows:
  - Vin. The input voltage to the board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

https://www.arduino.cc/en/Main/ArduinoBoardMega2560

Vin is the same as the external positive power input.


Try this:

void setup ()
{
  pinMode(0,OUTPUT); //IB1
  pinMode(1,OUTPUT); //IA1
//  pinMode(2,OUTPUT); //IB2
//  pinMode(3,OUTPUT); //IA2
  pinMode(4,OUTPUT); //RGB red
  pinMode(5,OUTPUT); //RGB green
  pinMode(6,OUTPUT); //RGB blue
  boolean motorOn = false;
}

void loop ()
{
  digitalWrite(0,motorOn);
  if(motorOn) {
    digitalWrite(4,HIGH);  // red on
    digitalWrite(5,LOW);   // green off
    digitalWrite(6,LOW);   // blue off
  }
    digitalWrite(4,LOW);   // red off
    digitalWrite(5,HIGH);  // green on
    digitalWrite(6,LOW);   // blue off
  }
  delay(1000);             // wait
  motorOn = !motorOn;      // toggle the status of the motor.
}

The code above has the disadvantage that the on-time is the same as the off-time. We can make the code more flexible and a little more like your original by doing the LED related code in a subroutine:

void setup ()
{
  pinMode(0,OUTPUT);   //IB1
  pinMode(1,OUTPUT);   //IA1
//  pinMode(2,OUTPUT); //IB2
//  pinMode(3,OUTPUT); //IA2
  pinMode(4,OUTPUT);   //RGB red
  pinMode(5,OUTPUT);   //RGB green
  pinMode(6,OUTPUT);   //RGB blue
  boolean motorOn = false;
}

void loop ()
{
  motorOn = false;
  digitalWrite(0,motorOn);
  updateLEDs();            // update the LED status
  delay(1000);             // wait
  motorOn = true;          // toggle the status of the motor.
  digitalWrite(0,motorOn);
  updateLEDs();            // update the LED status
  delay(750);              // wait a different time
}

void updateLEDs(){
  // This routine updates the LEDs based on status of motorOn.
  if(motorOn) {
    digitalWrite(4,HIGH);  // red on
    digitalWrite(5,LOW);   // green off
    digitalWrite(6,LOW);   // blue off
  }
    digitalWrite(4,LOW);   // red off
    digitalWrite(5,HIGH);  // green on
    digitalWrite(6,LOW);   // blue off
  }
}


OK let me cry till morning...

i was having this issue during day, but the solution was sooo easy

i need to pay attention more ...

  i2c_start(addr | R/W-bit)
  Initiates a transfer to the slave device with the (8-bit) I2C address addr.

what i was trying is to push 7 bit address.

i hope this might help some others.

Thank you for help.


How to write a function to return matrix?

You cannot return an array from a function. There are several
alternatives, though. One of them is to allocate the memory for the
array within the function, as suggested by user2912328's answer. I would
not recommend this approach though, for the reasons already stated in
that answer.

For an overview of the other possible options, see this response to the
question “Returning an int array from a function”.

Now, your problem is slightly different, as you have a 2D array.
The C/C++ syntax for dealing with those is tricky, but here we go.

If you opt for the “static array” solution (make sure you understand the
implications), you could write:

float (*matrix(float phi))[2]
{
    static float R[2][2];
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
    return R;
}

and you would use it like this:

float (*M)[2] = matrix(angle);

If you instead let the caller manage the allocation, then

float (*matrix(float phi, float (*R)[2]))[2]
{
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
    return R;
}

Or maybe forgo the return value to make the syntax simpler:

void matrix(float phi, float (*R)[2])
{
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
}

and you could use it like:

float M[2][2];
matrix(angle, M);

The “array in a struct” solution is more straightforward.

If the syntax for dealing with 2D arrays bothers you (which would be
understandable), you can instead use arrays of pointers to 1D arrays.
This are easier to deal with but trickier to allocate. That approach
could warrant another answer...

Edit: One common way to simplify a convoluted array syntax is to use
typedefs. As an identifier for a 2x2 array decays to a pointer to an
array of 2 floats, you can name that type:

typedef float (*pmatrix)[2];  // pointer to an array of 2 floats

Then, instead of

float (*matrix(float phi))[2] { ... }
...
float (*M)[2] = matrix(angle);

you would write

pmatrix matrix(float phi) { ... }
...
pmatrix M = matrix(angle);


Yes, your relays are hooked up the right way. I'm using the same modukes to drive a fan 75W and a HPS-Lamp with 400W. As long as you drive the heater with AC voltage, you're in the specs (different than stated in previous comments).
But the humidity sensor (a DHT11/22) isn't, as far as I remember its pinout...
And could you explain what the Transistor is for (if it is a transistor, I'm curious what you want to achieve with this wiring)?


Switch between ntc resistor sensors time based for other device

It sounds like what you want is a small SPDT relay (maybe a reed relay).

simulate this circuit – Schematic created using CircuitLab

Turn on the GPIO, the MOSFET (or NPN BJT if you choose - increase R1 if you do) turns on, which energises the relay. The relay then switches between the NTC and the resistor being connected into the circuit.


esp_partition_get_sha256() mismatches PHP's hash() function in HTTPUpdate

Your problem stems from a misunderstanding of what the functions are doing.

Your MD5 hashes are the hash of the binary file itself. And so they match.

Your PHP SHA256 is the hash of the binary file (like the MD5), but the ESP's SHA256 is not.

The file itself contains an SHA256 hash of the content of the file, not the whole file.  The function esp_partition_get_sha256 merely returns that SHA256 hash.

According to the SDK documentation:

  For apps with SHA-256 appended to the app image, the result is the appended SHA-256 value for the app image content. The hash is verified before returning, if app content is invalid then the function returns ESP_ERR_IMAGE_INVALID. For apps without SHA-256 appended to the image, the result is the SHA-256 of all bytes in the app image. For other partition types, the result is the SHA-256 of the entire partition.

If you were to take the binary file and somehow strip off the extra sha256 information and then perform a hash of the results you should (theoretically) get the same hash, which would be the same has as is contained within the file itself.


SIM900a Mini Modem, IMEI 0, help with TX RX pins

Finally I found solution to this problem:
My Pins connections were wrong, it should not be: 0 and 1 it should be 2 & 3:
2 - RX Arduino
3 - TX Arduino

also SoftwareSerial.h is not working with SIM900A
Pins:
All connections should be like this:
SIM900A - Arduino
=================
VCC     - VDC (+5V)
GND     - GND
5VR     - Connect to Arduino TX (Pin 3)
5VT     - Connect to Arduino RX (Pin 2)

As discussed here.
Very important:
Any program with header/library: #include <SoftwareSerial.h> is not working but #include <GSM.h> is working fine. As SoftwareSerial.h only work with GSM Shield and SIM900A isn't a shield.
Program/Sketch to Upload:
/*
SMS sender

created 25 Feb 2012
Originally written by Tom Igoe
But this is modified version
*/

// Include the GSM library
#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess;
GSM_SMS sms;

void setup(){
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial){
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.println("SMS Messages Sender");
// connection state
boolean notConnected = true;

// Start SIM900A GSM

while (notConnected){
    Serial.println("Status 1: Please wait a while, If it taking lot of time, \nmeans you have wrong pin connections.");
    // If your SIM has PIN, pass it as a parameter of begin() in quotes
    if (gsmAccess.begin(PINNUMBER) == GSM_READY){
    Serial.println("Status 2: GSM is ready.");
    notConnected = false;
}else{
    Serial.println("Status 3: Not connected");
    delay(1000);
  }
}
    Serial.println("Status 4: GSM initialized. " );

    // calling function to send message
    sendMessage();
}

void loop(){
    // empty loop
}

// method to send message to specific number just once.
void sendMessage(){
    Serial.print("Message is sending...: ");
    // send the message
    sms.beginSMS("03XXXXXXX "); // Replace XXXXXXX with your mobile number.
    sms.print("This is just some message"); // Message content, replace with your's.
    sms.endSMS();
    Serial.println("COMPLETE!\n");
    Serial.println("Message Sent...!\n");
}

Bam, It is working, and it successfully can send message.
Things to remember:

As everywhere being said you need to supply external power supply to SIM900A   it requires 5 Volts and 2 Amphs.

Connect GND of SIM900A to Arduino GND.

Connect VCC+ (above photo connection 2) to 5V pin of Arduino.

One Problem:
When I upload sketch of:

Example > GSM > TestModem:

to Arduino, I got this output from Serial Monitor:

Starting modem test...ERROR, no modem answer.
Checking IMEI...Modem's IMEI: 0
Reseting Modem... Modem is functioning properly: IMEI: 0

I cannot get IMEI from SIM900A but I can send message.