text:
SOLVED: Soft Power On SIM900 module - JP pads missing!
I have this SIM900 board and working just fine.
But i can't find a way to soft power on this board from arduino.
I read for JP pads. They need soldering first, but from my board this JP pads missing.
Know someone other way to soft power on this from arduino?

Dielatin... Winner, Winner, Chicken Dinner!! Works a treat, been trying to figure this one out for sometime and there is nothing on the web about it!! So thanks for the solution upload!!

OK for anyone who has the same problem. I solved this by soldering a cable on the underside of the board on this pin (see image) on power button. Then I connect the cable to pin 9 on Arduino and run this on sketch:
  pinMode(9, OUTPUT);
  digitalWrite(9,LOW);
  delay(1000);
  digitalWrite(9,HIGH);
  delay(2000);
  pinMode(9, INPUT);

I don't know how it works, but it solves my problem.

Near C6 and J15 you have 2 points.  You need to solder it.
Before soldering yon can hold wire on one of it (down pin , during code execution).


text:
Receiving live astronomical coordinates on Arduino Mega using telnet and ESP8266 wifi module
I'd like to receive on my arduino live coordinates of planets of solar system. Because there are already websites listing every planet coordinates, I thought it would be easier to just use a wifi module (in my case an ESP8266) and connect the arduino to one of these website.
I have the option of getting it from this website, but I have no idea how to do that.
The other way of doing it may be to connect to Horizon via their telnet server at this adress :telnet://horizons.jpl.nasa.gov:6775
Though I know how establish a connection with this server on my computer using Putty, I have no idea how to connect my arduino to it, execute commands, and, more importantly, get data (RA and DEC) of every solar system main objects.
This is my first time using Arduino wifi module, so I have no experience with it, and I don't know what it is capable of.
Thanks a lot for your attention,
Thomas

That telnet interface is an interactive service. Getting an Arduino to interact with it is not an easy task - certainly not a task for a beginner with no experience of network programming.
A much easier task is to scrape the website since that just returns text which you then need to search through a bit at a time looking for the information you need.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
NFC 'dynamic' UID database
Hi SE (and Majenko in particular, if I'm lucky) -
I have a setup with an SD module (on SPI) and an Elechouse PN532 NFC reader (on I2C). I would like to use a master tag to enter MASTER MODE [sic] to add tags if they are not present in a file on my SD card, or remove tags which are present in the same file. I am currently checking tag UID against a hardcoded master UID, and it works well enough for now. What trips me up is making the tag database in the most arduino-friendly way. How would you advise me to do this in the most spartan way? And when removing existing tags from the database, how would you suggest I update it, to remove unwanted UIDs? I am using a flat text database now, but it could be a binary file - I am just puzzled by what is the best method to remove an entry(line) from a file using SD library.

I an considering using EEPROM instead, if it can have a decent lifespan (I will only rarely add or remove tags), but it would be convenient to have the UIDs in a text file on microsd.

If the list isn't too large you could just read all the entries into memory, modify the list, and write back the modified list. Alternatively you could overwrite the entry with zeros instead of actually removing it.

You got me ;)
Since a UID is a fixed size you don't need to think in "lines", only in bytes.
The most efficient way of storing the UIDs is as pure bytes. I am not familiar with that specific card and reader combination, but I will assume as an example an 8 byte UID (though this all holds true for any other length you care to choose).
You treat your file on SD card like a kind of database with a number of records in it. Each record is the exact same size (8 bytes in this case) . To read or write a specific record you just "seek" to the record number multiplied by the record size - so multiples of 8 in this example.
myFile.seek(recordNumber * 8);

If .seek() returns false then you have reached the end of the file.
So to find a tag you can:
myFile.seek(0); // Start at the beginning of the file
int recno = 0;
char foundUID[8];
bool found = false;
while (myFile.read(foundUID, 8)) {
    if (strncmp(foundUID, myUID, 8) == 0) { // 8 bytes match
        found = true;
        break;
    }
    recno++;
}

At the end of that found will be true if there is a match, and recno will be set to the record number. Now the magic begins...
If it has been found and you want to delete it, think again. That's a very wasteful idea. Instead you just want to "invalidate" it - that is, replace the UID in the database with something the UID can never be - all 0xFF is a good choice. Simply:
myFile.seek(recno * 8);
for (int i = 0; i < 8; i++) {
    myFile.write(0xFF);
}

Now the tag has gone from the database. You may want to add a filter at the card reading phase to stop anyone using a card that has a UID of all 0xFF, of course.
Now for adding a new card...  This is where the fun starts.  You could just add 8 bytes to the end of the file, but then the file will grow and grow and grow. Instead, you can first search through the file for a tag entry that is all 0xFF and replace that data with your new UID. Just the same as when you deleted it - seek to 8x the record number and write 8 bytes.
It might help to write a function to wrap the tag seeking routine so you can easily call it multiple times from multiple places. Returning the record number would be most useful - and you could return -1 if it's not found.
If you really want it to be plain text you can do the exact same thing but work with the ASCII representation of the UID bytes instead of the raw values - maybe as HEX. So your 8 byte records would become 18 bytes (16 bytes for 2 ASCII characters per UID byte, plus two for the \r\n line ending). Doing the conversion between bytes and text and back to bytes again though is wasteful if you don't really need it.

In case you're wondering why I recommended 0xFF as the deleted tag fill value and not 0x00 or anything else, it is simply because when you erase flash memory it is set to 0xFF. When you change the contents of a block on an SD card the block is read, it is modified in memory, the block is then erased (the whole lot set to 0xFF), then the modified block re-written back to the card. The act of erasing the block slightly damages it as it forces electrons through bits they don't really want to go through to make it all 0xFF. By setting your empty records to 0xFF, when it comes time to filling them again, the flash doesn't have to work as hard to erase that block since those bits are already in the erased state. Therefore the lifetime of the flash card should be extended slightly.

Excellent. I won't have time to do it now, but I'll use a binary db. I will read this answer many times to fully appreciate it. Thanks!

You are a lesser deity - this is an excellent method!

Majenko is next to godliness.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Can I convert 3.7V to 5V's using 3.3v to 5v converter

THe product: (https://www.sparkfun.com/products/12009)
So guys, here' s a pretty simple but important question for me:
Can I convert 3.7V (li-po battery's voltage level) to 5V's (I do have arduino pro mini running on 5 volts) using 3.3v to 5v converter (picture shown above...) ??
Thanks already...

That looks like the SparkFun BOB-12009 Level Converter https://www.sparkfun.com/products/12009 . If so, it would help if you identified it as such

Thanks, glad I' ve heard that. I' m editing my Q right now...

No. That is a level shifter. It uses a low voltage (3.3V) to switch a separate high voltage (5V) supply to create different logic levels.
It does not convert voltage, it merely switches.
To create 5V from 3.7V you need either a boost converter (inductor based circuit) or a charge pump converter (capacitor based circuit).


text:
Pin 0 (62) you are trying to use is not supporting interrupts
Using RCLib (github) I'm getting this error. The trick is that the RCLib example works on it's own but does not work in my program (github).
Serial Output "Error"
Pin 0 (62) you are trying to use is not supporting interrupts
Pin 1 (63) you are trying to use is not supporting interrupts
Pin 2 (64) you are trying to use is not supporting interrupts
Pin 3 (65) you are trying to use is not supporting interrupts
Pin 4 (66) you are trying to use is not supporting interrupts
Pin 5 (67) you are trying to use is not supporting interrupts

It is quite right. Those pins aren't interrupt pins. What you want to do is make it use PinChange interrupt pins instead.
This can (by the look of things) be done by including the PinChangeInt.h library before including the RCLib library.

Does that make the Arduino use software interrupts instead of hardware interrupts?

No. That makes a different kind of hardware interrupt available to that library.

Hmm, well I have NO idea how you came to this conclusion and the quickness at which you did it is disorienting. I'm sure much of it chalks up to experience but can I bother you to open my mind to your troubleshooting technique(s) ?

Simple: I looked at the source code for RCLib.h and found the bit where the error message is. Then I saw that it's wrapped in a test to see if PinChangeInt_h was defined (which is done by the PinChangeInt.h library) and that by including that library it will change the behaviour accordingly.


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

From what Isee, it does not show "nothing" but it shows entirely black points which is different. If you could post the code you u;load that might help people here trying to find out what happens.

Cannot exactly see from the image, but check your soldering. I feel like some of the pins might be in contact. Also, try changing the contrast with a potentiometer and see what happens.

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 installed, you can get Streaming5.zip from arduiniana.org.
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;
}

Blocks on the first line means it's incorrectly initialized. But blocks on the both lines means more likely bad contrast voltage.

@KIIV, that sounds correct


text:
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.

"This question does not show any research effort..." ie, you really should do a web search before posting a question here, as if you had you would already know the answer.

One aspect of it wouldn't work fine without it. Do a little digging in the Arduino documentation, and you'll find out what.

The capacitor provides one of the most basic functionalities of the Arduino. If you don't know what that is, then google it.

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.

It is not the USB serial chip, it is the operating system serial driver's most common default mode settings.  And regardless of that, the Arduino programming process typically toggles it explicitly.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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.

Avoid "" in URL, these are not standard separators, in addition these are escape characters in C and C++ strings. Your "192.168.1.13\test\" should probably be replaced with "192.168.1.13/test\".

I think it would help us (and yourself too) if you traced the response of all AT commands sent to the ESP8266, so that we could check that all of them succeed as expected.

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

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

You need to provide an IP address or domain name - NOT a URL
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.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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?

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...


text:
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:

Why does my sketch works only with delay(), but does not work
without it?
Why does blinking sketches work with millis(), while they do not use any delay() just like my sketch.
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?
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.

Without delay() it is doing exactly what you tell it. It is blinking the LED - just far too fast for you to see. Try using values in the hundreds of millions instead of just a few hundred for your counter.

The typical design pattern used to perform a delay without delay() is described here: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

“millis() uses long variable (which is bad for cpu time and ram)” If you never need to compare timestamps more than 65 seconds apart, then you can do the timekeeping with 16-bit unsigned integers.

@Edgar Bonet , i was thinking about it, but what happens, when previous millis() value is 60000, and than it overflowed and current millis() is 3000? 3000-60000=-57000, and who knows what will arduino do next... Or did i miss smth? Tell me please if so, that would a nice solution.

@ Dirk Grappendorf , thank you for that, but it also uses millis(), and it is too costly in my current project.

@Majenko , indeed it is!) Thank you!

With unsigned ints, 3000 − 60000 = 8536. Unsigned numbers follow the rules of modular arithmetic, which make the overflow irrelevant as long as you compare durations instead of timestamps.

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);
  }
}

There is absolutely no reason for the optimizer to remove the counting. If it did that sort of thing then nothing would ever work. The compiler has no clue what delay() does.

You are right when delay is there. I mean when delay is gone.

Why do you think that removing a function that has no relationship at all with the counting would affect how the compiler optimizes the counting?

because loop() is actually in a while(true) loop. So without the delay you get while(true){count++;if(count==316){[something]}}. Which can get optimized to while(true){[something]}. I have had that happen to me.

What makes you think the optimizer would ever do something as idiotic as that? (By the way: try it for your self. Compile the code without delay() and look at the assembly output. You'll see the count never gets optimized out). The only time the optimizer would remove the counting is if the result of the counting does nothing (i.e., if the if is empty).

As I said, It happened to me. I never stated it would happen. As Arduino now is plenty of toolchains and cores I think it is save to say: I could happen. Maybe you should reread  my answer.

As long as the result of the count is used somewhere (and that "somewhere" doesn't get optimized out) the count will never be optimized, under any circumstances. Such behaviour would break massive amounts of code all over the place. I reiterate: it cannot happen. Ever. Full stop. I suspect your "it happened to me" was something completely different. You may have seen it optimized out as a casualty of something else being optimised out (such as an empty if that gets optimized out) but as long as there is something using the count it CANNOT be optimized out. Counting is perfectly reliable.

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).
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.

Wow, thank you for that! But that is so much more than i know for know, i do not really understand that sketch. Can you please provide some more info or some links, so that i could learn what is going on there?  Do i understand correctly that some hardware timer is used here? Also i have no clue how to make a second timer for another pin in that sketch, would love extended example.  Thank you again!

See amended reply. Yes, it uses a hardware timer.


text:
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?

You could add a large value resistor as a pull-down.

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.


text:
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?

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

It worked! Answer the question and I will choose your answer as the best one.

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.


text:
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.

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 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.

I am extremely newbie in these electronics. thanks man you are genius .but small question "you are likely to lose the first byte received from serial if you are asleep" don't that data will be saved in serial buffer ??

No, because the clock (used for all operations) take a few microseconds to "spool up" after sleep. The processor is held inoperative until it has - the exact time depends on fuse settings. Without a clock it can't clock in serial data. Some clock modes don't stop the clock, but they don't save as much power.

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?


text:
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, but I'm wondering if a more direct approach is possible, maybe by adjusting the SPISettings.

You might try the SdFat library - it's much more efficient than the default SD library.

You might also want to make sure your SD card is of good quality, although 5000 bytes seems too low for any kind of SD card.

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.
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) 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.

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

1. Your Software
The SdFat 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.

I will try this in a few days and let you know the results. Thanks.

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.

I don't know what you mean by handshake, because AFAIK SD uses a (512 kB) buffer internally anyway. But I also observed that writing individual bytes with File.write is extremely slow and the compiler doesn't seem to be able to optimize it (after all it's just copying one byte to the internal bufffer and checking if buffer is full and SPI transmission should start). Using my own buffer outside and File.write(buffer,size) brought extreme performance improvement also in my application.


text:
Arduino connection confirmation
I am using Arduino Uno. I want to control my room lamp both manually and over the network, so when I switch off my lamp manually, how do I get acknowledgement over the network that lamp is off ?

Disconnect the switch from the lamp and instead connect it to a digital pin on the Arduino. Have the Arduino toggle the lamp when the switch changes position.

Or attach a lightsensor to see if the bulb is on.

@Gerben not nice.

Please read How do I ask a good question?. What do you mean by "manually"? What do you mean by "acknowledgement over the network"? I don't know why the above comments have been reported to the moderators.

@PhillyNJ could you explain what you mean by not nice? Do you mean it's unsafe to do so?

@Gerben - My mistake.- I read it wrong. Sorry


text:
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?

These are so minimally documented and widely sourced that you may do no better than experimenting with the ones you intend to use.  Certainly there is no point in triggering a new reading before the echo at your greatest intended range has had a chance.  After that it is more a question if the implementation forces a minimum, or if in highly reflective environments you could misread a delayed reflection of an old pulse as a new one.  5ms would be the roundtrip to a surface less than a meter away, so trying to re-read that quickly does seem like it could lead to such mixups.

Note that the microsecond delays in your current code are to form the trigger pulse, if you are using it as posted the inter-reading delay would be coming from the time waiting for the first echo (or the timeout waiting for it).

@ChrisStratton I am not worried about the microsecond delays. And I am aware that pulsein takes time. I was just wondering if I could decrease from 150ms.

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!

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


text:
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.

There seems to be a lot going on in your full program, which can explain why it is slower. If you want to minimize the problem, avoid floating point and – most importantly – blocking calls. delay() is not the only blocking function: pulseIn() is also blocking, and Serial.print() becomes blocking is the output buffer fills up.

@EdgarBonet I cannot really avoid using pulseIn() - it is needed for the sensor. Even if I remove Serial.print(), it makes no difference to the servo and sensor.

I cannot really avoid using pulseIn() - Yes you can, easily. pulseIn is just a blocking way of measuring the time between two events. You could use interrupts and not block.

@NickGammon Ok. If this is the source of the issue, I guess I will change it. But I am not sure if it is. After I followed the suggestion below, the servos work, but the sensor still gives me 0s.

Well it sounds like you have more than one problem then. :)

What is the value of the duration variable after the pulse and before your calculations?

@RobertoLoGiacco If cm is 0, then duration must be 0 as well. Since x/2/29.1 = 0, then x = 0.

@NickSolonko did you actually check the duration is 0? Because you are operating on integers and 50 / 2 / 29.1 cast into an int is actually 0...

I think you'll need an Oscillograph or a Digital Analyzer to observe what happens on TRIG and ECHO pins. In particular, it might be interesting to check timing of TRIG pin is correct (10us HIGH) and observe if there is or not an ECHO signal. My belief is that servo interrupts may negatively impact your ping() method.

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?

Although it is often considered good practice to explicitly set the mode of every pin you use, here it doesn't make any difference, as all the pins are initialized to INPUT by the hardware.

You are right @EdgarBonet, default state for pins is INPUT, but he might have includes or other non displayed code which changes the pin state.
Also the pulseIn(...) function should actually change the pinMode implicitly via the call to portInputRegister(...) contained inside it, but that depends on the version of Arduino libraries he is using...

Thank you for pointing out to me something so obvious. I indeed forgot to set the pinMode to INPUT for echo AND set it as OUTPUT for trig. The trig pinMode caused the issue I am guessing. I spend so much time trying to find a flaw and it was just one line of code.

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.

So you are saying that the HC-SR04 is sending me a 0 because of an uneven surface? I just tested it without servo rotation and commented everything extra out and it still gave me 0. When I tried running the same code in a separate sketch, the sensor gives me actual values. So I am still not sure why it is giving me 0s. The surface and distance are not the ones causing the issue. I also changed pulsein to 24000L. I saw no change with servo rotation.

Never mind, the servos rotate normally now after I added 24000L. The sensor still does not work.

You may have a voltage drop issue (this happened to me in the past, due to the number of devices you are driving. Did you use decoupling caps for each device?

It is possible. When I removed all the code for those devices, it still gave me 0. Those devices were still connected up though. They were also connected up when I uploaded the first sketch and everything worked.  I am using capacitors.

It is hard to tell, without seeing your wiring. If you have an oscillograph, then you can check voltage of HC-SR04 power pins and see if it's stable. If you don't, just add a 10uF cap as near the HC-SR04 as possible.

What cap values do you use? Are caps near each device? Could you consider (for testing only) providing voltage to the HC-SR04 through a separate power supply (you'll need to join GND pins of course)?

Sorry for not responding. I connected the sensor to another 5 volt power source and the same thing occurred.

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!


text:
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, 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?

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

I would suggest working the other way around.

Start the Arduino IDE and set external editor in the Preferences (once).
Open the sketch file(s) in the Arduino IDE and VIM.
Edit the sketch file(s) in VIM.
Move to the Arduino IDE and Verify, Upload, Monitor, etc.
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.
Cheers!
PS: VIM = any external editor such as GNU Emacs, TextEdit, etc.

I had no idea about the external editor! That would work for now. A Makefile would be the way to go when I have more time to look into it!


text:
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.

Please add the wiring used.

Cable length won't lead to sensor heating but may cause sufficient distortion of signals to prevent recognition of all the devices.

@JRobert  I know :), but the cable "consumes" current and I beg this is my problem her. Going to heat the iron and report the outcome.

Or to be more accurate, the current in a long cable could cause a voltage drop (current in must == current out at any point on the bus). But yes, testing with a short bus is a good first step. Also see my (ASCII) schematic for a parasitic bus with strong pullup, in my answer below.

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.

Nice Work. Upvote for that, even If it is not my wiring.


text:
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.

It all depends which library you are using.

It is not clear what your question is about. It makes me wonder if this is a school assignment which you did not understand or you just simply don't know how to describe your problem. In any case, you have to provide more details: wiring, code you have written so far... In particular the sentence "I have to define names of pins so that I can call those names in arguments of a function" is not clear; maybe you could give the prototype of the function as you imagine it, that would give us food for thought.

i have to use multiple touch keypads with arduino via a port extender. I have managed to operate both the sensors and the port extender individually but when i came to combine them i faced a problem that when i call the library of touch keypads, i have to pass them the pin numbers on which they are connected. in my case i have connected them with port extender via SPI. i am confused how to refer port extender pin number because if i simply type a pin number, arduino will refer to its own pins.

You may have to edit the touch keypad library's code or write your own to use the port expander's pins instead of the Arduino's own pins.

If you use this arduino library:
#define LED_PIN 15

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

mcp.digitalWrite(LED_PIN, LOW)

If you are using my library 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);

There is also the Adafruit 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);
}


text:
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?

Please note that "functional programming" is not what you think it is, I guess you wanted to say "procedural programming".

Functional programming usually involves the use of closures, in languages that support them. C++ doesn't, and you would probably use functors instead.

Check out this article. It explains the neglegable performance effect of using classes.

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:

There is no point
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.

Is there more than one Serial object? If not, what's the difference between Serial.begin and (hypothetically) Serial_begin?

On some boards yes there are multiple Serial objects.

If OOP is using C++ classes for implementation then this answer is fine. A more detailed answer may be found by first reading Peter Wegner's paper; http://www.cse.msu.edu/~stire/cse891/wegner.pdf. Arduino would be OOP if interfaces/classes would be more encapsulated, reused and extended.

You mean like Cosa? ;)

Hard to miss :)


text:
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.

Unless you mean that this works normally and only breaks when the shield is present, remove the shield for the moment and take it out of your title.  Then edit the the output of lsusb into your question.  Also look for messages in dmesg after re-plugging the board, and consider trying another cable.  There could also be permission issues, but I'd expect a different error message then.

I just tried it without the wifi101 shield, and I got the same error.

And lsusb shows what???  And dmesg ???

Experiments with a different CMSIS-DAP show that this is probably a permission issue - openocd does not distinguish between the absence of a CMISIS-DAP programmer vs. lack of permission to access one which is present.  The usual solution is to create or install an appropriate udev rule and then restart udev or the system and replug the device.  This does not seem to be well documented, so one might say the board is not a well  supported product at present.

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.

98-opencd.rules >>> 98-openocd.rules

missing closing double quote ? LABEL="openocd_rules_end >>> LABEL="openocd_rules_end"

Yes. Fixed. Very old message...


text:
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?

esp8266 chip is unrelated to anything arduino

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.


text:
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...

Do you want to split the string on a particular character or position?

You can use strtok(). It's not part of the Arduino core library: it's just a libc function.

And, how am I supposed to find that libc (I guess a library) thing?

Mr.Bonet, pls, I need this answer...

It would help to have the above questions answered. Do you want to split at  a certain spot (eg. 5th character)? Or after certain symbols (eg. a comma)?

How do you find strtok? Google? For example: http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm

there is no method such strtok() like in C can help me with this - yes, there is. Just use it. No need to include any extra libraries or anything. Why do you think there is "no method"? Did you try it?

I did, I have edited my question. please check that out

strtok() is not a method, it's a plain function that works on C strings (char *), not on String objects. Nick Gammon googled the doc for you, you should take a look at it.

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

in arduino ide?

Yes, of course.


text:
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 ) 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:

Are you able to put up a schematic of how the relay is connected ?

Thanks, added the diagram. Very simple, works fine with USB input. Not 100% sure how they've wired with the external power, trying to find out.

"units are at a mine" I don't know what your are doing, but if you are operating an Arduino and an off-the-shelf relay in a mining environment, you are likely violating safety rules and/or laws related to electronics in hazardous environments. Have you considered the hazardous location equipment qualifications needed for electronics?

The relay is to fire a turnstyle and it's not related to any industrial equipment and the guys on site are working under supervision so I don't think that this is an issue

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  to leads to this thread on the Arduino forums.
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) 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:

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:

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:

Thanks. I do agree this is probably the right way to do it - but because the site is so remote we did not want to risk blowing the board. I've accepted as answer and then added what we did as a "workaround"

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.


text:
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.
#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");
  }
}

You could have any of several issues: electrical noise, sagging power supply under load in a circuit which does not factor that out, or perhaps power consumption of the circuit (the majority of which will end up as heat) causing the assembly to heat a bit above ambient.  Your question is not really answerable without precise details of your setup - schematics, part numbers, and physical layout.

Can you please try putting a Diode (like an LED) between them? That way you'll eliminate the possibility that the LCD may be back feeding. Can you also tell us what Temperature sensor you're using? I've done a similar project (with DS18B20) but it didn't cause funny readings ......

I have added my code just in case, though I highly doubt it has anything to do with this. I will add the layout as well.

Layout is in the post.

Your "layout" is nearly uninterpretable, but try giving the temperature sensor its own leads to the power supply so it does not share with the LCD, and add some bypass capacitors.

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

+1, Useful suggestion b/c TMP 36 is an analog sensor and power supply noise or sag would affect the reading. Why the drive-by downvote, @someone?

I didn't downvote but this isn't a complete answer at all. It's just general advice without any reasoning written in. It should explain why the LCD power should be from a separate power source, and how it relates to the question.

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.

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.

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).

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.


text:
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:

What am I doing wrong?
How could I debug this?

I think PostarDados() is missing to \r\n\r\n at the end of the HTTP message

Thanks, but it didn't work

You're hiding any errors  in your webservice method as there is nothing between your Catch and End Try. My first action would be to add logging in there to see if anything is going wrong there.

I would also try to code up a simple GET request webservice - just to simplify things and to make sure the requests are getting to the webservice at all...

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

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

worked


text:
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.

Tricky at best. CapSense relies on pretty tight time measurement to determine small changes in capacitance. You would be better off using a proper CapSense interface chip. There's plenty to choose from - most of them I2C based.

I am new in this field. Can you please refer me any CapSense interface chip. I am using the following touch keypad by waveshare
Waveshare Touch Keypad

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).


text:
max7219 chained display showing text only on the first display
I'm using a max7219 like this one max7219. 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, 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);
}

I don't think you understand how the protocol works. Have you read the MAX7219 datasheet?

Why don't you just get a copy of the library that drives the max7219 ??  http://playground.arduino.cc/Main/LEDMatrix.

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.


text:
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 which commands you have to use but it doesn't do anything. What is my fault, how to solve it?

Please add a link to the LCD Shield.

use can see and read about the lcd here: http://www.robot-electronics.co.uk/htm/Lcd03tech.htm

You need to first read about how to use Wire and then the LCD communications protocol. The above code snippet is not a complete command.

SOLVED!
I forgot to write beginTransmission(). Here's my code:
#include <Wire.h>

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

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

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.

no the adress is 0x63 tested with i2c scanner

@marangisto  many I2C addresses are quoted like this as an 8 bit value - made up of the 7 bit address plus the data direction (read/write) bit.
0b11000110 (0xC6) removing the least significant bit is 0b1100011 (0x63). There is also 10 bit addressing (http://www.i2c-bus.org/addressing/10-bit-addressing/), but that only confuses things even further...

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.


text:
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.

There's no such thing as "uncompressed MP3". MP3 is compressed. What format are you really sending? Raw 16-bit signed samples?

Majenko:  You are correct -- pardon my redundancy.  The MP3 data will come from an iPhone's music library, by WiFi to the Arduino (probably Adafruit Feather M0)

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.


text:
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.

Sounds like a question for Adafruit or at least adding links to the product descriptions, circuits, etc.

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


text:
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
       }
     }
   }
 }

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.