message:
Single #include pulls in all libraries

I am tracking down the memory usage of an Arduino-like project I am working on (not a real Arduino, but has same microcontroller and it uses the Arduino build environment, version 1.6.8). I have some modules that I am using and placed them in the Libraries directory in my sketch directory:

    Encoder
    LiquidCrystal
    OneWire
    TGPages
    TGPro

Now, when I compile a minimal sketch...

    #include <Arduino.h>

    void setup()
    {
    }

    void loop()
    {
    }

...the compiled size is 450 bytes Flash and 9 bytes RAM. So far, so good.

Now here's the weird part: when I include a single header file from anywhere in the Libaries folder, the compiled size increases dramatically.

    #include <Arduino.h>
    #include "pins.h"

    void setup()
    {
    }

    void loop()
    {
    }

"pins.h" is located in the TGPro directory and only contains #defines, not even code or other includes.

    ....
    Using library TGPro in folder: C:\Users\User\Project\TG\libraries\TGPro (legacy)
    Using library OneWire in folder: C:\Users\User\Project\TG\libraries\OneWire (legacy)
    Using library Encoder in folder: C:\Users\User\Project\TG\libraries\Encoder (legacy)
    Using library LiquidCrystal in folder: C:\Users\User\Project\TG\libraries\LiquidCrystal (legacy)
    Using library EEPROM at version 2.0 in folder: C:\Users\User\Project\TG\hardware\arduino\avr\libraries\EEPROM
    Using library Wire at version 1.0 in folder: C:\Users\User\Project\TG\hardware\arduino\avr\libraries\Wire

    Sketch uses 2,266 bytes (7%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 230 bytes (11%) of dynamic memory, leaving 1,818 bytes for local variables. Maximum is 2,048 bytes.

And I'm like: WTF? I'm not even referencing any of the files, still they get pulled in, wasting space. There are a few global, static variables in there which explain the used space and referenced code.

So, my questions:

 1. Is het normal for Arduino to pull in *all* files in the Sketch\Libraries directory, regardless if they are referenced or not? It doesn't seem to do this with the 'core' libraries.
 2. How can you prevent this? Suppose I have a large collection of modules that I use in various projects, but not all modules are used all the time. It would be a waste to include code that is never actually used.
 3. How can I find out more about the code that is compiled in; I know the linker will leave out unreferenced code, but I want to make sure this is due to the statically defined variables.

body:
What you are experiencing is due to the fact that your use case does not match with the Arduino foreseen use cases of "importing a library".

Basically you want the use case "include a file" and you get "import a library". The use case "import file" is simply not foreseen in the Arduino IDE.
Because the Arduino IDE add the library to your code it also adds the source doe files to your code. When these source codes contain global variables (which is very common and not a bad practise in embedded world) these will be part of your final code. As such your sketch will increase size even if you do not use these global variables.

To answer questions
1) yes it is normal because the use case "include file" is translated into "include library" in .ino files in the Arduino IDE.
Why this does not happen for the core? The core is first linked into a archive and then linked to the sketch. This leaves the linker more options to remove stuff.

2) I think the easiest is to copy the pins.h file in your sketch work folder (and you probably will need to restart the Arduino IDE).
Another option is to go for a real IDE like the arduino eclipse plugin called [sloeber][1] (which I develop)
In sloeber you could link to the pins.h file instead of copying. You could also reference the pins.h with a (partial/full) path avoinding the library include.

3) All global variables, static and similar stuff in the source code of the "imported libraries"

  [1]: http://sloeber.io


sender: user

message:
Audio sampling and serial communication

**tl;dr:** The sample rate of my code seems to be lower than what I expect it to be. How can I fix this?

**Director's cut:**
I am trying to sample audio data and send it via serial. The setup consists of a guitar plugged into an amplifier (about 10x) + low-pass filter (second order, around 1kHz) + voltage divider (centered at 2.5V), that is then connected to and Arduino Uno Rev3. When the Arduino receives a 'cap' command via serial, it enables the interrupt-based function that takes samples and sends them via Serial. With the 10-bit resolution, it gives me a number between 1 and 4 digits. With a baud rate of 115200 and adding 1 byte for the '\n' character, the slowest rate is of 2880 values per second, but most likely around 3.6k values per second (3+1 characters).

From what I understood (not used to working with timer interrupts), I've set up timer1 so that it doesn't have any prescaling, and it should be running pretty close to 2048Hz. The interrupt sequence reads the data at the analog input and sends it via Serial (for now, to the computer; later, a smartphone via Bluetooth).

To check if it is working, I am copying the data received by the computer, putting it into Matlab and running the `sound(data, sampleRate)` function. If I run it with 2048 as `sampleRate`, I get a clearly higher pitched sound, which indicates that the sample rate is in fact lower. Testing different values, I found that it sounds close enough around 1900.

From what I've read, the serial and the timer interrupt work in parallel, and the serial is faster than the capture. Why am I getting this apparently lower sample rate? How can I fix this?

**Code:**

    // Variables
    const int sampleRate = 2048; // Sampling rate
    const int numSamples = 2048; // Number of Samples
    //volatile int samples[numSamples]; // Data array
    int currentSample = 0;
    boolean capturing = false; // flags if it is in capture mode
    boolean done = false; // flags if the capture is done
    char chrCommand; // holds current character read
    String strCommand; // joins the complete command string

    // Functions
    void captureSample();
    void readCommand();
    void executeCommand();

    void setup() {
      /****************
       * Timer Setup
       ****************/
      cli(); // stop interrupts
      // set timer1 interrupt at 2048Hz
      TCCR1A = 0; // set the entire TCCR1A register to 0
      TCCR1B = 0; // set the entire TCCR1B register to 0
      TCNT1  = 0; // initialize counter value to 0
      // set compare match register for 2048Hz increments
      OCR1A = 7811; // = (16*10^6) / (sampleRate) - 1
      // turn on CTC mode
      TCCR1B |= (1 << WGM12);
      // no prescaling
      TCCR1B |= (1 << CS10);
      // enable timer compare interrupt
      TIMSK1 |= (1 << OCIE1A);
      sei(); // allow interrupts

      /****************
       * Serial Setup
       ****************/
      Serial.begin(115200);

      pinMode(13,OUTPUT);
    }

    void loop(){
      if(!capturing){
        // Case: waiting for command
        if(!done){
          if(Serial.available() > 0){
            readCommand();
            executeCommand();
          }
        }else{
          done = false;
        }
      }
    }

    /************************
     * Function Definitions
     ************************/

    // Timer function
    ISR(TIMER1_COMPA_vect){
      if(capturing){
        captureSample();
      }
    }

    void captureSample(){
      //samples[currentSample] = analogRead(0);
      Serial.println(analogRead(0));
      ++currentSample %= numSamples;
      if(currentSample == 0)
      {
        done = true;
        capturing = false;
      }
    }

    void readCommand(){
      strCommand = "";
      while(Serial.available() > 0)
      {
        chrCommand = ((byte)Serial.read());
        if(chrCommand == '\n')
        {
          break;
        } else
        {
          strCommand += chrCommand;
        }
        delay(1);
      }
    }

    void executeCommand(){
      // Command cap = capture
      if(strCommand == "cap"){
        capturing = true;
        return;
      }
      // Command mov = move
      if(strCommand == "mov"){
        // get the motor movement in the following command
        readCommand();
        moveMotor();
        return;
      }
      if(strCommand == "clr"){
        done = false;
        capturing = false;
        for(int i = 0; i < 2; ++i){
          digitalWrite(13,HIGH);
          delay(50);
          digitalWrite(13,LOW);
          delay(50);
        }
        return;
      }
    }

sender: assistant

body:
You calculation of the data rate is wrong:

* `Serial.println()` adds CRLF (i.e. "\r\n") to terminate the line,
  That's 2 bytes, not one.
* Each byte is sent by the serial port as one start bit, followed by 8
  data bits, followed by one stop bit. That's 10 bits in terms of
  timing.

In the worst case scenario (value ≥ 1000), you are sending 6 bytes,
or 60 bits: the fastest possible rate is 1920 samples per
second. In the arguably most common case (100 ≤ value < 1000), you send
50 bits per sample at up to 2304 S/s.

**Edit**: Here are a few optimization tips, just to make sure your
program is not CPU-bound:

- Declare `captureSample()` as `static`, this way the compiler can
  inline it and save the call overhead.
- Make `currentSample` unsigned, this way the compiler can optimize the
  modulo operation into a bitwise AND.
- Replace `analogRead(0)` with a direct read of the `ADC` register, and
  start the next ADC conversion right away. This way you do not have to
  wait for 104 µs while the ADC does its work.
- You may want to move the `Serial.println()` out of the ISR, otherwise
  you may be blocking interrupts for too long if the serial port cannot
  cope with the sampling rate.
- Make some kind of binary protocol instead of using plain ASCII.

You may also trigger the ADC directly from a timer instead of going
through the timer ISR (see the datasheet for details). You would then
use `ISR(ADC_vect)` to retrieve the ADC result. This way you get a very
steady (hardware controlled) sampling rate.

**More about the binary protocol**: you could send only two bytes per
sample and remain ASCII-compatible (which is often desirable) by using
32 printable characters to represent 5 bits. This is the same idea used
in base64, but simplified to use consecutive characters:

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

    uint8_t high_5_bits = sample >> 5;
    uint8_t low_5_bits  = sample & 0x1f;
    Serial.write('@' + high_5_bits);
    Serial.write('@' + low_5_bits);

This gives a stream of characters in the range `@A-Z[\]^_`. Then your
maximum sampling rate is 5760 S/s.


message:
Sending Arduino data to MySQL using phpMyAdmin and XAMPP using Windows10

I want to send my Arduino's sensor data to a MySQL database, using XAMPP and phpMyAdmin. I have been using an ESP8266 for the wifi connection. But I am unable to send the value. And actually I have to send four values, but for the time being I am sending only one value. So also please tell how to send multiple values. I have written the PHP file and saved in to Apache's htdocs.

    #include <WiFiEsp.h>
    #include <WiFiEspClient.h>
    #include <WiFiEspUdp.h>
    #include <SoftwareSerial.h>
    #include <PubSubClient.h>
    #include <SPI.h>
    IPAddress ip(192,168,8,1);
    char ssid[] = "ZONG MBB-E8372-B67D"; // your network SSID (name)
    char pass[] = "08522547"; // your network password
    int status = WL_IDLE_STATUS; // the Wifi radio's status
    int photocellPin = 4; // Analog input pin on Arduino we connected the SIG pin from sensor
    int photocellReading; // Here we will place our reading
    char server[] =  "192.168.8.1";
    // Initialize the Ethernet client object
    WiFiEspClient espclient;
    SoftwareSerial soft(2,3); // RX, TX

    void setup() {
      // initialize serial for debugging
      Serial.begin(115200);
      // initialize serial for ESP module
      soft.begin(115200);
      // initialize ESP module
      WiFi.init(&soft);
      // check for the presence of the shield
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        // don't continue
        while (true);
      }
      // attempt to connect to WiFi network
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network
        status = WiFi.begin(ssid, pass);
      }
      // you're connected now, so print out the data
      Serial.println("You're connected to the network");
    }

    void loop() {
      photocellReading = analogRead(photocellPin);
      // Fill the sensorReading with the information from sensor
      // Connect to the server (your computer or web page)
      if (espclient.connect(server, 80)) {
        espclient.println("GET /write_data7.php?"); // This
        espclient.println("value="); // This
        espclient.println(photocellReading);
        // And this is what we did in the testing section above.
        // We are making a GET request just like we would from our browser
        // but now with live data from the sensor
        espclient.println(" HTTP/1.1"); // Part of the GET request
        espclient.println("Host: 192.168.8.1");
        // IMPORTANT: If you are using XAMPP you will have
        //to find out the IP address of your computer and put it here
        // (it is explained in previous article). If you have a web page,
        // enter its address (ie.Host: "www.yourwebpage.com")
        espclient.println("Connection: close");
        // Part of the GET request telling the server
        // that we are over transmitting the message
        espclient.println(); // Empty line
        espclient.println(); // Empty line
        espclient.stop();    // Closing connection to server
      } else {
        // If Arduino can't connect to the server (your computer or web page)
        Serial.println("--> connection failed\n");
      }

      // Give the server some time to recieve the data and store it. I used 10 seconds here. Be advised when delaying. If u use a short delay, the server might not capture data because of Arduino transmitting new data too soon.
      delay(10000);
    }

Following is the PHP code:

    <?php
 //connecting to the database
 define('DB_HOST', 'localhost');
 define('DB_NAME', 'connected_car_1');
 define('DB_USER','Maryam1');
 define('DB_PASSWORD','telecom1213');

 $con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
 $db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

    $sql = "INSERT INTO connected_car_1.sensor (value) VALUES ('".$_GET["value"]."')";
    // Execute SQL statement
    mysql_query($sql,$con);
    mysql_close($con);
 ?>

And this is my serial monitor output:

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

I am very new to coding in Arduino as well as PHP and databases. So kindly tell me what I am doing wrong. And do I have to provide the IP address of the server, ie. 127.0.0.1? If yes, then where?

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

body: You should write the PC IP, for example: `192.168.1.53`, because `127.0.0.1` is the IP used only for phpmyadmin and the database inside your computer.


message:
Code example SPI multiple slaves Arduino DUE

I'm trying to get 2 devices (camera and sd card)to work on the SPI interface with an Arduino DUE.  I'm having trouble finding example code online showing how to communicate with multiple slaves on the DUE as I know it is slightly different than with the UNO.
Questions I have include:
How do you indicate you want to talk to a slave on pin 4? Instead of digitalWrite(4,LOW) do you call SPI.begin(4)? etc..

 Can someone post some example code?

body:
Everything you need is given here - you just need to know how to put it together:

* https://www.arduino.cc/en/Reference/DueExtendedSPI

There are variants of all the major methods that take an extra parameter - that parameter is the first parameter in the parameter list and defines the SS Pin to use for that function.  That includes the `.transfer()` function.

To use it you have to `begin()` all the pins you want to use SPI with. Then you can use `.transfer()` with those pins:

    void setup() {
        SPI.begin(10);
        SPI.begin(4);
    }

    void loop() {
        // Receive using pin 10 as SS
        byte byteFromTen = SPI.transfer(10, 0x00);
        // Transmit 123 using pin 10 as SS
        SPI.transfer(10, 123);
        // Both directions:
        byte otherByteFromTen = SPI.transfer(10, 123);

        // Receive using pin 4 as SS
        byte byteFromFour = SPI.transfer(4, 0x00);
        // Transmit 123 using pin 4 as SS
        SPI.transfer(4, 123);
        // Both directions:
        byte otherByteFromTen = SPI.transfer(4, 123);
    }

Doing multi-byte transfers is slightly more complex since you don't have control over the SS pin, so you have to use yet another version of the `transfer()` function that tells it to "continue" the transaction:

    // Receiving 3 bytes using pin 4:
    byte firstByte = SPI.transfer(4, 0x00, SPI_CONTINUE);
    byte secondByte = SPI.transfer(4, 0x00, SPI_CONTINUE);
    byte thirdByte = SPI.transfer(4, 0x00);

Of course, mixing reading and writing is pretty much the same as usual. For instance, to read the port A values from an MCP23S17 would look like:

    SPI.transfer(4, 0x41, SPI_CONTINUE); // Address 0, read bit set
    SPI.transfer(4, 0x12, SPI_CONTINUE); // Select register 0x12 (GPIOA)
    byte porta = SPI.transfer(4, 0x00);

The `SPI_CONTINUE` tells the SPI system to keep the SS pin LOW. It is only then raised once it gets a `.transfer()` without the `SPI_CONTINUE`. This is the same as the traditional way of using `digitalWrite()` to lower SS before the first transfer and raise it after the last transfer.


message:
Complete Bread board arduino

I bought a ATmega328 microcontroller and burn the bootloader. Now I want to upload code directly from pc to the microcontroller on bread board. I have max232 ic for the communication but I recently knew that I need a serial port rather usb to connect max232 to pc. There are many usb to serial converter available on the market but can I make my own? One more thing is there any other way burn program from arduino ide to microcontroller via USB on bread board without having the arduino board. Or can I burn program to microcontroller on the bread board from arduino board without removing the on board ic.

body:
> There are many usb to serial converter available on the market but can I make my own?

Yes, but if you need to ask how then you're not ready to undertake the task.

> One more thing is there any other way burn program from arduino ide to microcontroller via usb on bread board without having the arduino board.

Yes. The IDE doesn't care how you connect to the MCU, only that it has the appropriate bootloader for the programming method.

> Or can I burn program to microcontroller on the bread board from arduino board without removing the on board ic.

ArduinoISP will let you use an existing Arduino as an AVR ISP programmer. ISP does not require a bootloader, nor does it require a serial (UART) connection.


message:
send mixed data over serial

I want to launch a communication between two Arduinos, in which case the first Arduino *(S)* sends data to the second one *(R)*. The type of the data is mixed, consisting of integers, longs, floats and maybe some text. For example:

    {125, 1250, 12500, 125000, 1.25, 12.5, 125.0, "some text"}

- I thought about converting each one value to string, adding up all strings to a big one, and send the final string with  `Serial.print(Big_string)`.  In that case I reckon that it would be difficult for the Receiver to extract the string to the exact substrings and convert them to real values.

- A second thought was to convert all values to bytes and create a byte *(or char)* array, but each value would be limited to 0-255 *(let alone floats and text)*

- A third thought was to convert them to word type *(let alone the text)*, but I think that `Serial.print( )` sends only bytes, not words.

**In any case, which is the best way to send mixed data over serial?**

Any thoughts would be appreciated.

body:
I think the easiest way to solve your problem is using a separator and transmit the array values one after the other. That means having a `for` loop and in every iteration sending one value of the array with

`Serial.println(array[i])`.

The function will

 - convert numbers into Strings so you will get "125", "1250", ...
 - append a carriage return character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n')

On the receiver side you can simply wait for `Serial.read()` to equal the number `13` and (immediately afterwards) `10` and split the messages there. That works unless your transmitted strings contain new lines.

The disadvantage is, that numbers are of course transmitted in an *unefficient* way. If you want to transmit them as *real numbers* instead of strings you have to write your own protocol. [This video "Wireless Module Multiple Receivers" goes into that direction, it's using a fixed packet length but it gives an idea of how such a thing works.][1]

  [1]: https://youtu.be/h3OevEdl674 "Wireless Module Multiple Receivers"


body:
If your primary concern is transmission speed, you might consider turning everything into bytes and reversing the process at the other end.  If speed is not important, you can use sprintf() to create a character string and sscanf() to parse out the character string at the other end.

Turning everything into bytes is a very custom / specific approach.  A character would turn into 1 byte, an integer into 2 bytes, ect.  You would have to write custom code to encode this and remember to write code at the other end to do exactly the reverse process.  The advantage is that you would only be sending your data and no other information.  But this approach is not vary flexible.  If you were able to fit your data into 1 byte then suddenly needed 2 bytes (for example, a value once always less than 255 was now 300), you would have to re-write your code at both ends of the connection.

Turning everything into a string with sprintf() is very similar to printing out all your data.  You will be including extra characters like commas and / or space for delineation. At the other end sscanf() is used to parse out the character string.  At both ends, if done properly, all string assembly and parsing should be done by only these 2 calls.  And some issues are taken care of automatically.  For instance, the number 100 is 3 characters long and the number 10 is 2 character long.  But the sprintf() and sscanf() calls automatically compensate for these (reasonable) variations and continue to work as expected.

added later...

FYI: Even though sscanf() is available for the Arduino, it is not clear to me if it is well supported.  You might try testing (create and parse a string in the same sketch) what you want to send / receive before actually committing to this method.


body:
If you want to communicate between 2 arduino's with similar cpu (for instance uno and mega) I would go for binary data in a struct.
When using a struct you can not use the String class but you can use a char array.
Consider this struct as example

    struct SerialDataPacket
    {
      int someIntegerData;
      long someLongData;
      int someMoreIntegerData;
      char aString[20];
    };

You can send this struct as follows:

 String myString;
 SerialDataPacket transmissionPacket;
 transmissionPacket.someIntegerData=1;
 transmissionPacket.someLongData=millis();
 transmissionPacket.someMoreIntegerData=2;
 strncpy(transmissionPacket.aString,myString.c_str(),min(20,myString.length()));
 Serial.write((uint8_t *) &transmissionPacket, (uint16_t) sizeof(SerialDataPacket));

you can receive the struct at the other side as follows:

    Serial.readBytes((uint8_t *) &transmissionPacket, (uint16_t) sizeof(SerialDataPacket));
    myString=transmissionPacket.aString;

Again this method will only work if you have possessors with the same memory byte order. If the processors have a different bit (8 16 32 bit) you lust use processor independent types for it to work.


body:
I have a library that does exactly what you want. It can also work with RS-485 and RS-422 multi-drop networks.

* https://github.com/MajenkoLibraries/ICSC

You can even get it communicating with a Linux computer (such as a Pi or BeagleBone Black) with the Linux library:

* https://github.com/MajenkoLibraries/icsc-linux

You can use it to send data of any kind between nodes and trigger specific functions to be executed (like RPC) at the remote end.


message:
Arduino Uno and ESP01: can't issue AT commands [Solved]

I would like to connect an Arduino Uno and an ESP 01 module. I use the Arduino IDE and I tried to test communication via serial monitor. I get the "ready" message from the ESP 01, but I am not able to issue AT commands from the serial monitor. It only displays random characters on the console.

It seems that no newline character is issued, because if I try to insert commands, they are inserted next to previous characters. I use "Both NL & CR" and 115200 baud settings in Arduino IDE. I tried 9600 baud too, but then the text is unreadable.

I used the following pins on my ESP-01:

    Vcc -> 3,3V
    Gnd -> Gnd
    Rx  -> Tx(pin 0) of my Arduino, used voltage divider to make it 3.3V.
    Tx  -> Rx(pin 1) of Arduino
    CH_PD -> 3.3V

Please see serial monitor screenshot:
[![enter image description here][1]][1]

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

**EDIT: PROBLEM RESOLVED:**

My Arduino is connected to my PC via USB, so I changed pins for communication with the ESP by SoftwareSerial to pins 10 and 11. Now it works. Thank you.

body:
It could be the case, that the **Arduino power supply is insufficient**.

"[...] note that the Arduino 3.3V regulated output (50 mA max) can't drive the current requested by the ESP (Up to 200 mA). Some tutorials on the Internet use the Arduino 3.3V to power the ESP, but it didn't worked for me. I'm using an external power supply (An old 5V Android charger)."[Source][1]

*Possible*, that the power consumption was within range when the readable text was printed and too high when all the unreadable stuff was sent.

  [1]: http://dalpix.com/blog/connecting-your-arduino-wifi-esp-8266-module "Source"


body:
Just to have an answer instead of just an edit/addition to the question:

> EDIT: PROBLEM RESOLVED:
>
> My Arduino is connected to my PC via USB, so I changed pins for communication with the ESP by SoftwareSerial to pins 10 and 11. Now it works. Thank you.

Ok... sure... your Uno's Atmega384 was talking with pins 0 and 1 to the USB adaper chip (Atmega16u2 on Uno R3) and at the same time to the ESP-01.

Read the fine schematic: [Arduino Uno R3](https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf)


message:
Oxygen sensor up to 50%

Are there any oxygen sensors that measure up to 50%?.

As I understand, there are sensors that measure only in range 0-30%.

Is it possible to increase the threshold of sensitivity of the sensor?

body:
The Bosh LSU 4.X sensor(s) are what I think you are looking for. Here are some related links:

http://www.waltech.com/open-source-designs/wbo2_report/

https://github.com/Hell-Fire/WidebandO2


body:
You can try [SO002][1] or [DS-TR250][2].

> Is it possible to increase the threshold of sensitivity of the sensor?

I don't think its possible. Perhaps you can tweak the reading sensitivity, but since the sensor are mostly analog, it's not possible. And maybe that also the reason the 2 sensors I've mentioned above have several series based on their measuring threshold.

  [1]: http://www.sensore-electronic.com/wp-content/uploads/2016/04/SO002e-3_Data-sheet-sensor.pdf
  [2]: http://www.co2meters.com/Documentation/Datasheets/DS-TR250Z-sensor.pdf


message:
Receiver Module Second Data Pin

Many of the receiver modules (MX-05V) working with the Virtual Wire library (*I would like to add a link here but it requires 10 reputation, so I'll do that later)* have two data pins. However only one of them is used in the examples I have seen so far.

This picture shows a transmitter (top left) and a receiver (bottom right). Apparently the receiver has four pins - two of them are data pins.

[![Transmitter and receiver module][2]][2]

[Image source][3]

**What is the purpose of the second data pin on the receiver module and how to use it?**

  [1]: https://www.pjrc.com/teensy/td_libs_VirtualWire.html "Virtual Wire library"
  [2]: https://i.stack.imgur.com/2Dj21.jpg
  [3]: http://www.simsso.de/?type=arduino/mx-05v-mx-fs-03v "Image source"

body:
I would expect only one data line output from the receiver.

Looks like the manufacturer might have just connected the 2 data pins together. You could try using either pin to confirm that the two data output pins are simply connected together.

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

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


message:
Trouble reading analog (PWM)

I'm trying to test my `analog` signal before I send it to an actual `analog` device. I've written some code and considering the `analog` square I have expected to see a `digital` **ON** *or* **OFF** during a single `duty cycle` but I'm either seeing all **OFF** for `analog` values 0-127 and all **ON** for values 128-255.

My expectation is that I would see 51 **ON** and 49 **OFF** thus getting a value closer to 128 of 255.

**What am I missing? Is this even possible?**

    int OUTPUT_PIN = 2; // digital 2 (PWM)
    int INPUT_PIN = A0; // analog 0

    void setup() {
      pinMode(OUTPUT_PIN, OUTPUT);
      pinMode(INPUT_PIN, INPUT);

      Serial.begin(9600);
    }

    void loop() {

      analogWrite(OUTPUT_PIN, 128);

      float j = 0;
      for(int i = 0; i < 100; ++i) { // get 100 reads per duty cycle
        float v;
        v = digitalRead( INPUT_PIN );
        if(v >= 1) Serial.println("ON");
        if(v <= 0) Serial.println("OFF");
        j += v;

        delay(12); // trying to match the duty cycle
      }
      j /= 100; // average out the 100 reads

      Serial.println(j);

    }

body:
Seeing all on for 128+ and all off for 127- is indicative that you are using a pin that can't do PWM.

If you use a non-PWM pin with analogWrite it goes "Is this less than 128? Yes? Then I will turn it off. Otherwise I will turn it on.".

    case NOT_ON_TIMER:
    default:
        if (val < 128) {
            digitalWrite(pin, LOW);
        } else {
            digitalWrite(pin, HIGH);
        }

Since you don't mention what board you are using I can only assume that you have picked a pin that can't do PWM. Change to a pin that *can* do PWM and you should get a PWM signal.


message:
Bizarre behavior, loop function affects setup function

I've connected two stepper through two uln2003 chip. And wrote a small class to control them.
The class works perfectly and I'm able to control the steppers (rotate the CW and CCW).

My main code looks like this :

    #include "StepperControl.h"

    StepperControl myStepperControls[2];

    void setup() {
     delay(1000);
     myStepperControls[0].init(6,5,4,3);
     myStepperControls[1].init(11,10,9,8);

     delay(1000);
     for (int i = 0; i < 2; i++)
     {
      myStepperControls[i].DelayBetweenSteps = 1200;
      myStepperControls[i].StepCCWDegree(90);
      myStepperControls[i].StepCWDegree(51);
     }
    }
    int moveNumber = 0;
    void loop(){
     int stepperNumber = moveNumber / 2;
     bool cw = ((moveNumber % 2)  == 0);
     moveNumber = (moveNumber + 1) % 4;
    }

As you can see I:

 - Init both instances of the class to different pins.
 - Set the Delay between the steps (in microseconds).
 - Rotate `myStepperControls[0]` counter clock wise and then clock wise.
 - Same for `myStepperControls[1]`

This doesn't work correctly, one of the motors doesn't move clock wise.

It is not always the same motor !! For the last hour the problem appeared only in `myStepperControls[0]`, now it is only in `myStepperControls[1]`.

I'm 100% sure it is not a wiring/electrical problem because:

 1. If I'll delete the content of the loop (which runs after setup) it will fix the problem.
 2. If I'll make the delay between steps 2000 it will fix the problems.
 3. As I've mentioned the problem was only in `myStepperControls[0]` for an hour, in that hour i switch the pins of the motors and still the motor that was connected to `myStepperControls[0]` was not able to rotate CW.

Any suggestions to how to investigate the problem will be appriciated

Here is my library code:

    // StepperControl.h

    #ifndef _STEPPERCONTROL_h
    #define _STEPPERCONTROL_h

    #if defined(ARDUINO) && ARDUINO >= 100
     #include "arduino.h"
    #else
     #include "WProgram.h"
    #endif

    class StepperControl
    {
     public:
     StepperControl();
     void init(byte blue, byte pink, byte yellow, byte orange);
     void StepCW(int steps);
     void StepCCW(int steps);
     void StepCWDegree(float degrees);
     void StepCCWDegree(float degrees);
     const int StepsPerFullRotation = 4076;
     int DelayBetweenSteps;
     private:

     void setPinsState(byte step);

     byte m_currentState;
     byte m_pinValuelookup[9];

     byte m_bluePin; // = 11;    // Blue   - 28BYJ48 pin 1
     byte m_pinkPin; // = 10;    // Pink   - 28BYJ48 pin 2
     byte m_yellowPin; // = 9;    // Yellow - 28BYJ48 pin 3
     byte m_orangePin; // = 8;    // Orange - 28BYJ48 pin 4
           // Red    - 28BYJ48 pin 5 (VCC)

    };

    #endif

here is the cpp file :

    #include "StepperControl.h"

    StepperControl::StepperControl() : m_pinValuelookup{B01000, B01100, B00100, B00110, B00010, B00011, B00001, B01001, B00000}, DelayBetweenSteps(1100), m_currentState(0)
    {
    }

    void StepperControl::init(byte blue, byte pink, byte yellow, byte orange)
    {
     m_bluePin = blue;
     m_pinkPin = pink;
     m_yellowPin = yellow;
     m_orangePin = orange;

     pinMode(m_bluePin, OUTPUT);
     pinMode(m_pinkPin, OUTPUT);
     pinMode(m_yellowPin, OUTPUT);
     pinMode(m_orangePin, OUTPUT);
     delayMicroseconds(DelayBetweenSteps);
     setPinsState(8);
     delayMicroseconds(DelayBetweenSteps);
    }

    void StepperControl::StepCW(int steps)
    {
     for(int i = 0; i < steps; i++)
     {
      m_currentState = (m_currentState - 1) % 8;
      setPinsState(m_currentState);
      delayMicroseconds(DelayBetweenSteps);
     }
     setPinsState(8);
    }

    void StepperControl::StepCCW(int steps)
    {
     for(int i = 0; i < steps; i++)
     {
      m_currentState = (m_currentState + 1) % 8;
      setPinsState(m_currentState);
      delayMicroseconds(DelayBetweenSteps);
     }
     setPinsState(8);
    }

    void StepperControl::StepCWDegree(float degrees)
    {
     float steps = degrees * (float)StepsPerFullRotation / 360.0f;
     StepCW((int)steps);
    }

    void StepperControl::StepCCWDegree(float degrees)
    {
     float steps = degrees * (float)StepsPerFullRotation / 360.0f;
     StepCCW((int)steps);
    }

    void StepperControl::setPinsState(byte step)
    {
      digitalWrite(m_bluePin, bitRead(m_pinValuelookup[step], 0));
      digitalWrite(m_pinkPin, bitRead(m_pinValuelookup[step], 1));
      digitalWrite(m_yellowPin, bitRead(m_pinValuelookup[step], 2));
      digitalWrite(m_orangePin, bitRead(m_pinValuelookup[step], 3));
    }

body:
Some one helped me in the Arduino forums, and I felt obligated to add the answer here :

The : `m_currentState = (m_currentState - 1) % 8;` is the bug.
I accidentally assumed that doing `%` on `-1` will jump to `7`.

Somehow this caused the strange behavior I had.


body:
You found the solution yourself. I am posting this answer anyway just to
give some background on the problem.

I must say you were somewhat unlucky: you have just hit a couple of the
least intuitive features of the C and C++ languages: integral promotion
and signed division.

1. **Integral promotion**: C does not know how to perform arithmetic on
   anything smaller than an int. When you write `m_currentState - 1`,
   the variable `m_currentState` is automatically promoted to `int`.
   Note that this promotion has converted an _unsigned_ type (`byte` is
   unsigned) into a _signed_ integer. Then, `(byte) 0 - 1` is `(int) -1`
   instead of `(byte) 255`.

2. **Signed division**: When dividing a negative number by a positive
   one, the quotient is rounded towards zero and, conversely, the rest
   is negative. Then, `-1 % 8` is -1 instead of 7.

There are several ways around these problems. One is to replace the
modulo operation `% 8` by a bitwise and: `& 7`. This is an optimization
the compiler would have done anyway if dealing with _unsigned_ integers.
The option I prefer is to simply undo the integral promotion by an
explicit cast:

    m_currentState = (byte) (m_currentState - 1) % 8;

This way, if `m_currentState` is zero, `(byte) (m_currentState - 1)` is
255 and the result is, as expected, 7. Also, the compiler optimizes the
unsigned modulo operation into a bitwise and: the whole lines compiles
very efficiently into just two single-cycle instructions:

    subi r24, 0x01  ; subtract 1
    andi r24, 0x07  ; bitwise and with 7

It is worth noting that nothing of this would have happened if
`m_currentState` was an `unsigned int`, as there would have been no
integral promotion in the first place.


message:
Sparkfun Can-Bus Shield example not working

I recently bought a [Sparkfun Can-Bus Shield][1], and tried the SparkFun_CAN_Demo from [here](https://learn.sparkfun.com/tutorials/can-bus-shield-hookup-guide "Sparkfun Can Shield Tutorial") but the program only prints "CAN-Bus Demo" and then does nothing, even when I have it connected into my vehicle's OBD-II port and the key is turned to ON (I can't run the engine because I am in my garage). Any help will be appreciated.

  [1]: https://www.sparkfun.com/products/13262

body:
SPI pins are located on different pins in Arduino Mega. You have to wire it correctly with your shield. Some shields uses ICSP (6-pin header) for better compatibility but this one doesn't.

See [Arduino SPI Reference][1] for more details (section: Connections)

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


message:
Precise rotation (steering direction to a given angle) on obstacle avoidance robot

Forgive my lack of knowledge of some robotic related terms, but the way my two wheel drive robot steers is simply by having each wheel move at different speeds; for left, for example, the left wheel moves while the right one stays stationary for a given delay of time and vice versa.
but I want to make my obstacle detection a little more sophisticated with the following logic:

As the robot moves, scan the environment using an ultrasonic sensor(60 degrees to left and 60 degrees to the right) and using a simple max finding algorithm find the optimal angle i.e. angle at which the ultrasonic reading was highest. and then I want to find a way, using the same system of vehicle rotation if possible, turn to that specific angle proceed to move forward and scan simultaneously.

what I aim to achieve in the end is smoother obstacle avoidance as compared to the most common stop when close to obstacle -> turn left or right -> move and loop

body:
The only way you can know how far you have turned, with any form of accuracy and, more importantly, repeatability, is by employing some form of feedback.

In other words, to work out how far you have turned you need, first, to know how far you have turned.

The simplest method is probably to use some form of monitoring on the wheels themselves. That could be an optical encoder to give a nice high resolution "number of degrees the wheel has turned", which can be coupled with the circumference of the wheel to calculate the distance travelled (which can then be used with some simple trigonometry to work out the angle you have turned through) or a more coarse "magnet on the wheel + hall effect sensor" to give you the number of revolutions the wheel has gone through (not very accurate and only really any use at higher speeds when there will be lots of revolutions. Maybe this method would be better on the motor before the gearbox that drives the wheel?)

However, do you really care that much anyway? Are you over thinking things a little too much?

Surely a simpler method would be to first turn left an arbitrary amount (somewhere around 60-degrees-ish, you're not really worried) then sweep from left to right (a distance of somewhere around 120 degrees in total) looking for the furthest distance. Once you have completed your sweep you then just reverse your turn direction *until you read the same (or within a certain tolerance) distance* at which point you will be facing your longest space.

All that can be done just with spinning the wheels either for a pre-defined period, or until a specific reading has been obtained. No need to worry about precise angles or anything fancy like that.


body:
You could try an electronic compass, such as [this one][1]. Use it to compare your current (turn) angle to the desired angle, and keep turning until the desired angle is reached.

  [1]: https://www.sparkfun.com/products/10530 "HMC5883L"


message:
ESP8266 Web Server Crash + Arduino IDE

I am working on HTTP GET Request. I have created ESP wifi as web server. It creates a access point with IP address : 192.168.4.1
When my android app is connected to web server, it sends values every 50ms on 192.168.4.1/R"VALUE". Value is integer type (0~1023). Example :- 192.168.4.1/R546

However, it is working fine when I send values every 1s, but esp crashes, when IP is hit every 5ms second. I have captured the crash detail on serial monitor. Attaching the file and code as well. Kindly help. [![enter image description here][1]][1]

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

    #include <ESP8266WiFi.h>
    #include <EEPROM.h>
    #include <ESP8266WebServer.h>

    #define RED_LED     12

    WiFiServer server(80); //Initialize the server on Port 80

    char myTestUrl[100];

    void setup()
    {

      EEPROM.begin(512);
      Serial.begin(9600); //Start communication between the ESP8266-12E and the monitor window

      WiFi.mode(WIFI_AP); //Our ESP8266-12E is an AccessPoint
      WiFi.softAP("LED_Downlight1", "12345678"); // Provide the (SSID, password); .
      server.begin(); // Start the HTTP Server

      IPAddress HTTPS_ServerIP = WiFi.softAPIP(); // Obtain the IP of the Server
      Serial.print("Server IP is: "); // Print the IP to the monitor window
      Serial.println(HTTPS_ServerIP);
    }

    void loop()
    {
      WiFiClient client = server.available();
      if (!client)
      {
        return;
      }

      String request = client.readStringUntil('\r');
      //Serial.print(request);

      request.toCharArray(myTestUrl, 100);

      char *Red = strstr(myTestUrl, "/R");
      if (Red)
      {
        int RedValue  = atoi(Red + 2);
        analogWrite(RED_LED, RedValue);
        Serial.print("Red: ");
        Serial.print(" ");
        Serial.print(RedValue);
        Serial.print("\n");

        int SetRedValue = (RedValue / 4);
        EEPROM.write(0, SetRedValue);

        EEPROM.commit();

        Serial.print("Red Memory Write :");
        Serial.print(" ");
        Serial.print(SetRedValue);
        Serial.print("\n \n");

      }
    }

body:
I've worked with ESP8266 to create a centralized network over which different devices could communicate. In my first iteration I used an ESP8266 as an AP and let other ESP8266s connect to it. This didn't work for longer than 5 minutes. I suspected the ESP8266 couldn't handle many connections for a long period of time and bought an USB WiFi router. Now, I connected all ESP8266 to the WiFi router, including the ESP8266 that I set up as server. And it worked.

In other words: the ESP8266 isn't *strong* enough to be an AP and communicate a lot of data at the same time. Instead, you'd rather like your ESP connect to an existing wireless network with other devices and let those devices connect to the IP of the ESP.


message:
Programming Arduino With Python

Im a beginner working with arduino.
Im little familliar with java syn and its not hard for me to do the work with ide ;but i know python better....is there any Lib that let you program Arduino with Python?

body:
Here is a page on interfacing Arduino with Python.

[Interface Arduino with Python][1]

  [1]: http://playground.arduino.cc/Interfacing/Python


message:
Accelerometer Z Value off a significant amount, all other values reasonable

I'm using the MPU9255 Accelerometer to measure acceleration in the X,Y, and Z directions.  As per the datasheet, I've applied a scaling to the raw digital values based off of whether I specified +- 2G, +- 4G, +- 8G etc.  This scaling works fantastically, but there is consistent noise on the Z axis, far greater than that of gravity's 1G of force.  Here is a sample output

    ACCELEROMETER-X
    0.7226562500
    ACCELEROMETER-Y
    0.1523437500
    ACCELEROMETER-Z
    7.9707031250

    ACCELEROMETER-X
    0.7460937500
    ACCELEROMETER-Y
    0.1875000000
    ACCELEROMETER-Z
    8.0468750000

As you can see, there is about 7G of noise on the Z axis. I calculated the scaling with this code:

    //Get accelerometer scaling based off of how many G's per of variation the system was tuned to handle
    int16_t getAccScalar(int16_t system_scale){
      int16_t acc_scalar = 16384;
      short scalar = 1;
      if(system_scale == ACC_FULL_SCALE_4_G){
        scalar = 2;
      }
      else if(system_scale == ACC_FULL_SCALE_8_G){
        scalar = 4;
      }
      else{
        scalar = 8;
      }
      acc_scalar /= scalar;
      return acc_scalar;
    }

And then in configuration I use a register writing function with this header:

    void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data)

and call it with these values

    I2CwriteByte(MPU9250_ADDRESS,28,ACC_FULL_SCALE_2_G);

Anyone know why this is happening? Thanks and have a squanchy day.

body: Accelerometer static errors are usually not anywhere near that large, so I suspect your scaling code is not behaving correctly. You could verify this by turning the accelerometer on its side and see if the Z axis retains a +7G value, or if the X/Y axis instead becomes too large.


message:
Using an external interrupt alongside serial

I want to read data from an accelerometer sensor, which pushes its data to the Arduino via an external interrupt. I then want the Arduino to relay this data to a host computer via the serial connection.

Will the external interrupt interfere with the serial connection? If the Arduino's in the middle of transmitting via serial, and the accelerometer triggers the interrupt, won't that potentially break the serial connection?

body: Transmitting a single character via UART on the ATmega328P (and all other AVRs with a dedicated USART) cannot be interrupted since it is independently clocked. Loading the next character into the transmit buffer can be (since the `INTx` interrupts have priority over the `USART,xxx` interrupts), but this will not actually break communications, just slow it down.


message:
NodeMCU Arduino set PWM Frequency to specific frequency

I am using NodeMCU and I program it using Arduino IDE, I need to change the PWM frequency of a port, in Arduino I used to change the frequency using timers registers like that:

    TCCR1B = (TCCR1B & 0xF8) | 1 ;
How can I change the frequency of a digital pin using some function like that:

    analogWriteFrequency(pin, 31250);
So that the code will looks like that:

    #ifdef __AVR__
    TCCR1B = (TCCR1B & 0xF8) | 1 ; //generates the MCKL signal
    #else
    analogWriteFrequency(pin, 31250);
    #endif
    analogWrite(pin, 128) ;
Thanks.

body:
> PWM frequency is 1kHz by default. Call `analogWriteFreq(new_frequency)` to change the frequency.

source


message:
Arduino Dim RGB LED

I have an RGB led and I (just) would like to dim is brightness programmatically.

I searched Google thoroughly without any interesting code.
Some of them present only "how to" fade from on to another color.

If I change PWM value from 0 to 255, I can easily change color, but, my need is to change the brightness value from potentiometer (through read from analog pin).

body:
To control the brightness of an LED with a POT read the pot position using the ADC, convert the range of values from 0 - 1024 to 0 - 255 then write that to the PWM controlling the LED.

This segment of code came from [this][1] discussion:

    void loop()
    {
      knobvalue = analogRead(potpin);
      knobvalue = map(knobvalue, 0, 1023, 0, 255);
      analogWrite(11, knobvalue);
    }

This is just for 1 LED.  If you have 3 LEDs connected to 3 Arduino PWM pins, you will have to write the same value to all 3 pins.

If this is 1 RGB LED and you are controlling each of the 3 LEDs with 3 Arduino PWM pins, this will (for most RGB LEDs) cause the RGB LED to always appear White as you are varying all colors by the same amount.

If you are trying to vary the brightness of an RGB LED that is set to an arbitrary color...  this is more difficult:

Using 3 variables ranging from 0 to 255 pick your color.  Before writing these to the 3 PWMs which control the RGB LED, multiply each by the value read from the ADC connected to the POT.  Now divide each by the maximum possible ADC value.  Take care you do not exceed the range of your variables!  Write these new values to the 3 PWMs which control the RGB LEDs.

  [1]: http://forum.arduino.cc/index.php?topic=81039.0


message:
Does anyone have a data sheet for MC16-0072

I can't seem to relibly find data sheets for MCM electronics parts.. Searched for hours.. Any help?

body:
A quick search gave me the impression that MC16-0072 is actually some sort of rebranding. It seems MCM is not the manufacturer, simply a distributor.

Does the hardware itself have any number or serial printed on it?

In any case, when I dug a bit deeper and found [this datasheet](http://www.farnell.com/datasheets/168101.pdf?_ga=1.88928286.403328245.1468222988). However, without an image of your hardware or its serial number, I cannot confirm the datasheet is for your hardware.


message:
ACS712 Not working correctly with Arduino

So I have the basic setup ready with one relay that is controlling a 200W bulb. The Phase of this bulb is passed through a current sensor acs712. While running a simple analog read example sketch, I get output 511 from ADC, which is as expected. Then I subtracted this 511 from my measurement and observed the results while turning on/off the bulb.

    int sensorValue;

    void setup()
    {
      Serial.begin(9600);  // sets the serial port to 9600
    }

    void loop()
    {
      sensorValue = analogRead(0);       // read analog input pin 0
      Serial.println((511-sensorValue), DEC);  // prints the value read
      delay(100);                        // wait 100ms for next reading
    }

Here is the output graph;

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

While the bulb is off, the current remains 0, but when I turn on the bulb, the voltage fluctuates over positive and negative side. Why is the sensor showing this behavior ?, I am not using any additional capacitor for noise reduction. Do I need to ? but I guess this is not noise. Is it ?

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

body:
You are seeing that because that is what the current is doing. It's called AC - Alternating Current. It's what the mains current is.

To work with AC you have to rapidly sample over a short period to get the maximum and minimum values. Subtract one from the other and that gives you the *peak-to-peak* current. You can then use that to calculate the *RMS* current which is what you are (most likely) interested in.

* http://whatis.techtarget.com/definition/root-mean-square-RMS


message:
Storing an array of function pointers

I have some Arduino code that looks like:

    char packet = ser.read();
    switch(packet){
        case 'a':
             someobj.somefunc();
             break;
        case 'b':
             otherobj.otherfunc();
             break;
        ...
    }

I've added a few large libraries that are now causing my sketch to exceed the Arduino Uno's memory. I've done all the usual tricks to reduce memory usage, like using F(), removing unused variables and functions, but I'm still 5% over the memory limit.

I tried commenting out various parts of my code to see what was taking up so much space, and I found removing this switch statement freed up a whopping 20% of memory.

Since it acts like glorified array index, I was wondering if it could in fact be replaced with an array of function pointers, with the packet variable serving as the array index. e.g.

    uint packet = ser.read();
    func_array[packet]();

Although the class instance types are arbitrary, the methods all return the same type and take no arguments.

How would you write an array of pointers to arbitrary class instance methods in Arduino C/C++?

body:
I'm not sure if it will not blow your memory limit as every pointer takes up 16 bits. But in C you usually do it this way:

    void func1() {
        puts("Hello");
    }

    void func2() {
        puts("World!");
    }

    void func3() {
        puts("Array of Size 4");
    }

    void func4() {
        puts("with Pointer");
    }

    void func5() {
        puts("to a Function with no arguments");
    }

    void func6() {
       puts("with return type void");
    }

    void (* myFunc[6])() = { func1, func2, func3, func4, func5, func6 };

    int main(int argc, const char * argv[]) {
        for (int i = 0; i < 6; i++) {
            myFunc[i]();
        }

        return 0;
    }

For explanation of

    void (* myFunc[6])()

You read form inside to outside looking first to the right then to the left

The variable is named myFunc.

    myFunc

My func is an array of size 6.

    myFunc[6]

Each of those entries is a Pointer.

    * myFunc[6]

Now we need parentheses to make clear, that we have a Pointer to a function with no arguments.

    (* myFunc[6])()

And its return type is void.

    void (* myFunc[6])()

Hope this helps a bit.


body:
This is not a direct answer to your question, as I have no such answer,
and I believe the answer you are seeking would be of no use to you.

The problem with your question is that your method of testing memory
usage is heavily flawed. By removing the `switch` statement, you most
likely have allowed the linker to remove lots of methods referenced by
it, leading to huge memory savings. Those savings **do not mean** the
culprit is the switch statement itself.

The correct way to test static memory usage is to use either
`avr-objdump` or `avr-nm`. You have to find where the IDE puts the
compiled elf file, then you can issue the command:

    avr-nm --size-sort -Crtd my_program.elf

This will give you a list of all symbols in your program sorted by size.
Symbols of type 't', 'w' and 'd' (upper or lower case) eat flash.
Symbols of type 'd', 'b' and 'v' eat RAM.


body:
This all gets very much trickier than just an array of function pointers.

Your functions are methods in unknown objects. As such you can't have one single type that stores pointers to the functions in different objects.

The simple reason is that C++ changes the function prototype for you.  For instance, it changes:

    class MyClass {
        public:
            int myFunction(int size) { ... }
    };

into:

    int myFunction(MyClass *this, int size) { ... }

For another class you end up with something like:

    int myFunction(MyOtherClass *this, int size) { ... }

And that is a problem, because although you started with functions that, to you, look the same, they are actually very different. So you can't have one function pointer array with one type that can store either.

One possible method is to use *polymorphism*, where you have one *interface* class that defines the interface your other classes use:

    class MyBaseClass {
        public:
            virtual int myFunction(int size) = 0;
    };

    class MyClass : public MyBaseClass {
        public:
            int myFunction(int size) { ... }
    };

    class MyOtherClass : public MyBaseClass {
        public:
            int myFunction(int size) { ... }
    };

You can then access `myFunction()` in either object as if it were in the class `MyBaseClass`.  Instead of then storing pointers to the functions within the classes you can then store pointers to the classes themselves:

    MyBaseClass *classes[2];

    classes[0] = (MyBaseClass *)&myClassInstance;
    classes[1] = (MyBaseClass *)&myOtherClassInstance;

And then access the functions:

    x = classes[i]->myFunction(z);

However, this is all probably very much a moot point.  The `switch` statement in your code is most likely not what is using all the memory, but all the classes are. By removing the switch you are most likely then not actually doing anything with the classes you have included, and so the linker is then stripping out all that now unreferenced code. A single `switch`, unless it is an absolutely mammoth bit of code, won't take 20% of the Uno's flash.


message:
ATMEGA328 SPI MCP2515 - SPI communication freezes at certain point

I got 2 boards with an [ATMEGA328][1] microcontroller and [MCP2515][2] CAN Controller and I'm trying to get them communicate with each other.

To shortcut the programming a little bit I'm using the [Sparkfun CAN BUS Library][3], but I am not using ther [CanbusClass()][4], I'm directly using the included [mcp2515.c/h][5]

The MCP2515 drives a [MCP2551][6]. CAN_H and CAN_L of both boards are connected with each other, the line has a [120Ohm][7] termination resistor.

[![enter image description here][8]][8]
[![enter image description here][9]][9]
Both Microcontrollers share the same code:

    #include <mcp2515.h>
    #include <global.h>
    #include <mcp2515_defs.h>
    #include <defaults.h>
    #define CANSPEED_125  7
    const uint8_t PIN_LED_RED = 6;
    const uint8_t PIN_LED_GREEN = 7;

    void setup()
    {
   Serial.begin(9600);
     pinMode(PIN_LED_GREEN, OUTPUT);
   pinMode(PIN_LED_RED, OUTPUT);
   unsigned long now=micros();
   unsigned long init = 0;
   if(mcp2515_init(CANSPEED_125)) {
  init=micros();
  Serial.println("CAN Init ok");
  digitalWrite(PIN_LED_GREEN, HIGH);
  delay(500);
  digitalWrite(PIN_LED_GREEN, LOW);
   } else {
  init = micros();
  Serial.println("Can't init CAN");
  digitalWrite(PIN_LED_RED, HIGH);
  delay(1000);
  digitalWrite(PIN_LED_RED, LOW);
   }
   Serial.print("Time for init: ");
   Serial.println (init-now);
   delay(1000);
   mcp2515_bit_modify(CANCTRL, (1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);
   Serial.println("-------------------------");
   Serial.println("1. CAN - MSG1");
   Serial.println("-------------------------");
    }

    void loop()
    {
   tCAN CANmessage;
   unsigned long tnow;
   unsigned long tsend;
   if (Serial.available() > 0) {
    char incomingByte = Serial.read();
  switch (incomingByte) {
   case '1':
    Serial.println("1. CAN - MSG1");
    tsend=micros();
    CANmessage.id = 0x01;
    CANmessage.header.rtr = 0;
    CANmessage.header.length = 8;
    CANmessage.data[0] = B01010101;
    CANmessage.data[1] = B11001100;
    CANmessage.data[2] = B11100011;
    mcp2515_bit_modify(CANCTRL, (1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);
    mcp2515_send_message(&CANmessage);
    tnow=micros();
    Serial.print("Message send in time: ");
    Serial.println(tnow-tsend);
    break;
  }
   }
   checkCANBus();
    }

    void checkCANBus() {
   if (mcp2515_check_message()) {
  tCAN CANmessage;
  PORTD ^= _BV(7);
  Serial.println("Has message");
  if (mcp2515_get_message(&CANmessage))
  {
   Serial.print("Message receivced: ");
   Serial.print(CANmessage.id);
   Serial.print(", ");
   Serial.print(CANmessage.data[0], BIN);
   Serial.print(", ");
   Serial.print(CANmessage.data[1], BIN);
   Serial.print(", ");
   Serial.print(CANmessage.data[2], BIN);
   Serial.print("end ");
   if (CANmessage.id==0x01) {
    Serial.println("MSG ID1 received");
    PORTD ^= _BV(6);
   }
  }
   }
    }

On Serial port of both boards I get on startup:

> CAN Init ok
> Time for init: 250
> 1. CAN - MSG1

When I send a byte on the Serial port of one baord ('1') I get on the Serial:
> Message send in time: 212

On the receiver side I only get
> Has message

and the green LED on PIN7 is turned on (means mcp2515_check_message() returns that the MCP2515 has set the receive interrupt signal).

After that the program crashes in the routine mcp2515_get_message().

By toggling the LED's I figured out that the program crashes directly at the beginning of mcp2515_get_message() in the line mcp2515_read_status(SPI_RX_STATUS);
So the problem lies in mcp2515_read_status().

    int8_t mcp2515_get_message(tCAN *message)
    {
      // read status
      uint8_t status = mcp2515_read_status(SPI_RX_STATUS);
      ...
      ...
    }

    uint8_t mcp2515_read_status(uint8_t type)
    {
     uint8_t data;
     RESET(MCP2515_CS);
     spi_putc(type);
     data = spi_putc(0xff);
     SET(MCP2515_CS);
     return data;
    }

    uint8_t spi_putc( uint8_t data )
    {
   SPDR = data;
   while( !( SPSR & (1<<SPIF) ) )
  ;
   return SPDR;
    }
By further toggling I figured that the last line correctly executed is spi_putc(type);

The line data = spi_putc(0xff); freezes the microcontoller! Which means the while loop in spi_putc() is endless running as the SPIF bit is not cleared.

Here is what I think I figured out so far:

 - The SPI bus connection is clearly working as the initialization is working!
 - As the mcp2515_check_message() returns on the receiver board that MCP2515_INT is set so I assume the CAN communication is working (otherwise, why would controller set the MCP2515_INT).

SPI_RX_STATUS is defined as 0xB0(original as in library).
The [Datasheet][2] of the MCP2515 controller states on page 66

> The RX STATUS instruction (Figure 12-9) is used to
quickly determine which filter matched the message
and message type (standard, extended, remote). After
the command byte is sent, the controller will return
8 bits of data that contain the status data. If more clocks
are sent after the eight bits are transmitted, the
controller will continue to output the same status bits as
long as the CS pin stays low and clocks are provided.

Which it clearly doesn't! But what I cant figure out is why :)

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
  [2]: http://www.farnell.com/datasheets/1669372.pdf
  [3]: https://github.com/sparkfun/SparkFun_CAN-Bus_Arduino_Library
  [4]: https://github.com/sparkfun/SparkFun_CAN-Bus_Arduino_Library/blob/master/src/Canbus.h
  [5]: https://github.com/sparkfun/SparkFun_CAN-Bus_Arduino_Library/blob/master/src/mcp2515.c
  [6]: http://ww1.microchip.com/downloads/en/DeviceDoc/21667f.pdf
  [7]: https://electronics.stackexchange.com/questions/55389/why-does-the-can-bus-use-a-120-ohm-resistor-as-the-terminating-resistor-and-not
  [8]: https://i.stack.imgur.com/F4U8A.png
  [9]: https://i.stack.imgur.com/cVAIP.png

body:
There is one huge pitfall in Master Mode in this ATMega - Select Slave pin (/SS - active low). If it's configured as input, SPI is switched to Slave Mode by low level on this pin. And /SS is on pin PB2 (used as CAN_INT).

In the [library defaults][1] I can see: `#define MCP2515_INT D,2`. PD2 is also INT0 external interrupt pin, so it does make sense to be here and it can be used with attachInterrupt. PB2 is used as an output for selecting slave device, so it's ok too.

[Schematics][2] corresponds with that defaults:
[![shield interface][3]][3]

In OPs schematics there are slight changes. Interrupt request CAN_INT is located on /SS pin (PB2, arduino pin 10). CAN_CS was moved from PB2 to PB1 (arduino pin 10 -> pin 9)

And in [Mega328][4] datasheet is section: 19.2 SS Pin Functionality:

> **19.3.2 Master Mode**

When the SPI is configured as a Master (MSTR in SPCR is set), the user can determine the direction of the /SS
pin.

If /SS is configured as an output, the pin is a general output pin which does not affect the SPI system. Typically,
the pin will be driving the SS pin of the SPI Slave.

**If /SS is configured as an input, it must be held high to ensure Master SPI operation. If the /SS pin is driven low by
peripheral circuitry when the SPI is configured as a Master with the /SS pin defined as an input, the SPI system
interprets this as another master selecting the SPI as a slave and starting to send data to it.**
 To avoid bus
contention, the SPI system takes the following actions:

1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As a result of the SPI becoming a Slave, the MOSI and SCK pins become inputs.

2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled, and the I-bit in SREG is set, the interrupt
routine will be executed.

Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists a possibility that SS is
driven low, the interrupt should always check that the MSTR bit is still set. If the MSTR bit has been cleared by
a slave select, it must be set by the user to re-enable SPI Master mode.

**Conclusion**: If you are using HW SPI in master mode, you can't just use pin 10 (PB2) as general input.

  [1]: https://github.com/sparkfun/SparkFun_CAN-Bus_Arduino_Library/blob/master/src/defaults.h
  [2]: http://cdn.sparkfun.com/datasheets/Dev/Arduino/Shields/SparkFun_CAN-Bus_Shield_v13a.pdf
  [3]: https://i.stack.imgur.com/v6Zoo.png
  [4]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf


message:
Serial Monitor listing rapidly

I am using an infrared sensor and a flex sensor to read values from the serial monitor in arduino, however after maybe ten seconds or so it seems the serial monitor breaks and the printed values start to print out rapidly. Does anyone have any suggestions on why this might occurring. Any information would be highly appreciated.

Thanks.

    int previousMillis = 0;

    long interval1 = 300;
    long interval2 = 350;

    void setup() {

        Serial.begin(9600);
    }

    void loop() {

        unsigned long currentMillis = millis();

        if ( currentMillis - previousMillis >= interval1 ) {
            previousMillis = currentMillis;

            Serial.println( "TIMER IS DONE!" );

            int val1 = analogRead(0);
            Serial.print("Sensor Value 1 is ");
            Serial.println(val1);
            delay(5);
        }
        if ( currentMillis - previousMillis >= interval2 ) {
            previousMillis = currentMillis;

            int val2 = analogRead(1);

            Serial.print("Sensor Value 2 is ");
            Serial.println(val2);
        }
        delay(10);
    }

body:
You are doing math with 2 different types.   One is long and the other is an int.  So, eventually the long will always be lager than the int and the test will always be true.  (A 32 bit long can count up to over 2 billion.  A 16 bit int can only count up to about 32 thousand.)

Also, the method millis() is of type "unsigned long".  So change all your variables to match this type.

Also note that when the millis() timer overflows and start over your program may perform unexpectedly.  Since this rarely happens it may not concern you.


body:
I hate to start with "I hate delays", but I hate delays :)

Why have you included them? If you want your outputs to be slower, increase your intervals.

Use a state machine instead:

    unsigned long previousMillis = 0;
    unsigned long currentMillis = 0;

    unsigned long interval1 = 300;
    unsigned long interval2 = 350;

    #define LEDPIN  13

    int state = 0;
    // 0 = waiting for sensor one interval
    // 1 = another 50ms for sensor two

    void setup() {
        currentMillis=millis();
        previousMillis=currentMillis;
        Serial.begin(9600);
        pinMode(LEDPIN, OUTPUT);
        digitalWrite(A0, HIGH); // internal pullups
        digitalWrite(A1, HIGH); // internal pullups

    }

    void loop() {
        currentMillis = millis();
        if ( state == 0 )
        {
            if ( currentMillis - previousMillis >= interval1)
            {
                int val1 = analogRead(0);
                Serial.print( currentMillis );
                Serial.print(" Sensor Value 1 is ");
                Serial.println(val1);
                digitalWrite(LEDPIN, HIGH);
                state = 1;
            }
        }
        else
        {
            if ( currentMillis - previousMillis >= interval2)
            {
                int val2 = analogRead(1);
                Serial.print( currentMillis );
                Serial.print(" Sensor Value 2 is ");
                Serial.println(val2);
                digitalWrite(LEDPIN, LOW);
                state = 0;
                previousMillis = currentMillis;
            }
        }
    }

This way, test 2 will only be conducted 50ms after test 1 and then previous millis is reset

edit: I fixed the interval test regarding overflow (which you had correctly in the first place)

edit2: (I'm having too much fun with this)
assuming you want each test conducted at specifically the interval requested (ie sensor 1 every 300ms and sensor 2 every 350ms), I have come up with v2 (and removed the state machine, since it's just not needed)

    unsigned long previous1 = 0;
    unsigned long previous2 = 0;
    unsigned long currentMillis = 0;

    unsigned long interval1 = 300;
    unsigned long interval2 = 350;

    const int LEDPIN = 13;

    void setup() {
        currentMillis=millis();
        previous1=currentMillis;
        previous2=currentMillis;
        Serial.begin(9600);
        pinMode(LEDPIN, OUTPUT);
        digitalWrite(A0, HIGH);
        digitalWrite(A1, HIGH);
    }

    void loop() {

        currentMillis = millis();
        if ( currentMillis - previous1 >= interval1)
        {
            previous1 = currentMillis;

            int val1 = analogRead(0);
            Serial.print(currentMillis);
            Serial.print(" Sensor Value 1 is ");
            Serial.println(val1);
            digitalWrite(LEDPIN, HIGH);
        }
        if ( currentMillis - previous2 >= interval2)
        {
            int val2 = analogRead(1);

            Serial.print(currentMillis);
            Serial.print(" Sensor Value 2 is ");
            Serial.println(val2);
            previous2 = currentMillis;
            digitalWrite(LEDPIN, LOW);
        }
    }

edit: including some sample output to indicate a working state:

    188609 Sensor Value 1 is 15
    188659 Sensor Value 2 is 14
    188959 Sensor Value 1 is 14
    189009 Sensor Value 2 is 15
    189309 Sensor Value 1 is 15
    189359 Sensor Value 2 is 14
    189659 Sensor Value 1 is 14
    189709 Sensor Value 2 is 1017
    190009 Sensor Value 1 is 15
    190059 Sensor Value 2 is 1002
    190359 Sensor Value 1 is 14
    190409 Sensor Value 2 is 1013
    190709 Sensor Value 1 is 14
    190759 Sensor Value 2 is 1019
    191059 Sensor Value 1 is 15
    191109 Sensor Value 2 is 1004
    191409 Sensor Value 1 is 14
    191459 Sensor Value 2 is 1019
    191759 Sensor Value 1 is 15
    191809 Sensor Value 2 is 15
    192109 Sensor Value 1 is 14
    192159 Sensor Value 2 is 15
    192459 Sensor Value 1 is 14
    192509 Sensor Value 2 is 14
    192809 Sensor Value 1 is 15
    192859 Sensor Value 2 is 15
    193159 Sensor Value 1 is 14
    193209 Sensor Value 2 is 16
    193509 Sensor Value 1 is 14
    193559 Sensor Value 2 is 15
    193859 Sensor Value 1 is 1005
    193909 Sensor Value 2 is 1021
    194209 Sensor Value 1 is 1021
    194259 Sensor Value 2 is 1003
    194560 Sensor Value 1 is 1004
    194609 Sensor Value 2 is 1020
    194909 Sensor Value 1 is 1020
    194959 Sensor Value 2 is 1004
    195259 Sensor Value 1 is 15
    195309 Sensor Value 2 is 1001
    195609 Sensor Value 1 is 14
    195659 Sensor Value 2 is 1022
    195959 Sensor Value 1 is 15
    196009 Sensor Value 2 is 998
    196310 Sensor Value 1 is 15
    196359 Sensor Value 2 is 1019
    196659 Sensor Value 1 is 15
    196709 Sensor Value 2 is 1002
    197009 Sensor Value 1 is 14
    197059 Sensor Value 2 is 15
    197359 Sensor Value 1 is 14
    197409 Sensor Value 2 is 15
    197709 Sensor Value 1 is 15
    197760 Sensor Value 2 is 13
    198060 Sensor Value 1 is 14
    198110 Sensor Value 2 is 15
    198410 Sensor Value 1 is 15
    198460 Sensor Value 2 is 14


message:
RC522 RFID reader doesn't read NTAG216 chip

I have an RFID-RC522 module based on the [MFRC522 chip](http://www.nxp.com/documents/data_sheet/MFRC522.pdf). This chip is described in the datasheet as supporting "ISO/IEC 14443 A/MIFARE and NTAG" protocols. I have wired it up to an Arduino Uno using the recommended wiring in the documentation for the [MFRC522 library](https://github.com/miguelbalboa/rfid) I'm using. I have a sketch that (among other things) polls for presence of a new card:

    void setup() {
        lcd.setup ();       // initialise LCD display
     SPI.begin();  // Init SPI bus
     mfrc522.PCD_Init(); // Init MFRC522 card
    }

    void loop() {
        // Look for new cards
        if ( ! mfrc522.PICC_IsNewCardPresent()) {
            return;
        }
        lcd.println ("Found new card");
        ...
    }

This sketch correctly detects the presence of the card that was supplied with the module (I believe this is a Mifare Classic card) but does not detect my NTAG216 implant. Does anyone have any idea why it might be failing to find the implanted chip?

body:
I got my RFID kit (RF522) just this week, but I haven't had a chance to play with it yet - nor do I have an NTAG216 implant. But I remember when I was researching them seeing a couple of posts that had to do with "Authentication errors". The problem for you (maybe) is that they were in Python rather than C:

https://github.com/mxgxw/MFRC522-python/issues/24

and Cotix's link

https://github.com/mj3052/MFRC522-Pi

Give them a lookover and see what they can tell you.

The problem with the `PICC_IsNewCardPresent()` function is that it gives a Yes/No answer, not a "Yes, but there's an error". In that case it would also return `false`. But the other code may give you a clue - you'll have to delve into the library...


message:
If - else statement in Arduino

I'm starting to learn how to use Arduino and I tried to make this code, which is just a simple if else statement; what I want to make is when the input is LOW, LED 1 is HIGH and LEDs 2,3 are LOW, and when the input is HIGH, the LEDs 2,3 are HIGH and LED 1 is LOW. I wrote this code but when I put the switch in LOW, instead having just like what I intended, all the outputs are HIGH.

I try changing the output and I checked all the wiring to the LEDs so my mistake is in the code.

Could you guys tell me what's wrong with the code?

    int switchstate = 0;
    void setup() {
      pinMode (13,OUTPUT);
      pinMode(12,OUTPUT);
      pinMode(11,OUTPUT);
      pinMode(3,INPUT);
    }

    void loop() {
      switchstate = digitalRead(3);
      if (switchstate == LOW) {
        digitalWrite(11,HIGH);
        digitalWrite(12,LOW);
        digitalWrite(13,LOW);
      } else {
        digitalWrite(11,LOW);
        digitalWrite(12,HIGH);
        digitalWrite(13,HIGH);
      }
    }

body:
Your code doesn't seem to be the problem. Contrary to what you are saying I think your problem is most definitely in your hardware setup.

Most likely, your digitalRead doesn't register a HIGH input, so it doesn't get 5V. Instead of digitalRead, go for analogRead(A0). So change your circuit and attach it to pin A0.

Use serial.println(switchstate) to print the results to the serial monitor and then decide what your top value (HIGH) and bottom value (LOW) for detection will be. Perhaps include a pull down resistor as well on the A0 pin.


body:
To debug this, as Len has suggested I would recommend putting in some Serial.println("Debug info") commands into your code. This will confirm that you are programming the Arduino as you expect, and that the Arduino is running.

To do this simply include a `Serial.begin(9600)` command in your setup block, and then a `Serial.println("Some text")` wherever you want to check if you are reaching a certain part of the code. You can then read these messages via the serial monitor (which you can get to from Tools->Serial Monitor in the Arduino IDE).

For hardware debugging if you have a multi-meter available I would check that you are getting 0V/5V on digital pin 3 when you expect (i.e. when you are / are not pressing the button). Also, to check your LEDs are working, and connected to the output pins you think they are, write a script which just scrolls through them with a short delay (See the `Blink` example under File->Examples->01.Basics->Blink for an example of how to do that).


message:
Why send my Arduino sometime Hex and sometimes the wrong?

Hi i have an Arduino mega 2560 i send data from the Arduino over USB to PC. That works when i test a simple Serial.print("Hello"); but that is not that what i need. I send a timestamp as a longe Value and the databyte as a short Value. When i send the timestamp as BIN like that:

          //Initialisisation

    const int RX = 0;
    const int TX = 1;
    const int RX1 = 19;
    const int TX1 = 18;
    unsigned long currentMillis;

    void setup()
    {
      pinMode(RX, INPUT);   //Readpin for USB
      pinMode(TX, OUTPUT);  //Writepin for USB
      pinMode(RX1, INPUT);  //Readpin for bus
      pinMode(TX1, OUTPUT); //Writepin for für bus

      Serial.begin(38400);   //open interface for USB
      Serial1.begin(4800);   //open interface for bus

      while (!Serial & !Serial1 &! Serial2)
      {
        ;//wait for serial port connect.
      }
    }

    void loop()
    {
      //Ask if the timestamp over 8 hours, when yes,
      //send the time to the pc and reset currentMillis.
      currentMillis = millis();
      if (currentMillis >= 28800000)  //milli() 8 hours is a 4 byte  timestamp 28.800.000 millisec.
      {
        unsigned long timestamp = currentMillis;
        sendBinaryTime(timestamp);
        currentMillis = 0;
      }//end if

      //if the businterface available, read a byte
      //and send it with the timestamp to the PC.
      //If the businterface not available send an error.
      //short incomingByte = Serial1.read();
      //sendBinaryValue(incomingByte);
      if(Serial1.available()>0) //if the bus (serial1) available?
        {
          short incomingByte = Serial1.read(); //read the next byte from _rx_buffer
          sendBinaryValue(incomingByte);
          sendBinaryTime(currentMillis);   //sendBinary send a long over the bus
        }//end if
    }//end Loop()

    //Methods for sending long values

    void sendBinaryValue(short incomingByte)
      {
        int temp = (incomingByte & 0xFF00)>>8;
        Serial.println(temp, HEX);
        temp = (incomingByte & 0x00FF);
        Serial.println(temp, HEX);
        return;
      }

    void sendBinaryTime(unsigned long currentMillis)//send milliseconds after every byte
    {
      int temp = (currentMillis & 0xFF000000)>>24; //send 16 bit of the low value
      Serial.print(temp, BIN);
      temp = (currentMillis & 0x00FF0000)>>16;      //send 16 bit of the high value
      Serial.print(temp, BIN);
      temp = (currentMillis & 0x0000FF00)>>8;
      Serial.print(temp, BIN);
      temp = (currentMillis & 0x000000FF);
      Serial.print(temp, BIN);
      return;
    }

All is fine i haven´t any error. But i want the timestamp as DEC so i have changed the code to:

           void sendBinaryValue(short incomingByte)
     {
       int temp = (incomingByte & 0xFF00)>>8;
       Serial.println(temp, HEX);
       temp = (incomingByte & 0x00FF);
       Serial.println(temp, HEX);
       return;
     }

    void sendBinaryTime(unsigned long currentMillis)
    {
     int temp = (currentMillis & 0xFF000000)>>24;
     Serial.print(temp, DEC);
     temp = (currentMillis & 0x00FF0000)>>16;
     Serial.print(temp, DEC);
     temp = (currentMillis & 0x0000FF00)>>8;
     Serial.print(temp, DEC);
     temp = (currentMillis & 0x000000FF);
     Serial.print(temp, DEC);
     return;
    }

Now when i look on the serial monitor i get an error.
Here you can see it:

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

I send an A as ASCII sign that must be Hex 41 and i receive a Hex 5 but why? When i send the timestamp as BIN i get the 41 and haven´t any problem.

I hope someone can help me with friendly wishes sniffi

  [3]: https://i.stack.imgur.com/i7ruR.png

body:
I have found several problems with your program, although they may not
be related with your primary problem:

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

    while (!Serial & !Serial1 &! Serial2)

You mean `while (!Serial || !Serial1 || !Serial2)`, although this is
only useful with virtual serial ports, like on the Leonardo. On the
mega, all of these ports are real hardware ports.

    void sendBinaryValue(short incomingByte)

The way you name the parameter is misleading: a `short` is not a byte,
it's two bytes.

    int temp = (incomingByte & 0xFF00)>>8;

You are bit-shifting a signed number, which is going to do a sign
extension. This is probably not what you want.

    Serial.print(temp, DEC);

You are printing several numbers one after the other with no separator.
This is going to cause ambiguities: you cannot know whether "345" means
"3 45" or "34 5".

Finally, I don't get the purpose of your functions. Why don't you just
print the numbers like this?

    Serial.println(incomingByte, HEX);
    Serial.println(currentMillis);


message:
How to use same sketch on two different computers in two different directories

I have the same sketch one that I use at my desk and in the lab, but they are in different directories on the different computers.  This means that I have to change the paths to the includes which I have to fixup every time I transfer back and fourth.  Is there a way to put in a #ifdef that I can set at the start of the build that would include correct path.

body: Open `preferences.txt` in `C:\Users\YourUserName\AppData\Roaming\Arduino` and change the path of `sketchbook.path=C:\Users\YourUserName\Documents\Arduino` to `sketchbook.path=YourDesiredPath`.


message:
Using micros() to measure analogRead() time varies based on Serial.print location?

I'm trying to use micros() to measure the time it takes to execute an analogRead() cycle, but am having some issues.  Originally, I just printed out the measured time for the analogRead() right after doing the subtraction, but I wanted to change that to printing out all of the time values for the 100 loops at once.  When I print the start times, end times, and values both in the if statement (right after calculating them) and at the end, the values printed are the same.  I'm not sure if they're accurate because they fluctuate a lot within those 100 tests.  For example, some of these measured times consecutively are 216, 97, 153, 34, 89, 145, 27.  I put the ADC in freerun mode, so I figured it could be normal for that.  However, when I don't print the start times, end times, or values immediately after calculating them and instead try to print them in the else if statement, it gives a stream of values that are all either 407 or 408.  If I print "Test" instead of the values right after calculating them, it still gives the (I'm assuming) correct values that vary a lot, not the 407s.  If, instead of printing them in the if statement, I print them just in the general loop (currently commented out) and the else if statement, they are still the varying maybe-correct values.  I assumed that even if the values aren't being printed, they're still being stored in the array correctly.  I don't understand why printing something unrelated right after storing the values would change them.  Any ideas?

Thanks

        int sensorPin = A1;    // select the input pin for the potentiometer
        int ledPin = 13;      // select the pin for the LED
        int sensorValue[1000];  // variable to store the value coming from the sensor
        int ind = 0;
        int starts[1000];
        int ends[1000];
        int vals[1000];
        int stopprint = 0;
        int i = 0;
        int countto = 100;

        void setup() {
          // declare the ledPin as an OUTPUT:
          Serial.begin(57600);
          analogReadResolution(12);
          pinMode(ledPin, OUTPUT);
          Serial.println("ready to begin");
            analogReadSetup(A1);
          for (i = 0; i < 1000; i++) {
            starts[i] = 0;
            ends[i] = 0;
            vals[i] = 0;
          }
        }

        void loop() {
          // read the value from the sensor:
          if (ind < countto) {
          starts[ind] = micros();
        //  delay(50);
          sensorValue[ind] = analogRead(sensorPin);
          ends[ind] = micros();
          vals[ind] = ends[ind] - starts[ind];
        //  Serial.println("Test");
            Serial.print(ind);
            Serial.print('\t');
            Serial.print(starts[ind]);
            Serial.print('\t');
            Serial.print(ends[ind]);
            Serial.print('\t');
            Serial.print(vals[ind]);
            Serial.print('\t');
            Serial.print('|');
            Serial.print('\t');
          Serial.print('\n');
          Serial.print('\r');
          ind++;
          }
          else if (stopprint == 0) {
            Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");
            for (int j = 0; j < countto; j++) {
        //        Serial.println(j);
                Serial.print(starts[j]);
                Serial.print('\t');
                Serial.print(ends[j]);
                Serial.print('\t');
                Serial.print(vals[j]);
                Serial.print('\n');
                Serial.print('\r');
                stopprint = 1;
            }
          }
          else if (stopprint == 1) {
            while(1);
          }
        //  Serial.print(ind-1);
        //  Serial.print('\t');
        //  Serial.print(starts[ind-1]);
        //  Serial.print('\t');
        //  Serial.print(ends[ind-1]);
        //  Serial.print('\t');
        //  Serial.print(vals[ind-1]);
        //  Serial.print('\n');
        //  Serial.print('\r');
       }

Also, I'm using the Arduino Zero if it makes a difference.

body:
Not sure if it is related to your problem but... if I were to try such a
measurement, I would use local variables, like

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

    unsigned int start = micros();
    int value = analogRead(sensorPin);
    unsigned int end = micros();
    sensorValue[ind] = value;
    starts[ind] = start;
    ends[ind] = end;
    vals[ind] = end - start;

This way you would be measuring the time it takes to call both
`analogRead()` and `micros()`, and very little more. If you do something
like

    sensorValue[ind] = analogRead(sensorPin);

then you are also measuring the time taken by the pointer arithmetic and
the memory access.

I generally program AVR-based Arduinos. These have a load-store
architecture, where saving to a local variable costs essentially
nothing, as the variable is typically assigned a CPU register by the
compiler. Saving to a global takes more time because of the RAM access.

I have no experience with ARM-based Arduinos, like the Zero, but I
believe it's also a load-store architecture, thus the same
considerations should probably apply.

**Update**: I tried the following experiment on my Uno:

    #define PRINT_WHILE_READING

    #define READ_COUNT 100

    void setup() {
        unsigned int starts[READ_COUNT];
        unsigned int ends[READ_COUNT];
        unsigned int vals[READ_COUNT];

        Serial.begin(57600);
        Serial.println("Ready to begin");

        // Take the readings.
        for (int i = 0; i < READ_COUNT; i++) {
            starts[i] = micros();
            analogRead(A1);
            ends[i] = micros();
            vals[i] = ends[i] - starts[i];
    #if defined(PRINT_WHILE_READING)
            Serial.print(i);
            Serial.print('\t');
            Serial.print(starts[i]);
            Serial.print('\t');
            Serial.print(ends[i]);
            Serial.print('\t');
            Serial.println(vals[i]);
    #endif
        }

    #if !defined(PRINT_WHILE_READING)
        // Print them now.
        Serial.println("All data taken");
        for (int i = 0; i < READ_COUNT; i++) {
            Serial.print(i);
            Serial.print('\t');
            Serial.print(starts[i]);
            Serial.print('\t');
            Serial.print(ends[i]);
            Serial.print('\t');
            Serial.println(vals[i]);
        }
    #endif
    }

    void loop() {}

If `PRINT_WHILE_READING` is defined as above, I get times that fluctuate
between 108 and 116 µs. If I comment out the line
`#define PRINT_WHILE_READING`, I get mostly 116 µs and,
occasionally, 124 µs. In both cases, the first reading takes longer
(208 and 212 µs respectively).

The fact that the first reading takes longer is explained in the
datasheet: the ADC does some initializations in that first reading. All
measured times are multiples of 4 µs because that is the resolution
of `micros()`.

Now, trying to understand the differences between the two cases:

1. With `PRINT_WHILE_READING` the times are shorter on average. This is
   because the numbers are not stored in RAM, as the compiler figured
   out the arrays `starts[]`, `ends[]` and `vals[]` are not really
   needed and optimized them away. When `PRINT_WHILE_READING` is not
   defined, I can see the “store in RAM” instructions in the generated
   assembly.

2. With `PRINT_WHILE_READING` the numbers fluctuate more. I guess this
   is due to the printing through the serial port taking a variable
   amount of time depending on the numbers being printed, and thus
   creating timing inconsistencies.

The last point deserves some explanation. The ADC is clocked by a
prescaler that divides the frequency of the main clock by 128. This
gives a clock period of 8 µs. When an ADC conversion is started,
the ADC waits for the next rising edge of its clock, which can take
anywhere between 0 and 8 µs, then it does the conversion in
13 cycles of its clock. This means the whole process can take
anywhere between 104 and 112 µs depending on the exact time the
conversion is started relative to the phase of the prescaler. If the
conversions are started at irregular intervals, you expect to see
roughly 8 µs of fluctuation in the measured times.

All these observations have been done on an Uno, which is based on an
AVR clocked at 16 MHz. I know the Zero is quite different. You will
have to look at the datasheet of the ATSAMD21G18 to see whether anything
of the above can be extrapolated to the Zero.


body: If you have access to a digital scope, try bracketing your code with changes to the state of an output pin. print() has a lot of moving parts, some (like buffer size, interrupt implementation) will vary with various Arduinos as others have noted. I am mostly using ARM Cortex M4 on Teensy 3.2. If I want to time something really precisely I will drive an I/O pin (with digitalWrite()) at the beginning and end of what I want to time. This has super fast execution. You could use more than one pin to see two things at once. Then, look at them on an oscilloscope. Trigger on the starting edge of the most important signal. Adjust the time scale to encompass the active pin level time. With a digital scope you can set persistence to infinite and then you can see the variation on the trailing edge of the pulse. You can move the digitalWrite points around in your program until you see what is causing the variation. millis() and micros() are 32-bit values so on an 8-bit AVR that is multiple machine cycles to access. A single digitWrite is usually one machine cycle so it is quick even on a slowly-clocked 8-bit AVR. Once you find the place where most of the variation occurs you at least have a quantified smoking gun to tell you what details to excavate further.


message:
ESP 01 - reset settings to default values

I set up communication between Arduino UNO and ESP 01 module. ESP replied to AT commands, but sometimes I got result from ESP uncompleted or with wrong characters, so I tried to set AT+IPR=9600, I didnt receive any output to this command and after reboot I only can see random characters on every baudrate, blue diode on ESP shines all the time. Is there any way how I can reset ESP 01 to default settings? Tried to set RESET pin to GND, but it didnt help.

I use remote power supply 3,3V/1A

Pins connected:

    Vcc = external power supply 3,3V
    GND = GND (interconnected bot Arduino and power supply GND)
    Tx = Arduino Rx(changed pin to 11 by SoftwareSerial)
    Rx = Arduino Tx(changed pin to 10 by SoftwareSerial)
    CH_PD - 3,3V

body:
Current ESP-01 firmware versions do not have an `AT+IPR` command. If you're trying to change the ESP's baud rate to use it with SoftwareSerial, the command to do so (in recent versions of the firmware) is: `AT+UART=9600,8,1,0,0` for 9600 baud, 1 stop bit, no parity, no flow control.

The full syntax is:
 `AT+UART=<baudrate>, <databits>, <stopbits>, <parity>, <flow control>`
, where <databits> is the number of data bits per frame, 5,6,7,or 8; <stopbits> is 1, 2, or 3 for 1, 1.5, or 2 stopbits (respectively); <parity> is 0, 1, or 2 for None, Odd, Even (respectively); and <flow control> is 0, 1, 2, or 3 for None, RTS, CTS, RTS and CTS (respectively). Most serial communication and devices that most of us will ever see will be 8 data bits, no parity, and 1 stop bit, abbreviated as "8N1". Flow control is sometimes used, but often it is contained in the data stream itself, such as sending Ctl-S and Ctl-Q from the keyboard to manually stop and resume incoming data transmission.


body:
While this technically is not an answer, I can highly suggest the ESP 8266 Arduino library. This way you can program in the Arduino IDE and upload to the ESP module. It's so much faster and efficient than AT commands and because you can see the code in the IDE, you have a better overview of what is happening in the code.

https://github.com/esp8266/Arduino


message:
Arduino + ultrasonic rangefinder behaving unexpectedly

I'm using an [HC-SR04 ultrasonic rangefinder][1] to control the frequency at which an Arduino pin turns on and off, with the output going via a 1/4" jack plug into my computer's audio interface. (i.e. it's a simple audio oscillator that responds to gestures). This is the code (based on that given [here][2]):

    #define trigPin 10
    #define echoPin 12

    void setup() {

      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(9, OUTPUT);

    }

    void loop() {

      float duration, distance;
      digitalWrite(trigPin, LOW); // Sends a 2 µs LOW signal to the trigPin
      delayMicroseconds(30);

      digitalWrite(trigPin, HIGH); // Sends a 10 µs HIGH signal to the trigPin
      delayMicroseconds(30);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH); //Defines the duration variable

      digitalWrite(9, HIGH); //square wave oscillator
      delay(0.1+duration*0.01);
      digitalWrite(9, LOW);
      delay(0.1+duration*0.01);
    }

Pin 9 is the output, and sounds roughly as expected, but what's confusing me is that making any kind of gesture other than very slow ones (i.e. if the distance isn't changing very slowly) causes the output to stop completely for a few seconds, then start again, as if something is overloading and then resetting. What am I doing wrong?

  [1]: http://www.micropik.com/PDF/HCSR04.pdf
  [2]: http://www.circuitbasics.com/how-to-set-up-an-ultrasonic-range-finder-on-an-arduino/

body:
Your comments don't match your timing delay values and the datasheet specifies a 10 µs pulse. You're giving it 30 µs but you might get away with it.

I'd look at how often you're triggering the device.

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

_Figure 1. Don't trigger the device more frequently than 40 times per second._

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


body:
I do not really understand the behaviour of your program, but I would
like to point out a couple of points that may be problematic:

1. Your comment says “Sends a 10 µs HIGH signal to the trigPin”, just as
   the program you based yours on, yet you have a 30 µs delay. If
   this extra delay makes you miss the rising edge on the echo pin, then
   `pulseIn()` will believe it is seen the _previous_ pulse, and it will
   wait for the next raising edge before starting its measurement. Since
   that next rising edge will never happen, `pulseIn()` will eventually
   time out after one second. This is probably the silence you are
   hearing.
2. Your sound frequency may not be what you expect, because the time
   needed to run through the loop is not only the two calls to
   `delay()`, but also the time taken by `pulseIn()` and the various
   `delayMicroseconds()`. You should have more consistent timings if you
   use the `tone()` function instead of trying to bit-bang the sound.


message:
Which Protocol to use to control WiFi (ESP8266) enabled Led Light

I am developing a Wifi based Led light (Got Inspired from Philips hue, Lifx). I have little knowledge about web server, clients, Web protocols. I will be using ESP8266 as Controller cum WiFi module.

There are two ways to control Led light over WiFi.

 1. Locally
 2. Remotely

Android/iOS app will be handling all the control part.

Which protocols can I use to control Led light, locally? HTTP or Websockets?

> Note :- The speed is critical, android/iOS app can send around 50-60 values per second.

Also, which protocol should I go with if Led light is controlled Remotely.? So far, MQTT seems reliable. Any suggestion?

Kindly help!

body:
UDP :D

Seriously though, ESP8266 is limited in resources, AND you want to send 50-60 updates a second, just UDP will be the most lightweight, and you won't run out of connections (5 I think on ESP), because UDP has no connection state.

This is what was used here to control a RGB strip: https://github.com/cnlohr/esp8266ws2812i2s , it just listens for UDP packets on port 7777, and each packet contains rgb values, one byte for R,G,B, etc.

MQTT is nice, but it doesn't work well for 60hz updates, *I Tried* :D
It resulted in un-smooth animation, and frames out of order.