message:
Help needed to add and extra sensor

I am new to Arduino, and already tried to edit this many time. But I cant figure out whats wrong.

The following code has a PIR sensor, 1 LED and 1 buzzer.
I want to add one more PIR sensor, but it should trigger a separate LED , and the same buzzer. In serial monitor.
I have searched many sketches, but all of them seems to have a different method , cant figure out the basics!

    int ledPin = 13;                // choose the pin for the LED
    int inputPin = 2;               // choose the input pin (for PIR sensor)
    int pirState = LOW;             // we start, assuming no motion detected
    int val = 0;                    // variable for reading the pin status
    int pinSpeaker = 10;           //Set up a speaker on a PWM pin (digital 9, 10, or 11)

    void setup() {
      pinMode(ledPin, OUTPUT);      // declare LED as output
      pinMode(inputPin, INPUT);     // declare sensor as input
      pinMode(pinSpeaker, OUTPUT);
      Serial.begin(9600);
    }

    void loop(){
      val = digitalRead(inputPin);  // read input value
      if (val == HIGH) {            // check if the input is HIGH
        digitalWrite(ledPin, HIGH);  // turn LED ON
        playTone(300, 160);
        delay(150);

        if (pirState == LOW) {
          // we have just turned on
          Serial.println("Motion detected!");
          // We only want to print on the output change, not state
          pirState = HIGH;
        }
      } else {
          digitalWrite(ledPin, LOW); // turn LED OFF
          playTone(0, 0);
          delay(300);
          if (pirState == HIGH){
          // we have just turned off
          Serial.println("Motion ended!");
          // We only want to print on the output change, not state
          pirState = LOW;
        }
      }
    }
    // duration in mSecs, frequency in hertz
    void playTone(long duration, int freq) {
        duration *= 1000;
        int period = (1.0 / freq) * 1000000;
        long elapsed_time = 0;
        while (elapsed_time < duration) {
            digitalWrite(pinSpeaker,HIGH);
            delayMicroseconds(period / 2);
            digitalWrite(pinSpeaker, LOW);
            delayMicroseconds(period / 2);
            elapsed_time += (period);
        }
    }

body:
Well, after playing with the code for some time, I just did it!!
pasting the updated code here, may be useful for someone else like me..

    int ledPin = 13;                // choose the pin for the LED
    int ledPinB = 12;               // choose the pin for the LED 2
    int inputPin = 2;               // choose the input pin (for PIR sensor)
    int inputPinB = 4;              // choose the input pin (for PIR sensor 2)
    int pirState = LOW;             // we start, assuming no motion detected
    int val1 = 0;                  // variable for reading the pin status
    int val2 = 0;                  // variable for reading the pin status
    int pinSpeaker = 10;           //Set up a speaker on a PWM pin (digital 9, 10, or 11)

    void setup() {
      pinMode(ledPin, OUTPUT);      // declare LED as output
      pinMode(ledPinB, OUTPUT);      // declare LED as output
      pinMode(inputPin, INPUT);     // declare sensor as input
      pinMode(inputPinB, INPUT);     // declare sensor as input
      pinMode(pinSpeaker, OUTPUT);
      Serial.begin(9600);
    }

    void loop(){
      val1 = digitalRead(inputPin);  // read input value
      val2 = digitalRead(inputPinB);  // read input value
      if (val1 == HIGH) {            // check if the input is HIGH
        digitalWrite(ledPin, HIGH);  // turn LED ON
        playTone(300, 160);
        delay(150);

        if (pirState == LOW) {
          // we have just turned on
          Serial.println("Motion detected!");
          // We only want to print on the output change, not state
          pirState = HIGH;
        }
      }
      else if (val2 == HIGH) {            // check if the input is HIGH
        digitalWrite(ledPinB, HIGH);  // turn LED ON
        playTone(300, 160);
        delay(150);

        if (pirState == LOW) {
          // we have just turned on
          Serial.println("Motion detected!");
          // We only want to print on the output change, not state
          pirState = HIGH;
        }
      }

      else {
          digitalWrite(ledPin, LOW); // turn LED OFF
          digitalWrite(ledPinB, LOW); // turn LED OFF
          playTone(0, 0);
          delay(300);
          if (pirState == HIGH){
          // we have just turned off
          Serial.println("Motion ended!");
          // We only want to print on the output change, not state
          pirState = LOW;
        }
      }
    }
    // duration in mSecs, frequency in hertz
    void playTone(long duration, int freq) {
        duration *= 1000;
        int period = (1.0 / freq) * 1000000;
        long elapsed_time = 0;
        while (elapsed_time < duration) {
            digitalWrite(pinSpeaker,HIGH);
            delayMicroseconds(period / 2);
            digitalWrite(pinSpeaker, LOW);
            delayMicroseconds(period / 2);
            elapsed_time += (period);
        }
    }

[Link to circuit and virtual demo][1]

  [1]: https://circuits.io/users/1283839


sender: user

message:
Writing your own Arduino flashing tool

I want to make Arduino flashing tool only for a `nano`, a simple flashing application which could run on windows taking input as a `.hex` file.

I know how to do this in Linux environment using `Makefiles` and writing script to automate it but have no idea what all are the things which I need to know and consider before I proceed with any windows application for such cases (implementing light GUI).

Any initial guide or read through would be a great help!

sender: assistant

body:
This application already exists. It's called `AVRDUDE`:

http://www.nongnu.org/avrdude/

You can download it compiled for Windows at the link above. This is the very flashing tool that the Arduino IDE uses for the AVR boards such as Nano. You can get the AVRDUDE command the Arduino IDE uses to upload to the Nano by following these steps:

1. Start the Arduino IDE
2. File > Preferences > Show verbose output during: > upload (check) > OK
2. Tools > Arduino Nano
3. Sketch > Upload
4. After the process completes scroll the black console window at the bottom of the Arduino IDE window up to the start of the upload output and you will see the command generated by the Arduino IDE, which you can adapt to your needs.

If you want to use Makefiles you can get `make` compiled for Windows from this package:

http://winavr.sourceforge.net/

Note that it's incorrect to call what you're trying to do an IDE. IDE stands for Integrated Development Environment, which this is certainly not.


message:
Why we can wake Arduino Uno from sleep using only pin 2?

Can we use other pin as an interrupt to wake Arduino Uno from sleep ?

body:
I think you also can use pin 3 (INT1), see [link][1]

There are two interrupts:

- INT0, pin 2
- INT1, pin 3

According to the link (among other techniques), an external interrupt can be used, so both INT0 and INT1 should be valid.

  [1]: http://www.engblaze.com/hush-little-microprocessor-avr-and-arduino-sleep-mode-basics/


body:
It's not just Pin 2 that can wake from sleep. Depending on which sleep mode you are in different interrupts (both internal and external) can wake the chip up.

The datasheet contains this helpful table:

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

The external interrupts (pins 2 and 3 on the Uno, and only "Level" trigger mode), pin change interrupts, I2C address matching, and the watchdog are the only interrupts that can wake the chip from *any* sleep mode. Other interrupts only work in certain sleep modes since they require parts of the chip to still be running in order for the interrupt to fire.

So that means that yes you can use any pin you like (using the "Pin Change" Interrupts) to wake the chip.

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


message:
Two PIR sensors not working properly, help needed

I a just beginning with Arduino, I need some hellp here!!
I have added two PIR sensors to this circuit with an LCD.
Both PIR sensors are working fine and LCD is showing the correct PIR - only if a single PIR is active.
Problem-1. If the PIR1 and PIR2 gets active at the same time, and PIR1 goes off - it will still work as both PIRs are on, both LED will be on and buzzer will sound!!
In short when both sensors are active, Arduino cant sense which one went off later!!

Problem-2. second issue is the LCD is not displaying some text correctly.

If possible, it will be great if the system can display PIR1 status on line 1 and PIR2 status on line 2.

Can anyone help please to  fix the two problems and add the extra feature ?

Here is a [Link][1] of virtual circuit to see the sketch and connections.

Here is the code

    #include <LiquidCrystal.h>

    int ledPin = 13;                // choose the pin for the LED
    int ledPinB = 12;               // choose the pin for the LED 2
    int inputPin = 6;               // choose the input pin (for PIR sensor)
    int inputPinB = 7;              // choose the input pin (for PIR sensor 2)
    int pirState = LOW;             // we start, assuming no motion detected
    int pirStateB = LOW;            // we start, assuming no motion detected PIR2
    int val1 = 0;                  // variable for reading the pin status
    int val2 = 0;                  // variable for reading the pin status
    int pinSpeaker = 10;           // Set up a speaker on a PWM pin (digital 9, 10, or 11)

    LiquidCrystal lcd(9, 8, 5, 4, 3, 2);

    void setup() {
      pinMode(ledPin, OUTPUT);      // declare LED as output
      pinMode(ledPinB, OUTPUT);      // declare LED as output
      pinMode(inputPin, INPUT);     // declare sensor as input
      pinMode(inputPinB, INPUT);     // declare sensor as input
      pinMode(pinSpeaker, OUTPUT);
      Serial.begin(9600);

      lcd.setCursor(0, 0);           // Set LCD cursor position (column, row)
      lcd.print("Security");         // Print text to LCD
      lcd.setCursor(0, 1);           // Set LCD cursor position (column,row)
      lcd.print("System");           // Print text to LCD
      delay(1000);                   // wait 1s  Delay to read text
      lcd.clear();                   // clear LCD display
      lcd.setCursor(0, 0);           // Set LCD cursor position (column, row)
      lcd.print("System Booting");
      delay(1000);                   // Delay to read text
      lcd.clear();                   // Clear LCD
      lcd.setCursor(0, 0);
      lcd.print("Processing...");
      delay(1000);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Waiting For");
      lcd.setCursor(0, 1);
      lcd.print("Motion");
    }

    void loop(){
      val1 = digitalRead(inputPin);  // read input value
      val2 = digitalRead(inputPinB);  // read input value
      if (val1 == HIGH) {            // check if the input is HIGH
        digitalWrite(ledPin, HIGH);  // turn LED ON
        playTone(300, 160);
        delay(150);

        if (pirState == LOW) {
          // just turned on
          Serial.println("Motion detected!");
          lcd.clear() ;
          lcd.setCursor(0, 0);   // Set LCD cursor position (column 0, row 0)
          lcd.print("PIR 1 Active!!");
          // only want to print on the output change, not state
          pirState = HIGH;
        }
      }
      else if (val2 == HIGH) {            // check if the input is HIGH
        digitalWrite(ledPinB, HIGH);  // turn LED ON
        playTone(300, 160);
        delay(150);

        if (pirStateB == LOW) {
          // just turned on
          Serial.println("Motion detected!");
          lcd.clear() ;
          lcd.setCursor(0, 1);      // Set LCD cursor position (column 0, row 0)
          lcd.print("PIR 2 Active!!");
          // only want to print on the output change, not state
          pirStateB = HIGH;
        }
      }

      else {
          digitalWrite(ledPin, LOW); // turn LED OFF
          digitalWrite(ledPinB, LOW); // turn LED OFF
          playTone(0, 0);
          delay(300);
          if (pirState == HIGH){
          // just turned off
          Serial.println("Motion ended!");
          lcd.clear() ;
          lcd.setCursor(3, 0);
          lcd.print("Waiting For");
          lcd.setCursor(3, 1);
          lcd.print("Motion.");      // only want to print on the output change, not state
          // only want to print on the output change, not state
          pirState = LOW;
        }
      }
    }
    // duration in mSecs, frequency in hertz
    void playTone(long duration, int freq) {
        duration *= 1000;
        int period = (1.0 / freq) * 1000000;
        long elapsed_time = 0;
        while (elapsed_time < duration) {
            digitalWrite(pinSpeaker,HIGH);
            delayMicroseconds(period / 2);
            digitalWrite(pinSpeaker, LOW);
            delayMicroseconds(period / 2);
            elapsed_time += (period);
        }
    }

  [1]: https://circuits.io/users/1283839

body:
Your problem is with the entire structure of your program. Pretty much everything is dependent on something else not having happened. Instead you need to make things more independent.

You should separate out your PIR sensor code into discrete chunks. One sensor isn't dependent on the other one having triggered or not, so there is no call to "link" them with an "else if". Also naming variables better will help understand the flow of code easier.

    uint8_t savedStatePIR1 = LOW;
    uint8_t savedStatePIR2 = LOW;

    bool motionDetectedPIR1 = false;
    bool motionDetectedPIR2 = false;

    void loop() {
        uint8_t currentStatePIR1 = digitalRead(inputPinPIR1);
        uint8_t currentStatePIR2 = digitalRead(inputPinPIR2);
        bool haveChanged = false;

        if (currentStatePIR1 != savedStatePIR1) {
            savedStatePIR1 = currentStatePIR1);
            haveChaged = true;
            if (currentStatePIR1 == HIGH) { // Activated
                motionDetectedPIR1 = true;
            } else { // Deactivated
                motionDetectedPIR1 = false;
            }
        }

        // Exact duplicate with PIR1 changed to PIR2
        if (currentStatePIR2 != savedStatePIR2) {
            savedStatePIR2 = currentStatePIR2);
            haveChanged = true;
            if (currentStatePIR2 == HIGH) { // Activated
                motionDetectedPIR2 = true;
            } else { // Deactivated
                motionDetectedPIR2 = false;
            }
        }

        // Now, if either state changed this iteration through loop()
        // update the LEDs and the display, and play a tone if you
        // need to. Note that there is already a tone() function so
        // you really don't need to write your own.
        if (haveChanged) { // Something changed, so update things.
                digitalWrite(ledPin, motionDetectedPIR1);
                digitalWrite(ledPinB, motionDetectedPIR2);
                lcd.clear();

                if (motionDetectedPIR1 || motionDetectedPIR2) {
                    tone(pinSpeaker, 300, 160);
                    if (motionDetectedPIR1) {
                        lcd.setCursor(0, 0);
                        lcd.print("PIR 1 Active!!");
                    }
                    if (motionDetectedPIR2) {
                        lcd.setCursor(0, 1);
                        lcd.print("PIR 2 Active!!");
                    }
                } else {
                    lcd.setCursor(3, 0);
                    lcd.print("Waiting For");
                    lcd.setCursor(3, 1);
                    lcd.print("Motion.");
                }
            }
        }
    }

Note: this code isn't tested at all (it'll be full of errors). The basic principle, though, is:

1. First look for motion in PIR 1 and record if there is or not.
2. Repeat for the second PIR.
3. If there has been any change in state then (and only then) update the outputs.


body:
Thanks for the reply @Majenko, But as I said in the question, I am just a beginner. I couldn't figure out how to use it. I did change the pin number, but I dont know what is "haveChanged". So I did changed the code I already have and it seems to be working virtually. But it does take time to respond sometimes, may be in real world conditions, it will be better ?
Here is the link to virtual demo, please check and tell me if it is going to work.[https://circuits.io/circuits/5142920-two-pir-project-1-0][1]

Did spend some time, and made this code.

    #include <LiquidCrystal.h>
    //the time we give the sensor to calibrate (10-60 secs according to the datasheet)
    int calibrationTime = 5;

    int NpirPin = 2;    //the digital pin connected to the PIR sensor's output
    int SpirPin = 3;
    int NledPin = 13;
    int SledPin = 12;
    int buzzerPin = 10;

    LiquidCrystal lcd(9, 8, 7, 6, 5, 4);                          // initialize the library with the numbers of the interface pins

    //SETUP
    void setup(){
      Serial.begin(9600);
      pinMode(NpirPin, INPUT);
      pinMode(SpirPin, INPUT);
      pinMode(NledPin, OUTPUT);
      pinMode(SledPin, OUTPUT);
      pinMode(buzzerPin, OUTPUT);
      digitalWrite(NpirPin, LOW);
      digitalWrite(SpirPin, LOW);
      digitalWrite(buzzerPin, LOW);
      lcd.begin(16, 2);
      lcd.setCursor(3, 0);
      lcd.print("Waiting For");
      lcd.setCursor(3, 1);
      lcd.print("Motion....");

      //give the sensor some time to calibrate
      Serial.print("calibrating sensors ");
        for(int i = 0; i < calibrationTime; i++){
          Serial.print(".");
          delay(500);
          }
        Serial.println(" done");
        Serial.println("SENSORS ACTIVE");
        delay(50);
      }
     ////////////////////////////
    //LOOP
    void loop(){

         if(digitalRead(NpirPin) == HIGH){
           digitalWrite(NledPin, HIGH);   //the led visualizes the sensors output pin state
           playTone(300, 300);
           delay(150);
             Serial.println("---");
             Serial.print("motion at NORTH");
            lcd.clear() ;
          lcd.setCursor(0, 0);                                           // Set LCD cursor position (column 0, row 0)
          lcd.print("PIR1 Active!");
             delay(500);
           }

         else if(digitalRead(NpirPin) == LOW){
           delay (300);
           digitalWrite(NledPin, LOW);
           digitalWrite(buzzerPin,LOW);}

         if(digitalRead(SpirPin) == HIGH){
           digitalWrite(SledPin, HIGH);   //the led visualizes the sensors output pin state
           playTone(300, 300);
           delay(150);
             Serial.println("---");
             Serial.print("motion at SOUTH");
            lcd.clear() ;
          lcd.setCursor(0, 0);                                           // Set LCD cursor position (column 0, row 0)
          lcd.print("PIR2 Active!");
             delay(150);
           }

         else if(digitalRead(SpirPin) == LOW){
           delay (300);
           digitalWrite(SledPin, LOW);
           digitalWrite(buzzerPin,LOW);}

    }

    // duration in mSecs, frequency in hertz
    void playTone(long duration, int freq) {
        duration *= 1000;
        int period = (1.0 / freq) * 1000000;
        long elapsed_time = 0;
        while (elapsed_time < duration) {
            digitalWrite(buzzerPin,HIGH);
            delayMicroseconds(period / 2);
            digitalWrite(buzzerPin, LOW);
            delayMicroseconds(period / 2);
            elapsed_time += (period);
        }
    }

  [1]: https://circuits.io/circuits/5142920-two-pir-project-1-0


message:
My Arduino Uno buzzer isn't working

/*

    */

    void setup() // Built in initialization block
    {
        Serial.begin(9600);
        Serial.println("Beep!");
    }

    void loop() // Main loop auto-repeats

    {

    //   Serial.println("Beep!");

       tone(4, 3000, 1000); // Play tone for 1 second

       delay(1000); // Delay to finish tone
    }

body:
First, take a look at the two links provided in the comments to your question and explain why your question is different from them.  Start by describing your "buzzer."  If your question is not significantly different then it will attract downvotes instead of answers, or it may be marked as duplicate or just simply closed.

Here is one solution, making the assumption you are writing about a piezo beeper:

    void setup() {
      pinMode(4,OUTPUT);
    }
    void loop() {
      digitalWrite(4,HIGH);
      delay(1000);
      digitalWrite(4,LOW);
      delay(1000);
    }

Alternatively, take the first example program from your IDE, called blink, and hook your beeper to pin 13 (positive) and GND (negative) while that runs.  It does basically the same thing.


message:
The LCD doesn't display the words typed

I've tried this code on an LCD, and instead of displaying "Hello World!" it displays what is shown on the picture.

Code:

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup() {
      lcd.begin(16, 2);
    }

    void loop() {
      lcd.print("Hello World!");
      delay(500);
      lcd.clear();
      delay(500);
    }

[![Photo of LCD displaying corrupted text][1]][1]

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

body:
Try the following

 1. Double-check the LCD soldering
 2. Double-check your wiring

 1. Ensure that the pins you are using for your LCD are not assigned to some other function. This caused jumbled, random characters [here][1].

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


body:
From the attached I can see that you are connecting D7 to digital 2 of arduino. And I assume the pins D6 D5 D4 are also connected to 3, 4, 5 pins respectively, which is correct for your code.
But make sure the R/W pin is connected to proper ground. Verify that by measuring voltage if possible.
Also serial print whatever you are giving the lcd  to make sure it is not an encoding issue.


body:
Don't take this the wrong way but some of those solder joints looks a little rough. I'm not sure this is your issue but you need some soldering practice. Solder joints should be bright and shiny and should completely cover the pad.

I can tell by the joint on pin 16 you didn't get it hot enough or the solder would have flowed to cover the entire pad. Some of the other joints look like they were overheated. Does your soldering iron have a temperature control? Experience will help you know when to turn it up and when you can get by with a lower temperature. Is your tip too large or needs replacing?

There's lot's of soldering how-to videos out there but no substitute for practice, practice, practice and then practice some more. :)


message:
How to use AtMega328P-PN

I am making an AC (the summer kind) control circuit with an AtMega328P chip. I bought the AtMega328P-PN instead of the P-PU. I followed the instructions on how to burn the bootloader, but nothing seems to work on the P-PN. I searched on Google for it and could find nothing anywhere.

Thanks in advance,

Iain

body:
The ATmega328P-PN differs from the ATmega328P-PU essentially only in being rated over a wider temperature range.

It is for all ordinary purposes a direct substitute for where an ATmega328P-PU could be used, and has the same signature word.

Whatever your actual problem is, it is elsewhere.

(The chips that *do* require some special accommodation if ordered are the ATmega328 *without* a "P" before the dash and the ATmega328PB)


message:
How does one set attributes for SD files?

How does one set file attributes, e.g., creation date, for a file being created on an SD?

body:
The [Arduino SD library][1], is based on [Github: greiman/SdFat][2], by William Greiman.

From [SD Created File Attributes][3]:

> The basic SD.h library doesn't set the attributes. You notice everything has the same creation date? The library doesn't have any way of knowing what the date is.

However, you need to use a callback function. The following information is from [file creation date and time in sd card ?][4]:

> Install the SdFat library - there is an example called [Timestamp.ino][5] describing in detail how to do it...
>
>     // after your rtc is set up and working you code just needs:
>
>     void dateTime(uint16_t* date, uint16_t* time) {
>       DateTime now = rtc.now();
>
>       // return date using FAT_DATE macro to format fields
>       *date = FAT_DATE(now.year(), now.month(), now.day());
>
>       // return time using FAT_TIME macro to format fields
>       *time = FAT_TIME(now.hour(), now.minute(), now.second());
>     }
>
>     //put that outside of any functions, before your 'setup'
>
>     //Then inside your 'loop' or 'setup'
>
>     void loop(void)
>     {
>
>       //Other code that does stuff
>
>       //put this next line *Right Before* any file open line:
>       SdFile::dateTimeCallback(dateTime);
>       dataFile = SD.open(datafilename, FILE_WRITE);
>
>       //other code that does stuff
>
>     }

There is another way of achieving this, in a sketch without having to convert to SDFat:

> @donald0000 wants the Date Modified field to show an actual time stamp
> when you look at the files present on the card using Windows Explorer.
> As Billy Ho says, the callback function is the way to do it. You can
> indeed use this function with `SD.h`  if you don't want to convert to
> SDFat. Here is an example of the function in a sketch. Notice the
> timing of when the date modified time stamp is written, it is when
> `file.close()` writes the actual data to the card.
>
>     #include <SPI.h>
>     #include <SD.h>
>     #include <Wire.h>
>     #include <RTClib.h>
>
>     File file;  // test file
>     const uint8_t SD_CS = 10; // SD chip select
>     RTC_DS1307 RTC;  // define the Real Time Clock object
>
>      char timestamp[30];
>
>     //------------------------------------------------------------------------------
>     // call back for file timestamps
>     void dateTime(uint16_t* date, uint16_t* time) {
>      DateTime now = RTC.now();
>      sprintf(timestamp, "d:d:d -/-/- \n", now.hour(),now.minute(),now.second(),now.month(),now.day(),now.year()-2000);
>      Serial.println("yy");
>      Serial.println(timestamp);
>      // return date using FAT_DATE macro to format fields
>      *date = FAT_DATE(now.year(), now.month(), now.day());
>
>      // return time using FAT_TIME macro to format fields
>      *time = FAT_TIME(now.hour(), now.minute(), now.second());
>     }
>     //------------------------------------------------------------------------------
>     void setup() {
>
>      Serial.begin(9600);
>      Wire.begin();
>      if (!RTC.begin()) {
>        Serial.println("RTC failed");
>        while(1);
>      };
>      // set date time callback function
>      SdFile::dateTimeCallback(dateTime);
>
>       DateTime now = RTC.now();
>       sprintf(timestamp, "d:d:d -/-/- \n", now.hour(),now.minute(),now.second(),now.month(),now.day(),now.year()-2000);
>       Serial.println("xx");
>       Serial.println(timestamp);
>
>
>      if (!SD.begin(SD_CS)) {
>        Serial.println("SD.begin failed");
>        while(1);
>      }
>      file = SD.open("TEST_SD.TXT", FILE_WRITE);
>      file.println("Testing 1,2,3...");
>
>      delay(5000);
>      file.close();
>      Serial.println("Done");
>     }
>     //------------------------------------------------------------------------------
>     void loop() {}

  [1]: https://www.arduino.cc/en/Reference/SD
  [2]: https://github.com/greiman/SdFat
  [3]: https://forum.arduino.cc/index.php?topic=473869.0
  [4]: https://forum.arduino.cc/index.php?topic=348562.0
  [5]: https://github.com/greiman/SdFat/blob/master/examples/Timestamp/Timestamp.ino


body:
Quite simply `FAT16` only supports 1 date, normally Modified Date. `FAT32` has (limited) support for 3 dates (but AFAIK there is no Arduino library which supports `FAT32`).

Even then not all OS even support Creation Date. Windows has 2 different interpretations depending on application, Linux natively only supports Change Date, although extensions provide support for more dates.


message:
Purpose of capacitors in this project

I'm currently working on a project where I am making a wheeled robot using the Hack-e-bot library on the arduino. The circuit board which I have planned to put together through soldering will eventually look similar to this:
[![enter image description here][1]][1]

Here is a schematic:[![enter image description here][2]][2]

I understand my circuit quite well but my mentor recommended using a capacitor for this and although I have got it on my schematic, I've never actually worked with capacitors before. Why should they be used in this project?

  [1]: https://i.stack.imgur.com/JVYEz.jpg
  [2]: https://i.stack.imgur.com/0Fi2Y.jpg

body:
Based on the schematic shown, the capacitor acts as a decoupling or smoothing capacitor. When the circuit components such as a motor require a sudden source or produce a sudden spike of energy, this would help filter out the noise and balance the power line.

More info regarding decoupling capacitor may be found on wikipedia [here][1].

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


body:
A [capacitor][1] is a device that can store (and release) charge. It is made up of 2 metallic electrodes (or plates) that are separated by a thin dielectric material.

> When you apply a voltage over the two plates, an electric field is created. Positive charge will collect on one plate and negative charge on the other. - build-electronic-circuits.com

In short, a capacitor lets the AC component through and blocks the DC component.

---

Capacitors can be used in the following ways:

Decoupling Capacitors

**(Also called Bypass capacitors)**

> A decoupling capacitor’s job is to supress high-frequency noise in power supply signals. They take tiny voltage ripples, which could otherwise be harmful to delicate ICs, out of the voltage supply.

[![Noisy motor][2]][2]

Image reference http://www.seattlerobotics.org/encoder/jun97/basics.html

>In a way, decoupling capacitors act as a very small, local power supply for ICs (almost like an uninterupptable power supply is to computers). If the power supply very temporarily drops its voltage (which is actually pretty common, especially when the circuit it’s powering is constantly switching its load requirements), a decoupling capacitor can briefly supply power at the correct voltage. This is why these capacitors are also called bypass caps; they can temporarily act as a power source, bypassing the power supply.

>Decoupling capacitors connect between the power source (5V, 3.3V, etc.) and ground. It’s not uncommon to use two or more different-valued, even different types of capacitors to bypass the power supply, because some capacitor values will be better than others at filtering out certain frequencies of noise.
- sparkfun.com

Power Supply Filtering

DC power supplies can be quite noisy on their own. Take the output of a [bridge rectifier][3] for example, there is a lot of ripple on the output. Capacitors are a perfect solution for reducing the ripple/noise of power supplies.

![bridge rectifier smoothing capacitor][4]

Image Reference: http://www.electronics-tutorials.ws/diode/diode_6.html

> Capacitors are stubborn components, they’ll always try to resist sudden changes in voltage. The filter capacitor will charge up as the rectified voltage increases. When the rectified voltage coming into the cap starts its rapid decline, the capacitor will access its bank of stored energy, and it’ll discharge very slowly, supplying energy to the load. The capacitor shouldn’t fully discharge before the input rectified signal starts to increase again, recharging the cap. This dance plays out many times a second, over-and-over as long as the power supply is in use.

Also see [Keelan's answer over at electronics stack exchange][5].

Signal Filtering

> You can also combine capacitors and resistors to form filters that target specific frequencies. - build-electronic-circuits.com

> They can block out low-frequency or DC signal-components while allowing higher frequencies to pass right through. They’re like a bouncer at a very exclusive club for high frequencies only. - sparkfun.com

> For example in an audio system you can target the high frequencies to remove them (e.g. in a sub-woofer). This is called a low-pass filter.  - build-electronic-circuits.com

[![Low pass filter][6]][6]

Image Reference: [Wikipedia][7]

------

Back to your application.

Motors are notoriously noisy. Your mentor has recommended a capacitor to decouple the noise of the motors and protect the IC from voltage drops/spikes.

Side note: D1 in your schematic is a power indication LED. It needs a current limiting resistor in series with the LED to limit the current and prevent the LED from burning out.

-----

Resources:

 - [https://learn.sparkfun.com/tutorials/capacitors][8]
 - [https://www.build-electronic-circuits.com/how-does-a-capacitor-work/][9]
 - [Basic Circuits - Bypass Capacitors][10]
 - [wikipedia.org/wiki/Capacitor][1]
 - [wikipedia.org/wiki/Decoupling_capacitor][11]
 - [Youtube - How a Capacitor Works - by Dr. Oliver Winn][12]
 - [explainthatstuff.com/capacitors][13]

  [1]: https://en.wikipedia.org/wiki/Capacitor
  [2]: https://i.stack.imgur.com/hGhUL.gif
  [3]: https://en.wikipedia.org/wiki/Diode_bridge
  [4]: https://i.stack.imgur.com/BLGnf.gif
  [5]: https://electronics.stackexchange.com/a/73870/104097
  [6]: https://i.stack.imgur.com/agNqX.png
  [7]: https://commons.wikimedia.org/wiki/File:1st_Order_Lowpass_Filter_RC.svg
  [8]: https://learn.sparkfun.com/tutorials/capacitors
  [9]: https://www.build-electronic-circuits.com/how-does-a-capacitor-work/
  [10]: http://www.seattlerobotics.org/encoder/jun97/basics.html
  [11]: https://en.wikipedia.org/wiki/Decoupling_capacitor
  [12]: https://www.youtube.com/watch?v=t9Qwx75eg8w
  [13]: http://www.explainthatstuff.com/capacitors.html


message:
How does Arduino IDE 'Get Board Info'?

I want my C# application to automatically select the correct COM port by way of a string equality check against a 'GetInfo'-type request to the Arduino board.

I know the Arduino IDE can get info from the board;

`Tools > GetBoardInfo`

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

But I don't know how to get it using a sketch or if it is even possible for that matter.

Is this something that can be read from the board, or is it a USB-thing. If it's a USB thing, I'd have to get the info from `GetUSBDevices.DeviceID` or whatever, then get the serial port used by the USB Device, which would probably work, but I'd rather do it all via a `serialPort`.

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

body:
Looking at the source code of the Arduino IDE on github, it looks like they call an executable (listComPorts.exe). So I would guess you can't get that info through serial.

Here's a C# app using WMI that can get port, vid, and pid:

    namespace PortTest
    {
        class Program
        {
            // Helper function to handle regex search
            static string regex(string pattern, string text)
            {
                Regex re = new Regex(pattern);
                Match m = re.Match(text);
                if (m.Success)
                {
                    return m.Value;
                }
                else
                {
                    return null;
                }
            }

            static void Main(string[] args)
            {
                // Use WMI to get info
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
                    "SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"");

                // Search all serial ports
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    // Parse the data
                    if (null != queryObj["Name"])
                    {
                        Console.WriteLine("Port = " + regex(@"(\(COM\d+\))", queryObj["Name"].ToString()));
                    }
                    //PNPDeviceID = USB\VID_1A86&PID_7523\5&1A63D808&0&2
                    if (null != queryObj["PNPDeviceID"])
                    {
                        Console.WriteLine("VID = " + regex("VID_([0-9a-fA-F]+)", queryObj["PNPDeviceID"].ToString()));
                        Console.WriteLine("PID = " + regex("PID_([0-9a-fA-F]+)", queryObj["PNPDeviceID"].ToString()));
                    }
                }
                Console.WriteLine("Done");
                int c = Console.Read();
            }
        }
    }

From there, it looks like it searches an online database for more info. See: [`getBoardWithMatchingVidPidFromCloud()`][1] function.

  [1]: https://github.com/arduino/Arduino/blob/master/arduino-core/src/processing/app/Platform.java


body:
Please look here [https://todbot.com/blog/2012/03/02/listcomports-windows-command-line-tool-for-usb-to-serial/][1]
The article is right about what you are seeking.
Thanks to @Johnny Mopp, searching "listComPorts" keyword helped me.

Quote from that article:

> **How it works**
>
> The C and the VBS versions both utilize the WMI
> infrastructure that’s been around since Windows 2000 to query the
> machine about its configured PnP devices. The WMI is a huge data
> structure of just about any information in Windows. Except, it seems,
> good information about COM ports. While there is a “Win32_SerialPort”
> table in WMI, that only contains information about hardware serial
> ports, not USB-to-serial adapters. Instead, these two tools look at
> the “Win32_PnPEntity” table. While this table does list USB-to-serial
> adapters, it does not contain a proper mapping of the adapter’s USB or
> PnP ID to COM port. Instead, these tools do a string search on the
> “Caption” field for the string “(COMn)” where “n” is a number. It’s an
> incredible hack but seems to work.

  [1]: https://todbot.com/blog/2012/03/02/listcomports-windows-command-line-tool-for-usb-to-serial/


message:
Getting the "Device has problem: 0x0a: CM_PROB_FAILED_START." error code 10 while installing device driver for Arduino Uno

After uninstalling and reinstalling Arduino IDE, my Arduino Uno is not recognized by my PC. When I connect it to my PC all lights are glowing in my board but my PC is not showing anything connected to USB.

When I tried to install drivers manually I'm getting the error device cannot start code 10. I have used the default drivers for Arduino, which I downloaded with the IDE. I tried installing them manually. I don't have any idea about chipset interface whether it is CH or FTDI. I have looked at all the possible solutions but my problem wasn't solved.

[![drivers image][1]][1]

[![error][2]][2]

  [1]: https://i.stack.imgur.com/XFs0b.png
  [2]: https://i.stack.imgur.com/2Gyjk.png

body:
Error code 10 mean Bad Environment.  I would guess that you are using the wrong driver, probably 64 bit on a 32 bit OS, etc.

This does not look like a Arduino fault, it looks like a windows Driver fault, so unlplug the board, reboot the PC logon as admin and download the latest drivers for you device and see if that fixes it.  You might be able to get better help on a Windows admin forum I think.


message:
Need help with calculator logic

I am trying to build a calculator with an Arduino, an LCD display, and a keypad. Getting inputs from the keypad is not the issue. Before I can add, subtract, multiply, or divide any two numbers, I want to make sure the calculator registered the given number. I am trying to program it (so far) so that I type in a number and press enter (the @ sign I assigned to my keypad) and the LCD prints out that number. As you will see, I attempted to devise a logic mechanism for the Arduino to recognize the typed number.

I thought since as you type more numbers the value of the first number typed increases by 10 fold each time (if you start by pressing 4 then if you press another number such as 5 following it, that 4 will become 40, and 400 if another number is pressed, etc...) I could multiply that number (and every following number) by 10, 100, 100, etc...

But it doesn't work and I need help so that the number can be collected by the Arduino.

Here's my attempt at it:

        #include <LiquidCrystal.h>
        #include "Arduino.h"
        #include "Keypad.h"

        int count = 0;
        int row = 0;
        int column = 0;

        //const int buzzer = 0;

        int value1;
        int value2 = 0;

        int spot1 = 0;
        int spot2 = 0;
        int spot3 = 0;
        int spot4 = 0;
        int spot5 = 0;
        int spot6 = 0;
        int spot7 = 0;
        int spot8 = 0;

        LiquidCrystal lcd(1, 2, 3, 4, 5, 6 );

        const byte ROWS = 4; //four rows
        const byte COLS = 3; //three columns
        char keys[ROWS][COLS] = {
          {'1','2','3'},
          {'4','5','6'},
          {'7','8','9'},
          {'%','0','@'}
        };
        byte rowPins[ROWS] = {10, 9, 8, 7}; //connect to the row pinouts of the
        keypad
        byte colPins[COLS] = {13, 12, 11}; //connect to the column pinouts of
        the keypad
        Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS
        );

        void setup() {
          //pinMode(buzzer, OUTPUT);
          lcd.begin(16,2);
          lcd.print("---Calculator---");
          delay(2000);
          lcd.clear();
          lcd.print("Value1: ");
          lcd.blink();

        }

        void loop() {
    char key = keypad.getKey();

    if(key != NO_KEY){
      lcd.print(key);
      if(key != '%' && key != '@'){
        count++;
      }
      else if(count == 1){
        spot1 = key;
      }
      else if(count == 2){
        spot2 = key;
      }
      else if(count == 3){
        spot3 = key;
      }
      else if(count == 4){
        spot4 = key;
      }
      else if(count == 5){
        spot5=key;
      }
      else if(count == 6){
        spot6=key;
      }
      else if(count == 7){
        spot7=key;
      }
      else if(count == 8){
        spot8=key;
      }

      if(key=='@'){
        if(count == 1){
          value1 = spot1;
        }
        else if(count == 2){
          value1 = (spot1*10)+(spot2);
        }
        else if(count == 3){
          value1 = (spot1*100)+(spot2*10)+spot3;
        }
        if(count == 4){
          value1 = (spot1*1000)+(spot2*100)+(spot3*10)+spot4;
        }
        if(count == 5){
          value1 = (spot1*10000)+(spot2*1000)+(spot3*100)+(spot4*10)+spot5;
        }
        if(count == 6){
          value1 = (spot1*100000)+(spot2*10000)+(spot3*1000)+(spot4*100)+(spot5*10)+spot6;
        }
        if(count == 7){
        }
        if(count == 8){
        }
        lcd.print(value1);
      }

      if(key  == '%'){
        count = 0;
        lcd.clear();
        lcd.print("Value1: ");
        lcd.blink();
      }
    }

    }

PS: If you know any better way to accomplish this goal, I would love to hear it.

body:
    if(key != '%' && key != '@'){
      count++;
    }
    else if(count == 1){
      spot1 = key;
    }
    else if(count == 2){
      spot2 = key;
    }

You've got a problem here.  If key isn't '%' and isn't '@' then you increase count but since all the rest are else if to that then it skips over all of them and never actually puts the digit int the spot.


body:
If your keypad setup results in '%' and '@' arriving correctly, then it probably also results in the characters '0', '1', ... '9' arriving when number keys are pressed, rather than digit values 0, 1, ... 9 arriving.

Be that as it may, there's a far simpler approach to building `value1` which does not use a big set of spot values like your method does.  Here is an illustration of it.

    // ... Before number input, zero out a number-accumulator variable
    long int nin = 0;

    do {
      key = keypad.getKey();
      if (key != NO_KEY) {
        lcd.print(key);
        // As number keys are pressed, add them to tail of number
        if (key >= '0' && '9' >= key) {
          nin = 10*nin + (key & 0xF);   // Get low 4 bits of key
        }
      }
      if (key == '@') {
        lcd.print("Value = ");
        lcd.print(nin);
        // ... do whatever else with value
        // ... then get ready for next value
        nin = 0;
      }
    } while (1);


message:
Using the SD library with the ESP8266 DevKit

The situation is as follows, I've connected a SPI TFT screen to the ESP8266 DevKit, set my own MISO,MOSI, CD, SCK pins and it works fine, wanted to do the same for using the SD card reader, but then I realized that the SD library is using the pre-defined pins with no visible way override this.. There must be a way, no?

I did try editing the pins_xxx files:

    static const uint8_t SS   = 10;
    static const uint8_t MOSI = D7; //11;
    static const uint8_t MISO = D5; //12;
    static const uint8_t SCK  = D6; //13;

But it did not work, I'm not that well familiar about the build process..
So, is there a way to accomplish this? Maybe a different library?

P.S. I am using the Arduino IDE for the ESP.

body:
After some trial and error got both the screen and sd card reader working sharing the MISO and SCK lines.
I was using a display wit the Adafruit ST7735 driver (and their library), worked fine with both hardware and software, but the SD card reader (generic, not even a part number on it) was able to work only with hardware SPI as the standard SD library does not support software SPI for some reason.
The most important takeaway is this: **The SD library internally uses the predefined MOSI,MISO and SCK pins, but fot the ESP8266 dev kit they were mapped to pins labeled HMOSI, HMISO and HSCLK - D7, D6 and D5.** Now that I think about it, the H must stand for "Hardware", if only I had this epiphany sooner.


message:
Thought Dropbox was gone, but Arduino IDE kept it running. Search led to Temboo & Arduino Yun. Will it cripple my IDE to cut it out?

Just discovered that long after uninstalling Dropbox the service was still running.  I disabled it in the normal Services control panel.  It turned out to be hiding in /winndows/system32 as dbxsvc.exe

Then went a step further and did this in an Administrator CMD window:

    cd /windows/system32
    attrib -h -s dbxsv*.*
    del dbxsvc.exe
    copy con dbxsvc.exe
    Nyah^Z
    attrib +r dbxsvc.exe

So that should take care of that.

Upon further system searching (using [Everything][1]) discovered that Dropbox is used by software called Temboo, which is some kind of cloud-share package for coordinating Arduino Yun applications.

**It turned out that it was the Arduino IDE that kept it running.**

More searching led me here:

[Arduino & Temboo: How It Works][2]

Excerpt:

> ON YOUR YÚN Your Arduino Yún includes two lightweight software
> components that make it easy to connect with hundreds of APIs and
> cloud services from any sketch.
>
> First, there's a small C++ library called Temboo.cpp that comes
> bundled with the Arduino IDE. When you include this library in a
> sketch, it provides a streamlined syntax for configuring and invoking
> calls to run Temboo Choreos.
>
> Behind the scenes, calls to Temboo are routed to a client program that
> comes packaged with your Linino base image. This client is a Python
> program that formats the Choreo execution request and uses HTTPS to
> forward the request to Temboo via the cURL utility.
>
> THE TEMBOO PLATFORM Temboo is a scalable, fault-tolerant environment
> for running and managing smart code snippets that we call Choreos.
> Choreos can call APIs, simplify the OAuth process, send email
> messages, perform encoding, update databases, and lots more. You can
> even create your own custom Choreos. Temboo automatically generates
> the sketch code you needed to call these processes, making it simple
> to get up and running with any service from your Yún.
>
> The request from the Yún's temboo client causes the Choreo specified
> in your sketch code to be executed on the Temboo platform. In many
> cases, this means assembling your inputs into the format expected by a
> third-party API, performing the API interaction, handling errors, and
> dispatching filtered results back to the Yún via HTTPS. The results
> are made available to your Arduino sketch by way of Process’s Stream
> methods.

I only use the standard Arduino IDE and regular Arduino Unos and Nanos.  Sure some are Chinese-made, and some use the CH340 connection type.

I do not want my system reaching out through the firewall to any cloud-based services, nor do I appreciate that the Arduino IDE thwarted my earlier effort to disable and remove Dropbox.
-

**I get that it came bundled with the standard Arduino IDE.**

**So my question is whether anyone knows if it will damage anything if I remove this junkware?**

--ADDENDUM - Why to dump Dropbox:

[The Dropbox hack is real][3]

Excerpt:

> Motherboard reported on what had been rumoured for some time, namely
> that Dropbox had been hacked.
>
> Not just a little bit hacked and not in
> that "someone has cobbled together a list of credentials that work on
> Dropbox" hacked either, but proper hacked to the tune of 68 million
> records.
>
> Very shortly after, a supporter of Have I been pwned (HIBP)
> sent over the data which once unzipped, looked like this:
>
> (The Dropbox data across 4 text files)
>
> What we've got here is two files with email address and bcrypt hashes
> then another two with email addresses and SHA1 hashes. It's a
> relatively even distribution of the two which appears to represent a
> transition from the weaker SHA variant to bcrypt's adaptive workload
> approach at some point in time. Only half the accounts get the "good"
> algorithm but here's the rub: the bcrypt accounts include the salt
> whilst the SHA1 accounts don't. It's just as well because it would be
> a far more trivial exercise to crack the older algorithm but without
> the salts, it's near impossible.
>
> At first glance the data looks legit and indeed the Motherboard
> article above quotes a Dropbox employee as confirming it.

  [1]: https://www.voidtools.com/
  [2]: https://temboo.com/arduino/yun/yun-and-temboo
  [3]: https://www.troyhunt.com/the-dropbox-hack-is-real/

body:
There is **no** Dropbox software included with ANY version of the Arduino IDE, nor installed on any Linux based Arduino board.

That is **not** how Temboo and Dropbox work.

You have Temboo as a (source code) library which you can compile into your sketch, and as a user-agent that runs on the Linux portion of the Yùn. That then forwards a request to the Temboo web servers detailing what operations you want to perform on what services.

**It is then the Temboo web servers that connect to Dropbox (or whatever service you want to use) and perform operations on your behalf.**

If you have Dropbox software installed on your computer **it is not the fault of the Arduino IDE.**


message:
Arduino not detected

I took an Arduino from a friend yesterday but when I connect it to the laptop there is no light blinking from the Arduino and the laptop doesn't detect any device.

Is there a problem with the Arduino or is there a possibility that the USB has problems?

body:
Are you sure your laptop doesn't detect any device? It is possible that you need to install right driver for your arduino. The problem could be with:

 1. Cable: Try to replace it with a working cable
 2. Drivers Issue: You need to install driver for your `Arduino`. Generally, your laptop will issue warnings if it didn't find any appropriate driver for it.
 3. USB-To-UART Bridge: This is an IC in `arduino board`. It needs to be working for laptop to detect your board.
 4. Microcontroller: Since, you told us that your board is blinking, then `microcontroller` will be working for sure.

Can you see any part getting hotter? Have you tried with other laptop and cable?


body:
Adding on to abhiarora's answer, if there are no lights at all on the Arduino, and you verify your cable is outputting power, then you may have shorted the device and need to replace the USB port diode.  On my Arduino Nano, this diode is directly under the USB-mini port, on the bottom of the board.

Picture of diode:
[![USB diode (original)][1]][1]

I replaced this on my Arduino Nano with the [CDBW0520L-HF][2] from Comchip Technology and the Arduino worked perfectly. (Link provided is from [www.arrow.com][3]).

And in case you have a Chinese Arduino Nano like me:
[![USB diode (Chinese)][4]][4]

  [1]: https://i.stack.imgur.com/Z26t6.jpg
  [2]: https://www.arrow.com/en/products/cdbw0520l-hf/comchip-technology
  [3]: https://www.arrow.com/
  [4]: https://i.stack.imgur.com/eo2u3.jpg


body:
When you say Arduino, which product specifically are you referring to ? the Arduino UNO ?

Assuming it is the Arduino UNO (or Nano) you will need to first check if it is a genuine Arduino product or a clone (not that there is anything wrong with using a clone). Check your board for a CHIP near the USB port. See if it reads FTDI or CH340. If it reads CH340, then you have a clone. Not to worry, you can still use it as any normal Arduino, you will just need to install the appropriate drivers for the CH340 chip. A simple search for "CH340 driver" can fetch you the right results for your operating system.
[![enter image description here][2]][2]
[![enter image description here][3]][3]

  [1]: http://www.arduined.eu/ch340-windows-8-driver-download/
  [2]: https://i.stack.imgur.com/C5blf.jpg
  [3]: https://i.stack.imgur.com/6GSW0.jpg


message:
Write char array containing new line to SD card

How do I a buffer (char array) containing new line character to SD card using SdFat?

I tried:

    File myFile = SD.open("test.txt", FILE_WRITE)
    myFile.write(buffer, BUFLEN)

but I get this instead:

    0000 0000 0000 0000 0000 0000 0000 3337
    3837 3838 3937 3035 2c20 2020 2031 2c20
    2020 3531 0a33 3738 3738 3839 3730 352c
    2020 2020 322c 2020 2035 310a 0000 0000
    0000 0000 0000 0000 0000 0000 0000 0000

If I use the normal method, then it seems that SdFat stop printing at the newline character:

myFile.print(buffer);

Note: the buffer containing data samples in fixed width csv format

    3787889751,    1,   49
    3787889752,   10,   49
    3787889753,    1,   49

body:
`File.print()` stops printing at a NULL character (ASCII 0) not a new line.  You can stick as many new lines as you like in a string and it will print.  Try this example

    void loop ()
    {
      Serial.print ("Hello\nMultiline\nPrint\n");
      Serial.print ("Hello\0Multiline\0Print\n");
    }

`File.write()` writes binary data to a file, it will write BUFLEN bytes, even if you don't give it that many bytes.

Looking at the output from you hex editor your string ends with ... 2020 2035 310a which would be 3 spaces (20), 51 (35 and 31) and a new line (0A).  There is also a null (00) after that, but I can't tell how many because you have 0s to pad the output (or fill the file).

If you look further back in the output (3rd col, 3rd row) you can see another newline (0a33) so that proves its not new lines that is stopping your output.

Without your code we can't say whats wrong, but I agree with Mark that its not what you think it is.

To write data to a CSV file I would write each row of data into a struct and then hold those structs within a list.  Then have a function that iterated through the list and printed each record to the file.  That way you wouldn't need a buffer.  If it didn't have to be a CSV then you could just call

    myFile.write (currentRecord. sizeof(StructRecord));


message:
Speed of reading I2C

How long does it take to read I2C?

I'm reading data from I2C sensor through a 20Hz timer interrupt. The interrupt handler only set the readSensorFlag, and I double checked that it happens at 20Hz through putting a Serial print there.

    void TIMER2_Interrupt(void) {
      if (NRF_TIMER2->EVENTS_COMPARE[0] != 0) {
            readSensorFlag = true;
            NRF_TIMER2->EVENTS_COMPARE[0] = 0;
          }
        }
Now in the main loop I perform the reading of sensors.

    void loop() {
      // Reading data from sensors to a buffer
      if (readSensorFlag) {
        readSensorFlag = false;

        if (bufferCounter < BUFLEN - 2*SAMPLESIZEINCHAR - 1) {
          epoch = millis();
          proximity = vcnl.readProximity();
          ambientLight = vcnl.readAmbient();

The strange this is that: if I set proximity and ambient light to be some constant and not reading from I2C, then the recorded sampling frequency is 20Hz:

      1988,    7,   10
      2038,    8,   10
      2088,    9,   10
      2188,    1,   10
      2238,    2,   10
      2288,    3,   10

If I revert back reading I2C code (second column is data from sensor), then frequency is only 8Hz!!!

     17637,    8,   33
     17763,    9,   33
     17937,    1,   34
     18067,    2,   35
     18194,    3,   34
     18320,    4,   34

How could reading I2C block the timer interrupt? And how could it be so slow? (I've tried a similar sensor before, and could reach 100Hz with that).

body:
Let's take a look at a typical function for reading this sensor. This is from the Adafruit_VCNL4010 library and is for reading the proximity:

    uint16_t  Adafruit_VCNL4010::readProximity(void) {
      uint8_t i = read8(VCNL4010_INTSTAT);
      i &= ~0x80;
      write8(VCNL4010_INTSTAT, i);

      write8(VCNL4010_COMMAND, VCNL4010_MEASUREPROXIMITY);
      while (1) {
        //Serial.println(read8(VCNL4010_INTSTAT), HEX);
        uint8_t result = read8(VCNL4010_COMMAND);
        //Serial.print("Ready = 0x"); Serial.println(result, HEX);
        if (result & VCNL4010_PROXIMITYREADY) {
          return read16(VCNL4010_PROXIMITYDATA);
        }
        delay(1);
      }
    }

So let's tot up all the I2C transactions in that one function:

    read8
    write8
    write8
    {repeated
        read8
        [read16]
        delay(1)
    }

So in a best case scenario, assuming it's in a "ready" state, that's the minimum number of transactions, and the delay doesn't occur.  So what is in each of those transactions?

* read8:

Begin the transaction, write the address, end transaction, delay 170µs, begin request, read 1 byte, end transaction.  Total 4 bytes plus 170µs

* write8:

Begin transaction, write address, write data. Total 3 bytes.

* read16:

Begin the transaction, write the address, end transaction, begin request, read 2 bytes, end transaction.  Total 5 bytes (I notice this one has no delay...?)

So now we can see a best case scenario total of bytes transferred:

    4 read8 *
    3 write8
    3 write8
    {repeated
        4 read8 *
        5 [read16]
        delay(1)
    }

    4+3+3+4+5 = 19 bytes, plus 2x170µs delay.

The default clock speed for I2C on the Arduino is 100kHz. We have 19 bytes, plus start/stop/ack bits. So 19 * 8 for the data bytes (152 bits) plus 19 ACK bits (171 bits) and 5 * start + 5 * stop. That's 181 bits in total.

181 bits, at 100kHz, takes 1.81ms to transfer. Add to that the 2*170µs delay, and we are up to a *best case* scenario of 2.15ms transfer.

Double that up for reading the ambient light as well, and we're up to 4.3ms transfer. That's a theoretical absolute maximum of about 230Hz readings.

Remember: that's a **best case scenario**.  If the sensor isn't ready to return a reading at the time that there will immediately be a 1ms delay imposed and the number of transactions will increase.

So why would it not be ready to send a reading? The simplest explanation is that it's not set to a suitable sampling rate.

The library doesn't appear to change the sampling rate for the proximity from the default 1.95 samples per second, nor the ambient light sampling rate from the default of 2 samples per second - so unless you are using a different library, or manually changing these settings through your own Wire calls, even at a reduced triggering speed you'll not be getting anywhere near the kind of information you are after.

The fastest you can get for ambient light sampling is 10 samples per second. Proximity caps out at a more respectable 250 samples per second. But only if you tell it to...


message:
ESP8266 constantly reconnects

So, my ESP8266 now has this problem where every three seconds it goes offline for a split second and the light blinks as it comes back. It seems to be constantly resetting... I recieved this problem when I had it connected to a power brick in my pocket, and I am pretty sure it happened because of static. I would have bought a protective case for it but it appears that I csn only find 3D printed parts but I currently do not own a 3D printer. I am wondering how I can fix it. If I try to re-flash it the re-flash fails because it disconnects before the flashing finishes.

body: I managed to fix the problem. I have a PC with Ubuntu 16.04 and I tried to re-flash it using Ubuntu's ESPTool, which was why it was failing. I noticed it failed constantly at a certain point. To fix it, I re-flahed the firmware with [this](https://github.com/themadinventor/esptool.git) python script, and it was successful.


message:
Is there any option to connect XDTouch IrTouchScreen to Arduino?

Is there any option to connect XDTouch IrTouchScreen with USB interface or RS232 to Arduino board?

At the cable of this touchscreen i have something like at the photo.
At the top of the photo pins (+, t, r, -) from touchscreen to [SP232EEN](http://www.alldatasheet.com/datasheet-pdf/pdf/189641/SIPEX/SP232EEN.html), and at the bottom of photo pins (+, D-, D+, -) from CY7C63803-SXC module to USB output.

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

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

body:
Looks like your touch screen may talk RS-232. It uses the SP232EEN (a MAX232 clone) to interface with an MCU (Cypress CY7C63803) to get USB.

Connect wires to T1 IN and R1 OUT (I assume it's on channel 1) to your Arduino for UART communication. You would most likely need to disconnect those pins from talking to the Cypress chip, or they will interfere. Use the +5V and GND pins of the USB interface to power it direct from the Arduino.

Alternatively cut that board off and use a cheap MAX232 interface board to connect to the Arduino - that may be cheaper.  T and R are TX and RX (though from which PoV is anyone's guess).


message:
Controlling TFT LCD with Arduino

I bought [this LCD module][1]. How many pins does this LCD module uses? They have written in the product description that this LCD module uses 8 bit communication, but the LCD module has 16 bit pinout (DB0-DB15). What is the right pin number?

Is there any Arduino LCD library that supports this LCD module, which uses the OTM4001A LCD driver? Usually for LCD the UTFT library works, but it does not support the OTM4001A LCD driver.

Thanks for your help!

  [1]: http://www.ebay.com/itm/172272062467?_trksid=p2060353.m2749.l2649&ssPageName=STRK:MEBIDX:IT

body:
Trust what is on the board, not what the eBay seller says. They invariably can't tell the difference between a TFT screen and a doll, and they sell everything in between. They just regurgitate Chinglish nonsense. If the board says DB0-DB15 then DB0-DB15 is what you need to use.

Plus it says in the description:

> Support 16 bit RGB565 format , can connect any 16 bit data bus.

At least this one has told you what the driver chip is (OTM4001A) - many times they can't even do that and don't even understand what you are asking when you request that information.

Mind, it's a driver chip I have never come across before, so maybe I should get one on order to support it in DisplayCore...


message:
What are safe memory usage limits?

The Arduino IDE used to warn you when your sketch used too much memory. This warning now seems to have been removed. I compiled a sketch, and was surprised to see it use 175% of data memory...but not give me any explicit warning that this would be unstable, much less be physically unable to load onto the Arduino.

What are program and data memory usage levels that you should be concerned about? I seem to remember the best practice was to keep data memory under 80%. Is this still true? Is there any general rule for program memory?

body:
The compiler can only report the amount of statically allocated (RAM) memory. Depending on what you are doing in your sketch the value may be important, or it may be completely meaningless.

Suffice it to say, the total of heap + stack + static must not exceed the memory of your MCU.

When it comes to the Flash memory you can go right up to 100%.


body: It's a tough question to answer as it depends on the rest of the sketch.  You can safely use every single byte of memory as long as you're sure that's all you're using.  The number that it spits out on compile doesn't tell you that.  It just tells you about global and static variables really.  If you've got a loop that doesn't call any functions then you only need to save a few bytes for the stack. But if you've got a function that creates a local array with 500 ints then you're not safe even if that number it spits out on compile is only 50%.


message:
DS1307 Real-Time Clock

I am trying to make an Arduino project based on the Sparkfun DS1307 RTC (real-time clock).

There are a few issues with how Arduino libraries don't support checking if the Arduino board has been powered down and check for that.

Then using that as a conditional as to when the program should fall back to the compiled time if the RTC isn't set to a time yet because of something else.

When I power down the clock, it will automatic fall back to the compiled time every single time, regardless of what is currently on the RTC. Clearly this is not something you would want.

Edited - This is my current code. Keep in mind there are a few more changes I could do like take Byte zero declare out of the loop so it is still rough.

<!-- language: lang-js -->

    #include <Wire.h>
    #include <SparkFunDS1307RTC.h>

    #define DS1307_ADDRESS 0x68

    void setup() {
      Wire.begin();
      Serial.begin(9600);
      rtc.begin();
      if(false){
        //Should check RTC somehow to determine if should fallback to compiled time here.
        Serial.println("The DS1307 clock has lost power and reset to compiler's time");
        rtc.autoTime();
      }
    }

    void loop() {
      if(digitalRead(7)==LOW)
        printDate();
      delay(1000);
    }

    byte bcdToDec(byte val){
      return ((val/16*10) + (val));
    }

    void printDate(){
      rtc.update();
      Wire.beginTransmission(DS1307_ADDRESS);
      byte zero = 0x00;
      Wire.write(zero);
      Wire.endTransmission();
      Wire.requestFrom(DS1307_ADDRESS, 7);
      int second = bcdToDec(Wire.read());
      int minute = bcdToDec(Wire.read());
      int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
      int weekDay = bcdToDec(Wire.read()); //0-6 -> Sunday - Saturday
      int monthDay = bcdToDec(Wire.read());
      int month = bcdToDec(Wire.read());
      int year = bcdToDec(Wire.read());
      //Print the date like 3/1/1/11 23:59:59
      Serial.print(month);
      Serial.print("/");
      Serial.print(monthDay);
      Serial.print("/");
      Serial.print(year);
      Serial.print(" ");
      Serial.print(hour);
      Serial.print(":");
      Serial.print(minute);
      Serial.print(":");
      Serial.println(second);
    }

body:
> There are a few issues with how arduino's libraries doesn't support checking if the arduino board has been powered down and check for that.

How is it supposed to do that? The board's powered down.

> When I powered down the clock. It will automatic fallback to compiled time every single time regardless of what is currently on RTC. Clearly this is not something you would want.

So don't have a compiled in time.


body:
Easy. Here is one way to do it.

1. Read the clock off the rtc.
2. Wait a known period of time, based on the mcu frequency,
3. Read the clock off the rtc again.
4. Compare the two time reading and it should have advanced. If not, fall back to compiled time.

There are other ways to do it as well, like bor, or square wave output, interrupt on vbat line, ......


body:
DS1307 gives a square wave output which can be set to specific frequencies which is available in the datasheet.
Initially the square wave output is disabled.
You can enable it when you set the time.
When you power up again, check for the square wave and if it is absent you can set the time again.
This can be easily done by creating a timeout code and resetting the timeout timer in an interrupt. If square wave is present an interrupt will be generated accordingly and the timeout time period will be set to initial value.
If the timeout time expires you set the clock. This can even track clock failures in real time. Also you can use the same interrupt to extract data from the RTC as square wave output can be configured to 1Hz and hence you can poll the RTC at every 1Hz and take the data from the RTC.


body:
You could periodically store the date and time in the battery-backed SRAM in the DS1307. Every few seconds, once a minute, something like that.
Upon sketch start, perhaps in setup(), read the current RTC time, compare to the stored time, if the current time is later than the stored time, you can do the math and see how long the Arduino has been down.  Or use the Arduino's EEPROM to hold the last stored time if you are concerned about the RTC losing it's battery and resetting to it's default date and time, which would be earlier than the EEPROM time.


message:
SdFat library Change output style of sd.ls(LS_R)

I'm using the [SdFat Library's](https://github.com/greiman/SdFat) `sd.ls(LS_R)` function to give me a serial output stream of all files on an SD card. My issue is that I would like to have it use a different character than '\n' at the end of each line as I'm using it as a termchar for my overall comms protocol. How can I get it to print a `:` or (another symbol that doesn't appear in file names) instead of a `\ln`

body:
I am currently trying to have fun Modding my own sd.ls().

Worst way, modifying the library:

Go into FatFilePrint.cpp

(Suggestion: Create yourself a new 'flag' like LS_COMMA)

Find the line

    void FatFile::ls(print_t* pr, uint8_t flags, uint8_t indent) { ...

add your flag

    if (flag & !LS_COMMA) {
       pr-->write(':');
    } else {
        //original library set of
        // pr->write(stuff);
    }

# --> SuperClass version # (prefered )
this will override the original ls() method by creating a new Class inheriting from the original one.

rather then invoking it from "volume",
    sd.ls( __your params__);

invoke it from a directory file instead.

    superFatFile rootDir;
    rootDir.open("/");
    rootDir.ls( __your_params__);

Place this superClass declaration in your .h
don't hesitate to remove any of the "flags" related code if YOUR requirement never calls for them.

    class superFatFile : public FatFile {
        public:
     void ls(print_t* pr, uint8_t flags /* = 0 */, uint8_t indent /* = 0 */){
      superFile file;
      rewind();
      while (file.openNext(this, O_READ)) {
       if (!file.isHidden() || (flags & LS_A)) {
        // adds 'spaces' indent for dir level
        for (uint8_t i = 0; i < indent; i++) {
         pr->write(' ');
        }

        if (flags & LS_DATE) {
         file.printModifyDateTime(pr);
         pr->write(' ');
        }

        if (flags & LS_SIZE) {
         file.printFileSize(pr);
         pr->write(' ');
        }

        // prints filename
        if (!file.isDir()) {
         file.printName(pr);
         pr->write('\r');
         pr->write('\n'); // HERE IS YOUR SEPARATOR CARACTERS !!!
        }

        // execute recursivly if LS_R flag was set
        if ((flags & LS_R) && file.isDir()) file.ls(pr, flags, indent + 2);

       }

      }
            file.close();
     } // end of new LS method
    }; // end of superClass


message:
Scrambled query responses from ESP8266 to Uno, what are possible causes of the problem?

I have a small test sketch that sends queries to an ESP8266 chip [mounted on an ESP-01 board], and these responses are invariably scrambled,
though the response varies from execution to execution, e.g.,

(execution 1)

    _________[ Connect to AP ]__________
    __________[ AT+CWJAP="KCTcircuit2","" ]__________
    AT+CWJAX="I⸮Tcircuiz2",""H

(execution 2)

    __________[ Connect to AP ]__________
    __________[ AT+CWJAP="KCTcircuit2","" ]__________
    AT+CWJAH="KCTcircuiz2!,""H

What could be the source of the problem?  I need to resolve this before I can start testing the real sketch.

My test sketch follows [stripped of extraneous code]:

    #include <SoftwareSerial.h>
    // _______________________________
    #define sendit(x) ( { \
        Serial.print(F("__________[ ")); \
        Serial.print(x); \
        Serial.println(F(" ]__________")); \
        esp8266.write(x); \
        esp8266.write(F("\r\n")); \
        esp8266.readBytes(buffer, sizeof(buffer)); \
        Serial.println(buffer); \
        delay(2000); \
      } )

    // _______________________________
    #define desc(x) ( { \
        Serial.println(); \
        Serial.print(F("__________[ ")); \
        Serial.print(F(x)); \
        Serial.println(F(" ]__________")); \
      } )

    // _______________________________
    SoftwareSerial esp8266(12, 13); // RX, TX
    char buffer[50];

    // _______________________________
    void setup()
    {
        Initialise();
    }

    // _______________________________
    void loop()
    {
    }

    // ____________________________________________________________________________________________________
    void Initialise()
    {
        SerialReadBuffer.reserve(64);
        esp8266.begin(115200);
        Serial.begin(9600);
        CommandList();
    }

    // ____________________________________________________________________________________________________
    void CommandList()
    {
      desc("Test AT Startup");
      sendit("AT");
      desc("Restart the module");
      sendit("AT+RST");
      desc("Query baud rate");
      sendit("AT+CIOBAUD?");
      desc("Query firmware version");
      sendit("AT+GMR");
      desc("WIFI mode");
      sendit("AT+CWMODE?");
      desc("Get local IP address");
      sendit("AT+CIFSR=?");
      desc("Query current multiplex mode");
      sendit("AT+CIPMUX=?");
      desc("Enable echo (Sends back received command before response)");
      sendit("ATE1");
      desc("Set Station mode");
      sendit("AT+CWMODE=3");
      desc("Lists available APs");
      sendit("AT+CWLAP");
      sendit("AT+CWLAP");
        desc("Connect to AP");
      sendit("AT+CWJAP=\"KCTcircuit2\",\"\"");
      desc("Prints the SSID of Access Point ESP8266 is connected to.");
      sendit("AT+CWJAP?");
      desc("List clients connected to ESP8266 softAP");
      sendit("AT+CWLIF");
      desc("Get IP address of ESP8266 station.");
      sendit("AT+CIPSTA?");
      desc("Get information about connection");
      sendit("AT+CIPSTATUS=?");
      desc("Get local IP address");
      sendit("AT+CIFSR=?");
      desc("Get the SSID of Access Point ESP8266 is connected to.");
      sendit("AT+CWJAP?");
      desc("Get the SSID of Access Point ESP8266 is connected to -CUR");
      sendit("AT+CWJAP_CUR?");
      desc("Configuration of softAP mode");
      sendit("AT+CWSAP?");
      desc("Configuration of softAP mode = CUR");
      sendit("AT+CWSAP_CUR?");
      desc("Disconnect from AP");
      sendit("AT+CWQAP");
      Serial.println(F("__________________"));
      Serial.println();
     }

Typical output is as follows:

    "ESP8266_ATcmdtest", compiled on: Jun  5 2017 at 14:00:04
    Running on: Arduino UNO: ATmega328P

    __________[ Test AT Startup ]__________
    __________[ AT ]__________
    ATn

    __________[ Restart the module ]__________
    __________[ AT+RST ]__________
    AT+QST$

    __________[ Query baud rate ]__________
    __________[ AT+CIOBAUD? ]__________
    AT+CHOBAUD⸮⸮

    __________[ Query firmware version ]__________
    __________[ AT+GMR ]__________
    AT+TJ⸮⸮AUD⸮⸮

    __________[ WIFI mode ]__________
    __________[ AT+CWMODE? ]__________
    AT+CWLODE?G⸮

    __________[ Get local IP address ]__________
    __________[ AT+CIFSR=? ]__________
    AT+CHFSR=?⸮

    __________[ Query current multiplex mode ]__________
    __________[ AT+CIPMUX=? ]__________
    AT+CIPMUX=r⸮

    __________[ Enable echo (Sends back received command before response) ]__________
    __________[ ATE1 ]__________
    ATE0=PMUX=r⸮

    __________[ Set Station mode ]__________
    __________[ AT+CWMODE=3 ]__________
    AT+CWMODE=⸮⸮

    __________[ Lists available APs ]__________
    __________[ AT+CWLAP ]__________
    AJ+CWL@P⸮=⸮⸮
    __________[ AT+CWLAP ]__________
    AT+CWLAP⸮=⸮⸮

    __________[ Connect to AP ]__________
    __________[ AT+CWJAP="KCTcircuit2","" ]__________
    AT+CWJAH="KCTcircuiz2!,""H

    __________[ Prints the SSID of Access Point ESP8266 is connected to. ]__________
    __________[ AT+CWJAP? ]__________
    AT+CWJAP?⸮KCTcircuiz2!,""H

    __________[ List clients connected to ESP8266 softAP ]__________
    __________[ AT+CWLIF ]__________
    AV+CWLIFx⸮KCTcircuiz2!,""H

    __________[ Get IP address of ESP8266 station. ]__________
    __________[ AT+CIPSTA? ]__________
    AT+CIPSTA?CTcircuiz2!,""H

    __________[ Get information about connection ]__________
    __________[ AT+CIPSTATUS=? ]__________
    AT+CIP*UQUM⸮⸮2ircuiz2!,""H

    __________[ Get local IP address ]__________
    __________[ AT+CIFSR=? ]__________
    AT+CIFSR=?}⸮⸮2ircuiz2!,""H

    __________[ Get the SSID of Access Point ESP8266 is connected to. ]__________
    __________[ AT+CWJAP? ]__________
    AT+CWJAP? }⸮⸮2ircuiz2!,""H

    __________[ Get the SSID of Access Point ESP8266 is connected to -CUR ]__________
    __________[ AT+CWJAP_CUR? ]__________
    AT+CW⸮AP5UI⸮⸮⸮ircuiz2!,""H

    __________[ Configuration of softAP mode ]__________
    __________[ AT+CWSAP? ]__________
    AT+CWSAP?HI⸮⸮⸮ircuiz2!,""H

    __________[ Configuration of softAP mode = CUR ]__________
    __________[ AT+CWSAP_CUR? ]__________
    AT+CWSAP5UI⸮r⸮ircuiz2!,""H

    __________[ Disconnect from AP ]__________
    __________[ AT+CWQAP ]__________
    AZ+CWPAP⸮UI⸮r⸮ircuiz2!,""H
    __________________

body:
Cause: software serial at 115200 baud.

Solution: configure the esp8266 for a lower baud rate or use hardware serial.

The problem is basically that the Arduino cannot run 115200 baud SoftwareSerial reliably. It is common to get corruption of incoming characters, or characters completely skipped, due in part to the SoftwareSerial implementation being unable to react fast enough to the data coming in. The time between one stop bit and the next start bit is often shorter than the amount of time taken to store the data in the receive ring buffer, so the ISR cannot respond to the new start bit in time, and data is lost.  Running at a lower baud rate gives more time for the data to be stored before the next start bit arrives, thus giving the ISR time to finish and be ready to respond to the next byte coming in.

You need to change the baud rate of the ESP8266 itself (I find 9600 is a good reliable value) using one of (depending on your firmware version):

    AT+CIOBAUD=9600

or

    AT+UART_DEF=9600,8,1,0,0

or

    AT+IPR=9600

Last time I did it on an ESP8266 it was the first one that worked.

Then you will need to change your program to use 9600 baud instead of 115200 baud in your `esp8266.begin(...)`.


body: Since you mentioned you tried other baud rates, I am guessing it could be an RF issue. ESP8266 is a very sensitive device and is known to have weird electrical behaviour. Do you have a cap between VCC and GND?


message:
Can I control a Z84 counter timer circuit with Arduino?

[Link to pin description][1] and [to the Datasheet][2].

I'm thinking about connecting channel outputs to LEDs and control the clock with IO-Arduino or a 555: I would program it with a 595 register.

Can someone explain me why this is a bad idea?

  [1]: http://www.z80.info/z80ctc.htm
  [2]: http://www.google.com

body: I wouldn't say it was a "bad" idea - pointless maybe, but not "bad". A good learning experience if nothing else.


message:
Reading HMC5883L hex values in 2's compliment C code

I want to develop my C code for HMC5883L.

I have 2 questions for my current code development.

My first question is:
But what I found in the datasheet is that the values are in the 2's compliment, so I don't know how to deal with them?! Do I have to take the values as they are in the data registers and convert them to decimal values and that's it? Or I have to convert them from 2's compliment to the original hex values?

This is a quote from the datasheet:

> Send 0x3D 0x06 (Read all 6 bytes. If gain is changed then this data set is using previous gain)
Convert three 16-bit 2’s compliment hex values to decimal values and assign to X, Z, Y, respectively.

My second question:
How o read the data registers? What is the procedure?
I saw in the datasheet the following method but I didn't understand it.

> Loop
Send 0x3D 0x06 (Read all 6 bytes. If gain is changed then this data set is using previous gain)
Convert three 16-bit 2’s compliment hex values to decimal values and assign to X, Z, Y, respectively.
Send 0x3C 0x03 (point to first data register 03)
Wait about 67 ms (if 15 Hz rate) or monitor status register or DRDY hardware interrupt pin
End_loop

So, I didn't understand that I send read command then I send write command, so how HMC5883L would return the value to me?

Regards,

body:
2's complement is the normal signed values in any modern system, including Arduino.

Just place the bytes into a signed variable of the right size in the right positions and there is your value.

In I2C, to read a register, you typically have to make two transactions. The first is a write to set the register number you want to access, the you follow that with a read transaction to get the data.


message:
Stepper Motor with Limit Switches

I have the code below which is my attempt to control a stepper motor direction that moves a carriage to the right and left. In addition there are limits at each end of the travel that when activated stops movement in the respected direction. My problem is that the motor works just fine in the left and right directions but I can only get one of the limit switches to work. I'd appreciate any suggestions.

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

    int PUL = 7; //define Pulse pin
    int DIR = 6; //define Direction pin
    int ENA = 5; //define Enable Pin
    int RGT = 3;
    int LFT = 2;
    int potPin = A5;
    int count = 0;
    int interval = 1000;
    int val = 0;
    int Spd = 500;

    #define Limit01 8  // Pin 2 connected to Limit switch out
    #define Limit02 9  // Pin 3 connected to Limit switch out

    void setup() {
      pinMode (PUL, OUTPUT);
      pinMode (DIR, OUTPUT);
      pinMode (ENA, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {

      if (digitalRead(LFT) == LOW) {  //  If joystick is moved Left
        if (digitalRead(Limit01) == HIGH) {} // check if limit switch is activated

        else {  //  if limit switch is not activated, move motor clockwise

          digitalWrite(DIR, LOW);
          digitalWrite(ENA, HIGH);
          digitalWrite(PUL, HIGH);
          delayMicroseconds(500);
          digitalWrite(PUL, LOW);
          delayMicroseconds(500);
        }
      }

      if (digitalRead(RGT) == LOW) { // If joystick is moved right

        if (digitalRead(Limit02) == HIGH) {} // check if limit switch is activated

        else {  //  if limit switch is not activated, move motor counter clockwise

          digitalWrite(DIR, HIGH);
          digitalWrite(ENA, HIGH);
          digitalWrite(PUL, HIGH);
          delayMicroseconds(500);
          digitalWrite(PUL, LOW);
          delayMicroseconds(500);

        }
      }
    }

body:
What I understood from your question is you want only one limit switch to control the stepper motor in both directions.So here is the code that might be helpful for you in that case:

    int dirpin_T1 = 2;
    int dirH_T1 = 3;
    int steppin_T1 = 4;
    int limit = 10; // ASSUME LIMIT-SWITCH IS PLACED AT RIGHT CORNER
    void setup() {
      pinMode(limit,INPUT);

      pinMode(dirpin_T1, OUTPUT);
      pinMode(dirH_T1, OUTPUT);
      pinMode(steppin_T1, OUTPUT);

    }

    void loop() { //STEPPER TRAVELLING LEFT TO RIGHT

        digitalWrite(dirpin_T1, LOW );
        digitalWrite(dirH_T1, LOW);
       do
       {
          digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
          digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
          delayMicroseconds(50);

       }(digitalRead(limit)==HIGH); //AS LIMIT-SWITCH PRESSED MOTOR STOPS
      delay(500);
      //WHEN LIMIT-SWITCH IS LOW CHANGE THE DIRECTION OF MOTOR ROTATION
      if(digitalRead(limit)==LOW)
      {
          digitalWrite(dirpin_T1, LOW ); //CHANGE MOTOR DIRECTION (LOW TO HIGH)
          digitalWrite(dirH_T1, HIGH);
         for(int i=0; i<36000;i++)
          { //please try changing value of i as it depends on how much rotations you want your motor to step forward

          digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
          digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
          delayMicroseconds(50);
         }

      }
    }

The simple logic would be to move the motor in one direction until limit-switch is HIGH. And to move it to the other direction when its LOW i.e already pressed.Correct me if I am wrong and try modifying the code as per this logic.However you need to change your code depending upon what type of driver you are using. Right now I am using TB6560 driver.You can use if loop instead of do while loop to make it easier to understand.


body:
Use
while ( condition)
{ code to execute }
making sure the code itself is "short" not to overrun the condition

If you use while construct instead of do / while you are checking the condition first before code execution.
while( not at limit switch)
move stepper one step
Also the limit switch active state should be ground, not +V. Safety issue.
If you  accidentally ground the signal it will be valid, if the signal path is grounded already , by accident, putting  +V to it won't be detected.


message:
Arduino freezing with OLED display

I have a 0.96" `OLED` display hooked up to my `Arduino` `Mega` via `SPI`. I installed the `Adafruit` library and GFX library. I can run through the little graphical demo from `Adafruit` just fine as well as display static text with no problem.

However, I am trying to put together a project I thought would be simple and straight forward. I am trying to use a `DHT22` to collect temperature and humidity and then display it on the `OLED`. The problem I am running into is that the `Arduino` freezes after an indeterminate amount of time. The most it has been able to run is about 6 minutes.

Here is the code I am using:

    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    #include <DHT.h>

    #define DHTPIN 7
    #define DHTTYPE DHT22
    DHT dht(DHTPIN, DHTTYPE);

    // If using software SPI (the default case):
    #define OLED_MOSI   8
    #define OLED_CLK   9
    #define OLED_DC    10
    #define OLED_CS    11
    #define OLED_RESET 12
    Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

    #define LOGO16_GLCD_HEIGHT 16
    #define LOGO16_GLCD_WIDTH  16

    #if (SSD1306_LCDHEIGHT != 64)
    #error("Height incorrect, please fix Adafruit_SSD1306.h!");
    #endif

    long previousMillis = 0;
    long interval = 5000;

        String temperature;
        String humidity;

    void setup(){
      dht.begin();

      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);

      // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
      display.begin(SSD1306_SWITCHCAPVCC);

      display.clearDisplay();

      display.setTextSize(2);
      display.setTextColor(WHITE);
      display.setCursor(0,0);

      display.println(" Madgayrah");
      display.display();
      while(millis()<2000);
    }

    void loop() {

      unsigned long currentMillis = millis();
      if(currentMillis - previousMillis > interval) {
        previousMillis = currentMillis;

        float h = dht.readHumidity();
        float f = dht.readTemperature(true);

        if(isnan(h) || isnan(f)){
          int x = 6;
          String dashes = "";
          for(int y=1; y<=x; y++){
            dashes += "-";
          }
          temperature = humidity = dashes;
        }else{
          temperature = String(f)+(char)248;
          humidity = String(h)+"%";
        }

        display.clearDisplay();
        display.setTextColor(WHITE);
        display.setCursor(0,0);

        display.setTextSize(1);
        display.println(String(previousMillis/1000));
        display.println("");

        display.println("Temperature:");
        display.setTextSize(2);
        display.println(temperature);

        display.setTextSize(1);
        display.println("Humidity:");
        display.setTextSize(2);
        display.println(humidity);

        display.display();
      }
    }

In my attempt at debugging I discovered that NOT printing out the temperature and humidity variables allows the program to run indefinitely. However, for some reason turning on either one of those lines and printing out that variable leads to the issue of the `Arduino` freezing.

ADDITIONAL INFORMATION:
I am using a 12 volt external power supply hooked up to the barrel of the `Mega`. The Mega is providing 5 volts and ground to a bread board which powers/grounds both the `OLED` and the `DHT22`.

Any ideas as to what could be causing the freezing issue on what "should be" a simple and straightforward project? Thanks.

body:
Because your program uses various `String` objects in several different sizes, there's a good chance that heap memory (in RAM) is getting fragmented to the point that `String` allocation begins to fail, or begins to allocate on top of stack variables.  (Typically, heap and stack work toward each other, from opposite ends of memory that is free after static variables are allocated.)

For example, the code `for(int y=1; y<=x; y++){ dashes += "-"; }` with `x=6` creates half a dozen `String` objects, all of different lengths.

To avoid this problem, you could carefully release each heap allocated object when done with it, or more effectively, could avoid using `String` objects, which actually aren't needed in this program.

For example, instead of `display.println(String(previousMillis/1000));` say `display.println(previousMillis/1000);` and instead of building `dashes` a character at a time before using it, just say `"------"` in place of `dashes`.


body:
I had exact same problem and james's answer helped me realize the problem is related to heap memory.

In addition to what he has already commended, I found [here](https://forum.arduino.cc/index.php?topic=123055.0) that you should also wrap all your constant strings in F() function.

For example instead of

    display.println(" Madgayrah");

You write

    display.println(F(" Madgayrah"));

This will store the string in the flash memory instead of SRAM.

Also if you only use OLED display for printing text, I strongly recommend the more lightweight [SSD1306Ascii](https://github.com/greiman/SSD1306Ascii) library

It output text to oled display without buffering which causes slight flickering but massively reduce the amount of memory required to drive the OLED.

Another helpful tip is to use arduino's [watchdog](https://tushev.org/articles/arduino/5/arduino-and-watchdog-timer). Basically after you enable that you need to constantly call `wdt_reset();` function and if you failed to call it for certain amount of seconds, arduino will automatically reset.


message:
Seven-Segment Display doesn't work on two lights

This is my code:

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

 void loop() {
  digitalWrite(2, HIGH);
 }

This is my circuit:
[![enter image description here][1]][1]

Problem:

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

Light A and B doesn't work when I plug the red cable to 4 and 5.
All the other lights works just fine.

  [1]: https://i.stack.imgur.com/K9xSZ.png
  [2]: https://i.stack.imgur.com/H6u6c.png

body:
As [jwpat7 states][1], you need a current-limiting resistor for *each* segment, between the data pin (on the Arduino) and the segment pin (on the display). Your Fritzing diagram only shows *one resistor* in the circuit, from the common cathode to GND on the Arduino.

You can not, or should not, *share one resistor to ground* (assuming that you have a common cathode seven segment display). You need a current-limiting resistor on *each anode* (again, (assuming that you have a common cathode seven segment display).

If you are sharing the current-limiting resistor between all segments, and then try to light more than more segment, at a time (which it sounds like you are doing ("when I plug the red cable to 4 and 5"), then the current through the current-limiting resistor will increase, and as a result, the voltage will change significantly enough, such that there is not sufficient voltage drop across the LED in order to make it light up.

Remember, 0.7 V is dropped across the LED.

Test each on the segments, **one at a time**, to make sure they all work, as [Ignacio states in his comment][2].

Also, your sketch should be more complete, along the lines of:

    void setup() {
        pinMode(2, OUTPUT);
        pinMode(3, OUTPUT);
        pinMode(4, OUTPUT);
        pinMode(5, OUTPUT);
        pinMode(6, OUTPUT);
        pinMode(7, OUTPUT);
        pinMode(8, OUTPUT);
    }

    void loop() {
        digitalWrite(2, HIGH);
        digitalWrite(3, HIGH);
        digitalWrite(4, HIGH);
        digitalWrite(5, HIGH);
        digitalWrite(6, HIGH);
        digitalWrite(7, HIGH);
        digitalWrite(8, HIGH);
    }

Connect up all of the pins, using a current-limiting resistor on each anode, and then try it programmatically.

If your seven segment display is a common anode, then, again, you need a resistor between each cathode and the data pins, and bring the pins `LOW` to light the corresponding segment, i.e.

        digitalWrite(8, LOW);

  [1]: https://arduino.stackexchange.com/questions/39194/seven-segment-display-doesnt-work-on-two-lights#comment79319_39194
  [2]: https://arduino.stackexchange.com/questions/39194/seven-segment-display-doesnt-work-on-two-lights/39198#comment79313_39194


message:
Using SoftwareSerial along with FastLED library to control WS2812 LEDs

I am controlling WS2812 LEDs with Arduino nano using [`FastLED` library][1]. I want the LED patterns to change on receiving a command from another Arduino Nano over software serial, I don't have the option to use he hardware serial.

I have read that in order to write data to LEDs, the library disables all the interrupts. However the [`SoftwareSerial` library][2] also uses interrupts to transmit data properly. Is there any possible way to achieve this? Presently, when I am trying to do this I am getting garbage data.

  [1]: https://github.com/FastLED/FastLED
  [2]: https://www.arduino.cc/en/Reference/softwareSerial

body:
How fast do you need to update the LEDs? The nice thing about WS2812s is that if you don't update them they maintain the current settings which means you only need to drive them once you have received a serial message.

The best way to do this would be to use some form of flow control over the serial port. e.g. you send a special control code over the serial line requesting the master to stop sending data. You then wait long enough for that to be sent and any data currently in transmission to arrive (so a absolute minimum of 20/(baud rate) seconds). After that time you call the function to update the LEDs. Once the LED update is done you send a second control code indicating that the other end can resume transmission.

This is the basic structure of software flow control (or XON/XOFF as it is also called) that most serial ports support as an option. You can either use the standard implementation or use something a little simpler since you only need data and flow control in one direction.

The other option is to design the system around rules that ensure you don't miss data. The system sending you the LED updates knows that once you get the update you will need to apply it to the LEDs and that during that time you can't receive serial data. So after an update it waits and doesn't send more data until you've had time to do that.


body:
The FastLED and NeoPixel libraries turn off interrupts for the specific timing of the WS2812. The Adafruit NeoPixel has a few extra options to be able to still handle some interrupts. The FastLED has a wiki that describes the problem with interrupts: [FastLED wiki interrupts][1]

The SoftwareSerial requires interrupts. When the SoftwareSerial is busy, the Arduino is occupied.

To me it seems impossible to make both libraries work at the same time. I think you have to change something. For example use a Arduino Micro or Pro Micro and use the spare hardware serial port. Or use a ledstrip with leds that have a clock signal and don't need specific timing.

If that is not possible, you might have to use pin 0 (RX) and pin 1 (TX), which are also used by the serial monitor and to upload a sketch.
It is possible to split RX and TX. The only thing that RX and TX have in common is the baudrate, but you can use them for seperate tasks.
For example, use TX to send (debug) messages to the serial monitor, and use the RX to receive commands from another Arduino board. Disconnect that other Arduino board to upload a sketch.

[**ADDED**] After reading the answer by @Andrew and the FastLED wiki about interrupts, I think that my answer and @Andrew's answer are equally good answers. Perhaps the best way is to do it all: faster Arduino board, hardware serial port for commands, do one thing at a time, implement some kind of XON/XOFF in software, and if possible use other leds.

  [1]: https://github.com/FastLED/FastLED/wiki/Interrupt-problems


body:
Another approach is to make the commands to change the pattern very short. Like, one letter/byte.

This assumes that the patterns are stored on your Arduino, and you just choose which one to show.

In order for that to work, the Arduino has to confirm commands it received, and return an error if it receives something it does not understand (e.g. only half of the command). This allows the host to check if the Arduino received the command or if it was animating at that time, in that case re-send the command.

This approach avoids the issue that you receive partial data (because the smallest transmission unit is used). Commands can still be lost, but then they can be re-sent.