message:
ESP8266 Nodemcu create custom PWM with 1.25us resolution

I am trying to control some SMD LEDs WS2812B with the [ESP8266](https://espressif.com/en/support/download/documents?keys=&field_type_tid[]=14)-[Nodemcu](http://nodemcu.com/index_en.html). I am using Arduino environment for coding. Actually I am trying to accomplish a PWM  that is precisely able to:

 - Go High for 850ns and then
 - Go Low for 400ns

According to the [Spec][1] this, this High Low change is considered as a bit with value 1.

I have tried to delay between the lows and highs, without an effort (delays only work for microseconds and above i suggest).

Do you have any idea how to accomplish that?

  [1]: https://www.google.de/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwiOyJDx5OTQAhWG6xQKHV64BWEQFggcMAA&url=https://cdn-shop.adafruit.com/datasheets/WS2812B.pdf&usg=AFQjCNH2BvBw_dQ2mDd1MTmHL4eXng0wSw&sig2=cNIcEuT9Nzwpj-0rmX8GGg

body:
According to §1.7 (Pulse-Width Modulation) of espressif.com's [ESP8266 technical reference](https://espressif.com/sites/default/files/documentation/esp8266-technical_reference_en.pdf) document, “PWM frequency range is adjustable from 1000 μs to 10000 μs, i.e., between 100Hz and 1 kHz.”  That range is shown in other sections of that reference, and in other ESP8266 documents as well.  I don't know whether that range reflects any hardware limitations, or whether the PWM APIs enforce such limits or can be operated outside them.

Depending on what your intent is, you might instead consider use of UART capabilities.  For example, if you set the UART data rate to 2.5 MHz and transmit a 110110110... binary pattern synchronously, you will have 800 ns high alternating with 400 ns low.  [I've seen references to use of USARTs on ESP8266's but don't know with certainty whether synchronous protocol actually is supported.]

The I2S subsystem mentioned in §1.5 and described in §10 of the technical reference document also may be able to generate a bit stream as desired.  As noted in §10.2.1.5 one six-bit field selects an input clock prescale factor, and another six-bit field is used as the frequency divider of the communication clock signal.

*Edit 1:* As noted in cranphin's comments, [cnlohr's esp8266ws2812i2s github page](https://github.com/cnlohr/esp8266ws2812i2s) provides code that uses the I²S subsystem and DMA to drive WS2812 LED units.  Using DMA (direct memory access, *ie* transfer of memory data under control of a subsystem other than the CPU) means that once the CPU has set up a data buffer for a new display, it can turn actual transmission of the buffered data over to I²S / DMA and then go on with unrelated tasks while transmission occurs.  Note, cnlohr's page [links to a youtube video](https://www.youtube.com/watch?v=6zqGwxqJQnw) that illustrates and briefly explains the process.


sender: user

message:
What USB to UART chip provides highest data rates with Arduino boards?

Checking out online stores for a USB/TTL adapter, I came across a wide range of products, and I'm having a hard time selecting the one which would achieve the highest data rate. I was comparing datasheets of the chips I have seen so far, to understand which baud rates are supported:

- [FT232R](http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf) (FTDI): 183 to 3M baud, including **250k**, **500k** and **1M**, 128 RX / 256 TX FIFO
- [PL2303](http://www.electronicaestudio.com/docs/PL2303.pdf) (Prolific): 75 to 1.2M baud, not including 250k, 500k and 1M, 256 RX / 256 TX FIFO
- [CP2102](https://www.silabs.com/Support Documents/TechnicalDocs/CP2102-9.pdf) (Silicon Labs): 300 to 921600 baud, including **250k** and **500k**, 576 RX / 640 TX FIFO
- [CH340G](http://cdn2.boxtec.ch/pub/diverse/ch340g-datasheet.pdf) (WCH): 50 to **2M** baud, not including 250k, 500k and 1M, unknown FIFO size

As explained [here](https://arduino.stackexchange.com/a/299/13327), 500k, 1M and 2M are particularly important, because those are the highest baud rates supported with 16MHz crystals. Moreover, data transmission becomes CPU-limited above 500k, so real data rates are practically the same with all three baud rates.

Am I right to assume that in order to get the highest data rate, I essentially have to stay away from PL2303, and prefer FT232R adapters, the other two chips being in the middle? Or are there other factors that I didn't take into account which may affect my choice?

sender: assistant

body:
Here's my experience with the above chips over the last two years:

**FT232R** is the fastest, works well with any baudrates. UART adapters with it are sometimes more expensive than alternatives.

**PL2303** is good if you don't plan to go faster than 115200. Additionally, it has the strongest 3.3V reference (available on some adapters as 3.3V output) which can be abused as a 3.3V 20mA power supply. Other chips will refuse to work if you draw more than 5mA from the 3.3V reference.

Prolific is currently fighting against clones by making their up-to-date drivers incompatible with non-original chips, so if your adapter won't work in Windows with code 10, take a look at [this page](http://www.totalcardiagnostics.com/support/Knowledgebase/Article/View/92/20/prolific-usb-to-serial-fix-official-solution-to-code-10-error).

**CP2102** which looks great in theory didn't work well for me (in Windows 10, with driver v10.1.3). Bulk data transfers at 115200 were in some cases 4 times as slow compared to other chips.

**CH340G** has a sketchy-looking windows driver, but otherwise works quite well and is often the cheapest option available. Unfortunately, it lack the intermediate baud rates, and getting 2Mbps UART link to work may be hard sometimes. Arduino clones which have this chip on-board do work at 2Mbps without issues (the ones I have seen do, anyway).


message:
How do I run multiple vibration motors from an Arduino Mini with PWM?

I'm building a project for my Physical Computing class that involves 4 vibration motors for varied haptic feedback based on serial input via analogRead. I have each coming out of their own pin and assigned to conditionals.

I'm wondering:

 - how do i control the PWM of each individual motor?
 - assuming I need an external power source for the motors, do I need to have a diode and transistor in between each motor and the ground?

Thanks in advance - I'm still learning but definitely looking forward to taking Part II next semester!

body:
 1. You can control motor PWM by using AnalogWrite() feature. Arduino Mini is equipped with 6 PWM pin, so you can use 1 PWM pin for each of you motor. Check [here][1] about more information on AnalogWrite, and [here][2] about Arduino Mini
 2. This is the circuit if you want to use external power source. Normally, I use 1k ohm resistor, I'm sure there are someone out there that knows the exact formula.

<!-- 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/TOHa5.png)

<!-- End schematic -->

  [1]: https://www.arduino.cc/en/Reference/AnalogWrite
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardProMini


message:
How to read RPS for fast rotation with status change method in Arduino?

I'm trying to calculate the coming RPS from rotary encoder. I am  trying to get it by checking the status with `digitalRead`. However, I can not get more than 6 RPS. Any solution? I will be obliged for your help.
Following is the code.

    float rps;

    void setup() {
      Serial.begin(9600);
      DDRC &= ~_BV (1); // pinMode (A1, INPUT);
    }

    void loop() {
      static int lastReedState;
      static unsigned long lastTransition;
      int reedState = (PINC & _BV (1)) == 0; // digitalRead (A1);
      // On a rising transition of the reed switch:
      if (reedState == LOW && lastReedState == HIGH) {
        // HIGH LOW measuring the low period
        // Compute time since last valid transition.
        unsigned long now = micros();
        unsigned long revolutionTime = now - lastTransition;
        // measuring the High period
        // Compute the RPS
        rps = 1.00 / (12.00*revolutionTime) *1000000.00;
        // 12 is rotary encoders resolution
        // Remember this transition.
        lastTransition = now;
      }
      // Remember last state.
      lastReedState = reedState;
      Serial.println(rps);
    }

body:
For one channel I'd use Input Capture capability on `Timer/Counter 1`. Without debouncing it'll be pretty easy.

If you want to read 8 inputs simultaneously, you can use Pin Change interrupts and `Timer/Counter 1` as a timebase. If you don't use Serial communication, you can use whole `PORTD`, otherwise you can use for example 4 channels on `PORTC` and 4 channels on `PORTD`. But again, debouncing will be little bit challenging.


body:
Consider using code similar to that shown in answers to the following questions: *[Reading from a KY-040 rotary encoder with Digispark](https://arduino.stackexchange.com/a/16420/3917)*; and *[Read RC receiver channels using Interrupt instead of PulseIn](https://arduino.stackexchange.com/a/18221/3917)*; and *[Can external interrupts be OR'd together on the '328 (Uno)?](https://arduino.stackexchange.com/a/19109/3917)*.

The [first answer](https://arduino.stackexchange.com/a/16420/3917) illustrates a fast-operating state machine to handle quadrature-encoded signals, ie rotary-encoder inputs.

The [second answer](https://arduino.stackexchange.com/a/18221/3917) illustrates handling of multiple encoders via a single interrupt routine, using a pair of two pin-change-interrupt (PCI) pins per encoder.  The method assumes pins of a pair are in the same port.  Most Arduino IO pins are PCI capable; some are not; on some models of Arduinos, some PCI pins aren't brought out to headers, or aren't recognized as PCI by the IDE, as noted in the question *[Why PJ0 and PJ1 are not reporting as PCINT pins](https://arduino.stackexchange.com/q/16551)*.

The [third answer](https://arduino.stackexchange.com/a/19109/3917) includes code from the first two, and also has a sketch that displays a table of PCI vectors and masks.  This table assists in planning pin layouts to reduce ISR overhead.  For example, if you have half a dozen encoders, you might attach three of them to six pins on one port (and one vector), and the other three to six pins on another port (and another vector).  Or you might put two encoders on each of three ports.  The latter method might run, on average, a little faster (eg a microsecond or so per ISR invocation).


message:
Timer for how long button is not pressed

I would like to timer for how long a button is not pressed. So actually if(buttonState == LOW 'for two seconds') than execute the code that comes after it. But the problem is while the user is still pressing the button the timer already starts.

Code:

    int ledPin[] = {7,8,9,10};
    int ledPin11 = 11;
    long randNumber;
    const int buttonPin = 2;
    int buttonPushCounter = 0;
    int buttonState = 0;
    int lastButtonState = 0;
    unsigned long previousMillis = 0;
    const long interval = 2000;

    void setup() {
     Serial.begin(9600);
     pinMode(LED_BUILTIN, OUTPUT);
     randomSeed(analogRead(0));
     randNumber = random(1, 16);
     Serial.println(randNumber);
     for (int i = 0; i < 4; i++) {
       pinMode(ledPin[i], OUTPUT);
     }
      pinMode(buttonPin, INPUT);
     }

     void loop() {
      displayBinary(randNumber); //functie 'display binary'
      unsigned long currentMillis = millis();
      if(currentMillis - previousMillis >= interval){
        previousMillis = currentMillis;
        if(buttonState == LOW){
        antwoord(buttonPushCounter,randNumber);
        delay(5000);
        displayBinary(randNumber);
      }
     }
     buttonState = digitalRead(buttonPin);
     if (buttonState != lastButtonState) { // als de button word ingedrukt krijgt buttonPushCounter + 1
     if (buttonState == HIGH) {
      buttonPushCounter++;
      Serial.print("Nummer hoe vaak is gedrukt");
      Serial.println(buttonPushCounter);
     } else {
      Serial.println("off");
    }
    delay(250);
     }
    }

    void antwoord(int teller, int antwoord) {
     if (teller == antwoord) {
      for (int i = 0; i < 4; i++) {
      pinMode(ledPin[i], LOW);
     }
     digitalWrite(LED_BUILTIN, HIGH);
     delay(250);
     digitalWrite(LED_BUILTIN, LOW);
     delay(250);
     digitalWrite(LED_BUILTIN, HIGH);
     delay(250);
     } else if (teller > antwoord || teller < antwoord) {
       for (int i = 0; i < 4; i++) {
        pinMode(ledPin[i], LOW);
      }
        digitalWrite(LED_BUILTIN, HIGH);
      }
    }

    void displayBinary(byte numToShow) //van byte naar decimaal
      {
       for (int i = 0; i < 4; i++) {
        if (bitRead(numToShow, i) == 1) {
        digitalWrite(ledPin[i], HIGH);
        } else {
          digitalWrite(ledPin[i], LOW);
        }
       }
      }

body:
Your question is not clear enough.

I hope I get what you want.

Do while loop about the pressing...

    if (button == LOW)
         while(!digitalread(button)){};


body:
I would start a timer when the button changes state. Then you timeout if
the button is released **and** it hasn't changed state for too long:

    void loop()
    {
        static int lastButtonState;
        static unsigned long buttonChangeTime;
        int buttonState = digitalRead(buttonPin);
        unsigned long now = millis();

        // Record time when button changes state.
        if (buttonState != lastButtonState)
            buttonChangeTime = now;

        // Timeout if button is not pushed for too long.
        if (buttonState == LOW && now - buttonChangeTime >= interval)
            Serial.println("Timeout.");

        lastButtonState = buttonState;
    }

Don't forget to update `lastButtonState` on each iteration.


message:
Writing new functions into progmem after main program is burned

I've been experimenting with writing very basic operating system-like programs on the Arduino, and so far I have been running user-defined programs on a small virtual machine I wrote.  This has been an interesting experience, but the VM runs on an assembly-like language and not C.

I want to be able to do something more.  I would like to be able to write a core OS, and then install new programs, written in C.  The core OS would get user input for which program to run, and then jump to that program.

Now, I know that I can do this trivially by writing the OS along with all of the programs into a single sketch. The programs are then just functions, and the OS just calls those functions.  However, I want to do this with functions I've written *after* I've burned the main OS.

From what I can tell, this is just a bootloader with additional user functionality.  However, I don't think that's quite right for two reasons:

First, I keep hearing that you can't write to progmem at runtime.  But isn't that what a bootloader does?  Which is correct?

Second, once a user program ends, I should return to the OS.  As far as I understand it, on the ATMega, once the main function terminates it jumps into a no-operation function and that's that.  I'd need it to jump back to the bootloader and continue the bootloader's operation.  Is that even possible?

body:
> First, I keep hearing that you can't write to progmem at runtime. But
> isn't that what a bootloader does?

Indeed. My understanding is that _non-bootloader code_ cannot write to
the Flash, except on the smallest AVRs. You may need to check the
datasheet of your target MCU.

> Second, once a user program ends, I should return to the OS.

You could require for the user programs to be linked against a library
you provide. Just implement `void exit(int status)` in that library and
it will automatically override the version from avr-libc.


message:
How to run a timer every 12 hours (exceeding the max size of int) without an RTC?

I'm experimenting with a Nano, and trying to trigger an action around twice a day. I'm aware that it's not super accurate, but I don't really mind, as long as it's in the ballpark.

I've tried using the [SimpleTimer library][1] but I'm running into an issue because it takes milliseconds as an int, and 12 hours is 43200000 (larger than 32,767 max). Is there another library, or another technique I can use for this?

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

body: Set the timer for every hour, which is within the limit. In your action, keep a `static int`, initialized to zero, which you increment each time. When it `==12`, do the thing you want to do and reset your `int` back to zero.


body:
> I'm running into an issue because it takes milliseconds as an int ...

No it doesn't. Look at the function prototype:

---

    int setInterval(long d, timer_callback f);

> Call function f every d milliseconds. The callback function must be declared as void f().

---

The interval `d` is a long. The `int` you see is the return value from the function, not the interval.


body:
You have 2 other options to the `setInterval()` function:

 - `delay()` (blocking)
 - `millis()` (non-blocking)

Both of these functions deal with an `unsigned long` which has 32 bits = (2^32)-1 = 4,294,967,295. Doing the sums (and considering that both are in milliseconds), this will last for 49 days and 17 hours.

1 second = 1000 milliseconds
1 minute = 60 seconds
1 hour = 60 minutes
12 hours = 12 * 60 * 60 * 1000 = 43,200,000

`delay(x)` will delay for x number of milliseconds.  The delay function is blocking, meaning that while it is running/delaying you can't do any other task. The code would be:

    delay(43200000);

`millis()` on the other hand is non-blocking and returns the number of milliseconds since power-up.  This can be implemented with the following code:

    #define TWELVE_HRS 43200000UL
    unsigned long startTime;

    setup()
    {
      startTime = millis();
    }

    loop()
    {
      if (millis() - startTime > TWELVE_HRS)
      {
        // Put your code that runs every 12 hours here

        startTime = millis();
      }
    }


message:
Arduino Due: ADC gain adjustment problem

I want to increase gain of the ADC channel. To achieve this I'm using `adc_set_channel_input_gain` function from **adc.h**. Here is the entire sketch:

    const byte aPin = A6;

    void setup() {
      analogReadResolution(12);

      // Configure ADC gain
      // Arduino/hardware/arduino/sam/system/libsam/include/adc.h
      adc_channel_num_t ch = (adc_channel_num_t)(g_APinDescription[aPin].ulADCChannelNumber);
      adc_set_channel_input_gain(ADC, ch, ADC_GAINVALUE_3);
      Serial.begin(9600);

      // Delay for serial stabilization
      Serial.println("Begin.");
      delay(2000);
    }

    void loop() {
      int analog = analogRead(aPin);
      Serial.println(analog);
      delay(500);
    }

The problem is that output values are not depending on the gain value.

body:
Well, the solution was very simple. We just need to call `adc_enable_anch()` before changing gain or offset of the ADC. I improved my setup and the sketch works as expected now:

    void setup() {
      analogReadResolution(12);

      // Configure ADC gain
      // Arduino/hardware/arduino/sam/system/libsam/include/adc.h
      adc_channel_num_t ch = (adc_channel_num_t)(g_APinDescription[aPin].ulADCChannelNumber);
      adc_enable_anch(ADC);
      adc_set_channel_input_gain(ADC, ch, ADC_GAINVALUE_3);

      Serial.begin(9600);

      // Delay for serial stabilization
      Serial.println("Begin.");
      delay(2000);
    }


message:
De-Auth "attacks" using Arduino?

I'm trying to use my Arduino and an ESP8266 to spam De-Auth "attacks". I am quoting attacks because I do not plan on using this for malicious or destructive purposes. I've heard that the ESP8266 supports monitor mode, but I haven't found any information about using it to spam De-Auth packets. I want to do something similar to the mdk3 command in Linux (mdk3 <monitor mode interface> d).

If you need me to clarify anything, please just ask.

Thanks in advance!

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


body: Check this GitHub repo, could be what you are looking for: https://github.com/spacehuhn/esp8266_deauther


message:
How can I stop my Servo rotating?

I have a continuous servo motor connected to my Arduino UNO. I want it to react to the Hexadecimal code received by an Infrared remote. I want the motor to rotate once in one direction and then rotate once in the reverse direction and then stop until triggered by the remote again. At the moment, the remote will cause the the motor to rotate once in one way but then it rotates continuously in the reverse direction. Any help would be much appreciated!

    #include "IRremote.h"
    #include <Servo.h>

    int receiver = 11; // Signal Pin of IR receiver to Arduino Digital Pin 11

    Servo servoMain;
    IRrecv irrecv(receiver);
    decode_results results;

    void setup()
    {
      Serial.begin(9600);
      Serial.println("IR Receiver Button Decode");
      irrecv.enableIRIn(); // Start the receiver
      servoMain.attach(10);
    }

    void loop()
    {
      if (irrecv.decode(&results)) // have we received an IR signal?

      {
        translateIR();
        irrecv.resume(); // receive the next value
      }
    }

    void translateIR() // takes action based on IR code received

    // describing Remote IR codes
    {

      switch (results.value)

      {

        case 551520375: servoMain.write(180); delay(1000); servoMain.write(0);     delay(1000); break;
        default: break;

      }

      delay(500); // Do not get immediate repeat

    } //END translateIR

body:
Unlike a normal servo motor where the argument of the [Arduino's servo.write(angle) method][1] represents a position, a continuous servo motor uses the argument for speed and direction.  Most continuous servo motors interpret stop to be approximately 90 degrees.  Full, say, reverse as 0 degrees.  And full, say, forward as 180 degrees.  As stated in the above link:

> On a continuous rotation servo, this will set the speed of the servo
> (with 0 being full-speed in one direction, 180 being full speed in the
> other, and a value near 90 being no movement).

Also of interest, most continuous servo motors have an adjustment to set the "90 degree position" (full stop).  That is to say, servo motor control signals are analog, not digital!  It follows that the processor's interpretation of the "90 degree position" may not be the same as the servos' interpretation of the "90 degree position".  Hence the ability to adjust the servos' interpretation.

This picture from the [parallax servo tutorials web site][2] shows how this is done:

[![enter image description here][3]][3]

  [1]: https://www.arduino.cc/en/Reference/ServoWrite
  [2]: http://learn.parallax.com/tutorials/robotics-propeller-boe-bot/center-and-test-servos/center-servos
  [3]: https://i.stack.imgur.com/tSoFs.jpg


body:
I am posting that may help others in future. I have MG996R Servo Motors, this motor when I opened and inside I didn't find LOCK at main wheel and I assume its 360 degree.

I have similar problem that while testing Robotic Arm, my motor was loosing position and it was rotating 360 degree. I tried all sort of remedies but didn't find the solution.

MY SOLUTION: Connect your Servo with external power 5v supply, even connecting 5V to arduino board with round pin does not solve. once I connected with external power with 5V power my issue was solved and motors were retaining position


message:
MAC address arduino

The MAC address is hardwired onto the NIC card when a device is manufactured. How is it that, we get to set a 48 bit MAC address of our choice while programming the arduino ?

body:
MAC address is not *hardwired* in the modern network interface cards; it is set during programming of the configuration of the card, which is loaded on the card's start/configuration.

Modern NICs usually have option for user to set custom MAC address.

If you talk about shield device based on network chip like W5100 - there's no initial configuration within this network card for Arduino; thus by "programming the arduino" you set this initial configuration of the "card". You act like a manufacturer of the NIC.


body:
Your initial premise is incorrect. The MAC address is NOT "hardwired".  In many cases it is held in a very small non-volatile memory chip. But when the Ethernet driver is initialized you can feed it whatever MAC address you want.  For most people they just accept "defaulting" it to the address programmed into the tiny memory.

Remember that the MAC address must be unique. At least within your LAN.  If you start diddling the MAC addresses and you end up with a duplicate, at best you will kill connectivity for your node plus the other node with the same MAC address. Not a good thing to do. That is why people generally just accept the manufacturer's MAC address which is designed to be unique.


message:
How to I press a button once to display text and again to remove it?

My code is displaying voltage and I want to have a button that when pressed it displays a text and when I pressed it again it would turn off the text. I put the word "YES" just for a test

    float vPow = 4.7;
    float r1 = 1000000;
    float r2 = 100000;
    const int buttonPin = 8;
    int buttonState = 0;
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup() {
      lcd.begin(16, 2);
      pinMode(buttonPin, INPUT);
      Serial.begin(100);
    }

    void loop() {
      float v = (analogRead(0) * vPow) / 1024.0;
      float v2 = (v / (r2 / (r1 + r2)))/.48;
      lcd.setCursor(0,0);
      lcd.print("V:");Serial.println(v2); lcd.print(v2); lcd.print("%");delay(100);
      buttonState = digitalRead(buttonPin);
      if (buttonState == HIGH) {
        lcd.setCursor(0,1); lcd.print("YES");
      } else {
        lcd.setCursor(0,1); lcd.print("");
      }
    }

body:
You can try to use a variable which is used to save the last condition. (whether it displaying or removing in the last button-press event)

    bool state=false;
    bool pressed = false;

    void loop() {
      float v = (analogRead(0) * vPow) / 1024.0;
      float v2 = (v / (r2 / (r1 + r2)))/.48;
      lcd.setCursor(0,0);
      lcd.print("V:");Serial.println(v2); lcd.print(v2); lcd.print("%");delay(100);

      pressed = false;
      while (digitalRead(buttonPin)) pressed = true; //wait the button to unpressed

      if (pressed)
     {
     state=!state;
     if (state) {lcd.setCursor(0,1); lcd.print("YES");}else
          {lcd.setCursor(0,1); lcd.print("   ");} //3 spaces. To erase 3 characters ("YES")
     }
    }


body:
You need to somehow debounce the button. Using a long delay in the loop
(your `delay(100)`) can do the trick, but it's probably not the best
way, as it will slow down anything that you may later add to your
program.

Better would be to write your own debounce function, or to use one of
the libraries that already implement that. For example, with
[Bounce2](https://github.com/thomasfredericks/Bounce2), you would write
something like:

    #include <Bounce2.h>

    const int buttonPin = 8;
    Bounce button;       // debounced button
    bool textDisplayed;  // whether the text is displayed or not

    void setup()
    {
        button.attach(buttonPin, INPUT);

        // etc...
    }

    void loop()
    {
        // Read and display the analog value, then...

        // Update the state of the debounced button.
        button.update();

        // Toggle display on rising edges of the button.
        if (button.rose()) {
            lcd.setCursor(0,1);
            if (textDisplayed) {
                lcd.print("   ");
                textDisplayed = false;
            } else {
                lcd.print("YES");
                textDisplayed = true;
            }
        }
    }


message:
Problem with combination of Bluetooth and RF 434MHz with Arduino Mega

I want to receive text from Bluetooth from an android phone to Arduino Mega. Then I want to send that text to other Arduino UNO through RF 434MHz.
Here is my code for Transmitter.

    #include <VirtualWire.h>
    void setup()
    {
      Serial.begin(9600);
      vw_setup(2000);
    }

    void loop()
    {
      String voice;
      digitalWrite(8,HIGH);
      while (Serial.available())
      {                 //Check if there is an available byte to read
        delay(10); //Delay added to make thing stable
        char c = Serial.read(); //Conduct a serial read
        if (c == '#') {break;} //Exit the loop when the # is detected after the word
        voice += c; //Shorthand for voice = voice + c
      }
      if (voice.length() > 0)
      {
        Serial.println(voice);
      }
      send(voice);
      delay(1000);
    }

    void send (char *message)
    {
      vw_send((uint8_t *)message, strlen(message));
      vw_wait_tx(); // Wait until the whole message is gone
    }

after compiling, I am getting an error as

> exit status 1
cannot convert 'String' to 'char*' for argument '1' to 'void send(char*)'

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

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

Please anyone tell me a way for solving this.
Problem is at transmitter part only. So I posted only about it.

body:
> exit status 1 cannot convert 'String' to 'char*' for argument '1' to 'void send(char*)'

The compiler is telling you about the issue. You can access the `String` as a character vector (C string) with the member function [`c_str()`][1], e.g. `send(voice.c_str());`

You might need to check that it is not too long for the payload in the VirtualWire library.

Cheers!

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


body:
[This should be a comment, but its too long]

> •exit status 1 invalid conversion from 'const char*' to 'char*'
> [-fpermissive]

This means that the function you are calling wants a char* as a parameter, but you are passing it a char* that can't be modified.  The chances are that the send function doesn't modify the value in the parameter, so you _might_ be OK just casting it, but you might get a runtime error if send does modify the value (a segmentation fault most likely, or just an ugly crash).  If you do you will need to allocate a temporary buffer that is big enough (str.length() + 1) and then copy it into that buffer and pass that to send.

So, try this first:

    send((char*)voice.c_str());

If that fails then try this:

    char* tempBuffer = malloc(sizeof(char) * (voice.length() + 1));
    if (tempBuffer)
    {
        strncpy(tempBuffer, voice.c_str(), (voice.length() + 1));
        send(tempBuffer);
        free(tempBuffer);
        tempBuffer = 0;
    }

Of course if the data is always a fixed length then you can allocate an array on the stack instead of mallocing a buffer onto the heap.


message:
How to unify all RPS reading in one function?

Want to unify rps reading in one function.
However, it shows incorrect values.
when it is reading for one it works fine.
Following is the code. Appreciate for your help.

    float rps[4] = {0.00, 0.00, 0.00, 0.00};
    long int PRINT_PERIOD = 1000;
    long int lastTimePrinted = 0;

    void setup() {
        Serial.begin(9600);
        DDRD &= ~_BV(7); // pinMode(7, INPUT);     // rps_1
        DDRB &= ~_BV(0); // pinMode(8, INPUT);     // rps_2
        DDRC &= ~_BV(1); // pinMode(A1, INPUT);    // rps_3
        DDRD &= ~_BV(2); // pinMode(2, INPUT);     // rps_4
    }

    float rps_out(int k) {
        static int lastReedState;
        static unsigned long lastTransition;
        static float rps_result;
        int reedState;
        unsigned long now;
        unsigned long revolutionTime;

        if (k == 1)    reedState = (PIND & _BV (7)) == 0; // digitalRead(7);
        else if (k==2) reedState = (PINB & _BV (0)) == 0; // digitalRead(8);
        else if (k==3) reedState = (PINC & _BV (1)) == 0; // digitalRead(A1);
        else if (k==4) reedState = (PIND & _BV (2)) == 0; // digitalRead(2);

        // HIGH LOW measuring the low period
        // LOW HIGH measuring the high period
        // On a rising transition of the reed switch:
        if (reedState == HIGH && lastReedState == LOW) {

            // Compute time since last valid transition.
            now = micros();
            revolutionTime = now - lastTransition;    // measuring the High period
             rps_result = 1.00 / (12.00*revolutionTime) *1000000.00;  // 12 is rotary encoders resolution
            // Remember this transition.
            lastTransition = now;
        }

        // Remember last state.
        lastReedState = reedState;

        return rps_result;
    }

    void loop() {
        rps[0] = rps_out(1);
        rps[1] = rps_out(2);
        rps[2] = rps_out(3);
        rps[3] = rps_out(4);

        if (millis() - lastTimePrinted >= PRINT_PERIOD) {
            Serial.println(rps[0]);
            Serial.print(',');
            Serial.println(rps[1]);
            Serial.print(',');
            Serial.print(rps[2]);
            Serial.print(',');
            Serial.println(rps[3]);
            lastTimePrinted = millis();
        }
    }

worked code except for rps[3] at the beginning. it shows rps[3] = 672.04

    float rps[4];
    long int PRINT_PERIOD = 100;
    long int lastTimePrinted = 0;
    int lastReedState[4];
    unsigned long lastTransition[4];
    int reedState[4];
    unsigned long now[4];
    float rps_result[4];
    unsigned long revolutionTime[4];

    void setup(){

     Serial.begin(9600);

     DDRD &= ~_BV (7); // pinMode (7, INPUT);       // rps_1
     DDRB &= ~_BV (0); // pinMode (8, INPUT);       // rps_2
     DDRC &= ~_BV (1); // pinMode (A1, INPUT);      //  rps_3
     DDRD &= ~_BV (2); // pinMode (2, INPUT);       //  rps_4

    }

    float rps_out(int k){

        //static int lastReedState;
        //static unsigned long lastTransition;
        //static float rps_result;
        //float rps_result;
        //int reedState;
        //unsigned long now;
        //unsigned long revolutionTime;

       if ( k == 0 )     reedState[0] = (PIND & _BV (7)) == 0; // digitalRead (7);
       else if ( k==1 )  reedState[1] = (PINB & _BV (0)) == 0; // digitalRead (8);
       else if ( k==2 )  reedState[2] = (PINC & _BV (1)) == 0; // digitalRead (A1);
       else if ( k==3 )  reedState[3] = (PIND & _BV (2)) == 0; // digitalRead (2);

        // On a rising transition of the reed switch:
        if (reedState[k] == HIGH && lastReedState[k] == LOW) {                   // HIGH  LOW   measuring the low period    // LOW HIGH measuring the high period
            // Compute time since last valid transition.
            //unsigned long now = micros();
            //unsigned long revolutionTime = now - lastTransition;       // measuring the High period
             now[k] = micros();
             revolutionTime[k] = now[k] - lastTransition[k];       // measuring the High period
            // Compute the rps

            if(revolutionTime[k] == 0 ) rps_result[k] = 0.00;     // avoid deviding by zero

            else rps_result[k] = 1.00 / (12.00*revolutionTime[k]) *1000000.00;  // 12 is rotary encoders resolution

            // Remember this transition.
            lastTransition[k] = now[k];

        }

        // Remember last state.
        lastReedState[k] = reedState[k];

        return rps_result[k];

    }

    void loop() {

       rps[0] = rps_out(0);
       rps[1] = rps_out(1);
       rps[2] = rps_out(2);
       rps[3] = rps_out(3);

        if (millis() - lastTimePrinted >= PRINT_PERIOD) {

         Serial.print(rps[0]);
         Serial.print(',');
         Serial.print(rps[1]);
         Serial.print(',');
         Serial.print(rps[2]);
         Serial.print(',');
         Serial.println(rps[3]);

          lastTimePrinted = millis();

         }

    }

body:
Your problem is that you have one set of (static) state information that you are trying to use for all your inputs. That's never going to work. You need separate state information for each and every input.

There's numerous ways of doing that:

1. The traditional C library "re-entrant" style. This involves passing pointers to any state variables into your function. The caller is responsible for creating and managing these variables and passing the pointers when the function is called. This is messy but pretty much completely portable across systems since it doesn't rely on any C++ facilities.
2. Similar to option 1 but grouping your different state variables into a `struct` to make things cleaner.
3. Global arrays - have a global array (maybe of structs as in option 2) to store the state information and pass the slice number to your function.
4. The OOP (C++) way - create a class with all the state variables and functions within it then instantiate a new object for each input. This is by far the cleanest and most self contained way but does require knowledge of creating and using classes.

Of the four options I would most likely choose option 4:

    class RPS {
        private:
            uint8_t _pin;
            uint8_t _lastReedState;
            uint32_t _lastTransitionTime;
            uint32_t _rps;

        public:
            RPS(uint8_t pin) : _pin(pin) {}
            void begin() {
                pinMode(_pin, INPUT);
                _lastReedState = digitalRead(_pin);
                _lastTransitionTime = millis();
                _rps = 0;
            }
            void calc() {
                uint8_t reedState = digitalRead(_pin);
                if (reedState != _lastReedState) {
                    uint32_t now = millis();
                    _lastReedState = reedState;
                    if (reedState == HIGH) {
                        uint32_t diff = now - _lastTransitionTime;
                        if (diff == 0) {
                            _rps = 0; // Avoid divide by zero
                        } else {
                            _rps = 1000 / diff;
                        }
                    }
                    _lastTransitionTime = now;
                }
            }
            uint32_t get() {
                return _rps;
            }
    };

    RPS rps1(1);
    RPS rps2(2);

    #define PRINT_PERIOD 1000

    void setup() {
        rps1.begin();
        rps2.begin();
    }
    void loop() {
        static uint32_t lastTimePrinted = 0;

        rps1.calc();
        rps2.calc();

        if (millis() - lastTimePrinted >= PRINT_PERIOD) {
            lastTimePrinted = millis();
            Serial.print("RPS 1: ");
            Serial.println(rps1.get());
            Serial.print("RPS 2: ");
            Serial.println(rps2.get());
        }
    }

*(note: Untested. It may not even compile)*


message:
How do I see the command line equivalent of clicking Verify?

I am using the ESP8266 board manager. I want to see how Arduino IDE compiles my code once I click Verify.

### Why do I want to do this?

I am trying to integrate a C library for which there is now Arduino library package available. So I have to integrate it from source. I want to be able to specify custom `-I`, `-L`  and `-l` flags when I compile my code.

body:
In the Arduino IDE switch on `File`>`Preferences`>`Upload erbose` and `Compile Verbose`

When you build you will see all the compiler commands

The verify is often a `-v` param in the command

You will find the esp8266 platform.txt in a location such as `c:\users\[name]\appdata\local\arduino15\packages\esp8266...`

The `platform.txt` contains all the compiler switches, the `boards.txt` in the same location can also contain board specific switches.

You can not specify different switches for different files in a compilation but you could compile your code into an archive then force it into the build process. Not sure if that is practical or not.


message:
Understanding Nikon modified version of SPI

I am trying to use this library to connect a Nikon lens to an Arduino.
https://lainy.github.io/NikonLens/classlain_1_1t_nikon_lens.html

I'm finding it very hard to understand the correct wiring.

> Connections are as follows (with Arduino Uno pin numbers):
>
> SS (10) is unused.
>
> SCK (13) is connected directly to lens SCLK.
>
> MISO (12) is connected to the lens Data line, which must be pulled
> high.
>
> MOSI (11) drives the lens Data line through a transistor,
> open-collector. So: MOSI -> Base, Data -> Collector, GND -> Emitter
>
> handshakePin_In is connected directly to lens H/S
>
> handshakePin_Out drives lens H/S through a transistor, open-collector.

I would like help to understand this.

> drives the lens Data line through a transistor, open-collector. So:
> MOSI -> Base, Data -> Collector, GND -> Emitter

It uses a variant of SPI interface. I'm just finding it hard to wrap my mind around it.

body:
It is simply a way of splitting a single-pin read/write function between two pins. It's easier to visualise with schematics:

<!-- 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/aqDCA.png)

<!-- End schematic -->

Under idle conditions the resistor pulls the data signal high. When the lens wants to transmit the open-collector output (represented by a transistor here) either pulls the data line low (for a 0) or releases it to be pulled up by the resistor (for a 1).

The Arduino reads that data in through the data in pin.

When the Arduino wants to transmit it does the same thing, but the "open collector" is external in the form of the transistor. It drives the transistor using the data output pin to get it to pull the data line low for a 0, or release it to be pulled up by the resistor for a 1.

This is exactly the same way (on an electrical level) that I2C works and studying that protocol can help you to understand what is going on here.


message:
Best way to detect tilt using MPU 6050

I want to make a gesture controlled car using this IMU.. What is the simplest way to detect tilts? I've seen many programs on the Internet that calculate the angles but is this really necessary?
Why can't we just get components of acceleration in the x, y plane and then detect tilts..Pls tell me how to do this!

body:
Well suppose you have a starting position, let's say 0 degrees, then once you detect and angle change, let's say 10 degrees, you know that there is a tilt of 10 degrees on one of the 3 axies.

The MPU6050 is a 6DOF, meaning 6 Degrees Of Freedom. This means that it can detect acceleration on axis: x, y, and z and it can detect gyro angles on axis: yaw, pitch, and roll.

For the best accuracy, use a mix of both acceleration and the gyroscope. This is the best way to calculate position. Heck, the Apollo space program used a gyro and accelerometer to navigate from planet Earth to the Moon.


message:
Global variables use to much space in the dynamic memory

I use two simple libraries (see [1][1], [2][2]) I found online for my code on the Arduino Uno, unfortunately I also use ROS and all those libraries take away to much space, when I compile my code I get this error:

    Global variables use 2,112 bytes (103%) of dynamic memory, leaving -64 bytes for local variables. Maximum is 2,048 bytes.

I shortened my Strings, but it was not enough. How can I change the code in the libraries to achieve less used memory?

I think I don't understand the concept of global variables completely. For example I changed all `double` variables in the libraries to `float` variables, but it did not change dynamic memory use at all. How can I use less memory?

  [1]: https://github.com/t0mpr1c3/Arduino-PID-AutoTune-Library/tree/6329d97eb00431efdf1dd0cc540c3a63347ed1f7/PID_AutoTune_v0
  [2]: https://github.com/br3ttb/Arduino-PID-Library/

body:
When you write a program, some memory can be determined in compilation time, due to it's predefinition, (`float` and `double` in Arduino - not Due model - use 4 bytes each - in Due, `double` uses 8 bytes for 64 bit precision).

But there is some memory that only can be known at runtime; where we are talking about objects (or arrays determined by user input). In these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators `new` and `delete`. More info at: [Dynamic memory](http://www.cplusplus.com/doc/tutorial/dynamic/).

You should control the creation of objects and arrays (those are created with `new` and then deleted with `delete`).

If your requirements are greater than the resources of any Arduino (except Arduino Due), you should change to the Due model, which has more memory space and computing power (but changes the 5 V to 3.3 V, be careful).


body:
@jonas I had a similar problem not quite exceeding the limit.  One item you can do is move the strings to Flash.
`<pgmspace.h>` there is the definition of PSTR which will place the literal in flash
the patternname, which we normaly just use strcpy, we need to use strcpy_P.
strcpy_P states the string will come from Flashmemory and copy it into SRAM space.  Once it is in SRAM sapce we can maniputate it all we want.
for example:

    setPatternName((char*)PSTR("My PatternName"));

    void setPatternName(const char* text) {
      memset(patternName, MAX_PATTERN_NAME_LEN + 1, 0 );
      strcpy_P(patternName, text);
      int length = strlen(patternName);
    }
This should have a significant reduction in mem usage.


body:
    char buf[50];

    char* tm1Txt (byte num){
      if (num == 0){strcpy_P(buf, (char*) F("t1 - Задepжka koмaнды xoд"));}
      if (num == 1){strcpy_P(buf, (char*) F("t2 - Bpeмя cepвoфиkcaции "));}
      if (num == 2){strcpy_P(buf, (char*) F("t3 - Bpeмя дoтягивания   "));}
      if (num == 3){strcpy_P(buf, (char*) F("t4 - Bpeмя тopмoжeния    "));}
      if (num == 4){strcpy_P(buf, (char*) F("t5 - Наложениe тормоза   "));}
      if (num == 5){strcpy_P(buf, (char*) F("t6 - Снятия нагр воздуха "));}
      return buf;
    }


message:
Why use a motor driver board?

I'm just getting into electronics in general and I'm confused a bit as to why I'd want/need to use a motor driver board instead of just setting up my own transistor/diode/etc when attempting to power and control a DC motor.

Any chance someone could clarify the point to using a motor driver board instead (assuming there is another option as I think there to be)?

body:
A motor driver board is just a convenient way of creating what is known as a "H Bridge". This is an arrangement of 4 (or more, but 4 primary) transistors.

You can make it yourself with discrete transistors, but it is simpler to just use a pre-made chip.

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

A H Bridge gives you greater control over a motor than a single transistor alone. It allows you to control the direction, which you can't do with a single transistor, and it also gives you access to braking modes where the motor becomes harder to turn thus assisting in slowing down the load.

With a single transistor you can turn the motor on and off (or vary the speed if you use PWM) but that is all.

<!-- 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/xRFWY.png)

<!-- End schematic -->

  [1]: https://i.stack.imgur.com/U3d8Y.gif


body:
A couple of extra reasons.  If you have low power controllers (like computers), it keep the low power devices away from higher power motor drivers, electronic noise etc.

If you use AC, it can also keep the issues of driving inductive loads away from your micro-electronics (phase and power factor issues).


message:
Keyboard.println missing characters when I print long strings

The topic is pretty straight forward: When I use `Keyboard.println()`, it sends short (up to 30-ish) strings just fine, but when I get up around 100 characters there are random characters missing. "Random" - meaning it is not all the time, it's somewhat consistently the same characters missing though.

I've checked and the data is arriving at the Arduino correctly (over web service), but once it shows back up in the notepad, it's missing random stuff.

Any thoughts or suggestions?

Edit: Examples as requested:
I'm sending...

> cheat SpawnDino Blueprint'/Game/PrimalEarth/Dinos/Pelagornis/PelaCharacter_BP.Pela_Character_BP' 10 1 1 10

And what's printing is...

> cheat SpawnDino Blueprint'/Game/PRIMALEarth/Dinos/Pelgornis/PelaCharacter_BP.Pela_Character_bP' 10 1 1 10

I've actually noticed now that it's changing capitalization too, the BP to bP and Primal to PRIMAL.

body:
I'd bet the issue is overflowing the keyboard buffer of the device you're talking to. On Windows, you can change a registry value to make the buffer larger:

http://www.windowsnetworking.com/kbase/WindowsTips/WindowsNT/RegistryTips/Hardware/KeyboardBufferSize.html

(and in fact, the Windows keyboard buffer is 100 characters by default.)

The reason the capitalization is becoming strange is because the device missed the shift-down or shift-up event, so it's using whatever it would use if the shift key wasn't pressed or released.

The best solution is to avoid sending so much: break it down and send a little at a time as Gerben said.


message:
Temperature sensor and LCD

I have a project which uses a [DS18B20](https://www.maximintegrated.com/en/products/analog/sensors-and-sensor-interface/DS18B20.html) temperature sensor and an LCD with an I2C interface on it. I have connected the sensor to my micro-controller (the DS18B20 has a 12-bit digital output) to the ATmega16 PD17, but as I try to print my values on the terminal the sensor output a really high value in decimal. Here is part of the code (and yes everything is working fine, this is a home-made Arduino):

    DDRD &= 0x00;
    PORTD |=  0x00;
    ds18b20_init(&PORTD, 20, 30, DS18B20_12BIT_RES);
    int temperature_sensor_output =  (float)ds18b20_temperature(&PORTD);
    printf("Temperature: %d  ", temperature_sensor_output);
    delay_ms(500);

ds18b20_init is the Dallas function for initializing the module. ds18b20_temperature returns a float value of the temperature

From this code it just prints:

> Temperature: 51603

If I change %d to %f it prints:

> Temperature: without any value

I do not understand where I may have missed some things.

body:
Without more detail about the system, I won't understand what `printf()` does; in non-embedded systems,  `printf()` writes to `stdout` by default, but Arduino systems typically don't use such a device.

That aside, `%d` is the proper format code for printing an integer value, and `%f` is proper for a float or double.  If you attempt to print an integer value like `temperature_sensor_output` under a `%f` format code, either the compiler will complain or the integer pattern of bits (plus perhaps two additional random bytes) will be interpreted as if it is a float or double pattern of bits.  No type cast occurs within `printf()`.  If you want to use a `%f` format code, pair it up with a float-type variable.

If, as you say, `ds18b20_temperature()` returns a float, then the type cast  `(float)ds18b20_temperature(&PORTD)` will have no effect.  Generally, casts convert data from one form to another, or in some cases declare that data has a given form.  Going from float to float doesn't change anything.

In a C statement like `a=b`, if `b` has a type that's different from that of `a`, the `b` value will be cast to the type of `a`.  Thus, the float value on the right hand side of

    int temperature_sensor_output =  (float)ds18b20_temperature(&PORTD);

will be converted to an integer value and stored into the integer variable `temperature_sensor_output`.


body:
Have you looked at the raw return value from ds18b20_temperature(), without casting it to float and then to int, perhaps in hex? It may not be your printing code that's causing trouble but the value returned from the function. If the function *is* returning something equivalent to 51603, it is already bogus. DS18b20s temperature values are in 16-ths of a degree (Celsius, assuming the routine didn't convert it). 51603/16 is still an unreasonable value, not to mention that viewed as as a 16-bit int, the sign bit is set. Is it truly negative? Did something overlow?

I think you need to look at what that function is doing.


message:
Serial Communication

When I send data using

Serial.println()

in what format does it go? I want to observe the data using the software 'Terminal'. When I observe there, if I've sent 255 using Serial.println(), I get a series of numbers 0 0 224 on the terminal. I've kept the baud rate same in both places(9600), Stop Bits as 1 in Terminal.

body:
On the Arduino [Serial.print() method][1] web page it says:

> Prints data to the serial port as human-readable ASCII text.

...which is suitable for most terminal programs.  [ASCII or American Standard Code for Information Interchange][2] is (usually) an 8 bit code for printing characters.  It is not a code which you can do normal math with.  That is the integer 1 (which is, in binary, b00000001) is not the same as the character '1' (which is, in binary, b00110001).

 - Example: If you want to print "123" on most terminals you can use the Serial class method print:

    Serial.print(123);

Now, you have to understand that the Arduino paradigm is to make programming simple.  So the print method in the Serial class will assume you want to see the characters "123" on the terminal.  So, guessing, the print method will convert each decimal number into an ASCII character and print them out as 3 values to the terminal.  That is, the ASCII value for 1, followed by the ASCII value for 2 finally followed by the ASCII value for 3.

If this is not what you want there are other variations for the print method in the Arduino Serial class.  But all tend to print using ASCII codes.

If you want to print out the binary values, see the [Serial.write()][3] method.  This method will send the value of the argument to the terminal with out converting into ASCII code.

 - Example: If you want to print "1" on most terminals you can use the Serial class method write:

    Serial.write(49);

...as 49 is the decimal equivalent of the ASCII code for the character '1'.

  [1]: https://www.arduino.cc/en/Serial/Print
  [2]: https://en.wikipedia.org/wiki/ASCII
  [3]: https://www.arduino.cc/en/Serial/Write


body:
Try using terminal program on PC side. NOT Arduino Serial port monitor built into Arduino IDE.

For example try http://docklight.de/

With this or some other similar terminal program, you can see each byte not only as ASCII representation, but also in HEX or binary format.

So you will easily in no time understand difference between ASCII "224" string and single byte 224 value.

With binary format you can have much much faster PC communication especially when sending float numbers. 4 bytes vs 3.7348823457458743 for example :)

On docklight you even have possibility to define macros for sending back to Arduino i ASCII or in binary format. Or even adjustable macros to send most of the string fixed, but change one byte inside string every time when sending.

But even basic ASCII or binary representation of data is enough for now to help you understand this problematic.


message:
4.7v as HIGH on digital output instead of 5v

I'm new to Arduino, just got my starter kit, and I noticed that digital outputs 3 & 4 have 5v as HIGH level while 5 to 13 have 4.7v as HIGH level.
Is it as it suppose to be?

body:
Yes, that's perfectly fine.

According to the datasheet, at 5V, the minimum voltage you can expect on a HIGH output (AKA VOH) is 4.2V. 4.7V is above that, so it's fine.


body:
Also depends on what your driving via this output. Standard TTL is:

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

But CMOS will be a bit different:

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

  [1]: https://i.stack.imgur.com/TWptO.png
  [2]: https://i.stack.imgur.com/DxwVx.png


body:
Some of the answers here suggest that a reading of 4.7V is in spec (which it is). As Majenko says, 4.2V is the minimum output high voltage, at an ambient temperature of 85°C, with a load of 20 mA, and Vcc = 5V.

*However* with no load, and at room temperature, I measured 4.99V on all of those pins, when set to `OUTPUT` and `HIGH` on *my* Uno. Test code:

    void setup()
    {
    for (int i = 3; i <= 13; i++)
      pinMode (i, OUTPUT);
    }
    void loop()
    {
    for (int i = 3; i <= 13; i++)
      digitalWrite (i, HIGH);
    }

> That was weird for me, because 1 hour ago it was showing 5v to me.

Right. What were you doing an hour ago? Did you have LEDs connected to those pins? If so, what value resistor did you have in series with them? Or were you driving a motor from the pins perhaps?


message:
Barebones Arduino Zero with ATSAMD21G18

I have been using the ATmega328P TQFP32 chip for quite a while and I would like to try something new. I came across the ATSAMD21G18 used by Arduino Zero and M0. However, there aren't any information online regarding how to develop a standalone, very basic setup of it.

Previously, I have used...

- ATmega328P TQFP32

- For the crystal: 16Mhz and 22pF caps

- For bootloading: 10 11 12 13 for Arduino ISP

- For uploading programs: TX and RX of an Arduino Uno with its chip removed.

For the ATSAMD21G18, I am also looking for a similar setup. I checked out the Sparkfun Mini breakout schematics, but I am not good at reading them and there seems to be a lot of components just for protection and to make it more stable, which I don't need as you can probably know from the setup I used for the 328.

https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/sparkfun-samd21-mini-breakout-v10.pdf

What are the basic required components for it to work properly?

For bootloading, am I required to use the Atmel Ice? If so, what are the pins and components needed for burning the Arduino Zero bootloader?

For uploading a program, am I required to use the USB functionality built in? How can I use it (components pins and connections)? Can I use Arduino ISP using an Arduino Zero?

Finally, what should I bear in mind when switching from an ATmega328P to an ATSAMD21G18?

Thanks in advance!

body:
This seems to be the simples form of the Arduino M0 I could find.

From [this tutorial site][1]

The ICE programmmer makes it very easy to program and all you need is the SWD pins to program the bootloader.

ISP is for AVR chips where as with ARM chips like SAMD21 you will need to use JTAG/SWD to program it.

I am also try to make a home brew Zero but I am getting stuck after the bootloader where the board just does not want to expose a Serial port.

[![Basic M0][2]][2]

  [1]: http://www.avdweb.nl/arduino/samd21/sam-d21.html
  [2]: https://i.stack.imgur.com/ElHCK.jpg


message:
Can I detect with software when a PIR sensor is physically connected to Arduino?

I'm creating a circuit using an Arduino Nano + ESP8266 to allow LED remote (via mobile app) activation and configuration (RGB colour, timeout, etc.). The circuit also has an optional PIR sensor to switch on the LED when someone enters the room.

I'd like the circuit to behave differently when the PIR is physically connected to the Arduino (i.e. to light the LED in a different colour) but I have no idea of how detect if the sensor is physically connected to the circuit.

I tried reading the value of the Arduino PIN but (obviously) the signal is LOW whether nothing is detected by the PIR or is not physically connected.

I have two different PIR detectors that I can use for the project:

 1. Arduino Compatible PIR Motion Detector ([Description][1])
 2. DFRobot PIR Detector ([Description][2], [Schematic][3])

Thank you for your time. If there is missing information in my question, please tell me and I will add it.

  [1]: https://www.jaycar.com.au/medias/sys_master/images/8902201344030/XC4444-dataSheetMain.pdf
  [2]: http://core-electronics.com.au/pir-motion-sensor-14541.html
  [3]: http://image.dfrobot.com/image/data/SEN0171/SEN0171_V1_Schematic.pdf

body:
The PIR sensor I have will overpower the internal pull-up resistor of the ATmega328P used on the Arduino Nano. This means if you turn on the pull-up and then get a read of LOW you know something is connected to that pin because the unconnected pin will always read HIGH with the pull-up on. With this approach you can get false negatives because the pin will also read HIGH if the PIR is triggered but you won't ever get false positives for PIR sensor detection. This means you can't rely on just doing a single test in `setup()` because the PIR might be triggered then so you will need to repeatedly run the test until the PIR sensor is detected. Example sketch:

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

    int PIRpin = 2;    //the input pin for the PIR sensor
    boolean PIRconnected = false;

    void setup() {
      Serial.begin(9600);
      pinMode(PIRpin, INPUT);
    }

    void loop() {
      if (PIRconnected == false) {
        pinMode(PIRpin, INPUT_PULLUP);
        if (digitalRead(PIRpin) == LOW) {
          Serial.println(F("PIR sensor detected"));
          PIRconnected = true;
        }
        pinMode(PIRpin, INPUT);  //turn off the internal pull-up to reduce power consumption
      }
      Serial.println(digitalRead(PIRpin));
      delay(500);
    }


message:
Using MMA8451 accelerometer to count steps

I'm trying to use an Adafruit MMA8451 accelerometer to create a pedometer-type device that counts steps. I'd like to initiate a counter that says "if the x-axis readout is > some threshold, add 1 to the counter" so that once the counter reaches a certain point, I'll be able to trigger a separate event (like an LED turning on). I'm an Arduino beginner, and would appreciate any pointers in the right direction as I work through this.

I'm using the Sparkfun Redboard and the Adafruit MMA8451, and wrote a loop to check whether the x-axis readout was over 5. If it's over 5, I want it to add 1 to the accumulator. However, it's accumulating 1 each readout regardless of what the 'x' reading actually is. Can anyone tell what I'm doing wrong? A nudge in the right direction would be much appreciated.

Code is here:

    /**************************************************************************/
    int lastStepCount = 0;
    int accum = 0;

    #include <Wire.h>
    #include <Adafruit_MMA8451.h>
    #include <Adafruit_Sensor.h>

    Adafruit_MMA8451 mma = Adafruit_MMA8451();

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

      Serial.println("Adafruit MMA8451 test!");

      if (! mma.begin()) {
        Serial.println("Couldnt start");
        while (1);
      }
      Serial.println("MMA8451 found!");

      mma.setRange(MMA8451_RANGE_2_G);

      Serial.print("Range = "); Serial.print(2 << mma.getRange());
      Serial.println("G");

    }

    void loop() {
      // Read the 'raw' data in 14-bit counts
      mma.read();
      Serial.print("X:\t"); Serial.print(mma.x);
      Serial.print("\tY:\t"); Serial.print(mma.y);
      Serial.print("\tZ:\t"); Serial.print(mma.z);
      Serial.println();

      /* Get a new sensor event */
      sensors_event_t event;
      mma.getEvent(&event);

      /* Display the results (acceleration is measured in m/s^2) */
      Serial.print("X: \t"); Serial.print(event.acceleration.x); Serial.print("\t");
      Serial.print("Y: \t"); Serial.print(event.acceleration.y); Serial.print("\t");
      Serial.print("Z: \t"); Serial.print(event.acceleration.z); Serial.print("\t");
      Serial.println("m/s^2 ");

      /* initiate for loop to count movement— this is the piece I'm having trouble with */
      if (event.acceleration.x >= 5);
        accum = accum + 1;
      Serial.print("X Counter: "); Serial.print(accum);

      /* Get the orientation of the sensor */
      uint8_t o = mma.getOrientation();

      switch (o) {
        case MMA8451_PL_PUF:
          Serial.println("Portrait Up Front");
          break;
        case MMA8451_PL_PUB:
          Serial.println("Portrait Up Back");
          break;
        case MMA8451_PL_PDF:
          Serial.println("Portrait Down Front");
          break;
        case MMA8451_PL_PDB:
          Serial.println("Portrait Down Back");
          break;
        case MMA8451_PL_LRF:
          Serial.println("Landscape Right Front");
          break;
        case MMA8451_PL_LRB:
          Serial.println("Landscape Right Back");
          break;
        case MMA8451_PL_LLF:
          Serial.println("Landscape Left Front");
          break;
        case MMA8451_PL_LLB:
          Serial.println("Landscape Left Back");
          break;
      }
      Serial.println();
      delay(500);

    }

**Update: the output I'm getting is as follows. The "X Counter" accumulates even when the x-reading is well below 5...not sure what's going on:

    X: 1Adafruit MMA8451 test!
    MMA8451 found!
    Range = 2G
    X: 144 Y: 50 Z: 4052
    X:  0.34 Y:  0.11 Z:  9.66 m/s^2
    X Counter: 1Portrait Up Front

    X: 138 Y: 62 Z: 4052
    X:  0.34 Y:  0.11 Z:  9.70 m/s^2
    X Counter: 2Portrait Up Front

    X: 0 Y: 48 Z: 4040
    X:  -0.02 Y:  0.11 Z:  9.67 m/s^2
    X Counter: 3Portrait Up Front

    X: -780 Y: 106 Z: 3814
    X:  -1.80 Y:  0.25 Z:  9.11 m/s^2
    X Counter: 4Portrait Up Front

    X: -510 Y: 106 Z: 4008
    X:  -1.46 Y:  0.20 Z:  9.68 m/s^2

body:
Change your `if` statement - remove `;` (semicolon) from the end.

Use this:

    if (event.acceleration.x >= 5)
    accum = accum + 1;

Notice there is no semicolon after if statement


message:
Implementing an external ADC in Arduino

I'm planning to use a ADS1220 4-channel 24 bit adc but I really have no experience with SPI. I have found [this][1] library but I can't really understand the code that much and also this is measuring the differential voltage. I want to use this for my accelerometer (x, y and z data) but I can't seem to find how to do read from 3 channels, and I can't understand the code in the library :( I've also found a video for this adc in youtube but he didn't used it for multiple channels. I'm sorry for asking this, I'm just pressured since the deadline is really soon.

## EDITED ##

----------

## sketch ##

    #include "Protocentral_ADS1220.h"
    #include <SPI.h>

    #define PGA 1                 // Programmable Gain = 1
    #define VREF 3.3
    #define VFSR VREF/PGA
    #define FSR (((long int)1<<23)-1)

    volatile byte MSB;
    volatile byte data;
    volatile byte LSB;
    //volatile char SPI_RX_Buff[3];
    volatile byte *SPI_RX_Buff_Ptr;

    long int bit32, data1, data2, data3;
    long int bit24;

    Protocentral_ADS1220 ADS1220;

    void setup() {
      pinMode(ADS1220_CS_PIN, OUTPUT);
      pinMode(ADS1220_DRDY_PIN, INPUT);

      ADS1220.begin();
      //ADS1220.Single_shot_mode_ON();
    }

    void loop() {

      byte *config_reg;

      data1 = aRead(0x81);
      data2 = aRead(0x91);
      data3 = aRead(0xA1);

      Serial.print(data1);
      Serial.print("    ");
      Serial.print(data2);
      Serial.print("    ");
      Serial.println(data3);
      delay(500);

    }

    long int aRead(uint8_t config_byte) {
      ADS1220.writeRegister(CONFIG_REG0_ADDRESS , config_byte);
      uint8_t r = ADS1220.readRegister(CONFIG_REG0_ADDRESS);
      //Serial.println(r,HEX);

      ADS1220.SPI_Start();

      while (ADS1220.NewDataAvailable == false) {
        SPI_RX_Buff_Ptr = ADS1220.Read_Data();
      }

      if(ADS1220.NewDataAvailable = true) {
        ADS1220.NewDataAvailable = false;

        MSB = SPI_RX_Buff_Ptr[0];
        data = SPI_RX_Buff_Ptr[1];
        LSB = SPI_RX_Buff_Ptr[2];

        bit24 = MSB;
        bit24 = (bit24 << 8) | data;
        bit24 = (bit24 << 8) | LSB;

        bit24= ( bit24 << 8 );
        bit32 = ( bit24 >> 8 );
      }

      return bit32;
    }
I tried to use the above sketch and I successfully read from 3 different channels but I noticed that the readings vary too much, compared to the example code. In the example code when I turn my potentiometer full CW, it outputs 8388607 which is correct right? since it is signed int.

But when running this sketch, the image below shows the output when the potentiometer is fully CW. Also turning the potentiometer fully CCW leads to negative values (shown in the 2nd picture) but in the example code, it gives 100-300 decimal values.  Also these are the configuration registers I sent in registers 1-3 (I edited it in the part of the [library][2]) and for register 0, it is on the sketch.

`Config_Reg1 = 0x00;
 Config_Reg2 = 0x40;
 Config_Reg3 = 0x00;`

[![serial monitor output][3]][3]
 [![enter image description here][4]][4]

###using accelerometer###
format is (x,y,z)
[![enter image description here][5]][5]

  [1]: https://github.com/Protocentral/Protocentral_ADS1220/blob/master/Libraries/examples/Basic/Protocentral_ADS1220.ino
  [2]: https://github.com/Protocentral/Protocentral_ADS1220/blob/master/Libraries/Protocentral_ADS1220.cpp
  [3]: https://i.stack.imgur.com/bfqMr.png
  [4]: https://i.stack.imgur.com/ZgKfY.png
  [5]: https://i.stack.imgur.com/FiQ89.png

body:
To get an understanding of how to read from the various ADS1220 channels, first review Figure 38, Analog Input Multiplexer, in the Datasheet as obtained from a link on [TI.com's ADS1220 technicaldocuments webpage](http://www.ti.com/product/ADS1220/technicaldocuments).

[![Figure 38][1]][1]
  [1]: https://i.stack.imgur.com/tdo4q.jpg

As can be seen, you'll need to close a switch from an AINx input line to the AINₚ bus, and also close the switch between AINₙ and AVSS.  The IDACx switches and the BCS switches should remain open.

To operate those switches, first look at §8.6.1, Configuration Registers, in the Register Map section of the Datasheet.  You'll see that MUX bits are in register 0, BCS is in register 1, IDAC is in register 2, and IxMUX are in register 3.  To see what to put into those fields, look at Tables 16, 17, 19, and 20.  For the MUX field, you will want a binary value like 1000, 1001, 1010, or 1011 to select one of AIN0-AIN3 as the AINₚ input and AVSS as the AINₙ input.  BCS, IDAC, I1MUX, and I2MUX all should be zero.

For example, to read channels 0, 1, 2 in sequence, set MUX to 1000, set up other register fields, and trigger a conversion.  After reading the result, change MUX to 1001, trigger a conversion, read result,  change MUX to 1010, trigger a conversion, read result, etc.

---
*Edit 1:* In slightly more detail, one could do as follows.
>• Use a WREG command [as in §8.5.3.6; or some library equivalent] to send three bytes to set up Configuration Registers 1, 2, 3.
• For i=0, 1, and 2 in turn, construct a configuration byte, send that byte to Configuration Register 0, start a conversion, await result, read result; as follows:
>> Set the MUX field of a byte to i
Set PGA as desired (ie, to 1, 2, or 4, via codes 000, 001, or 010)
Set the PGA_BYPASS bit (as required when AINₙ = AVSS)
Use a WREG to send the constructed byte to Configuration Register 0
Use a START/SYNC command to start a conversion (see §8.5.3.2)
Wait for DRDY to go low
Use an RDATA command to read iᵗʰ ADC result (see §8.5.3.4)

---
*Edit 2:* In [Protocentral's ADS1220.ino sketch](https://github.com/Protocentral/Protocentral_ADS1220/blob/master/Libraries/examples/Basic/Protocentral_ADS1220.ino), one finds the code sequence

      MSB = SPI_RX_Buff_Ptr[0];
      data = SPI_RX_Buff_Ptr[1];
      LSB = SPI_RX_Buff_Ptr[2];
      bit24 = MSB;
      bit24 = (bit24 << 8) | data;
      bit24 = (bit24 << 8) | LSB; // Converting 3 bytes to a 24 bit int
      bit24= ( bit24 << 8 );
      bit32 = ( bit24 >> 8 );     // Converting 24 bit two's complement to 32 bit two's complement

More competently and concisely, and with `SPI_RX_Buff_Ptr` renamed to `SPI_RX_Buff`, this could be written as:

      bit32 = (((long)(SPI_RX_Buff[0]<<8 | SPI_RX_Buff[1])<<8 | SPI_RX_Buff[2])<<8)>>8;

which acts as follows:  Assemble three bytes from `SPI_RX_Buff` into a 24-bit twos-complement-signed number.  Shift that number left 8 bits so that its sign bit now sits in the sign bit position of a 32-bit signed integer.  Shift that result 8 bits right with sign extension so that the final result is a signed 32-bit integer with possible values from -2²³ up to (2²³-1).

Sign extension occurs – usually – because in [many implementations of C](https://stackoverflow.com/questions/7622/are-the-shift-operators-arithmetic-or-logical-in-c), the `>>` operator does an [arithmetic shift](https://en.wikipedia.org/wiki/Arithmetic_shift) instead of a [logical shift](https://en.wikipedia.org/wiki/Logical_shift) when its operand is signed.


message:
ML8511 Sensor, unable to achieve meaningful results. Output voltages are atypical

Problem: ML8511 Sensor, unable to achieve meaningful results.  A mapping to the voltage output yields values that are unrealistically high. Variance is greater than expected [by me], and sensitivity, if any is questionable. In essence, the sensor reports high levels of UV whether is a dimly lit room, or exposed to daylight.

Background:
The interface is simple enough, and Google Search renders numerous hits, e.g., https://learn.sparkfun.com/tutorials/ml8511-uv-sensor-hookup-guide
All coding examples I have seen are akin to the one shown by Sparkfun.

Prior experience: I have a number of other Arduino devices running my sketches that record, collect, analyse, distribute, transmit and display findings.  All of these work as intended.

Observations:  I have spent a lot of time trying to make sense of the behaviour i observe with the sensor output, but have been unsuccessful. I have used two different sensors [same model], and switched UNO boards.  I've removed all other connections to the board, reverted to using the example code, then to code measuring only pinout values.  I have also measured pin voltage via voltmeter for both the output signal and the 3.3 volt reference pin..  According to specs, the sensor outputs voltage correlate with UV levels, and calibration is achieved via a known voltage reference level.

Based on a 3.3 volt reference, the sensor should output 1 to 3 volts, which can be mapped to a UV Intensity (mW/sq cm) range of 0 to 15.  My output voltages range from 2.8 to 3.2 v, the last of which is seemingly out of specs.
I have also used different sample sizes that comprise a data point, but that has little effect, but since the underlying values are out of range, it really would not matter.
Although cheap sensors such as this are not known for great accuracy. I find that they generally work rather well.

My supposition is that:
a) I am working with defective [abeit new] sensors.
b) This particular model of sensor functions in an atypical manner.
c) Being unexperienced in such, I an overlooking something glaringly obvious to others.
d) Somehow my perception of reality is defective.
e) I have truly entered into the Twilight Zone.

Seeking: Information that supports or refutes my observations.  Ideas that I might use to further isolate/ identify the problem.  A solution to the problem.

Image of item used

[![Image of item used, GYML8511][1]][1]

ML8511 UV Intensity Graph from specs

[![ML8511 UV Intensity Graph from specs[1]][2]

Typical ML8511 Wiring Diagram, the GYML8511 also has an additional connector for 5V, which I have tried both connected and disconnected, not understanding the board behaviour.

[![Typical ML8511 Wiring Diagram][3]][3]

  [1]: https://i.stack.imgur.com/FF9GX.png
  [2]: https://i.stack.imgur.com/S9f0r.png
  [3]: https://i.stack.imgur.com/TbGoh.png

body:
I found another, third sensor identical to mine and functioning properly.  By measuring pin output, then cross swapping with one of my two "supposedly abberant" sensors, I have identified my two as being defective, i.e., the other sketch then failed to function properly with one of those so identified sensors, whilst mine now worked as it should.

I typically buy at least two of everything in an effort to isolate such problems, but if from the same batch, two may not be sufficient in some situations.


message:
Why declare analog pins as ints?

I often see code like this:

    const int piezo = A0;
    const int sensorPin = A1;

From my understanding, an int variable can hold things like -123, 0, 1, 456, etc.

How can A0 or A1 be an int?

body: They are defined in the Arduino libraries, and the Arduino libraries will translate them into the appropriate pins and registers before they are used. But in the meantime they're numbers.


body:
The board definition (pins_arduino.h) has this:

    static const uint8_t A0 = 14;
    static const uint8_t A1 = 15;
    static const uint8_t A2 = 16;
    static const uint8_t A3 = 17;
    static const uint8_t A4 = 18;
    static const uint8_t A5 = 19;
    static const uint8_t A6 = 20;
    static const uint8_t A7 = 21;

Since A0 is a constant variable equal to 14, if you assign that to a variable, it just assigns 14.

In other words:

    A = 14.
    B = A.
    Therefore B = 14.


message:
How is a local variable address retrieved/returned inside the CPU of Arduino?

How is the address of a local variable retrieved in Arduino's ATMEGA328 micro-controller?

Lets say somewhere inside the main we have lines as:

    int x = 5; //a variable declared and value of 5 stored in SRAM ??
    int  *p; // a pointer is declared
    p = &x; // p holds the address of the variable x

What happens above is &x retrieves the address of the variable x.

But how does this happen in a lower level?
Which function retrieves the address of a variable and how does it do it?
How does that function know the address of the variable x?
I'm wondering what happens step by step after the instruction comes to the instruction register.

**edit**: Another question for int x = 5; is 5 stored at CPU register or SRAM?
.

body:
> Another question for int x = 5; is 5 stored at CPU register or SRAM?

That depends entirely on how the compiler optimizes your code. If you never refer to `x` in your code the compiler may discard that statement entirely. Or it might use a CPU register. It might use RAM.


body:
To answer your question you first have to understand what exactly happens when a function is called.

The very first operation, in what is known as the *[function prologue](https://en.wikipedia.org/wiki/Function_prologue)*, a *[stack frame](https://en.wikipedia.org/wiki/Call_stack#STACK-FRAME)* is allocated. This stack frame contains, amongst other things:

* The return address of the function
* Copies of any CPU registers that the function uses
* Storage space for any local variables

This may be through the use of a dedicated `PUSH` instruction or by manual manipulation of the *[stack pointer](https://en.wikipedia.org/wiki/Call_stack#Stack_and_frame_pointers)* and writing of data direct to memory, depending on the CPU architecture.

During this process the compiler says "This variable is stored at stack offset X" for each variable. From that point on there is no "variable" as such, only a stack offset. All accesses to the variable are actually accesses to the memory at the location it already knows about within the stack frame.

When you then access the address of a variable you are basically saying "instead of getting me the contents of this memory address, just give me the memory address". Since the compiler already knows what that offset is it just adds it to the address of the stack frame and gives you that.

So if your stack frame is at 0x500 (for example) and the variable `x` is at offset 0x004:

* Accessing `x` gives you the contents of address 0x500 + 0x004
* Accessing `&x` gives you the value 0x500 + 0x004

Assigning `p` to `&x` creates another variable in the stack frame (which could be at offset 0x006 say). To that variable is assigned the value 0x500 + 0x004 (or 0x504 of course).

However, that is all from the point of view of a non-optimising compiler.  The compiler itself may go "There is no need to store this value in memory, I have enough registers to keep it internally". So it doesn't actually allocate anything on the stack for the variable, it just "remembers" it in a register. That makes the function shorter and faster since there are less memory accesses.

There are a couple of variable attributes that affect how these decisions are made. The first is [`volatile`](https://en.wikipedia.org/wiki/Volatile_(computer_programming)) which tells the compiler that "this variable must be stored in RAM and, further to that, don't trust that the value in RAM is the same since I last looked at it". This is essential for variables shared between the main loop and an interrupt context, since the compiler doesn't know if the interrupt is going to change the value of the variable.

    volatile int foo;

The second is the `register` attribute.  This suggests to the compiler that it might like to store this variable in a register to make things faster. This flag is seldom seen any more since the optimiser generally does a much better job of working out which variables would fit better in a register than a human can. It's very much a deprecated attribute now.

    register int foo;


body:
Just as an experiment, I tried the following:

    void bar(int *);

    void foo()
    {
        int x = 5;
        int *p;
        p = &x;
        bar(p);
    }

And here is what gcc translated that into (comments mine):

<!-- language-all: lang-none -->

    __SP_H__ = 0x3e
    __SP_L__ = 0x3d
    __tmp_reg__ = 0
    foo:
        push r28            ; save r28
        push r29            ; save r29
        rcall .             ; make room on the stack
        in   r28, __SP_L__  ; copy SP into r29:r28 = Y: LSB...
        in   r29, __SP_H__  ; ... and MSB
        ldi  r24, lo8(5)    ; store x in a register: LSB...
        ldi  r25, 0         ; ... and MSB
        std  Y+2, r25       ; copy x into the stack: MSB
        std  Y+1, r24       ; ... and LSB
        movw r24, r28       ; r25:r24 = Y
        adiw r24, 1         ; r25:r24 = Y+1 = &x
        call bar            ; call bar(&x);
        pop  __tmp_reg__    ; release the two bytes...
        pop  __tmp_reg__    ; ... of stack space
        pop  r29            ; restore r29
        pop  r28            ; restore r28
        ret                 ; return

Expanded comments:

The instruction `rcall` is normally used to call another function. Here
it's calling the following instruction, so it doesn't affect the program
flow. It's only a trick: as `rcall` saves the return address into the
stack, it makes the stack grow by two bytes, and is used here as an
optimized way of reserving to bytes of stack space for storing `x`.

Next you see the stack pointer being copied into the r29:r28 register
pair, also known as “Y pointer”. The stack pointer is a CPU register
holding the address of the top of the stack, namely of the _first free
slot_. As the stack grows towards the bottom of the RAM, at this point
it looks like this:

    address | SP = Y | Y+1 | Y+2  | Y+3 | Y+4 | Y+5  |  Y+6  |...
    --------------------------------------------------------------
    data    | (free) | room for x |  saved Y  | return addr. | ...

Next you see the value of `x` being placed first in a register pair
(r25:r24), then on the stack at the addresses Y+1 and Y+2.

The instruction `mowv` copies a register pair, so now you have a copy of
the stack pointer in the pair r25:r24. The instruction `adiw` adds an
immediate value (here, 1) to a register pair, so that now r25:r24 holds
the address of `x`. Finally, the function `bar()` is called: per the
calling convention, the argument is to be passed in the r25:r24 pair.

A few final remarks:

* I passed the pointer to another function just to make gcc believe that
  I am actually _using_ that pointer, otherwise it would optimize out
  the whole code into a function that does noting but return.
* You don't need to create a pointer variable to hold the address of
  `x`: calling just `bar(&x)` compiles into the very same assembly.
* Most local variables are assigned to CPU registers. Only because I am
  _using_ the address of `x` did this variable get stored in the stack.
* The compiler output is very sensitive to the surrounding code, the
  compiler version, the optimization options, and so on. So you should
  consider all this as only an example.
* If you do not completely understand what each instruction is doing,
  you should now take a look at the [AVR Instruction Set Manual][]

[AVR Instruction Set Manual]: http://www.atmel.com/images/Atmel-0856-AVR-Instruction-Set-Manual.pdf


message:
Explanation of the formula of the map funtion

Can someone please explain (mathematically) how the formula for the map function actually came to light?
I have given the code of the map function below. You can see that it uses a formula to "map" values in a given range from a certain range. I don't quite understand how it came (not good at maths) :| So, I would like an explanation to how this formula came to light.

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

body:
`map()` implements **linear interpolation**.

> In mathematics, linear interpolation is a method of curve fitting using linear polynomials to construct new data points within the range of a discrete set of known data points.


body:
    (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;

X is your value. in_min is the minimum value of X. If you subtract that minimum value from X you re-map X into the range it can be.

For instance if X can be between 10 and 20 the in_min would be 10 and in the in_max would be 20. X will be somewhere between the two. Say X is 14. So X is 4 more than the minimum, or X - in_min = 4.

That gives you how far (in quanta of X) into the range you are.

out_max - out_min gives you the range of the output in the same way. If you want to map to 200 to 300, say, the range between the two is 100.

The same with in_max and in_min - it gives the size of the input range - 10 in this case (20 - 10 = 10).

So you now have some values:

* 4 is how far through the input range you are
* 100 is how big the output range is
* 10 is how big the input range is

Multiply the first two together and divide by the third and you get how far through the output range the input is. You could also do it the other way around - divide the input offset (4) by the input size (10) to get the percentage (in the range 0 to 1) that you are through the input. Multiply that percentage by the size of the output range to get how far through the output you are. The way it is done avoids the use of any floating point values which makes it faster.

So 4 * 100 = 400. 400 / 10 = 40.  Or, 4 / 10 = 0.4, 0.4 * 100 = 40.

Then you just add to that the output minimum values which just gives it an offset.  40 + 200 = 240.

Thus:

    map(14, 10, 20, 200, 300) == 240.

To reiterate the steps:

* 14 - 10 = 4 (input offset)
* 20 - 10 = 10 (input range)
* 300 - 200 = 100 (output range)
* 4 * 100 = 400 (percentage of input range
* 400 / 10 = 40 applied to output range)
* 200 + 40 = 240 (add output offset)


message:
Arduino + ESP8266 as Webserver

I want to connect Arduino to my Home Wifi and make it serve as a server to access GPIO pins on Arduino from remote (like controlling LED connected to Arduino from remote).

I am using ESP8266 to connect to my wifi network.

I am facing some issues like:

 - sometimes it doesn't connect to my wifi router.
 - not connecting to my mobile Hotspot.
 - not able to serve default and AP mode.

I am following tutorial from http://allaboutee.com/2014/12/30/esp8266-and-arduino-webserver/

Here is my code:

    #include <SoftwareSerial.h>
    #define DEBUG true

    SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                                 // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                                 // and the RX line from the esp to the Arduino's pin 3
    void setup()
    {
      Serial.begin(9600);
      esp8266.begin(115200); // your esp's baud rate might be different

      sendData("AT+RST\r\n",2000,DEBUG); // reset module
    //  sendData("AT",2000,DEBUG); // send AT command
    //  sendData("AT+GMR\r\n",2000,DEBUG); // returns firmware
    //  Serial.println("checking mode");
    //  sendData("AT+CWMODE=?\r\n",5000,DEBUG); // check supported modes
    //
    //  Serial.println("scanning APs");
    //  sendData("AT+CWLAP\r\n",21000,DEBUG); // scan list of access points

      Serial.println("set mode 1");
      sendData("AT+CWMODE=1\r\n",5000,DEBUG); // configure as both mode

    //  Serial.println("joining AP");
      sendData("AT+CWJAP=\"<MY_WIFI_SSID>\",\"<WIFI_PASSWORD>\"\r\n", 16000, DEBUG); // connect to wifi

      Serial.println("Testing CIFSR");
      sendData("AT+CIFSR\r\n",7000,DEBUG); // get ip address

      Serial.println("setting for multiple connection");
      sendData("AT+CIPMUX=1",2000,DEBUG); // configure for multiple connections

      Serial.println("print MAC address");
      sendData("AT+CIPSTAMAC?\r\n",2000,DEBUG); // print current MAC address

      Serial.println("set port 80 for server");
      sendData("AT+CIPSERVER=1\r\n,80",2000,DEBUG); // turn on server on port 80
    }

    void loop()
    {
      if(esp8266.available()) // check if the esp is sending a message
      {

        if(esp8266.find("+IPD,"))
        {
         delay(2000);

         int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                               // the ASCII decimal value and 0 (the first decimal number) starts at 48

         String webpage = "
Tyagi IoT
<button>LED1</button>";

         String cipSend = "AT+CIPSEND=";
         cipSend += connectionId;
         cipSend += ",";
         cipSend +=webpage.length();
         cipSend +="\r\n";

         sendData(cipSend,1000,DEBUG);
         sendData(webpage,1000,DEBUG);

         webpage="<button>LED2</button>";

         cipSend = "AT+CIPSEND=";
         cipSend += connectionId;
         cipSend += ",";
         cipSend +=webpage.length();
         cipSend +="\r\n";

         sendData(cipSend,1000,DEBUG);
         sendData(webpage,1000,DEBUG);

         String closeCommand = "AT+CIPCLOSE=";
         closeCommand+=connectionId; // append connection id
         closeCommand+="\r\n";

         sendData(closeCommand,3000,DEBUG);
        }
      }
    }

    void sendData(String command, const int timeout, boolean debug)
    {
        esp8266.print(command); // send the read character to the esp8266
        long int time = millis();

        while( (time+timeout) > millis())
        {
          while(esp8266.available())
          {
            // The esp has data so display its output to the serial window
            Serial.write(esp8266.read());
          }
        }
    }

body:
Are you using an arduino (as in UNO / mini / nano etc.) and communicating with a separate esp8266 via serial?
I've found esp8266 module to be more reliable by using a 12e or such like and running arduino boot loader on it. There's more memory to play with, and I tend to formulate the data I need within the ESP8266 and then communicate with that via serial or I2C to get data / requests to and from.

Make sure you're supplying the ESP module with enough current - they're juicy little things, so good 300mA @3.3v and use a good 470uf 10v cap or something too.. They can splurge current on occasion, particularly when scanning networks.

Let me know what set up you're running

Cheers


message:
Is it possible to measure the velocity of a Unmanned Aerial Vehicle using only accelerometer?

Our project is about dropping a payload from a UAV on the specified area. We are using an accelerometer (connected to the Arduino board) to measure the velocity of the plane (assuming the initial velocity to be zero). Is it possible to accurately measure the velocity of a plane moving in the air for a time `t`? Will this method be feasible?

body:
Not with any measure of accuracy, no.

You're basically asking about [Dead Reckoning](https://en.wikipedia.org/wiki/Dead_reckoning) which is problematical at best - and when doing it with just a low-grade accelerometer it can't be anything more than a rough "It's moving quick" or "it's moving slower now" accuracy.


message:
Stepper motor jittering

I'm trying to make a [nema17 stepper motor](http://www.omc-stepperonline.com/stepper-motors-nema-17-stepper-motors-c-1_21.html) work using ramps1.4 and [A4988 driver](http://www.allegromicro.com/en/Products/Motor-Driver-And-Interface-ICs/Bipolar-Stepper-Motor-Drivers/A4988.aspx).
But when I'm trying to rotate motor, it spins with almost no torque and constant shaking.

- Motor 2-phase nema17 , Step Angle 1.8° .
- Power supply 12v/60w.

Here is the sketch:
(I copied it from RepRap wiki , and removed everything except X Motor)

    #define X_STEP_PIN         54
    #define X_DIR_PIN          55
    #define X_ENABLE_PIN       38

    void setup()
    {
      pinMode(X_STEP_PIN       , OUTPUT);
      pinMode(X_DIR_PIN        , OUTPUT);
      pinMode(X_ENABLE_PIN     , OUTPUT);
      digitalWrite(X_ENABLE_PIN, LOW);
    }

    void loop ()
    {
      if (millis() % 10000 < 5000)
      {
        digitalWrite(X_DIR_PIN    , HIGH);
      }
      else
      {
        digitalWrite(X_DIR_PIN    , LOW);
      }

      digitalWrite(X_STEP_PIN     , HIGH);
      delay(1);
      digitalWrite(X_STEP_PIN     , LOW);
    }

The wiring diagram:
(I have only X Motor plugged in)

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

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

and video: (_Google Video link is dead @ 2017-02-09_)

body:
Add a second delay after:

 digitalWrite(X_STEP_PIN    , LOW);

Also try increasing the delay maybe you are pulsing the step pin too fast.


message:
2D Tracking of an object - which sensor?

I'm currently working on a project for which I require a sensor. I've made a quick and simplified drawing of what the result is supposed to do:

[![Diagram of object movement sensor ][1]][1]

Basically, I want one LED of a LED-Strip to light up dependent on the location of a moving object. If the object in above image (say a slow rolling ball) were to move from bottom to top, then the LED strip should also light up from bottom to top. I have no problem getting the LED strip to light up adequately, however I'm not sure which sensor actually can pick up objects as required in this case.

As I've understood regular IR sensors can only detect *if* there is an object and how far it is away, however they can't pick up said object's relative position on the y-axis. Is there any way to do this rather easily, perhaps with triangulation? I've looked into Bluetooth and RFID but haven't found anything particularly useful.

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

body:
There are many solutions to the problem.  For a free moving ball confined to a square flat surface with sides:

 1. Choose IR LEDs mounted at such a height and distribution to be
    blocked by the rolling ball.  Make sure at least 1 IR LED is blocked by the ball no matter where it is located.
 2. Line two adjacent sides with strips of these IR LEDs.
 3. Use the Arduino to light each LED one at a time at a frequency of about 40KHz.  Scan all LEDs within a second.  This should be adequate to locate a slow moving ball in 2D space.
 4. On the two opposite sides mount a ASK Remote Control receiver.  A common device easily harvested from old entertainment equipment or bought from electronics part supply houses.
 5. Use the Arduino to sense when the ASK Remote Control receiver detected or did not detect the flashing IR LED.
 6. When the Arduino finds an IR LED that is not detected, the ball can be assumed to be between the IR LED and the ASK Remote Control receiver.

Note, the patter of intersecting lines will look more like two sets of bicycle tire wheal spokes.  Not like a checker board.  It may be better to confine the ball to a smaller square then that of the square where the transmitting IR LEDs and ASK Remote Control receiver are mounted on.


body:
I feel that an array of IR transmitters and receivers could work for you.

If you put the transmitters/receivers in an recessed tube with (black, non-ir reflectant) separations, you can avoid crosstalk.
You should be wary that it may require some tweaking to find the right sensitivity.

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

Here is a [video][2] (and [here][3]) that shows this in practice. I like the fact that you don't need sensors on either side of the object.

You may also consider video-processing, but that's out of scope for Arduino.
Or use a [Lidar][4].

  [1]: https://i.stack.imgur.com/CfY6T.png
  [2]: https://www.youtube.com/watch?v=xkohbr9ApMo
  [3]: https://www.youtube.com/watch?v=-uCG2RsV-MQ
  [4]: https://www.youtube.com/watch?v=xkut3yRL61U