ESP8266 - 12F High consumption in led blink (with pictures)

The SDK library of the ESP8266 remembers on flash memory the mode, SSID and password of the last WiFi network it connected. At start or by enabling STA mode it tries to connect to that network. The SDK library is always part of the compiled sketch for the esp8266.

The esp8266 WiFi library has some functions to control this:

WiFi.setAutoConnect(false)
WiFi.disconnect(true);
WiFi.persistent(false)


Force compiler to execute instructions sequentially?

You can use the optimize function attribute to change the compiler optimization level for an individual function. That's the closest you'll get.

  optimize

  The optimize attribute is used to specify that a function is to be compiled with different optimization options than specified on the command line. Arguments can either be numbers or strings. Numbers are assumed to be an optimization level. Strings that begin with O are assumed to be an optimization option, while other options are assumed to be used with a -f prefix. You can also use the #pragma GCC optimize pragma to set the optimization options that affect more than one function. See Function Specific Option Pragmas, for details about the #pragma GCC optimize pragma.

  This attribute should be used for debugging purposes only. It is not suitable in production code.

E.g.,:

void __attribute__((optimize("O0"))) myFunction() {
    // ...
}


Can't make ultrasonic sensor work with motor controller

Pin numbers 0 and 1 are reserved for the Serial monitor which you're using on the board.
The function int mdistance() should return an integer.
You also didn't seem to set the motor pins as OUTPUT.


Memory usage: #define vs. static const for uint8_t

You'll find no noticeable difference memory-wise between the two.

The only real difference is that the const method also imposes a type to the value, which can be useful for function overloading or mathematical operations.


Powering 3.3V Arduino and 12V peripherals from single 12V power supply?

@Majenko remarked:

Put 12V on the IN, connect the OUT to a volt meter, twiddle the knob till it reads 5V. Disconnect the volt meter. Connect it to the VIN of your photon.

@loopforever added:

For the 3.3V Arduino (Photon) current draw will not exceed 500mA. For the 4x 12V peripherals, if all were in an "alarm" state simultaneously, current draw will not exceed 110mA.

@Dampmaskin added:

Dropping 8.7V at 500mA wastes 4.35W so OK you're right, that is inefficient. A buck converter is probably the best approach then

@SDsolar added:

If you use a screw-terminal barrier block you can have both 12V and your lower voltages available at the same time


Not sure I'm understanding pipes for NRF24

I don't see any reason for doing this.

Multiple devices sending data at the same time will cause collisions irrespective of the pipe-nr they are using.

Pipe is also a not very accurate name for what it actually is. It's just a number, that the receiving NRF can check, to see if the packet that was received was intended for it. Kind of like a MAC address on a network.

You can have two unique reading pipes. Then there are 4 more pipes you can use, that are identical to the second pipe, except for the last byte.

The first pipe is used to specify the pipe you are sending through. So if you send to different pipes, this pipe isn't ideal for listening, as you'd have to change it back every time you send a packet. Possibly loosing a packet that was send in between.

If you want more information, i'd suggest reading the datasheet, and read the documentation of one of the libraries. I personally checked the sourcecode of the library a lot while at the same time referencing the datasheet, to really understand what it's doing.


How to select which resistor is required for my curcuit to reduce voltage

A resistor can only drop a certain voltage when there is a certain current - as you know from Ohm's Law.  If you have resistance R and current I the voltage dropped is R×I.

So if the current changes the voltage changes - and if the voltage changes the current changes.

So what do we do? Well, we have one known fixed value, and that is the 5V from the GPIO pin. And since that is fixed (at least when HIGH) we could add a fixed resistance to it to give a fixed current, right?

So let's do that. Pick a random value. Experience teaches you that certain values are better than others, but the actual value doesn't matter too much, as long as:

It's not so small that too much current flows out of the GPIO pin, thus damaging it, and
It doesn't create too high an output impedance, which we will come on to later.

10kΩ is a good figure to start with. Not only does it keep the current low enough, but it's pretty much guaranteed that you'll have one in your bits box somewhere. And we connect it to the GPIO like this (we completely ignore the ESP8266 for the moment):

simulate this circuit – Schematic created using CircuitLab

When TX is HIGH it's at 5V. It's connected directly across a 10kΩ resistor, so therefore we can use Ohm's Law to calculate the current - I=V÷R = 5 ÷ 10,000 = 0.0005, or 0.5mA. (Another useful thing with 10kΩ resistors is it makes calculations nice and easy).

Now, what if we were to split that resistor in half, so it was two 5kΩ resistors in series? The circuit would look like this:

simulate this circuit

Resistors in series add together, so those two 5kΩ resistors are the same as one 10kΩ resistor. We know that 0.5mA flows through 10kΩ at 5V, so the same must run through 5+5kΩ at 5V. But now we have two fixed value resistors. Because of that we can now apply Ohm's Law to each one to find the voltage drop across it.

So with 0.5mA flowing through a 5kΩ resistor we get V=I×R = 0.0005 × 5000 = 2.5V.  That's 2.5V across R1 and 2.5V across R2, since they are both the same. That's exactly 50% of the 5V across each one. At the point in the middle, point "A" on the schematic, you can see that the voltage has been cut in half. Once the current has gone through one resistor the voltage has halved (dropped by 2.5V), and when it goes through the other resistor it drops the rest to 0V, which is the other 2.5V.

If we were then to connect something to point A it would see a logic signal of 0V (LOW) and 2.5V (HIGH) from our 0V (LOW) and 5V (HIGH) signal.

But 2.5V is too low for the ESP8266 to read. Well, the answer is simple. We see that if we use two resistors we divide the voltage into two. The same applies for dividing it into three. For instance:

simulate this circuit

The sum is 10kΩ (well, 9.9kΩ but we'll call it 10kΩ for simplicity - a third each resistor, 3333.33Ω). 0.5mA through 3.3kΩ would be 0.0005 × 3333 = 1.66V. Funnily enough, 5 ÷ 3 = 1.66, so we have proved that it splits it into a third. That means at point A 1.66V of our 5V has been dropped (across R1), so 5V is now (5-1.66) 3.33V. Perfect for the ESP8266. Incidentally, point B would be 1.66V (3.33 - 1.66).

So now we have three resistors and the result we desire. However it's a little messy still. Remember that resistors in series add together? So why not add R2 and R3 together into a single resistor? That would be 6.6kΩ. Now I don't know of a 6.6kΩ resistor that's easily available, but 6.8kΩ ones are, though chances are you may not have one. If you did then a 3.3kΩ and a 6.8kΩ would net us near enough 3.3V to be usable.

But as I say you may not have one. So you pick resistor values that you do have. For instance you could use a 2.2kΩ and a 4.7kΩ, or a 10kΩ and a 22kΩ - anything that gives a roughly 1:2 ratio of value (the "upper" R1 resistor about half the value of the lower "R2" resistor).

Now - we get onto that mysterious phrase I mentioned earlier: Output Impedance. You recall we calculated the current that flows through the resistors - 0.5mA. The higher the value of resistors we use the lower the current. Well, that current not only flows through the resistors - a small amount also heads off into the ESP8266. The more that the ESP8266 wants for its RX pin the less there will be available for the R2 resistor. The result? Less current through the resistor = less voltage dropped across it.

The current drawn by the pin attached to point A on our circuit affects the voltage dropped across the resistors.

Too much current drawn and the voltage at point A will droop. Less will be dropped across the (current starved) R2, which means more must be dropped across R1. So point A is now a lower voltage. If that gets too low (too much current is drawn) then the RX pin can't read it properly.

Increasing the resistances decreases the current, but also decreasing the resistances increases the current. If the current is increased then the fraction of the current needed by the RX pin becomes reduced compared to what is available, so the output voltage drops less.

This output impedance, in case you're interested, is measured in Ohms, and is the same as the value of the two resistors in parallel - so (R1×R2)÷(R1+R2).

For instance, I tried connecting an ESP8266 the other day using 3 10kΩ resistors - R1 = 10K, R2 = 20K. It didn't work. You'd expect it to, given the ratios involved, however the output impedance (6.66kΩ) was too high for the ESP8266 I was using. Replacing them for 1kΩ resistors, so it was 666Ω output impedance, made it work straight away.

You can understand it easier if you think of the ESP8266 as just another resistor (it's actually more complex than that - it's also like a capacitor, so it forms a low pass filter which limits the frequency of, and deforms the shape of, the incoming digital waveform). For example:

simulate this circuit

I have deliberately shown the ESP8266 as a lower resistance that it would really be (you can expect MΩ) so as to illustrate the problem clearer.

Your R2 now has R(esp) in parallel with it. So the nice clean 20kΩ is now actually (20,000 × 100,000) ÷ (20,000 + 100,000) = 16.66kΩ. That gives us a total of 26.66kΩ, and at 5V that means a current of 0.188mA. Through the 10kΩ resistor we end up with (10,000 * 0.000188) 1.875V dropped. Take that from 5V and you can see that the ESP8266 would only be getting 3.125V.

By reducing the resistors in our network the difference that R(esp) makes to R2 reduces. For instance, reducing it to 1kΩ + 2kΩ gives us an R2 total of (2,000 * 100,000) ÷ (2,000 + 100,000) = 1.96kΩ - hardly any different from the 2kΩ we started with, so the voltage difference will be minimal (3.31 as opposed to the ideal 3.33).

The simple formula for calculating the output voltage from an input voltage and pair of resistors, so you don't have to go long-hand through Ohm's Law every time (though it is useful for understanding exactly what is happening) is:

Vout = R2 ÷ (R1 + R2) × Vin

I can never remember it, though, and usually use an online voltage divider calculator.


Connecting Load combinator to HX711 then to Arduino

To be able to wire load sensors up you first need to understand how they work and what the wires on them actually mean. There are no standards as regards colour coding of the wires.

So step one is to find out the colour coding of your load cells. Assuming they are "normal" cheap 3-wire ones, internally they look like:

simulate this circuit – Schematic created using CircuitLab

You need to identify those wires on your cells.  We'll call them +, C and - (in that order) from now on.

The idea is that you provide power between + and - and a varying voltage comes out of C depending on the load applied. More load means a lower voltage, since R1 and R2 form a simple potential divider.

However that's not enough to get good results - the voltage differences are too small. So they are usually used as part of a Wheatstone Bridge. This allows a much smaller voltage variance to be detected.

The Wheatstone Bridge is created by the combinator board. It does it by combining the individual parts of separate cells together to form just two load cells along with the static resistances.  This is the form the Wheatstone Bridge create takes:

simulate this circuit

I have boxed in each load cell so you can see how two "variable" legs combine into a single variable resistance, and two "static" legs combine into a single static resistance.

Now you can see how you could test the combinator to make sure it's giving proper results. Apply a voltage between E+ and E- (say 5V) and measure the voltage between A+ and A-. Apply pressure to the load cells (all of them at once) and observe a change in the voltage between A+ and A-.

Assuming that is showing good results (the voltage change will be quite small, so set your DMM to its most sensitive setting), your next point of call is the connection to the Arduino itself.

The HX711 uses a digital serial protocol. Sparkfun has software that bit-bangs that protocol over any pair of IO pins you choose. There is nothing special about which pins are chosen - any two can be used. So as long as you have +5V, GND and the two data pins connected up to the Arduino there's not much that can go wrong.

So that then leaves the software.  The biggest mistake people often make is to not tell the software which pins are being used for the serial communication. Or telling it the wrong pins - getting the clock and data pins mixed up, for instance.  This would be the first port of call for checking the software. Make sure you have the right pins specified.  Quite how you do that without seeing your software I can't say, but Sparkfun have some example software (scroll down to the bottom of the page) which just uses a pair of #define macros to specify the pins.


(noob) 2 servos for robot (head & chest) movement at different speeds at once

Heres a little sketch you can try.  It uses timing to accomplish the different servo speeds.  It won't give you the exact servo travel each loop but it sounds like you might not mind if it randomly is off by a few degrees each loop.
#include <Servo.h>
Servo servo1;
Servo servo2;
int i = 0;
void setup() {
  Serial.begin(9600);
  servo1.attach(8);
  servo2.attach(9);
}

int sweep_time = 3500; // 70 * 50ms = 3500

int head_degrees = 75; // sweep degrees for the head to move
int body_degrees = 65; // sweep degrees for the body to move

int millis_per_head_move = sweep_time / head_degrees;
int millis_per_body_move = sweep_time / body_degrees;

void loop() {
  int i = 0; int j = 0;
  unsigned long now_millis = 0;
  unsigned long start_sweep = millis(); // mark the time when we start the first sweep

  while ( millis() - start_sweep < sweep_time ) {  // keep moving first sweep until sweep time has elapsed
    now_millis = millis() - start_sweep;
    if (now_millis % millis_per_head_move == 0 ) servo1.write(i++);
    if (now_millis % millis_per_body_move == 0 ) servo2.write(j++);
    delay(1);
  }
  Serial.print(i); Serial.print(" "); Serial.println(j);

  start_sweep = millis();  // mark the time when we start the second/back sweep
  while ( millis() - start_sweep < sweep_time ) {  // keep moving second sweep until sweep time has elapsed
    now_millis = millis() - start_sweep;
    if (now_millis % millis_per_head_move == 0) servo1.write(i--);
    if (now_millis % millis_per_body_move == 0) servo2.write(j--);
    delay(1);
  }
  Serial.print(i); Serial.print(" "); Serial.println(j);
}


I2C TinyWireS SEND: How to convert unsigned long to uint8_t array?

This might not be politically correct code, but it is pretty simple to just cast a pointer to uint8_t like this:

long data = 5;
uint8_t *rx = (uint8_t*) &data;

You can still use array subscripts even though its a pointer, and you can pass it to a function like an array. Just don't go past rx[3].

Alternately, you could also make a union like this:

union{ long data; uint8_t bytes[4]; } convert;
convert.data = 5;

And then use convert.bytes as your array to send.


How do you balance an Arduino quadcopter using calculated gyro values?

That was happening with me too. Check if the weight distribution of the drone is perfect. Lets say if the battery is placed a little more to one side of the frame than the other side, your drone will try to hover from the other side.
The center of gravity should be taken care of when the drone is not balancing properly.


The code is working properly. You have mixed up your error messages. The code should be:

#if defined(TEST)
  #error "DEFINED"
#else
  #error "NOT DEFINED"
#endif

UPDATE: The question was edited after the time of this answer to correct the mixed up error messages.


Digispark ATtiny 85 - not recognised as HID device

After five seconds, which is when the bootloader should switch to running your code, how does it show up in the list of usb devices (lsusb in Linux, Device Manager in Windows, etc.)

The original Digispark was a bit temperamental when plugged into USB 3 ports. If you are plugging it into one, try using a usb2 hub and plugging it into the hub instead.

Also, did you get this from Digistump, or is it a knock-off?


Does a pulldown resistor use less battery power than a pullup resistor?

The input current does not depend on the pin level. Have a look at this discussion from avrfreaks. The input impedance of a digital pin is extremely high. The leakage current of the Atmega328P (here as example chip) is mentioned to be 1uA for both pin states. So this current is both unavoidable and neglectable from a normal view.

But the input impedance of a digital input pin is not only dependent on this leakage current. There is also a capacitance, which will lower the impedance for higher frequencies. So, if you drive the input with higher frequencies, the input will draw more current. But you only have a switch connected to it, which is very very low frequency.

So it doesn't matter, if you pullup or pulldown. The main current consumption will result from the moments, where the switch is activated, since then a current flows through the pullup/pulldown resistor to ground.

  Tangentially, should there be a resistor on the connection to Vcc as well?

No need for a resistor there. The input impedance of the pin is already high enough and you don't want to create a voltage divider with your pulldown resistor (which would change the voltage levels at the pin).


Send Email through Cayenne serial connection

No, the Arduino cannot send emails directly through serial. The communication channel you have set up is a direct connection between the Arduino and Cayenne. It cannot be used for anything else other than communicating with Cayenne.

However that doesn't mean you can't try and see if there is some way of making Cayenne send emails for you. Having never used Cayenne I cannot comment on this aspect. You would be better off consulting directly with Cayenne and their users through their forums.


I had the same problem with using the SD reader with a SPI SRAM. It turns out that the very cheap SD reader cards do not like multiple SPI components on the same port. Since the Arduino has only one SPI, the only thing that worked was to use a SD data logger card.

To add a tristate solution by using two resistors on the MISO line also did not work in my case.

See my post for the post I created regarding this probably similar problem.


Detecting Ultrasonic sensor malfunction within the arduino sketch

First of all, this question is hard to answer because you don't provided a name of ultrasonic sensor that you are using. Also as @Majenko pointed out, the key here is to determine the state that you think sensor is not working correctly.

But if assume that you're using standard trig/echo ultrasonic sensor (HC-SR04 or similar) interface - the only possible solution here is to monitor the output(echo) signal of the sensor. Broken sensor will not respond on trigger pulses, so you'll not get the echo pulses. However, these sensors also do not send a signal if the object is out of range of the sensor.

Thus, it is possible to determine the breakdown by monitoring the output signal from the sensor only if you know that the object will always be in range. Otherwise - you can not determine for certain because of what you did not receive a signal, whether it is a sensor failure, or the object is too far from the sensor.


Please provide more information about the power module, or at least a link to it.

But you could supply 12v directly to the Arduino's DC-In barrel-jack. It's not ideal; the Arduino's regulator is likely to get warm, but it would work. This module looks like it regulates its input down to 5v or 3.3v (jumper-selectable). If that is so, then its 5v output would be just right for the Arduino's 5v-In pin. Just make sure your the motors and the Arduino are each directly connected to whatever supply(s) you use. What you need to avoid is trying to power the motors through the Arduino. Your first photo has it right.

Update:

After reading about the supply (using your link), I see that its output is limited to 700ma. Some of that will have to go to power the Arduino (you can use the power supply's USB port for that), leaving a little less for the motors. That will be marginal for one motor and insufficient if the motor is stalled or moving more than a trivial load. It won't be sufficient for more than one motor at a time without scheduling them to prevent simultaneous starts.

You haven't described your motors, so I looked up the Tower-Pro SG-90 hobby servos, one of the simplest and least expensive of the hobby servos. I found a very similar looking one (maybe a clone?) described as being similar to the Tower-Pro, the only one for which I could find current specs. At 5 volts, it draws 100mA with no load and 700ma when stalled. With a stalled motor, the output voltage would likely drop, possibly stopping and resetting the Arduino.

So bottom line is, this supply is marginal, even for one hobby servo in a mechanism that won't stall it. With a larger motor or a heavier load, I don't think it will do the job.


Read Audio Data in Real-time over 3.5mm Stereo Cable

The middle path

Build the simple op-amp (or whatever) 70s-era color organ, but without all the LEDs. Then basically feed the organ's LED-driving lines into the Arduino's ADCs. Sampling that pre-processed/summarized data, you can define a wide variety of RGB interactions without complicated math or an EE background. The timing requirements will be well-within the Arduino's reach, unlike computing FFTs or other "difficult" processes. Besides, old/new hybrids are cool!


You do not need the IP address of the server. You connect with the name of the server and DNS will resolve it to IP address. See the WiFiClient example of the ESP8266WiFi library


Use this:

byte x;
if (Serial.available() > 0) {
  x = Serial.read();
  }

This doesn't block, because you only read when there is something available in the input buffer.

Now, if you want to read an integer with time-out the serial input, this is a short demo:

#define TIME_OUT 10000L
void setup()
{
    Serial.begin(9600);

    while(!Serial);

    Serial.println();

    Serial.println("Input an int (waiting for 60 seconds");
}

void loop()
{
    static unsigned long timeLastInput = 0;
    unsigned long now = millis();
    static char buffer[10];
    static int index = 0;
    int value;

    if(Serial.available() > 0) {
        char x = Serial.read();
        timeLastInput = now;

        if(isDigit(x)) {
            buffer[index++] = x;
        } else {
            if(index > 0) {
                buffer[index] = 0;
                value = atoi(buffer);
                Serial.print("Integer=");
                Serial.println(value);
                index = 0;
            }
        }
    }

    if(now - timeLastInput > TIME_OUT) {
        Serial.println("Time out");
        index = 0;
        timeLastInput = now;
    }
}

It works by reading all digits into buffer. A non digit input signal the end of the integer. We use atoi to convert the integer ascii representation in his binary value. The result you wants is stored in the value variable.

Note that we read only one char at the time in each loop pass.

And this how the output looks:

And remember: code doesn't manage any error condition; is up to you.


How to connect the INT pin of a MPU 6050?

Possible problem: pin interference

  But as soon as I connect INT to anything (pins 0 through 3), the
  sketches do not find the MPU6050 any more. (They report ""MPU6050
  connection failed").

  Is my wiring off, or is my chip defective, and even more important,
  how could I figure that out on my own in the future? =)

If I'm reading the Arduino Leonardo schematic correctly,
Arduino D0 is Rx, Arduino D1 is Tx,
Arduino D2 is the I2C_SDA, and Arduino D3 is the I2C_SCL.

You're already using the I2C_SDA and I2C_SCL as bidirectional I2C communication;
connecting some other output pin (such as the MPU6050 INT pin) to either of those pins is going to disrupt that communication and then things won't work.

On most Arduinos, Serial.println() and Serial.read() and the reprogramming process use the Rx and Tx pins.
Perhaps connecting the MPU6050 INT pin to either of those pins also causes some sort of problem leading to things that don't work.
(Although the Arduino Leonardo actually uses its USB_D- and USB_D+ pins for both Serial.println() and reprogramming, so maybe it isn't really a problem for the Leonardo?).
I would avoid using those pins for anything other than serial communication, even though I'm not at all sure that would actually cause a problem on the Arduino Leonardo.

  The example source code says
  ... this sketch depends on the MPU-6050's INT pin being connected to
  the Arduino's external interrupt #0 pin. ...
  The example does nothing (that I can see) to configure this pin.

I assume you're using https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/Examples/MPU6050_DMP6/MPU6050_DMP6.ino , right?

Interrupts are configured a little differently than I/O.
(In particular, "volatile" is critical to getting interrupts working right).

The part that configures that interrupt is in the setup() function:

void setup() {
    // ...

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
    // ...
}

The "attachInterrupt(0, dmpDataReady, RISING)" line
configures the interrupt vector table and the configuration bits so that when something drives Arduino pin D2 (i.e., external interrupt source 0) from a low to a high, no matter what the Arduino is in the middle of doing, the Arduino puts that on hold, executes the dmpDataReady() function, and then the Arduino resumes where it left off.

I don't see how that ever worked, since "external interrupt 0" comes from pin D2, which on the Arduino Leonardo is connected to I2C_SDA, which we're using for I2C communication, so we can't use it for watching the gyro interrupt pin.

However, since the "attachInterrupt()" gets run long after the "MPU6050 connection failed" message gets printed out on your screen, a software bug in how the example code uses attachInterrupt() doesn't explain why you get that "fail" message printed on your screen.

what to do about pin interference

I would try either using some other pin, or try getting it to work without hooking that pin to the Arduino at all.

Using some other pin

I would try to assign a dedicated pin on the Arduino to the MPU6050 INT pin.
Maybe D9 would work?

I'm guessing on the Arduino Leonardo, the interrupt should be set up something more like:

// warning: untested code.
#include <PinChangeInt.h>
#include <PinChangeIntConfig.h>

// connect MPU6050 interrupt to Arduino D9
#define MPU6050_INT D9

void setup(){
    // ...
    // pin change interrupt
    pinMode(MPU6050_INT, INPUT);
    PCintPort::attachInterrupt(MPU6050_INT, dmpDataReady, RISING);
    // ...
}

Getting it to work without hooking INT to the Arduino

It's not at all clear that the Arduino really needs to be connected to the MPU6050 INT pin.
It appears that another option is for the Arduino to occasionally use the I2C communication to read the status of the MPU6050, which includes the current state of that pin.
That simplifies the hardware -- simply leave the MPU6050 INT pin unconnected.


'Non-Deterministic' memory usage on Arduino

You haven't posted any code, so any answer is guesswork. However ... if your code makes decisions based on external events (eg. readings from sensors) then it may allocate memory differently, and in a different order, each time.

Sometimes memory allocation leaves gaps (known as "heap fragmentation"). Small differences in your results probably show slightly different sized gaps, due to the allocation order.


HUZZAH ESP-8266 (by ADAFRUIT): How to use with the ARDUINO R3

Ok, I'll keep this post open for anyone who got this board and the Arduino and wanted to use them together (it's probably only me, but who cares). Anyway, when looking at this board it's basically it's own controller. The front pins are what you need to communicate with the board itself. It's meant to be used with a FTDI cable to the computer. Anyway, looking further into it we see many pins behind the first 6 or so. To connect it to the computer using the Arduino you need to use this config.

Arduino | HUZZAH ESP8266
RX | RX (In the front)
TX | TX (In the front)
5V | V+ (In the front)
GND | GND (In the front)

Also, you need to create a thing where the Arduino won't be able to function, making it a communicator port for the HUZZAH itself. To do this simply take one of the GND pins on the Arduino and connect it to the RESET pin on the Arduino. After doing this you need to set up your ESP8266. This is a link to a basic guide on how to do this by ADAFRUIT. Instead of the USB cable, you are using your arduino as a cable essentially (a pretty expensive one). Anyway, the port number should be the port that your arduino is connected to (to the computer). This is if you want to use the ARDUINO IDE.

To use NODEMCU LUA which it comes preloaded with, you need to refer to this guide.

The other thing I wanted to mention was how to utilise a basic board with the controller. I had to use a MFRC522 RFID board with the Arduino, and I wanted to send the info to the internet. Sadly, it seemed as if I couldn't use the arduino itself. To use this board I used many sources. First, was the library github (this one).

The next step was to get the pin layout (from here). However, if you look at it it's in the pin format of a WESMOS D1 MINI board. The final source was to look at the product page (here) and convert the pin format to fit the HUZZAH Board (It's in the PIN section). That took a long time, but now you're done. That's a basic guide on how I used the HUZZAH Board with my arduino.


arduino rfid with led, code is compiling but not working as expected!

Your unespecified problems are consecuence of a collection of small details.

You are not putting a binary zero to end the input string.
That's not the way to read serial input.
Code doesn't filter out control caracteres (LF, CR).

Here is your code cleaned up:

#define ID_SIZE 12

int count=0;
char input[ID_SIZE + 1]; // rfid input
int led=3; // led pin
char first[ID_SIZE + 1]= {"270059204B15"}; //rfid tag no

void setup()
{
    // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(led,OUTPUT);
}

void loop()
{

    // put your main code here, to run repeatedly:
    while(Serial.available() > 0 && count < 12) {  // code for rfid input
       char c = Serial.read();
       if (isAlphaNumeric(c)) {
          input[count++]=c;
          }
      }

    input[count] = 0;
    if(count >= 12) {
        Serial.print(input);
    }

    if(strcmp(input,first)==0) /*comparing two string rfid tag no and input
   if matches led is on*/
    {
        digitalWrite(led,LOW); /* as the board which we are using is in sink
    mode low is taken as 1 or on*/
        delay(500);
        Serial.println("led is on\n");
        input[0] = count = 0;
    }

    else {
        digitalWrite(led,HIGH);
        delay(500);
        Serial.println("led is off\n");
    }
}

And here is the result:

Edit:

The C strings are char arrays of undefined lenght. To signal the end of the string, put a binary zero next to the (effective) last element. Then, if you want to store a 10 chars string, you need an 11 elements arrays (10 for the string itself, 1 for the binary zero).

Failure to put a binary zero at the end of a string is a very common cause of program failure.

Control characters. In general, when you type "TEST" in the Serial Monitor and press SEND, what Arduino receive is the word TEST itself, plus a Line Feed/Carriage Return pair (LF/CR) to mark the end of the line.

In real world, your serial input can be contaminated with tabs, spaces, LF/CR and other valid chars. You need to discard them (unless they are valid for your app).


What value of resistance to put between the output of a 74hc595 and the LEDs?

You are correct that a lower resistance would offer higher brightness. The more current through the LED, the brighter it will be. The current is calculated by dividing the voltage across the resistor by resistance value. The voltage across the resistor would be your 5V - the voltage drop across the LED. this often varies by color. A RED LED might have a 1.2V drop, and GREEN or BLUE would be higher. So to get the same relative brightness in different color LEDS, you will often see a lower resistance used, to get the same current.

Lets say you have a 20mA Red LED, with a 1.2V drop. So (5 - 1.2)/.020 = 190 ohms. If the LED required 10mA, that would be 380 ohms.

Now you DO need to look at the data sheet for the chip driving the LED, and make sure it is up to the task. Can a pin source or sink 10mA? 20mA?


Arduino Pico doesn't work with ST7735 screen

I found out the problem. I was trying to connect to the SCK and MOSI pins on the back of the Pico. Later research shows that these are meant for programming and burning a bootloader onto the microprocessor.
The Adafruit library allowed me to define my own pins for SCK and MOSI.
Once I switched to using the Adafruit_ST7735(int8_t cs, int8_t dc, int8_t mosi, int8_t sclk, int8_t rst) constructor, it worked after that.


You need to open the .ino file. that is the project file for the Marlin Firmware. then upload that. Also do some research about the settings for Marlin. It isn't just plug and play, you have to enter some information about your individual stepper motors.

http://solidutopia.com/marlin-firmware-user-guide-basic/ - heres a guide for Marlin.

the cpp and h files are c++ files that are apart of the project. the Arduino IDE cannot open these individually. the .ino file is the project file that will allow you to open up the entire project and not just one portion of it.


What MQTT client are you using?

Paraphrased from the MQTT spec  http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718099

  The MQTT protocol provides three qualities of service for delivering
  messages between clients and servers: "at most once", QOS0; "at least
  once" QOS1; and "exactly once" QOS2. For QOS 1&2: The message must be
  stored locally at the publisher, until the publisher receives
  confirmation that the message has been delivered to the receiver.
  However, for QOS0 there is no storage requirement.

The problem with the Arduino is that there is no large quantity of storage available. If the client is disconnected from the broker while using a QOS of 1 or 2 the client must store the messages until a connection is reestablished and the message transfers are acknowledged. On an Arduino there is no guarantee all the messages can be saved. Consider a sensor node collecting 16-bits (int value) every second. Then supposed the broker goes down over the weekend and a repair person isn’t paid to work on the weekend. That’s two days’ worth of data or 172800 readings or about 1/3 MB (without overhead). The Arduino does not have that much storage.


A bootloader to network-boot might be too large to leave enough code space for your application. Your second suggestion sounds more workable - to collect & verify the entire new image in secondary storage first, then call a storage-to-flash boot loader. You really don't want to start loading an image that then suffers damage in transit, or to have the link go down mid-download. The likely only way out of that is a site-visit. Saving first lets you confirm the integrity of the new image before you start over-writing any of the old one.


Why is 1020 steps used for crossfading colors on an RGB LED?

Extract from code:

int wait = 10;      // 10ms internal crossFade delay; increase for slower fades

for (int i = 0; i <= 1020; i++) {
  redVal = calculateVal(stepR, redVal, i);
  grnVal = calculateVal(stepG, grnVal, i);
  bluVal = calculateVal(stepB, bluVal, i);

  analogWrite(redPin, redVal);   // Write current values to LED pins
  analogWrite(grnPin, grnVal);
  analogWrite(bluPin, bluVal);

  delay(wait); // Pause for 'wait' milliseconds before resuming the loop

  if (DEBUG) { // If we want serial output, print it at the
    if (i == 0 or i % loopCount == 0) { // beginning, and every loopCount times
    }
    DEBUG += 1;
  }
}

The 1020 in the loop determines the time taken to make the crossfade from the current colour to the next - not the total cycle as you seem to think. In the main loop we have

crossFade(red);
crossFade(green);
crossFade(blue);
crossFade(yellow);

And each of these crossfades will take 1024 * wait ms to complete. 'wait' is set to 10 ms so I would expect it to take 10.24 s to complete a fade from one colour to the next.

[Edit]

I think the large number (1020) is just to give a fine resolution in the steps calculation which is all done with integers. (What struck me as odd is that it doesn't use 256 * 4 = 1024.) The larger we make this number the finer the step resolution becomes. With coarse steps the ramp will complete too early.

Let's say we had 255 steps and we wish to go from 134 to 0.

step = 255 / (endValue - prevValue)
step = 255 / (134 - 0 ) = 1.9 which will be rounded down to 1.

This means that the crossfade will be complete in 134 steps instead of 255. i.e., it will finish 47% early.

If we use 1020 steps and we wish to go from 134 to 0.

step = 1020 / (endValue - prevValue)
step = 1020 / (134 - 0 ) = 7.6 which will be rounded down to 7.

This means that the crossfade will be complete in 938 steps instead of 1020. i.e., it will finish 8% early.


How to extract the last byte out of an IP adress

localIP() returns an IPAddress object.  That object has an operator for [] allowing you to access the individual parts of it.

IPAddress ip = Ethernet.localIP();
Serial.println(ip[3]);


How to read a higher voltage digital input?

As @Gerben says, voltage dividers are a good place to start. To elaborate on the topic, you can use a combination of voltage dividers, zener diodes and clamping diodes.

This EE.SE post has some good info about this, related to ADC, but still the same.

First off, a voltage divider circuit is easily found on the internet,

Google
Wikipedia

This circuit from Hyperphysics shows the basics:

To add more protection to this so as not to go over the max I/O voltage of the MCU, you can add a zener diode on the Vout.
That would give you something like this(Olins):

This will give you the desired range to give legitimate High and Low on an I/O.

If you wanted to forgo the voltage divider and zener you can use clamping diodes to the microcontroller supply voltage Vcc. This will give a range that will not damage the I/O.

simulate this circuit – Schematic created using CircuitLab

The 10k resistor is there to limit the current through the diodes, which are Schottky diodes.

Another method, which I have used before and is reliable, is to use a diode and two resistors like below:

The logic is that, when the input IN is > Vcc(5V) the signal on the I/O _IN will be the voltage of the pull_up resistor R2, if it is low or floating the signal will be low. R1 also gives a known logic state if the input floats.

Edit: Changed the image to proper logic flow.


While I'm not experienced with running an RTOS on it, I'd highly recommend Teensy 3.1 as the "beefiest, fastest, most compute-centric Arduino". FreeRTOS and ChibiOS both support Teensy.


Arduino Yun can no longer send to Dropbox

I'd eventually figured out how to do it running the latest Dropbox module installed into the sd card where there was room.


DHT11 Humidity/Temp Sensor showing incorrect values

Obviously the DHT sensor has not acquired data to make sure do as follows:

void loop() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t) ) {
   lcd.setCursor(0,0);
    lcd.println("DHT not ready!");
    return;
  }
 lcd.setCursor(0,0);
  lcd.print("Temp: ");
  lcd.print(t);
  lcd.print((char)223);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print("Humidity: ");
  lcd.print(h);
  lcd.print("%");
  delay(1000);
}

Make sure you connected the DHT the right way and initialized

DTH11

    Pin1 --> 5v and 10k ohm resistor

    Pin2 --> Arduino Pin7 and 10k ohm resistor

    Pin3 --> no connection

    Pin4 --> Gnd

Initialize correctly

    DHT dht(DHT11_PIN, DHT11);

and in setup() you have to start like

 dht.begin();

Now test and report back


MEGA 2560: Simple program - One analogWrite turns off the other

As you are using using ArduinoIDE >=1.8.10 its an "optimization" problem by the compiler for the Mega try to replace the line

 void setup()

with

 void setup() __attribute__((optimize("-O0")));

// also -O1 works the default -Os and -O3,-O4 not

Actually the problem is not the IDE version but the included AVR boards package version.  You can install any AVR boards package in any IDE with Boards Manager. Last good AVR boards package is 1.6.21. If your compiler (tool chain) shows 7.03 in the output window you  are affected. I have examples where the compiler even optimizies the loop away, which ends in funny results - I dont know wether other boards are also affected but the MEGA is for sure.


About possibility of implementing kalman filter on atmega32

Sure, it can be done, and simply enough. Here is an implementation in C that could be easily adapted.

It won't be as fast as Mahoney, of course, but the calculations are possible. The question is, is it fast enough for your usage?


Unable to initialize W5100 using Arduino Pro Mini

One of the Ethernet examples shows you should test the result of the begin function call, like this:

// start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

Try displaying the return value from begin to see if that initialization succeeded.


Wemos: 16x2 display doesn't show anything

You are doing it on wemos d1 mini isnt it ?

Then you dint include its header files,
Did you check the "LiquidCrystal.h" has definitions for wemos pinouts?

Your lcd is fine, n wemos too, its just your configuration is wrong.

Check those and update here.


Nano v3 dual power source use & detection

To check, if VIN is connected, you can connect VIN through a voltage divider to a digital pin (as suggested in the comment of Code Gorilla). For checking the USB connection you would have to connect VUSB to another digital pin. Since VUSB is not exposed on a pin, this could be difficult to do, but it is possible.

But note, that this would also show a disconnect, when the voltage drops (e.g. empty battery). When you want to detect real mechanical disconnects, you need a power jack with an extra switch integrated.

Let's take a look at the schematics: Arduino Nano 3.0 Schematics

The selection of voltage supply is done by the diode D1. If the voltage resultung from the VIN regulator is higher than VUSB - diode_voltage_drop, the diode is closing and the power comes from VIN. If the voltage resulting from VIN is lesser, the current can flow from VUSB. How much power is really drawn from USB depends on the voltage difference.

So - to detect which source is actually used - you can measure the voltage on the diode with an analog measurement with the ADC or through connecting for example a comparator and using a digital pin.

Note that the voltage on the diode can be positive or negative, depending on which source is used.


You can't. It's not an Arduino library. You will have to find a different implementation.


a code to implement a simple traffic signal and also display on LCD which color is ON?

Write a sketch to test your LCD.

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 4, 2);
void setup(){
    lcd.begin();
    lcd.print("Hello World!");
}
void loop() {
    lcd.setCursor(0, 1);
    lcd.print(millis() / 1000);
}

Make sure the R/W pin is connected to GND on your breadboard. You may need to connect the contrast pin to 5V. Ideally it should be connected to the wiper of a 10KOhm trimpot with either end connected to GND & 5V (so you can vary the contrast).

Once that set-up works change your code

 void setup(){
     lcd.begin();
     lcd.print("Traffic signals");
     delay(500);
     pinMode(red, OUTPUT);
     pinMode(yellow, OUTPUT);
     pinMode(green, OUTPUT);
 }

 void loop(){
     changeLights();
     lcd.setCursor(0,0);
 }


i think i solved in some way, i send always the same codes at the start and at the end of the datas, so i can racognize the end and then i parse the first element of the destination array. tell  me what you think abou, if it could help someone else:

 if (BTserial.available()>0)
{
  c = BTserial.read();
  check =  String(c, HEX);
  if(check!="fff3"){              // i always start wit an fff3
  inData[index] = c;
  index++;
 }
  else if(check=="fff3"){         //end of data
  index=0;                        //reset the index for the next set of data
  if(String(inData[1], HEX)=="ffbc"){
    Serial.println("read the next 10 data of the array");
    }else if(String(inData[1], HEX)=="11"){
    Serial.println("turn on led 1");
    }

    // for more operations use a switch/case over the if

  }


Is it possible to reduce the size of this program to 1KB

There are several problems with your program as shown that make a good answer impossible.  After I list those problems, I'll then proceed to give an answer, partly good, partly bad.  The good part is that the 432-bytes-of-code program shown below should send all the indicated text strings, in the proper order and separated by appropriate delays.  The bad part is that it sends at 115200 bps instead of 9600.  Depending on point of view, it may be good or may be bad that the code doesn't look for absence of '>' on Serial input; as I note in discussion of problems, the original code's unclear.

As promised, here are several problems with your program as shown, and how to fix them:

The statement delay; is a constant expression [address of the delay() function rather than a call to delay()] so take it out.
The statement for (int i=0 ;i < 1 ;i++) is a do-nothing so take it out.
The sequence while(Serial.read()!='>'); { is confusing – it compiles but isn't something a rational programmer would write – so take it out.  (As written, with a semicolon directly between the right parenthesis and the left brace, it busy-waits until it reads '>' on Serial input.  Then the unnecessarily-blocked block of statements within the matched braces executes one time and loop() exits its current pass.  If the semicolon weren't there, the statements within the braces would execute repeatedly until a '>' appears on Serial input.)

Anyhow, with the minor fixes outlined above, and using the BasicSerial library from nerdralph's writing AVR assembler code with Arduino page, we get the following message for the program shown below.

  Sketch uses 432 bytes (42%) of program storage space. Maximum is 1,024 bytes.  Global variables use 68 bytes of dynamic memory.

#include <BasicSerial.h>
char *text = "AT+CMGF=1\n\0"    "AT+CMGS=\"+918269394684\"\0"
  "22.7010709,75.9372517\0" "\033\r\n";
#define send(item) while (*item) TxByte (*item++)
void setup() {
  //Serial.begin(9600);
  delay(2000);
  //Serial.write("AT+CMGF=1\n");
  send(text);
  //delay;
}
void loop() {
  char *msg = text;
  delay(1500);          // took out `for`
  //Serial.write("AT+CMGS=\"+918269394684\"");
  send(msg);
  //while(Serial.read()!='>'); {
  //Serial.write("22.7010709,75.9372517");
  send(msg);
  delay(500);
  //Serial.write("\033\r\n");
  send(msg);
  delay(5000);
  //}
}

Program Notes:

The string text contains all the text from your original Serial prints and writes.  With the text organized as a single string, the program only needs to set its character pointer msg once per loop, saving perhaps half a dozen bytes of code.
The commented-out Serial.write statements are equivalents of your various Serial.println, Serial.print, and Serial.write statements, with adjacent strings lumped into single writes, thus for example using one write instead of three to write the Esc, CR, LF sequence just before delay(5000).  Just changing those printlns, prints and writes all to writes reduces code size  by about 150 bytes, which might be enough of a reduction to get you by, depending where you start from.  But in my tests, substituting BasicSerial in place of Serial saves over a thousand bytes so is likely to be a requirement.
You probably can modify the code in BasicSerial.S for other data rates, or perhaps can substitute one or another of the small Serial replacements listed in ernstc's Serial communication with the Tiny's webpage, to get different data rates and/or receive as well as transmit.

Edit:  As Edgar Bonet noted in a comment, an ATtiny13 has 64 bytes of RAM, so the above program (using 68 bytes of RAM) will fail.  RAM usage can be reduced by copying string characters individually from program memory, instead of copying the string into RAM (per Arduino default).  See the following revision of the program, which also corrects a problem (leaving msg pointed at a null byte) that would keep the former program from working.  Note, with these changes, we have:

  Sketch uses 456 bytes (44%) of program storage space. Maximum is 1,024 bytes.     Global variables use 6 bytes of dynamic memory.

#include <BasicSerial.h>
#include <avr/pgmspace.h>
const char text[] PROGMEM = "AT+CMGF=1\n\0"
  "AT+CMGS=\"+918269394684\"\0"
  "22.7010709,75.9372517\0" "\033\r\n";
char *front = (char*)text;
#define send(item) while (pgm_read_byte(item)) TxByte (pgm_read_byte(item++))

void setup() {
  delay(2000);
  send(front);  ++front;
}
void loop() {
  char *msg = front;
  delay(1500);
  send(msg);   ++msg;
  send(msg);   ++msg;
  delay(500);
  send(msg);
  delay(5000);
}


How would I go about scrolling a name across a LoL shield with a potentiometer?

You know how wide the display is. You know how wide the text is. You know the position of the potentiometer. With those you can determine where in the text (if the text is wider) or display (if the display is wider) you need to start drawing from and where you need to stop drawing. Subtracting the text width from the display width will give you the range for performing linear interpolation with the pot position.


How to call more than 10 different functions based on serial input?

First, you could use a string for the commands. You just need to ensure there is some special char to mark the end of a command - like the newline char. Read the input from the port one char at a time, building the string as you go:

char buffer[256];
uint16_t buffer_index = 0;
void loop() {
  while (Serial.available()) {
    int c = Serial.read();
    if ('\n' == c) {
      buffer[buffer_index] = 0;   // Append EOS
      // Complete message - do something
      buffer_index = 0;   // Reset, ready for next message
    }
    else {
      // Append char to end of buffer
      buffer[buffer_index++] = c;
    }
    // Check for overflow
    if (256 == buffer_index) {
        buffer_index = 0;
    }
  }
}

There are plenty of examples like this on this site.

Next, I don't recommend using an if statement with a hundred or more conditions. Instead, you can store pointers to each function in an array:

// Use a typedef to simplfy
typedef void (*function_type)(); // A function with no params and no return, change as needed
// Fixed array size
const int max_functions = 200;
// Create an array of 200 function pointers
function_type all_functions[max_functions] = {0};

So to call function #11:

all_functions[10]();

Now you just need a way to marry the function pointers to a name. A hash table could work here. A hash function converts a string to a number. There are lots of examples on the web. Here's one:

uint16_t djb2_hash(const char *str)
{
    unsigned long hash = 5381;
    int c;

    while (0 != (c = *str++)) {
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
    }

    // Note: we use the mod operator to make sure value
    // is less than array size
    return hash % max_functions;
}

Create two functions, one to add a function and one to retreive:

bool add_function(const char *name, function_type f)
{
  // Convert name to number
  uint16_t index = djb2_hash(name);  //  0 <= index <= max_functions
  if (NULL != all_functions[index]) {
    // There is already a function stored at this index
    Serial.print("Adding ");
    Serial.print(name);
    Serial.print("failed. index = ");
    Serial.println(index);
    return false;
  }
  else {
    // Store the function in the array
    all_functions[index] = f;
    return true;
  }
}
bool run_function(const char *name)
{
  uint16_t index = djb2_hash(name);
  if (NULL == all_functions[index]) {
    // Name not found
    return false;
  }
  else {
    // Call the function
    all_functions[index]();
    return true;
  }
}

Last, create some functions and add to hash table:

void f1() {Serial.println("F1");}
void f2() {Serial.println("F2");}
void f3() {Serial.println("F3");}

void setup() {
  Serial.begin(9600);
  add_function("F1", f1);
  add_function("F2", f2);
  add_function("F3", f3);
}

All that's left is to modify loop() to call the functions when a complete message is received.

void loop() {
  while (Serial.available()) {
    int c = Serial.read();
    if ('\n' == c) {
      buffer[buffer_index] = 0;
      run_function(buffer);
      buffer_index = 0;
    }
    else {
      buffer[buffer_index++] = c;
    }
    // Check for overflow
    if (256 == buffer_index) {
        buffer_index = 0;
    }
  }
}

If you enter "F1", "F2", or "F3" in the serial monitor, those functions should execute. Just make sure you change the serial monitor to append a newline.

Some notes: the hash function may not create a unique id for each string. You need to handle this situation. Also, the names are case sensitive. If you don't want that, convert everything to all upper case or all lower.


Arduino Keyboard - print() works but println() does not

Please test: Keyboard.print("Hello world.\n");

...

  That works. println still doesn't.

I'm going to guess here that println is doing something odd in the Yun libraries. I note that the Keyboard.cpp file in my release has this in it:

#define SHIFT 0x80
const uint8_t _asciimap[128] =
{
    0x00,             // NUL
    0x00,             // SOH
    0x00,             // STX
    0x00,             // ETX
    0x00,             // EOT
    0x00,             // ENQ
    0x00,             // ACK
    0x00,             // BEL
    0x2a,           // BS   Backspace
    0x2b,           // TAB  Tab
    0x28,           // LF   Enter
    0x00,             // VT
    0x00,             // FF
    0x00,             // CR    <---------- note!

Notice that linefeed has a code mapped (0x28) but carriage return (CR) does not (unless you call 0x00 a mapping).

I think you'll find that when you hit Enter on a keyboard it is sending a CR (after all, it used to be labelled the "return" key) and not a LF.

However I thought that the Print class outputted both:

size_t Print::println(void)
{
  return write("\r\n");
}

Maybe yours doesn't. I'm not certain which exact println will be pulled in for a Yun. The fact that it used to work, and now doesn't, suggests a change there somewhere.


Circuit works on breadboard but has power problems on protoboard

I have a page about power saving.

To summarize some of the techniques you can use:

Run the processor at a lower frequency
Run the processor at a lower voltage
Turn off unneeded internal modules in software (eg. SPI, I2C, Serial, ADC)
Turn off brownout detection
Turn off the Analog-to-Digital converter (ADC)
Turn off the watchdog timer
Put the processor to sleep
Don't use inefficient voltage regulators - if possible run directly from batteries
Don't use power-hungry displays (eg. indicator LEDs, backlit LCDs)
Arrange to wake the processor from sleep only when needed
Turn off (with a MOSFET) external devices (eg. SD cards, temperature sensors) until needed

I've got a temperature and humidity sensor which has been running for years on 3 x AA batteries.

  The circuit is powered by a 9V battery (6LR61) connected to RAW (Vin on other Arduino boards).

That's not a great choice for a start, as the voltage regulator has to turn the 9V into 5V (in the form of wasted heat). You'd be better off with 3 x AA batteries (around 4.5V) and put them straight into the 5V pin.

Those 9V batteries have notoriously low mAh because they are basically 6 coin cells stacked on top of each other.


(I'm assuming you're using the official Arduino IDE here.)

Before uploading a sketch, you need to select which port you want to upload to. Within the Arduino IDE, click on the Tools menu and open the Port submenu. Click on the port your Arduino is connected to, such as COM3 or COM4.

You also need to ensure the appropriate board type is selected in Tools -> Board.

You should then be able to and upload the sketch.


Which wireless technology should I use for medium range, many to one, bidirectional communication?

Depends on how much data you're sending, what packet structure you want to use, whether you want to spin your own PCBs or use a plug-in module, whether you need a low-power solution, etc..

For that distance, probably a sub-1GHz solution would work best.

I've had good results with the TI range of Value Line transceivers as they offload all the packet-handling, sync-words, CRC etc. from the microcontroller.  The modules also handle addressing, and have a "listen before talking" functionality - both of which could be useful with your physical architecture.

Down sides:

You'd probably need to spin your own PCB - they have good reference
designs.
No library for Arduino... but I'd personally rather use a
transceiver that manages all the low-level comms between the modules
so I can focus on the application.


Why can't I use just the digital pins and a ground to use a potentiometer?

A potentiometer is an analog device, meaning it communicates its position by varying the voltage rather than sending discrete ones and zeros.

If a linear potentiometer is turned half way then the output of the pot will be at half the voltage of the input. If it is turned all the way then the output will equal the input voltage and if it is not turned at all then the output will be 0V.

In order to make sense of the potentiometer you must connect the output to the analog pins and it will give you a 10 bit number, the higher this number the closer the output voltage of the potentiometer is to 5v (or whatever you set the Analog Reference voltage to be, but don't worry about the AREF pin for now).

Digital pins are either on or off, there is no in between, so they do not work for this application

This page has an excellent potentiometer user guide: https://www.arduino.cc/en/Tutorial/Potentiometer


(HELP)How to read Physical Dimensions in datasheets

I have annotated your drawing a little to help you understand it better:


Way to use other baud rates in console or different input/output rates

The Arduino Uno is powered by an ATmega328P microcontroller. This
microcontroller has only one UART which is not capable of using
different baud rates for sending and receiving.

You could look into the different software serial port implementations
for the sending side. Another solution would be to continually change
the baud rate: each time you get a complete message from the serial
monitor,

you switch the baud rate to 31250 bps
you send the packet to the midi synth
you Serial.flush() to make sure the bytes have actually been sent
you switch back the baud rate to whatever you used in the serial
monitor

You will probably see some garbage on serial monitor as it receives the
bytes at the wrong rate, but that should not be an issue.


Note that this is one of those situations where direct port access
just makes things easier. You did not specify what board you are using,
and I will assume you have some AVR-based board. On those boards, I/O
pins come in groups called ports, with up to eight pins per port. You
can update all the pins of a port at once by writing a number to the
port output register. And guess what? The number you write comes out the
pins in binary, jut like everything works in binary inside the
microcontroller.

For example, on an Arduino Uno, you could wire your LEDs to the first
four pins of port B: i.e. pins 8 (lest significant bit) through 11 (most
significant bit). Then you can output a number to the LEDs just by
writing PORTB = number, and your loop would become:

void loop()
{
    static uint8_t number;
    PORTB = number;              // output to pins 8..11
    Serial.println(number, 2);   // print the value in binary
    number = (number + 1) % 16;  // increment modulo 16
    delay(1000);
}


Design considerations for creating an Arduino 'shield' shield to limit EMI

What would be helpful would be explanation of the type of AC you are using and then possibly a schematic or board layout.

That aside, there does seem to be noise between the two boards. The Idea of placing a PCB with just a large copper pour would work.

DC Ground

If you connect the DC ground from the main board you should use a ferrite bead(FB) between the two grounds, this will ensure that you don't get noise getting back into the ground of the main board after you have tried to shield it. You should try to match the ferrite bead to the noise frequency you experiencing (use a scope if you have one).

Using the DC ground as a shield is often done, if you look at the EMI cages on cellular phones, WiFi modules, and other noise generating devices/susceptible-to-noise devices, they are connected to ground. It gives the noise somewhere to go, instead of your signal lines. Thus using the DC ground is defiantly an option

i.e.:

Main ground>--------[__FB__]-------<SHIELD

AC Ground

You could use the AC earth line on the top part of the shielding board. The coupling part might be a bit over kill, leave space for it to test to see if it helps when you make the board. Also AC earth can be used for shielding but is used for the safety aspect of earth leakage.

Don't do a direct DC ground to AC ground unless you know what you are doing as this will create a ground loop, this will change the way stuff behaves and will make your circuit no longer a floating device.

Other stuff

I would also make sure how you drive the relay is isolated from the control circuitry, although from what you describe:

  if I move the shield further away I also don't see the issues.

If you share power rails between the relay board and the main board, try filtering the power going to the CPU section. Also the control lines can be isolated between the controller and the relay with opto-couplers, this might stop noise coming back into the circuit from the relay part.


AVR Timer1 OCR1A controls TIMER1_COMPB_vect interrupt!

By setting WGM12, you set the time to CTC mode. In this mode the timer will restart when it reaches that value set to OCR1A. So the lower the value, the faster it restarts, so the higher the frequency.

The OCR1B value only changes where in this cycle the interrupt occurs. It will however still only be called once per timer1 overflow.


What to use to Drive: 16 Segment LED, 4 Digit, Common Anode (4 sets)

It might be easier to just get a new common cathode led display or get the whole board from Adafruit https://learn.adafruit.com/14-segment-alpha-numeric-led-featherwing


It looks like from that page you can also use various API's to execute
  Python directly on the Arduino.

I don't see that, at all. All those links show you how to communicate with the Arduino over serial using Python on the host side.

You'd need a python interpreter to be able to run python on the Arduino. There is the Python On A Chip project and it seems like they have support for the Mega.

  2010/09/01 (1bdb8d31f27b) New platform: Arduino Mega.

Some more info from the PyMite page:

  any device in the AtMega family which meets these requirements: 20KiB
  Flash and 4K RAM, will run today

I doubt you'll find anything that'll let you mix Arduino and Python code in the same sketch.


Simulating a microcontroller's program is common, but not as part of a circuit, unless you're into Systems on Chips.

Model the micro interfaces and simulate the peripherals separately

Analog systems cannot be modelled accurately by hand calculations alone, therefore simulation is often a necessary step (on top of that, real circuits might behave differently from the model). Non-programmable digital systems are deterministic in their behaviour, but only if the interfaces are correct - tight specifications on impedances and such often mean simulation is required here as well. Generally speaking, for both simulation becomes a must when the system is not dead simple. Microcontrollers on the other hand are sufficiently deterministic not to require any simulation: they do what they're told, except in very very very rare cases (single event upsets from radiation for example). Now, what they're told might allow glitches to happen, but that's a different story*. Therefore, usually the analog, or digital circuits around a microcontroller would be given equivalent interfaces based on the microcontroller's behaviour and physical specifications, and simulated separately.

*: As the code becomes more and more complex, it gets more and more difficult to follow what the microcontroller might do. Unexpected glitches may arise from e.g. concurrent access (though I can't say this is common in the micro realm), or insufficient resources (that is why dynamic allocation [malloc,new] are highly discouraged, so that the resources allocation is known at compilation time) etc. That's usually why tests are required, and step-by-step debugging is used as a means to locate any error that arises. But inherently, microcontrollers are highly predictable and except in certain cases, it is not worth it to go through simulation (do not mix up simulations and tests, tests are always required!).

Advantages of microcontroller simulators

However, microcontrollers simulators do exist. They are particularly helpful to watch what happens inside the microcontroller when the code executes step by step: call stack, watches on variables, interrupt vectors etc. This can also be done on the actual hardware using in circuit debuggers, but simulators are cheaper and are also good to save on EEPROM erase/write cycles and to avoid damaging your micro if you are afraid that the devices around it might be incorrectly configured (some controllers are very expensive, especially if they are qualified for medical, military or aerospace applications). I have seen such ICD's and simulators for Microchip PICs (MPLABX), but there must be equivalents for AVR (the micro which is on the Arduino's), or perhaps even integrated in an arduino-friendly environment (though I doubt it). You might want to take a look here.

If you've got deep pockets: mixed signal simulators

Finally, there are mixed signal simulators which allow you to simulate analog, programmable and non-programmable digital circuits alike; one component will have an analog SPICE model, another a VHDL model, and ADC/DAC blocks will be added automatically by the simulator between those devices depending on the logic input/output technology you specify. Those are extremely expensive (the one I used is Cadence Virtuoso), you don't want to do that unless you're doing an integrated circuit or something critical.

P.S: DesignSpark PCB v3 has LTspice in it. Never tried that feature in there though, I used to use LTspice directly.

Note that your opening "QUCS is the only open source software [...]" is wrong. There are plenty of simulators out there which are open source. I agree QUCS is a very user-friendly one though.


Arduino Serial library (Synchronous or Asynchronous?)

The Arduno 101 doesn't communicate to the PC using a UART. It uses CDC/ACM over USB, which looks like a UART to the PC.  But it isn't.

USB sends packets of data, not individual characters
It only sends if there is something to receive it at the other end
There is no such thing as baud rate with USB.

Basically, when the CDC/ACM port has been opened by an application (e.g., the serial monitor) the Arduino 101 starts to send the data down the line. When the port is closed all data to be sent gets silently dropped by the Arduino since there is nowhere to send it to.

Hence when the port is closed it runs much faster since the data that would normally have to be packed into packets and sent down USB isn't. It's just thrown away.

To address your confusion:

You are misunderstanding the concept of synchronous and asynchronous with regards to serial. There are basically two types of serial communication: Asynchronous, where both ends have to (pretty precisely) agree on the speed of communication (baud rate), and synchronous, where one end tells the other end what the speed is by providing a discrete clock signal. UART (RS-232, RS-485, etc) is asynchronous. It sends at a specific rate and has to rigidly stick to that rate for the other end to be able to receive it properly.  SPI and I2C are synchronous - they both (as master) provide a clock signal to the receiving end (slave) and the receiver synchronises its reading and writing of data with that clock signal (hence synchronous).

You are confusing those concepts with another meaning of synchronous and asynchronous - terms that could better be used would be parallel and sequential processing. If something happens in parallel then two (or more) things happen at once. This is the case of the hardware UART where you submit characters to be sent to the buffer and they get transmitted out by the hardware separately to the sketch - in parallel. Sequential would mean that one thing has to happen after the other. If the UART behaved like that your program would stall every time you wanted to send a single character.

So UART processing happens in the background, in parallel to your sketch. So does USB data processing for CDC/ACM. These things are generally coupled with interrupts to allow the CPU to handle tasks such as placing more data in the buffer or storing data that has arrived somewhere that you can get to it.  Interrupts aren't strictly parallel, in that they do stall your program while they run, but they are kind of in a different thread, or context. So they appear to be parallel.


Field Programming a Arduino with another Arduino with SD card over RX/TX lines

There's actually a library for that as well! See here and here.


How to Segment Accelerometer Signal at idle points

There are many algorithms you can use. I would advise you to look carefully at the data and the "idle state" and see what is always different. Try everything you can think of and see what works best, or if one does everything you need just stop there.

It might be that you can just calculate if the accelerometer values go over a certain threshold, but that requires that either the orientation be know or the threshold being over 1g.

You could also calculate the rate at which the accerometer value is changing by subtracting the last value (the derivative if you are up on your calculus) and threshold that value, which might produce better results.

You could also calculate a running average and then compare the current value with that. If the numbers match (or are very close) then you can say the accelerometer has been idle. This has the effect of making a changing threshold relative to the most recent activity tuned by the average's response.

I doubt any of these will be perfect, so you might require the algorithm to say "idle" multiple times in a row before changing state from "active" to "idle", or something to that effect.


Arduino Uno with CC3000 WiFi Shield cannot be initialized

Solved it, the problem was because the SparkFun library was not working with my shield. I replaced it using the Adafruit_CC3000_Library and now it works fine.


Why does my sketch report too many button presses?

Contact Bounce

This is known as contact bounce and happens when the metal contacts in the button or switch bounce against each other when you push it. The microcontroller is fast enough to pick up these bounces and, as far as it's concerned, you're toggling the switch many times in as much as 10 milliseconds of time.

Different switches and buttons will have a different amount of contact bounce, and even one switch will behave differently between two presses.

Here's a button press captured on a scope (image from Maxim):

At 2ms/div we don't see a stable signal until 6ms after initial contact!

Solutions

Add a delay

The absolute simplest solution is to introduce a short delay after you read the button input. This will prevent the code from picking up any bounces and when it resumes, the signal should be stable.

if (digitalRead(A3) == 0) {
    // do something here
    delay(500);
}

In the example above, I delay 500ms after reading the state of the pin. The button is normally high so when I press it down, the state of the pin goes to logic 0. I pick that up in the code and do something and then wait at least 500ms before continuing.

Obviously, this code will just halt for half a second every time you push a button, which may or may not be acceptable in your application. You can decrease the amount of delay depending on the contact bounce time of your switch, too, but I play it safe here.

Ignore button presses too close to each other

Similar to the solution above but instead of adding a hard delay, you use the millis() function to keep track of when the last time the switch was triggered. Every time you see a switch trigger, you compare against the time and, if not enough time has elapsed (say like 500ms in my previous example), you ignore it.

This solves the problem of having to use delay() in your code.

Switch debouncer IC

There are things like the MAX6816 which is an IC that you put in between your switch and microcontroller input. It will denounce the signal for you. At a price of $1.62 @1k you'll probably never use this.

Other

There are many solutions to this problem... I always do it in software, but some others include using a latch or capacitor.

Debounce Code – one post to rule them all


Increasing distance of IR remote / transmitter

I assume that the led you purchased just isn't as bright as the led that came with your remote.
As I've seen from your link you could quite easily swap the led from the board.
If the new led has the same voltage, the board should work just fine with any other led. Maybe just search for a brighter led with the same wavelength.

I don't think that a back reflector would have such a big effect to boost the range to the distance you need. Also I think it would be rather complicated to install one on the tiny board.


Arduino as Slave to Return Multiple Values

Bidirectional communication in I2C is a two stage thing.

First you have to tell the slave which pin (or register) you want to read. Then you have to read it.

A typical master sequence would be:

Wire.beginTransmission(0x22);
Wire.write(1);
Wire.endTransmission();
Wire.requestFrom(0x22, 2);
byte b1 = Wire.read();
byte b2 = Wire.read();

And of course your slave has to respond to the write() and remember which pin is being selected, then separately respond to the requestFrom() and return the data corresponding to the pin that was selected earlier.


Solution for simple multi-Arduino communication network (or alternative?)

Thanks all for your answers.

I did some more research with the new info you provided and found my perfect solution: TCA9548A. That's a 1-to-8 port i2c multiplexer that will allow the master MEGA2560 to control up to 8 independent i2c buses, where I can connect my displays. The chip is dirt cheap here - 2 euro only, and it is available in the store.

Thanks again guys!


I got one of the D1 Robot version 1 from AllElectronic and I had to adjust the contrast before I could see the words on the display.


This answer will also be not so specific, but you can try:

Check all wiring (use a multimeter/analyzer)
Reduce the data rate
Find out if there is a pattern whenever garbage is created (depending on values?)
Check (if possible) for errors (overrun/parity)
Play with the parity setting/stop bits to see if it makes a difference


Need help with understanding the CapacitiveSensor circuit diagram

The other capacitor shown in the article is the ambient capacitance (that is, the capacitance between the pin and the things around it). There is no actual capacitor.

What it is saying is that there is a RC circuit (the supplied resistor and the capacitance in the air) which will change the charging time of the RC circuit as the capacitance changes, when you move your hand near it.

From a comment:

  and the other capacitor with a value of 20-400pF

Yes, it does say that:

  Adding small capacitor (20 - 400 pF) in parallel with the body capacitance, is highly desirable too, as it stabilizes the sensed readings.

However that doesn't make any sense to me. How do you add a capacitor in parallel with your body? Do you carry one around with really long wires? And how do you hold it? I would ignore that part.


Your updating LED_T_ON and LED_T_OFF but those values were already passed into the constructor and changing them will not change the object. you need to update  relay3.OnTime and relay3.OffTime


It's an ATmegaU2, which has USB hardware and handles the USB communication. It passes the hex file on to the bootloader in the main microcontroller. That is its only job.


I want to ask a question.

You don't need to tell us.

  Can i communicate 2 esp module like xbee ?

You can make two ESP8266 modules talk together, yes. It's not "simple" like an XBee, since you have a generic WiFi network interface, so there's many many different ways of doing it. Typically one would be running as a WiFi Access Point (SoftAP) and the other would connect to it. Then you'd run some "server" code on one module (typically the SoftAP one) and the other acts as a client and connects to it (or sends data to it).


Problem uploading big program to arduino

The sync error is a common issue that doesn't have one simple solution (as shown here)

It means that the computer can't communicate with the processor, but it recognizes that it's there (out of sync). This is probably due to something (a peripheral, stray wire) interfering with the transmission from computer to device.

Solutions that have worked in the past:

Unplugging the Arduino for 30 seconds, then plugging it back in.
Removing any wires connected to Rx and Tx pins during upload.
Soldering components connected to Rx or Tx to the board (in this case, I was using a shield that allowed me to do this)

There are lots of solutions available from different sources on the internet, but I have not come across one that names program size as the reason.


ESP8266 ESP-01s Not Responding, No LED Blinking, Overheating

The ESP8266 is (highly likely) dead. The overheating is the giveaway.
Because you haven't mentioned it, please measure the 3.3V coming out of the Arduino with a multimeter. Unlikely to be the issue but it is easy to check.
You will need to buy a new ESP8266 and connect it up and give it a try with a fresh board. If all is good with the new board then the first thing you will notice is that there is no overheating. (If there is overheating, then you need to check your wiring.)
I notice that quite a lot of people add a 10K pull up resistor between the 3.3V line and the Enable pin. It certainly won't hurt to add a 100 ohm resistor between the Tx pin and D2 of the Arduino as a current limiting resistor, just in case.


This looks like a rounding problem. If the number you want to print lies
within the open interval (9.95, 10), the condition value < 10 is true,
as the number is strictly less than 10. Obviously, value != 10 is also
true. Yet, lcd.print(x, 1) will round the number to the closest
multiple of 0.1, which in this case is 10.
I see no better solution than handling the rounding yourself. I would
use integers for the comparison, as they avoid all rounding issues:
// Print a float to the LCD in 2.1 format (xx.x), left padded with a
// zero if needed. Assume x < 100.
void printPadded(float x)
{
    // Left pad.
    int i = round(x * 10);
    if (i < 100) lcd.write('0');

    // Print the rounded value.
    lcd.print(i * 0.1, 1);
}


If an I2C connection is lost for a short period of time will it work if the connection is live again?

When an I2C master starts a transmission or a request from a slave, it sends the slaves address and then check for an acknowledgement (ACK) from the slave (SDA LOW, when the clock has a HIGH pulse). When no slave is connected, or there is no slave with this address, then there isn't any circuit to pull SDA to LOW on the clock pulse, that is generated by the master. This is interpreted as No acknowledgement (NACK) and the transmission/request fails and should exit. So a disconnection between the transmission should not freeze your code (though I don't know what your library is doing exactly).

A quick google search gives me, that the esp8266 does not have hardware I2C, so your library does a pure software I2C. There are many pitfalls, which can block the I2C bus (especially, if one the lines is hold LOW by one of the involving circuits). Your library may or may not implement the correct I2C protocoll.

So to clearly answer your questions:

You don't have to reinit connection. Your master transmission fails, if there is no slave, and should give you an error as return value. But be sure, that there isn't happening anything on the SDA or SCL lines, when it starts up again after reconnection. Master or slave can interpret voltage spikes as signal.
If the library is implemented correctly, it will exit, when there is no ACK from the slave.

Look into the documentation of your library how it handles these events. And check the state of SDA and SCL, when a block occures. You can refer to this site for further information about I2C. It also gives some advice if your bus is blocked.


Changing Uid Using MFRC522 Via Arduino Error

Search for UID changeable card. The kit included this RFID reader just had a normal RFID card and keychain. You will probably have to buy it yourself. I bought it from aliexpress but I don' t remember which seller. Good Luck! (I mean who read this...)


Yes you can use multiple UART/Serial devices with a single Arduino.

However, there are some things to consider:

The Arduino Uno supports a single hardware serial connection (which is used for programming and debugging with the Serial Monitor). The Arduino Mega supports 4 hardware serial connections.

The arduino environment has a software Serial library that allows for additional Serial connections. However it is worth noting that software serial is slower than its hardware counterpart.

Also, if you want to use software serial, be sure to verify that any shields you want to use will support using a software serial connection.


Check this example: rather than sleep(), it uses PT_WAIT_UNTIL

  while(1) {
      PT_WAIT_UNTIL(pt, millis() - timestamp > interval );
      timestamp = millis();
      doSomething();
  }

That should be the proto-thread way of waiting: PT_WAIT_UNTIL will make sure that your thread sleeps in a way that allows other threads to run.

The rest looks fine, but I have not tried to run the code.


I2C begginer with I/O expander with mega328p C code

OK the answer is that I didn't send the correct address!

Because if the I2C starting command with the slave is successful, then you should get successful sending ACK according reading the value of transmission status from the status register TWSR and ANDing this value with 0xF8. Then by reading the datasheet you know the value of transmission status. I developed a function to determine the status of transmission with Arduino Serial library which is I2C_TWSR_Check();.

I did this code for Master transmitter and receiver only.

So the trick is that you have to fix the address according to the AVR's TW address command format, which is the first bit is for read/write command and the remaining 7-bits are for the address, so you have to shift the real address which I got by "I2C address scanner" I got from one of AVRfreaks members.

For example, if the address is 0x20, then after shifting it 1-bit to the left, the new address is 0x40 for write operation and 0x41 for read operation.

void I2C_init(void);
void I2C_start(uint8_t address);
void I2C_stop(void);
void I2C_tx(uint8_t data);
uint8_t I2C_rx(void);
void I2C_TWSR_Check(void);

uint8_t bitmask;

/////////// I2C modules addresses ////////////
// 8-bit I/O expander 0x20
#define IOEXP_WR  0x40    // I/O 8-bits expander address
#define IOEXP_RD  0x41

// LCD1602 adapter
#define LCD1602_WR  0x4E  // LCD1602 I2C adapter address
#define LCD1602_RD  0x4F

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  I2C_init();
}

void loop() {

  I2C_start(LCD1602_WR);
  I2C_TWSR_Check();
  I2C_tx(0xff);
  I2C_TWSR_Check();
  I2C_stop();
  _delay_ms(500);

  I2C_start(LCD1602_WR);
  I2C_tx(0x00);
  I2C_stop();
  _delay_ms(500);
}

void I2C_init(void)
{
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1<<TWEN);
}

void I2C_start(uint8_t address)
{
  TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while (!(TWCR & (1<<TWINT)));
  //I2C_TWSR_Check();
  TWDR = address;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  //I2C_TWSR_Check();
}

void I2C_stop(void)
{
  TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t data)
{
  TWDR = data;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  //I2C_TWSR_Check();
}

uint8_t I2C_rx(void)
{
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

void I2C_TWSR_Check(void)
{
  uint8_t Status;
  Status = TWSR & 0xF8;
  switch(Status)
  {
    /////////////// MASTER TRANSMITTER //////////////
    case 0x08:
    Serial.println("Start is OK");
     break;
    case 0x10:
    Serial.println("Re start");
     break;
    case 0x18:
    Serial.println("SLA+W OK ACK");
     break;
    case 0x20:
    Serial.println("SLA+W no ACK");
     break;
    case 0x28:
    Serial.println("data TX OK ACK");
     break;
    case 0x30:
    Serial.println("data TX OK no ACK");
     break;
    case 0x38:        // arbitration lost in SLA+W or data TX
    Serial.println("arbitration lost in SLA+W or data TX");
     break;

    /////////////// MASTER RECEIVER //////////////
    case 0x40:
    Serial.println("SLA+R OK ACK");
     break;
    case 0x48:
    Serial.println("SLA+R OK NO ACK");
     break;
    case 0x50:
    Serial.println("data RX OK ACK");
     break;
    case 0x58:
    Serial.println("data RX OK NO ACK");
     break;

     default:
     Serial.println("Error");
    break;
  }
}


ESP8266 occasionally stops receiving data

dandavis helped me find the answer! Turns out it was a memory leak, due to some poor math on my end. All I had to do was fix that up and it worked fine.


How to send information from a web-site to the arduino?

Yes of course!
First things first - Yes, it is possible to accomplish what you're thinking.
The idea is to create a server on the Ethernet Shield and open the webpage hosted by it on any device and based on the options selected on the web page we can trigger desired actions on the Arduino.
I've modified the web server code of Arduino built-in examples to match your requirements, just upload it and make necessary changes as required, here it is-
#include<SPI.h>
#include<Ethernet.h>

byte mac[] = {
   0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
 };

 IPAddress ip(192,168,1,199); // Any ip address not on your network.
 EthernetServer server(80);   // Port 80 is default for http.

  int led=2;

  String request;

  void setup(){
    Ethernet.begin(mac,ip);
    pinMode(led,OUTPUT);
    Serial.begin(9600);
   }

  void loop(){

      EthernetClient client = server.available();
  if(client)
         {
       Serial.println("Client is trying to connect......");
       while(client.connected())
       {
  if(client.available())
  {
    char c = client.read();
    request.concat(c);
    if(c=='\n'){
    Serial.print(request);
    if(request.indexOf("ON")>0){
      digitalWrite(led,HIGH);
      Serial.println("ON");
      }

      else if(request.indexOf("OFF")>0){
        digitalWrite(led,LOW);
        Serial.println("OFF");
        }
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    //client.println("Refresh: 5");  // refresh the page automatically every 5 sec
    client.println();

    client.println("<!doctype html>");
    client.println("");
    client.println("<title>LED</title>");
    client.print("<!DOCTYPE HTML>
LED ON

LED OFF

" );
    client.println("");
    client.stop();
    request="";

  }
  }
 }

    }

   }

This sketch will turn an LED on or off attached to digital pin 2.
You have to go to the IP address that you provide to the shield (192.168.1.199 in my case). You'll see 2 hyperlinks to switch on or off the led and that would pass a query which the Arduino looks for again and again in the loop and takes action accordingly.
Hope this helps, try this out, and do let me know the result.
NOTE
Make sure that you access the Ethernet Shield from a device within your LAN only otherwise you'll have to use port forwarding.


How are locations in FLASH memory addressed?

I'm not clear if this is the page address or the byte address from which I will start recording?

That is the byte address.  As the data sheet in section 8.5.13 says:

If an entire 256 byte page is to be programmed, the last address byte (the 8 least significant address bits) should be set to 0. If the last address byte is not zero, and the number of clocks exceed the remaining page length, the addressing will wrap to the beginning of the page.

In other words: if you want to write an entire page then start at the beginning of the page. If you don't and you write more than there is room left in the page you will wrap round back to the beginning of the page again.
So if you write two bytes starting with address 0x10FF you will actually write one at 0x10FF and the second at 0x1000, not 0x1100, since you wrap at the page boundary.


SPI - Apparently Random pulses on CS/SS line

See my page about SPI.

  Pin 10 of the Arduino is the SS line - so does this mean you have to use it for the peripheral SS line? Or should it be kept high? The answer (from the Atmega documentation) is that the SS line (pin 10) must be configured as an output (regardless of what value is on it). If configured as an output the Arduino ignores the value on that line, and thus the SPI hardware will not be put into slave mode.

  Since the value on pin 10 is ignored, providing it is set as an output, then it can also be used as the SS line for your first, or only, slave. You could then use other pins (eg. 5, 6, 7, 8, 9) to control other slaves.

For you to successfully make an SPI master then pin 10 on your Uno must be configured as an output, regardless of whether or not you actually use pin 10 for SS. Under the circumstances, you may as well use pin 10 for SS if you are going to make it an output anyway.

  This issue persists when using pin 10 as the SS.

I tried your code with my Uno (no device connected) and had no such problems. Sounds like an electrical issue to me.


How to Write a function or Loop or program to receive fixed number of Integers or characters over Serial?

As noted in the comments, since your prototype is receiving data from the serial port, you need some way for the user to indicate to the program that they are finished entry, since a 4-character entry is a necessary point along the way to a 5-character entry.

What you are doing now, by checking if Serial.available()>5 is letting the serial buffer hold 6 characters before you read from it (note: 5 is not >5), but then your else statement:

else if (Serial.available() < 4)
{
  Serial.read();
}

Clears out the buffer (Serial.read() removes one character from the buffer), so you will never get to 5 characters anyway, unless all 6 characters come in between runs of loop(), which is not likely at 19200 baud.

Not to mention that while data is sitting in the buffer, you don't know what it is and can't act on it. It is better to use the buffer as intended, which is to allow the Arduino to collect serial data, even while your program is working on other things, and then grab any pending data from the buffer as the program loop()s.

You have declared the userInput[5] array to hold user input, but note that if you only declare it at 5 chars long, it cannot hold the null-character terminator that is standard for C-style strings. It would be better to declare this as:

char userInput[6];  // Holds 5 user characters, plus null terminator.

In your loop(), you should copy out the contents of the buffer into your userInput, check the length or for a termination character, such as a carriage return or newline (i.e., pressing 'Enter' on the serial terminal.) and act accordingly. Here is an example, showing just the relevant bits for the user input and hiding the rest in [...]:

char userInput[6];  // Holds 5 user characters, plus null terminator.

void setup() {
  userInput[0] = '\0';  // Initialize string to empty
  Serial.begin(9600);
}

void loop() {
  uint8_t processInput = 0;   // Set to 1 if we have complete entry
  while (Serial.available()>0) {
    char input = Serial.read();
    if (input=='\r' || input=='\n') {
      // Have received a terminating character,
      // Flush the rest of the buffer
      while (Serial.available()) {
        Serial.read();
      }

      processInput = 1;

    } else {
      int s_len = strnlen(userInput, 5); // Get current length of userInput
      if (s_len<5) {
        userInput[s_len++] = input;      // Append character
        userInput[s_len] = '\0';         // Null-terminate string
      } else {
        // User has entered more than 5 characters and no terminating
        // character; here is where you can decide to clear the userInput
        // and start over, or just drop the first character and care
        // about the most recent 5, etc. Here, we will clear the input
        // and start over; The 6th character is dropped/ignored and
        // user input starts again. It is as though the 6th character
        // entered is like pressing Enter, but it does not process
        // the incoming data, beacuse 6 characters is an invalid input.
        userInput[0] = '\0';
        s_len = 0;
        processInput = 0;
        // Invalid input
        Serial.println("Error: invalid data");
      }
    }
  }

  if (processInput) {
    Serial.print("User input - ");
    Serial.println(userInput);

    if (strnlen(userInput, 5)==5) {
      // Do something **here** with the input string!!

      // Reset input string
      userInput[0] = '\0';
    } else {
      // Invalid input
      userInput[0] = '\0';
      Serial.println("Error: invalid data");
    }
    processInput = 0;
  }
}

Note, this code is not fully tested and may contain bugs. In particular, I did not intensely check if the while (Serial.available()) {} properly handles a lot of extra data.

One final note, you don't need the delay() with this code.

EDIT:

I tried the sample code above and it had a couple of bugs, one of which was that after a successful 5-digit entry, the input string was not reset to empty. I have now updated the code and it's a valid, working program to receive and process a 5-character input on the serial port and to toss an error if fewer than 5 or more than 5 characters are entered. Entry is terminated with a carriage return or newline (enter key).


You need to create a power budget. This means pouring through the datasheets of each component and finding the max and nominal current consumption info and then summing it up. From this, you should be able to come up with a battery capacity value.
There is a great article called "What is a Power Budget" written by Chris Gammell (from The Amp Hour) that goes into power budgets in more detail. Here are the key items from that page:

So what is a power budget? Much like a budget you might have for your personal finances, a power budget shows where all the possible power will be used by a device to by breaking it down into components and categories.
As you can see, not much more is required than your datasheets and a spreadsheet type program. ... The first two columns (A&B) are simply identifiers to allow you to recognize which components correspond to which set of data. The next two columns (C&D) determine the multiplicative factor. If you have 5 components that contain 4 op amps per, then that will consume 20x the power of a device that has the same supply current needs but only one op amp per and there is only one on the board.  The next two columns (E&F) show how much current each individual component contributes and then the sum of all the components of that type contribute. Note that this parameter on a data sheet would be listed as “supply current” or “active current”. The “quiescient” number is when the device is in a resting state and will likely be much less than the active number (and not relevant for this example). Finally, the supply voltage is listed (in column G) to calculate power (using the formula P=I*V) which is listed in column I per device. All of these contributors are summed, an efficiency is estimated (I assumed a poor efficiency linear type supply) and the total power required input to the device is given. Further calculations could result from much of this initial data.