message:
Arduino Mega LCD

I am interfacing an LCD with an Arduino. Sometimes it shows nothing after uploading the program. What should I do?

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

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

body:
An LCD will show blocks like that if it isn't initialized correctly.  You may have an intermittently-bad connection on one or more of the control lines.  [But see edit 1, below, regarding contrast adjustment.]

To diagnose intermittent connections, you could run a sketch that repeatedly initializes the LCD and then displays different sets of characters for a few seconds.  This will allow you to wiggle different pins and find out which is responsible for the bad connection.

To avoid intermittent connections, you could use a shield with soldered pins, or could get multipin shells to replace the single-pin shells of the Dupont-type connectors shown in the photograph.  Having adjacent connectors fixed in a single multipin shell results in more-stable connections.

---

*Edit 1:* As noted in a comment, blocks appearing on both lines is typical of contrast adjustment problems or missing contrast voltage.  On the other hand,  blocks appearing on just the first line is typical of incorrect  initialization, which could be caused by poor connections or by software errors.

---

Below is a sketch that repeatedly initializes the LCD and then displays different sets of characters for a few seconds each.

Note, if you don't have  the `Streaming.h` [contributed library](https://www.arduino.cc/en/Reference/Libraries) installed, you can get [`Streaming5.zip`](http://arduiniana.org/Streaming/Streaming5.zip) from [arduiniana.org](http://arduiniana.org/libraries/streaming/).

Note, if not using an I2C-interfaced LCD, change the included LCD library .h from `LiquidCrystal_I2C.h` to whatever is appropriate, and remove I2C-address-related stuff from the sketch.  If you are using an I2C-interfaced LCD on a known fixed address, remove the `lcd.setAddress(address);` and `lcd.getAddress(address);` stuff.  Those routines are not part of the usual LCD libraries; they probably can be added by subclassing `LiquidCrystal_I2C`, but on my system I added code as shown after the sketch.

---

    /* Screen-test sketch for PCF8574/PCF8574A/PCF8574T I2C LCD Backpack
    Uses library from https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads GNU General Public License, version 3 (GPL-3.0) */
    #include <Streaming.h>
    #include <Wire.h>
    #include <LCD.h>
    #include <LiquidCrystal_I2C.h>

    enum { LCDcols=16, LCDrows=2 };        // # of rows and cols on LCD
    enum { LCDaddr2=0x27, LCDaddr3=0x3F}; // For TI PCF8754 or PCF8754A
    LiquidCrystal_I2C lcd(LCDaddr2,2,1,0,4,5,6,7);

    void initLCD(byte address) {
      byte cdata[8];
      Serial << "initLCD(" << _HEX(address) << ')' << endl;
      lcd.setAddress(address);       // Set LCD I2C address
      Serial << "LCD address ... " << _HEX(lcd.getAddress()) << endl;
      // activate LCD module
      lcd.begin(LCDcols, LCDrows);
      lcd.setBacklightPin(3,POSITIVE);
      lcd.setBacklight(HIGH);
      lcd.noCursor();

      // Load custom characters
      for (int c=0; c<8; ++c) {
        unsigned int d = ((c+4)<<12 | (c|3)<<9 | (c|2)<<6 | (c|1)<<3 | c) ^ 0x5555;
        //Serial << "c=" << c << "  d=" << _HEX(d) << endl;
        for (byte k=0; k<8; ++k)
          cdata[k] = d >> k;
        lcd.createChar(c, cdata);
      }
      lcd.home ();
      lcd.print("Initialized");
      delay(1000);
    }

    void setup() {
      Serial.begin(115200);
      Serial << "Starting up" << endl;
      Wire.begin();                 // Setup to wirescan to check for 8754 addr
      Serial << "after Wire.begin()" << endl;
      TWBR = 152;  // 50 kHz, use if it works, or use slower rate
      TWBR = 158;  // 12.5 kHz, = slower rate
      TWSR |= bit (TWPS0);  // change prescaler
      Serial << "after TWBR / TWSR" << endl;
      Wire.beginTransmission (LCDaddr2);
      Serial << "after Wire.beginTransmission()" << endl;
      if (Wire.endTransmission() == 0) // Does 0x27 succeed?
        initLCD(LCDaddr2);      // Set up with 0x27 address
      else
        initLCD(LCDaddr3);      // Set up with 0x3F address
      Serial << "after initLCD()" << endl;
    }

    void show(char base, byte delt) {
      enum {MD=2000};
      byte k, ro;
      for (ro=0; ro<LCDrows; ++ro) {
        lcd.setCursor(0, ro);
        for (k=0; k<LCDcols; ++k) {
          lcd.print(base);
          base += delt;
        }
      }
      if (base==' ') {
        lcd.setCursor(1, 1);
        lcd << "LCD @" << _HEX(lcd.getAddress()) << " =" << lcd.getAddress();
      }
      delay(MD);
    }

    long p=0;
    void loop() {
      byte c;
      Serial << "Pass " << p++ << " on " << _HEX(lcd.getAddress()) << " at t=" << millis() << endl;
      lcd.home ();   // Set cursor to 0,0
      show('#', 0);   // Screen of # characters
      show(' ', 0);   // Screen of ' ' characters
      show('@', 0);   // Screen of @ characters
      show( 0,  1);   // lo specials + ' '...'/'
      for (c=' '; c < '~'; c+=16)
        show(c, 1);

      lcd.setBacklight(HIGH);
      while (Serial.available()) {
        c = Serial.read();
        if (c == '2') initLCD(LCDaddr2);
        if (c == '3') initLCD(LCDaddr3);
      }
    }

---

To add `lcd.setAddress(address);` and `lcd.getAddress(address);` routines:

 // add after void setBacklight(...); in LiquidCrystal_I2C.h
    void setAddress(uint8_t addr);
    uint8_t getAddress();

and

    // add after void setBacklight(...); in LiquidCrystal_I2C.cpp
    void LiquidCrystal_I2C::setAddress(uint8_t addr) {
      LiquidCrystal_I2C::_Addr = addr;
    }
    uint8_t LiquidCrystal_I2C::getAddress() {
      return LiquidCrystal_I2C::_Addr;
    }


sender: user

message:
Why does this Arduino Pro Mini use a capacitor on the DTR reset line?

I'm kind of curious as to why there is a 0.1uF capacitor on this Arduino Pro Mini (https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf). It seems like it would work just fine without it.

sender: assistant

body:
Most USB to serial chips set the DTR to LOW on connecting, but it keeps it LOW.

This would reset the arduino, but since the DTR never goes HIGH the Arduino will never get out of this reset state, and not run your code.

The capacitor will AC couple the signal. The the DTR goes low, the other side of the capacitor will go LOW too, but the pull-up resistor will slowly charge the capacitor, till the reset pin is HIGH again.

So it will convert a LOW transition to a LOW pulse.


message:
Posting data with ESP8266 module?

I have an ESP8266 module attached to an Arduino Uno that is connected to my local network. On the network, at address 192.168.1.13, I have a nodejs/express server running on port 3000. How would I go about posting an eight digit number from the Arduino to the webserver? In my current attempts the server console isn't receiving any data when using AT+CIPSEND while connected to it.

EDIT: My Code is as follows:

         #include <SoftwareSerial.h>

    const byte rxPin = 9; // Wire this to Tx Pin of ESP8266
    const byte txPin = 10; // Wire this to Rx Pin of ESP8266

    // We'll use a software serial interface to connect to ESP8266
    SoftwareSerial ESP8266 (rxPin, txPin);

    void setup() {
      Serial.begin(9600);
      ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
      delay(1000); // Let the module self-initialize
      Serial.println("Sending an AT command...");
      ESP8266.println("AT+CWMODE=1");
      delay(1000);
      ESP8266.println("AT+CWJAP=\"username\",\"pass\"");
      delay(10000);
      ESP8266.println("AT+CIPMODE=1");
      delay(1000);
      ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\test\",3000");
      delay(1000);
      GetData();

    }
    void loop() {
     while (ESP8266.available()){
         String inData = ESP8266.readStringUntil('\n');
         Serial.println("Got reponse from ESP8266: " + inData);
      }
    }
    void GetData(){
      ESP8266.println("AT+CIPSEND=4");
      ESP8266.print("test");
    }

and My output is this

      Sending an AT command...
    Got reponse from ESP8266: AT+CWMODE=1

    Got reponse from ESP8266:

    Got reponse from ESP8266: OK

    Got reponse from ESP8266: AT+CWJAP="surveillancevan4","7073199495"

    Got reponse from ESP8266: AT+CIPSEND=4

    Got reponse from ESP8266: testI

EDIT 2: I modified my code to this

        #include <SoftwareSerial.h>

    const byte rxPin = 9; // Wire this to Tx Pin of ESP8266
    const byte txPin = 10; // Wire this to Rx Pin of ESP8266
    // We'll use a software serial interface to connect to ESP8266
    SoftwareSerial ESP8266 (rxPin, txPin);

    void setup() {
      Serial.begin(9600);
      ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
      ESP8266.println("AT");
      delay(1000);
      ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\",3000");
      delay(20000);
      String request = "POST /test HTTP/1.0 \r\n";
      ESP8266.println("AT+CIPSEND=19");
      delay(5000);
      ESP8266.println(request);

    }

    void loop() {
     while (ESP8266.available()){
         String inData = ESP8266.readStringUntil('\n');
         Serial.println("Got reponse from ESP8266: " + inData);
      }
    }
and now my output claims it posted successfully, but I'm still not seeing any data in my nodejs server. Here is the output:
Got reponse from ESP8266:

    AT

    Got reponse from ESP8266:

    Got reponse from ESP8266: OK

    Got reponse from ESP8266: AT+CIPSTART="TCP","192.168.1.13",3000

    Got reponse from ESP8266: CONNECT

    Got reponse from ESP8266:

    Got reponse from ESP8266: O

    Got reponse from ESP8266: busy sytes

    Got reponse from ESP8266:

    Got reponse from ESP8266: SEND OK

I can confirm that it is connecting to my web app because when I run the code on the module without the server running it returns an error.

body:
     ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\test\",3000");

That line is going to fail miserably for a number of reasons:

1. You need to provide an IP address or domain name - NOT a URL
2. Even if you could provide a URL this bit `192.168.1.13\test` would end up, after C escaping, as `92.168.1.13        est` since `\t` is a TAB character.

And then on top of all that I assume you are connecting to a HTTP server, yet you aren't sending a HTTP request, you are just sending the word "test", which the HTTP server has no hope of ever understanding.

You need to formulate and send a proper HTTP request and send it to the server. I suggest you go and look at a few tutorials and maybe look up how HTTP Servers actually operate and what the protocol looks like.


message:
Why so different not connected analog inputs?

I took just Arduino Uno board, connected Ethernet Shield to it and compiled Web Server example. And it works.

But it outputs:

    analog input 0 is 1023
    analog input 1 is 1023
    analog input 2 is 789
    analog input 3 is 663
    analog input 4 is 525
    analog input 5 is 449

Why so different values? Shouldn't it be zeros? Is this static electricity or what?

body: Floating inputs, EMI, high input impedance and sample-and-hold capacitor. It can measure anything at this point (usually electro static charge is split between pin capacity and S&H capacitor. It can be used even for touch sense pins...


message:
Sketch does not work without delay() or other complex functions like digitalWrite()

I have a simple sketch here that should just blink a led once a second or so (approximately):

    boolean onOff=true;
    int count=0;

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

    void loop() {
        count++;
        delay(1);

        if (count == 316) {
        onOff=!onOff;
        digitalWrite(13, onOff);
        count=0;
        }
    }
So, if `count` is 316 it changes the state of led. It works right now, but it does not without `delay()` function or some other complex ones like `digitalWrite()` being in the `loop()` too. If i am deleting `delay()`, than led is just always on. I can feel it is smth about interrupts, but i am not sure.

----------

 What am i trying to do here is to make an alternative to `delay()` and `millis()` for my other project. One of the most needed thing for me is to make ASAP (as soon as possible) "timer", so that some code could run every 2(3-4...) iterations of loop(). delay() is bad always, and millis() uses `long` variable (which is bad for cpu time and ram), and while having problems with ram and cpu time in my project, i want smth lighter for ASAP and other not very precise timing.  So, the questions are:

 1. Why does my sketch works only with delay(), but does not work
    without it?
 2. Why does blinking sketches work with millis(), while they do not use any delay() just like my sketch.
 3. Am i a bad person for trying to make smth like an ASAP timer?:)  Is saved ram and cpu time worth of it?  Any other possible problems?
 4. Can this sketch be workable without `delay()` or other complex or ram and cpu costly functions?

Thank you.

So, the sketch up there works indeed, but here is the version that you can can observe with your eyes:

    boolean onOff=1;
    unsigned int counter=0;
    unsigned long time=0;

    void setup() {
      pinMode(13, OUTPUT);
      Serial.begin(57600);
    }

    void loop() {
       if (counter==0)  time=micros();
        counter++;
        if (counter == 0) {
            onOff= !onOff;
        digitalWrite(13, onOff);
        Serial.println(micros()-time);
        }
    }
With Serial i was checking delay between blinks, and it is 140164 mcs = 140 ms = 0.14s. But to be honest it feels slower, so please correct me if i can benchmark it in a better way.

body:
As majenko answered in the comments, the blinking rate will be so fast you can not see it.
Also it is possible that without the delay the optimizer removes the whole counting. So increasing the number as proposed by majenko may not even work due to compiler optimisations.
Using a method based on counters is a very unreliable way to use timings.

Look at the blinkwithout delay example as proposed by Dirk.
It boils down to using millis() for timing. millis tells you how many millis the arduino is running.

    void loop() {
      // here is where you'd put code that needs to be running all the time.

      // check to see if it's time to blink the LED; that is, if the
      // difference between the current time and last time you blinked
      // the LED is bigger than the interval at which you want to
      // blink the LED.
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }

        // set the LED with the ledState of the variable:
        digitalWrite(ledPin, ledState);
      }
    }


body:
This sketch blinks an LED on D10 (on a Uno) at one second intervals. It does not use `delay`, `micros`, `millis` or any unsigned long variables (apart from a constant).

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

    const int STROBE_FREQ = 1000;     // sets the period in milliseconds
    const unsigned long countTo = ((float) F_CPU / 1024.0) / (1000.0 / STROBE_FREQ);

    void setup ()
      {
      // D10 to output
      bitSet (DDRB, 2);

      // Fast PWM top at OCR1A
      TCCR1A = bit (WGM10) | bit (WGM11); // fast PWM
      TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS12) | bit (CS10);   // fast PWM, prescaler of 1024
      OCR1A = countTo - 1;                 // zero relative
      OCR1B = (countTo / 2) - 1;           // 50% duty cycle
      bitSet (TCCR1A, COM1B1);   // clear OC1B on compare
      }  // end of setup

     void loop ()
       {
        // do something useful
       }

It frees up the main loop to do something useful without worrying about time taken to do the blinking.

For more details see [my page about timers](http://www.gammon.com.au/timers).


message:
How to encode resistance change (reed) for Arduino?

I have a water counter which switches reed on each 10 liters of water. I would like to count these values with Arduino.

I wrote a program which counts changes from analog input and connected counter between `+5V` and analog input. It counts well but I am doubt I connected correctly. Because when reed is opened, then analog input is connected to nothing, while it should be connected to `GND`.

How to implement correct conversion from reed to analog or digital input?

body: A reed switch is just a button. Treat it as such. Either connect it between a digital input and ground, with a pull-up resistor (internal one would do) or between a digital input and +5V and use a pull-down resistor.


message:
Perform function after a period of time

I am working on a project that I am supplying with voltage an LED through a digital pin (26) and I want the LED to be switched off after 4 seconds.

I am using Arduino Mega2560 and I am programming it using Arduino's IDE version 1.6.10. I have installed the SimpleTimer library .zip method but it does not seem to function.

**Code**

    #include <SimpleTimer.h>

    SimpleTimer timer;

    void setup() {
    pinMode(26, OUTPUT);
    digitalWrite(26, HIGH);

    timerId = timer.setTimeout(4000, switchOff);
    }

    void switchOff() {
      digitalWrite(26, LOW);
    }

    void loop() {
    }

The problem is that the LED stays just on (*digitalWrite(26, HIGH);*) instead of going to the *switchOff* function and turning off (*digitalWrite(26, LOW);*). I have also tried using Timer1 and Timer libraries but they also do not work. Can someone who has made any of the libraries work, provide me with some guidance?

body:
You have to call `timer.run()` inside loop function.

The SimpleTimer library is more like a scheduler. You call at every so often, and it checks if there is any event that has expired.


message:
Interrupt driven serial in Arduino Mega

This is the multi serial example from Arduino IDE

    void setup() {
      // initialize both serial ports:
      Serial.begin(9600);
      Serial1.begin(9600);
    }

    void loop() {
      // read from port 1, send to port 0:
      if (Serial1.available()) {
      // plus do some operations
        int inByte = Serial1.read();
        Serial.write(inByte);
      }

      // read from port 0, send to port 1:
      if (Serial.available()) {
        // plus do some operations
        int inByte = Serial.read();
        Serial1.write(inByte);
      }
    }

As you can see, the loop is running multiple times doing almost nothing at most of cycles, this will eat up battery life (if it has one).

Is it possible to read when data is available without looping, just like with an interrupt.

Also, is it a good practice to run a loop all the time? Is there any way to sleep? I have seen examples like this one http://playground.arduino.cc/Learning/ArduinoSleepCode which uses some other pin to wake up. I don't want that.

body:
Why do you not want to sleep the processor? If it's running at all, it doesn't matter whether it is polling the UARTs or executing something else; it will still be using power.

The first several paragraphs of the article you linked to describe putting the processor into low-power mode and reducing the power consumption further by disabling some internal hardware modules. When the UART receives a byte, the processor will wake up and continue execution from where it slept. Isn't that what you are asking for?


body:
Serial input can wake the processor from sleep, assuming it is useful for it to sleep (for example, if it is battery-powered).

[My page about power](http://www.gammon.com.au/power) shows various technicques including using serial input to wake it from sleep (see reply #8 on that page). However a disadvantage of that is, it take a few microseconds to wake from sleep - sometimes quite a few - so you are likely to lose the first byte received from serial if you are asleep.

> Also, is it a good practice to run a loop all the time?

There is no harm, except for battery consumption.


message:
How to increase SD card write speed in arduino

I'm creating a data-logger system which logs data in SD card at a high speed of about 20000-30000 bytes per second. But the SD library in arduino currently writes data at about 4500-5000 bytes per second which is too slow.

I've read this [hack to improve the write speed][1], but I'm wondering if a more direct approach is possible, maybe by adjusting the [SPISettings][2].

  [1]: https://hackingmajenkoblog.wordpress.com/2016/03/25/fast-efficient-data-storage-on-an-arduino/
  [2]: https://www.arduino.cc/en/Reference/SPISettings

body:
Many factors would decide if you can reach this wanted speed. Only some of these.

----------

1. Your Software
-----------

The [SdFat][1] Library is faster than the standard SD Library of the Arduino IDE. It also has an easy to use compatibility function with the standard SD Library. Try it out.

2. Your Hardware
----------------
You should use a high class SD Card. As you maybe know SD Cards are sorted into performance classes. Most people in the internet recommend a SanDisk SD Card.

  [1]: https://github.com/greiman/SdFat


body:
OK. So, I tried the SDFat lib. This library is definitely better than the default SD library that comes with adruino.
But that is not how I solved my problem of low data-rate.

I followed the instruction of the author of SDFat library from [***this post***][1].

According to *fat16lib*, to increase the data rate we need to use flush() wisely. We would want to write() the data in each cycle, but we only need to flush() once every 100 cycles or so depending on how much data is being written in each cycle. Also, be sure to keep the flag in SD.open() as 'O_WRITE | O_CREAT' instead of 'FILE_WRITE'.

This sure increased the speed by a great factor. But I needed more!

Storing the data in binary ([check out this blog][2]) improved the performance even more.

My current speed is approximately 100-120 KBps (that's kilo bytes) with a class 4 SD card!

Finally, I want to thank you guys for your help.

  [1]: http://forum.arduino.cc/index.php?topic=49649.msg354701#msg354701
  [2]: https://hackingmajenkoblog.wordpress.com/2016/03/25/fast-efficient-data-storage-on-an-arduino/


body:
Avoid the handshake getting a buffer!

Use
**SD.write(buf,size);**

Hi every one, I'm working in a project with the same issue. I was following the same steps of yours and got exactly the same numbers. I've just fixed it out. The problem is the handshake when you call the `SD.write()`.

Instead:

    //for each loop, it is going to make a handshake
    while(<yourCondition>){
        SD.write(<yourValue>);
    }

Do:

    char buf[length];
    while(yourCondition){
        buf[index] = yourValue;
    }
    SD.write(buf,index);//only one handshake

In my project the first one I got **4100** bytes, and the second one using a buffer with 128 (buf[128]) I got **145408** bytes in my project. Good enough.


message:
How often can I ping an HC-SR04 ultrasonic sensor?

In my current project, I want the sensor to be continuously scanning for a value of less than 30cm. I was wondering how long of a delay I need (if any) between each call of the ping function. It currently works at 150ms between each ping call with no problem. The less the delay, the better for my project. This is the ping function:

    void ping() {
      digitalWrite(trig, LOW);
      delayMicroseconds(2);
      digitalWrite(trig, HIGH);
      delayMicroseconds(10);
      digitalWrite(trig, LOW);
      duration = pulseIn(echo, HIGH);
    }

For example, would having a delay of only 5ms be sufficient?

body:
> How often can I ping an HC-SR04 ultrasonic sensor?

This ping() function is vulnerable to interrupts during the pulseIn(). This implies that a delay needs to wait for queued interrupts as from, for instance, Serial output. Input interrupts may still affect the results. This function only works in very simple sketches.

Possible solutions are to 1) disable during the pulse measurement (not the wait for pulse start), 2) use a more advanced method to allow concurrent events (such as timer capture).

Cheers!


body:
[Documentation from elecfreaks.com][1] recommends 60 milliseconds between measurements. That'll cut down your time by ~60% (from your 150ms delay). It works for me.

  [1]: http://www.elecfreaks.com/244.html


message:
Why does HC-SR04 return 0s in this sketch

I am building a robot with multiple sensors, abilities etc. Since I had a bug with a HC-SR04 rotated by a servo, I experimented in a different sketch. If the distance is less than 30cm, the servo turns left and right. Since I need continuous readings of other sensors, I cannot use delays so I used millis in order to keep time. The sensor worked correctly in a different sketch, but something in the full one conflicts with it.

    #include <LiquidCrystal.h>
    #include <Wire.h>
    #include <RTClib.h>
    #include <Servo.h>
    #include <IRremote.h>

    RTC_DS1307 rtc;

    /*const int blue2 = 12;
    const int blue1 = 11;
    const int red1 = 10;
    const int red2 = 9;
    */
    Servo servo;

    byte leds[4] = {8, 7, 6, 9};

    const int STBY1=45;
    const int ain11=47;
    const int ain12=43;
    const int aPWM1=2;
    const int bin11=41;
    const int bin12=40;
    const int bPWM1=4;
    const int STBY2 = 39;
    const int ain21=33;
    const int ain22=31;
    const int aPWM2=5;
    const int bin21=35;
    const int bin22=37;
    const int bPWM2=3;

    const int piezo = 32;

    const int flamePin = A7;

    int flameState;

    const int photoResistor = A1;

    int photoState;

    const int temp = A2;

    float temperature;

    int ledAnalog;

    const int irGnd = 52;

    const int irVcc = 50;

    const int irSignal = 48;

    decode_results results;

    IRrecv irrecv(irSignal);

    boolean manualLeds = false;

    boolean ledsOn = false;

    unsigned long counter;

    unsigned long prevMillis = 0;

    int piezoInterval = 200;

    int drivingMode = 0;

    boolean playPiezo=false;

    #define trig 22
    #define echo 24
    long duration;
    boolean turned150 = false;
    int cm30, cm, cm150;
    bool checkLeft = false;
    boolean checkRight = false;
    boolean mainPing = true;
    unsigned long servoTimer = millis();

    void setup(){
      Wire.begin();
      rtc.begin();
      pinMode(piezo, OUTPUT);
    pinMode(STBY1, OUTPUT);
      pinMode(aPWM1, OUTPUT);
      pinMode(ain11, OUTPUT);
      pinMode(ain12, OUTPUT);
      pinMode(bPWM1, OUTPUT);
      pinMode(bin11, OUTPUT);
      pinMode(bin12, OUTPUT);

      pinMode(STBY2, OUTPUT);
      pinMode(aPWM2, OUTPUT);
      pinMode(ain21, OUTPUT);
      pinMode(ain22, OUTPUT);
      pinMode(bPWM2, OUTPUT);
      pinMode(bin21, OUTPUT);
      pinMode(bin22, OUTPUT);

     servo.attach(12);
     for(int i=0;i<sizeof(leds)/sizeof(leds[0]);i++){
        pinMode(leds[i], OUTPUT);
     }

      pinMode(flamePin, INPUT);
      pinMode(photoResistor, INPUT);
      pinMode(temp, INPUT);
      pinMode(irGnd, OUTPUT);
      digitalWrite(irGnd, LOW);
      pinMode(irVcc, OUTPUT);
      digitalWrite(irVcc, HIGH);
      pinMode(irSignal, INPUT);
     Serial.begin(9600);
      irrecv.enableIRIn();
      digitalWrite(STBY1, LOW);
        digitalWrite(STBY2, LOW);
    servo.write(90);
    delay(200);
    }

    void loop(){

     counter=millis();
     //Serial.print("Millis1: ");
     //Serial.println(millis());
     if(irrecv.decode(&results)){
        translateIR();
        irrecv.resume();
      }
     // Serial.print("Millis2: ");
     //Serial.println(millis());
    if(drivingMode == 1){
       if(((counter-servoTimer) >= 150) && mainPing){
        ping();
        cm=duration/29.1/2;
        Serial.println(cm);
        counter=millis();
        servoTimer=counter;
      }
      if((cm<30) && mainPing){

        mainPing=false;
        checkRight = true;
        counter=millis();
        servoTimer=millis();
        servo.write(150);
        cm=30;

      }
      if(checkRight && !checkLeft && ((counter-servoTimer) >= 170)){

        ping();
        checkLeft=true;
        cm150 = duration/29.1/2;
        counter=millis();
        servoTimer=millis();
        servo.write(50);
      }
      if(checkRight && checkLeft && ((counter-servoTimer) >= 340)){
      checkRight=false;
      checkLeft=false;
      mainPing=true;
      ping();
      cm30 = duration/29.1/2;
      counter=millis();
      servoTimer=millis();
      servo.write(90);

      }

     }

    //getTime();
    //existsFire();
    /*if(!manualLeds){
    readPhoto();
    }*/

    }

    void readPhoto(){

      photoState = analogRead(photoResistor);
      if(photoState>600){
        ledAnalog=0;
      }
      else if(photoState<300){
        ledAnalog=255;
      }
      else{
        ledAnalog = 150 - photoState/4;
      }
      for(int x = 0;x<sizeof(leds)/sizeof(leds[0]);x++){
      analogWrite(leds[x], ledAnalog);
      }

    }

    void existsFire(){
    flameState = analogRead(flamePin);
    Serial.println(flameState);
    if(flameState <= 50){
      static boolean playingBuzzer = true;
      if(counter - prevMillis > piezoInterval){

         prevMillis = counter;
         playingBuzzer=!playingBuzzer;

      }
      if(playingBuzzer){

        digitalWrite(piezo, HIGH);

      }
      else{
        digitalWrite(piezo, LOW);
      }

    }
    else if(!playPiezo){
      digitalWrite(piezo, LOW);
    }
    else if(playPiezo){
      digitalWrite(piezo, HIGH);
    }

    }

    void checkTemp(){

      temperature = ((analogRead(temp) / 1024.0 * 5.0) - .5) * 100;
      Serial.println(temperature);

    }
    void ping(){

        digitalWrite(trig, LOW);
        delayMicroseconds(2);
        digitalWrite(trig, HIGH);
        delayMicroseconds(10);
        digitalWrite(trig, LOW);
        duration = pulseIn(echo, HIGH);

    }
    void getTime(){

      DateTime now = rtc.now();

      Serial.print(now.year(), DEC);
        Serial.print('/');
        Serial.print(now.month(), DEC);
        Serial.print('/');
        Serial.print(now.day(), DEC);
        Serial.print(" ");
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.print(':');
        Serial.print(now.second(), DEC);
        Serial.println();
    }
    void forward(){
    digitalWrite(STBY1, HIGH);
    digitalWrite(ain11, HIGH);
    digitalWrite(ain12, LOW);
    analogWrite(aPWM1, 255);

    digitalWrite(bin11, LOW);
    digitalWrite(bin12, HIGH);
    analogWrite(bPWM1, 234);

    digitalWrite(STBY2, HIGH);
    digitalWrite(ain21, LOW);
    digitalWrite(ain22, HIGH);
    analogWrite(aPWM2, 255);

    digitalWrite(bin21, LOW);
    digitalWrite(bin22, HIGH);
    analogWrite(bPWM2, 234);
    }
    void backward(){

    digitalWrite(STBY1, HIGH);
    digitalWrite(ain11, LOW);
    digitalWrite(ain12, HIGH);
    analogWrite(aPWM1, 255);

    digitalWrite(bin11, HIGH);
    digitalWrite(bin12, LOW);
    analogWrite(bPWM1, 235);

    digitalWrite(STBY2, HIGH);
    digitalWrite(ain21, HIGH);
    digitalWrite(ain22, LOW);
    analogWrite(aPWM2, 255);

    digitalWrite(bin21, HIGH);
    digitalWrite(bin22, LOW);
    analogWrite(bPWM2, 235);

    }
    void left(){

    digitalWrite(STBY1, HIGH);
    digitalWrite(ain11, HIGH);
    digitalWrite(ain12, LOW);
    analogWrite(aPWM1, 255);

    digitalWrite(bin11, HIGH);
    digitalWrite(bin12, LOW);
    analogWrite(bPWM1, 255);

    digitalWrite(STBY2, HIGH);
    digitalWrite(ain21, LOW);
    digitalWrite(ain22, HIGH);
    analogWrite(aPWM2, 255);

    digitalWrite(bin21, HIGH);
    digitalWrite(bin22, LOW);
    analogWrite(bPWM2, 255);

    }
    void right(){
    digitalWrite(STBY1, HIGH);
    digitalWrite(ain11, LOW);
    digitalWrite(ain12, HIGH);
    analogWrite(aPWM1, 255);

    digitalWrite(bin11, LOW);
    digitalWrite(bin12, HIGH);
    analogWrite(bPWM1, 255);

    digitalWrite(STBY2, HIGH);
    digitalWrite(ain21, HIGH);
    digitalWrite(ain22, LOW);
    analogWrite(aPWM2, 255);

    digitalWrite(bin21, LOW);
    digitalWrite(bin22, HIGH);
    analogWrite(bPWM2, 255);

    }
    void brake(){

    digitalWrite(STBY1, LOW);
    digitalWrite(ain11, LOW);
    digitalWrite(ain12, LOW);
    analogWrite(aPWM1, 0);

    digitalWrite(bin11, LOW);
    digitalWrite(bin12, LOW);
    analogWrite(bPWM1, 0);

    digitalWrite(STBY2, LOW);
    digitalWrite(ain21, LOW);
    digitalWrite(ain22, LOW);
    analogWrite(aPWM2, 0);

    digitalWrite(bin21, LOW);
    digitalWrite(bin22, LOW);
    analogWrite(bPWM2, 0);

    }
    void translateIR(){
    //Serial.println(results.value, HEX);
    switch(results.value){
    case 0xFF02FD:
    case 0x20DF22DD:
    //stop(ok)
    if(drivingMode==0){
    brake();
    //Serial.println("brake");

    }
    break;
    case 0xFF629D:
    case 0x20DF02FD:
    //forward
    if(drivingMode==0){
    forward();
    //Serial.println("forward");
    }
    break;
    case 0x20DF827D:
    case 0xFFA857:
    //back
    if(drivingMode==0){
    backward();
    //Serial.println("back");

    }
    break;
    case 0xFF22DD:
    case 0x20DFE01F:
    //left
    if(drivingMode==0){
    left();
    //Serial.println("left");
    }
    break;
    case 0x20DF609F:
    case 0xFFC23D:
    //right
    if(drivingMode==0){
    right();
    //Serial.println("right");

    }
    break;
    case 0xFF6897:
    case 0x20DF8877:
    if(drivingMode==0){
      brake();
      drivingMode=1;
    }
    else{
      brake();
      servo.write(90);
      drivingMode=0;
    }
    //1(switch driving mode)
    break;
    case 0xFF9867:
    case 0x20DF48B7:
    //2(switch led mode)
    if(!manualLeds){
    manualLeds=true;
        for(int x = 0;x<sizeof(leds)/sizeof(leds[0]);x++){
      digitalWrite(leds[x], LOW);
      }
    }
    else{
    manualLeds=false;
    }

    break;
    case 0xFFB04F:
    case 0x20DFC837:
    if(manualLeds){
      if(!ledsOn){
        for(int x = 0;x<sizeof(leds)/sizeof(leds[0]);x++){
      digitalWrite(leds[x], HIGH);
      }

      ledsOn=true;
      }
      else{
           for(int x = 0;x<sizeof(leds)/sizeof(leds[0]);x++){
      digitalWrite(leds[x], LOW);
      }
      ledsOn=false;
      }
    }
    //3(toggle leds if mode is on)
    break;
    case 0xFF30CF:
    case 0x20DF28D7:
    //4(play sound)
    playPiezo = !playPiezo;

    }

    }

EDIT 2:

I decided to see what will happen if I start removing code. I removed most of the code that I did not need for this experiment. After the removal, the issue persisted. The sensor is still giving me 0s. This is all the code that was left after I removed stuff:

    #include <Servo.h>

    //RTC_DS1307 rtc;

    /*const int blue2 = 12;
    const int blue1 = 11;
    const int red1 = 10;
    const int red2 = 9;
    */
    Servo servo;

    unsigned long counter;

    unsigned long prevMillis = 0;

    int piezoInterval = 200;

    int drivingMode = 0;

    boolean playPiezo=false;

    #define trig 22
    #define echo 24
    long duration;
    boolean turned150 = false;
    int cm30, cm, cm150;
    bool checkLeft = false;
    boolean checkRight = false;
    boolean mainPing = true;
    unsigned long servoTimer = millis();

    void setup(){

     servo.attach(12);
    /* for(int i=0;i<sizeof(leds)/sizeof(leds[0]);i++){
        pinMode(leds[i], OUTPUT);
     }
    */
     Serial.begin(9600);

    servo.write(90);
    delay(200);
    }

    void loop(){

     counter=millis();
     //Serial.print("Millis1: ");
     //Serial.println(millis());
    /* if(irrecv.decode(&results)){
        translateIR();
        irrecv.resume();
      }*/
    //  Serial.print("Millis2: ");

    if(drivingMode == 0){
       if(((counter-servoTimer) >= 150) && mainPing){
        ping();
        cm=duration/29.1/2;
        Serial.println(cm);
        counter=millis();
        servoTimer=counter;
      }
      if((cm<30) && mainPing){

        mainPing=false;
        checkRight = true;
        counter=millis();
        servoTimer=millis();
        servo.write(150);
        cm=30;

      }
      if(checkRight && !checkLeft && ((counter-servoTimer) >= 170)){

        ping();
        checkLeft=true;
        cm150 = duration/29.1/2;
        counter=millis();
        servoTimer=millis();
        servo.write(50);
      }
      if(checkRight && checkLeft && ((counter-servoTimer) >= 340)){
      checkRight=false;
      checkLeft=false;
      mainPing=true;
      ping();
      cm30 = duration/29.1/2;
      counter=millis();
      servoTimer=millis();
      servo.write(90);

      }

     }

    //getTime();
    //existsFire();
    /*if(!manualLeds){
    readPhoto();
    }*/

    delay(2);
    }

    //}
    void ping(){

        digitalWrite(trig, LOW);
        delayMicroseconds(2);
        digitalWrite(trig, HIGH);
        delayMicroseconds(10);
        digitalWrite(trig, LOW);
        duration = pulseIn(echo, HIGH, 24000L);

    }

Maybe this means that the issue is within this remaining code. Of course I will need all of the code that I removed for the final project, but I was just trying to debug.

I made my code a lot more concise since the posted code draft, but the ultrasonic sensor still gives me 0s. I do not understand what can affect its performance as it works fine in my other sketch.

I tried connecting the sensor to an external 5 volt power source and the same thing happened. The reason for the issue is not because if my power source.

I used to have a small delay at the end of my code and I removed that in order to make it run faster. Since pulseIn is blocking for 24ms, the delays do not affect it and it should work normally. But it does not.

Also, the sensor is giving 0s not because the target is too far away. Even if I put my hand close, it still gives 0s. If I make the cm equal 400 if the duration equals 0, the cm are always 400 regardless of the distance from the sensor.

body:
> Why does the same block of code act differently in different sketches?

There are different interrupt sources in the sketches that may affect pulseIn(). Try using a more advanced method to measure the pulse width such as Timer Capture.

Cheers!


body:
`pulseIn()` may block up to **1 second** (by default), which would happen everytime the **HC-SR04** receives no echo, which might be the case if ultrasounds do not get properly reflected on a flat surface or if the nearest echoing surface is over ~4 meters away from it.

In this situation, not only would `pulseIn` block for one second, but it would also return `0` to indicate the pin never changed level during that time (which can explain the **0cm distance** you calculated).

Since the **HC-SR04** range is maximum 4 meters, the max ultrasound distance echoed should be then less than 8 meters. Under normal atmospheric conditions, sound propagates at **~340m/s**, that means in the worst case, i.e. an obstacle found 4 meters away, the sound roundtrip should take less than **8/340s**, i.e. **~24ms** rounded up.

This shows it is pointless to have `pulseIn` wait for 1 second, where 24ms would be enough. To tell `pulseIn` to use a shorter timeout, just pass it an extra argument:

    duration = pulseIn(echo, HIGH, 24000L);

Note that timeout must be expressed in **us**.

Then, in other parts of your code, before using `duration`, you should check that it is not `0` (which means no obstacle found less than 4 meters away), for example you might consider in this case the distance is 4 meters (or anything larger).

E.g. you could replace:

    cm150 = duration/29.1/2;

with:

    cm150 = duration == 0 ? 400 : duration/29.1/2;

Since this calculation is found several times you should probably create a function for it, that would improve code maintainability and maybe code size as well.


body:
In the `setup()` function add a `setPin(echo, INPUT)` statement.

**UPDATE**

Have you checked the wiring? A loose connection of either the `trig` or `echo` pins would cause this behavior.

I know it might seem obvious, but double checking continuity between the Arduino pins and the HC-SR04 module with a basic multimeter (while your board is not powered) is not going to hurt, right?


message:
Is there any way to prevent Arduino CLI from closing each time?

I prefer writing code in Vim, so I'd like to get a workflow going with the Arduino CLI. I used to use [`ino`](http://inotool.org), but I didn't like the restructuring of the project, which meant anyone who downloaded the code having to use `ino`.

I can build and verify using `/Applications/Arduino.app/Contents/MacOS/Arduino --verify MyProject.ino`, which pops up a new instance of the Java IDE, then exits after verifying.

While this works, and works well, it's incredibly slow. Is there any way to keep the IDE open to save the few seconds lost from the IDE starting again?

body:
> Is there any way to prevent Arduino CLI from closing each time?

I would suggest working the other way around.

1. Start the Arduino IDE and set external editor in the Preferences (once).
2. Open the sketch file(s) in the Arduino IDE and VIM.
3. Edit the sketch file(s) in VIM.
4. Move to the Arduino IDE and Verify, Upload, Monitor, etc.
5. Repeat steps 3-4.

The alternative is to use a make based build system. An example may be found in the [Cosa build system for Linux][1].

Cheers!

PS: VIM = any external editor such as GNU Emacs, TextEdit, etc.

  [1]: https://github.com/mikaelpatel/Cosa/tree/master/build/Arduino-Makefile


message:
Weird OneWire bus problem

I have two DS18B20 temperature sensors connected via a OneWire bus to an arduino. I noticed that these sensors get hot, when permanently powered and decided to just turn them on for measurment.

First attempt: Define a pin as output and feed the sensors. Because I received only one value (first sensor on bus), I assumed that the current delivered may not be high enough and utilized a transistor (+resistor) as switch for the main 5V line to feed the sensors from the mains (as before). The result is the same. I only get the value of the first sensor. When I connect the sensors directly, I get both values.

I tried up to 4 seconds delay after switching the bus on and again after reading the values (before switching the bus off again), with no luck. Only the first sensor answers.

Do I have a timing or a current problem here?

**UPDATE**

Wiring (working): Two DS18B20 in parrallel with a 4,7k resisor between `DATA` and `VIN`. One Arduino pin used, Sensors directly powered by power-supply (same as arduino)

Wiring (not working): Broke the `VIN` line and added a transistor as switch between power-supply and sensors `VIN`. Used a second pin and a resistor to power up the line.

The transistor is a `TC124E` (npn) logic level transistor. I have the feeling, that this boy is not providing enough current to the sensors, which in addidtion have five meter cables attached...

**UPDATE II**
It is not the current. I replaced the transistor with a mosfet (70T03H) and the result is exactly the same: When switched, only one sensor answers . When I connect the gate directly to a +5V line, I get both values as expected.

Kinda think, that the switching of the pin irritates the bus or the specific device.

**UPDATE III (Solution)**

I tracked this down to a mixture of

* Different resolution settings on the sensors
* my code not waiting long enough to get the sensor with the higher resolution to setup (on-to-read time). Giving the bus slightly more time to setup before any reading is accepted, solved my problem.

body:
If you were trying to wire your bus in parasitic mode, here is what I am using:

    OneWire Bus in parasitic mode:

    +------------+     +5v            +---------+     +---------+
    |    MCU     |      |             | DS18b20 |     | DS18b20 |
    |            |  R_pu = 4.7K       | g  d +5 |     | g  d +5 |
    | Strong-    |      |             +-o--o--o-+     +-o--o--o-+
    | Pullup   > o------o               |  |  |         |  |  |
    |            |      |               +--|--+         +--|--+
    |            |      |               |  |            |  |
    |    Data <> o------o---------------|--o------------|--o------ - - -
    |            |                      |               |
    +------------+                      V               V

I run at least three sensors this way on an approximately 6 meter bus, completely reliably.


message:
How can I define a port extender MCP23s17 pin in Arduino

My task is to use a port extender (MCP23s17) to drive a touch keypad for which I have to define names of pins so that I can call those names in arguments of a function.

I have searched for different methods to define "PORT EXTENDER" pin but could not find any satisfactory results. Kindly help me handle the situation.

i have used the following libraries downloaded from Arduino playground
1. CapacitiveSensor.h
2. MCP23S17.h
Now I have to use MCP23S17 Pin in the following function

    #define key1 2
    #define key2 4
    CapacitiveSensor cs_4_2=Capacitivesensor(key2,key1);  //capacitive sensor is connected to pin 4 and 2

key1 and key2 are Arduino's pins. I want some method by which I can refer key1 and key2 to the port extender's (MSP23S17) pin. The above answers are surely helpful but they doesn't fulfill my requirement.

Thanks in Advance
Sorry for English.

body:
If you use this [arduino library](http://playground.arduino.cc/Main/MCP23S17#pinMode):

    #define LED_PIN 15

    mcp.pinMode(LED_PIN, LOW); //set led pin on the MCP23S17 to an OUTPUT

    mcp.digitalWrite(LED_PIN, LOW)


body:
If you are using [my library](https://github.com/MajenkoLibraries/MCP23S17) you can do something like:

    MCP23S17 expander1(&SPI, 10);

    #define LED_PIN expander1, 15

    void setPin(MCP23S17 &expander, int pin, bool level) {
        expander.digitalWrite(pin, level);
    }

    // ... later ...

    setPin(LED_PIN, HIGH);


body:
There is also the [Adafruit][1] Library, all do similar things, just in a slightly different way. I use this one, it just depends on which method you are most comfortable with and what your requirements are. Try them all and find out.

    void setup() {
      Serial.begin(9600);  // debugging
      mcp.begin();      // use default address 0

          for(int i = 0; i < 6; i++) {
            mcp.pinMode(trafficLights1[i], OUTPUT);
          }
           for(int i = 0; i < 6; i++) {
            mcp.pinMode(trafficLights2[i], OUTPUT);
           }
            for(int i = 0; i < 5; i++) {
            mcp.pinMode(trafficLights3[i], OUTPUT);
            }
      for (int P=0;P<16;P++) {
        mcp.pullUp(P, HIGH);  // turn on a 100K pullup internally
        mcp.digitalWrite(P,LOW);
     }
          mcp.digitalWrite(11, HIGH);
    }

  [1]: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library


message:
OOP vs procedural programming on arduino

It seems like the majority of Arduino applications are written without using classes / objects. Is there a reason for this? Does is slow down the Arduino or somehow present undesirable behavior?

body:
Your assumption is quite wrong:

* The majority of libraries use OOP.
* The majority of in-built device drivers use OOP.
* The core is filled with many OOP helper objects and classes.
* 99.99% of all sketches use those OOP objects.

The sketches themselves may not be written as a class or set of classes for a number of reasons:

1. There is no point
2. The programmer doesn't know how

When a sketch is just stitching together calls to objects defined through libraries and making a few decisions there is little point in making the sketch itself an object. It's just a waste of time.  In general if the sketch gets too complex to manage it gets broken down into smaller units - i.e., libraries - which are very often written as classes.

The moment you do `Serial.begin(9600);` you are using OOP.


message:
Arduino zero Error: unable to find CMSIS-DAP device

I am uploading a test sketch(Blink) to my new Zero(with Wifi101 shield) and when I press Upload in the IDE, the Console says the following:

Arduino: 1.6.10 (Linux), Board: "Arduino/Genuino Zero (Programming Port)"

    Open On-Chip Debugger 0.9.0-gd4b7679 (2014-10-03-00:26)
    Licensed under GNU GPL v2
    For bug reports, read
     http://openocd.org/doc/doxygen/bugs.html
    debug_level: 0
    adapter speed: 500 kHz
    adapter_nsrst_delay: 100
    cortex_m reset_config sysresetreq
    Error: unable to find CMSIS-DAP device
    Error: No Valid JTAG Interface Configured.
    Error: No Valid JTAG Interface Configured.

I am using the Zero programming port.

body:
I had exactly the same error with the same board. Running the IDE as root solved the problem. So, Chris was right pointing out a permission issue.

I found more information here : http://bitofahack.com/post/1437909576

Then I added the file `/etc/udev/rules.d/98-openocd.rules` :

    ACTION!="add|change", GOTO="openocd_rules_end"
    SUBSYSTEM!="usb|tty|hidraw", GOTO="openocd_rules_end"
    ATTRS{product}=="*CMSIS-DAP*", MODE="664", GROUP="plugdev"
    LABEL="openocd_rules_end"

I then ensured that I was member of group `plugdev`.

`udev` looks for changes in his rules directory so you don't have
to restart it.

I plugged the board again and it worked.

Note that you can force udev to read the rule files again by entering :

    sudo udevadm control --reload

I had to do this because I first made a mistake in the rule file.

Hope this helps.


message:
How does Arduino decide when to go into flashing mode and normal mode?

Just this general question.As the titles says.

How does Arduino decide when to go into flashing mode and normal mode?

Is it by connecting certain pins to ground,so it's a hardware check or does it have to do with the code?

Other similar arduino like products such as the esp8266 work the same way as long as they use the same chip?

body:
It first runs the bootloader. If there is no data coming into the serial connection within a certain amount, i.e. it's not being programmed, it will exit the bootloader and start the actual sketch.

In the UNO you will notice a 3 second delay between providing power, and your sketch starting.


message:
How to split a string into substring Arduino

I'm about identify myself stupid, howcome I couldn' t figure out how to split a string into substring using arduino, even after 10 days of searching. The number is fact... So, As Mr.Arduino.cc says: *string*.substring() is just can be used as conditional phrase with loops like if. and there is no method such strtok() like in C can help me with this. So guys, I' m bagging you for help, please!

    if (ks > 255 * 60)
                {
                        vek.print("Bu yazı, ", 25, 0);
                        vek.printNumI(255*60, 25, 8);
                        vek.print("karakterd-", 25, 16);
                        vek.print("en uzun ol", 25, 24);
                        vek.print("dugundan", 25, 32);
                        vek.print("gosterlemz", 25, 40);
                }

    for (byte i = 0; i <= ss ; i ++)
                {
                        for (byte j = 0; j <= 6; j++)
                        {
                                int ilk_kar = j * 10 + i * 60;
                                int son_kar = ilk_kar + 10;

                                String yaz=readString.strtok(ilk_kar,son_kar);

                                vek.print(yaz, 25, j);

                                if (analogRead(A5) == 1023)
                                {
                                        continue;
                                }
                                else
                                {
                                        break;
                                }
                        }
                }
        }
    }

Error: sketch_aug22a.ino: In function ‘void loop()’:
sketch_aug22a.ino:83:56: error: ‘class String’ has no member named ‘strtok’

What am I supposed to do?

Thanks, already...

body:
Import the *string.h* library by adding `#include <string.h>` on top of your sketch, in order to use the `strtok()` function.
Checkout the usage example of `strtok()` here: http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok


message:
Arduino nano digital pins not working with external power source

We are using an Arduino Nano for simple serial comms to fire a relay from a Windows 10 PC.

Initial issue we had was windows not recognizing the device (COM Port) when the pc is powered off (as per this link: [Arduino Nano - USB not present after reboot][1] ) so we powered the arduino nano over a 5V pin and now when Windows starts up the device is recognized.

However, as I'm learning with these chips, nothing is ever that simple. Now the relay that we are firing does not work with external power, but if you unplug the external power then the relay does fire (powered over USB)

The units are at a mine and at the moment and I believe that the problem is that the serial chip is now not responding as per this - from the official Arduino Nano page:

*The FTDI FT232RL chip on the Nano is only powered if the board is being powered over USB. As a result, when running on external (non-USB) power, the 3.3V output (which is supplied by the FTDI chip) is not available and the RX and TX LEDs will flicker if digital pins 0 or 1 are high.*

Note - I included the above from another question but this no longer appears on the official arduino nano page (can't past link as it's my first post)

The question is how can we get the digital pins on the arduino nano to fire using an external power source and input from a Windows PC?

Thanks

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

  [1]: https://electronics.stackexchange.com/questions/74123/arduino-nano-usb-not-present-after-rebootn
  [2]: https://i.stack.imgur.com/zhH2X.png

body:
I think you may need to back up and start over again.

Rather than changing the power supply, you need to fix the problem that made you think you needed to change power supplies.

Following a link in a comment on the [question you linked](https://electronics.stackexchange.com/questions/74123/arduino-nano-usb-not-present-after-rebootn)  to leads to [this thread on the Arduino forums.](http://forum.arduino.cc/index.php?topic=23025.0)

The suggestion there is that a particular pin on the FTDI chip on the Nano isn't connected as it should be.

To be exact, the Test pin ([pin 26 on the FT232RL chip](https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf)) needs to be grounded to fix the original problem you were having with communications with the Nano.

The description there fits your description.  The Nano can't talk to the PC if the Nano is connected to the PC at power on.  The same thing happens with the circuit referenced in that Arduino forum thread, but they are using another embedded system instead of a PC.

If you fix that, then you won't need to use an external 5V supply.

To back up the conclusion from the Arduino forum, here's an excerpt from page 8 (pin descriptions) of the [FT232RL datasheet:](http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf)

> 26 TEST   Input  Puts the device into IC test mode. Must be tied to GND
> for normal operation, otherwise the device will appear to fail

You need to connect pins 25 (ground) and pin 26 (Test.)

Excerpt from the Nano schematic:
[![enter image description here][1]][1]

Pins 25 (ground) and 26 (Test) are right next to one another, so easy to fix.

You need to put a blob of solder on the red marked spot in this picture:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/XaPqA.png
  [2]: https://i.stack.imgur.com/ovzQJ.png


body:
I accepted the answer from JRE as I believe this is the best answer. For certain reasons we weren't able to do this so I've posted this as a workaround.

We ended up splitting the USB input to the arduino nano by using a Y cable. We used the one end for the power to the device and the other end for comms from the PC (with power disabled). This solved our issue as the chip now received power and responded to comms and the USB driver also initialised correctly on Windows when starting up.

If you are unable to solder the chip then this is a workaround that we have used.


message:
Why do my temperature sensor values become inconsistent when additional hardware is added to the board?

I have this strange problem. My TMP 36 sensor works fine when it is the only thing connected to my Arduino Uno board. The voltage measurements, and thus the temperature, are accurate and consistent. However, when I attach an LCD screen to the Uno and have a program print the TMP's measurements to the screen, the values become inconsistent, and can change up to 10 degrees F from one reading to another. (I have the sensor take a measurement every second.) This does not happen when the LCD screen is not plugged in. I decided to remove separate connectors from the screen and see when the measurements became consistent again. I tried this once and found that a ground wire that goes to connection 5 on the screen caused to value to change when I repeatedly inserted and removed it from a ground pin. The TPM values were changing even when there was nothing else connected to the LCD (it wasn't on) except for the ground wire. I don't understand how this is possible, and I don't know if this is a hardware or software issue.

I rewired the LCD screen starting with sensor wires, then ground wires, and then the two 5V connections, with one of them having a 220 ohm resistor. I did this while the circuit was powered, and watched the values for any large changes. The first change was a few seconds after I wired the last 5V wire. The sensor measured 80 degrees F and then 85 degrees F one second later. It then went to 81 for a few seconds, then 87. The values continued to change, but not by as much as previous times. By the way, the temperature in the area that the Arduino is in is about 82 degrees F.

TMP values do not change by more than 3 degrees F when the LCD is not connected to the screen. I don't understand what could be causing this. Has anyone else had this problem before, or know the cause?

Here is [the layout][1].

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12,11,5,4,3,2);
    const int sensorPin = A5;
    const float baselineTemp = 20.0;

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

    void loop() {
      int sensorVal = analogRead(sensorPin);
      Serial.print("Sensor value: ");
      Serial.print(sensorVal);
      float voltage = (sensorVal / 1024.0) * 5.0;
      Serial.print(", volts: ");
      Serial.print(voltage);
      Serial.print(", degrees C: ");
      float temperature = (voltage - .5) * 100;
      Serial.print(temperature);
      Serial.print(", degrees F: ");
      float fahrenheit = (temperature * 1.8 + 32);
      Serial.println(fahrenheit);
      delay(1000);
      lcd.begin(16,2);
      lcd.print(fahrenheit);
      lcd.print(" degrees F");
      float averageTemp;
      if(temperature < baselineTemp) {
        lcd.setCursor(0,1);
        lcd.print("Below room temp");
      }
    }

  [1]: http://fritzing.org/projects/tmp-and-lcd

body: Don't take power for LCD from Uno pins. Connect LCD power to separate power source.


body: I don't see +5v -> Aref (and Aref -> bypass capacitor -> Gnd). Necessary, if you are using the power supply voltage as a reference, as you appear to be.


body:
For an analog sensor like the TMP36, the Arduino uses the 5V as reference. If the 5V changes (but the TMP36 voltage stays the same), the Arduino thinks that the temperature has changed. The value returned by analogRead() increases. That is why the temperature seems to raise if the 5V is lowered.

The TMP36 (with resistor) outputs a certain voltage. That is different from 'ratiometric' sensors, they output a voltage relative to the 5V, and changes to the 5V have no effect on the result. A 'ratiometric' sensor is for example a wheatstone bridge, or a LDR with resistor.

With the TMP36, you need a good voltage reference to read the actual voltage. The internal voltage reference can be used. Perhaps an extra voltage divider is needed. Or use a power supply to the power barrel jack and let the onboard voltage regulator create a fixed voltage of 5V which can be used as reference.

When using digital temperature sensors, like the DS18B20, all these problems are gone instantly.

The 5V should never be connected to AREF. It is already internally connected to VCC at default, and when the internal voltage reference is selected, the AREF pin changes the voltage. In that case, an internal shortcut is created when AREF is connected to 5V. There is no need to add 100nF to AREF, since the Arduino Uno has already 100nF to AREF and GND.

A breadboard can have bad contacts. Since the current of the LCD uses the same GND and +5V wires, it can have influence on the TMP36. It is better to use seperate wires as already mentioned by Chris Stratton. To reduce noise you could take a number of analogRead() values and use the average. For an analog temperature sensor it is common practice to average a number of samples.


body: Try powering your circuit using a 9V battery. I have also had this problem and it worked when I used a separate power supply. It seems to be an electrical noise caused by your computer USB. The answer posted by JRobert should be necessary if you want to power from the computer.


body: I had this issue and put a 0.1 µF capacitor across the sensor and got much reduced noise (to within half a degree which is really +- one tick).


message:
HTTP Post not working

I am wanting to POST some data from Arduino to WebService (written in .NET), intending to save some temperature data to MS SQL Server.

My code in arduino is:

    void PostarDados(String dados, String chamador) {
      if (client.connect("mysite.com.br",80)) {
        client.println(chamador);
        client.println(F("Host: mysite.com.br"));
        client.println(F("Content-Type: application/x-www-form-urlencoded"));
        client.print(F("Content-Length: "));
        client.println(dados.length());
        client.println();
        client.println(dados);
      }
      if (client.connected()) client.stop();
    }

When sending to Serial instead of client, I am obtaining the following text:

    POST /webservice.asmx/SetValoresTempUmidade HTTP/1.1
    Host: mysite.com.br
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 39

    Chave=1&Temperatura=23.30&Umidade=42.20

I have enabled HTTP POST in web.config to make HTTP POST possible (I can successfully invoke webservice from browser):

      <location path="Webservice.asmx">
        <system.web>
          <webServices>
            <protocols>
              <add name="HttpGet"/>
              <add name="HttpPost"/>
            </protocols>
          </webServices>
        </system.web>
      </location>
      <system.webServer>
        <httpProtocol>
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
          </customHeaders>
        </httpProtocol>
      </system.webServer>
    </configuration>

I have also set `ScriptMethod` to my webservice functions:

    <WebMethod()> <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
    Public Sub SetValoresTempUmidade(Chave As Integer, ByVal Temperatura As Double, ByVal Umidade As Double)
        Dim ctx As New DataClassesDataContext
        Try
            Dim A As New TBL_DADO
            A.CHAVE_INICIO = Chave
            A.DATA = Now
            A.TEMPERATURA = Temperatura
            A.UMIDADE = Umidade
            ctx.TBL_DADOs.InsertOnSubmit(A)
            ctx.SubmitChanges()
        Catch ex As Exception
        End Try
    End Sub

Finally, I am trying to get some response from server using the following code (not receiving anything):

    while (client.connected()) {
      while (client.available()) {
       buffer[counter++] = client.read();
      }
    }

Explained that, I have two questions:

 1. What am I doing wrong?
 2.  How could I debug this?

body:
Using

    byte server[] = {XX, XX, XX, XX}; //IP
    if (client.connect(server,80)) {

instead of

    if (client.connect("mysite.com.br",80)) {

worked


message:
how to use capacitive touch keypad without using CapacitiveSensor.h Library

i want to use multiple capacitive touch keypads with arduino uno but number of IO ports are not enough. So I decided to use MSP23S17 port extender. Now i have to find some methods to sense the touch keypad without using its library. Can anyone tell me if there is any way to do the task.

body: Here's one: Microchip mtch6102, though it might be a little more complex than you're looking for.  All the others I found with a quick search were surface mount or single button controllers.  You might be able to multiplex a single button controller like the Atmel AT42QT1011, but I don't know what the settling or reset times are.  It may take to long to change pads, reset the chip, then wait for settling/calibration time (if any).


message:
max7219 chained display showing text only on the first display

I'm using a max7219 like this one [max7219][1]. When I first tested my circuit, I used an 8x8 display and the code worked just fine. Now, after I modified the code and changed the display with the chained one, the text is showing only on the first matrix. I've seen someone that had another problem with the same matrix module, only that in his case the same text was printed on all the matrixes [unsolved problem][2], in the end he didn't find a solution. Below, I'll attach my code. Please help me find the problem.

    //Pin connected to ST_CP of 74HC595
    int latchPin = 6;
    //Pin connected to SH_CP of 74HC595
    int clockPin = 7;
    ////Pin connected to DS of 74HC595
    int dataPin = 5;

    int period = 30;

    byte rotl(byte n, byte b)
    {
      return (n << b) | (n >> (8 - b));
    }

    byte X[] {

    0x80,
    0x80,
    0x80,   //L
    0x80,
    0x80,
    0x80,
    0x80,
    0xFF,

    /*0x10,
    0x00,
    0x10, //I
    0x10,
    0x10,
    0x10,
    0x10,
    0x10,

    0XF0,
    0x90,
    0x80, //C
    0x80,
    0x80,
    0x80,
    0x90,
    0xF0,

    0xF0,
    0x09,
    0x09,
    0x09,
    0x09,
    0x09, //A
    0x09,
    0xF0*/

    };

    void setup() {
      //set pins to output so you can control the shift register
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
    }

    void loop()
    {
      for (int i = 0; i < 8; i++)
      {
        X[i] = rotl(X[i], 1);
      }
      for(int i = period;i>0;i--)
      {
        displayX();
      }

    }

    void DisplayMatrix(byte numCol, byte numLine)
    {
      byte numberToDisplay1 = numCol;
      byte numberToDisplay2 = numLine;

      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay1);
      shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay2);
      digitalWrite(latchPin, HIGH);
      delay(1);

    }

    void displayX()
    {
       DisplayMatrix(X[0],1);
       DisplayMatrix(X[1],2);
       DisplayMatrix(X[2],4);
       DisplayMatrix(X[3],8);
       DisplayMatrix(X[4],16);
       DisplayMatrix(X[5],32);
       DisplayMatrix(X[6],64);
       DisplayMatrix(X[7],128);
    }

  [1]: http://www.aliexpress.com/item/MAX7219-Dot-Matrix-Module-For-Arduino-Microcontroller-4-In-One-Display-with-5P-Line/32637207300.html?spm=2114.30010308.3.1.1iTpoC&ws_ab_test=searchweb201556_10,searchweb201602_5_10057_10056_10055_10049_10017_10059_10058_10060_10061_10062_412_10063,searchweb201603_7&btsid=7c7446b0-8328-4abd-b0d9-6d20abc0b98a
  [2]: http://forum.arduino.cc/index.php?topic=402935.0

body:
Communicating with more than one MAX7219 chip when cascaded involves sending data to all the chips at once. You have to treat the cascaded sequence of chips as a single entity - an entire display in its own right.

With one chip you send an 8-bit register value followed by an 8-bit data value. To use two chips you have to send twice that - an 8-bit register and 8-bit data for the second chip, followed by an 8-bit register and 8-bit data for the first chip.

The chips have a "NO-OP" register (0x00) which can be used to ensure that nothing is done on that chip if you don't want to change anything.

So setting line 3 to 0x55 on the first display, and line 5 to 0xAA on the second display you would send the sequence `\ 0x05,0xAA,0x03,0x55 /` as a single transaction (lower CS `\` before, raise it `/` afterwards).

If you only wanted to set line 2 on the second display to 0x69 you would send the sequence: `\ 0x02,0x69,0x00,0x00 /`

For three chips you need to send three blocks of 8+8 values. For four chips, 4 blocks of 8+8. Etc.

Note that it is important to send enough data for *all* the chips - you can't shortcut and only send data for the first display if that is all you want to talk to, since whatever is currently in the first display's shift register will get sent out to successive chips, and you will get the display duplication as seen in the other question.


message:
Arduino Wire.h library: how to communicate with an LCD?

I am having an Arduino Uno and a C2042A LCD with I2C shield on it. Because the VirtualWire library does not work for me. I tried only the wire library but it's still not working:

My code:

    #include <Wire.h>

    void setup() {
      Wire.begin(0x63);
    }

    void loop() {
      Wire.write(4);
    }

I just read on [this website][1] which commands you have to use but it doesn't do anything. What is my fault, how to solve it?

  [1]: http://www.robot-electronics.co.uk/htm/Lcd03tech.htm

body: The documentation under the link you posted says: "The I2C display is located on the I2C bus at an address of 0XC6.", not the address you have used in your code.


body:
SOLVED!

I forgot to write `beginTransmission()`. Here's my code:

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

    #include <Wire.h>

    void setup() {
      Wire.begin(0x63);
    }

    void loop() {
      Wire.beginTransmission(0x63);
      Wire.write(byte(0x00));
      Wire.write("Temperatur:");
      Wire.endTransmission();
    }


body:
You can't begin writing unless you first initialize it like with Serial.begin

In this case you don't show Wire.beginTransmission.

Perhaps it is in the code you didn't show us, but it is required.


message:
Can MP3 be sent to SPI of Adafruit Music Maker Arduino shield instead of from its SD card?

Can uncompressed MP3 audio data be sent from Arduino board, by SPI, to Adafruit Music Maker shield instead of from the SD card on the Music Maker?

Instead of using SD card on Music Maker board, I want to send the compressed MP3 data from a Particle Photon board on the Particle shield shield, by SPI, to the VS1053B codec chip on Music Maker board, and then to amplifier for speakers.

Particle Shield Shield is attached to Particle Photon board, which has STM32F205RGY6 120Mhz ARM Cortex M3.

Particle Photon board uses its WiFi to receive uncompressed MP3.

body:
As far as I can see the SD card on the shield isn't read by the VS1053 directly, but by the arduino, which sends it to the VS1053.

So as far as I can see, you should be able to do what you want.


message:
Is Adafruit Arduino Feather M0 WiFi compatible with Adafruit Music Maker shield?

I want Arduino to receive MP3 by WiFi (from iPhone), and then send to Music Maker codec and amplifier.

I want to use Arduino IDE and library software from Adafruit for the Music Maker, so I need an Arduino board 100% compatible with the library for Music Maker.

body: No, it is not.  Adafruit Feather boards are only compatible with Feather 'wings' and not Arduino shields.


message:
What SMS can send to switch LED?

I have code but I don't know how to send SMS from my Mobile
I mean what the message I can send to switch the Led?
To switch On or Off.
I use SIm900
and use this code

    #include <SoftwareSerial.h>

     char inchar; // Will hold the incoming character from the GSM shield
     SoftwareSerial SIM900(7, 8);

     int led = 10;

     void setup()
     {
       Serial.begin(19200);
       // set up the digital pins to control
       pinMode(led, OUTPUT);
       digitalWrite(led, LOW);

       // wake up the GSM shield
       SIM900.begin(19200);
       delay(20000); // give time to log on to network.
       SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
       delay(100);
       SIM900.print("AT+CNMI=2,2,0,0,0\r");
       // blurt out contents of new SMS upon receipt to the GSM shield's serial out
       delay(100);
       Serial.println("Ready...");
     }

     void loop()
     {
       //If a character comes in from the cellular module...
       if(SIM900.available() >0)
       {
         inchar=SIM900.read();
         if (inchar=='#')
         {
           delay(10);

           inchar=SIM900.read();
           if (inchar=='a')
           {
             delay(10);
             inchar=SIM900.read();
             if (inchar=='0')
             {
               digitalWrite(led, LOW);
             }
             else if (inchar=='1')
             {
               digitalWrite(led, HIGH);
             }
             delay(10);
             // SIM900.println("AT+CMGD=1,4"); // delete all SMS
           }
         }
       }
     }

body: The code appears to be looking for an SMS that says `#a0` or `#a1`. The logic doesn't look very robust, though. It reads a character, then waits 10ms and tries to read another. What does `SIM900.read()` do if there is no next character? Will it return something? Or wait until there is another? If it waits, the code can get out of sync with incoming, badly-formed commands.


message:
Arduino I2C long string

I am trying to get 2-Arduinos passing data. The Master will request the data and the Slave send it. But, the length of the string the Slave will send is unknown each cycle.

I found some things here on writing strings with I2C but it seems it is limited to 32 bytes no matter what the Master requests. How can I get the full string sent each time?

Master makes request for string that could be about 180 bytes max - ever.

    Wire.requestFrom(8,200);  // I2C-ID = 8, Length = 200
    while (Wire.available())
    {char c = Wire.read();
    cmdInStr.concat(c);
    }

Slave sends

    int len = cmdOutStr.length()+1;
    char ascii_num[len];
    for (int i=0; i<len; ++i)
    { Wire.write(ascii_num[i]);
    }

body:
There is no maximum length for sending/receiving in I2C. It is the Wire library `BUFFER_LENGTH 32` macro, causing this limitation.

You can either copy some code from Wire library and implement your own `requestFrom` function which will store data directly to your `cmdInStr` string buffer or you can change Wire.h to have bigger `BUFFER_LENGTH`.

Or another way is to extend Wire.h like this:

    #ifndef BUFFER_LENGTH
    #define BUFFER_LENGTH 32
    #endif

and in your sketch:

    #define BUFFER_LENGTH 180
    #include <Wire.h>

All depends on your preferences, but implementing own requestFrom and storing it directly into your `cmdInStr` buffer will be little bit more efficient than copying it into Wire buffer and then into your own buffer again.

And do you really need all these data in one string, isn't it possible to proceed it on the fly?


body:
You can only send and receive fixed length amounts of data with I2C. The master has to know how much to request from the slave - or the slave to accept from the master.

There's a number of ways around it though:

1. Splitting / joining.

The trick here is to split the data into packets and re-assemble it at the remote end.

For instance, you split your string into 16-byte chunks. Then you send each chunk separately. Prefixed to each chunk (so the chunk becomes 17 bytes) is a byte telling the remote end how many characters are in this chunk.  Any spare space in a chunk is padded with something (0x00 for instance) so it remains 17 bytes long in total.

2. two-stage transaction

In this method you first make a transaction which tells the remote end how many characters to receive in the next transaction, or retrieves the number of characters that need to be received from the remote end. The second transaction then receives (or sends) that specific number of characters.

If your strings are longer than the internal I2C buffer (32 bytes) then method 1 is probably the best way.

You can also combine the two methods so both ends know how much to expect to be transferred in total as well as how much of each packet is valid data. The sum of the second should match the first.


message:
"avrdude: stk500_recv(): programmer is not responding" when uploading sketch

When I try to upload any sketch to my arduino uno r3, the code compiles, the board resets and the RX light blinks 3 or 4 times.I have nothing from the TX light.

The uploading progress bar in the IDE stucks at it's end for a period and then gives me "avrdude: stk500_recv(): programmer is not responding" 10 times.

I've done the loopback test and it works well so, what should i do ?

thanks for help.

body:
> yes, it has worked before. ... uncorrect bootloader or something,,...

Does the last program you successfully uploaded write anything to the serial port? If you just run the Arduino (no upload attempt) with the Arduino IDE's serial terminal open, can you see that output? It's pretty hard to damage the boot-loader without actually writing a new, bad one to the chip.

If the current program seems to running but not writing to serial when it should, a likely cause of upload failure is the code in 16U2 processor (or the chip itself) that handles the USB to serial conversion; it's the square 32-pin chip between the 16 MHz crystal and USB connector. Its firmware can be re-loaded - search here for how to do that. If the chip itself is damaged it is probably not worth attempting a repair.

Update: Is the +5v pin on the power header (left edge of the board, if the USB connector is pointing up) reading 5v? You'd expect the output pins to read 0v, 5v, or be noisy if they are floating. A steady 1v sounds strange. At this point it would be worth trying this board on another computer, and another board on your computer, and see which one fails.


message:
The most effective way to format numbers on Arduino

I made a big search about how to Format Numbers with the Arduino. I want to **format unsigned Longs into a String** in this format: "*23,854,972*".

The most of the snippets I found work **only with the standard C / C++ Libraries**. They **dont work on the Arduino** until I should put some STL libraries on the Arduino, which I want to prevent. It would be too bit of a overhead to import these only for this task. Also these Libraries will of course use some additional Flash and SRAM.

For my Application it is very important that the solution uses the minimum Flash, SRAM and is **fast**.

Even if a solution does not use STL or works only with the native Arduino Libraries, I would need help to decide which one is **more effective** in the sense of speed.

Incoming Number: 23854972
Arduino Program Output: 23,854,972

body:
> The most effective way to format numbers on Arduino

If "effective way" is minimum effort you could hack the avr-libc source code for [ltoa][1] and do something like below:

    char *ultos_recursive(unsigned long val, char *s, unsigned radix, int pos)
    {
      int c;

      if (val >= radix)
        s = ultos_recursive(val / radix, s, radix, pos+1);
      c = val % radix;
      c += (c < 10 ? '0' : 'a' - 10);
      *s++ = c;
      if (pos % 3 == 0) *s++ = ',';
      return s;
    }

    char *ltos(long val, char *s, int radix)
    {
      if (radix < 2 || radix > 36) {
        s[0] = 0;
      } else {
        char *p = s;
        if (radix == 10 && val < 0) {
          val = -val;
          *p++ = '-';
        }
        p = ultos_recursive(val, p, radix, 0) - 1;
        *p = 0;
      }
      return s;
    }

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

      char buf[32];
      Serial.println(ltos(12345678, buf, 10));
      Serial.println(ltos(-12345678, buf, 10));
    }

    void loop()
    {
    }

Gives the output:

    12,345,678
    -12,345,678

Cheers!

PS: Please see the table driven, non-recursive, number conversion in [Cosa][2] ([source][3] and [benchmark][4]) for a lean and faster implementation.

  [1]: https://github.com/vancegroup-mirrors/avr-libc/blob/master/avr-libc/tests/simulate/stdlib/ltoa-2.c
  [2]: https://github.com/mikaelpatel/Cosa
  [3]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/IOStream_dtoa.cpp
  [4]: https://github.com/mikaelpatel/Cosa/tree/master/examples/Benchmarks/CosaBenchmarkUART


body:
Here is my try at it: The usual way to write a number in decimal is to
get the digits from right to left with a loop that looks something like

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

    digit = '0' + val % 10;
    val /= 10;

The following function does exactly this, with the addition of adding
commas at the correct positions:

    /*
     * Format an unsigned long (32 bits) into a string in the format
     * "23,854,972".
     *
     * The provided buffer must be at least 14 bytes long. The number will
     * be right-adjusted in the buffer. Returns a pointer to the first
     * digit.
     */
    char *ultoa(unsigned long val, char *s)
    {
        char *p = s + 13;
        *p = '\0';
        do {
            if ((p - s) % 4 == 2)
                *--p = ',';
            *--p = '0' + val % 10;
            val /= 10;
        } while (val);
        return p;
    }

Note that the string is right adjusted in the buffer, and the unused
characters are not touched. This means you can get a right adjusted
string by:

* pre-filling the string with spaces (for padding)
* calling the function above
* using the original buffer as the right adjusted string

Otherwise you would use the returned pointer to have a string with no
padding.

Here is a simple test program:

    unsigned long vals[] = {0, 1, 2, 9, 10, 999, 1000, 0xffffffff};
    const int COUNT = sizeof vals / sizeof vals[0];

    void setup()
    {
        Serial.begin(9600);
        char buffer[14];
        for (int i = 0; i < COUNT; i++) {
            unsigned long val = vals[i];
            Serial.print(val);
            Serial.write('\t');
            Serial.println(ultoa(val, buffer));
        }
    }

    void loop() {}


message:
Sending LCD commands to a slave micro

I need to split up code which I've already developed for one micro into two different Arduinos connected by serial. The "remote" micro is directly connected to a 20x4 character LCD and the main micro will be sending it a command set to print, move cursor, etc.

My plan was to make functions that used existing code such as
lcd.print("This or that");
to replace the lcd library on the main micro and send command bytes and data bytes up to the remote micro. Seems pretty straightforward.

Then I discovered that apparently lcd.print cannot be a function name. Fine, so I changed it to lcd_print(). So far, so good. But in the existing library, lcd.print accepts strings, bytes, just about anything any length. For example:
lcd_print("any string of any length");
lcd_print(a_2d_array [x] [y]);
lcd_print(this_byte);
lcd_print(this_integer);

Now it's getting over my head. I know I can painstakingly turn a single function into many different functions, but wouldn't it be nice to replicate the functionality of the Arduino LCD library with a single command:

lcd.print();

Then all I have to do is create the function and keep the existing code and send the bytes up to the slave micro. Wouldn't that be nice! I appreciate any thoughts. Thanks.

body:
Just inherit `Print` class and implement `virtual size_t write(uint8_t);` and you can use all kinds of print/println that Print implements. See [Print Class @arduino.cc][1].

It implements these methods for you:

    size_t print(const __FlashStringHelper *);
    size_t print(const String &);
    size_t print(const char[]);
    size_t print(char);
    size_t print(unsigned char, int = DEC);
    size_t print(int, int = DEC);
    size_t print(unsigned int, int = DEC);
    size_t print(long, int = DEC);
    size_t print(unsigned long, int = DEC);
    size_t print(double, int = 2);
    size_t print(const Printable&);

    size_t println(const __FlashStringHelper *);
    size_t println(const String &s);
    size_t println(const char[]);
    size_t println(char);
    size_t println(unsigned char, int = DEC);
    size_t println(int, int = DEC);
    size_t println(unsigned int, int = DEC);
    size_t println(long, int = DEC);
    size_t println(unsigned long, int = DEC);
    size_t println(double, int = 2);
    size_t println(const Printable&);
    size_t println(void);

However you have to implement 2D array print if you really need this, I don't see why do you need it but whatever (you can print each line separately). It just saves you time with implementing everything else.

And for std::ostream like approach I like this (works with anything inherited from Print class):

    template <class T> inline Print & operator<<(Print & p, const T & val) {
      p.print(val);
      return p;
    }

    // ...

    void loop() {
      float variableA = 221.23;
      String variableB = "Some string";
      Serial << F("flash string to save some ram: ") << variableA << F(" / ") << variableB << "\n";
    }

Then you can implement some commands interface.

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


message:
Wiring LED strips in parallel & ground

Schematic:

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

I am making some light fixtures controlled by an Arduino UNO. Each fixture will host two approx. 1 meter long analog RGB LED strips with a current draw at full power of ~1.2 A per meter. I have a 12 V power supply that I will wire directly to the strips, with the RGB channels wired to the Ardiino PWM pins via NPN MOSFET (note in the schematic I've only shown one color channel for simplicity, but there would of course be three transistors hooked up to three PWM pins). The Arduino itself will be powered by USB.

My main difficulty in wiring the system is that for so much current I need fairly thick wire. The pads on the LED strips are delicate and I have several times damaged them by mechanical stress from the wire while soldering. The thick wire also crowds the narrow space between the pads creating a risk of a short. Therefore my first question is (bear with me, I'm pretty new to this):

1) How should I wire the LED strips?

My thought is to wire up the strips in parallel with thinner, more flexible wires. This brings up two sub-questions:

1a) How should I join the thinner wires to the thick wire coming from the power supply?

1b) At the junction between the wires leaving the lights and running to the transistor, does the wire need to become thick again? (I think the answer is yes – the current should be the same as coming out of the power supply.)

I also am unsure about the ground.

2) Does the wire coming from transistor to ground need to be joined to the ground pin on the Arduino or can it run directly to the ground terminal of the power supply?

Sub-question:
2a) Does the wire coming from transistor to ground need to be thick?

I don't really understand how transistors work (basically my understanding is that the Arduino uses a small amount of current over the PWM pins to somehow control how much current is allowed to flow through the rest of the circuit.

I've drawn a schematic showing how I think maybe this system needs to be wired up. Do I need to make changes?

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

body:
I think you are overestimating the size of wire required to attach to the LED strips, I have connected a lot of single color LED strip (in excess of 1mtr) with the wire that was already attach and it was reasonably light gauge.
Look at this [Example][1] on Ebay and you can see what i mean.

I am note an Electrical Engineer so i don't know the method to calculate the minimum wire gauge, but if in doubt contact the manufacturers and ask them or search on the web.

As for the Transistor mounting/wiring you would mount that on a small circuit board with terminal block fitted for ease. Any power/connecting wire should not be less that used to the LED strip.

Also you will need a current limiting resistor attached to the Base pin on your transistors. You will have to work out the value of that based on the spec sheet.

There is a bit of learning required first, once you have researched the above you will have you exact answers.

  [1]: http://www.ebay.com.au/itm/NEW-2835SMD-300-LED-Flexible-Strip-Light-Ribbon-Lamp-Lighting-COOL-White-DC12V-/302050174238?hash=item465397e51e:g:P7sAAOSwRQlXeyVB


body:
It's all a question of *losses*.

Wire is basically a resistor. The thinner and longer the wire the higher the resistance. Current flowing through a resistor causes a voltage drop across the resistor.

Long thin wires with large amounts of current through them will basically mean you get less than your 12V at the LED strips. The question has to be: how much less a voltage is tolerable?

Each strip takes 1.2A. Take for example 24AWG wire. That has a resistance of 0.0842Ω per meter. With 1.2A flowing through a meter of that you get 0.10104V dropped across the wire. That turns your 12V into 11.9V.

Conversely, a meter of 14AWG wire has a resistance of 0.00829Ω - so you would lose 0.009948V over that length.

Now you want two strips - which is double the current, and thus double the voltage drop. On 14AWG you would lose about 0.02V over a meter. Not really enough to worry about. But you can't connect 14AWG to the LED strips. You can connect thinner wire (say 24AWG as above) to them. But that looses too much voltage. Well - *over a meter it loses too much voltage*. But what about over, say, 10cm? That's a 10th the length of before, and so a 10th the voltage loss: 0.01V.

So what is to stop you having a short length of thin wire connected to the LED strips, which then connects to a longer length of thick wire? Answer: absolutely nothing.

And how do you join them together? Well, I find the best way is with solder. Insert the thin wire (stripped) into the end of the fat wire (stripped) and twist them together (axially) then flood the joint with solder.

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

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


message:
Servomotor losing its connection right after being connected to Arduino

I am working with two servomotors and both are having the same problem: right after i connect them to the arduino and upload the code, they do as the code says for a really small amount of time (0.1s maybe), and then they simply stop. If i keep connecting and reconnecting it again the servo answer to the code for a really small amount of time and then stop, as I said before.

    #include <Servo.h>

    #define SERVO 6 // Porta Digital 6 PWM

    Servo s; // Variável Servo
    int pos; // Posição Servo

    void setup ()
    {
      s.attach(SERVO);
      Serial.begin(9600);
      s.write(0); // Inicia motor posição zero
    }

    void loop()
    {
      for(pos = 0; pos < 90; pos++)
      {
        s.write(pos);
      delay(15);
      }
    delay(1000);
      for(pos = 90; pos >= 0; pos--)
      {
        s.write(pos);
        delay(15);
      }
    }

I am using the code above, and it looks totally fine. Does anyone know what might be causing this problem?

body:
Your code is correct. Check the following:

 - Arduino works from 5V, but most servos need 6V.
 - Even if your servo works from 5V, don't ever connect your servo power directly to Arduino pins. These pins are not able to provide adequate power for servo.
 - Check that grounds of both power supply for Arduino and power supply for servo are connected together.


message:
Faster and lighter approximate timing code without using timer

I want to use loop() iterations counter to execute some tasks periodically or tasks like debouncing. My other sketch is running every loop() at least 20 ms, and if i am using 5 ms time to wait to
debounce a button, it will still be at least 20 ms waiting, also cpu will have to compare two not zero values, which is a bit slower.
I think it is more difficult for cpu than just incrementing and decrementing one variable and comparing it to 0. So i came up with pattern like that:

    boolean onOff=1; // arduino led state. My task here is LED blinking.
    byte loopCounter=2; // number of iterations made by loop(). Set as little variable as possible to save ram and cpu time.
    //Code will be executed every "loopCounter" iteration of loop().
    void setup() {
      pinMode(13, OUTPUT);
    }

    void loop() {
          if (--loopCounter == 0) { //comparing with 0 should be a bit faster and easier for Arduino to process. Correct me if i am wrong.
            loopCounter=2; // That digit sets how often your code will be executed. Every 2(3,4... set your own value) iterations of loop().
            digitalWrite(13, onOff= !onOff); // the task itself.
            }
    }
It may be more convenient in some ways than millis() and micros() patterns. Also i do want want to use hardware timers for timing.
It may be convenient in cases, when you don't care when exactly task will be done, you just want it to be done ASAP (as soon as possible), but
not during that particular iteration of loop(). Basicly you can use it as a timer if you know how it takes one iteration to be done.
So, if your sketch runs 1 iteration of loop() for 1 ms, and you need some action to be done every 1 sec, 1ms*1000 == 1 sec. So you
need it to be done every 1000 iterations.

 1. So, is that really can save some ram and cpu time?
 2. Is comparing with zero is faster for arduino than comparing with not
    zero?
 3. Are millis() and micros() timing patterns using more operations
    (setting value to variable, computing the difference between 2
    values and than comparing it to a period you have set) instead of
    decrementing and comparing to zero with my pattern?
 4. Any side-effects of using my pattern? I can only think of very
    unaccurate timing and delays more than you think if your sketch done
    smth more than usual, because of button push for example or some
    sensor changed value.

 Thank you!

body:
Personally I wouldn't be putting too much effort into optimizing away your timers. `millis()` is pretty fast - the work needed to calculate the result is done in the background *anyway* (by interrupts). I tried some test code:

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

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();

      unsigned long start, finish;

      start = micros ();
      for (byte i = 0; i < 100; i++)
        digitalWrite (13, HIGH);
      finish = micros ();

      Serial.print ("Time taken to do digitalWrites: ");
      Serial.println (finish - start);
      Serial.flush ();

      start = micros ();
      volatile unsigned long now;
      for (byte i = 0; i < 100; i++)
        now = millis ();
      finish = micros ();

      Serial.print ("Time taken to do millis: ");
      Serial.println (finish - start);
      Serial.flush ();

      }  // end of setup

    void loop ()
      {

      }  // end of loop

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

Results:

    Time taken to do digitalWrites: 520
    Time taken to do millis: 188

You can see that the `digitalWrite()` (which you weren't worried about) takes 5.2 µs, whereas calling `millis()` (which you *were* worried about) takes 1.88 µs.

---

> Are millis() and micros() timing patterns using more operations (setting value to variable, computing the difference between 2 values and than comparing it to a period you have set) instead of decrementing and comparing to zero with my pattern?

Yes, just adding one to a variable and then comparing will be faster. Whether it is worth the effort is debatable.


message:
No power_usi_disable() on Arduino Uno

we have an error after compiling the code in arduinouno that is displayed as
error: 'power_usi_disable' was not declared in this scope   in Board: "Arduino/Genuino Uno".how to rectify this error. please reply us fast

body:
The Arduino Uno does not have a USI peripheral. Thus, you cannot disable
the power of the (non-existent) USI, and there is no
`power_usi_disable()` function.

Solution: remove the call to `power_usi_disable()` from your code.

**Update**: To answer your _new_ question in the comment, `WDTCR` is the
Watchdog Timer Control Register on some AVR chips. On the Uno it is
called `WDTCSR`, because it is a control and status register.

Looks to me like you have downloaded from somewhere a program you do not
understand. That program was written for an ATtiny chip and you are
trying to compile it as-is for an Arduino Uno, which is based on an
(incompatible) ATmega328P. That's not the way to do it: you have to
understand the program and rewrite all the ATtiny specific stuff to fit
the Uno.