body:
For a project of mine I am programming an Arduino UNO to show information I get from some sensors on an LCD display.

As a first step I setup Arduino to show "Hello, world!" on the LCD, which worked.

[![LCD showing "Hello, world!"][1]][1]

For "decorative" reasons I wanted to add some LEDs between the resistors that I placed in series between PIN 3 (V0) of the LCD and ground (about 1.5K Ohm total resistance).

I first of all added one LED between the last resistor and ground. To my surprise this causes the LCD display not to show "Hello, world!" any more.
As you can see the current is flowing (the LED is lit), but I can't understand why the LCD does not show the text.

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

Can you help me understand what's going on? I know very little of electronics and I am learning it by doing, so I would appreciate an answer that is good for a beginner!

  [1]: https://i.stack.imgur.com/n9x7m.jpg
  [2]: https://i.stack.imgur.com/xwjCA.jpg

title: Why adding a LED between Pin 3 and Ground causes LCD display not to show text?

Answers: 2

body:
In a [typical 1602 LCD pinout](https://www.openhacks.com/uploadsproductos/eone-1602a1.pdf), pin 3 or V0 is the contrast setting for the display.  It usually is set to a voltage near ground, often by using a 10K pot with ends connected to Vdd and Vss with wiper to V0.

By putting an LED in series with your resistors (that apparently go to ground) you've either disconnected V0 from ground or have raised its voltage by the LED voltage.  This reduces contrast to the point that characters aren't visible even though they are on the display.

The LED backlight remains on and at the same brightness as before because it is driven via pins 15 and 16, independent of all other display settings.

*Edit 1:* I haven't duplicated your circuit to take measurements, so at the moment don't know for sure; but (in resistors-only case) V0 from pin 3 on the 1602 LCD board apparently sources some small current through your 1500 Ω to ground.  When you add an LED it can disconnect V0 from ground or can raise its voltage by the LED voltage, as follows:  firstly, if the LED cathode faces V0 and V0 is positive, no current will flow through the diode, thus disconnecting V0.  Secondly, if the LED anode faces V0 and V0 is positive, current will flow through the LED.  If the LED lights at all, most of its Vf characteristic voltage (typically between 3 and 4 volts for a green LED) will appear across it.  Thus, V0 sits at close to Vf plus whatever drops across the resistors.

*The same as for other diodes, LED forward current increases exponentially with voltage ([Ref: wikipedia on LED physics](https://en.wikipedia.org/wiki/Light-emitting_diode#Physics)) hence voltage change is tiny over large changes in current when an LED is emitting light.  In other words, if the LED is lighting up, its voltage will be close (ie within a few dozen millivolts) to its characteristic band gap voltage.  See [petervis.com's led-resistor-calculator](http://www.petervis.com/electronics/led/led-resistor-calculator.html) for a "Chart by Colour" that shows characteristic Vf forward voltages.

body:
> Can you help me understand what's going on?

that pin controls the contrast and it needs to be 3.5 - 4.x volt (typical) below Vcc. an led in conduction would drop 2 - 3v, depending on the led, making that pin's potential much closer to Vcc -> minimum contrast so you cannot see the text being displayed.


body:
I've been experimenting with Arduino on both esp8266 and AVR chips. The structure of the `.ino` file usually looks like this:

    #include "Arduino.h"
    #include "ESP8266WiFi.h"
    ##Some includes

    void setup()
    {
    ...
    ##Will be only run once at the begining.
    }

    void loop()
    {
    ##Runs this code in a constant loop
    }

My assumption is that somewhere behind simplification, before the compilation takes place, there is a `full blown source file`. It includes the platform specific initialization and contains the calls to `setup()` and `loop()`. When I say `full blown source file` I mean something that can be passed to the compiler and will compile given that the dependencies are met.

My questions are:

* Is this assumption correct?
* If so, can someone share an example on how does the `full blown source file` look like, and where did you get it from?

title: What does an arduino sketch translate to before compilation?

Answers: 2

body:
C++ (the actual language/compiler that is used) is a multiple-compilation-unit language. There is no single source file, but rather a bundle of compiled source files, that are linked together to create the executable (or downloadable image).

In you case the user sketch provides the `setup()` and `loop()` functions, which are called from another source file, which is provided by the Arduino IDE.

body:
The Arduino core libraries (which are nothing more than a bunch of C/C++ files - there is no such thing as the "Arduino" programming language), are compiled along with your source code. These files include all of the initialisation routines and function definitions for things like `digitalWrite` and so forth.

There is a `main.cpp` file that gets compiled which is pretty much nothing more than:

    #include "Arduino.h"

    int main(void) {
        //Initialise timers and things (internal)
        init();
        //Your initialisation stuff (setup)
        setup();
        //Loop forever
        for (;;) {
            //Calling your loop function
            loop();
        }
    }

In terms of what your `.ino` file becomes, it is basically just copied to a temporary build directory and renamed to `.cpp`. There are some minor changes made, which is basically to just copy all of the function declarations and place them at the top of the file.

This process is actually why if you use your own header file which has some `typedef` in it which you then use in a function call, the code will break because the declarations get added above the `#include` statements meaning the custom type is used before it is defined.

If you go to the preferences you can tell it to enable verbosity during compilation. This will actually show you exactly what is being compiled. It will also give you the path to the temporary build directory in which you will find the `.cpp` file with the same name as your `.ino` file.


body:
I'm trying to control the speed of a DC motor using PWM. Here is my code so far:

    int motor = 9;
    int fadeValue = 5;

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

    void loop() {
      for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
        analogWrite(motor, fadeValue);
        delay(100);
      if (fadeValue==245) {
        fadeValue=255;
        break;
      }
    }

I want the motor to slowly increase it speed then stay high. However, the loop keep repeating.

Thanks in advance guys.

title: Slowly increase speed using PWM arduino

Answers: 5

body:
>However, the loop keep repeating.

That's the whole point of loop(). If you want some code to run only once after the program starts put it in `setup()`:

<!-- language: lang-cpp -->

    int motor = 9;
    int fadeValue = 5;

    void setup() {
      pinMode(motor, OUTPUT);

      for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
        analogWrite(motor, fadeValue);
        delay(100);
        if (fadeValue == 245)
        {
          fadeValue = 255;
          break;
        }
      }
    }

    void loop() {
    }

body:
If you dont want the code to repeat at the maximum, just add a condition to the loop. Your solution could look like this:

    int fadeValue = 5;

    void loop()
    {
        if (fadeValue < 255)
        {
            if (fadeValue >= 245)
            {
                fadeValue = 255;
            }
            else
            {
                fadeValue++;
            }
            analogWrite(motor, fadeValue);
            delay(100);
        }

        //Other code here
    }

By setting `FadeValue` to another value, the fade will start again from the new value until the maximum.

body:
it can be put in the loop(): putting it in the setup(), if the speed-up period is long, isn't practical or feasible in some applications.

you can use a loop counter or time counter to slow down the ramp-up without tying down the mcu, like this:

      time_now = time(); //take a reading of current time. or millies()
      if (time_now < TIME_RAMPUP) { //still need to ramp it up
        if (time_now > time_prev) { //need to increment motor speed
          time_prev+=TIME_INC;
          motor_dc+=PWM_STEP;  // you may wish to bound the dc here
          analogWrite(MOTOR_PIN, motor_dc); //increase dc
        }
      }

body:
If you want void loop() to only run once and don't want to put your code into setup() for some odd reason, just as an infinite while loop at the end with a delay inside like this:

    void loop()
    {
      for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10)
    {
        analogWrite(motor, fadeValue);
        delay(100);
      if (fadeValue==245)
    {
        fadeValue=255;
        break;
      }

    While(1)
        Delay(1000);

    }

body:
Could you also change the order the loop is in? So the code would look like this instead:

    void loop() {
      if (fadeValue == 245) {
        fadeValue=255;
        analogWrite(motor, fadeValue);  // motor will stay at highest value
        }
      else {
          for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
            analogWrite(motor, fadeValue);
            delay(100);
            }
      }
    }

So now, the loop will run until fadeValue == 245, at which point the loop will not advance to the for loop because the "if" in the if/else statement is satisfied. I'm not actually sure if this will work, but it's an idea.


body:
I'm trying to read 4 analog inputs (1kHz speed). I changed the prescaler to 16 for my Arduino Leonardo according to this [link][1]. I then tried to read the analog pins and I used the following code to display the time and the readings:

----------

    #define FASTADC 1
    // defines for setting and clearing register bits
    #ifndef cbi
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif
    double t = 0;
    void setup() {
      int start;
      int i;
      #if FASTADC
      // set prescale to 16
      sbi(ADCSRA, ADPS2);
      cbi(ADCSRA, ADPS1);
      cbi(ADCSRA, ADPS0);
      #endif

      Serial.begin(9600);
      Serial.print("ADCTEST: ");
      start = millis();
      for (i = 0 ; i < 1000 ; i++)
        analogRead(0);
      Serial.print(millis() - start);
      Serial.println(" msec (1000 calls)");
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // print out the value you read:
      t = millis() / 1000;
      Serial.print(t);
      Serial.print('\t');
      Serial.print(analogRead(A0)); delay(1);
      Serial.print('\t');
      Serial.print(analogRead(A1)); delay(1);
      Serial.print('\t');
      Serial.print(analogRead(A2)); delay(1);
      Serial.print('\t');
      Serial.println(analogRead(A3)); delay(1);
    }

I connected 2V from the DC supply to all the 4 channels and the readings were similar. I used the output from the serial monitor and pasted the readings for 1 sec in Excel to see the frequency. With a 9600 baud rate and no delay between the readings I got 200 Hz (for the 4 analog inputs).

Why is that happening? And is there a relationship between the sampling frequency and the baud rate? Is my way of finding the frequency correct? If not what's the right way?

Finally, I'll be plotting the readings in Matlab, so I guess this will affect the sampling frequency. How can I control it so that I'm sampling with 1kHz rate for all the channels?

Here is the screenshot of the readings from the 4 channels (2V input).

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

Summarizing everything, I need to know the following:

1. The effect of adding a delay between every two readings on the accuracy of the readings and the sampling frequency.

2. How to find the best sampling frequency for every input and how to control it?

3. Will using Matlab to plot the data affect the sampling frequency?

Thanks.

  [1]: http://forum.arduino.cc/index.php?topic=6549.0
  [2]: https://i.stack.imgur.com/YUqjH.png

EDIT: I accepted the answer below, if anyone has the same problem , please make sure that you change the prescaler as I mentioned above for the best results.

title: Delay between multiple analogReads

Answers: 4

body:
I tried your program on my Arduino Uno with similar results : it prints
about 44 lines per second. Then I did the math:

Each line consists of 22 characters, including the CR and LF at the end.
Each character is transmitted as 10 bits (8 data bits, one start bit and
one stop bit). At 9600 bits/second, each bit takes 0.104 ms to be
transmitted. All this amounts to 22.88 ms per line (22 × 10 × 0.104), or
about 43.7 printed lines per second, on average.

Now, since you are using a Leonardo, things could be a little different,
as the Leonardo does not use a real serial port, but a virtual one. You
may still try to increase the baud rate to see if it makes any
difference.

body:
At first I thought that the main problem was not that you too slow at sampling, but that you were too slow at transmitting the data. As Edgar already stated, at 9600 b/s you need 22.88ms to send a line, so the maximum frequency is less than 50Hz.

However as you experienced, the speed you are getting is 200Hz. This is because that calculation is right in the case of a real serial interface. Arduino Leonardo, on the other hand, emulates the serial interface. But.. There is no such thing as baud rate. If you look at [the CDC emulation source code](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/CDC.cpp) you will see that the baud rate you pass to the `begin` function is ignored.

So... Why is it still slow? Because you are using the `delay` function! You are waiting for 1ms every time you perform an acquisition, and then you still have to perform all the sending. This has two errors embedded: 1) using the `delay` function breaks the timing - better use a timer - and 2) you are too slow.

Now, if you want a 1kHz sampling (or any delay multiple of 1ms) you already have a timer running (so you can just use that):

    #define INTERVAL_LENGTH_US 1000UL

    unsigned long previousMicros;

    void loop()
    {
     unsigned long currentMicros = micros();

     if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
     {
      previousMicros += INTERVAL_LENGTH_US;

      int val_a0 = analogRead(A0);
      int val_a1 = analogRead(A1);
      int val_a2 = analogRead(A2);
      int val_a3 = analogRead(A3);

      Serial.print(((double)currentMicros) / 1000000UL, 1); // 1 is the number of decimals to print
      Serial.print('\t');
      Serial.print(val_a0);
      Serial.print('\t');
      Serial.print(val_a1);

      Serial.print('\t');
      Serial.print(val_a2);
      Serial.print('\t');
      Serial.println(val_a3);
     }
    }

NOTE: The `millis()` function is replaced by `micros()` according to Edgar's and Nick's comments.

Change just the define to change the sample time. Now its set to 1000us (i.e. 1ms, so 1kHz), but don't go much higher otherwise you will have to check accurately the sampling time and the transfer speed. The `t` variable is not needed anymore.

Just a side note: this will also fix the bug in your code that prevents the program to display the current timing (instead of printing 2.5 it prints 2.0).

<s>If you need a faster sample rate you should use another timer to get the correct timing, but again avoid delays.</s> Not needed anymore

body:
Two ways to sample at or near a given frequency:

1. Select the right ADC clock prescaler. This has some limitations and may not get you too the precise sampling frequency.

2. Use a timer to trigger the sampling. Can be done in either. Hardware or software. It is the most flexible way here, especially if coupled with the ADC isr.

body:
A few recommendations to get good performance out of the Arduino boards.

 - Maximize your analogResolution if the default is not already the max (as in the case of the Due.)
 - If possible, use a simple oscillator instead of a constant Voltage source.  If you can create a sine or triangle wave with its peaks within the Arduino's input voltage range, you can plot something more interesting than a straight line.
 - There is no need to do any analogReads in setup(), and you DON'T want to do anything with the Serial object in setup() except configure it.  (There is an under-the-hood reason for that.)
 - To get good sample rates from the Arduino boards, don't convert to text until MUCH later in the data flow.  TO try this SIGNIFICANT speed optimization, declare an array of 4 elements of type unsigned int, another array of 12 elements of type unsigned char, and an unsigned long to hold the time.
 - In loop(), start by assigning micros() to the unsigned long
 - Then **call the four analogReads in an uninterrupted sequence**, assigning them to the four elements of the unsigned int array.
 - Then copy the four bytes from the unsigned long and the eight bytes from the four unsigned ints into the 12 elements of the unsigned char array.  You will need to use the C++ shift right operator ">> 4" and the "(unsigned char)" type conversion to do this part.
 - Then, still in loop(), call Serial.write(byteArray, 12) once to send the time and digital representations all at once (in the byte order you specified) through the serial connection.
 - Place delayMicroseconds at the very end of the loop to get a higher resolution delay between loop iterations.
 - On the other side of the serial connection (the workstation or laptop) use dd or some other low level transfer program (instead of a terminal emulator) to copy from the binary 12-byte sample vectors from the serial device that your workstation or laptop uses to access the serial connection to a binary file.

The above eliminates several bottlenecks typical of the newbie example programs.  The issue remaining is that, to optimize speed, you never converted the raw binary data vectors to a tab-delimited text file that MATLAB or GnuPlot can read with ease.

A simple C, Java, or Python program can then read the 12 byte vectors and convert the byte groups of 4, 2, 2, 2, and 2 back into the 32 bit time stamp and the four 16 bit unsigned channel values in a loop.  The byte order is what you chose in your Arduino sketch.  You will need to use the left shift operator and bitwise and and or operations to reconstruct the time stamp and four channel values.  At the end of this loop, you can write these values as a single tab-delimited line coresponding to the current binary input vector.  Iterate through all the vectors to get a complete tab-delimited data file.

You can experiment with different delayMicrosecond values to get different sample rates, and you can calculate our baud rate to stay ahead of the sampling so that the program could theoretically run indefinitely without backing up the Serial buffer on the Arduino side.  Each Arduino analogRead and Serial object has its own maximum speed, which you can find by experimentation.


body:
I read that **volatile** is used when we want to store variables in SRAM.

But aren't all the variables in a code are stored in SRAM anyway?

And what makes it an advantage sometimes for variables(like volatile) to be stored in SRAM?

title: Confusion with storage of declared variables and volatile

Answers: 2

body:
That's just plain incorrect.

The `volatile` keyword tells the compiler that the value of that variable may change at any time, and that therefore it must re-read the value every time you use it in your code.

If you don't use `volatile`, the compiler may choose to make an optimisation.

Consider this code:

    int b = 7;
    a = b + b;

The compiler can see that 'b' is always 7 -- it is assigned the value 7 and nobody ever changes it.  The compiler may choose to optimise this to the equivalent of

    a = 14;

But if you do this:

    volatile int b = 7;
    a = b + b;

then the compiler MUST read `b` twice from memory.

Why would you want to do that?  Perhaps you have an interrupt which might change the value of `b`.  Perhaps your interrupt changes the value of 'b' every time you press a button.  You need the code to really check the value of `b` every time it calculates `a`, and not rely on it always being 7.

[Here][1] is a fuller explanation.

  [1]: http://barrgroup.com/Embedded-Systems/How-To/C-Volatile-Keyword

body:
Technically, variables can be stored anywhere, in SRAM, eeprom or enev flash.

However, without doing anything special, variables are stored in SRAM.

Thee votike attribute is just that, it tells the compiler that the variable could change its value and the compiler shouldn't assume that values obtained from prior access is valid now. This forces the compiler to re-read the variable on demand.


body:
I am trying to make an RGB LED with Fan Controller for PCs. It is an Open Sourced project. But I want to implement RTOS using [this][1] implementation of it as a function in it, namely `rollColor()`, takes a lot of cycles.

The data the Arduino uses comes from the Serial. The Serial data has to wait until the function `rollColor()` completes. This function also has a delay and total runtime of this function is approximately 20 Seconds.

This is the original code, in which RTOS is not implemented: [nonRTOS][2]

Now I don't want to give a consecutive 20 seconds of execution time to a single function, but time slices would be good.

Now this falls under (RT)OS category and I would like to utilize this library but I seem to be unable to do that as there is not much documentation to begin with. The code I have come up with is this:

    #include <Arduino_FreeRTOS.h>
    #include <LCD.h>
    #include <LiquidCrystal_SR.h>

    #define FAN1 3
    #define FAN2 5

    #define LEDR 6
    #define LEDG 9
    #define LEDB 10

    #define LCD_DT 14
    #define LCD_CK 15
    #define LCD_EN 16

    #define E_FAN1 0
    #define E_FAN1 1

    #define SAMPLE 100

    #define E_RGB_START 2
    #define E_RGB_END 502

    LiquidCrystal_SR lcd(LCD_DT, LCD_CK, LCD_EN);

    int led[2][6];
    int led_type = 0;
    int led_bright = 0;
    int fan[2] = {50, 50};
    int load[3];
    int temp[2];
    int gradient[SAMPLE][3];

    bool fchange = false;
    bool lchange = false;

    void TaskPrintLCD( void *pvParameters );
    void TaskRGBCycle( void *pvParameters );
    void TaskFanSpeed( void *pvParameters );

    void setup() {
      Serial.begin(57600);
      xTaskCreate(
        TaskPrintLCD
        ,  (const portCHAR *)"Print_To_LCD"  // A name just for humans
        ,  128  // This stack size can be checked & adjusted by reading the Stack Highwater
        ,  NULL
        ,  2  // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
        ,  NULL );
      xTaskCreate(
        TaskRGBCycle
        ,  (const portCHAR *)"Cycle_RGB_Colors"  // A name just for humans
        ,  128  // This stack size can be checked & adjusted by reading the Stack Highwater
        ,  NULL
        ,  3  // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
        ,  NULL );
      xTaskCreate(
        TaskFanSpeed
        ,  (const portCHAR *)"Set_Fan_Speed"  // A name just for humans
        ,  128  // This stack size can be checked & adjusted by reading the Stack Highwater
        ,  NULL
        ,  1  // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
        ,  NULL );
    }

    void loop() {

    }

    void TaskPrintLCD(void *pvParameters) {
      (void) pvParameters;
      Serial.println("LCD Settings...");
      lcd.begin(20, 4);
      for (;;) {
        printCPUUsage(load[0]);
        printGPUUsage(load[1]);
        printRAMUsage(load[2]);
        printTemps(temp[0], temp[1]);
      }
    }

    void TaskFanSpeed(void *pvParameters) {
      Serial.println("System Started...");
      Serial.println("Setting Pins...");
      pinMode(FAN1, OUTPUT);
      pinMode(FAN2, OUTPUT);
      (void) pvParameters;
      for (;;) {
        if (fchange) {
          Serial.println("SETTING FAN SPEED");
          int speed1 = ((fan[0] * 256) / 100 ) - 1;
          int speed2 = ((fan[1] * 256) / 100 ) - 1;
          fchange = false;
        }
      }
    }

    void TaskRGBCycle(void *pvParameters) {
      (void) pvParameters;
      pinMode(LEDR, OUTPUT);
      pinMode(LEDG, OUTPUT);
      pinMode(LEDB, OUTPUT);
      for (;;) {
        if (led_type == 1) {
          //ROLLCOLOR() FUNCTION START
          Serial.println("ROLLING GRADIENT START...");
          for (int i = 0; i < SAMPLE; i++) {
            analogWrite(LEDR, gradient[i][0]);
            analogWrite(LEDG, gradient[i][1]);
            analogWrite(LEDB, gradient[i][2]);
            vTaskDelay(100 / portTICK_PERIOD_MS);
          }
          for (int i = SAMPLE - 1; i >= 0; i--) {
            analogWrite(LEDR, gradient[i][0]);
            analogWrite(LEDG, gradient[i][1]);
            analogWrite(LEDB, gradient[i][2]);
            vTaskDelay(100 / portTICK_PERIOD_MS);
          }
          //ROLL COLOR FUNCTION END
          Serial.println("ROLLING GRADIENT END...");
        } else {
          analogWrite(LEDR, led_bright);
        }
      }
    }

    void serialEvent() {
      Serial.readStringUntil('*');
      while (String main = Serial.readStringUntil('>')) {
        Serial.println("IN WHILE");
        Serial.println(main);
        if (main == "") {
          break;
        }
        String data;
        if (main == "leds") {
          lchange = true;
          int type = Serial.readStringUntil(':').toInt();
          led_type = type;
          if (type == 1) {
            Serial.println("LED TYPE: " + led_type);
            for (int i = 0; i < 6; i++) {
              data = Serial.readStringUntil(',');
              Serial.println(data);
              if (i < 3) {
                led[0][i] = data.toInt();
              } else {
                led[1][i - 3] = data.toInt();
              }
              data = "";
            }
            generateGradient();
          } else {
            led_bright = Serial.readStringUntil(',').toInt();
          }
          Serial.readStringUntil(';');
        } else if (main == "fans") {
          fchange = true;
          for (int i = 0; i < 2; i++) {
            data = Serial.readStringUntil(',');
            fan[i] = data.toInt();
            data = "";
          }
          Serial.readStringUntil(';');
        } else if (main == "stat") {
          for (int i = 0; i < 2; i++) {
            data = Serial.readStringUntil(':');
            if (data == "load") {
              for (int j = 0; j < 3; j++) {
                data = Serial.readStringUntil(',');
                load[j] = data.toInt();
                data = "";
              }
              Serial.readStringUntil(';');
            } else if (data == "temp") {
              for (int j = 0; j < 2; j++) {
                data = Serial.readStringUntil(',');
                temp[j] = data.toInt();
                data = "";
              }
              Serial.readStringUntil(';');
            }
          }
        }
      }
    }

    void printCPUUsage(int usage) {
      int loc;
      int i;
      lcd.setCursor(0, 0);
      lcd.print("CPU% ");
      for (i = 1; i <= ceil(usage / 10); i++) {
        lcd.write(255);
      }
      for (i; i <= 10; i++) {
        lcd.print(" ");
      }
      lcd.print(" ");
      if (usage > 99) {
        lcd.print(usage);
      } else {
        lcd.print(" ");
        lcd.print(usage);
      }
      lcd.print("%");
    }

    void printGPUUsage(int usage) {
      int loc;
      int i;
      lcd.setCursor(0, 1);
      lcd.print("GPU% ");
      for (i = 1; i <= ceil(usage / 10); i++) {
        lcd.write(255);
      }
      for (i; i <= 10; i++) {
        lcd.print(" ");
      }
      lcd.print(" ");
      if (usage > 99) {
        lcd.print(usage);
      } else {
        lcd.print(" ");
        lcd.print(usage);
      }
      lcd.print("%");
    }

    void printRAMUsage(int usage) {
      int loc;
      int i;
      lcd.setCursor(0, 2);
      lcd.print("RAM% ");
      for (i = 1; i <= ceil(usage / 10); i++) {
        lcd.write(255);
      }
      for (i; i <= 10; i++) {
        lcd.print(" ");
      }
      lcd.print(" ");
      if (usage > 99) {
        lcd.print(usage);
      } else {
        lcd.print(" ");
        lcd.print(usage);
      }
      lcd.print("%");
    }

    void printTemps(int cputemp, int gputemp) {
      lcd.setCursor(0, 3);
      lcd.print("TEMP ");
      lcd.print("CPU ");
      if (cputemp < 100) {
        lcd.print(" ");
      }
      lcd.print(cputemp);
      lcd.print(" GPU ");
      if (gputemp < 100) {
        lcd.print(" ");
      }
      lcd.print(gputemp);
    }

    void generateGradient() {
      Serial.println("GENERATING GRADIENT...");
      float m[3];
      int r, g, b;
      m[0] = (led[1][0] - led[0][0]) / SAMPLE;
      m[1] = (led[1][1] - led[0][1]) / SAMPLE;
      m[2] = (led[1][2] - led[0][2]) / SAMPLE;
      for (int i = 0; i < SAMPLE; i++) {
        r = ceil(m[0] * i) + led[0][0];
        g = ceil(m[1] * i) + led[0][1];
        b = ceil(m[2] * i) + led[0][2];
        gradient[i][0] = r;
        gradient[i][1] = g;
        gradient[i][2] = b;
      }
      lchange = false;
      Serial.println("GRADIENT GENERATED...");
    }

To me this code seems complete, but there is nothing from Arduino end, no LCD print nothing. I may be doing something wrong, but I don't know what, so please advice.

If you have any other better alternative please advise that too.

PS: I wrote this in two sittings so there might be something amiss so please feel free to edit or ask any questions for clarification.

  [1]: https://create.arduino.cc/projecthub/feilipu/using-freertos-multi-tasking-in-arduino-ebc3cc
  [2]: https://github.com/DragoTechInnovations/DIYFanNLedController/blob/master/Arduino Software/nonRTOS/nonRTOS.ino

title: FreeRTOS Implementation on Arduino

Answers: 0


body:
I have installed the IDE on a Mac. It works great. I want to use Eclipse as an editor only. Some files I have include "Arduino.h". Where is this file? I cannot find it.

If it is built in to the tools can I download a copy of this file(s)?

title: Where is Arduino.h on a Mac? Can I download a copy if missing?

Answers: 4

body:
I've don't have a Mac, so I can't test this, but on the Arduino Forum they say find the file `Wiring.h` and create an empty file called Arduino.h in the same folder.

I don't know if that's the right approach, but it should get you to the next error, which may well be some system constant is not defined. If it does work you could go to github for the IDE (don't know exactly where that is) and download `Arduino.h` from there and stick it alongside `Wiring.h`.

body:
Generally, if you need to find a file you can open a terminal and type

    locate myfile.dat

This looks in a database (rather than searching the disk), which you may need to update by typing

    sudo updatedb                       // on linux
    sudo /usr/libexec/locate.updatedb   // on Mac

body:
On a Mac the Arduino.h file is within the Arduino application itself. It's not that easy to get to without resorting to the command line.

You also need far more than just Arduino.h - you need the entirety of the Arduino AVR core, which is a collection of .h, .c and .cpp files. They are all together in the application.

You would probably be best off getting them from the github repository (https://github.com/arduino/Arduino) - the files you need are all under `hardware/arduino/avr`

On your Mac you may find them as `/Applications/Arduino.app/Contents/Resources/hardware/arduino/avr` or somewhere similar (not entirely sure where it puts it within the app).

body:
There simply is no "Arduino.h" file. Basically there are multiple platforms (the most common in Arduino world is the Arduino AVR platform). Each platform can contain multiple cores (but mostly only contains 1) and each core contains a "Arduino.h" file.

So to find the Arduino.h file you need to identify the board. The board gives you the platform and the core. Based on those the Arduino.h file is in the folder [platform installation folder]/cores/[core].

The [platform installation folder] is dependent on how the platform was installed on your system. For instance arduino avr comes with the Arduino IDE and as such it is installed in the app like majenko explained.

If it is installed by the boards manager on Linux, the Arduino IDE uses `~/.arduino15/packages/[provider]/hardware/[architecture]/[version]` and if I'm not mistaken the same location is used on Mac.

You can also point to a folder location where additional hardware is installed.

A word on Eclipse and Arduino. There are quite a few options to run compile Arduino sketches in Eclipse. Depending on the tool it goes from easy to pretty complex.

I personally advise to use Sloeber from sloeber.io as I am the developer.


body:
I am working with `Capacitive Touch Sense` technology.In that I am using `TTP224` Touch detector IC. I am getting good sensitivity when I am using Touch pad without putting any non electric material over it and able to switch ON/OFF connected led.But when I put any non electric material like `Acrylic Sheet` of `2mm` thickness I am not able to get any signal through pad or not able to ON/OFF connected led.

So, How can I increase sensitivity of Touch pad?

[I have bought TTP224 module from here.][1]

And what can be the alternatives for `TTP224`???

  [1]: http://www.ebay.in/itm/172493711487?aff_source=Sok-Goog

title: How to increase sensitivity of Capacitive Touch Switch?

Answers: 3

body:
According to [the datasheet](http://www.tontek.com.tw/download.asp?sn=373) (if you can name it that):

> The capacitance Cs0~Cs3 can be used to adjust the sensitivity. The value of Cs0~Cs3 use smaller, then the sensitivity will be better. The sensitivity adjustment must according to the practical application on PCB. The range of Cs0~Cs3 value are 0~50pF.

So, reduce the capacitances Cs0 to Cs3 and you will get better sensitivity.

body: Sometimes things just ****. In my case, where 0.5 mm more of gap make the TTP223 unable to work, because I designed such a small pad. My solution? Remove the paint in the PCB, put a lot of solder in to make the pad taller. Work like a charm.

body: remove all c3 to c10 capacitors of 22pf. This will increase sensitivity and will sense through 5 mm sheet also .


body:
Consider the following code:

    void loop() {
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);

      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if (buttonState == HIGH) {
        // turn LED on:
        digitalWrite(ledPin, HIGH);
      }
      else {
        // turn LED off:
        digitalWrite(ledPin, LOW);
      }
    }

The line **buttonState = digitalRead(buttonPin);** checks the input voltage.

But how is that checked internally?

I mean at what rate the input is checked?

title: At what frequency/rate does the digitalRead function read an input?

Answers: 3

body:
That depends on the frequency your Arduino runs at.

It's basically once per iteration of the loop, and that depends on everything that is happening in the loop.

You can examine the assembly language output of the compiler (disassemble the .elf file using `avr-objdump -h -S <elf file>`) and count the number of clock cycles per iteration (the datasheet has the number of clock cycles per instruction). However that is tedious.

If you want to read the input at a specific frequency then you should do it using a timer interrupt.

body:
> When I get time, I will provide more definitive answers.

I did follow through with this, and the result is here, towards the end of the page: https://dannyelectronics.wordpress.com/2016/05/01/the-price-of-avr-arduino/

the short answer is: digitalRead() takes 4.9us to execute on a 16MIPS Arduino Uno, or 79 ticks (=instructions).

the fastest you can read digitalRead() is then 200KHz (= 1/4.9us).

Hope it helps.

body:
It read a port just like it reads memory (to which it's mapped.) So speed is how fast an instruction can read memory.  EEPROM is a different animal.

Might get it a little faster by replacing

buttonState = digitalRead(buttonPin);
    with
buttonState = PORTB & _BV(buttonPin);

Assuming it's PORTB that you are using. This will alleviate at least one function call, I would think, and will generate a single instruction to read the port into the variable. It may require an instruction to load the variable address, but that's up to the compiler.  The replacement may be more trouble porting to other micros.  Normally you don't see a variable as a parameter although legal, usually a constant in a #define.

 _BV(INPUT_PIN_X) is a macro (BV is for 'bit value') that expands to
(1 << INPUT_PIN_X)

dannyf times seem quick to me, but it sounds like he's done the testing. Is he taking into account the complete function call as part of the time?  I run at 1Mhz normally, so it's more difficult to relate.

Take Majenko advice and start reading the generated assembler :)

Best of luck.


body:
I'm running the Uno board and want to connect the BLE Bluetooth shield (http://redbearlab.com/bleshield/) to control the Braccio Arm I have.

When I sit the Braccio Arm Shield on the Uno everything works - I can control the Arm.

When I sit the Bluetooth Shield on the Uno, everything works I can find the device and connect to it using the IOS App.

When I sit all 3 together, I can still control the arm but can no longer find the Bluetooth device.

Any ideas as to why this is?

title: Arduino Uno, BLE Bluetooth Shield and Braccio Arm Shield

Answers: 1

body:
Be aware that the BLE Shield is using  a SPI interface therefore on Arduino Uno the SPI bus uses pins 10 (SS), 11 (MOSI), 12 (MISO), and 13 (SCK) and the Nordic’s ACI requires two hand-shake signals, RDYN and REQN, two additional pins will be used (pins 8 & 9 in the default settings), from [BLEshield][1]
Therefore the BLE shield uses 6 pins e the [Braccio][2] uses almost all Arduino Uno pins.
Conclusion, you probably can't have both shields together as the Arduino Uno hasn't enough pins.

You can try an Arduino MEGA and adapt the shields connections wiring them together using different pins for the Braccio interface for example

  [1]: http://redbearlab.com/bleshield/
  [2]: http://www.arduino.org/products/tinkerkit/arduino-tinkerkit-braccio


body:
 I'm trying to test AT commands (I am working with an  Arduino Uno and a GSM/GPRS SIM900  shield; my system is ubuntu 14.10) . Yesterday when I was testing , all  ran well.. For example after typing AT+SAPBR=3,1,"APN","ooredoo" in the serial monitor it  showed me OK.. but But now it  shows me strange  characters.

This is my code

        #include <SoftwareSerial.h>
        SoftwareSerial GPRS(2,3);

    void setup() {
      // put your setup code here, to run once:
     GPRS.begin(9600);
      Serial.begin(9600);
     Serial.write("start");

    }

    void loop() {

      // put your main code here, to run repeatedly:
         while(GPRS.available())
         Serial.write(GPRS.read());

      while(Serial.available())
        GPRS.write(Serial.read());

    }

And this it is the result of AT+SAPBR=3,1,"APN","ooredoo" typed in the serial monitor

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

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

Thank you for helping me

title: Strange characters after typing an AT command in serial monitor

Answers: 1

body:
for those who have this issue, i resolve this by changing the speed baud of my GPRS Shield :

    GPRS.begin(2400);
    Serial.begin(9600);

and if you want to test AT command directly on the serial monitor you must use 2400 anywhere

    GPRS.begin(2400);
        Serial.begin(2400);

and don't forget to change also  the speed on the serial monitor to 2400
I hope this will help someone


body: I am under the impression that the origin of RAM on a Cortex M is 0x20000000.  However, in the linker file for it, the ORIGIN of RAM is set to 0x1FFFF800.  Is that an error, or is there a reason for the discrepancy?

title: Teensy lc linker script question

Answers: 1

body:
The Cortex M does not "have RAM at 0x2000000". The Cortex M is just a CPU. It is down to the chip manufacturer where they choose to place RAM in the memory map.

In the case of the [MKL26Z64VFT4](https://www.pjrc.com/teensy/KL26P121M48SF4RM.pdf) used on the Teensy LC:

> The on-chip SRAM is a single contiguous block split into two ranges: 1/4 is allocated to SRAM_L, and 3/4 is allocated to SRAM_U. Regardless of the block size, the SRAM is implemented such that:
>
> * SRAM_L is anchored to 0x1FFF_FFFF and occupies the space before this ending address.
> * SRAM_U is anchored to 0x2000_0000 and occupies the space after this beginning address.
>
> Valid address ranges for SRAM_L and SRAM_U are then defined as:
>
> * SRAM_L = [0x2000_0000–(SRAM_size/4)] to 0x1FFF_FFFF
> * SRAM_U = 0x2000_0000 to [0x2000_0000+(SRAM_size*(3/4))-1]

Since there is 8kB of SRAM, 2kB is below 0x2000000 and 6kB is above 0x20000000. 2kB is 0x800. 0x2000000 - 0x800 = 0x1FFFF800.


body:
I have an arduino thing, and the hardware I plan to connect to it (a triac zero-crossing based dimmer) provides a synchronization signal from the mains power phase it connects to.

Main power does of course vary some from the nominal 60Hz, however the exact frequency gets adjusted over the course of the day to ensure there are almost exactly 5184000 cycles per day and pretty much exactly 36288000 cycles per week, and is used by mains-powered wall clocks to keep time.

Since my application will need to keep accurate time-of-day across weeks or months without adjustment, it would be advantageous to be able to use this time source.

I can of course write my own code to increment a counter every time the arduino receives a pulse, but if a library that can handle this already exists, I would prefer to use that, in particular since then I won't have to write code to track days and months, handle DST, or any of that stuff.

What libraries exist (if any) to handle timekeeping based on a fixed-pulse-rate input source?

title: Mains-Frequency Clock Library

Answers: 1

body: Counting the pulses is child's play and doesn't need a library (hint: use an interrupt input and increment a counter). From that count you can use [TimeLib.h](https://github.com/PaulStoffregen/Time) to convert seconds since 01/01/1970 to an actual time.  Or just do simple division to convert seconds (`count/50`) into minutes, hours, whatever division you want.


body: I currently have a project using an Arduino R3, set up across the room from my computer. This has become quite annoying, as every time I want to push something to the Arduino I have to get up and move either the computer or the Arduino to another location, plug it in, and hope my code works the first time, lest I have to repeat the test over and over again. I am trying to set up an SSH server between my Raspberry Pi 2 and computer so I can just push new sketches over SSH, however, I use my Pi 2 for other projects occasionally and want to purchase a second board specifically for this purpose. Is there a good, cheap, board with wifi built in (besides the Pi 3) that I could use for this? Any suggestions?

title: What is the best board for setting up an SSH protocol to an Arduino?

Answers: 3

body: Sounds like you want an [Arduino Yun](https://www.arduino.cc/en/Main/ArduinoBoardYun) instead of an Uno.  Or a [Dragino Yun Shield](http://www.dragino.com/products/yunshield/item/86-yun-shield.html) that turns your Uno into a Yun.

body:
If you get it working on the Pi2, could you just drop in a Pi Zero ($5) and a cheap USB network adapter ($2)?

Note that your question title asks for "best", but you don't define your criteria.  Reading between the lines I suspect "cheapest and adequate" is what you mean.

body: You could swap out the Arduino for a ESP012, not sure it meets your I/O needs. The new ESPs support over wifi firmware uploads.


body:
I am trying to build an array of LEDs where their brightness is controlled by a potentiometer.  The LCD will display the percentage of brightness based on the potentiometer.  I am able to successfully control the brightness of a circuit with only one LED.  However, I am having trouble with 2 two LEDs in series (which are in parallel with other sets of 2 LEDs in series).  And I believe the problem is that the Arduino is only supplying enough voltage to power one LED (maybe < 5V).  How can I properly wire a 9V battery to this circuit in which the potentiometer can control the amount voltage coming from this battery?  Are Arduinos only capable of controlling <5V with a potentiometer?

Here is my code:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    int potPin = A0;
    int ledPin = 6;
    int potValue = 0;

    void setup() {
      pinMode(potPin, INPUT);
      pinMode(ledPin, OUTPUT);
      lcd.begin(16, 2);
      lcd.print("Potentiometer");
    }

    void loop() {
      potValue = (analogRead(potPin)/10.02);
      analogWrite(ledPin, potValue);
      lcd.setCursor(0,1);
      lcd.print(potValue);
      lcd.print("%");
      delay(100);
      lcd.print(" ");
      delay(1);
    }

And here is a picture of my circuit setup:

[![LED array with potentiometer, LCD, and Arduino][1]][1]

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

title: Wiring a potentiometer to control a 9V battery powering 2 LEDs in series

Answers: 1

body:
Yes, Arduino is a 5V microcontroller, meaning it can directly control 5V circuits only. You might incur in problems also trying to deal with 3.3V circuits, even if Arduino is pretty friendly to 3.3V counterparts.

That does not mean though you cannot control higher voltage circuits, just not directly. Actually if anything above 6V is connected to an Arduino PIN you will blow that pin and potentially others which are logically connected within the MCU, so be aware.

To control higher voltage circuits you have multiple options, in your case you are probably interested into using a BJT transistor, an 2N2222 might do.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

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

<!-- End schematic -->

Please note the values of R1 and R2 must be adjusted to the LEDs you are using depending on their Vf (forward voltage drop) and the maximum current you want to provide.


body:
I am building a quadcopter with this schematic:
[![enter image description here][1]][1]

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

It works very good but i have the pins on 3,5,6,9 = PWM pins. Is it possible to use "regular" pins instead? I will add more modules later on so i will most likely run out of PWM pins.

I could of course try it right now but i want to ask first so i could potentially avoid to destroy any items!

title: Do I need to use the PWM pins in order to control brushless motors Arduino Uno?

Answers: 1

body:
No, you need to use PWM in order to control the ESCs which, in turn, control the motors. If you need more PWMs you might add daugtherboard based on other ICs which might provide additional PWM outputs via I2C or serial interface.

In some non critical conditions (ESCs **are** critical for a quadcopter) you can simulate PWM by switching a plain digital pin HIGH and LOW very quickly, but that is not as reliable as using hardware PWM.


body:
How do you make a fading led with 8 different colors I already made a blinking led every 1 second. Can you give me an idea how am I going to fade it every time it switch?

    const int red = 5;
    const int green = 6;
    const int blue = 9;

    void setup() {
        // put your setup code here, to run once:
        pinMode(red, OUTPUT);
        pinMode(green, OUTPUT);
        pinMode(blue, OUTPUT);
    }

    void loop() {
        lightMe(red);
        lightMe2(red, green);  // yellow
        lightMe(green);
        lightMe2(green, blue);  // cyan
        lightMe(blue);
        lightMe2(blue, red);  // magenta
        lightMe3(red, green, blue); // white
    }

    void lightMe(int pin){
        digitalWrite(pin, HIGH);
        delay(1000);
        digitalWrite(pin, LOW);
        delay(500);
    }

    void lightMe2(int pin1, int pin2) {
        digitalWrite(pin1, HIGH);
        digitalWrite(pin2, HIGH);
        delay(1000);
        digitalWrite(pin1, LOW);
        digitalWrite(pin2, LOW);
        delay(500);
    }

    void lightMe3(int pin1, int pin2, int pin3) {
        digitalWrite(pin1, HIGH);
        digitalWrite(pin2, HIGH);
        digitalWrite(pin3, HIGH);
        delay(1000);
        digitalWrite(pin1, LOW);
        digitalWrite(pin2, LOW);
        digitalWrite(pin3, LOW);
        delay(500);
    }

title: Fading LED Lights

Answers: 2

body:
You could look at this example, which fades an LED using PWM.

https://www.arduino.cc/en/Tutorial/Fading

Basically you use `analogWrite` to control the output of the pins with finer resolution, 0-255 rather than 0-1.  Only certain pins support PWM, they should be marked on your board.  You just need to extend the example to support your LED.  (Put the resistor on the common pin)

body:
    int color_set = 0;    //set to red first
    int wait_fade = 1000 // delay time in ms.  1000ms is equal to 1sec

    // set the color for all the LEDs based on the color code
    void setcolor(int colorcode) {

      for (int i = 0; i < LED_COUNT; i++) {
        // instead of setting the color all at once we're going to step through each LED to show how to set them individually
        switch(colorcode) {
          // We're going to pass a CRGB here,
      case 0: leds[i] = CRGB(255, 0 , 0); break; // red

      case 1: leds[i] = CRGB(255, 127, 0); break; // orange

      case 2: leds[i] = CRGB(255, 255, 0); break; // yellow

      case 3: leds[i] = CRGB(0, 255, 0); break; // green

      case 4: leds[i] = CRGB(0, 255, 255); break; // cyan

      case 5: leds[i] = CRGB(0, 0, 255); break; // blue

      case 6: leds[i] = CRGB(75, 0, 130); break; // indigo

      case 7: leds[i] = CRGB(148, 0, 211); break; // violet
    }
      }
         LEDS.show();
        }
    // we'll make the color fade in and out by setting the brightness
    void pulse(int wait_fade) {
      // let's fade up by scaling the brightness - in general, brightness shouldn't go above 93, so the strip won't draw too much power.
      // Oh, and 93 is plenty bright!
      for(int scale = 0; scale < 93; scale++) {
        LEDS.setBrightness(scale);
        LEDS.show();
        delay(wait_fade);
      }
      // now let's fade down by scaling the brightness
      for(int scale = 93; scale > 0; scale--) {
        LEDS.setBrightness(scale);
        LEDS.show();
        delay(wait_fade);
      }
    }

    // this is the main loop where we call the other functions.
    void loop() {
      int waiting_time = 10; //time in ms for color scaling
      setcolor(color_set);  //we call our color-set routine
      pulse(waiting_time); //now we make it fade in and out
      color_set++;        //next color
      color_set = color_set % 8; // number of color modulus, remember it's 0 based.
    }

because there are so many different microcontrollers, i left it basic, and you only need to define `color_set` as a integer and then the `setcolor()` loop, as you can see in the main loop we pass the parameter color_set from our *integral* 8 colors. here is my complete arduino setup:

    #include <FastLED.h>

    #define LED_COUNT 96 // number of LEDs!
    struct CRGB leds[LED_COUNT]; // this struct contains 60 CRGB values.

    #define PIN_BUTTON 10
    #define PIN_IO_A   7
    #define PIN_IO_B   11
    #define PIN_SIGNAL 13
    #define PIN_INPUT  10

    int color_set = 0;   // set to red
    int wait_fade = 1000 // delay time in ms.  1000ms is equal to 1sec
    // first, let's get ready to blink using some FastLED routines
    // take a look at the FastLED example called Fast2Dev for more usage info
    void setup()
    {
      LEDS.addLeds<WS2812B, PIN_SIGNAL, GRB>(leds, LED_COUNT); // this configures the Board - leave as is.
      LEDS.showColor(CRGB(0, 0, 0)); // set the color for the strip all at once.
      LEDS.setBrightness(0); // start out with LEDs off
      LEDS.show(); // you'll always need to call this function to make your changes happen.
    }

    // set the color for all the LEDs based on the color code
    void setcolor(int colorcode) {

      for (int i = 0; i < LED_COUNT; i++) {
        // instead of setting the color all at once we're going to step through each LED to show how to set them individually
        switch(colorcode) {
          // We're going to pass a CRGB here,
      case 0: leds[i] = CRGB(255, 0 , 0); break; // red

      case 1: leds[i] = CRGB(255, 127, 0); break; // orange

      case 2: leds[i] = CRGB(255, 255, 0); break; // yellow

      case 3: leds[i] = CRGB(0, 255, 0); break; // green

      case 4: leds[i] = CRGB(0, 255, 255); break; // cyan

      case 5: leds[i] = CRGB(0, 0, 255); break; // blue

      case 6: leds[i] = CRGB(75, 0, 130); break; // indigo

      case 7: leds[i] = CRGB(148, 0, 211); break; // violet
    }
      }
         LEDS.show();
        }
    // we'll make the color fade in and out by setting the brightness
    void pulse(int wait_fade) {
      // let's fade up by scaling the brightness - in general, brightness shouldn't go above 93, so the strip won't draw too much power.
      // Oh, and 93 is plenty bright!
      for(int scale = 0; scale < 93; scale++) {
        LEDS.setBrightness(scale);
        LEDS.show();
        delay(wait_fade);
      }
      // now let's fade down by scaling the brightness
      for(int scale = 93; scale > 0; scale--) {
        LEDS.setBrightness(scale);
        LEDS.show();
        delay(wait_fade);
      }
    }

    // this is the main loop where we call the other functions.
    void loop() {
      int waiting_time = 10; //time in ms for color scaling
      setcolor(color_set);  //we call our color-set routine
      pulse(waiting_time); //now we make it fade in and out
      color_set++;        //next color
      color_set = color_set % 8; // number of color modulus, remember it's 0 based.
    }

A lot of the code is commented.  I use [FastLED][1] too.  If you have any questions please let me know.

  [1]: https://github.com/FastLED/FastLED/wiki/


body: Is it possible to use the analog output pin with some circuit to generate a 0 to 15V analog output?

title: Can I use Arduino to generate a 0 to 15V analog output?

Answers: 2

body:
The Arduino does not have any "analog output pin". There are analog inputs, and you can generate a variable output with `PWM` pins.

Whether the latter meets your needs depends on your (unstated) requirements.

body:
The Arduino cannot directly produce anything more than 5V.

You can use PWM and a Low-Pass Filter to produce an analog waveform between 0 and 5V, which you can then amplify using a suitable non-inverting buffer with 3x gain (op-amp), which will boost the voltage to 15V. Whether that is suitable for your needs, though, since the current will generally be quite low (most op-amps have a high output impedance) is unknown.

If you want a cleaner waveform you can attach or create a DAC which produces discrete output voltages (again between 0 and 5V) which you then amplify similarly.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

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

<!-- End schematic -->

R3 and C1 form the low-pass filter and should be sized according to the frequency ranges you want to filter and keep. Note that many op-amps that can cope with the higher voltages you need aren't *rail-to-rail* which means you will have to use a higher power supply voltage than you want to output to leave some headroom. Similarly the 0V will be clipped and will never go below a certain voltage. If you want to get right down to 0V you will need a negative power supply to feed the V- supply of the op-amp (which is currently connected to ground in this schematic). That would allow the output to drop right down to 0V.


body:
I am building a test IOT architecture. At the moment I do have a NodeMCU "Amica" V1 module (more will come) and some ESP-01. I have not yet tried to flash the ESP-01 because the MCU is just so user friendly, while buying 6 MCU is more pricey than .

I was wondering, if I do de-solder the ESP-12 from the NodeMCU and then connect a female receptacle for the ESP-01 to the now empty MCU breakout board, would i be able to flash the ESP-01 from the Arduino IDE?
Would it maintain the automatic Reset and Flash pulls (as on the stock ESP-12)?
Will it also work with a pogo-pin assembly to flash other ESP-07/12 ?

Approximate answers and thoughts are well accepted, thank you very much.

title: Flash Esp-01 and Esp-12 using NodeMCU module

Answers: 1

body:
On [this site][1] there's a description of how to use a USB-serial adapter to flash a ESP-01 with the Arduino IDE. I'm not very familiar with the NodeMCU boards, but I imagine that they contain a USB-serial chip, and thus it _is_ possible to desolder the ESP-12 and connect a ESP-01 (with cables or an adapter with pogo-pins) and program it that way. I'm not sure about the Reset/Flash pulls, but I imagine that it could be possible, study the pinouts for the ESP-12 and ESP-01 and circuitry for flashing (see the link). I did flash my ESP-01 this way, before I got other ESP8266 boards.

I would only do this operation if I was very handy with a soldering iron and the NodeMCU/ESP-12 was something that could go to waste if anything went wrong.

I think picking up a 3.3V LDO and USB-serial (3.3v!) breakout much easier, and more failproof, so that's what I'd recommend.

  [1]: https://www.hackster.io/rayburne/esp8266-01-using-arduino-ide-67a124


body:
Recently I salvaged a BIOS chip (EN25QH16) which has 2 Megabytes of memory (8192 pages, 256 bytes/page). I followed this [instructables](http://www.instructables.com/id/How-to-Design-with-Discrete-SPI-Flash-Memory/) and it works. I double checked the opcodes because the code is for a `Winbond` chip, mine is `Eon` and of course, they're the same (standards?). All commands worked as it should. I modified the code that writes `Hello World` string to a page. I tried the command but it returns (from the memory) `Hello Worlb`. This is the snap of the serial monitor:

[![serialmonitor][1]][1]
  [1]: https://i.stack.imgur.com/YAXLX.png

I erased the chip just to make sure and ran the command `test_write` (which I added). It wrote `48 65 6c 6c 6f 20 57 6f 72 6c 00 62 03 0b 00 0b 00` which is in ASCII `Hello Worlb` and I don't know why that happened. Btw this is the modified code:

    /*
        windbond_serial_debug.cpp
        A simple program for the Arduino IDE to help familiarize you with
        using WinBond flash memory; can also be used to download the entire
        contents of a flash chip to a file via a serial port interface.

        Important bits of the code: the low-level flash functions (which
        implement the timing diagrams in the datasheet), and a simple
        serial-port command interface that allows you to talk to your
        UNO with any generic terminal application (even the command line).

        Copyright 2014, Peter J. Torelli

        This program is free software: you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation, either version 3 of the License, or
        (at your option) any later version.

        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

        You should have received a copy of the GNU General Public License
        along with this program.  If not, see <http://www.gnu.org/licenses/>

    Revisions:
        rev 2 - 21-SEP-2014.
        User 'fiaskow' pointed out that driving the WEL instruction after
        program and erase w/o waiting for the op to finish may be corrupting
        execution. Removed this code (also not needed b/c the WEL is already
        cleared after page write or chip erase).
    */

    #include <SPI.h>
    // SS:   pin 10
    // MOSI: pin 11
    // MISO: pin 12
    // SCK:  pin 13

    // WinBond flash commands
    #define WB_WRITE_ENABLE       0x06
    #define WB_WRITE_DISABLE      0x04
    #define WB_CHIP_ERASE         0xc7
    #define WB_READ_STATUS_REG_1  0x05
    #define WB_READ_DATA          0x03
    #define WB_PAGE_PROGRAM       0x02
    #define WB_JEDEC_ID           0x9f

    /*
     * These global variables enable assembly of the user serial
     * input command.
     */
    boolean g_command_ready(false);
    String g_command;

    /*
     * print_page_bytes() is a simple helperf function that formats 256
     * bytes of data into an easier to read grid.
     */
    void print_page_bytes(byte *page_buffer) {
      char buf[10];
      for (int i = 0; i < 16; ++i) {
        for (int j = 0; j < 16; ++j) {
          sprintf(buf, "x", page_buffer[i * 16 + j]);
          Serial.print(buf);
        }
        Serial.println();
      }
    }

    /*
    ================================================================================
    User Interface Routines
    The functions below map to user commands. They wrap the low-level calls with
    print/debug statements for readability.
    ================================================================================
    */

    /*
     * The JEDEC ID is fairly generic, I use this function to verify the setup
     * is working properly.
     */
    void get_jedec_id(void) {
      Serial.println("command: get_jedec_id");
      byte b1, b2, b3;
      _get_jedec_id(&b1, &b2, &b3);
      char buf[128];
      sprintf(buf, "Manufacturer ID: xh\nMemory Type: xh\nCapacity: xh",
        b1, b2, b3);
      Serial.println(buf);
      Serial.println("Ready");
    }

    void chip_erase(void) {
      Serial.println("command: chip_erase");
      _chip_erase();
      Serial.println("Ready");
    }

    void read_page(unsigned int page_number) {
      char buf[80];
      sprintf(buf, "command: read_page(xh)", page_number);
      Serial.println(buf);
      byte page_buffer[256];
      _read_page(page_number, page_buffer);
      print_page_bytes(page_buffer);
      Serial.println("Ready");
    }

    void delayed_read_all_pages(void) {
      delay(5000);
      read_all_pages();
      }

    void read_all_pages(void) {
      Serial.println("command: read_all_pages");
      byte page_buffer[256];
      for (int i = 0; i < 4096; ++i) {
        _read_page(i, page_buffer);
        print_page_bytes(page_buffer);
      }
      Serial.println("Ready");
    }

    void write_byte(word page, byte offset, byte databyte) {
      char buf[80];
      sprintf(buf, "command: write_byte(xh, xh, xh)", page, offset, databyte);
      Serial.println(buf);
      byte page_data[256];
      _read_page(page, page_data);
      page_data[offset] = databyte;
      _write_page(page, page_data);
      Serial.println("Ready");
    }

    /*
    ================================================================================
    Low-Level Device Routines
    The functions below perform the lowest-level interactions with the flash device.
    They match the timing diagrams of the datahsheet. They are called by wrapper
    functions which provide a little more feedback to the user. I made them stand-
    alone functions so they can be re-used. Each function corresponds to a flash
    instruction opcode.
    ================================================================================
    */

    /*
     * See the timing diagram in section 9.2.35 of the
     * data sheet, "Read JEDEC ID (9Fh)".
     */
    void _get_jedec_id(byte *b1, byte *b2, byte *b3) {
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_JEDEC_ID);
      *b1 = SPI.transfer(0); // manufacturer id
      *b2 = SPI.transfer(0); // memory type
      *b3 = SPI.transfer(0); // capacity
      digitalWrite(SS, HIGH);
      not_busy();
    }

    /*
     * See the timing diagram in section 9.2.26 of the
     * data sheet, "Chip Erase (C7h / 06h)". (Note:
     * either opcode works.)
     */
    void _chip_erase(void) {
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_WRITE_ENABLE);
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_CHIP_ERASE);
      digitalWrite(SS, HIGH);
      /* See notes on rev 2
      digitalWrite(SS, LOW);
      SPI.transfer(WB_WRITE_DISABLE);
      digitalWrite(SS, HIGH);
      */
      not_busy();
    }
    void _write_test(void) {
      String sampleText = "Hello World";
      byte data[sampleText.length()];
      sampleText.getBytes(data, sizeof(data));
      _write_page(0,data);
      }
    /*
     * See the timing diagram in section 9.2.10 of the
     * data sheet, "Read Data (03h)".
     */
    void _read_page(word page_number, byte *page_buffer) {
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_READ_DATA);
      // Construct the 24-bit address from the 16-bit page
      // number and 0x00, since we will read 256 bytes (one
      // page).
      SPI.transfer((page_number >> 8) & 0xFF);
      SPI.transfer((page_number >> 0) & 0xFF);
      SPI.transfer(0);
      for (int i = 0; i < 256; ++i) {
        page_buffer[i] = SPI.transfer(0);
      }
      digitalWrite(SS, HIGH);
      not_busy();
    }

    /*
     * See the timing diagram in section 9.2.21 of the
     * data sheet, "Page Program (02h)".
     */
    void _write_page(word page_number, byte *page_buffer) {
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_WRITE_ENABLE);
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_PAGE_PROGRAM);
      SPI.transfer((page_number >>  8) & 0xFF);
      SPI.transfer((page_number >>  0) & 0xFF);
      SPI.transfer(0);
      for (int i = 0; i < 256; ++i) {
        SPI.transfer(page_buffer[i]);
      }
      digitalWrite(SS, HIGH);
      /* See notes on rev 2
      digitalWrite(SS, LOW);
      SPI.transfer(WB_WRITE_DISABLE);
      digitalWrite(SS, HIGH);
      */
      not_busy();
    }

    /*
     * not_busy() polls the status bit of the device until it
     * completes the current operation. Most operations finish
     * in a few hundred microseconds or less, but chip erase
     * may take 500+ms. Finish all operations with this poll.
     *
     * See section 9.2.8 of the datasheet
     */
    void not_busy(void) {
      digitalWrite(SS, HIGH);
      digitalWrite(SS, LOW);
      SPI.transfer(WB_READ_STATUS_REG_1);
      while (SPI.transfer(0) & 1) {};
      digitalWrite(SS, HIGH);
    }

    /*
     * This handy built-in callback function alerts the UNO
     * whenever a serial event occurs. In our case, we check
     * for available input data and concatenate a command
     * string, setting a boolean used by the loop() routine
     * as a dispatch trigger.
     */
    void serialEvent() {
      char c;
      while (Serial.available()) {
        c = (char)Serial.read();
        if (c == ';') {
          g_command_ready = true;
        }
        else {
          g_command += c;
        }
      }
    }

    void setup(void) {
      SPI.begin();
      SPI.setDataMode(0);
      SPI.setBitOrder(MSBFIRST);
      Serial.begin(9600);
      Serial.println("");
      Serial.println("Ready");
    }

    /*
     * loop() dispatches the commands compiled by the serialEvent
     * parser callback. Some commands take multiple arguments, so
     * I have to split up the strings with some messy manipulation.
     */
    void loop(void) {
      if (g_command_ready) {
        if (g_command == "get_jedec_id") {
          get_jedec_id();
        }
        else if (g_command == "test_write") {
          Serial.println("Custom command: test_write");
          _write_test();
          }
        else if (g_command == "chip_erase") {
          chip_erase();
        }
        else if (g_command == "read_all_pages") {
          read_all_pages();
        }
        else if (g_command == "delayed_read_all_pages") {
          Serial.println("Custom command: delayed_read_all_pages");
          delayed_read_all_pages();
          }
        // A one-parameter command...
        else if (g_command.startsWith("read_page")) {
          int pos = g_command.indexOf(" ");
          if (pos == -1) {
            Serial.println("Error: Command 'read_page' expects an int operand");
          } else {
            word page = (word)g_command.substring(pos).toInt();
            read_page(page);
          }
        }
        // A three-parameter command..
        else if (g_command.startsWith("write_byte")) {
          word pageno;
          byte offset;
          byte data;

          String args[3];
          for (int i = 0; i < 3; ++i) {
            int pos = g_command.indexOf(" ");
            if (pos == -1) {
              Serial.println("Syntax error in write_byte");
              goto done;
            }
            args[i] = g_command.substring(pos + 1);
            g_command = args[i];
          }
          pageno = (word)args[0].toInt();
          offset = (byte)args[1].toInt();
          data = (byte)args[2].toInt();
          write_byte(pageno, offset, data);
        }
        else {
          Serial.print("Invalid command sent: ");
          Serial.println(g_command);
          g_command = "";
        }
    done:
        g_command = "";
        g_command_ready = false;
      }
    }

title: Writing to a SPI memory

Answers: 1

body:
Strings in C are terminated with a null byte - so the string "A" is in fact two bytes: the 'A' followed by a null.

Your `_write_test()` function counts only the characters in the string, and hence allocates one byte too few.  It should be:

    void _write_test(void) {
      String sampleText = "Hello World";
      byte data[sampleText.length()+1];
      sampleText.getBytes(data, sizeof(data));
      // See text below before calling write_page()
    }

But then we hit the issue of how much data `write_page()` will write.  It doesn't have any way of knowing how much data you are passing in - it just gets a pointer.  Looking at its implementation we can see that it writes exactly 256 bytes, so we need to pass in a buffer of 256 bytes.

    void _write_test(void) {
      String sampleText = "Hello World";
      byte data[256];
      sampleText.getBytes(data, sizeof(data));
      _write_page(0,data);
      }

(If we pass in a smaller buffer we're leaving it up to chance what will happen.  The Arduino doesn't have much protection so probably you'll just write garbage, but maybe, just maybe, you'll get unlucky and some weird crash will happen.)


body:
A byte stores an 8-bit unsigned number, from 0 to 255.

I can understand the following line:

    byte b = B10010;  // "B" is the binary formatter (B10010 = 18 decimal)

But I also saw a use such as:

    volatile byte state = LOW;

What does the last line mean here? Is that special for Arduino?
I mean LOW is not a 8 bit unsigned number. LOW is not a number here.

title: Confusion in the use of byte variable

Answers: 3

body:
There is probably somewhere else, like this:

    #define LOW 0

Which means the pre-processor turns your line from this:

    volatile byte state = LOW;

into this:

    volatile byte state = 0;

There is nothing arduino-specific here, just the use of standard C/C++ features.

body:
In the same way that you can do

    int blarb = 12;
    #define wibble 73

you can do

    int FOO = 73;
    #define BINKY 99

or even

    int LOW = 0;
    #define HIGH 1

So in the line

    volatile byte state = LOW;

someone has created some sort of numerical constant with the name `LOW`.

You can read all about various constants provided for you [here][1].

  [1]: https://www.arduino.cc/en/Reference/Constants

body:
It is common practise in C/C++ to define certain much-used constants at the beginning of the code.

    #define true 1

this means that every time you write true in your code, the compiler will see it as 1.

The arduino IDE comes with a few constants predefined:

 - true = 1
 - false = 0
 - HIGH = 1
 - LOW = 0
 - ...


body:
I have a robot that uses two motors to skid steer. The robot gets input from three ultrasonic sensors (left, middle, and right) and a passive infrared sensor. If the robot detects a person in front of it, then it follows.

The sensors seem to work as they are intended. The infrared sensor sees a person and the ultrasonic sensors see that the person is between 65cm and 150cm and it follows. If the left ultrasonic sensor has the person in range, it turns left, and if the right ultrasonic sensor has the person in range, it turns right.

The problem is that the robot gets stuck turning left or turning right depending on which sensor it checks first in the code. It's like it's stuck in a while loop even though I'm not using a while loop.

I have adapted [NewPing][1] and library. The code in question is at the bottom in the last function. The rest is part of NewPing to read the ultrasonic sensors.

If anybody has any suggestions, it would be greatly appreciated.

    #include <NewPing.h>

    #define SONAR_NUM     3 // Number of sensors.
    #define MAX_DISTANCE 170 // Maximum distance (in cm) to ping.
    #define PING_INTERVAL 35 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).

    unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
    unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.
    uint8_t currentSensor = 0;          // Keeps track of which sensor is active.

    NewPing sonar[SONAR_NUM] = {     // Sensor object array.
      NewPing(11, 4, MAX_DISTANCE), //Left -- Each sensor's trigger pin, echo pin, and max distance to ping.
      NewPing(8, 3, MAX_DISTANCE),  //Center
      NewPing(7, 9, MAX_DISTANCE),  //Right
    };

    int ledR = 13;
    int ledG = 2;
    int ledB = A0;
    int motorPinL = 5;
    int motorPinR = 6;
    int ePIR = 10;
    boolean epirVal;

    void setup() {
      Serial.begin(115200);
      pingTimer[0] = millis() + 75;           // First ping starts at 75ms, gives time for the Arduino to chill before starting.
      for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
        pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
      pinMode (ledR, OUTPUT);
      pinMode (ledG, OUTPUT);
      pinMode (ledB, OUTPUT);
      pinMode (motorPinL, OUTPUT);
      pinMode (motorPinR, OUTPUT);
      pinMode (ePIR, INPUT);
    }

    void loop() {
      for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
        if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
          pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
          if (i == 0 && currentSensor == SONAR_NUM - 1)
            oneSensorCycle();                             // Sensor ping cycle complete, do something with the results.
          sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
          currentSensor = i;                          // Sensor being accessed.
          cm[currentSensor] = 155;                      // Make distance 155 in case there's no ping echo for this sensor. changed from zero
          sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
        }
      }
      // Other code that *DOESN'T* analyze ping results can go here.
    }

    void echoCheck() { // If ping received, set the sensor distance to array.
      if (sonar[currentSensor].check_timer())
        cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
    }

    void allStop () {
      analogWrite (motorPinL, 0);
      analogWrite (motorPinR, 0);
      digitalWrite (ledG, LOW);    //LED corresponding to right ultrasonic sensor
      digitalWrite (ledR, LOW);    //LED corresponding to left ultrasonic sensor
      digitalWrite (ledB, LOW);    //LED corresponding to center ultrasonic sensor
    }

  [1]: http://playground.arduino.cc/Code/NewPing

title: Multiple if statements - stuck

Answers: 1

body:
Your logic is flawed. Translating your loop in pseudocode gives
something like this:

    if (PIR does not detect OR ANY sonar is out of range) {  // cond. 1
        stop
    } else if (PIR does detect AND right sonar is in range) {  // cond. 2
        turn right
    } else if (PIR does detect AND left sonar is in range) {  // cond. 3
        turn left
    } else if (PIR does detect AND center sonar is in range) {  // cond. 4
        go straight
    }

Notice that, if condition 1 is false, then that means that the PIR does
detect AND ALL of the sonars are in range. Which implies that condition
2 is necessarily true. Which implies that the following elses have no
effect. Your code can then be optimized (and the compiler probably did
optimize it) into

    if (ANY sonar is out of range OR PIR does not detect) {  // cond. 1
        stop
    } else {  // cond. 2 is true if cond 1. is false
        turn right
    }

You should rethink your problem asking yourself the following questions:

* under what conditions should the robot turn right?
* under what conditions should the robot turn left?
* under what conditions should the robot go straight?
* under what conditions should the robot stop?

Make sure that in any circumstance EXACTLY one of the above conditions
holds true. In other words, the conditions should be mutually exclusive
and cover every possibility. One you have the answers, the coding should
be straightforward.

------------------------------------------------------------------------

**Edit**: Your updated code still contains logic flaws. For example, if
the PIR senses the person and BOTH the left and right sonars are in
range, then you are asking the robot to BOTH turn left and turn right.
Unless it's a quantum robot evolving in an Everett's multiverse, it
won't be able to comply. To the risk of repeating myself, you must
decide on one and only one action for every possible situation.

If you are struggling with that concept, I suggest you start by filling
the truth table below. On each of the 16 lines of the table you should
fill the last column with one (and only one) action among: `allStop`,
`turnRight`, `turnLeft` and `straight`. Yes, I know it's tedious to
consider all the possible situations one by one, but you _must_ do that
before starting to write the code. Otherwise you end up with completely
broken logic.

    +--------+----------+----------+----------+-----------+
    | PIR    | sonar 0  | sonar 1  | sonar 2  |  robot    |
    | senses | in range | in range | in range |  action   |
    +--------+----------+----------+----------+-----------+
    |  no    |   no     |   no     |   no     |           |
    |  no    |   no     |   no     |   yes    |           |
    |  no    |   no     |   yes    |   no     |           |
    |  no    |   no     |   yes    |   yes    |           |
    |  no    |   yes    |   no     |   no     |           |
    |  no    |   yes    |   no     |   yes    |           |
    |  no    |   yes    |   yes    |   no     |           |
    |  no    |   yes    |   yes    |   yes    |           |
    |  yes   |   no     |   no     |   no     |           |
    |  yes   |   no     |   no     |   yes    |           |
    |  yes   |   no     |   yes    |   no     |           |
    |  yes   |   no     |   yes    |   yes    |           |
    |  yes   |   yes    |   no     |   no     |           |
    |  yes   |   yes    |   no     |   yes    |           |
    |  yes   |   yes    |   yes    |   no     |           |
    |  yes   |   yes    |   yes    |   yes    |           |
    +--------+----------+----------+----------+-----------+


body: If I want to power up 6 normal 3mm LED with the appropriate series limiting resistor, do I need the 5V with **1A** or **5A** power supply? Same goes to the Arduino, if I want to power it externally, do I go for the **1A** or **5A**?

title: 5V 1A vs 5V 5A power supply for 6 LED + Arduino

Answers: 2

body:
Depending on your led, it will draw 10 to 20mA for a standard led. Thats 0.010 to 0.020A. Multiply this by 6 and you see that a 1A power supply will be enough.

Your arduino, when driving those leds, will also use a few mA. So you can power everything with a 1A power supply.

body:
Both will work, but **go with 1A!!!**

It is more forgiving if a short happens.

A 5A short circuit will make sparks that might be dangerous.


body:
I don't know why but since yesterday, my Arduino sketch returns weird data. I've check eaches inputs and the returns values are ok.

But that line:

    sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));

returns something like this:

    3000;0;110;291;263;230;0;0 (It's like the analog reads are shift from 1 position to the right)

It's suppose to return something like this:

    3000;110;291;263;230;0;0;245

Here is my sketch:

    int HD = A0;
    int HG = A1;
    int CD = A2;
    int CG = A3;
    int ECG = A5;

    volatile boolean interruptFlag = 0;
    char read[45];
    char signal[2048];
    volatile int count = 0;
    volatile long x = 0;

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

      noInterrupts(); // Stop interrupts.

      TCCR1A = 0; // Set entire TCCR1A register to 0.
      TCCR1B = 0; // Same for TCCR1B.
      TCNT1  = 0; // Initialize counter value to 0.

      // Set compare match register for 50Hz increments.
      OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)

      // Turn on CTC mode.
      TCCR1B |= (1 << WGM12);
      // Set CS12, CS11 and CS10 bits for 64 prescaler.
      TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
      // Enable timer compare interrupt.
      TIMSK1 |= (1 << OCIE1A);

      interrupts(); // Allow interrupts.
    }

    ISR(TIMER1_COMPA_vect){
      if (!interruptFlag){
        interruptFlag = 1;
      }
    }

    void loop() {
      if (interruptFlag){
        writeAnalogSignals();
        count++;
        interruptFlag = 0;
      }
    }

    void writeAnalogSignals() {
      if (strlen(read) == 0) {
        sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
      } else {
        sprintf(read, "|%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
      }
      strcat(signal, read);

      x += 2;

      if (count >= 50) {
        Serial.print(signal);
        signal[0] = 0;
        count = 0;
      }
    }

title: Weird formatting behavior with sprintf function

Answers: 1

body:
Sometimes the sprintf can be used instead of 20 lines of code. In this case an array with integers and a loop with Serial.print would be better as Majenko already wrote.

When you do use the sprintf, a shift in the data means that one of the parameters has too many or too little bytes. The sprintf does not know the size of the parameter and the parameter will not be converted to a different type. When you use "%d", you have to put two bytes on the stack. Since your 'x' is 4 bytes, all those 4 bytes will be put onto the stack. The first "%d" reads two bytes of 'x' and the second "%d" read the other two bytes of 'x'. That is why it is shifted.

For a data rate of 50Hz, I suggest to raise the baudrate to 115200.

Using millis() for the 50Hz will result into the same timing accuracy as you have now. You don't need the timer and you don't need the interrupt.
See the [BlinkWithouDelay][1] example and use 20ms as an interval.

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


body:
On a Pi, to execute a C++ code, you'll need a Makefile.

Is there an equivalent with the Arduino? Where I have some valid C++ files to upload without the IDE's help, but instead with an executable?

title: Make Arduino Executable File

Answers: 2

body:
Whether you compile manually with a Makefile (or Arduino-Builder) or in the IDE, the end result is a HEX file.  This is a text file describing the data to load into the flash memory.

You then use avrdude to install it into the Arduino - either from the IDE or by running it manually (or specifying it in your Makefile, etc).

A Makefile doesn't produce an executable. A Makefile is merely a recipe - a set of instructions - telling the `make` program which programs to run (gcc, avr-gcc, etc) and in what order (and with what flags) to compile your code.

There are many Arduino Makefile projects out there that do it all for you.

body: Take a look at platformio.org. It Provides a simple CLI environment to compile, upload and monitor.


body:
Recently I have unsoldered most connector pins there are on the arduino uno board.
However, when I now attempt to upload a new sketch (works when I upload it to another model) it gives me the following error:

    > avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xfa
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xfa

I would like you take a look at my arduino board to see whether I have unsoldered important pins which might have to be connected.

Also when I try to upload a new sketch the 'L'-LED doesn't flash but the RX one.

(BTW: Yes I've set the settings to the correct board, port etc...)

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

  [1]: https://i.stack.imgur.com/8Ajo5.jpg

Thanks for any solution attempts!

title: Can't upload new sketch

Answers: 4

body: Pin 0(RX) and 1(TX) and the RESET pins are important to upload a sketch. Can you check those carefully with a magnifier ? Perhaps there is some solder that shortcuts to something else, or perhaps you damaged a copper trace.

body: Checking the schematic, the TX/RX leds are driven directly by the atmega16u and are not connected to the TX/RX lines of the 328p.  That would seem to indicate the 16u has a problem so it's a good place to double check. The lines that run to the TX/RX of the 328p run from pins 8 - 9 of the 16u. I assume that this ran previous to the fatal 'surgery'? I don't suppose you loaded something simple, like the led flash program before surgery?  Just curious, are you hard wiring it to something?

body:
Removing there pin headers should not cause any sketch upload issue. I have done it many times.

You did try uploading BEFORE unsoldering the headers right ?

However looking at the desoldering job you did, my guess is that you applied too much heat or cut a trace on the PCB while doing it.

Can you upload a high resolution of the back side of the board?

What I would try is to take a known good 328p chip and replace the one on this board with it and try uploading again.

body:
Try to unplug the IC and the plug it again.

I think that you have removed the IC off of the board. If it doesn't work then buy a new ATmega328P IC and replace it with the old one and then try again.


body:
I try to make a variable that can be modified from the server, using and ESP8266.

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

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

    ESP8266WebServer server(80);

    const int led = 13;

    void handleRoot() {
        digitalWrite(led, 1);
        server.send(200, "text/plain", "hello from esp8266!");
        digitalWrite(led, 0);
    }

    void handleNotFound() {
        digitalWrite(led, 1);
        String message = "File Not Found\n\n";
        message += "URI: ";
        message += server.uri();
        message += "\nMethod: ";
        message += (server.method() == HTTP_GET)?"GET":"POST";
        message += "\nArguments: ";
        message += server.args();
        message += "\n";

        for (uint8_t i=0; i<server.args(); i++){
            message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
        }

        server.send(404, "text/plain", message);
            digitalWrite(led, 0);
        }
    }

    void setup(void) {
        pinMode(led, OUTPUT);
        digitalWrite(led, 0);
        Serial.begin(115200);
        WiFi.begin(ssid, password);
        Serial.println("");

        // Wait for connection
        while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.print(".");
        }

        Serial.println("");
        Serial.print("Connected to ");
        Serial.println(ssid);
        Serial.print("IP address: ");
        Serial.println(WiFi.localIP());

        if (MDNS.begin("esp8266")) {
            Serial.println("MDNS responder started");
        }

        String content = "Basic";
        content += "<form action='action_page.php' method='POST'>
";
        content += "User:<input type='text' name='USERNAME' placeholder='user name'>
";
        content += "<input type='submit' name='SUBMIT' value='Submit'></form>
";

        server.on("/led", [](){
            server.send(200, "text/html", content);
            Serial.println(USERNAME);
        }

        server.on("/", handleRoot);

        server.on("/inline", [](){
            server.send(200, "text/plain", "this works as well");
        });

        server.onNotFound(handleNotFound);
        server.begin();
        Serial.println("HTTP server started");
    }

    void loop(void){
        server.handleClient();
    }

When I compile it, it says

> 'content' is not captured

I thought it may be from the input, and I tried to name it "Basic" for the start, but it still failed.

title: 'content' is not captured

Answers: 2

body: Are you looking at the last compiler error ? The first one is the most most important one. In the preferences, the compiler output can be turned on to show more. Then scroll up to see the first compiler error. The compiler has troubles with the `` at the very end of your sketch.

body:
Let's look at a simpler example:

    void setup ()
    {
      String content = "Basic";

      attachInterrupt (digitalPinToInterrupt (2),
                       []()
      {
        Serial.println(content);
      },

      FALLING );

    }  // end of setup

    void loop () { }

This gives the error:

    /tmp/arduino_modified_sketch_182173/sketch_jan25a.ino: In lambda function:
    sketch_jan25a:8: error: 'content' is not captured
         Serial.println(content);

Why? Because you are using a local variable `content` in a lambda function which runs at global scope. That is, `content` is not available to it, because it is inside `setup`.

To capture it, you can put it in the capture list:

      attachInterrupt (digitalPinToInterrupt (2),
                       [content]()  // capture content

However I found that my example doesn't compile even then.

---

I think the reason for that can be found here: [Lambda Functions in C++11 - the Definitive Guide](http://www.cprogramming.com/c++11/c++11-lambda-closures.html)

> **How are Lambda Closures Implemented?**
>
>So how does the magic of variable capture really work? It turns out that the way lambdas are implemented is by creating a small class; this class overloads the operator(), so that it acts just like a function. A lambda function is an instance of this class; when the class is constructed, any variables in the surrounding enviroment are passed into the constructor of the lambda function class and saved as member variables.

You can't pass an instance of a class to `attachInterrupt` because there is a hidden `*this` variable that needs to be passed to class instances, and ISRs don't do that.

Now your example isn't an ISR, but probably the same remarks apply.

---

I don't think there is an enormous amount of point of using lambda functions here. If you must, move `content` inside the lambda, since that is where you are using it.

Or failing that, make it global scope.

---

The closest I could get to something that compiled was:

    void setup ()
    {
      const int content = 42;

      attachInterrupt (digitalPinToInterrupt (2),
                       [=]()
      {
        Serial.println(content);
      },

      FALLING );

    }  // end of setup

    void loop () { }

Honestly though, I think using lambda functions here just makes your code obscure.


body:
I'm having a bad time trying to call a correctly-working expression (`ultra[currentSensor].ping_timer(echoCheck)`) from an own class method (`myclass::run`) instead of from `void loop()`.

I'm getting the following compiler error:
**"invalid use of non-static member function"**.

If I call `ultra[currentSensor].ping_timer(echoCheck)` directly from `void loop()` it gives me no error, so I may be missing something.

Here's the (shortened) piece of code which is generating the error:

    #include <NewPing.h>

    #define ULTRA_NUM      3
    #define MAX_DISTANCE 200

    class myclass {
      public:

        void run();
        void echoCheck();

        unsigned int distance[ULTRA_NUM];
        uint8_t currentSensor = 0;
    };

    NewPing ultra[ULTRA_NUM] = {
      NewPing(4, 5, MAX_DISTANCE),
      NewPing(6, 7, MAX_DISTANCE),
      NewPing(8, 9, MAX_DISTANCE)
    };

    void myclass::run() {
    // ....
          ultra[currentSensor].ping_timer(echoCheck);  // Compiler error
      }

    void myclass::echoCheck() {
      if (ultra[currentSensor].check_timer())
        distance[currentSensor] = ultra[currentSensor].ping_result
    }

`ping_timer()` is defined as it follows:

    void NewPing::ping_timer(void (*userFunc)(void), unsigned int max_cm_distance) {
     if (max_cm_distance > 0) set_max_distance(max_cm_distance);

     if (!ping_trigger()) return;
     timer_us(ECHO_TIMER_FREQ, userFunc);
    }

I hope any of you can help me!

Thanks in advance,

Eduardo

-------
**Edit**:
What I am trying to do is to adapt [this example][1] (from NewPing Arduino Library) so that the sonar ping (`sonar[currentSensor].ping_timer(echoCheck)`) is done from a class method, and not from `void loop()`.

  [1]: https://bitbucket.org/teckel12/arduino-new-ping/wiki/Help with 15 Sensors Example Sketch

title: Error: "invalid use of non-static member function" while calling a function from my own class-method

Answers: 2

body:
The problem is that `echo_check` isn't `void echo_check()` but `void echo_check(myclass *this)` because it's a member function of a class.

You can make the whole thing static (along with `run()`) by:

    class myclass {
        public:
            static void run();
            static void echo_check();
    };

    static void myclass::run() {
        ....
    }

    void myclass::echo_check() {
        ....
    }

And then you call:

    myclass::run();

instead of instantiating an object.

body:
Solved:

I moved the event handler out of the class, and made it static void.

Then the code compiled properly

D