text:
ArrayList implementation fails for string object
I'm using a customised C++ implementation of ArrayList based on the method found in Processing. The original code is by Obed Isai Rios, but I've added a version to Github with more explicit file structure.  The arraylist is appended to by the add_string_item method, which works ok in the format arraylist->add_string_item("text string") but fails when the same input is a String variable.  The following script illustrates:
#include "ArrayList.h"
void setup(){
  ArrayList *list = new ArrayList("text1");
  list->add_string_item("text2");
  String str = "text3";
  list->add_string_item(str);
}
void loop(){}

This fails on the last line with error message:
no matching function for call to 'ArrayList::add_string_item(String&)'

sketch_aug24b.ino: In function 'void setup()':
sketch_aug24b:7: error: no matching function for call to 'ArrayList::add_string_item(String&)'
/Users/robinedwards/Documents/Arduino/libraries/ArrayList/ArrayList.h:17: note: candidates are: void ArrayList::add_string_item(char*)

I'm not familiar with C++ so can't figure out why this method accepts a string but not when assigned to a String object str.  I'm pretty sure it's because I need to coerce to char* but not sure how to do this.  I've tried toCharArray without success, although this seems the right direction.  Very grateful for any assistance.
ArrayList.cpp code:
#include "Arduino.h"
#include "ArrayList.h"

ArrayList::ArrayList(char* init){
  stringlist = (char**)malloc(10*sizeof(char*));
  stringlist[0] = init;
  this->size = 1;
}

ArrayList::~ArrayList(void)
{
}

void ArrayList::add_string_item(char* item){
  char **neulist = (char**)malloc((size+1)*sizeof(char*));
  for(int i=0; i<size; i++){
    neulist[i] = stringlist[i];
   }
   //
   neulist[size] = item;
   stringlist = neulist;
   size = size + 1;
}

void ArrayList::set_string_item(char* item, int index){
  stringlist[index] = item;
}

void ArrayList::remove_selected_item(int index){
  char **neulist = (char**)malloc((size-1)*sizeof(char*));
  //From Begining
  for(int i=0; i<index; i++){
    neulist[i] = stringlist[i];
  }
  //From next Index
  for(int i=index; i<=size-1; i++){
    neulist[i] = stringlist[i+1];
  }
  //free(matrix);
  stringlist = neulist;
  size = size - 1;
}

void ArrayList::empty_list(){
   size = 1;
   char **neulist = (char**)malloc((size)*sizeof(char*));
   stringlist = neulist;
   stringlist[0] = "EMPTY";
}

void ArrayList::display_string_list(){
   Serial.begin(9600);
  for(int i=0; i<size; i++){
    Serial.println(stringlist[i]);
   }
}

char** ArrayList::get_stringlist(){
  return this->stringlist;
}

char* ArrayList::get_item(int index){
  return this->stringlist[index];
}

void ArrayList::set_stringlist(char** stringlist){
  this->stringlist = stringlist;
}

int ArrayList::get_size(){
  return this->size;
}

In theory, there's no reason why you shouldn't be able to call it by using toCharArray(). You would need to call it like this:
String str = "text3";
char * buf = new char[str.length()+1];
str.toCharArray(buf, str.length()+1);

list->add_string_item(buf);

That allocates a char buffer, copies the string data into it, then passes that buffer pointer to the list to be stored. Note that the buffer is one character larger than the string, as it needs to add a null terminator at the end.
However, there is a major problem with the rest of your code, which could eventually cause your Arduino to crash or do other strange things (depending on how much you use the list object).
Unlike Java, C++ is not a garbage-collected language, meaning it won't automatically clean-up memory for you. If you call new or malloc() to allocate heap memory, you have to call delete or free() (respectively) when you're finished with it to deallocate it.
Simply overwriting a pointer with another call to malloc() is not enough; it results in a memory leak. This means the block of memory it was previously using is lost, and cannot be reused again as long as the program is running. On a platform like Arduino, which has limited memory, you can very quickly run out.
Fixing the design of your class is probably beyond the scope of an answer on this site. I would strongly recommend working through some C++ tutorials (of which there are hundreds online).
As a side note, you should generally use new/delete instead of malloc()/free(). It doesn't make much difference when you're using arrays of char or char*, but it's important if you want to allocate class instances.

Awesomely helpful :)  The toCharArray fix works, but you're right it does crash the arduino after a while.  Think I'll revert to array methods until I find time to rework the library..


text:
Can I power an Arduino with a computer's motherboard?
I was thinking of using my Arduino to turn on and off a computer remotely. I would like to know if the 5v header pin on a computer's motherboard (which I’m using instead of a USB because the 5v pin provides a constant power supply) can power an Arduino UNO without frying it. If the Arduino can be powered where would the cable from the 5v motherboard pin go into the Arduino?

↑ These are the pins I would like to use

Can you post a picture or a description of this pin? Is it just on a USB header?

There is 5V at the power-header-pins, but I would assume there is a current limiting resistor somewhere on the MB. Better options are using either the internal usb-headers (which have fuses for extra protection). Or use one of the molex connectors used for powering CD-rom drives etc. (Red is 5V, black is GND).

You want to tap off of the +5VSB pin of the ATX or BTX power supply connector and send it to the 5V pin on the Arduino. Where this will directly drive the VCC(5V) of the UNO.

Note that 5V of the USB basically drives the VCC directly, except through a MOSFET that acts as a blocking diode to prevent local VCC from flowing back to the 5V_USB.

Not sure if you are suggesting that the 5V USB is frying Arduino's. If so that is bad. If true; Fix that first.

That said (with good 5V usb) you should be able to find or configure (BIOS) so that a USB connector will remain powered, and allow a wake up from mouse movement. Hence a possible solution would be to use a Leonardo/Micro's Mouse emulation to do just that as to wake the PC, without any hardware mod's.
Freeduino Micro's are pretty cheap.

Applying power to the 5v header, will bypass the polyfuse. I personally would just cut up a USB cable and use the power and ground wires to connect to the PC's power.

I ended up using the cut up USB header method that Gerben said to power the arduino for anyone who wanted to know

As stated by @mpflaga you can power your Arduino by the 5v power rail. As @ Gerben mentions in a comment, doing this will bypass the polyfuse. Because of this, I create my own Arduino for less than $10 (US) with a power regulator. Using a  L7805ACP will regulate the power.
Part List:
• 1 x P-DIP ATMEGA328P-PU programmed with Duemilanove Bootloader
• 3 x Through-Hole 22pF Capacitors (2 for crystal and 1 for Analog power smoothing)
• 1 x Through-Hole HC-49S 16 MHz Crystal (for clock)
• 1 x 5 Volt regulator (peak current 2 A, nominal )(L7805ACP
  Input Voltage = 7.5 to 18 V
  Output Voltage Low 4.8 Volts Nominal 5 Volts  High 5.2 Volts)
• 1 x 22 uF Capacitor (to stabilize power rail during rapid current draw.

source: Stack Exchange

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

sort: votes


text:
How to send RPM data as analog input from arduino to Xbee
I am new to arduino and Xbee these stuff.
Trying to send RPM (obtained and calculated by arduino using puulse function) data from arduino to Xbee as analog input to xbee series1.
It seems XBee analog input read a range of 0 volts to 1.2 volts.
However, not quite sure how to implement and write the corret code.
Following are Arduino code and schematic circuit.
Any idea?
I really appreciate your help.
int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val;
float rps;
float read_rpm;
int pin_out=10;

void setup()
{
   Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(pin_out,OUTPUT);
}

void loop()
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

analogWrite(pin_out,(int)rpm);

Serial.print("RPM=\t");

Serial.print(rpm);

Serial.print("\t rps= \t");

Serial.print(rps);

Serial.print("\t dt=\t");

Serial.println(val);

}

analogWrite() generates PWM output (oh, PS : except on Mega, but certainly not on Uno), not a purely analog output. And, though I'm not yet familiar with Xbee, I'm not sure you'll achieve analog transmission with it. You could try using some form of DAC, but as suggested below it would be better to send info in digital form.

I would suggest you to send bytes instead of "analog value". When you calculate your value, not sure why you use float and then convert it to int, but here is how i would do. Communicate to xbee via serial communication, send bytes to xbee(its even easier than "analog value"). Added if statment to print RPM every second.
Here is my code:
#include <SoftwareSerial.h>
/* Serial communication with Xbee.
On Arduino pin 9 is Rx connect to Xbee Tx,
pin 8 is Txconnect to Xbee Rx*/
SoftwareSerial xbeeSerial(9, 8); // RX, TX

int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val,time;
float rps;
float read_rpm;
int pin_out=10;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(pin_out,OUTPUT);
  Serial.println("I am ready to send some RPM!");

  // set the data rate for the SoftwareSerial port
  xbeeSerial.begin(9600);
  time = millis();
}

void loop()// run over and over
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

/* Sending float to Xbee
Float is 4 byte size*/
serialFloatPrint(rpm);

int floatToInt = (int)rpm;

/* To send INT to XBEE
Int is 2 byte size*/
xbeeSerial.write(highByte(floatToInt));
xbeeSerial.write(lowByte(floatToInt));

/*Print RPM every second*/
If(millis()-time>1000){
  Serial.print("RPM=\t");
  Serial.print(rpm);
  Serial.print("\t rps= \t");
  Serial.print(rps);
  Serial.print("\t dt=\t");
  Serial.println(val);
  time = millis();
 }
}

void serialFloatPrint(float f) {
  byte * b = (byte *) &f;
  //xbeeSerial.print("f:");
  xbeeSerial.print(b[0]);
  xbeeSerial.print(b[1]);
  xbeeSerial.print(b[2]);
  xbeeSerial.print(b[3]);
  /* DEBUG */
  Serial.println();
  Serial.print(b[0],BIN);
  Serial.print(b[1], BIN);
  Serial.print(b[2], BIN);
  Serial.println(b[3], BIN);
  //*/
}

Thank you for suggestion Martyans. You mentioned On Arduino pin 9 is Rx connect to Xbee Tx,
pin 8 is Txconnect to Xbee Rx but in Arduino uno isn't pin 1 for Tx and 0 for Rx. Please excuse me if I am wrong. and one more thing I just want to send rpm from arduino to xbee and then xbee send rpm  wirelessly to another xbee. Is it necessary to use Rx in Arduino?

Arduino uno has one Hardware Rx,Tx. I use it to communicate with PC(SerialMonitor). Programically i make pins 9,8 Rx,Tx two have second serial communication. Thats why i need library #include <SoftwareSerial.h>

And about sending data. All the information is stored in byte shape, so it is easier to give Xbee byte and send to another Xbee. In your case, you give arduino "analog value". How he knows what value it is? How he can messure it correctly? There are to many risks to loose data and it is inaccurate.

I got error message --> invalid operands of types 'float' and 'int' to binary operator for  floatToByte[i] = (rpm >> 8*i);   //Float to Byte

I got these   arduino_to_xbee_serial.ino: In function 'void loop()':
arduino_to_xbee_serial:45: error: invalid operands of types 'float' and 'int' to binary 'operator>>'
arduino_to_xbee_serial:57: error: 'If' was not declared in this scope
arduino_to_xbee_serial:57: error: expected `;' before '{' token

reduced to this arduino_to_xbee_serial.ino: In function 'void loop()':
arduino_to_xbee_serial:45: error: invalid operands of types 'float' and 'int' to binary 'operator>>'

Yes, zalt. I was in a hurry, see updated answer.

It worked. Now, how I can see the received serial data on X-ctu? I mean how should I set the parameters on X-ctu in order to see received serial data?

I realized now, still I can not receive data.

Hello zalt. To get data on Xctu you have to connect xbee to pc. If you use other arduino to receive data, then you can use Serial.print. Could you try to start from zero. Step 1: Test communication, send something from one arduino and read same on other, then proceed next steps. Next steps: calculate RPM; next: Send calculated RPM; Last: Confirm received data is correct

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


text:
Methods to prevent Accelerometer values changing from current spikes
I've connected an Arduino Uno to a MAX7219 IC, which is connected to only one standard 8x8 LED matrix, and an ADXL355 3-axis accelerometer. I use the matrix initially, and turn on all LEDs, while taking the "rest" values for the accelerometer to base all other calculations on. However, what happens is the current spike the LEDs create messes up the values - they become closer to 300, instead of the 230 they settle on when the spike is over. I've tried preventing this by adding up to a 5-second delay between the LEDs turning on and the rest values being measured. However, the problem still persists, though to a somewhat lesser extent.
Are there any methods to prevent this more effectively?

It seems to be a voltage drop issue. Potential solutions: add decoupling caps in your circuit, if not enough, use distinct power supply for MAX7219.

Adding a distinct power supply for the MAX7219, as suggested by @jfpoilpret, solved the issue.

I think you can just run the accelerometer from the 3.3V supply. The 3.3V should remain pretty stable, even if there is some voltage droop on the 5V.

@Gerben My particular accelerometer was in fact rated for 3.3V, so it was already connected there. The spike was still, IMO, unacceptable.

Weird that the noise or drop propagated to the 3.3V. You could also try adding some more capacitors. That is, unless you're okay with adding a second power-supply, of course.


text:
Improvement security in a domotic project
I recently started with a domotic project, I began creating a lock opening with a RFID
currently I'm trying improving the code (I took from http://forum.arduino.cc/index.php?topic=256260)
but I have some question about the security of this system (or any in the domotic way).
First, I know any system is 100% secure. starting from there, I was thinking, what happens if someone known that the system is built in the arduino platform and has some knowlege about it, that person can create a sketch, upload to the board and make "opening" all the pings?, they will have access to that room or thing I'm protecting (or trying). This is just a excercise, I don't want to go in depth about the external security that the board/system must have.
So, searching topics about it, I didn't find anything to help in the solution of this theoretical problem. I read some articles about the bootloader and I think, the solution can be there, I know Arduino is a openSource solution, but I think it doesn't mean insecure, so I think some kind of system who check a key before to load a sketch can help. It can have a default key, who can be used to the developing process, and other key (any) who must be verified, in the current sketch.
I'll try to explain it a little better:
Developing Mode
Bootloader [No Key] -----> can upload any sketch
Production Mode
Bootloader[check mode] -----> [Sketch with the secure key]
[Upload New sketch] -----> Bootloader[check the key in the new sketch with the key in the current sketch] (allow or block access, according as appropriate)
I don't have deep knowledge in criptography or bootloading, so I don't know if it's corret solution. I saw there are some way to "download" the code of the board (in a bin), I don't know if with this way the key will be exposed.
can someone tell me if this basic security would be helpful?
if it's, can be possible to implement? how?
Will the key be exposed in the bin (in case of download)?

Just make sure no one has access to the Arduino. By e.g. Placing it in the room you've locked with it :-). Once people have access to it, all bets are off. They might even replace the arduino entirely, negating any write protection you have added. People could also hack your developer PC and alter the compiler to create a backdoor in all your sketches. True Software security is pretty much impossible

Thanks Gerben, that is why I started saying about a system isn't 100% secure.
But you have some good point, the question is thinking with a specific scenario, 1. they don't have much time to replace a new arduino, they only have access to a usb port.
But really, having new point of view always helps to improve some things, even if they're too obvious.

First of all, a quick rule that you should follow... It is called Kerckhoffs's principle. Wikipedia states it as this:

A cryptosystem should be secure even if everything about the system, except the key, is public knowledge.

So, you're never going to reach "full security."
If the attacker can physically access your Arduino, all bets are off. They can upload new code, replace the Arduino, or just simply rewire your circuit so the door opens.
Also, they may be able to remove the RFID module and replace it with another Arduino board that sends random data in the right format hundreds or thousands of times a second. If they find the key code, they can make a new RFID tag with that ID. Thus, it is essential to keep that ID private.
So here's what you should do (in this scenario, password = RFID key's ID):

Make sure they can touch or access as little as possible. If you can, embed the RFID receiver inside a wall so they don't know where the receiver is and would have to break the wall to access it. If they break the wall, they could break the door, so this isn't necessarily a major security flaw. Of course, remember the sensitivity of your receiver.
Obfuscate your code: If you do something where you combine only certain bits/bytes of a few different strings to get a passcode to be compared to the sensor value. Of course, the compiler will remove most of this in an attempt to optimize your code. Note that this isn't actual security, just making the intruder having to do more work. A lot of people discourage this since it gives you a false sense of security, but I encourage it because it will take a little bit longer to hack into your application if they get your code. Remember that at any time they can use Serial.println(finalPasswordHere);.
If you're really worried, hash it. AVR chips probably don't have enough power to do advanced hashes like SHA-512. There seems to be a few MD5 hash algorithms for Arduino. MD5 isn't really secure with only a few digits, but if you have a 30 character hash that would take a long time to brute-force it. Add a salt with a ton of random characters (ex: lsjJK399!$%^&flk2) that aren't normally found in lookup tables. You'd combine the salt and the ID for the tag into one hash and put that in the code. Then, you'd hard code that hash into the main code. When you want to check if the ID being scanned is correct, you'd hash it with the salt and then compare that to the known hash. If you have more than one ID in the system, it's a good idea to have a different salt for each.

Annonomus Penguin, thanks for that detailed answer.
It's a good start, Is truth that never going to reach a "full security", but also is truth you can always keep improving something already done.
the three point are very important and useful, the last one very useful at level of code, I'm trying to asking myself some dumb/obvious topics who can be improved, in this kind of situation the time is gold, so one second of a dumb layer of security can really be a difference
thanks again.

A major factor in digital security is physical security. If you want a secure system you have to keep the bad guys from being able to connect wires and such.
If you have your Arduino inside a secure box inside your locked house, and it is not connected to the internet, the only way an intruder will be able to access it is to get into your house. Once inside the house you should require a second, higher level of security to unlock the Arduino's enclosure and muck with it.
If the Arduino is inside your house and an intruder doesn't have physical access to it, they can't install new apps on it or do ANYTHING with bootloaders.
If you don't use encryption of some sort you will not have very good security.
You can build an RFID or NFC system that uses a challenge-response scheme with encryption.
Something like this: When the house detects a unique RFID identifier, it generates a random number and encrypts it with that key's public encryption key. It sends the encrypted number to the key, which decrypts it using it's private key, then re-encrypts it with the house's public key and sends it back. The house decrypts the number, verifies that it is the correct number, and only then unlocks the door. The house is programmed to time out pretty quickly if it doesn't receive the correct key, to avoid brute force cracking of the encryption.
You also want a system where after a modest number of wrong responses, the system locks out for a couple of minutes.
With crypto, it doesn't matter if an intruder captures the RFID/NFC communication between the house and the key. What's sent is a one-time, encrypted code. Without the encryption keys, the intruder can't do anything with that data. It just looks like noise.
Even better is to add second factor authentication like a numeric code the user has to type, some sort of biometric scan, etc.
The above requires a fair amount of smarts in the key. There are RFID chips out there that have built-in crypto support. I don't know how good they are however. You either need hardware crypto support or a pretty high powered chip (ARM or better) to do crypto in a pocket sized device.

Thanks Duncan, I imagine a system like a Crypto have to be very effective in terms of encryptation.
What I'm trying to make, is a excercise to go step by step, and think things too obviuos and try to improve it it's possible, a set of poor and obviuos security layers, can make a difference.
I'll make some test with that random number with public/private keys, It can be a huge difference, this combined with some real time alerts can be very useful


text:
releasing memory in sub-function
I'm doing a program who get a line from the SD and shows it, this function is called getData()
FULL CODE:
#include <SD.h>
#include <MemoryFree.h>

File myFile;
int stringIndex = 0;
int cursorPosition = 0;
char inputString [25];
char inputChar;
boolean endOfLine;
char fullPath[11];

void setup(){

  Serial.begin(9600);

  Serial.print("Initializing SD card.");
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

}

void loop(){

  Serial.println(getDataSD());

  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
}

String getDataSD(){

  memset(inputString, 0, sizeof(inputString));

  getFileNameSD();

  myFile = SD.open(fullPath);

  if(myFile){
    myFile.seek(cursorPosition);

    endOfLine = false;

    while(myFile.available() && endOfLine == false){
      inputChar = myFile.read();

      if(inputChar == '*'){
        while(inputChar != '\n'){
          inputChar = myFile.read();
        }
      }else{
        cursorPosition = myFile.position()-1;

        if(inputChar == 10 || inputChar == ' ') inputChar = myFile.read();

        while(inputChar != '\n'){
          if(stringIndex < 25){
            inputString[stringIndex] = inputChar;
            stringIndex++;
            inputChar = myFile.read();
          }
        }
        inputString[stringIndex-1] = '\0';
        stringIndex    = 0;
        endOfLine      = true;
      }
    }
    myFile.close();
  }
  return inputString;
}

void getFileNameSD (){

  char folder[] = "/ACC";

  checkFolderSD(folder);

  myFile = SD.open(folder);
  myFile = myFile.openNextFile();

  if(!myFile) myFile.rewindDirectory();

  if(myFile){

    strcpy(fullPath,folder);
    strcat(fullPath,"/");
    strcat(fullPath,myFile.name());

    myFile.close();
  }
}

I don't have problem with this function(getDataSD). To get the name of the file, I've created another function who looks for a file in a specific folder, this function is called getFileNameSD()
I'm having problem with this last function, it's not releasing or overwriting some data, so every time it's called, it is stored new data in memory
I've included the memory Free library to see where is the problem. When I call the getDataSD and write the file manually I dont have problem.
myFile = SD.open("/ACC/11001");

Serial monitor
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/

the memory always is the same.
but not when I call the getFileNameSD()
myFile = SD.open(getFileNameSD());

Serial monitor
freeMemory()=6571
/-27/-26/-56/
freeMemory()=6540
/-27/-26/-56/
freeMemory()=6509
/-27/-26/-56/
freeMemory()=6478
/-27/-26/-56/
freeMemory()=6447
/-27/-26/-56/

I know I'm doing something wrong with getFileName() but I don't know what is, can anybody help/explain me?

Where did you declare and define fullPath?

sorry about that, was typo, I corrected the first post

Well, finally someone found where was the problem.
In the getFileName() function, I open two instances of the file but I close just one.
here is the answer:
#include <SD.h>
#include <MemoryFree.h>

File myFile;
int stringIndex = 0;
int cursorPosition = 0;
char inputString [25];
char inputChar;
boolean endOfLine;
char fullPath[11];

void setup(){

  Serial.begin(9600);

  Serial.print("Initializing SD card.");
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

}

void loop(){

  Serial.println(getDataSD());

  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
}

void getDataSD(){

  memset(inputString, 0, sizeof(inputString));

  getFileNameSD();

  myFile = SD.open(fullPath);

  if(myFile){
    myFile.seek(cursorPosition);

    endOfLine = false;

    while(myFile.available() && endOfLine == false){
      inputChar = myFile.read();

      if(inputChar == '*'){
        while(inputChar != '\n'){
          inputChar = myFile.read();
        }
      }else{
        cursorPosition = myFile.position()-1;

        if(inputChar == 10 || inputChar == ' ') inputChar = myFile.read();

        while(inputChar != '\n'){
          if(stringIndex < 25){
            inputString[stringIndex] = inputChar;
            stringIndex++;
            inputChar = myFile.read();
          }
        }
        inputString[stringIndex-1] = '\0';
        stringIndex    = 0;
        endOfLine      = true;
      }
    }
    myFile.close();
  }
}

void getFileNameSD (){

  char folder[] = "/ACC";
  File myDir = SD.open(folder);

  memset(fullPath, 0, sizeof(fullPath));

  if (myDir){
    myFile = myDir.openNextFile();

    if(myFile){
      strcpy(fullPath,folder);
      strcat(fullPath,"/");
      strcat(fullPath,myFile.name());
      myFile.close();
      myDir.close();
    }else{
      // Handle file not found
      myDir.close();
      fullPath[0] = '0';
    }
  }else{
    // Handle directory not opened
    fullPath[0] = '0';
  }
}

Ok,
I don't know, why your memory is leaking, but anyway, your program won't work safely.
You defined an array (fullPath) inside the local scope of your function. You return it, which means, you return a pointer to this array. But at the same time, this array gets invalid, because you leave the local scope of your function.
Better define that string outside the function and give it as a parameter to the function. Then you aren't in danger of accessing an invalid pointer. Furthermore your memory leak won't appear.

thanks for the advice Arister, I've edited the code to fix that problem, unfortunately it didn't solved my problem.


text:
pulseIn on ESP32 return 0 regularly
I'm using pulseIn on an ESP32 for measuring a frequency between 500 Hz and 10 KHz. I measure both the HIGH and the LOW time, as all simple examples suggest. 95% of the time the result is correct, but sometimes pulseIn returns 0. It can happen on the HIGH or the LOW measure. I'm using GPIO27, which should not be a problem. On a digital scope the signal is very steady and clean.The code is very basic.

const int pulsePin = 27; // Input signal connected to Pin 12 of Arduino

unsigned long Htime;
unsigned long Ltime;
unsigned long Ttime;
float Frequency; // Calculated Frequency

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

void loop() {
  Htime=pulseIn(pulsePin,HIGH);
  delay(10);
  Ltime=pulseIn(pulsePin,LOW);
  Ttime=Htime+Ltime;
  Serial.print(Htime);
  Serial.print(", ");
  Serial.println(Ltime);
  delay(100);
}

The output looks like below:

Of course I can add code to ignore measurements with a 0 result, but any ideas on why they appear?

pulseIn() returns 0 in case of a timeout

I'm aware of the time-out, but then it will take some time before it results to 0. In this case the 0 result come just af fast as the normal readings. If I disconnect the signal it all return zero, but also the reading becomes very slow. The zero-result above come just as fast as the normal readings. And even if I use the time-out parameter, with like a few seconds, the zero-readings come jus as fast as the normal, so there is no time-out, otherwise I would have to wait a few seconds.

It might be noise on the signal. If you just want to measure a frequency you can use the counter modules to count pulses in a specific range. This would probably be more precise than you approach

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


text:
Arduino: How does digitalRead read a value? And what is this value?
I have a Arduino Uno with 14 digital pins. I believe they have an output of 5V.
But they can also input values. I'm not sure of what exactly it reads when it does that (amperage, voltage ...). Also, how do they read it? How can such a tiny thing possibly know what it's receiving?
Just to provide a little more context to the reading part of this question, here's an example circuit. I have a 5V battery connected to an LED and a 220 Ohm resistor. Next thing in the circuit is a wire, which exits the main circuit and connects to a digital pin on the Arduino Uno (here it reads the value). Then the main circuit closes by connecting to ground.
Hope my question is clear enough :)

@NickAlexeev - there's nothing "Arduino" about this question to justify migrating it.  It's really a "how does a microcontroller work" question.

Modern digital electronics is made from many tiny electronic components called MOSFETs (a type of transistor). They can be switched on and off using a voltage, and a very small amount of current. They use the majority of the power when they are switching on and off; the rest of the time they use virtually no power. It this very low-power capability which allows us to make complex digital electronics.
Electronically, a MOSFET looks like a tiny capacitor, which triggers a very low-power switch, on and off. Once there is charge on the MOSFETs capacitor, the switch will stay on or off.
A modern large-scale processor, for example the type of device Intel makes, contains billions of MOSFETs, but requires less than 100W, and switches billions of times/second. So we can be confident that a MOSFET can be switched using much less than 1/10,000,000W. At 5V, that means 1/50,000,000A, or 0.000,000,02A, i.e. 0.02µA.
So, the input circuit, connected to an Arduino's pin has some protection, to protect the MOSFETs from static electricity (which could damage or destroy the capacitor), then a complementary pair of MOSFETs (called N-Chanel and P-Chanel). The input voltage switches one on, and the other off. It typically requires less than a micro-amp of current, but at a voltage close to ground or 5V. See pjc50's diagram.
So an Arduino input pin, connected to the 5V end of the resistor and LED will take a tiny amount of current, for a short time, to switch on.
If that pin is connected between the LED and resistor, at some voltage less than 5V, but more than 0V, then it might not switch fully. It might not give a reliable value of digital 0 or digital 1, and might switch high and low rapidly influenced by electrical noise in the environment.

Great explanation, thanks for taking your time to write this!

It measures voltage.
The input circuit is conceptually similar to this:

Voltages close to 5V will turn the lower transistor on and the upper one off.
Voltages close to 0V will turn the upper one on and the lower one off.
Voltages in the middle will turn both on to some extent, which is not recommended, and may be read as either 0 or 1 with a threshold in the middle.

"Such a tiny thing" contains tens or hundreds of thousands of transistors.

Great explanation, the image is really useful!

If somebody(like me) is looking for a explanation in terms of registers, the voltage at a pin when it's a digital input can be accessed with the PINx register, with a bit being used per a pin. Based on the value in the specific bit of the DDRx register, if it's 0 (an input), the voltage at the pin is represented by the bit in the PINx. When it's 1 (an output), the bit at the PINx register will be the value in the PORTx register for the specific bit(the value written). If the bit in the DDRx register for the pin is 0(an input), the bit in the PORTx register represents whether the internal pull-up resistor should be connected to the pin. x is used to mark the port (A,B, for example).
Edit: I've started working with the ATtiny10 for a specific, but most likely just-on-paper project. It has the separate PUEx register for the internal pull-ups. It has only 6 pins, with 4 or those being accessible as GPIOs. The pins have specific modes where every pin requires slightly different flag changes for changing the mode.

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


text:
How to eliminate noise from PWM controlled 12V fan at low speed
I am trying to build a simple fan controller (single fan). So far I have successfully created a circuit which powers the fan with an external 12v DC adapter and added a transistor (NPN) to switch it on and off. The transistor is connected to a PWM port on the Arduino.
When putting HIGH on the port the fan works perfectly at high speed, but when I want to lower the speed (say analogWrite(fanPin, 150)) it starts to make a humming noise. I believe this is caused by the use of PWM.
What is the best way to control the speed of the fan without (too much) noise?
ps. The fan is a Cooler Master 3-wire PC fan. Transistor is a P2N2222A.
Update: Here is the schema I am using:

Martynas pointed out that I should include the circuit, I will do that later today when I get home from work.

Try using pins 5 or 6, as those pwm pins are running at twice the frequency of the other pwm pins.

When I try your suggestion the noise changes but isn't gone.

I had the same problem with a 5V fan.  Something simple worked for me: To decrease the PWM frequency.  You probably want to do this using pin 9 or 10 (for the Uno) as changing the frequencies of other PWM pins messes up the delay and millis functions.  Details on how to do it and a very convenient function are provided in http://playground.arduino.cc/Code/PwmFrequency.  In my case, using the lowest frequency possible (31250/1024 = 31Hz), I completely eliminated the hum for higher speeds and significantly reduced it for lower speeds.  And by the way, I used the PWM pin to drive a MOSFET since the current of my fan was 140 mA, much higher than the 20 mA Arduino pins can safely provide.

I'd be interested in why this works. Is this sound due to some mechanical side effect of the motor or something more interesting like the hum produced by a transformer which (I believe) isn't mechanical.

It might help to use a capacitor to smooth your PWM signal.
See http://ww1.microchip.com/downloads/en/AppNotes/00771b.pdf

That document describes adding a capacitor to reduce slew rate while using an NPN transistor. Is there any way to slow the slew rate while using a MOSFET?

There will be no real difference between using a capacitor to smooth the output from an NPN transistor and filtering the output of a MOSFET. From the point of view of the load, an NPN transistor (driven fully on or off) is a switch with a series resistor on it, where a MOSFET has very low resistance. The extra resistance of the NPN transistor would slow the charge rate for the capacitor a little, but you can pretty much ignore the difference.

A capacitor is a crude low-pass filter. It starts to charge up during the ON cycle of the transistor, and starts to discharge when the transistor is off. Since it never fully charges or discharges, it evens out the peaks and valleys of the PWM signal to a rough average of the voltage that is fed to it. (Without a load, the capacitor will charge up to almost the full supply voltage since it during the ON cycle but doesn't really discharge.)

Try using pin 3 (or 11) and lower the prescaler of timer 2 using the following code in your setup;
//move from /64 prescaler to /32 prescaler
TCCR2B |= _BV(CS20);//set bit (remove this line for a /8 prescaler)
TCCR2B |= _BV(CS21);//set bit
TCCR2B &= ~_BV(CS22);//clear bit

Halving the prescaler will double the frequency.

When I try this I get a noise with a higher frequency.

The goal is to use a frequency high enough to not be audable by the human ear. Have you tried removing the line with CS20?

Yes, I tried that too, but I still hear an annoying noise.

I can also confirm that SAS answer ist correct. I tested it with a 5V DC fan. I hear a very high noise at lower speed, but you have to listen closely, and a very fast clicking noise at higher speeds.
All in all i would say lowering the PWM to the suggested 31Hz did it for me but it is not a perfect solution.

25kHz power PWM solved this problem for my 3-pin fan. Diode had no effect on noise, it fixes another problem (EMI).

Do you talk about 4-pin fans?

@SimSon no, I did 25kHz to power line. 3.3V GPIO from MCU is connected to darlington transistor. Didn't check by scope, likely there are all kinds of basic electrical problems, so not proposing any particular circuit. But the general idea to go high frequency seems an obviously right choice for me.

SAS is correct - lowering the PWM to 31Hz works great. Tested using a 12v fan.  Before lowering the PWM, the sound from the fan was a loud "WHEEEEEeeeeeeeee" sound at any speed other than full speed.  Low speed made the sound worse.
After lowering the PWM frequency, the noise is inaudible at higher speeds.  At lower speeds you might hear a light "clicking" noise.  The sound reminds me of the faint "clicking" noise you hear as the valves on a car engine open and close.

There is also the possibility adding a capacitor bypassing the transistor. But you have to be careful, if the capacity is to big you could damage your transistor.

I get that this post is 4 year old, but I successfully removed all fan noise with simple electrolytic cap and one ceramic on output, after adding caps you need to bias RPM. You can still get some relay low squeak coming from mosfet but only on low RPM

coment add circuit to know what you have done
Does your circuit looks similar like:
Do you use resistor for transistor? Diode for fan?

I suspect that you do not have diode.
The purpose of the diode is to allow current that is flowing in the motor coil to continue to flow in the same direction when the transistor turns off. When the transistor turns off, the voltage at the transistor collector will rise as it was flowing out of the motor. From Vce(SAT) it will rise above the power supply voltage and stop only when the transistor breaks down (or when it starts to ring with parasitic capacitance). By putting a diode from the transistor collector to the +12V rail, you prevent the voltage across the transistor from exceeding 12V and and allow the motor current to continue to flow.

If you need to ask the original poster questions, please do so by commenting on the question itself. An answer isn't the right place to do that.

@PeterR.Bloomfield i understand everything. Sorry for that, but i added an answer too. I would comment if not 44 rep. pts...

I added my schema. It's indeed very similar to yours. Only I had to connect the grounds to get it working.


text:
NodeJS (Galileo-IO) + Arduino sensor library
I've done some basic apps with NodeJS firmata where I can connect to my Arduino Uno and do the basics like reading a pin or doing a servo write. I'd like to go further and play with some different sensors from vendors like Adafruit.
Many such sensors appear to come with their own Arduino libraries. Using NodeJS firmata to communicate with my Uno, could I somehow use the sensor libraries? Maybe by including their header files in the Standard Firmata sketch before uploading or...? But then I don't know how I'd get at their methods from my NodeJS app.
Even better, I'd love a little direction on how to go about using an Arduino sensor library in a sketch, and use Galileo-IO to interact with the sensor that way, if possible.

Including the header files for the libraries in the standard Firmata
sketch is only the first step. You will have to also modify the sketch in
order to actually use the libraries. You will have to figure out a way
of interacting with the libraries through the Firmata protocol and
implement this in your modified version of the sketch. You will then
have to modify the JavaScript side to enable these new interactions.
That's where you will write the missing methods


text:
How do voltage and resistance work for two 5v servos when using an external 12v power supply?
I have a 12v/1.5 amp barrel plug power supply on my Arduino Uno. I have two servos that say they are rated for 4.8v to 6v, but no amps are specified. When my circuit is configured as it is in this image, it appears to work fine. (In my test sketch, I'm constantly and simultaneously rotating them from 0 - 180 degrees and then in reverse.)
But I don't understand why it works. I assumed the 5v pin can only supply 5v of total power to the whole configuration. Is it instead supplying a regulated 5v at as needed between both servos from a total pool of 12v (presumably up to 10v at once)? Do I need voltage regulation? Shouldn't I have to know the amps for the servo(s) and use some sort of resistance?
Thanks for any information and advice you can share on learning about the concepts underlying a situation like this.

Update: I ultimately modified my approach based on the feedback received here by wiring a separate 5v/2a power supply to the breadboard for the two servos, and wiring the rest of the circuit appropriately (using a common ground, etc.).

Do not do this.  Although the "total voltage" type of concern you raise is based in misunderstanding, there are real problems.  A servo encountering mechanical load can easily draw more power than the arduino's regulator can supply, causing brown out and misoperation (or if you are lucky, merely reset) of your program.  Even when not causing brown out, servos are notorious for putting "grunge" noise onto power supplies.  Give your servos their own regulator, preferably a switching one.

Ugh. I've got a lot to learn! Thanks for mentioning this. You mean something like this (two: one for each servo)? https://www.sparkfun.com/products/107

Because the supplies of both servos are connected in parallel, they both see the same voltage. Hence there is no "pool", both are being supplied the same 5V.
There is a regulator on the Arduino which reduces the 12V input down to 5V. It does so by burning off the other [7V times however much current is being used] as heat. Since you are supplying it with 1.5A, the most it can supply is in turn 1.5A.

Hmm, I understand less about this than I realized! I don't get how you can send 5v of electricity to two devices that both need 5v at the same time and they are able to work simultaneously. And I reckon I get that 1.5A is technically available to the servos, but I don't understand why I don't have to find out if the servos need a lower amount of current and put in resistance down to that amount, if necessary. (Or put another way, did I just get lucky that they can handle receiving 1.5A?)

"Volts" isn't a quantity, it's a characteristic of the electricity itself. It's the amount of energy imparted to each unit of charge. As for the current, most devices will only draw what they require regardless of how much is being supplied. The exception to this is P-N semiconductor junctions, since they absorb energy as charge flows across them ("reduce the voltage") and are generally not affected by current beyond consumption of power.

Addition to Ignacio. Explanation from real life.
Gregir, look at your home devices like TV, micro wave, fridge and so on. They all need 220-230 V AC and you can plug all them to one socket. As Ignacio said voltage doesn't plus. The current does plus, for ex. you have 2 servos connected in parralel, both 5V, no load current 0.1A. So to run them with no load you will have to supply 5V and 0.1+0.1=0.2A.
I tried to explain at very basic level ;)

Ah, of course! That makes good sense. I am still a little confused about the servos and their amperage. How do you get the 0.1A? (I can't seem to find it anywhere on the data sheets for the servos or on the manufacturer's site.)

Gregir that's for example :) Different motors consumes different amount of current. Bigger motor = more power = more current. First mini servo in google search http://www.rctoys.com/pdf/hitec-servos/HIT-HS55.pdf .You can google information about servos like this interesting pdf http://www.bpesolutions.com/bpemanuals/Servo.Info.pdf

Ah, OK. I see so few examples of people using resistors with servos so far, and hadn't found much info on my particular servos. Easily confused at this stage. Thanks for setting me straight.

Be careful though as a servo that stalls due to load will easily draw up to 1A so if they both stall you might draw more than can be supplied.


text:
Pattern library for addressable LED strips
Is there any central place that we can get drawing pattern functions for the addressable LED strips like the once based on the WS2812B component?  These are sold on the Adafruit site under the NeoPixel name.  For example I know of a few pattern examples like the Larson Scanner (Cylon), a candle light flicker or a rainbow pattern.  However I could not find a single pattern repository.
I am working on a project for kids learning to program the Arduino and it would be nice to have all the patterns in a single place and to be able to switch between the program examples with a mode switch.
If people send me links I am happy to post a blog of them.

I have never found a single pattern repository, however FunkBoxing has a fantastic sketch with 30 or so patterns well documented. http://funkboxing.com/wordpress/?p=2154
He uses the Fast_SPI (now FastLED) library, which is truly exceptional!
https://plus.google.com/u/0/communities/109127054924227823508

Thake a look at this library.
In this video you can see some of the many animations available.

I like the names you have given each pattern - Sparkle, Bubble etc.


text:
giving delay function to output
I want my arduino to give the output at a specified delay .The delay is calculated from a polynomial equation.
unsigned long t=40*Vin*Vin-760*Vin+4320;
delay(t);
digitalWrite(ledPin,HIGH);

but while doing this i was unable to get the delay accurately while observing it through oscilloscope??

Delay does not accept negative values, where does Vin come from? Do you make sure t is always positive? Post some code so we can try help you better.

@bpinhosilva, that quadratic function is positive for all values of Vin that don't cause overflow. Its min value is t=710 @ Vin=9.5

What do you mean by "i was unable to get the delay accurately"? What do you observe and what do you expect instead?

You should consider putting the pin low again after some time, as you want to measure the time between pulses?

I suggest you look into using a hardware timer rather than using delay(), I suspect it will give you more accurate timing.
Timer configuration is not as straight forwards as using delay - they don't work in milliseconds or microseconds, but instead in multiples of clock cycles, which (I find) makes configuring them a little difficult to understand, but it is possible to set the interval of a timer within its own interrupt routine.
Another advantage to using timers is that your code can do other things whilst waiting between interrupts.
Have a read here for more information and simple examples:
http://playground.arduino.cc/code/timer1
or just Google "Arduino timers" for other examples and explanations.

Perhaps you had in mind something like this fragment, which will raise ledPin for the time you calculated (in msec) then lower it again?
// ...
unsigned long t=40*Vin*Vin-760*Vin+4320;
digitalWrite(ledPin,HIGH);
delay(t);
digitalWrite(ledPin,LOW);
// ...


text:
Why is my boards.txt file not being found?
I'm using the ino command line tool for the first time. When attempting to build my first sketch I run:
ino build in the project directory.
I get the following error:
Searching for Board description file (boards.txt) ... FAILED
Board description file (boards.txt) not found. Searched in following places:
  - /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino
  - /usr/local/share/arduino/hardware/arduino
  - /usr/share/arduino/hardware/arduino

What's going wrong here?
I've found an open issue here: https://github.com/amperka/ino/issues/240
But I'm wondering if anyone has a workaround.

I got a hack to work  (macOS) by symlinking the files to where ino expected them to be.  But now I'm running into this issue: https://github.com/amperka/ino/issues/149
FWIW:
cd /Applications/Arduino.app/Contents/Resources;
ln -s Java ../Java;
cd /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino;
ln -s boards.txt avr/boards.txt;

Did it for me as far as finding boards.txt goes.
Still Broken otherwise. (Not marking as answer)


text:
Flash "sketch" hex over ISP, without bootloader - possible?
I'm wondering if it's possible to flash the arduino sketch into a AVR, without using a bootloader - over ISP. I'd use the BSD programmer, which is basically parallel port with some resistors.
Let's say I use the Arduino IDE, try to upload with "verbose" (no actual arduino is attached) - it shows path to the hex in the verbose output, and I "steal" the file.
Now I'd flash it using avrdude onto a blank 328 via ISP - would that work?
I assume there needs to be a 16Mhz crystal, is that it? Any other pitfalls I have to be careful about?

You don't need the arduino bootloader on the chip, if you are programming it using ISP.
It looks like BSD is no longer supported by avrdude.
In the Arduino 1.5 IDE you can add programmers, so you can do the uploading right from the IDE, instead of 'stealing' the hex file and manually uploading from the command line.
If the chips are blank you probably need to change the fuses first.
You don't need a 16mhz crystal. The atmega328 has an internal 8mHz oscillator inside.

Avrdude seems to support BSD just fine, look: bsd              = Brian Dean's Programmer, http://www.bsdhome.com/avrdude/ in the programmers list. The link is dead though, but there's schematics on google.

-c bsd doesn't work on my 2 versions of avrdude. But that might be because I'm on a Mac. So Windows might work fine.

Macs don't usually have a parallel port, so it's not surprising that a parallel port programmer isn't supported on it.

Edited to mention that using the internal oscillator means you can't use the UART reliably ( you can calibrate it but if the temperature changes it will be wrong again)

@cb88 I think that only applies to the higher baud-rates. Also, please add this information as a comment, instead of an edit. I don't think such an edit is appropriate.

Probably if you have ideal code setting up the baud rates... but it certainly isn't foolproof and the Arduino guys are known for getting those not quite right.... I think their code there is a bit better these days but it's still a likely source of headaches. And they acutally had more issues at low baud rates.


text:
Wire.endTransmission() Hangs
I have written a code that transmits data over the I2C channel, The device ID and every other stuff is working fine. The only issue being that my code gets stuck at Wire.endTrasnmission().
I found the issue using Serial debug messages.
Strange thing:
When i disconnect the SCL line (A5 on arduino Pro Mini), the hang disappears and the code starts to function again.
A search brought me to this forum
http://forum.arduino.cc/index.php?topic=66353.0
where a guy talks about the code snippet
if(hang)
unfreeze();

is this possible, if yes where do i place it?
Observation:  The hang goes away if i disconnect the SCL line on either of the arduinos communicating, the sam edoes not happen if i disconnect the SDA.

The only place some code to fix the problem could go is where code is still running during the hang: inside the twi library.

i tried changing the buffer size as pointed in some forums, but still it does not work.

Look into the watchdog timer. You can set it up to reset the chip if the timer hasn't been reset for e.g. 2 seconds. Just call wdt_reset() in every loop.

The device ID and every other stuff is working fine. The only issue being that my code gets stuck at Wire.endTransmission().

Nothing is transmitted until you call Wire.endTransmission() so that is where it will hang.

You should not try to do Wire transmissions inside an ISR (if you are doing that).

There is an alternative to the Wire library which times-out rather than hanging. It is at: Arduino I2C Master Library.

Make sure you have pull-up resistors on SDA and SCL. Typically 4.7 k from both to +5 V.

If none of that helps, please post your code.

Arduino I2C Master Library link is dead.  It's now on GitHub: https://github.com/rambo/I2C

@Casey (sigh) Let's hope that link doesn't go down. Amended answer. Thanks.

@Casey With a bit more reputation (like, 1000) you will be able to edit answers and fix things like that up, which is perfectly acceptable to do, providing you don't change the intention of the answer.

I think you can suggest edits with fairly low rep, I'm not sure exactly what that threshold is.

Thanks for that.  I'll have to learn how to do edits if SE ever gives me some big boy pants.  It's worth noting that the original DSS Circuits I2C library is on github (https://github.com/DSSCircuits/I2C-Master-Library), but it died 8 years ago and was forked and carried forward by rambo (https://github.com/rambo/I2C) which has some activity this year.


text:
Portable power for an UNO with a nrf24l01+ attached?
Okay so I have an UNO that has an nrf24l01+ attached. I want it to be completely wireless so free of the 5v USB power and the 12V wall plug. In this case what can I use? I do not wish to plug the power directly into the Vin as I am relatively new and afraid that it might fry the board. So I wish to plug it into the barrel jack. So I have read that using a 9v battery to power UNO is a waste of power as most of the power is translated into heat. Also, using 4 AA batteries seem to be a good solution except that I'm not sure if it has enough power for nrf24l01+ as I've read that an arduino with nrf24l01+ on batteries creates an unstable wireless node. I would like some help on what I can power the UNO with.

Vin is the same as the barrel jack (they are directly connected on the PCB). The NRF24L01 requires at least 2.7v. The uno board is however very inefficient (e.g. the usb-to-serial chip is always powered).

Oh I thought that the Vin bypasses the voltage regulator but it turns out that its the 5v and 3.3v that does bypasses it, not the Vin. Despite the fact that the uno is inefficient, thats the board that I need to use. So back to the question, since it requires at least 2.7v, 4 AA batteries of  6V should be enough right? I am unable to try it out as of now as I do not have the time to buy the necessary things to try...

That is kind of pushing the limits. 6v is the absolute minimum the voltage 5v regulator requires. If the batteries are drained a bit, they will go under this 6v limit. You could use 4 rechargable (1.2v) batteries to give you 4.8V, which you can connect directly the the 5v rail. But don't expect to get more than a day of battery life.

Hmmm... Alright. Thanks for the advice. I guess if no one else has solutions I will use 6 AA batts of 9V instead of a straight 9v batt since I need a high current. Thanks!

I've used the usb battery chargers (marketed to recharge cell phones) with great success on many different Arduino boards. They come in a variety of mAH capacities and are easily recharged with any powered USB port/power adapter.
Here's a link to one I've used. (I'm not affiliated with Duracell in any way).
http://ww2.duracell.com/en-US/product/instant-usb-charger.jspx

this is certainly a easy off the shelf solution, which likely suits this user

Sorry for the long wait in accepting your answer. I was setting up the exhibition in a location that was devoid of Wifi. I eventually went for the 6AA batts. But seeing your solution, I think it is the best and easiest solution. And its off the shelf as well!

Brilliant, much easier than trying to get batteries into the DC barrel adapter, which is what I was trying to do (and can’t find the barrel size/type anywhere!)

To get an idea of run time, I used this battery to power an Uno with a photocell attached for at least 16 hours. I was running a sketch to record the amount of sunlight to determine the best place for some tomato plants. The sketch didn't use any low power techniques. https://github.com/linhartr22/LightMeterLogger

Firstly if you only need short runs, go with the usb battery pack answer, but if you need the longest time from least batteries:
As has been pointed out, for best battery consumption an arduino board is not efficient due to power regulators and led lights. For best performance you want a standalone 328 chip with its BOD (brown out detector) reduced to 1.8v and then you can run it and the nrf24 chip off 2x AA batteries.
But all this might be a bit beyond you.
One thing though that will help your battery life is a PNP transistor or Mosfet on the +ve of your nrf24l01+ module triggered by a arduino io pin. as these power amplified versions dont sleep (per say, the chip does but not the PA) so it will always be consuming a large amount of power regardless of state. So just use your io pin to power it on and off for each use.
(that is unless you need it on always for recieving, in which case this wont help)


text:
How to read an RFID reader?
I want to connect an RFID reader to an Arduino board. The RFID reader has several wires attached, and the manual mentions them as follows:

Red: VCC +12V
Black: GND
Green: D 0/RX/4R+
White: D 1/TX/4R−
Blue: LED/CS
Yellow: Beep

There is also another black wire attached, but the manual does not mention it.
This is an image of it:

I have the red wire connected to the 5V pin and the black wire to the GND pin on Arduino board. Then I have the white wire connected to the RX pin on the Arduino board.
I'm trying to Serial-read the RX port using this code:
void setup() {
    Serial.begin(9600);
}

void loop() {
    if (Serial.available() > 0) {
        int b = Serial.read();
        Serial.print(b);
        Serial.print(" ");
    }
}

When I try to read a keyfob, only this is printed – nineteen times 248:
248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248

To me it looks like there's something wrong with the connection somewhere.
How can I properly read this RFID reader? If above assumption is not correct, is there something I should know?

Which RFID reader? Please post a part number or photograph. Please post all your code.

@NickGammon It's a cheap-ass RFID reader from China. They usually don't put a manufacturer's name or model number on it. I also have posted all my code, but that doesn't make it more clear.

Do you not have a phone with a camera in it? Anyway, this might help: RFID reader - HZ-1050

Are you 100% sure the fobs' standard matches the reader? Check if the ISO standards are the same.

@FuaZe Yeah, if I plug the RFID reader into an Access controller, everything's working.

Have you tried other baud rates? Could you paste a link to the manual or upload the manual itself? From what i could find quickly, the module supports 3 modes: RS232, RS485 and Wiegand 26/34. So the manual should provide some means of selecting a particular mode (perhaps the CS pin?). I suspect you arent actually using the RS232 mode, which is why you are getting strange results. If you can't find a way to select a mode, you could try brute-forcing it and try the WG26 mode next. This code from seeedstudio seems to do the job http://www.seeedstudio.com/depot/datasheet/RFID_630_WG.pde or you could look at the Wiegand protocol on Wikipedia and write your own code, since its relatively straight forward. Also a google image search turned up this link to Aliexpress: http://www.aliexpress.com/item/Waterproof-Security-Door-Access-Control-Wiegand-26-125KHz-RFID-ID-Card-Reader-EM4100-102A/1362129655.html; this is your reader, right?

That link looks much like his pic, and says "Output mode: Standard Wiegand26 Format For Access control "  so maybe http://arduino.stackexchange.com/questions/12927/parallel-connection-to-wiegand-26bit-rfid-readers would help.

Yeah, thats what i thought when i found the Aliexpress page, but his post says it supports 2 other modes according to his manual, so i'm not so sure. However, if there is a default mode, its probably the WG26 mode. From the link you provided, it looks like theres already a library (no surprise) that translates Wiegand https://github.com/monkeyboard/Wiegand-Protocol-Library-for-Arduino so its another option, i guess

From my personal experience, you should give some init time to the rfid reader to init.
Try to use a digital output to control the chip reset, and give it some milliseconds to init.
I had a similar behavior with a rfid reader and the reason was this I just told.
Good luck!


text:
analog serial read values are not equal
I have not used the Arduino in over 2 years and have forgotten a bunch of stuff I was wondering if someone could help me out. I have two analog sensors both the same connected to the appropriate analog pins. I am getting a read on the serial monitor and when i test the sensors the values are changing so i know the circuit is correct and everything is in the right place. I just have an issue with my code.
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue1 = analogRead(A0);

  // print out the value you read:
  Serial.println(sensorValue1);
   //Serial.print("val1 = " );
  Serial.print(sensorValue1);
  Serial.print(" ");

  delay(1000);        // delay in between reads for stability

   // read the input on analog pin 1:
  int sensorValue2 = analogRead(A1);

  // print out the value you read:
  Serial.println(sensorValue2);
  //Serial.print("val2 = " );
  Serial.print(sensorValue2);
  Serial.print(" ");
  delay(1000);        // delay in between reads for stability

 }

once i view this in the serial monitor it is not organized and the sensorvalue1 is skipping over to the next line. I would appreciate the help.

There are two sensors so there should be two values but in the picture the values are all messed up i would ideally like it to give me a two seperate values one for each sensor
val1= sensorvalue1
val2= sensorvalue2

Can you paste here the serial monitor output that you get, and write what you would expect? Otherwise your question won't be very clear to everyone.

jfpoilpret i have updated my question thank you

The delays likely won't affect the stability, since the switching of the ADC pins into the multiplexer in analogRead() doesn't happen before the delay().  If you switch pins with an extra analogRead() and throw away the value before the delay() you will get more stable readings.

Try something like this
void loop() {
  // read the input on analog pin 0 and 1 with delays for stability:
  delay(1000);
  int sensorValue1 = analogRead(A0);
  delay(1000);
  int sensorValue2 = analogRead(A1);

  // print out the value you read:
  Serial.print("val1 = " );
  Serial.print(sensorValue1);
  Serial.print(" val2 = " );
  Serial.println(sensorValue2);

 }

The problem here seems like you are writing the value with a println(), and then again the value without new line but space. Then you write value2 with an ending newline and again value2 without newline. In your output there is also a string that does not match up anywhere in the code you posted. Double check what you are uploading and check if it has error.


text:
Arduino LCD Display drawing image issue
I am playing with 3,5" (400x240) TFT display which is placed into Arduino Mega 2560 R3 board.
My final goal is taking .raw data from SD card and drawing it on display.
What I have done so far:
- My drawing method in the sketch:
void LoadImage(File& file)
{
    for (int y = 0; y < SCREEN_HEIGHT && file.available(); y++) {
        uint16_t buf[SCREEN_WIDTH];
        for (int x = SCREEN_WIDTH - 1; x >= 0; x--) {
            byte l = file.read();
            byte h = file.read();
            buf[x] = ((uint16_t)h << 8) | l;
        }
        myGLCD.drawPixelLine(0, y, SCREEN_WIDTH, buf);
    }
}

- For reference drawPixelLine method's implementation from UTFT library:
void UTFT::drawPixelLine(int x, int y, int sx, uint16_t* data)
{
    unsigned int col;
    cbi(P_CS, B_CS);
    setXY(x, y, x+sx-1, y);
    for (int tc=0; tc<sx; tc++)
    {
        char* p = (char*)&data[tc];
        LCD_Write_DATA(*(p + 1), *p);
    }
    sbi(P_CS, B_CS);
}
void UTFT::setXY(word x1, word y1, word x2, word y2)
{
    if (orient==LANDSCAPE)
    {
        swap(word, x1, y1);
        swap(word, x2, y2)
        y1=disp_y_size-y1;
        y2=disp_y_size-y2;
        swap(word, y1, y2)
    }
        LCD_Write_COM(0x2a);
        LCD_Write_DATA(x1>>8);
        LCD_Write_DATA(x1);
        LCD_Write_DATA(x2>>8);
        LCD_Write_DATA(x2);
        LCD_Write_COM(0x2b);
        LCD_Write_DATA(y1>>8);
        LCD_Write_DATA(y1);
        LCD_Write_DATA(y2>>8);
        LCD_Write_DATA(y2);
        LCD_Write_COM(0x2c);
}

My current rendering:

Desired image:

TFT Lcd and Mega Board

UPDATE1
I ran henningan test from utft library, drawing sin/cos graph and simple squares

Here is attempt to render yellow square 100x100 raw data

Have you tried drawing a solid image first?

@IgnacioVazquez-Abrams I tried to render yellow square, but without success. Please, see my updated post

I'have the same LCD from mcufriend and it doesn't work with original UTFT library.
Try modified version from https://github.com/dgolda/UTFT and use:
myGLCD(NIC35WS,38,39,40,41); //3.5" TFTLCD for arduino 2560 from mcufriend.com


text:
displaying a 3 digit clock time on a 4 digit 7 segment display
I purchased one of these 4 digit 7 segment displays using a TM1637.
I installed the TM1637 display library from the libraries manager and included it:
(#include <TM1637Display.h>).
I am trying to display the time, and I would like, preferably, to display 3 digit times with a colon, but without the leading zero.
I found this great reference online for using the library., and saw the usage for numbers with colons:
showNumberDecEx(number, dots, leading_zeros, length, position)
according to the guide, to have the colon in the center, you would pass 0b01000000 as the dots parameter.
And I figured that if I then want to display, for example, the time 1:36, then my number parameter would be 136, my leading_zeros parameter would be 0 (false), my length would be 3 for a 3 digit number, and my position would by 1 to start the number in the zero-indexed second position:
display.showNumberDecEx(136, 0b01000000, false, 3, 1); //displays 5136
But this displayed 5136 with no colon.
I tried a number of other things, including:
display.showNumberDecEx(136, 0b01000000, true, 3, 0); //displays 13:66
display.showNumberDecEx(136, 0b01000000, false, 3, 0); //displays 13:6A
I finally found code from this site, which works to display the time (albeit with a leading zero), but I don't fully understand it:
display.showNumberDecEx(1*100+36, 0x80 >> 1, 1, 4, 0);
I get that 1*100+36 represents number of hours plus minutes, but I don't get the 0x80 >> 1 bit. I'm assuming the rest of it is just saying make it a 4 digit number and add a leading zero.
Can anyone possibly:
* help me understand the above working code
* tell me an easier way to construct a time so that I can ideally just pass a 3 or 4 digit number and have it automatically render out a clock time with separating colon
* tell me why my previous attempts were incorrect

I tested your first code line and it outputs a right aligned 136 without colon at my display. (Said I have only a colon at the middle and no decimal points)
The 5 at the fist digit (and also the A at your third code line) must have been set somewhere beforehand. The function does not change the unused digit, so it will stay whatever you set it to beforehand (Even from before the last reset of the Arduino. The display doesn't reset with the Arduino). You can set the segments for that digit to zero (or set all segments to zero, to clear the complete display) before you show the decimal number.
About the colon: Here it is important on which position you start the printing of the number. The colon/decimal point bitmask, that you provide the function with, is seen from the starting position, that you provide. The middle colon of a 4 digit display is wired to the second digit. When providing 1 as the starting position, you start with the second digit. Thus the colon bitmask must set the most significant ("first") bit, to enable the middle colon, since it belongs to the first digit, that is processed by the function. Meaning:
position = 0 and bitmask = 0b10000000 --> colon/decimal point at first digit on
position = 0 and bitmask = 0b01000000 --> colon/decimal point at second digit on
position = 0 and bitmask = 0b00100000 --> colon/decimal point at third digit on
position = 1 and bitmask = 0b10000000 --> colon/decimal point at second digit on
position = 1 and bitmask = 0b01000000 --> colon/decimal point at third digit on
position = 2 and bitmask = 0b10000000 --> colon/decimal point at third digit on
position = 2 and bitmask = 0b01000000 --> colon/decimal point at fourth digit on

The 0x80 >> 1 is just a different representation of your binary number. 0x80 is the hexadecimal form of the binary 0b10000000. The >> operator shifts the byte to the right, here by one digit. Thus:
0x80 >> 1 = 0b10000000 >> 1 = 0x40 = 0b01000000

So the code, that you found, enables the colon/decimal point at the second digit.

tell me an easier way to construct a time

Easier it relative. I used such a display in a project to display a time and used two showNumberDecEx() calls; one for the minutes and one for the seconds:
display.showNumberDecEx(seconds, 0x00, true, 2, 2);
display.showNumberDecEx(minutes, 0x40, true, 2, 0);

Having directly minutes and seconds may make it easier for you. About the no-leading-zeros: Since the library always prints left to right, you need to handle that by yourself. But that is rather easy. One if statement to check, if the minutes are greater than 9 or not. Depending on that you set the position to 0 or 1.
display.showNumberDecEx(seconds, 0x00, true, 2, 2);
if(minutes > 9){
    display.showNumberDecEx(minutes, 0x40, false, 2, 0);
} else {
    display.showNumberDecEx(minutes, 0x80, false, 1, 1);
}

You could put that into a function, so that you don't have to write this code multiple times.
Note: For my last code snippet to work, you should first clear the display (or optionally only the first digit), so that no number from before will be displayed there.

In your last code snippet, the case minutes ≤ 9 won't work as expected since, as you put it yourself, “the function does not change the unused digit, so it will stay whatever you set it to beforehand”.

That's true. I assumed implicitly, that the display is cleared beforehand. I will add a note for that.

Always start by reading the docs. The README of the TM1637 display
library gives a short summary of the available functions, then states
“Please refer to TM1637Display.h for more information.” It would thus
seem the authoritative documentation is the header file itself, which is
indeed rich ins structured comments. According to it, the
signature of showNumberDecEx() is
void showNumberDecEx(int num,
                     uint8_t dots = 0,
                     bool leading_zero = false,
                     uint8_t length = 4,
                     uint8_t pos = 0);

where the parameters have the following meanings (emphasis mine):

num: the number to be shown
dots: dot/colon enable [...]
leading_zero: when true, leading zeros are displayed, otherwise
unnecessary digits are blank
length: the number of digits to set
pos: the position of the most significant digit
(0 - leftmost, 3 - rightmost)

The length and pos parameters control which digits are set. It is
important to note that any digits that are not set are left as is.
Note also that, if you are setting more digits than needed to display
the number, the leftmost digits are either zeros or blank, depending
on the value of leading_zero. And that is exactly what you want: you
want the leftmost digit to be blank.
Here are some examples of what various calls display:
display.showNumberDecEx(136, 0x40, true,  3, 1)  →  "X1:36"
display.showNumberDecEx(136, 0x40, false, 3, 1)  →  "X1:36"
display.showNumberDecEx(136, 0x40, true,  3, 0)  →  "13:6X"
display.showNumberDecEx(136, 0x40, false, 3, 0)  →  "13:6X"
display.showNumberDecEx(136, 0x40, true,  4, 0)  →  "01:36"
display.showNumberDecEx(136, 0x40, false, 4, 0)  →  " 1:36"

In the examples above, “X” means “whatever was previously left there”,
as the corresponding digit is not updated by the call. The last example
is the one you want. Incidentally, the last three parameters of this
example have their default values. You can thus achieve this simply
with:
display.showNumberDecEx(136, 0x40);

You can also follow chrisl's advice and display the hours and minutes
separately:
int hours = 1;
int minutes = 36;
display.showNumberDecEx(hours, 0x40, false, 2, 0);
display.showNumberDecEx(minutes,  0, true,  2, 2);

No need to separately handle the case where hours is larger than 9.


text:
How to power both arduino and 1 color led strip from single power source

I'm trying to understand and adapt this tutorial:
https://learn.adafruit.com/rgb-led-strips/current-draw
to my own use. I am doing essentially the same thing, except I have this single color LED strip, and I don't fully understand how to power both the arduino and the led strip from the same power source.
I tried to wire it using the diagram above, and something started smoking (I think the IR transmitter). I don't know much about circuits, but I'm pretty sure that's not good.
In this diagram, the 9v represents DC power, the IR sensor on the left represents the transmitter, the IR on the right is the receiver, and the white LED is the LED strip, with two outputs (+ - )
In the fritzing diagram for that tutorial, they have the + from the LED strip going straight in to Vin on the uno, but they don't show how either the LED strip or the uno themselves are being powered.
Do I need two power sources?
Do I need a mosfet considering I'm only using a one color LED strip?
I've got the IR sensors working, so I don't need help with that, and I can connect one of these 12V switching power supplies to one of these DC power screw terminals to power the lights without any arduino control, so all I'm missing is how to turn the lights on and off with arduino, IE, how to go from the power supply to the arduino to the LED strip.
I don't need to PWM the LED strip - just shut it off and on.
If anyone can help me correct the fritzing diagram or explain what I'm doing wrong / what I should be doing instead, I'd greatly appreciate it.

Note that VIN pin and the 2.5mm DC Jack are connected. So in the tutorial one of these is getting power from a +12Vdc source and the other is supplying +12V to the +12v labeled pin on the LED string. Where the R G and B pins of the strip should be connected to Collectors of NPN's. Each of the NPN's bases are driven by Arduino Output pin and all the Emitters are connected to Ground.
So +12V supplies the DC Jack (aka Vin) the Arduino's local regulator converts that to Ground. The +12V via Vin supplies the LED's. And the Digital Outputs drive the base's of the NPN's. Which in turn act like a relay closing the perspective LED's to Ground, so they can illuminate. Where a Digital ONE or HIGH or TRUE on the BASE results in 5V above ground, which causes it to have low resistance.

Sorry, I don't understand your diagram. Also, I think the details of my project are different. I am using a MOSFET (http://www.adafruit.com/datasheets/irlb8721pbf.pdf) so I'm dealing with G D S, and I'm using a single color LED strip - so + and - vs R G B + .  Is it possible to explain your answer as it relates to the fritzing diagram? Sorry, I'm trying to understand but I'm not clear on a few things: is the 7805 the IC of the arduino? How does the power split both to the IC and the Vin? what is the R? What are the two resistors resisting? What about the breakbeams?

You can use a mosfet instead of the transistor in the circuit. If you use a mosfet you can keep out R1. Since you only have one color, you can ignore the 3x part. Only the dash-outlined circuit, you need to build. The rest is part of the arduino board. Including the Vin pin (which is connected on the board to the jack). R1 is to limit the base-current going into the transistor. Without it the transistor will burn out, and possibly the output-pin. R2 is a pull down, so the led doesn't light up during power-up
I think the values for the two resitors are wrong. I'd use 1k for R1 and 10k for R2.

You asked: "Do I need a mosfet considering I'm only using a one color LED strip?"
Yes, absolutely. An Arduino logic line can only put out about 20 mA of power at 5V. That's not an unreasonable amount of power for a single low-power LED. An LED strip is likely to draw a lot more current than that, and it's pretty common for LED strips to use 12V, not 5V.
What LED strip are you using, and what input voltage and current requirements does it have?
You should be able to use a single power 12V power supply for your project. (assuming your LED strip needs 12V.) You'd feed it into the barrel jack of the Arduino. The Arduino's voltage regulator would use that to generate its 5V power. You'd also feed 12V into the power for your LED strip. You'd use a logic-level MOSFET to switch the power to the LED strip on and off. A logic level MOSFET is able to use a low current 5V signal from the Arduino to switch higher voltage, higher current loads like your LED strip with very little resistance, and thus with very little waste heat generated.


text:
Understanding how to power objects with a relay (featherwing, feather huzzah)
I am trying to learn how to control a relay to power various household objects. I bought a power relay shield for an adafruit feather huzzah, and I have just set up the arduino blink sketch to provide conditional high / low to a control pin on the relay:
const int ledPin = 13;

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

void loop {
    digitalWrite(ledPin, LOW);
    delay(1000);
    digitalWrite(ledPin, HIGH);
    delay(2000);
}

If I connect a jumper from the signal pin hole on the board to the appropriate ledPin (13), I can hear the relay switching on and off. If I use a multimeter in continuity mode, it will register continuity at the appropriate times in the blink sketch (HIGH or LOW).
I might be confused on how the relay should be wired, but shouldn't attaching wires from two of the terminal blocks deliver power to something? If I use a multimeter on wires coming out of the blocks, I don't detect any current. I've tried powering a simple led, but I can't get it to light up. Here's my setup. Can anyone explain what I might be doing wrong? Does the LED need a separate power source apart from what's coming from the feather itself? (the feather is powered by a USB cable from my computer).
Thanks for any clarification anyone can provide.

BTW, here is a reference photo from Adafruit of how they have it wired.

the relay is just a switch .... it is like touching two wires together

why are you posting at multiple sites? https://electronics.stackexchange.com/questions/378824/powering-an-object-with-a-relay-has-continuity-but-it-doesnt-seem-to-be-delive

Please give actual wiring diagrams, not pictures of breadboards, its to hard to tell how yours is wired, and the picture from adafruit is useless

@mheavers crossposting is explicitly prohobited

@ChrisStratton - so do I delete this post? Stack exchange warns me that "deleting a post with answers deprives users of useful knowledge" - which I agree with.

A relay is just a switch, that is controlled via a magnet force from coil. The power line to the relay breakout board is just used to drive enough current through this coil, since often the 20mA of a normal digital output pin aren't enough for that.
Relays are for switching big loads, that should not have contact with the microcontrollers circuit. You don't want the 230V (or 110V, depending on where you live) to find their way to the microcontroller. Also most boards can only provide a very limited amount of current. Big loads mostly need a lot of current and you don't want this big current flowing through the tiny copper traces on the board. You have to use an extra power supply for these.
So have to connect the relay like a normal switch, in series with the load you want to control with it. Also keep in mind the difference between the normally open and normally closed output of the relay. Here is a schematic, to explain further, what circuit you need:

simulate this circuit – Schematic created using CircuitLab
You provide power for the coil of the relay from the two power lines of the ESP (3.3V and GND). The digital pin, that you use for switching is just a signal. It only has to provide a very minimal amount of current. The board itself has a driver circuit to activate the coil. Here I used a simple MOSFET, but I actually don't know, what driver circuit is really used on that board.
If enough current is flowing through the coil, the switch inside the relay changes from NC (normally closed/connected) pin to NO (normally open) pin, closing the electrical circuit, that provide the big load (here a light bulb) with current from an external power supply (like a wall outlet). The two circuits are NOT electrically connected, so you won't have to deal with potential high voltage and current on the ESP side.

And in your sketch you don't ever turn the LED off. I assume this is just an error from copy/paste.

@chrisi - thanks for the clarification - I did miss a line of code copying and pasting. But I still don't understand how the circuit should be wired. I've been searching for a fritzing diagram or circuit diagram, but I can't find something that simplifies this process.

@mheavers: I added a schematic and further explanations

I don't see a current limit resistor in the LED circuit, 270 to 470 Ohms, must have. Also, there is no power supply for the LED, the relay is just a short circuit across the LED.


text:
project not working when switching to battery power

I have a project which involves a photocell, an led, a push button, and a small hobby servo (tower pro sg5010) - the project works as expected when the arduino is powered by usb, but when I switch to battery power (4 AA batteries) - it doesn't work.
When powered by batteries, the servo actually starts right up and moves to the correct angle, so I feel like it should be getting enough power, but when I push the push button, it doesn't move to the new angle. I can hear a clicking noise of the servo on a regular interval, like a clock, and my LED flickers on and off at about the same interval.
If I'm doing something wrong, can anyone point it out? If it's just that the servo is not getting enough power, is there a way to add a transistor or something so that I don't have to add a separate power supply for the servo (I'm not sure there's room in my project's enclosure).
I've attached a fritzing diagram as well as my project code.
CODE:
#include <Servo.h>

const int buttonPin = 2;     // the number of the pushbutton pin
boolean buttonPushed = false;

const int ledPin =  13;      // the number of the LED pin

const int servoPin = 9;
Servo servo;
int angle = 0;
int servoStartAngle = 90;
int servoEndAngle = 10;

boolean servoActivated = false;

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

int photoCellPin = 2;
int photoCellThreshold = 500;
int photoCellActivated = false;

void setup() {
  Serial.begin(9600);
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);

  servo.attach(servoPin);
  servo.write(servoStartAngle);

}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  int photoCellVal = analogRead(photoCellPin);

  if (photoCellVal > photoCellThreshold){
   photoCellActivated = true;
  } else {
   photoCellActivated = false;
  }

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW && buttonPushed == false) {
    // turn LED on:
    buttonPushed = true;
    Serial.println("button pushed");
  } else if (buttonState == LOW && buttonPushed == true){
   buttonPushed = false;
   Serial.println('deactivate');
  }

  if (buttonPushed == true){
   digitalWrite(ledPin, HIGH);
  } else {
   digitalWrite(ledPin, LOW);
  }

  if (buttonPushed && servoActivated == false && photoCellActivated == true){
    servoActivated = true;
    Serial.println("activate motor");

    for(angle = servoStartAngle; angle > servoEndAngle; angle--){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
  } else if (buttonPushed == false && servoActivated == true){ //deactivate
    for(angle = servoEndAngle; angle < servoStartAngle; angle++){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
    delay(200);
    servoActivated = false;

  }

  delay(200);
}

You may find that, with a high load on batteries, it's depleting the battery quickly; batteries often recover after a while, which may be confusing things further. Try using a multimeter to measure the voltage on the battery, when your program is running.
The Arduino (actually, the chip that runs the Arduino) has brown-out detection - if the voltage drops below a certain level, the Arduino will shut down; if the power comes back up, the Arduino will start up again - but reset. The chip has settings for 1.8v, 2.7v, and 4.3v brownout detection (or none at all!); something I read on the interweb (if you can trust that) said the default was 4.3v. It may be worth flashing an led on startup, so you can tell when the chip is reset.
Also, if you are powering the Arduino through the voltage regulator (using the power socket on the Arduino), then you need about 6-7 volt in just to get 5 volt at the Arduino - this causes further power loss. If using 4 AA batteries through the voltage regulator, you will get 6 volts (probably a little more when the batteries are fresh) going into the regulator - barely or not quite enough! - and the voltage on the Arduino is likely to be below the 5v it needs. Any load (in one of my projects, two large 7-segment displays) can cause the voltage to drop enough to trigger a reset. If you are using the voltage regulator, check the voltage between the 5V and GND pins.

I had an even simpler project only involving a TMP sensor and 433 MHz RF module. On a 9V (150 mAh) block battery it lasted only about 2,5 hours.
The Arduino is great for prototyping this sort of stuff, but when you want to build something for battery operation I found  that it draws 56 mA just looping without RF or motor!
Counting 2 digital outputs, 1 digital input and 1 analog input in your project, you can run that of an ATTiny85 or ATTiny45. It's the same family and after setup can be programmed with the Arduino environment. You can also opt for a lower speed bootloader 1 MHz or 8 MHz instead of 16 MHz for the Arduino to save energy, you don't seem to calculate that much. The ATTiny will draw about 10 mA looping this way.
Next you'll find also that you can disable the brown out detection in the bootloader, so it just drains the battery until completion.
Saving space in you enclosure by swapping Arduino board for ATTiny chip will allow you to put in more batteries, say 8 AA in two parallel packs of 6V each.
When that doesn't help you'll discover about the sleep modes and disabling ADC when not in use, where you go to sleep for specific intervals and allow the chip to be woken up by interrupts. In sleep mode I found the ATTiny to consume only 0.03 mA.
Some more information
Program an ATtiny with Arduino
ATTiny files for Arduino IDE


text:
Communication via IP adress with Arduino IDE and ESP8266
I have two Arduino boards and two ESP8266 modules with the NodeMCU firmware, and I want to make this:
One Aruino will be connected to one module and a vibration sensor, and when this sensor detects some vibration, it will send some data using the ESP8266 module as a server, then, the other Arduino will recieve the data with the other ESP module and display a message to a LCD screen.
I've already programmed the WiFi modules as a server and as a client using NodeMCU firmware and LuaUploader. The issue I have is that I don't know how to make a program in the Arduino IDE that communicate both Arduino boards using the ip adress assigned to both ESP modules, can you help me? Thanks

First, you need a SoftwareSerial interface, since the hardware serial is already used for debugging. To setup a SoftwareSerial this is an example:
#include <SoftwareSerial.h>

const byte rxPin = 6; // Wire this to Tx Pin of ESP8266
const byte txPin = 7; // 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(115200);
  ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
}

void loop() {
  while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got Data from ESP8266: " + inData);
     // The rest of your code...
  }
}

To send data from ESP8266 back to Arduino try something like this:
uart.setup(0, 115200, 8, 0, 1, 1 ) -- Change the baudrate to 115200
-- A simple http server
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive",function(conn,payload)
        payload = payload + "\n"
        uart.write(0, payload) -- send it back to Arduino via Serial interface
    end)
      conn:on("sent",function(conn) conn:close() end)
    end)

uart.on("data", function(data)
    -- When ESP8266 receives data from Arduino, it will trigger this event
end, 0)

And how can I send a data through the Arduino to the ESP8266?

I'll send you a link with my code for both Arduino boards and both ESP modules, hope you can help me Codes for my project

Hello, I'll have a look at the codes and get back to you.

You have the esp8266 talking.  Now you need to come up with a method of passing data from the arduinos to the esp.
You can use serial, you can use i2c, spi? Or something of your own design.  The problem wit using serial is the you are already using serial to communicate with the board from your PC.  You can use SoftSerial on the Arduino, but not sure how you'd do it on the ESP.
There are ways of making both boards work as master and slave i2c and spi, but it's probably overkill.
You could use two pins, one pin sends a binary bit and the other to clock the data, set high when new data has been written and set low when it has been read.
Then just use the same sort of algorithm as you did between you eps.
I have assumed that one Arduino is connected to one esp.  Let the ESPs worry about ip addresses.  If you want the Arduino to specify the destination then use a simpler addressing system than IP and let the ESPs translate that.

Well, can I connect the RX and TX pins to another Arduino digital pins so I can use the SoftSerial? @Matt

Also, I programmed the NodeMCU server like this
srv:listen(80,function(conn)   conn:on("receive",function(conn,payload)     print(payload)      conn:send("<h1> Hello, NodeMCU!!! </h1>")   end)   conn:on("sent",function(conn) conn:close() end) end)

You can use soft serial, but make sure you understand its limitations.
The NodeMCU code just needs a tweak to store the data received from the serial and send it when someone connects to the http socket.

After reviewing your codes, I've rewritten them this way, I didn't get a chance to test them though, so try them and let me know.
Server code: a. Arduino
#include <SoftwareSerial.h>

int ledPin = 13;
int txPin = 2;
int rxPin = 3;

SoftwareSerial wifi(rxPin, txPin);

void setup() {
    pinMode(ledPin, OUTPUT);
    Serial.begin(115200); // This baudrate is better than 9600
    wifi.begin(9600);
    wifi.println("dofile('wifiserv.lua')"); // This where it goes
    digitalWrite(ledPin, LOW);
    delay(2000); // delay is necessary
}

void loop() {
  while(wifi.available())
  {
     digitalWrite(ledPin, HIGH);
     String inData = wifi.readStringUntil('\n');
     if (inData.startsWith("Server IP: "))
        Serial.println(inData); // This is just the Server IP address
     else
        Serial.println("Got new sensor value: " + inData)
  }
  digitalWrite(ledPin, LOW); // This means no data is available
}

Server code: b. ESP8266
uart.setup(0, 9600, 8, 0, 1, 1 )
wifi.setmode(wifi.STATION)
wifi.sta.config("mynet","pass")
print("Server IP: " .. wifi.sta.getip() .. "\n")

srv = net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive",function(conn, s)
        data = s:match("sensor=(%w+)")
        data = data + "\n"
        uart.write(0, data)
    end)
end)

uart.on("data", function(cmd)
    -- When ESP8266 receives data from Arduino, it will trigger this event
end, 0)

Client code: a. Arduino
#include <SoftwareSerial.h>

int ledPin = 13;
int EP = 9;
int txPin = 2;
int rxPin = 3;

int dato = 10;

String ip; // Assign this to your server IP

SoftwareSerial wifi(rxPin, txPin);

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(EP, INPUT);
  Serial.begin(115200);
  wifi.begin(9600);
  wifi.println("dofile('wificlie.lua')"); // This where it goes
  delay(2000); // delay is necessary

}

void loop()
{
  long medida = TP_init();
  delay(50);

  if(medida > 1000)
  {
    Serial.println(medida);
    digitalWrite(ledPin, HIGH);

    String cmd = "ip=" + ip + " " + "data=" + String(dato);
    Serial.println("Sending: " + cmd);
    wifi.println(cmd);
  }
  else
  {
    digitalWrite(ledPin, LOW);
  }
}

long TP_init()
{
  delay(10);
  long medida = pulseIn(EP, HIGH);
  return medida;
}

Client code: b. ESP8266
wifi.setmode(wifi.STATION)
wifi.sta.config("mynet","pass")

uart.setup(0, 9600, 8, 0, 1, 1 )
uart.on("data", function(s)
    uart.write(0, "GoSending!")
    ip = s:match("ip=(%d+.%d+.%d+.%d+)")
    data = s:match("data=(%w+)")
    conn = net.createConnection(net.TCP, 0)
    conn:on("connection", function(c)
        print("connected");
        conn:connect(80,ip)
        conn:send("sensor=" .. data)
        uart.write(0, "Data has been sent successfully")
    end)
end, 0)

Comments are not for extended discussion; this conversation has been moved to chat. (cc @DanielCorona)