body:
IC stands for [*integrated circuit*](https://en.wikipedia.org/wiki/Integrated_circuit), which is a generic term encompassing any class of devices that has multiple electronic components (transistors, and possibly capacitors, resistors, diodes, and more) encased and interconnected within. The opposite of an integrated circuit is a discrete component, which is a single electronic component in its own package that relies on wiring (or a circuit board) to connect to other components.

Taking a look at the Arduino Uno R3 below (click for larger image), the long rectangular black thing is the primary IC. You can see the ATMEL logo on it, followed by a short series of numbers (a date code if I'm not mistaken). Below is the chip model itself; in this case, "ATMEGA328P-PU". With respect to the Arduino IDE, it's sufficient to know that the chip is an ATmega328P, which is sometimes incorrectly called ATmega328 in the Arduino world.

[![Arduino Uno R3][1]][1]

If you look closely, there are also several other ICs on the board. To the right of the ATmega328P is a small 5-pin package; if I'm not mistaken it's an [LP2985-33DBVR](http://www.smdmark.com/en-US/ic-367390.html), which is a low-dropout voltage regulator. On smaller packages like this they often have more cryptic legends printed on them, in this case if you squint at the full-size picture you can make out "LPFL". Fortunately for most Arduino development purposes, knowing the model of these auxiliary ICs is generally not necessary. Just below that, above the crystal (the metal oblong can marked SPK16.000G) is an 8-pin package marked 09TI R5R, which I believe is a [LMV358IDGKR](http://www.smdmark.com/en-US/ic-369055.html) dual op-amp.

Another IC of note on this board is the small square 32-pin package below the crystal; this is an ATmega16U2. In the case of the Arduino Uno R3, rather than being the primary microcontroller, this serves as the USB-to-serial converter.

Note that to the right of the crystal is a small three-pin package marked "340"; this is a [FDN340P](http://www.smdmark.com/en-US/ic-27432.html) MOSFET. While this model of MOSFET (as with many others) contains an integrated diode across its drain and source and could thus *technically* be classified as an integrated circuit, most would still consider it a discrete component.

  [1]: https://i.stack.imgur.com/6fQtC.jpg


sender: user

message:
Problem with the Frequency meter code

I am trying to build a frequency meter using Interrupts and Timer1, which works as if the system receives an Interrupt it would get the timer's data and would calculate

> Signal's Frequency = 1 / (Counter * Timer's Period) => F_s = F_t/TCNT

but the result is way off, and it does not even make sense. I have had altered my code to look that if the timer's data is not valid or sth, but the number that the timer counter has counted is sth that I expect.

Here is my code:

    int f=0;
    char msg[50];

    void setup()
    {
      Serial.begin(115200);
      noInterrupts();           // disable all interrupts
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
      TCCR1A = 0;
      TCCR1B = 0;
      OCR1A = 0;
      OCR1B = 0;
      TCCR1B |= (0<<CS12)|(1<<CS11)|(0<<CS10);    // Clock 2MHZ
      TCNT1  = 0;
      TIMSK1 = 0; // disable timer overflow interrupt
      interrupts();
      attachInterrupt(1,pin_ISR,RISING);
    }

    void pin_ISR(){
      //digitalWrite(13,!digitalRead(13));
      f = 2000000/TCNT1;
      TCNT1=0;
    }

    void loop()
    {
      sprintf(msg,"Humidity:%d \n",f);
      Serial.print(msg);
    }

sender: assistant

body:
Did you find an example that works that way ? Is it, for example, allowed that the TCNT1 is cleared in an interrupt routine? The TCCR1A is cleared, but not set to a value ?
[**edit**] Clearing TCCR1A is okay. Clearing TCNT1 is also okay, but can be improved as @EdgarBonet shows.

The calculation uses a long of 2MHz, but the others are 16 bits. Could you force that calculation with long ? `f = int( 2000000L / long( TCNT1));`
[**edit**] It is not needed to force the compiler into a 'long' calculation, it already does so.

The 'f' variable is used in an interrupt and outside that interrupt. It must be made 'volatile': `volatile int f=0;`

The 'f' is used in the loop, but the interrupt could happen when 'f' is only half read or half written. The ATmega328P is a 8-bit microcontroller and 'f' is a 16-bits variable. I suggest to disable the interrupts and make a copy.

    noInterrupts();
    int fcopy = f;
    interrupts();
    sprintf(msg,"Humidity:%d \n",fcopy);

What is the range that you want to measure ?

Do you know that there are good libraries to measure a frequency ? They are the [FreqMeasure Library][1] and the [FreqCount Library][2].

[ADDED]
Try to slow down the loop with a delay. If you fill the transmit buffer of the Arduino Uno TX, then the Serial.println wait for each character if there is a place in the transmit buffer.

  [1]: https://www.pjrc.com/teensy/td_libs_FreqMeasure.html
  [2]: https://www.pjrc.com/teensy/td_libs_FreqCount.html


body:
Your approach is basically a reciprocal counter and it can work, if you start and stop the timer in the isr. The logic is essentially this:

If timer is on stop the timer and save the timer count.
Else initialize the timer and start counting.

For counting a wide range of frequencies, you may need to consider timer over flow.

Edit: any solution that reads a multi byte counter while it is running will produce the wrong results. Google atomicity to understand why.


body:
As stated in my comment, your code is _kind of_ fine. Id mostly works,
but it looses a few microseconds on each iteration. If you are looking
at multi-kHz frequencies, you probably want to avoid loosing
microseconds. The solution is simple: _never_ reset the counter. I
changed you ISR as follows:

    uint16_t previous_counter;

    void pin_ISR(){
        uint16_t counter = TCNT1;
        f = 2000000/(counter - previous_counter);
        previous_counter = counter;
    }

and now it gives the correct frequency... on average. There are some
variations though, dues mostly to delays caused by other interrupts.

**Edit 1**: If you want to avoid the fluctuations caused by other
interrupts, your best bet is probably to use the input capture feature
of Timer 1.

**Edit 2**: Here is why your measurement was somewhat off. Your original
ISR essentially does something like this:

    void pin_ISR() {
        uint16_t temporary_value = TCNT1;
        loose_some_time();
        TCNT1 = 0;
    }

The time you loose in the ISR is the part of the signal period you are
not measuring, which means you are underestimating the period by that
much. In the ISR you posted, this is mostly the time taken by a 32-bit
division, which is quite significant. A simple improvement would be to
clear `TCNT1` right after reading it:

    void pin_ISR() {
        uint16_t temporary_value = TCNT1;
        TCNT1 = 0;
        loose_some_time();
    }

and now the average period you measure is _almost_ right. It is not
perfect though, as the whole reading and writing of `TCNT1` takes
8 CPU cycles.

The alternative I am suggesting, where you _never_ clear the timer, is
the correct way of measuring a period with a timer interrupt: you don't
loose a single CPU cycle. The best way is to use input capture: you get
rid of the software-induced jitter.

**Note**: You should also take care of the very valid points raised in
Jot's answer, about making `f` volatile and reading it with interrupts
disabled.


body:
So I have had asked this question on the Arduino forum and some one has fixed my code which gives me the accuracy that I expect. The problem was that the division was better not to be in the ISR routine but in the main loop. Here's the link to that answer because that guy should be credited as he helped me big time.
https://forum.arduino.cc/index.php?topic=486573.0

Thanks to all who replied to me, I have learned many things about ISR's and their limitations.


message:
mega2560- Interrupts reading digital input

Hi I am very new to Arduino, with very little programming experience.

I am using mega 2560 and trying to understand how interrupt works.

I have a code written, it is very similar as the example code Memsic2125, so i am gonna use that in here.

For my case, I am reading from my hardware, 5x5 array of sensors.

What I would like to do is to have it --   *print out x and y using interrupts*   , **I want to print outputs the x and y every 10ms. Instead of printing it continuously right now.**

I will be sending it out in 16 bits. I tried some other example and read a lot of material. but still couldn't get it to work.

Any idea, suggestion, help, comment is appreciated.
<!-- language-all: lang-cpp -->

    const int xPin = 2;
    const int yPin = 3;

    void setup() {

      Serial.begin(9600);
      pinMode(xPin, INPUT);
      pinMode(yPin, INPUT);
    }

    void loop() {

      int pulseX, pulseY;

      int x, y;

      // read pulse from x- and y-axes:
      pulseX = pulseIn(xPin, HIGH);
      pulseY = pulseIn(yPin, HIGH);

      x= ((pulseX / 10) - 500) * 8;
      y= ((pulseY / 10) - 500) * 8;

      // print x,y
      Serial.print("x,y= ( ");

      Serial.print(x);   Serial.print(,);
      Serial.print(y);   Serial.println(")");

      delay(100);
    }

body: There isn't any interrupt code in what you posted. What exactly is the problem?  One important note is that you shouldn't try to print to Serial line in the interrupt handler as serial is itself driven from interrupts which are switched off during your handler code.  If all you really want to do is to print something every 10ms then you don't need any interrupt.  Just use the "Blink Without Delay" style of timing and keep the other code from blocking.


body:
The simplest would-be to read the data and loop around for your desired time.

Alternatively, time stamp the events and onkybread the data if the desired time has elapsed.

Or to use a timer interrupt for that.


message:
Oscillating Analog Readings

I am using a JIC 139 UV Sensor ([datasheet](http://www.eoc-inc.com/ifw/JIC 137-138-139.pdf)) with an Arduino Mega 2560 and should be reading smooth curves as I bring a UV source to towards the sensor. Instead, my curves are increasing and oscillating. How can I remove the oscillations and what is the cause of these oscillations?

Code:

    float mapfloat(long x, long in_min, long in_max, long out_min, long out_max)
    {
        return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + out_min;
    }

    int averageAnalogRead(int pinToRead)
    {
        byte numberOfReadings = 8;
        unsigned int runningValue = 0;

        for(int x = 0 ; x < numberOfReadings ; x++)
            runningValue += analogRead(pinToRead);
        runningValue /= numberOfReadings;

        delay(100);

        return(runningValue);
    }

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

    void loop() {

       float pinRead0 = averageAnalogRead(0);
       float pVolt0 = pinRead0 / 1024.0 * 5.0;

       // In mW/m^2
       Serial.println(pVolt0);
       //  Serial.println(mapfloat(pVolt0, 0.0, 5.0, 0.0, 15.0));

       delay(100);
    }
`

Here is a sample screenshot from the Serial Plotter at 3 different distances from the UV Source:
[![enter image description here][1]][1]

Would post cicuit but don't have enough reputation. Will post as response.
  [1]: https://i.stack.imgur.com/4aXMI.png

**edit:** I added a very large capacitor(3300 uf) between the output pin and ground which seemed to smooth the values a little bit but the noise still exists

**edit:** The x-axis is number of readings and the y-axis is voltage(0-5v) calculated from analogRead()

body:
Without seeing circuit and construction details and oscilloscope traces, it's difficult or impossible to say what the problem is.  It may be due to op amp instability due to a large capacitive load.  It may reflect a beat frequency between some sensor and MCU signals, or aliasing between 60-Hz noise and your data-conversion rate.

Regarding op amp instability, see for example the article [*Op Amps Driving Capacitive Loads*, by Grayson King](http://www.analog.com/en/analog-dialogue/articles/ask-the-applications-engineer-25.html).  Here is a quote from that article:
>Q. *How does capacitive loading affect op amp performance?*
A. To put it simply, it can turn your amplifier into an oscillator. Here's how: [...]

Rather than just connecting that big 3300 μF capacitor to the output pin, perhaps instead try attaching an [Active Low Pass Filter](http://www.electronics-tutorials.ws/filter/filter_5.html) to the output, or a unity-gain op amp followed by a [Passive Low Pass Filter](http://www.electronics-tutorials.ws/filter/filter_2.html); etc.  Put big capacitors across power into the UV source and power into the sensor, instead of on the sensor output.

Regarding beat frequencies and aliasing, low-frequency oscillation like that seen in the trace may occur as a difference of two higher-frequency signals, or as a sampling artifact.  To check this out, attach an oscilloscope to the UV source and see if its power consumption oscillates; and/or try a more-rational sampling scheme than that shown in your code.

For example, instead of taking 8 readings within one millisecond in `averageAnalogRead()` and then waiting 100 ms, perhaps add a `delay(1)` inside the loop so that readings are spread out slightly more.  Remove the `delay(100)` from within `averageAnalogRead()`.  Compensate by changing the other `delay(100)` in `loop()` to, for example, `delay(191)` or `delay(193)`.  Try various delay amounts to see if they have an effect on the waveform.


message:
Connect Arduino Uno RX/TX to 3.3v NEO-M8N gps module

I'd like to connect an M8N gps module to an Arduino Uno. From what I understand

 - the Arduino pins 0-RX/1-TX work on 5V
 - the M8N RX/TX work on 3.3v
 - the sensor-TX sending to the Arduino-RX should work (3.3v is “good enough” to drive the Arduino-RX-pin)
 - the Arduino-TX sending to the sensor-RX is problematic because of the 5v (could break the sensor)
 - During USB-programming, the Arduino-RX sensor can be at 5v (so suddenly the current flows in the "wrong direction"- which could break the sensor)
 - A level-converter could be used to “translate” the voltages in each direction.

Assuming we don’t use a level-convertor

- Could we use a schottky-diode (which as I understand blocks current in 1 direction) to block the 5V from the ArduinoRX going into the sensor?
- But then the 3.3V from the sensor-TX would pass (correct direction ), but the diode will drop the voltage "a bit more"… is this still enough to drive the arduino RX-pin?

- And it works, why not also use a schottky-diode to also protect the Arduino-TX to sensor-RX connection ( just to be safe, since some people were saying one some Arduino they needed to connect RX-RX and TX-TX to get the communication to work.. ? ).

As an alternative to the schottky ( or maybe in addition to it)
- Could we simply take 2 voltage dividers (for one for both RX-TX and TX-RX) ?

We can use a “resistive voltage divider” to lower the Arduino-TX 5v to 3.3 V
- I understand to get from 5V to 3.3V we need “x” and “2 * x” resistors-values, so e.g 1K Ohm and 2K Ohm… but how do I know which values would be appropriate ( I mean, we could also take 10K Ohm and 20K Ohm, would also lead to 5V to 3.3v) but at a different current (Amps)… ?

- And what about a voltage-divider with a resistor and a capacitor (see https://en.wikipedia.org/wiki/Voltage_divider, low-pass RC filter)?
- What would be appropriate values for that solution for the resistor and capacitor?

Please be patient, electronics-beginner here trying to make sense of this…

body:
Buy some of these, it's a simple hardware solution to your problem then.

https://www.amazon.co.uk/gp/product/B0148BLZGE/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1

I know you said you don't want to use a level converter but it's the simplest way around the problem.
You stated that you're an electronics beginner AS AM I, which is exactly why when I came up against the same problem i just spent the money.
It was only £3.99 for 5 of them and as far as I'm aware you should be able to buy single ones off amazon too, haven't searched but i'd have thought you'd be able to.

Or if you need to do it with resistors you can use this calculator here

http://www.ohmslawcalculator.com/voltage-divider-calculator


body:
You can use something along the lines of this:

![schematic](https://i.stack.imgur.com/WMSnv.png)

When the 5V Rx is driven to 5V D1 protects the 3.3V Tx pin.

When the 5V Rx is driven to 0V R1 protects the 3.3V Tx pin from excessive current draw.

When the 5V Tx is driven to 5V D2 protects the 3.3V Rx pin and R2 pulls the pin to 3.3V.

When the 5V Tx is driven to 0V D2 pulls the 3.3V Rx pin to ~0.2 V

Resistor values are rough guidelines, lower values will put more strain on the parts and increase power draw but will also increase the maximum UART speed that will work reliably.


message:
How do I choose proper diodes for a 74HC595 shift register with a wired OR connection?

I want to use a [wired OR connection][1] to connect some pins of the 74HC595 shift register to an Arduino Digital Input Pin. How do I choose proper diodes for this situation?

* Maximum rated forward current has to be higher than whatever current a single pin of the 74HC595 produces.
* The `V_F` forward voltage drop has to be as low as possible to make sure that a HIGH from the shift register has still a voltage high enough to result in a HIGH at the Arduino pin after passing through the diode.
* Switching time has to be low enough to match the shift register's frequency.

So far, so good? What did I miss?

By the way, I haven't decided on the voltage for `VCC`, yet. Most likely, either `5 V` or `3.3 V`.

[![schematic][2]][2]

  [1]: https://en.wikipedia.org/wiki/Wired_logic_connection#The_wired_OR_connection
  [2]: https://i.stack.imgur.com/Zx2El.png

body:
For this, almost any diode will work.  Searching, it turns out that the [1N4148][1] is a popular ubiquitous choice.  But don't go out of your way to obtain this particular diode.

> Maximum rated forward current has to be higher than whatever current a
> single pin of the 74HC595 produces.

You should turn your thinking around.  Consider the nominal high voltage of the 74HC595, subtract the forward bias diode voltage drop (usually  0.7V for a silicon diode) and divide that by the resistor you pick.  That will be the current passing out of the 74HC595, through the diode and resistor.  Only a small amount of current will pass into the Arduino.  It should be negligible for most applications.  You should pick a resistor high enough to only allow milliamps of current to pass through this circuit.

> The V_F forward voltage drop has to be as low as possible to make sure
> that a HIGH from the shift register has still a voltage high enough to
> result in a HIGH at the Arduino pin after passing through the diode.

Check the voltage margin allow for a logical high input to the Arduino (Atmel processor).  I think 3V - 0.7V = 2.3V is still considered a logical high.  However, if you think this is too close, then switch to the 5 volt Arduino where the 0.7 volt drop will make less difference.

> Switching time has to be low enough to match the shift register's
> frequency.

I doubt this will be a problem.  That is, I doubt the CMOS logic will surpass the speed at which the diode can turn on / off.

  [1]: https://en.wikipedia.org/wiki/1N4148_signal_diode


message:
Possible ArduinoJson bug on ESP8266?

I'm making a small IOT project using the ESP8266 in which I make 2 API calls:

 1. api.openweathermap.org for weather data
 2. api.timezonedb.com

The request logic is the same for both calls, the only difference being how I parse the response string. The first response is parsed fine, while the other isn't.

 1. I print the String responses to Serial, they look fine.
 2. Tried both Dynamic and Static buffers to no avail.
 3. Making the request only to the second API, still not being parsed.
 4. If I make a test and just make the response a String, char[] or char*, it parses fine.

Parsing logic [works]:

    StaticJsonBuffer<1000> jsonBuffer;
    JsonObject& root = jsonBuffer.parseObject(response);
    float raw = root[String("main")][String("temp")].as<float>();

Parsing logic: [does not work]

    StaticJsonBuffer<500> jsonBuffer;
    JsonObject& root = jsonBuffer.parseObject(response);

    String data = root[String("formatted")].as<String>();

The response object looks like this:

    {
      "status": "OK",
      "message": "",
      "formatted": "2017-06-30 11:34:13"
    }

Request logic:

    String RequestAPI::performRequest(String url, char* host){
    WiFiClient client;
    if (!client.connect(host, port)) {
        lcd -> clearScreen();
        lcd -> drawText("Failed to connect to API", 0, 0, this -> randomUint16());
        delay(5000);
        return "";
    }

    char endOfHeaders[] = "\r\n\r\n";
    client.print(
    String("GET ") + url + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n"
    );
    // Skiping HTTP headers from the response
    client.find(endOfHeaders);

    unsigned long startTime = millis();
    while(client.available() == 0){
        if(millis() - startTime > this -> timeout){
            lcd -> clearScreen();
            lcd -> drawText("API request failed", 0, 0, this -> randomUint16());
            delay(5000);
            return "";
        }
    }

    String response = "";
    while(client.available()){
        response += client.readStringUntil('\r');
    }
    Serial.println(response);

    return response;
    }

Now I'm thinking, could the empty message be causing a bug? Or am I doing something wrong?

body:
The issue was caused because of: https://en.wikipedia.org/wiki/Chunked_transfer_encoding

Was not obvious as the data printed to the serial looked completely fine. Fixed with the below code:

    client.print(
      String("GET ") + url + " HTTP/1.0\r\n" +
      "Host: " + host + "\r\n" +
      "Connection: close\r\n\r\n"
    );

Dunno why it worked for one API but not the other though.


message:
Synchronising LEDs

Say I have 3 LEDs. I want LED1 to blink 5 times. At its third blink, LED2 should start blinking as well, also 5 times. While LED2 is at its 3rd blink, LED3 should start blinking. How do I do this in Arduino?
Here's what I have.

    int timeStep = 200; // delay time
    int myPins[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; // array with Pins
    int myPinsSize = sizeof(myPins) / sizeof(myPins[0]); // Length of my array
    int counter = 0;

    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      for (int i = 0; i < myPinsSize; i++) {
        pinMode(myPins[i], OUTPUT);
      }
    }

    // the loop function runs over and over again forever
    void loop() {
      LEDsequence();
      if(counter >= 9) {
        counter = 0;
      } else {
        counter++;
      }
    }

    void LEDsequence() {
      if(counter < 5) {
        switchOn(0);
      }
      if(counter >= 2 && counter < 7) {
        switchOn(1);
      }
      if(counter >=4 && counter < 9) {
        switchOn(2);
      }
      delay(timeStep);
      switchAllOff();
    }

    void switchOn(int index) {
      digitalWrite(myPins[index], HIGH);
    }

    void switchOff(int index) {
     digitalWrite(myPins[index], LOW);
    }

    void switchAllOff() {
      for (int i = 0; i < myPinsSize; i++) {
        digitalWrite(myPins[i], LOW);
      }
    }

body:
Since you have 3 leds, make a 2 dimensional array, first index for the leds (3), second for the period in which you want to have the led on or off.

E.g.

    const uint8_t NR_LEDS      = 3;
    const uint8_t TIME_PERIODS = 20;

    uint8_t period[NR_LEDS][TIME_PERIODS] = [
    // Time  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17, 18, 19
            {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // Led 1
            {0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, // Led 2
            {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }}; // Led 3

This means over 18 time periods, each state shows which led is on and off.
You can use HIGH or LOW, but that makes the lines too wide.

Now you can easily create a loop:

    void loop()
    {
      for (int period = 0; period  < TIME_PERIODS; period ++) // Time
      {
        for (int led = 0; led < NR_LEDS; led++)
        {
          switch(led, states[led, period ]); // set the led on or off
        }
        delay(1000); // 1 s
      }
    }

    void switch(uint8_t led, uint8_t state)
    {
      digitalWrite(led, state == 0 ? LOW : HIGH);
    }

So instead of switchOn and switchOff, use the switch and set it on or off by a parameter.

Also, this way it is very easy to change the schema (you can always visually see it in code). If you want longer schemes you can change the array into strings, like:

    char* period[NR_LEDS] = [
     // Time 0         10
     // Time 012345678901234567890
            "10101010100000000000", // LED 1
            "00001010101010000000", // LED 2
            "00000000101010101010", // LED 3

And check the index within the correct string and check for '0' and '1' instead of 0 and 1.

Since blinking is done for all leds 'in sync' (meaning during blinking leds change at the same time), you can also define a '1' as blink and '0' as off.

Than change:

    char* period[NR_LEDS] = [
     // Time 0         10
     // Time 012345678901234567890
            "10101010100000000000", // LED 1
            "00001010101010000000", // LED 2
            "00000000101010101010", // LED 3

to

    char* period[NR_LEDS] = [
     // Time 0         10
     // Time 012345678901234567890
            "111110000", // LED 1
            "001111100", // LED 2
            "000011111", // LED 3

And change the loop in

    void loop()
    {
      for (int period = 0; period < TIME_PERIODS; period ++) // Time
      {
        for (int led = 0; led < NR_LEDS; led++)
        {
          switch(led, states[led, period]); // set the led on or off
        }
        delay(500); // 0.5 s

        for (int led = 0; led < NR_LEDS; led++)
        {
           switch(led, '0');
        }
        delay(500); // 0.5 s
      }
    }

(use a constant for 0.5 s delay) and optionally create a function for the two small for loops above)


body:
Building on Michel's answer (this is a bit long to put in a comment):

Rather than using a 2 dimensional array or an array of strings (which is also a 2d array) it would be far more efficient to use a bitmask system.

    const uint8_t TIME_PERIODS = 20;
    const uint8_t NR_LEDS = 3;
    const uint8_t ledStates[] = [1,0,1,0,3,0,3,0,7,0,6,0,6,0,4,0,4,0,4,0];

and then the loop becomes:

      for (int period = 0; period < TIME_PERIODS; period++)
      {
        for (int led = 0; led < NR_LEDS; led++)
        {
          switch(led, ledStates[period] & 1<<led ); // set the led on or off
        }
        delay(500); // 0.5 s
      }

How this works:

`1<<led` will be 0001 in binary for led=0, 0010 for led = 1, 0100 for led = 2.

So if `ledStates[period]` was 3 (0011 in binary) then `ledStates[period] & 1<<led` will be non-zero for leds 0 and 1 and zero for led 2. The way the switch function is written any non zero value turns the LED on, 0 turns it off.

Why do it this way? Mainly size. Memory is always important, this uses 1 byte per state rather than 3. It could even be expanded to up to 8 LEDs without increasing the amount of memory used.


body:
> How do I do this in Arduino? Here's what I have.

easy:

1) write a routine that blink a pattern on a given pin;

something like this would work

    void myblinking(uint8_t pin, uint8_t *ptrn, uint8_t steps) {
      uint8_t index;

      pinMode(pin, OUTPUT);  //set pin as output
      for (index=0; index<steps; index++) {
        digitalWrite(pin, !digitalRead(pin)); delay(ptrn[index]); //flip pin, waste sometime
      }
    }

2. then all you need is to call that routine, like this:

      myblink(LED_PIN0, led_ptrn0, 10); //blink led_pin0, per led_ptrn0, for 10 steps
      myblink(LED_PIN1, led_ptrn1, 20); //blink led_pin1, per led_ptrn1, for 20 steps
      ...


message:
Arduino Mega 2560 with SIM808 module - Incomplete SMS response

I have this code to read a SMS:

    String read_SMS(int index)
    {
      Serial.println("--START READ SMS POSITION" + String(index) + "--");
      delay(400);
      sendATcommand("AT+CMGF=1", "OK", 1000);    // sets the SMS mode to text
      delay(2000);
      String tmp;
      tmp = readATcommand("AT+CMGR=1", 4000);
      Serial.println("Content: " + tmp);
      Serial.println("--END READ SMS POSITION" + String(index) + "--");
    }

    String readATcommand(String ATcommand, unsigned int timeout)
    {
      char response[800];
      unsigned long previous;
      memset(response, '\0', 800);    // Initialice the string

      int x = 0;

      GSMSerial.println(ATcommand);
      delay(3000);
      previous = millis();
      do {
        if (GSMSerial.available() > 0) {
          response[x] = GSMSerial.read();
          x++;
        }
      } while ((millis() - previous) < timeout);   // Waits for the asnwer with time out

      return (String) response;
    }

    // sending AT commands to the Sim808 module
    int8_t sendATcommand(String ATcommand, char* expected_answer, unsigned int timeout) {

      uint8_t x = 0, answer = 0;
      char response[200];
      unsigned long previous;

      memset(response, '\0', 200);    // Initialice the string

      delay(100);

      // Clean the input buffer
      while (GSMSerial.available() > 0 ) GSMSerial.read();

      if (ATcommand[0] != '\0') {
        // Send the AT command
        GSMSerial.println(ATcommand);
        //Serial.print(F("AT Command: "));
        //Serial.println(ATcommand);
      }

      // Waiting for the answer
      x = 0;
      previous = millis();

      do {

        // if there are data in the UART input buffer, reads it and checks for the asnwer
        if (GSMSerial.available() > 0) {

          response[x] = GSMSerial.read();
          x++;
          // check if the desired answer (OK) is in the response of the module
          if (strstr(response, expected_answer) != NULL) {
            answer = 1;
          }
        }

      } while ((answer == 0) && ((millis() - previous) < timeout));   // Waits for the asnwer with time out

      //Serial.println(F("START RESPONSE:"));
      //Serial.println(response);
      //Serial.println(F("END RESPONSE"));
      //if (answer == 0) {
      //  Serial.println("Could not get the expected answer!");
      //}
      //else {
      //  Serial.println("Found expected answer!");
      //}

      return answer;
    }

What can be wrong in the readATcommand function as it replies with an incomplete response:

    --START READ SMS POSITION1--
    Content:
    AT+CMGR=1

    +CMGR: "REC READ","+407245402XX","","17/06/29,10:
    --END READ SMS POSITION1--

But, when I run it from a terminal, the AT+CMGR=1 replies with:

    AT+CMGR=1

    +CMGR: "REC READ","+40724540234","","17/06/29,10:03:06+12"
    Salut

    OK

As you can see the message body is not there + the time of the SMS is also incomplete.

Thank you!

body:
Don't delay.

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

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

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


message:
Controlling an MCP41HV31 Digital Potentiometer

I need to control a 10kOhm digital potentiometer in rheostat mode in 256 steps. I found an Arduino tutorial, which works with an MCP41010 (I added a viper resistance according to the datasheet). This works fine - I can send values from 0 to 255 to the CS pin an the resistance between output pin A and B changes from 0 to 10kOhm.
The problem is, that my application requires 16V to go through this resistance, which the MCP41010 can't handle.

I tried to go with a [MCP41HVX1][3] high voltage digital potentiometer (which I soldered on a TSSOP-to-DIP Breakout board) and assumed it would work the same way. Turns out it doesn't... My connections are:

Arduino nano -> MCP41HVX1

- 10 -> CS
- 11 -> SDI
- 13 -> SCK
- 5V -> VL
- GND -> DGND

With the MCP41010 I connect a 115Ohm viper resistor between output pin A and wiper terminal and measure resistance between output pin A and B (pink connectors). I noticed, that the MCP41HVX1 has a different description for the rheostat modus but I can't get that to work either.

This is my circuit that works with the MCP41010
[![Arduino MCP41010  circuit][4]][4]

And here is the respective code (which sets the MCP41010 to 255 i.e. 10kOhm)
<!-- language-all: lang-cpp -->

    #include <SPI.h>
    byte address = 0x11;
    int CS= 10;

    void setup()
    {
      pinMode (CS, OUTPUT);
      SPI.begin();
    }

    void loop()
    {
      digitalPotWrite(255, CS);

    }

    int digitalPotWrite(int value, char Port)
    {
      digitalWrite(Port, LOW);
      SPI.transfer(address);
      SPI.transfer(value);
      digitalWrite(Port, HIGH);
    }

Has anyone ever done this or has a clue what's going on?

  [1]: http://www.instructables.com/id/Digital-Potentiometer-MCP41100-and-Arduino/
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/11195c.pdf
  [3]: http://cdn-reichelt.de/documents/datenblatt/A200/DS_MCP41HVX1.pdf
  [4]: https://i.stack.imgur.com/jyDke.png

body:
One thing I discovered, after coming back to the internet multiple times for clues, is that that SHDN pin on the MCP41HVX1 has to be tied HIGH.

If not, you can try incrementing, decrementing, or writing values to your heart's content and the thing is not going to budge.

I tied SHDN to the VL level via a 10k resistor and I can write and increment without problems.

I think it should have been flagged in the datasheet though, in the Pinout Description table.


body:
I realize that this thread is old. I am providing an answer for anyone else who may end up here like I did a while back looking to solve this.

I have created an Arduino library on Github (https://github.com/gregsrabian/MCP41HVX1) which allows for control of this family of chips. The README.md within the github project documents all of the APIs and also provides the wiring diagram. There are also example sketches included.

I have created an article on Instructables (https://www.instructables.com/id/MCP41HVX1-Digital-Potentiometer-for-Arduino/) that provides a step by step on how to control this family of chips. There is also an explanation on how to solder the TSSOP chip.


message:
What is an ICSP pin?

I have read that it is an AVR and a tiny programming header for the Arduino, but what is an AVR and what does an ICSP pin do?

body:
ICSP stands for *In Circuit Serial Programming*, which represents one of the several methods available for programming Arduino boards.  Ordinarily, an Arduino bootloader program is used to program an Arduino board, but if the bootloader is missing or damaged, ICSP can be used instead.  ICSP can be used to restore a missing or damaged bootloader.

A typical [Arduino ICSP header](https://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=1199&bih=663&q=arduino+icsp+header&oq=Arduino+icsp&gs_l=img.1.1.0l7j0i8i30k1l3.1229.4003.0.6313.8.8.0.0.0.0.129.579.5j1.6.0....0...1.1.64.img..2.6.577.0.NxIOJx-ygj) has six pins, arranged 2x3.  The article [Connecting the Programmer:
In-Circuit Serial Programming (ICSP)](https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader/connecting-the-programmer) at Sparkfun describes some of the functions of ICSP pins, which include MISO, MOSI, SCK, V+, Ground, and Reset.

Each ICSP pin usually is cross-connected to another Arduino pin with the same name or function.  For example, MISO on an Uno or Nano's ICSP header is connected to MISO / digital pin 12; MOSI on the ISCP header is connected to MOSI / digital pin 11; and so forth.  Note, MISO, MOSI, and SCK pins taken together make up most of an SPI interface.

Several Arduinos, including the Uno, have two ICSP headers.  One of them is for use with the ATmega328 (or similar), and the other for use with the ATmega16U2 (or similar) chip that implements USB. When present, this  allows reprogramming the USB chip.

---

[AVR](https://en.wikipedia.org/wiki/Atmel_AVR) refers to the instruction set architecture used in a family of Atmel microcontrollers.  Several Arduinos  – Mega, Uno, Nano, Micro – use AVR chips.  Others, like the Zero and Due, instead use ATSAM3 chips, with an [ARM instruction set architecture](https://en.wikipedia.org/wiki/List_of_ARM_microarchitectures).


message:
Two Arduinos get out of sync after a few seconds

I built a small PCB that has some LEDs (bare NeoPixel 5050) and an IR receiver on it. The microcontroller is an ATtiny85, and the PCB is powered by a LiPoly battery (3.7V). The circuit normally stays in ULP sleep mode until a pin change interrupt wakes the circuit. The pin change interrupt is tied to the IR receiver so when the receiver gets a signal from a remote (38kHz modulated IR burst) a lighting sequence is triggered. I have multiple of these PCBs running the exact same code (shown below). When the PCBs receive an IR signal they all start at the same time, but then after a few seconds they start to drift apart. The lighting needs to be synchronized. What is the reason for this drift and how can I eliminate it? Is it due to different battery voltages? That would be the only physical difference between any two PCBs. Thanks for your help.

    #define IR_PIN      4
    #define LIGHT_PIN   0
    #define DELAY_TIME  200

    #include <Adafruit_NeoPixel.h>
    #define NUM_PIXELS  2
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_PIXELS, LIGHT_PIN, NEO_GRB + NEO_KHZ800);

    #include "avr/interrupt.h"
    #include "avr/sleep.h"

    void setup() {
      pinMode(IR_PIN, INPUT);
      strip.begin();
      pixelsOff();
    }

    void loop() {
      sleep();

      for (int i = 0; i < 5; i++) {
       pixelsOnRed();
       delay(DELAY_TIME);
       pixelsOff();
        delay(DELAY_TIME);
       pixelsOnGreen();
       delay(DELAY_TIME);
       pixelsOff();
        delay(DELAY_TIME);
      }

      for (int i = 0; i < 5; i++) {
       pixelsOnBlue();
       delay(DELAY_TIME);
       pixelsOff();
        delay(DELAY_TIME);
       pixelsOnRed();
       delay(DELAY_TIME);
       pixelsOff();
        delay(DELAY_TIME);
      }

      for (int i = 0; i < 5; i++) {
       pixelsOnGreen();
       delay(DELAY_TIME);
       pixelsOff();
        delay(DELAY_TIME);
       pixelsOnRed();
       delay(DELAY_TIME);
       pixelsOff();
        delay(DELAY_TIME);
      }
    }

    void pixelsOff() {
      strip.setPixelColor(0, 0, 0, 0);
      strip.setPixelColor(1, 0, 0, 0);
      strip.show();
    }

    void pixelsOnRed() {
      strip.setPixelColor(0, 255, 0, 0);
      strip.setPixelColor(1, 255, 0, 0);
      strip.show();
    }

    void pixelsOnGreen() {
      strip.setPixelColor(0, 0, 255, 0);
      strip.setPixelColor(1, 0, 255, 0);
      strip.show();
    }

    void pixelsOnBlue() {
      strip.setPixelColor(0, 0, 0, 255);
      strip.setPixelColor(1, 0, 0, 255);
      strip.show();
    }

    ISR(PCINT0_vect)
    {
        //This is not needed for the current sketch
    }

    void sleep() {
        GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
        PCMSK |= _BV(PCINT4);                   // Use PB3 as interrupt pin
        ADCSRA &= ~_BV(ADEN);                   // ADC off
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

        sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
        sei();                                  // Enable interrupts
        sleep_cpu();                            // sleep

        cli();                                  // Disable interrupts
        PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
        sleep_disable();                        // Clear SE bit
        ADCSRA |= _BV(ADEN);                    // ADC on

        sei();                                  // Enable interrupts
    }

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

two solutions:

1) try using crystal oscillators;

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


body:
*Assuming internal RC oscillator:*

In the datasheet:

> By default, the Internal RC Oscillator provides an approximate 8.0 MHz clock. **Though voltage and temperature
dependent,** this clock can be very accurately calibrated by the user. See “Calibrated Internal RC Oscillator Accuracy”
on page 164 and “Internal Oscillator Speed” on page 192 for more details. The device is shipped with the
CKDIV8 Fuse programmed. See “System Clock Prescaler” on page 31 for more details

And page 192 shows a graph of frequency vs voltage.

On 164 it says:

> It is possible to manually calibrate the internal oscillator to be more accurate than default factory calibration. **Please
note that the oscillator frequency depends on temperature and voltage. Voltage** and temperature characteristics
can be found in Figure 22-40 on page 193 and Figure 22-41 on page 193.

So yes, conclusive evidence there that the voltage will affect the frequency.


body:
Other answers have noted that the internal RC oscillator's frequency is voltage and temperature dependent.  If you have good control over voltage and temperature, consider manually or automatically calibrating the clocks of your several ATtiny85's.

Absent that control, consider adding crystals or ceramic resonators to your circuits, or set up a synchronization protocol using IR.  For example, if your IR transmitter is programmable, have it send a synchronization character as often as necessary to adequately synchronize the lights.  If your IR transmitter is not programmable, add an IR LED and driver to one or more of your ATtiny85's, and send synchronization characters at regular intervals.


message:
HC-05 emit data without pairing

Is it possible to emit data from an arduino connected to a hc-05 Bluetooth module without pairing it to another device?
i.e. imagine that I want to send a Bluetooth signal as if it was a information spot. Then whoever who gets the signal can read it.

body: No. The HC-05 has to be paired. It runs on Bluetooth 2.x which requires pairing.  What you want is BLE (or Bluetooth 4.x) which has various "beacon" facilities.


message:
String to persistent memory (EEPROM?)

I am creating a server node that I want to be able to save the wifi SSID and the password into persistent memory so that when it starts ups it can connect to the network. I have looked for several hours and found just a few bits of information. One bit I found here http://playground.arduino.cc/Code/EEPROMWriteAnything

    #include <EEPROM.h>
    #include <Arduino.h>  // for type definitions

    template <class T> int EEPROM_writeAnything(int ee, const T& value) {
        const byte* p = (const byte*)(const void*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
              EEPROM.write(ee++, *p++);
        return i;
    }

    template <class T> int EEPROM_readAnything(int ee, T& value) {
        byte* p = (byte*)(void*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
              *p++ = EEPROM.read(ee++);
        return i;
    }

This code will not store String values to the EEPROM. So as I thought I would ask for advice from the Stack Exchange geniuses.

Thanks!

body:
[EEPROM](https://www.arduino.cc/en/Reference/EEPROMPut) library has two functions `put` and `get` , which can help you store character array of any size, not exceeding the size of internal EEPROM size of Arduino. Please see the examples provided in the link above.

Here is a sample code to get you going.

    int address = 10;
    char arrayToStore[20];                    // Must be greater than the length of string.
    String testString = "hello there";

    testString.toCharArray(arrayToStore, testString.length()+1);  // Convert string to array.

    EEPROM.put(address, arrayToStore);                 // To store data
    EEPROM.get(address, arrayToStore);                 // To read data


message:
Serial Communication between ESP8266 and Arduino Uno

I want to send data from arduino to ESP8266. I have done all the RX and TX connections.
The problem is that data is not sent every second, it stops after a single byte. When I remove the arduino cable then data is read.

My Arduino Code :

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

    void loop() {

        Serial.write("50");
        delay(1000);
    }

My ESP8266 Code :

    void setup() {

    Serial.begin(9600);

      // connect to wifi.
      WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

      while (WiFi.status() != WL_CONNECTED) {

        delay(500);
      }
      Serial.println("Connected !");

    }

    void loop() {

     Serial.print(Serial.readString());

    }

body:
Since you are  Arduino Uno, it has only one `Serial`. This Serial can be used to transmit data in USART mode to another Serial Device as well as see any Debug data in the Serial terminal.

However, both the functionality can not be used simultaneously. The Tx Rx pair of Arduino can be connected to one pair of other device i.e. either to the computer via the cable or to the Tx Rx of ESP8266.

But if you really need to plug in the Uno to the computer and send data to ESP8266 simultaneously, then you have to use [SoftwareSerial](https://www.arduino.cc/en/Reference/SoftwareSerial) library to convert any digital pin to Tx Rx pin, and connect them to ESP8266 for transmitting data.


body:
As explained by goddland_16. Using Software Serial library will solve the issue. Code is given below. By Initializing other digital pin as communication pin, Interupption between Tx and Rx and to ESP8266 is seperated.

**Arduino UNO / Nano Code :**

    /*
     * bismillah hir rahman nir raheem
     * UNO/Nano = Pin 7 & Pin 8
     * Note: Uno and ESP8266 cross connection
     */

    #include <SoftwareSerial.h>

    SoftwareSerial ArduinoUno(7,8);
    String f;

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

    void loop() {
        float i = (random(100) + 1);
        float j = (random(100) + 1);

        f = String('H') + String(i) + String('T') + String(j);
        ArduinoUno.println(f);
        delay(2000);
    }

**ESP8266 Code :**

    /*
     * bismillah hir rahman nir raheem
     * ESP8266 = Pin D7 & Pin D8
     * Note: Uno and ESP8266 cross connection
     */

    #include <SoftwareSerial.h>
    #include <ESP8266WiFi.h>

    SoftwareSerial NodeMCU(D7,D8);

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

     pinMode(D7,INPUT);
     pinMode(D8,OUTPUT);
    }

    void loop() {
        String content = "";
        char character;

        while (NodeMCU.available()) {
           character = NodeMCU.read();
           content.concat(character);
        }

        if (content != "") {
            Serial.println(content);
        }

        Serial.println("Temperature");
        Serial.println(content.substring(1, 6));
        Serial.println("Humidity");
        Serial.println(content.substring(7, 12));
        delay(2000);
    }


message:
error: expected unqualified-id before '.' token

I am working on a library to display custom text on a TFT screen and I came up with this error while making an example:

    EsploraHelloWorld:31: error: expected unqualified-id before '.' token
       TFTCharPlus.drawChar(chars[5, 0], chars[5, 1], chars[5, 2], chars[5, 3], chars[5, 3], 120, 0, 255, 255, 255, 4, EsploraTFT);
                   ^

Heres my code:

    #include <Esplora.h>
    #include <SPI.h>
    #include <TFT.h>
    #include <TFTCharPlus.h>

    // A table for all of the characters
    const char chars[6][5] = {
      {0xf8, 0x20, 0xf8, 0x1f, 0x15},
      {0xf8, 0x08, 0x08, 0x1f, 0x01},
      {0x70, 0x88, 0x70, 0x00, 0x00},
      {0xc0, 0x20, 0xc6, 0x29, 0xc6},
      {0xf0, 0x40, 0x80, 0x5f, 0x01},
      {0xf0, 0x90, 0x60, 0x00, 0x3d}
    };

    TFTCharPlus TFTCharPlus();

    void setup() {
      // initialize the screen
      EsploraTFT.begin();

      // make the background black
      EsploraTFT.background(0,0,0);

      // print the characters
      TFTCharPlus.drawChar(chars[0, 0], chars[0, 1], chars[0, 2], chars[0, 3], chars[0, 3], 0, 0, 255, 255, 255, 4, EsploraTFT);
      TFTCharPlus.drawChar(chars[1, 0], chars[1, 1], chars[1, 2], chars[1, 3], chars[1, 3], 24, 0, 255, 255, 255, 4, EsploraTFT);
      TFTCharPlus.drawChar(chars[2, 0], chars[2, 1], chars[2, 2], chars[2, 3], chars[2, 3], 48, 0, 255, 255, 255, 4, EsploraTFT);
      TFTCharPlus.drawChar(chars[3, 0], chars[3, 1], chars[3, 2], chars[3, 3], chars[3, 3], 72, 0, 255, 255, 255, 4, EsploraTFT);
      TFTCharPlus.drawChar(chars[4, 0], chars[4, 1], chars[4, 2], chars[4, 3], chars[4, 3], 96, 0, 255, 255, 255, 4, EsploraTFT);
      TFTCharPlus.drawChar(chars[5, 0], chars[5, 1], chars[5, 2], chars[5, 3], chars[5, 3], 120, 0, 255, 255, 255, 4, EsploraTFT);
    }

    void loop() {
      // not necessary
    }

And for reference, here is the `drawChar()` function:

    void TFTCharPlus::drawChar(byte data1, byte data2, byte data3, byte data4, byte data5, uint8_t xpos, uint8_t ypos, uint8_t colR, uint8_t colG, uint8_t colB, uint8_t size, TFT tft) {
      tft.stroke(colR, colG, colB);
      tft.fill(colR, colG, colB);
      byte data[5] = {data1, data2, data3, data4, data5};
      for (uint8_t x = 0; x < 5; x++) {
        for (uint8_t y = 0; y < 8; y++) {
          if (bitRead(data[x], 7 - y)) {
            tft.rect(x*size+xpos, y*size+ypos, size, size);
          }
        }
      }
    }

How can I fix the error?

**BTW**: The error is not in the library, everything is done correctly

**EDIT**: I realized that the error occurs on all six `drawChar()` lines, and After fixing a small error, I also got this:
`request for member 'drawChar' in 'TFTCharPlus', which is of non-class type 'TFTCharPlus()'`

body:
It appears that you are calling the "description" of the library method (function).  What is necessary is to use the "description" to create a "working copy" of the library method.  Then call the "working copy".

In the above statement, the "description" is the Class, "to create" means to instantiate and "working copy" is referred to as the Object.

In the [Arduino Serial Port Example][1], you will find the following line:

    SoftwareSerial mySerial(10, 11); // RX, TX

Here, the Class "SoftwareSerial" is used to instantiate the Object "mySerial".  Later in the code calls are made to the "write" method with in that object:

    mySerial.write(Serial.read());

  [1]: https://www.arduino.cc/en/Tutorial/SoftwareSerialExample


body:
In this line:

    TFTCharPlus TFTCharPlus();

you've given your TFT object the same name as its class, making that name ambiguous. If you change the name of the object to, e.g.:

    TFTCharPlus TFTobject();

 as well as changing all of your references to it (`TFTobject.drawChar(...)`), it should fix the issue.


message:
Power a Raspberry Pi 3 from an Arduino Uno

I would like to power my Raspberry Pi 3B using an Arduino Uno.

I have been able to do this by connecting the 5v on the Arduino to the 5 V on the Pi and connecting the GND to GND, and the Pi turns on. But I get a constant under voltage sign.

How can I get the Arduino to output the right amount of power (5 V and 2.5 A)?

body:
If you are using PC USB, your total current cap is <500mA. Arduino + Pi + accesories is exceed this cap.

Use an adapter for Arduino. Ardiuno will suck up some current and rest can flow to Pi or whatever else is there.

Arduino has a linear voltage regulator. Try not to use >5v adapters. Voltage regulator will generate more heat as more current pass.


body:
You can't.

The on-board regulator of the Uno, the NCP1117, is only able to supply up to 1A before starting to dropout voltage (hence your undervoltage warning).

Even worse, because the NCP1117 lacks a proper heatsink, it will probably start dropping out voltage before reaching 1A, due to its internal thermal shutdown protection.


body:
If you reverse which board gets the power adapter you should be able successfully power them both from a single 5V 2.5A power supply.

Connect the power adapter to the Raspberry Pi3 and power the Arduino from the Pi's 5V pin.  The Uno should only draw about 200mA @ 5V from the Pi (depending on everything else you have connected).


message:
Trying to communicate with an ESP8266

G'day guys, I'm trying to get an ESP8266 to work with an Arduino Uno.
Here is the wiring.

[![wiringPicture][1]][1]

  [1]: https://i.stack.imgur.com/JV3sP.png

When I go to the serial monitor (115200 baud) and type: AT, there is not response from the ESP8266.

Is there something that I am missing?

I also have a servo motor connected, it works fine.

    include "Arduino.h"
    include "ESP8266.h"
    include "dweet.h"
    include "Servo.h"

    define ESP8266_PIN_RX 10
    define ESP8266_PIN_TX 11
    define SERVO9G_PIN_SIG 2

    const int servo9gRestPosition   = 20;
    const int servo9gTargetPosition = 150;
    const char *SSID     = "Wireless Network";
    const char *PASSWORD = "wireless_password";

    ESP8266 wifi(ESP8266_PIN_RX,ESP8266_PIN_TX);
    Servo servo9g;

    const int timeout = 10000;
    char menuOption = 0;
    long time0;

    void setup()
    {
       Serial.begin(9600);
       while (!Serial); //await connection.
       Serial.println("start");

       wifi.init(SSID, PASSWORD);
       servo9g.attach(SERVO9G_PIN_SIG);
       servo9g.write(servo9gRestPosition);
       delay(100);
       servo9g.detach();

    }

    void loop()
    {
       servo9g.attach(SERVO9G_PIN_SIG);
       servo9g.write(servo9gTargetPosition);
       delay(500);
       servo9g.write(servo9gRestPosition);
       delay(500);
       servo9g.detach();
    }

I'm using the ESP8266 Library.
When trying to connect it just says `Initializing device...`

body:
Unless you have some project constraints which make it mandatory to use naked ESP8266, why not use a NodeMCU to communicate with the Arduino in a master/slave relation over I2C?

[![enter image description here][1]][1]

    #include <Wire.h>
    #define I2CAddressESPWifi 8

in `setup()`

    Wire.begin(D1,D2); // SCL D1 SDA D2

then call from anywhere inside your `loop()` call this function

 char readSlave(int x) { // send current time
   String xY = String(x);
   char c;
   int charArrayLength = xY.length()+1;
   char bufferChar[charArrayLength];
   Wire.beginTransmission(8);
   xY.toCharArray(bufferChar, charArrayLength);
   Wire.write(bufferChar);
   Wire.endTransmission();
   delay(10);
   Serial.print("wire sent: [");
   Serial.print(x);
   delay(50);//Wait for Slave to calculate response.
   int counter = 0;
   char buffMe[32];
   int bytesIn = Wire.requestFrom(8,32);
   while (Wire.available()) {
     delay(2);
     buffMe[counter] = Wire.read();
     /*
     c = Wire.read();
     Serial.print(c);
     */
     counter++;
   }
   delay(10);
   Wire.endTransmission();
   delay(500);
   Serial.print("] bytesIn: [");
   Serial.print(bytesIn);
   Serial.print("] buffMe: [");
   Serial.print(buffMe);
   Serial.print("]");
      return buffMe;
    }

and your arduino will be waiting (`setup`)

 Serial.begin(9600);
 // slave listens for call from master NodeMCU
 Wire.begin(I2CAddressESPWifi);  // predefined as `8` or whatever address you choose
 Wire.onReceive(receiveEvent);
 Wire.onRequest(requestEvent);

and at the end of your code

 void receiveEvent(int howMany) {
   if (howMany) {
     Serial.print("bytes[");
     Serial.print(howMany);
     Serial.print("] Received[");
     char charIn[howMany];
     int counter = 0;
     while (Wire.available()) {
       char c = Wire.read();
       charIn[counter] = c;
       //Serial.print(c);
       counter++;
     }
     delay(10);
     //do something with command from master
   }
 }
 void requestEvent() {
   char bufferChar[20] = "slave answer string";  // automatically null terminated extra character at end
   Serial.println(bufferChar);
   Wire.write(bufferChar);
 }

  [1]: https://i.stack.imgur.com/GFLO6.png


message:
Repeatedly checking multiple "if" statements

This code is part of a long code for a robot that is both obstacle-avoiding and remote control. I am trying to get the code to check both "if" statements when the code number FF807F is received from an IR remote. When the code number is received
the program checks both "if" statements and carries out the one that is true. I want the program, once it has finished carrying out the true "if statement, to check both "if" statements again.

    void loop () {
    if (My_Decoder.value==0xFF807F){
     if (cm<6)
     {
      motor_stop();
      digitalWrite(backlights, HIGH);
      delay(2000);
      motor_backward();
      digitalWrite(backlights, HIGH);
      Serial.println("backward");
      delay(2000);
      motor_stop();
      digitalWrite(backlights, HIGH);
      delay(900);
      motor_right();
      digitalWrite(backlights, LOW);
      Serial.println("right");
      delay(1000);
    }
    if (cm>6)
     {
      motor_forward();
      digitalWrite(backlights, LOW);
      Serial.println("forward");
    }
    }
    }

body:
Your are missing the case when "cm == 6".

You don't need to do two "if"; one "if-else" is enough because is either one or the other.

You don't have/need to check twice; "cm" doesn't change inside the "if". But i you want, use functions:

    void loop () {
      if (My_Decoder.value == 0xFF807F) {
        doSomething();
        doSomething();
      }
    }

    void doSomething() {
      if (cm < 6) {
        motor_stop();
        digitalWrite(backlights, HIGH);
        // ...
        delay(1000);
      } else {
        motor_forward();
        digitalWrite(backlights, LOW);
        Serial.println("forward");
      }
    }


body:
I am going to assume you don't want to include `cm == 6` which is why you have both cases. I would consider using a while loop instead of a singular 'if' statement in order to continuously check if those buttons are being pressed or not (`while (cm<6){do this stuff}`). Otherwise, it will check once and never check again.

Instead it will jump down to the next 'if' statement, it will fail and then jump to the top of the loop where it will check for the code 0xFF807F. Let me know how it goes!


body:
    if (My_Decoder.value == 0xFF807F) {
    if (cm<6)

Are you wanting both "ifs" to occur? Maybe a bitwise operator like logical AND (`&`)?


body:
This looks like a good use for a State Machine.

It would look something like this:

```c++
typedef enum State
{
  STATE_IDLE,
  STATE_THIS,
  STATE_THAT,
  STATE_OTHER
} State;

State state;

const int IR_BUTTON_1    = 0xFF807F;
const int IR_BUTTON_2    = 0x112233;
const int IR_BUTTON_3    = 0X445566;
const int IR_BUTTON_STOP = 0x778899;

void setup()
{
  Serial.begin(115200);
  Serial.println(F("setup()"));
  state = STATE_IDLE;
}

void loop()
{
  Serial.println(F("loop()"));

  switch(my_decoder.value)
  {
    case IR_BUTTON_1:
      state = STATE_THIS;
      Serial.println(F("Entered STATE_THIS"));
      break;
    case IR_BUTTON_2:
      state = STATE_THAT;
      Serial.println(F("Entered STATE_THAT"));
      break;
    case IR_BUTTON_3:
      state = STATE_OTHER;
      Serial.println(F("Entered STATE_OTHER"));
      break;
    case IR_BUTTON_STOP:
      state = STATE_IDLE;
      Serial.println(F("Entered STATE_IDLE"));
      break;
  }

  switch(state)
  {
    case STATE_THIS:
      DoThis();
      break;
    case STATE_THAT:
      DoThat();
      break;
    case STATE_OTHER:
      DoOther();
      break;
  }
}

void DoThis()
{
  Serial.println(F("DoThis()"));
}

void DoThat()
{
  Serial.println(F("DoThat()"));
}

void DoOther()
{
  Serial.println(F("DoOther()"));
}
```
This locks the state machine into an active state as per the [OP's comment][1]:
 >  I want it to repeat the "void doSomething();" function until another button is pressed.

However, as Dave Newton pointed out in the comments, locking a machine into a particular active state can be dangerous, so I've edited the code to add a STOP button to transition back to the IDLE state. But this still relies on the operator pressing the STOP button to return to idle; there is no automatic return to idle which could be a hazard depending on the application.

  [1]: https://arduino.stackexchange.com/questions/40128/repeatedly-checking-multiple-if-statements/84361?noredirect=1#comment81907_40131


message:
Arduino code to control 4 led's from 4 buttons

This is my very first arduino sketch and it's causing me a bit of a headache.
Sounds so simple really all I want the sketch to do is digitalread from one of 4 digital input pins and then digitalwrite to one of 4 output pins in essence.
So that when button 1 is pressed LED 1 lights up, button 2 pressed led 2 lights up and so on.
I've added a serial write so I could check that the buttons are actually working when pressed.

The code I've written:

<pre>const int buttonPin1 = 7;     // number of pushbutton 1 pin
int buttonState1 = LOW;       // set the default variable value for pushbutton1 status
const int ledPin1 =  6;       // number of the LED 1 pin
const int buttonPin2 = 8;     // number of pushbutton 2 pin
int buttonState2 = LOW;       // set the default variable value for pushbutton2 status
const int ledPin2 =  9;       // number of the LED 2 pin
const int buttonPin3 = 4;     // number of pushbutton 3 pin
int buttonState3 = LOW;       // set the default variable value for pushbutton3 status
const int ledPin3 =  5;       // number of the LED 3 pin
const int buttonPin4 = 2;     // number of pushbutton 4 pin
int buttonState4 = LOW;       // set the default variable value for pushbutton4 status
const int ledPin4 =  3;       // number of the LED 4 pin

void setup() {                  // Set Pins to Outputs Or Inputs
  pinMode(buttonPin1, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin1, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin2, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin2, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin3, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin3, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin4, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin4, OUTPUT);     // initialize the LED pins as an outputs:
  Serial.begin(9600);           // initialize serial communication at 9600 baud
}

void loop() {

  buttonState1 = digitalRead(buttonPin1);  // read current states of the pushbutton value:
  buttonState2 = digitalRead(buttonPin2);  // read current states of the pushbutton value:
  buttonState3 = digitalRead(buttonPin3);  // read current states of the pushbutton value:
  buttonState4 = digitalRead(buttonPin4);  // read current states of the pushbutton value:

  // check if the pushbutton is pressed buttonState# == HIGH/LOW
  // if pressed change buttonState == HIGH to turn on ledPin#
  // else if buttonState == LOW then digitalWrite(ledPin#, LOW) Keeps Led off.

    if (buttonState1 == HIGH) {    //check buttonState
    digitalWrite(ledPin1, HIGH);  //if HIGH turn LED on:
    } else {
    digitalWrite(ledPin1, LOW);   // turn LED off:
    }
    Serial.println(buttonState1); //Print buttonState to serial
    if (buttonState2 == HIGH) {   //check buttonState
    digitalWrite(ledPin2, HIGH);  //if HIGH turn LED on:
    } else {
    digitalWrite(ledPin2, LOW);   // turn LED off:
    delay(10);
    }
    Serial.println(buttonState2); //Print buttonState to serial
    if (buttonState3 == HIGH) {   //check buttonState
    digitalWrite(ledPin3, HIGH);  //if HIGH turn LED on:
    } else {
    digitalWrite(ledPin3, LOW);   // turn LED off:
    delay(10);
    Serial.println(buttonState3); //Print buttonState to serial
    }
    if (buttonState4 == HIGH) {   //check buttonState
    digitalWrite(ledPin4, HIGH);  //if HIGH turn LED on:
    } else {
    digitalWrite(ledPin4, LOW);   // turn LED off:
    delay(10);
    Serial.println(buttonState4); //Print buttonState to serial
    }

The Leds all have a common GND and the buttons all have a common GND.
Buttons are connected to +5V & Input pin# so one terminal has got two wires,
Led's are connected to digital output pins then resistor and straight to GND.
What happens is that ALL of the LED's come on when any one of the 4 buttons in pressed.

I've attempted to edit some of the code in the example sketches to get this to work.

Can anyone suggest anything that I'm doing wrong?
Or ammend the code sp that I can see where I'm going wrong.

body:
It is likely you have connected the switches incorrectly.  Normally, people use [single poll single throw (SPST) switches][1] connected to 5 volts and the input pin of the Arduino.  This will pull the input pin to 5 volts when the switch is closed.  Then, to pull the input pin to ground when the switch is open, people add a large resistor between ground and the same processor pin.

[![enter image description here][2]][2]

Almost any large resistor will work here.  Consider using 10K ohms (10,000 ohms) or there abouts.

Of course, if you are using a 3 volt Arduino, do not connect the switch to a 5 volt source.  Instead connect it to a 3 volt source.

Alternatively, a pull up resistor inside the processor, if available, can be activated.  Look at [this arduino.cc web page][3]. There this sample code shows how to activate the processor's pull up on pin number 2:

    pinMode(2,INPUT_PULLUP);

Because not all processors have a "pull up" feature on all input pins & because the range of internal to the processor pull up resistances can vary (for example 50,000 ohms to 150,000 ohms), it may be more useful and universal to use an external pull up resistor.

  [1]: https://en.wikipedia.org/wiki/Switch#Contact_terminology
  [2]: https://i.stack.imgur.com/VpRNc.png
  [3]: https://www.arduino.cc/en/Tutorial/InputPullupSerial


body:
Get rid of the external resistors, use the internal pullup resistor.

In setup():

pinMode (pinX, INPUT_PULLUP);

Wire the button between input pin pinX and Gnd, then test for a LOW to see if the button is pressed in loop():

if (digitalRead (pinX) == LOW){ // button is pressed

// do something

}

else { // button is not pressed

// do something else

}


body: I would suggest taking the resistor/s off the switches, so the button connects to digital inputs to the 3v/5v line. Then use 470ohm resistors for the leds(to limit the current) on the digital outputs.


message:
mcufriend 2.4 TFT with ESP8266

I have this TFT:

[![enter image description here][1]][1]

Now, the problem is, I will not use this as a shield (i.e. I will not just put it on top of an Arduino Uno). I will use it with an ESP8266 (NodeMCU). I want to know how to wire them up together. There is [this website][2] (and a few more that say the same way). But the problem is I cannot find `SDI/MOSI` or `SDD/MISO` on the TFT above.

  [1]: https://i.stack.imgur.com/9Dxot.jpg
  [2]: http://www.nihamkin.com/2016/03/04/connecting-esp8266-with-ili9341-tft-display/

body:
You have an 8-bit parallel interface TFT display. It requires 13 GPIO pins - D0-D7 plus reset, chip select, read, write and register select. You can forego the "read" signal and tie it high to save a pin. You can probably do the same with the reset signal, meaning you need a minimum of 11 pins.

I am not sure the NodeMCU has that many available, does it? (maybe it does, I don't have one to hand right now), so you may want to try getting it going with an SPI or I2C IO expander (though slowly).

And then of course you have to find the right library for the chip on the display (there's a few it could be - I have seen at least 3 different ones on the same, or similar, carrier PCB) that works with the NodeMCU.


body: SD_DI is the MOSI, and SD_DO is the MISO. According to the datasheet.


message:
Making a 7-hour timer-based relay

I want to make a very small 7-hour timer circuit that can turn on a relay after 7 hours. I am trying to make the first prototype with an Arduino Nano but I can't understand how to program it for such purpose. So please help me out.

Once I make a prototype in Arduino then I was thinking to make a small one  using an ATtiny13. Can I use an ATtiny13 for such purpose?

body:
> cant understand how to program it for such purpose so please help me out

it is fairly easy to approach such questions:

1) you can program any?

2) can you program this mcu to blink an led?

3) can you program this mcu to do short time counting?

4) can you program this mcu to do long time counting?

what you help helps you the most depends on your  answers to those questions.


body:
The question is whether its a one shot triggering ON the relay after 7 hours and thereafter you always leave it ON or its some periodic process where every 7 hours, you want the relay to trigger ON and OFF alternatively. Presuming the latter, this can be done in 2 ways:

1) Configure a hardware timer interrupt to call a small function every second and increment a variable within that function. So after 1 hour your variables value must be 3600, therefore after 7 hours it will be 25,200. Once the variable is equal to 25200, you can ON the relay and reset the variable to 0. Factors such as the number of hardware timers and its resolution differs from one MCU to another.

2) Use a Real Time Clock like the DS1307 for this purpose and save you hardware timers for performing some other time critical operations.

Hope this helps!.


message:
Micro servo is not working with Arduino UNO

I am new to Arduino and trying to do some basic tasks. I want a micro servo to rotate but it's not working, only slightly virbating when I launch a sketch. Below on the photos is how it is all assembled: I have a jumpwires connected to GND, 5V and #8 ports just as in the tutorial. I use micro servo SG-90 and Funduino UNO. Does anybody have any ideas what might the problem be? Here is also the sketch.

    #include <Servo.h>

    Servo servo;

    void setup() {
      // put your setup code here, to run once:
    servo.attach(8);
    }

    void loop() {
       // put your main code here, to run repeatedly:
    servo.write(0);
    delay(2000);
    servo.write(90);
    delay(2000);
    }

[![enter image description here][1]][1]
  [1]: https://i.stack.imgur.com/WygeG.jpg

body:
You should not power a servo from a USB port.

However, your most glaring problem is that you have entirely mis-wired the connections, such that no wire is going to the correct place.

Servo connections are in the order of `Ground` - `Power` - `Signal`, usually with a dark color for ground and a redder one for power.  Connector shells aren't standardized between brands, but within one there may be keying to prevent reverse installation.

It would appear that on your servo, `ground` is brown, `power` red, and `signal` orange.

Pull out all three wires and start over; also you'd do well to use a dark color for the ground, as you appear to have mixed up the power and ground as well as the signal.


message:
How can I define integer inputs to a function and get array as an output?

I am trying to write a function that takes integer values as an input and gives an array as an output. I have tried the following code but it doesn't show the output result in the serial monitor:

    int *phi (int cur,int vol,int t) {
      int z[4];
      z[0]=1;
      z[1]=cur;
      z[2]=vol;
      z[3]=t;
    //z=cur+vol+t;
      return z;
    }

    void setup() {
      // put your setup code here, to run once:

    }

    void loop() {

    int result;
    result=phi(1,2,5);
    Serial.begin(9600);
    Serial.print(result);

    }

body:
It appears you have created an array which only has scope with in the method "phi".

In practical terms, the array "z" is a local variable declared inside of the method and, as such, will likely end up in temporary RAM.  When the method has completed, the RAM reserved for that method's local variables is released and is available for other purposes.

To fix this you could make "z" a static or you could give "z" global scope.


body:
Defining the array in phi() returns a pointer to unassigned memory - it is no longer reserved once phi() returns. The next function call or interrupt (which you have no control over) will likely clobber the data.

A better choice would be to define `z` in the caller (loop() in this case) as an uninitialized array and pass it to phi() to fill and return. This is the more usual case, as it:

 - avoids using globals,
 - permits multiple calls to the function without clobbering previously returned data (you would pass different arrays in this case), and
 - it avoids statically defined arrays that may not be needed after the caller returns, in a memory-starved environment (this may not be applicable if loop() is the caller).

In short, it gives the calling function the greatest flexibility, while committing the least amount of memory.


message:
How do I read a sub-degree angle?

I need to measure (and record changes over a short time) the angle of a lever at a sub-degree resolution (The fulcrum can be the sensor) using an Arduino.

I've looked at rotary encoders, but even those with no detents have about 24 pulses per rotation. I need to measure only across a 90 degree arc. 24 pulses per rotation is 15 degrees per pulse. Which I guess results in a measurable resolution of 7.5 degrees!

I could add gears to increase the turns on the encoder, but that would increase the force required to move the lever.

Is there an option I'm not thinking of?

body:
>I've looked at rotary encoders, but even those with no detents have about 24 pulses per rotation.

It sounds like you have been looking at encoders intended for user input controls.

**Optical Rotary Encoders** for machinery applications are readily available with up to several thousand pulses per revolution.  Prices vary depending on if the wheel is glass or plastic, mounting options, brand, etc.

Do be aware that especially at the high resolutions, getting the encoder disk mounted perfectly concentric to the shaft being measured in important.  You would either need to buy a a wheel which already has a bushing of the same diameter as your shaft, have access to a lathe, or have something custom made.  (This is probably a case where a 3d printer is not accurate enough)

Also keep in mind that encoder wheels are often specified in cycles per revolution; with the typical two channel read head and quadrature decoding, there will be four times as many distinct state transitions.  So a mere 300 CPR wheel would give you 1200 counts per revolution.


body:
Try a spirit level (also called bubble level) app on your phone or tablet. It can get to sub-degree accuracy, but it is relative and not absolute accuracy. If that is good enough for you, then you could buy a modern accurate **accelerometer** and average the values.
It might even be possible to have more than one accelerometer for more accuracy.

Good quality (calibrated) digital spirit levels are very accurate. They use a accelerometer.

It will measure the angle with the earth gravity, and it is sensitive for vibrations.

There are more ways to measure the angle, but it depends on the mechanical construction of the lever. For example a **IR distance sensor** for short distances at the end of the lever. Maybe a magnet and **hall sensor**. There are probably more ways to measure the angle.


message:
65 hall effect sensors as switches to be used as a keyboard with a teensy

I'm trying to wire up a silly little keyboard using hall effect sensors and magnets in a glove. The idea being only I can use the keyboard since I'll have the glove.

 The sensors are 3 pin, (vcc, gnd, and an output that sends 5v out when a magnetic field is present. I don't have anywhere near enough pins on the teensy for all the sensors. Could I just use several port expanders? Are there issues with using 4 or 5 at once? How many keys could be pressed at a time?

Is there a better option than all those expanders?

 Also I know that this keyboard will be ugly and completely impractible to use regularly, but I thought it would fun to show off.

body:
[**Completely rewritten answer**]
That seems fun. But why 65 keys ? with 64 keys it is easier.

You have to test the sensitivity of the hall switches with the magnets to know how far apart the keys must be. Perhaps they only work with strong magnets or perhaps a number of them are activated when the glove is near.

With hall switches, there are 65 digital signals from the sensors.
The most common way to create more digital inputs is to use shift registers. For example with the [74HC165][2]. Nick Gammon has the best [tutorial of the 74HC165 with daisy-chain][3].
There is also an example is with the [CD4021][4] and the [ShiftIn][5] function, but the 74HC165 is mostly used.
The shift registers can be daisy-chained, they are made for that.

Your AH1807 has a open-drain output. That means you need 65 pullup resistors.
It is not possible to connect all the outputs and turn them on one by one, since it requires 150ms to wake up.

Another option is using multiplexers. It can be used for analog and for digital signals. For example with four 16-to-1 multiplexers you can create 64 inputs going to 4 pins. The best [multiplexer tutorial][6] is once again written by Nick Gammon.

With four analog multiplexers of 16-to-1 you would require only 4 pullup resistors after the multiplexer. I think it is better to use a resistor per hall sensor (65 pullup resistors).

When using reed switches (those tiny glass tubes, used in house alarms), they can be set in a matrix/grid with rows and columns and the [Keypad library][1]. For example 10*7 requires 17 pins. The Keypad library allows that multiple keys are pressed at the same time.

  [1]: https://playground.arduino.cc/Code/Keypad
  [2]: https://playground.arduino.cc/Code/ShiftRegSN74HC165N
  [3]: https://www.gammon.com.au/forum/?id=11979
  [4]: https://www.arduino.cc/en/Tutorial/ShiftIn
  [5]: https://www.arduino.cc/en/Reference/ShiftIn
  [6]: https://www.gammon.com.au/forum/?id=11976


message:
How to read response from server using an Ethernet shield?

I want to control a relay by reading values from MySQL. I'm using an Arduino and an Ethernet shield. So far, I can get the response from server and get the value. I just need the value `10110110`, but I get a response in the serial monitor like this:

<!-- language: none -->

    HTTP/1.1 200 OK
    Date: Sun, 02 Jul 2017 07:53:29 GMT
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1
    X-Powered-By: PHP/5.3.1
    Content-Length: 13
    Content-Type: text/html

    <10110110>

How to remove this long response and get the value `10110110`?

body:
There are, obviously, a great number of ways that this can be achieved. The simple brute force way would be to have a series of `if` statements, looking for a sequence of eight consecutive `0`s and/or `1`s, and loop through the string containing the response.

Or you could loop through the response, using `strcmp()`, similar to what is described here: [how to do like a grep in a sketch?][1]

However, a more intelligent method would be to use pattern matching and regular expressions.

From [New regular expression library released][2], Nick has provided a Regexp library. It uses Lua for the expression syntax, see [string.find] [3], for more details.

I am still playing with this code, but your sketch would need something like this:

    #include <Regexp.h>
    void setup ()
    {
      Serial.begin (115200);
      Serial.println ();

      unsigned int index = 0;
      char buf [100];

      MatchState ms;
      ms.Target ("HTTP/1.1 200 OK\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
    X-Powered-By: PHP/5.3.1\
    Content-Length: 13\
    Content-Type: text/html\
    \
    \
    <10110110>");  // what to search

      while (true){
        char result = ms.Match ("^<([01][01][01][01][01][01][01][01])", 0);  // look for an eight bit binary digit
        if (result == REGEXP_MATCHED)
        {
          Serial.println ("-----");
          Serial.print ("Matched on: ");
          Serial.println (ms.GetMatch (buf));
          Serial.println ("Captures:");
          for (int j = 0; j < ms.level; j++)
             Serial.println (ms.GetCapture (buf, j));
          // move past matching string
          index = ms.MatchStart + ms.MatchLength;
        }  // end of match
        else
          break;  // no match or regexp error

      } // end of while

    }  // end of setup

    void loop () {}

This code assumes that you are looking for a line beginning with `<` and captures an eight digit binary thereafter - as determined by the expression within the inner `()`, in the line:

        char result = ms.Match ("^<([01][01][01][01][01][01][01][01])", 0);  // look for an eight bit binary digit

 So, it *should* output:

    -----
    Matched on: <10110110
    Captures: 10110110
    -----

Obviously, instead of just outputting the captured binary digits to the serial monitor, you need to save them for your relay control.

----------

For neatness, you could replace

     ms.Target ("HTTP/1.1 200 OK\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
    X-Powered-By: PHP/5.3.1\
    Content-Length: 13\
    Content-Type: text/html\
    \
    \
    <10110110>");  // what to search

with

      char * str = "HTTP/1.1 200 OK\
        Date: Sun, 02 Jul 2017 07:53:29 GMT\
        Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
        X-Powered-By: PHP/5.3.1\
        Content-Length: 13\
        Content-Type: text/html\
        \
        \
        <10110110>";

      ms.Target (str);

Note the use of the backslashes at the ends of the lines. I've included them here, in order to get the test sketch to compile. You probably will not need them as you would be receiving the response from the server, and not providing an example string for testing.

----------

 Here is a *working* version, along with multiple test strings (`input_str `) and example match strings (`match_str`):

    #include <Regexp.h>
    void setup ()
    {
      Serial.begin (9600);
    //  Serial.begin (115200);
      Serial.println ();

      unsigned int index = 0;
      char buf [100];

    // Simple test pair
    //  char * input_str = "RGB:123";
    //  char * match_str = "(%a)";

    // Simulated MySQL responses
    // Most basic
    //  char * input_str = "<10110110>";
    // Over two lines
    //  char * input_str = "http\\n<10110110>";
    // Full response
      char * input_str = "HTTP/1.1 200 OK\
        Date: Sun, 02 Jul 2017 07:53:29 GMT\
        Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
        X-Powered-By: PHP/5.3.1\
        Content-Length: 13\
        Content-Type: text/html\
        \
        \
        <10110110>";
    // Full response with newlines
    //  char * input_str = "HTTP/1.1 200 OK\\n\
        Date: Sun, 02 Jul 2017 07:53:29 GMT\\n\
        Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\\n\
        X-Powered-By: PHP/5.3.1\\n\
        Content-Length: 13\\n\
        Content-Type: text/html\\n\
        \\n\
        \\n\
        <10110110>";
    // Shorter version of full MySQL response with newlines
    //  char * input_str = "Content-Type: text/html\\n\
        \\n\
        \\n\
        <10110110>";
    // Shorter version of full MySQL response with newlines with no preceeding spaces
    //  char * input_str = "Content-Type: text/html\\n\
    \\n\
    \\n\
    <10110110>";

    // Match strings for MySQL response, containing an eight bit binary number
    // Match at beginning of line
    //  char * match_str = "^<([01][01][01][01][01][01][01][01])";
    // Match at beginning of line with multiple newline characters
      char * match_str = "[\n]*<([01][01][01][01][01][01][01][01])";
    // Match at beginning of line with zero or one newline characters
    //  char * match_str = "[\n]?<([01][01][01][01][01][01][01][01])";
    // Match at anywhere
    //  char * match_str = "<([01][01][01][01][01][01][01][01])";

      MatchState ms;

      while (true){
        char result = ms.Match (match_str, 0);

        if (result == REGEXP_MATCHED)
        {
          Serial.println ("-----");
          Serial.print ("Matched on: ");
          Serial.println (ms.GetMatch (buf));
          Serial.println ("Captures:");
          for (int j = 0; j < ms.level; j++)
             Serial.println (ms.GetCapture (buf, j));
          // move past matching string
          index = ms.MatchStart + ms.MatchLength;
        }  // end of match
        else
          break;  // no match or regexp error

      } // end of while

    }  // end of setup

    void loop () {}

For the `match_str` line,

    char * match_str = "[\n]*<([01][01][01][01][01][01][01][01])";

you may or may not need the caret (`^`) to match at the start of the line, and the `[\n]*` or `[\n]?`. See which combination works for you.

  [1]: http://forum.arduino.cc/index.php?topic=41285.0
  [2]: https://forum.arduino.cc/index.php?topic=59917.0
  [3]: https://www.gammon.com.au/scripts/doc.php?lua=string.find


message:
Adafruit Gemma unrecognised USB device on Windows 10

I have a V2 Adafruit Gemma from the [Gemma starter pack][1], and I'm running Windows 10 Home (version 10.0.14393), on a 64-bit laptop. Following the [ Introducing Gemma guide][2] I've installed the Adafruit drivers and I'm now trying to get it to connect via USB.

After connecting, the board shows the green power LED, but not the pulsing red LED, and Windows shows the 'USB device not recognised' message.

**Tried so far**

 - I'm definitely using USB 2 ports, and I have tried it connected directly to the PC and via a USB hub.
 - I'm pretty sure the cable is working correctly (It works for exchanging data on a phone, and I've tried a few different ones).
 - Under Device Manager, the board shows as 'USB Device (Device Descriptor Request Failed)'.
 - 'Update driver software' > 'Search automatically...' reports that 'The best driver software for your device is already installed'.
 - If I do 'Update driver software' > 'Browse my computer...' and point it to the manual Adafruit driver files (available on the link to the [guide][2]), I get the same message.

Can anyone suggest anything to try? Do I need to (re)install the bootloader itself, and if so, can you point me in the direction of how I do this?

**Update**

As mentioned in the comments I have posted on Adafruit's own support forum but got absolutely nothing yet. I have also tried it on my work PC (Windows 10 Pro, 64-bit) and got exactly the same behaviour.

I'm keen to get this sorted so bounty added for anyone who can at least come up with some suggestions of what to try!

  [1]: https://www.adafruit.com/product/1657
  [2]: https://learn.adafruit.com/introducing-gemma/windows-setup

body:
I think, you've pretty much done everything. If you could gain access to another board, and try that one you could figure out more. Otherwise your symptoms remind me of a something called an ESD (Electrostatic Discharge) caused malfunction. This basically means one of the system essential chips on the board have been fried. It is very easy to ESD a chip without protection, just walk on a carpet or put on a sweater, and than touch the chip. Chances are you were electrostaticly charged with thousands of volts. The chip does not stand a chance. To prevent this from happening, touch something made out of metal before touching the board.<br />More on ESD: [Electrostatic discharge][1]

  [1]: https://en.wikipedia.org/wiki/Electrostatic_discharge


message:
Is this (loose) capacitor critical?

I have a Arduino Mega where a capacitor is 'broken off' ... I originally posted the question in the Electronics forum ([Question][1]).

One of the answers was that the capacitor is not critical. Can anyone confirm it (and consequences by not fixing it at all)? I didn't dare to turn on the Mega because of the broken capacitor.

It looks like this:

[![enter image description here][2]][2]

  [1]: https://electronics.stackexchange.com/questions/314084/is-this-solderable/314109#314109
  [2]: https://i.stack.imgur.com/oGEHR.jpg

body:
If the voltage regulator is a MC33269 as in the official Arduino Mega 2560, then you need that capacitor, or else the MC33269 might start to oscillate. Search in the datasheet of the MC33269 for the paragraph with: "The MC33269 requires an external output capacitor for stability". The board will probably still work without it, but if it does indeed start to oscillate, then it can cause trouble. This is only when powered via the power barrel jack or the VIN pin.

That capacitor does not do a lot when the Arduino Mega is powered via the USB cable. You can use it without any problem when powered via the USB.

According to the photo, you can solder it back into place. They wrote enough about that in the EESE section. Give it a try, but don't create a shortcut with too much solder.


message:
Upload original firmware to HID Arduino

I recently was playing around with Arduino and using dfu-programmer reflashed ATMega16u2 to make the computer think it was a keyboard device.

Well, I wish to put the original Arduino firmware back on, but now dfu-programmer says the device is not present.

The Arduino is listed under `/dev/hidraw5` on Ubuntu. Typing `lsusb` gives the following output for Arduino keyboard:

    Bus 004 Device 008: ID 03eb:2042 Atmel Corp. LUFA Keyboard Demo Application

I tried erasing with the command:

    sudo dfu-programmer atmega16u2:4,8 erase

and got

    dfu-programmer: no device present.

Is there a way to target `/dev/hidraw5` using dfu-programmer? Many thanks.

body:
Very sorry!  But I actually figured this out on my own.  I needed to reset by briefly bridging the reset pin with ground near the USB connector.  Then typed

    sudo dfu-programmer atmega16u2 erase

and I'm happy again.


message:
Read and store data with the usb

Hi i am new to Arduino and I want to know if it is possible to read the data from a sensor that it is connected to the Arduino, I am using the Arduino mega 2560, which is already working, as I have a LED which change color depending on the detection of the object and then store it in a file as txt or another normal extension.

body:
I don't have experience with Processing, but probably that is what you need. It communicates through USB and with the CreateWriter function, you can create a text file.

More about Processing can be found at [Processing][1]

Also another thread at Electronics stack exchange might help:

[Related question][2]

Alternatives (also mentioned in the above thread):

- Use serial port directly with a terminal application on the PC
- Use an SD card inside the Arduino to log

  [1]: https://processing.org/
  [2]: https://electronics.stackexchange.com/questions/54/saving-arduino-sensor-data-to-a-text-file


body:
From what I understand from your question, you want to store the data displayed in the Serial monitor to a text file or something similar. As the Arduino itself cannot do this task, I used "GoBetwino" to save my data from an Arduino into a text file, from where you can export the data into Excel if you want charts and graphs. The process is fairly easy and described properly in their user manual.
https://playground.arduino.cc/Interfacing/GoBetwino


message:
Need help with my code for my project using an Arduino Uno and Processing

I am using an Arduino Uno for my project. I use 4 digital inputs and they will be triggered by 4 different relays. I would like to save the data in a *.csv file in the format below.

For example, if any of the inputs goes high, it will save a station ID, date, time it goes ON (starts). But once the input goes low, it will save the time it goes OFF (stops) on the same line.

Kindly help to advise if my code is correct because I get too many errors when I run it.

Example table in .csv file:

    Date        Oven Station Time Start     Time Stop
    3/7/2017    Oven_P1_1    11:58    16:00
    3/7/2017    Oven_P1_2     7:30    11:00
    3/7/2017    Oven_P5_1    14:10    20:00
    4/7/2017    Oven_P5_2     01:20    7:30
    4/7/2017    Oven_P5_1     2:40    8:45
    4/7/2017    Oven_P1_2      08:05    12:00
    4/7/2017    Oven_P1_1      09:12    13:10

[![enter image description here][1]][1]

    import processing.serial.*;

    int Oven_P1_1 = 8;
    int Oven_P1_2 = 9;
    int Oven_P5_1 = 10;
    int Oven_P5_2 = 11;
    float Ovenvals [] = {0,0,0,0};

    Serial myPort;
    String val;
    Table table;

    String filename;

    void setup() {
      String portName = Serial.list()[5];
      myPort = new Serial(this, portName, 9600);
      table = new Table();
      table.addColumn("id");
      table.addColumn("year");
      table.addColumn("month");
      table.addColumn("day");
      table.addColumn("hour");
      table.addColumn("minute");
      table.addColumn("second");
      table.addColumn("Oven_P1_1");
      table.addColumn("Oven_P1_2");
      table.addColumn("Oven_P5_1");
      table.addColumn("Oven_P5_2");
    }

    void serialEvent(Serial myPort) {
      val = myPort.readStringUntil('\n');
      if (val != null) {
        val = trim(val);
        println(val);
        float Ovenvals[] =float(split(val, ','));
        TableRow newRow = table.addRow();
        newRow.setInt("id", table.lastRowIndex());
        newRow.setInt("year", year());
        newRow.setInt("month", month());
        newRow.setInt("day", day());
        newRow.setInt("hour", hour());
        newRow.setInt("minute", minute());
        newRow.setInt("second", second());
        newRow.setInt("Oven_P1_1", ovenVals[0]);
        newRow.setInt("Oven_P1_2", ovenVals[1]);
        newRow.setInt("Oven_P5_1", ovenVals[2]);
        newRow.setInt("Oven_P5_2", ovenVals[3]);
        {
          saveTable(table, "data/OvenStatus.csv");
        }
      }
    }

    void draw() {
      OvenVal[0] = digitalRead(Oven_P1_1);
      OvenVal[1] = digitalRead(Oven_P1_2);
      OvenVal[3] = digitalRead(Oven_P5_1);
      OvenVal[4] = digitalRead(Oven_P5_2);
      Serial.print(OvenVal[0]);
      Serial.print(",");
      Serial.print(OvenVal[1]);
      Serial.print(",");
      Serial.print(OvenVal[2]);
      Serial.print(",");
      Serial.print(OvenVal[3]);
      Serial.print(",");
      delay(100);
    }

  [1]: https://i.stack.imgur.com/Ehoz8.png

body:
You asked for (emphasis mine):

> [...] But once the input goes low, it will save the time OFF (stop)
> **on the same line**.

That's hard. What if several other inputs have gone HIGH in the
meanwhile? You will have to somehow rewind part of the file, then add
the stop time, the add again the subsequent lines...

You probably do not want to do all this on an Arduino. Especially
considering that the Arduino has no concept of file, unless you add an
SD card and the appropriate library. And it has no concept of time of
day, unless you add an RTC and the appropriate library. I would suggest
you go the easy path:

* have the Arduino tell your computer through the Serial port whenever
  one of those inputs changes state
* write a program in your computer (with processing or whatever) that
  reads this information and formats it the way you want.

For the first part, I suggest the following:

<!-- language: lang-c++ -->

    /*
     * Tell us when some pins change state.
     */

    const int CHANNELS = 4;
    const uint8_t pins[CHANNELS] = {8, 9, 10, 11};

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

    void loop()
    {
        static int states[CHANNELS];
        for (int i = 0; i < CHANNELS; i++) {
            int state = digitalRead(pins[i]);
            if (state != states[i]) {  // input changed state
                Serial.print("channel ");
                Serial.print(i);
                Serial.print(" going ");
                Serial.println(state ? "HIGH" : "LOW");
                states[i] = state;  // record new state
            }
        }
    }

The output will be something like

    channel 2 going HIGH
    channel 1 going HIGH
    channel 2 going LOW
    ...

For the second part, well, that's not an Arduino-related question
anymore!


message:
Purpose of this resistor in Arduino Nano schematic

I was looking at the Arduino Nano's [schematic](http://download.arduino.org/products/NANO/Arduino Nano-Rev3.2-SCH.pdf) and noticed a resistor that seems to be pointless (RP2C on this picture).
[![Strange resistor RP2C][1]][1]
Also there is numbers 6 and 3 on it, does it mean that resistor is connected to pins 6 and 3 on FT232 or to the same pins on Atmega328?

[1]: https://i.stack.imgur.com/zIbvS.png

body: It's an unused element of resistor array RP2. Both ends are grounded in order to reduce noise.


body:
The resistor is one of 4 resistors that make up an SMD resistor array, RP2. It is seen on the board here:
[![Arduino Nano underside][1]][1]

The resistor array works like this:
[![Resistor array][2]][2]

The resistor on this array is spare, so both terminals are grounded.

  [1]: https://i.stack.imgur.com/BemUn.jpg
  [2]: https://i.stack.imgur.com/FaBSm.gif