text:
Arduino gets stuck: battery powered, wireless, dc motor drive
I have a Arduino Mega 2560 connected to

L293D Motor Driver IC connected to two small size dc motors.
MPU-9150 using i2c
Xbee v1.1 arduino shield by seeed
Li-po battery, 7.4 volts, 2200 mah.

All components are tested separately, they all are working fine, the sensor readings showing data on serial monitor, the l293 drives the motors, xbee sends wireless serial data on pc, and li-po is also working fine.
I have checked the wiring alot of times. It all seems to be correct.
The problem arises when i connect all of them together, since I am using a single power source, I power the l293d with the Li-po and the Arduino also with the Li-po.

When the L293D is powered using Li-po and it starts drawing current from the battery, the serial monitor/arduino gets stuck. It doesnt show sensor readings anymore, while the dc motors start spinning. And they continue to spin, until I break connection with the battery.
Without the l293d powered, the sensor readings are working fine, everything is going normal, as it should, but as soon as the l293d is connected, arduino is stuck..

I have searched alot of forums for this, found some info, perhaps something to do analog and digital ground? mpu-9150 is digital ground. So that is why it stops the arduino mega as the l293d starts drawing current. All hell breaks loose.
Can anybody please help me with this? it is giving me headaches ever since!

Can you provide a schematic or wiring diagram?

Did you use decoupling caps or are you challenging the laws of nature?

Try adding a high value capacitor to the 5V. Alternatively try powering the motors using the battery voltage directly instead of (though the regulator) to  5v. Also, what happens if you only disconnect the motor, and not the L293D?

@jippie, many of your readers (like me) have a software background, not EE, and may not know what you're talking about with bypass caps. I've seen them used in regulated power supplies. It would be helpful if you provide a link to you would use bypass caps in a circuit that has both power loads and a micro controller on it.

@DuncanC to be honest, that was more or less the reaction I was hoping for. Check these related questions on EE:http://electronics.stackexchange.com/questions/105820/transistor-rating-with-capacitive-load and http://electronics.stackexchange.com/questions/59325/whats-the-use-of-a-decoupling-capacitor-near-a-reservoir-capacitor/59328#59328 and http://electronics.stackexchange.com/questions/90971/does-my-circuit-need-decoupling-caps/90972#90972 The problem is clearly related to power surges and caps may be able to solve that. BTW OP should really post a circuit diagram, because details unclear.

What do you think of my suggestion of powering the Arduino with a 9 volt battery as a test? That should isolate the large current pulses of the load from the Arduino board, and also keep the high frequency noise from the Arduino from getting to the motor driver.

@DuncanC when done correctly that is a perfect method to identify the cause of the problem, I do not think using two power sources all the time can be considered a good solution.

@DuncanC i have tried two power sources. 7.4v Lipo for the L293D and 9 Volt battery for the arduino, the ground is common between all, i hope that isnt creating problems?

@jippie decoupling caps? can u highlight please?

@Gerben ill show the circuit, where to add the capacitors?
and it WORKS fine without the motors connected to L293D. as soon as the motors start rotating, no more readings.

okay newbie here, how to add image?

Just add the capacitor between 5v and GND. You can't put an image inside a comment. You can however edit you question and add additional info, like an image, to it.

@Gerben the only 5 Volt source that i have is on the L298N motor driver shield. it is basically a voltage regulator, so the 7.4volt coming from LIPO is regulated to 5Volts. now where to add the capacitor

@gerben i mean the L298N has a voltage regulator in it, and it powers the L298N by using the voltage regulator, 7.4volt regulated, used to power the motor driver. and the 7.4volt used to drive the motors.
https://www.google.com.pk/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&docid=7wcBRF2MZnrUtM&tbnid=wpzRFhWuIOknzM:&ved=0CAUQjRw&url=http%3A%2F%2Fwww.ebay.com%2Fitm%2FArduino-Motor-Controller-Shield-L298N-Drive-2-Motors-%2F330521096218&ei=aR3UU5L0L6Sa0QWso4DgDQ&bvm=bv.71778758,d.d2k&psig=AFQjCNEBkuBsnJB0eLBP-aiHp5TO4xN8Cg&ust=1406496486061746

the link given is of the motor shield

Just put it on the arduino's 5v and GND. Aternatively add it to the battery's + and -.

My guess is that your motors are drawing too much current and the voltage from your battery is dropping too low for the voltage regulator on the Arduino. Looking at the data sheet, the L293D will provide up to 600-mA for up to 2 motors at a time. That's up to 1.2 amps, a whole lot of current. I would suggest trying to power your arduino from a separate 9 volt battery as an experiment.

i tried having two power sources.

Lipo 7.4v for the L293D
9 Volt battery for the Arduino.

there is a ground common between all, i hope that isnt creating the problems?


text:
How to find integer inside a file with STRNCMP
I'm trying to compare the int number 18 with strcmp but give to me wrong result, the program looking for char 18 and not for integer 18, how i can look for an integer with strcmp?
/*
 SD card read/write

This example shows how to read and write data to and from an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4

created   Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

#include <SD.h>

File myFile;
char buf[10];

char bufStringa[24];

void setup()
{
// Open serial communications and wait for port to open:
 Serial.begin(9600);
  while (!Serial) {
   ; // wait for serial port to connect. Needed for Leonardo only
 }

 Serial.print("Initializing SD card...");
 // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
 // Note that even if it's not used as the CS pin, the hardware SS pin
 // (10 on most Arduino boards, 53 on the Mega) must be left as an output
 // or the SD library functions will not work.
  pinMode(10, OUTPUT);

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

 // re-open the file for reading:
 myFile = SD.open("test.txt");
 if (myFile) {
   Serial.println("test.txt:");

   // read from the file until there's nothing else in it:
   int id=18;
   while (myFile.available()) {
      myFile.read(buf,2);
       if(strncmp(buf, id, 2) == 0) // i think the system give to me te char 18 and not the number 18 how to do this?
       {
           Serial.println("Match!");
           for(int i=0;i<10;i++)
           {
            Serial.print(buf[i]);

           }
            myFile.read(bufStringa, 24);
            for(int i=0;i<24;i++)
           {
            Serial.print(bufStringa[i]);

           }
          break;
       }
   }
   // close the file:
   myFile.close();
 } else {
  // if the file didn't open, print an error:
   Serial.println("error opening test.txt");
 }
}

void loop()
{
  // nothing happens after setup
}

Maybe make it as:
char id[] = "18";

This is if you want to find "18" in your file. That's what I understood from your question.
EDIT: I guess you want this http://playground.arduino.cc/Code/PrintingNumbers:
int num = 18;
char buffer[100]; // this will hold your number
itoa(num, buffer, 10);

Function description here. Also it's not to hard to make this your self for integers and it's a good exercise.

i have an Integer for input, i need to convert this integer to char for use it in STRNCMP , tnks

Check my edit, is this what you need?

source: Stack Exchange

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

sort: votes


text:
Speedometer slow reaction arduino
I'm trying to make a speedometer, with utilization of interrupt for get number of pulse and some calculation for getting speed, but when compute speed the arduino freeze for some second and i lose alot of impulse and false all my successive capture of impulse. Why? thanks for reply
const int contaImpulsi = 2;
volatile int impulsi =  0;
int impulsiOld = 0;
static int appoggio = 0;
unsigned deltaT[3];
unsigned vel = 0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(contaImpulsi, definisciTempi, RISING);
}

void loop() {

  if (impulsiOld == impulsi || impulsi > impulsiOld)
  {
    if (appoggio == 3) {
      deltaT[3] = millis();
      appoggio = 0;
    }
    if (appoggio == 2) {
      //Serial.println("ASSEGNO DELTA T 2");
      deltaT[2] = millis();
      //Serial.println(deltaT[2]);
      appoggio = 3;
    }
    if (appoggio == 1) {
      //Serial.println("ASSEGNO DELTA T 1");
      deltaT[1] = millis();
      appoggio = 2;
    }
    if (appoggio == 0) {
      //Serial.println("ASSEGNO DELTA T 0");
      deltaT[0] = millis();
      appoggio = 1;
    }
  }
  impulsiOld = impulsi;

  if (appoggio == 3) {

    int t1 = (deltaT[1] - deltaT[0]);
    int t2 = (deltaT[2] - deltaT[1]);
    int dividi = t1 + t2;
    vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85; // here i think is where the program freeze

    Serial.println("------------------------------------------");
    Serial.print("SPEED: ");
    Serial.println(vel);
    Serial.println("------------------------------------------");
  }
}

void definisciTempi() {
  impulsi++;
}

You should make impulse volatile, otherwise its value could be cached.

IF it is that line then I can see why it might be an issue.  Can you refactor the formula so there is only one multiplication operation instead of all those constants?  An alternative system design might be to use an independent counter IC that you query periodically, that way the calculation and presentation is separated from the counting.

Your deltaT has 3 elements, but you are writing to 4 and only reading from 3.

And when appoggio is 3, appoggio gets set to 0 and the if block for appoggio == 0 gets also executed in the same loop.

First off a comment on your variable types. It's not the cause of your problem, but just something to watch for in future:
int impulsi =  0;

This should be voltatile (Edit: I see you updated that, that's ok).
unsigned deltaT[3];
unsigned vel = 0;

These lack a type. As such the default to int. Your deltaT array should be unsigned long since it stores time. It will overflow very rapidly otherwise.
Now on to your problem.
The core of your problem is your methodology of calculating the speed. This bit:
if (impulsiOld == impulsi || impulsi > impulsiOld)
{
  ...
}
impulsiOld = impulsi;

is going to be running pretty much always. That's because impulsiOld and impulsi will either always be the same (since you set them to be the same) or impulsi is going to be greater than impilsiOld since you received a pulse in the brief interlude when it's not running that bit.
And that means that all your deltaT entries are going to be the same most of the time.  Which leads me on to the next bit:
int t1 = (deltaT[1] - deltaT[0]);
int t2 = (deltaT[2] - deltaT[1]);
int dividi = t1 + t2;
vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85;

If delatT[1] and deltaT[0] are the same, then t1 will be 0. The same goes for t2. 0 + 0 = 0, so dividi will also be 0.
And that means:
690 * 2000 / 0

Which will be a divide by zero exception and will cause the MCU either to lock up or to reboot. If the latter you will see the bootloader run for a couple of seconds.
There are two normal methods of calculating the speed from pulses, and I am not sure what your method is trying to be.
The simplest one is to just count the number of pulses over a given period. Increment the count in your ISR, and after a second has elapsed (or longer, or shorter, depending on the frequencies you are working with) you reset the count to 0 (after storing it elsewhere) and calculate the speed from that stored count.
The other way is to just take the time between two successive pulses. You can average it, maybe with a rolling (AKA moving) average, or just take the raw value depending on what you are measuring.  This method is a little harder since you need to do more work per pulse.
The two methods differ in critical ways when it comes to outputting the results. The first method will always give you a value every second (or whatever time period you use), but it can't cope with pulses that are further apart than the time period you use. The second method doesn't much care about the time between the pulses, but you can only get a meaningful reading if a pulse arrives, which if that is a while means you get no reading for a while. It's harder to determine "not moving" from that.
Also you should look at the use of critical sections when accessing your impulsi variable outside the interrupt routine. It more than 8 bits, so all access to it will be non-atomic and could be interrupted by the ISR.

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


text:
Thermistor doesn't work
Connecting all like shows the image, thermistor shows, that I'm going to be burnt:

The code is simple:
#define analogPin  A0 //the thermistor attach to
#define beta 4090
#define resistance 10

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

void loop()
{
  //read thermistor value
  long a =analogRead(analogPin);
  //the calculating formula of temperature
  float tempC = beta /(log((1025.0 * 10 / a - 10) / 10) + beta / 298.0) - 273.0;
  float tempF = 1.8*tempC + 32.0;
  Serial.print("Temp: ");

  Serial.print(tempC);

  Serial.print("  C");

  Serial.print("Fahr: ");
  Serial.print(tempF);
  Serial.print(" F");
  delay(200); //wait for 100 milliseconds
}

Do I have a wrong thermistor or wrong code?

There are no magicians here. What model/type of thermistor have you connected? What the thermistor's parameters are?

The series resistance is 220 Ohms (Red, Red, Brown).
You also need to take into account the thermistor resistance at 25C. Assuming its 10K. Hence choosing a 10K series resistance will make the calculations easier.
     int THERMISTORNOMINAL =  10000;
     int SERIESRESISTOR = 10000;
     int TEMPERATURENOMINAL = 25;

     a = 1023 / a - 1;
     a = SERIESRESISTOR / a;
     tempC = a / THERMISTORNOMINAL;     // (R/Ro)
     tempC = log(tempC);                  // ln(R/Ro)
     tempC /= Beta;                   // 1/B * ln(R/Ro)
     tempC += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
     tempC = 1.0 / steinhart;                 // Invert
     tempC -= 273.15;                         // convert to C

Could you make a full working sketch? This code snippet is confusing because it does not show if the variables are a float or integer. Add a link to a source for your calculation as well.

I used 10K. The image is wrong.

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


text:
Defining array in switch case
I’m completely new to arduino, so be polite. I’m trying to program my esp32 to drive neopixels as seven segment display. So I take a digit and pass it to switch case and in switch case I mention which led number should be lit.
`
function showDigits(digit){

switch(digit){

 case 1:
   int a[]={1,3,4,.....};
  break;

 case 2:
    int a[]={1,3,4,6,8,...};
   break;
  .
  .
  .
default:
   int a[]={1,2,3,4,5,6,7,8,9,....};
  }
}

Now this is throwing multiple errors including redeclare of array a in same scope. Is there any better way to code this?

If you want to declare multiple variables with the same name inside different case statements, you can enclose the code inside each of them inside curly braces:
case 1:{
    Code...
break;}
case 2:
...

The curly braces will set the limits for the variables scope to just this case.

I see several issues with your code.
First one is the issue of "scope". If you define the int a[] inside the switch it will be destroyed as soon as the switch will finish and no code that runs outside of its brackets will be able to access it.
I also think that array of integers is the wrong choice here. It would be much less memory consuming to use array of boolean that mean if each LED should be lit or not. You can use it later like that:
if (a[4]) { digitalWrite(LED4, HIGH); } else { digitalWrite(LED4, LOW); }

or even better using "ternary operator":
digitalWrite(LED4, (a[4] ? HIGH : LOW));

Third problem is that your function is incorrectly defined and it does not contain any type information. This is C and not Python so the types are EXTREAMLY important! The correct definition of your function should be:
void showDigits(int digit)

Take a look at this example that compiled correctly:
void showDigits(int digit)
{
  bool a[6] = {false, false, false, false, false, false};
  switch (digit)
  {
    case 1:
      a[0] = true;
      a[1] = false;
      break;
    case 2:
      a[1] = false;
      break;
    default:
      a[0] = true;
  }

  if (a[4]) {
    digitalWrite(4, HIGH);
  } else {
    digitalWrite(4, LOW);
  }
};

The switch..case is a very particular syntax. If you don't use the break; at the end of a case the execution will actually continue to next case definition, and compiler told you that you tried to define int a[] several times in the same scope. (which is a no-no)

While I don't discourage you from doing it yourself. I would go the easy route and use an available library. As is, or if need be, after modifying it. For me, it is the better way as I'm not that good at programming.
https://learn.adafruit.com/adafruit-neopixel-uberguide/neomatrix-library
And this looks good.
FastLED NeoMatrix

Better support for ESP32 than Adafruit::Neopixel

https://github.com/marcmerlin/FastLED_NeoMatrix

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


text:
How frequently do you need to poll UI buttons before they are perceived as laggy?
Whilst it is possible, and sometimes desirable, to use pin change interrupts to read the state of buttons, it is simpler to poll the state of buttons in loop(). This is a commonly used technique.
If you loop() executes quickly enough, then button presses are always going to be caught and the user will not be able to perceive any delay or lag.
It is possible that your loop would take so long as to cause a delay or lag to be perceived.
The question is, how long would it be, in general, before a user would see this?

If your loop() is rather slow (I mean, too slow to be able to give fast enough feedback to the end user), you could possibly use an ISR on pin level change and provide immediate feedback (if this can be calculated fast) to the user, or give him temporary feedback (eg LED lit on) to tell him his request has been recognized and will be processed shortly (in loop()); you would let loop() by setting some global bool variable in the ISR.

It's probably one of the few times where key-click is useful.

The short answer is that you have 100 miliseconds to respond to the user if you want them to feel the action occurred instantaneously.
According to Jacob Nielsen in his book Usability Engineering, from 1993, which is considered an important reference in Systems Usability and User Experience:

0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.

He also mentions that this basic advice regarding response times has been about the same for many decades [Miller 1968; Card et al. 1991].
I've taken this citation from this article: Response Times: The 3 Important Limits, also writen by Jacob Nielsen.
Note that in this time you must include all time taken to read the button press and give feedback to the user.
Other response time thresholds that are important for user experience, from the same source, but that were not mentioned directly by the OP are:

1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.

10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.

Brilliant answer. Thanks for the extra info, it's also helpful.

It's commonly known that people are unable to perceive changes when they happen underneath 10ms after their action. This responsiveness will result in an experience that has recently mostly been described as "snappy". It's noticeable but for users it's hard to put a name on it.
So if you want perfection, take about 15ms of delay. If you want really good, take 100 ms of delay. 100ms is 50ms on average, and will certainly pass for people.
The application and the expected response time is vital too. A sliding door or elevator is given very large tolerance (as the physical object will always take a lot more time) whereas ticket vending machine interfaces are not given any time at all.
The upper limit for polling would be around 1500ms. Around there people will always notice it is slow.
This data is purely personal experience as a gamer and programmer. YMMV and remember that just trying it yourself is the best way to find out how it feels. The only "scientific" answer is the <10 milliseconds, beyond that it's about the ability to perceive the delay (which varies per person and moment) and the tolerance of the user.
As a side note, you can try fluctuating the delays in order to conserve battery or CPU time when the interface is not being used. The user-action, the faster the polling. When the application is doing it's thing, poll very slowly. Better to poll when it matters!


text:
Using Arduino libraries with ARM based microcontroller
A week ago I started messing with LoRa. I got my STM32L151 IM880A kit.
Company that provided SX1272 LoRa modem chip (used in kit), provided some libraries, but lots of functionalities are still not implemented and is still not suitable for use in multi P2P aplications.
After googling I came across Libelium company which used SX1272 chip in their products design and they provided useful set of libraries that provides lots of functionalities and also implements some sort of LoRa frame protocol stack ideal for use in P2P applications.
The problem is that I'm using STM32 in my project and Libelium libraries are written for Arduino. So I was wondering if there is a smart way to port Arduino libraries so I could use them in my STM32 Keil projects, since the libraries seems huge.
Tips, hints, links would be appreciated (I don't have experience in using Arduino and I'm not familiar with Arduino library structure).

You can use Arduino software on an STM32: http://jeelabs.org/book/1545d/

I don't want to use Arduino, I just want to know if it is possible to port libraries and in what measure is it convenient.

Okay, now I want to spare myself of pain of porting/debuging. I was wondering if there is stack available, that works on LoRa radio layer (does not implement LoRaWAN), that will allow me to assign some sort of ID/NODE_ADDR to each node and be able to establish connection between them, so P2P comm ?

Every time I work on a project I use arduino libraries and port them to my micro controller.
I used sublime text editor with multiple selection and editing(ctrl-d). Then I copy the arduino code to both sublime and my uC IDE then compile it in the IDE, scroll up to the first undefined function and add its definition to the code or modify it using sublime multiple editing and selecting (like digital read and write was in my opinion useless). After that update the file in your IDE and compile again.
You would do that till you have finished and it would take some time.

So I was wondering if there is a smart way to port Arduino libraries so I could use them in my STM32 Keil projects, since the libraries seems huge.

Yes. the STM32 port of arduino uses GCC, which isn't that different MDK or ADS - I have ported quite a few from back and forth from GCC <-> MDK, and one from GCC to ADS. If the code is well written, in many times all you need to do is to change the isr-related code pieces (a few names) and hit the recompile.


text:
How to read Negative number with serial.read
how i can read negative number with command Serial.read()?
beacouse i with  this
    char tmpChar = Serial.read(); //read incoming character from serial port
    if (isDigit(tmpChar)) { //check if the in character it's a number
        setpoint =  (setpoint  * 10 ) + tmpChar - '0'; // convert from ascii code to it's corresponding number; '0' == DEC 48
      }
if (tmpChar == '\n' || tmpChar == '\r') { //if CR or LF was received
    if (setpoint > 0) {
      tmpChar = "";
      Serial.print(setpoint);
      Serial.println(" NUMERO STEP IN AVANTI");

    }

im using an encoder motor, i want to move for N steps the motor forward (positive number) or backward (negative number) , i insert the number of step in serial input
i can read only positive number. Thanks for help
how suggest Majenko i made a partial solution :
char buf[8];
int valore = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() >= 8) {
    for (int i = 0; i < 8; i++) {
      buf[i] = Serial.read();

    }
    String str();
    if (buf[0] == "-") {
      valore = (atoi(buf)) * -1;
      Serial.println(valore);

    }
    else {
      valore =  atoi(buf);
      Serial.println(valore);
    }
  }
}

but the problem now it's the static array ,
unpleasant to use

Personally I would read the data into a char array then use either atoi() or strtol() to convert that char array into a number.
Using those functions is more robust that parsing the data yourself since they identify where the number ends and discards any trailing garbage. It also skips any white space before the number. For instance it will interpret all these as the number -32: "     -32", "-32 Degrees", "   -32+4  " and "-32-2".
strtol() has the additional advantage that it can work in other bases than 10, so you could interpret hexadecimal data, binary data, sexagesimal data, etc.
atoi() and strtol() are standard C functions.
E.g.:
int val = atoi(mycharbuffer);

or
long val = strtol(mycharbuffer, NULL, 10);

can make an example please

Of what - the reading into the char buffer, or the converting to integer?

to convert readed char in a negative int , thanks for help

Done. See my edit.

im tryng with this without succes, where im wrong? `void loop() {
char tmpChar = Serial.read();
long val = strtol(tmpChar, NULL, 10);
Serial.println(val);
}`

That's because you're trying to convert one single char. You need to read the whole string of characters into a character array first. Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

You could do something like this:
static int setpoint;      // the partially read setpoint
static bool isNegative;   // whether it should be negative
void applySetpoint(int);  // apply the setpoint when fully read

char tmpChar = Serial.read();
if (isDigit(tmpChar)) {
    setpoint =  (setpoint  * 10 ) + tmpChar - '0';
} else if (tmpChar == '-') {  // minus sign
    isNegative = true;
} else if (tmpChar == '\r') {  // line terminator
    if (isNegative) {
        setpoint = -setpoint;
        isNegative = false;  // reset for next read
    }
    applySetpoint(setpoint);
}

Note that this is not very robust: it will happily interpret "3-2" as
meaning "-32". Note also that I assumed your terminator to be '\r', you
may be using another one.

The parseInt can read negative numbers (I think it does, the reference is very cryptic). The parseInt has a timeout so it does not wait forever.
Can you tell what kind of data you are reading ? Is it part of more data ?

im using an encoder motor, i want to move for N steps the motor forward (positive number) or backward (negative number) , i want to insert the number of step in serial input

Just a number then ? When parseInt has a timeout, it returns 0, that means you can't send a 0. If that is okay, then check for Serial.available and do a Serial.parseInt.


text:
I2C between 2 or more Arduino boards
HELLO I have already connected with I2C 2 Arduino's all is working with comunication on Bus I2C. My Setup is :
MASTER with LCD I2C , RTC1037
SLAVE some sensor not I2C
I allready put 2 pullup resistor 10Kohm on SDA and SCL
I need to switch off the slave arduino but when i switch off the Slave board the Master Arduino stop working.Why? It's possible to continue working with master board and the slave board switch off? Thank's for help

Define "shut down". Also, define "stop working"...

switch off :) sorry for my english

"switch off" as in remove the power completely? Then you may need to isolate the I2C bus from it as well.

Yep, remove power completely,how to isolate the i2c bus? 2 relay 1 for sda 1 for scl when i need to switch off ?

Relay is kind of overkill and power hungry. MOSFETS (as Adafruit use in the I2C level shifters) are a better choice. See Adafruit's app note here: https://cdn-shop.adafruit.com/datasheets/an97055.pdf - ignore the level shifting as you would have both sides the same voltage, but section 2.3 is of interest. Your slave would be the 3.3V side of the shifter (but at 5V not 3.3V). Paragraph 2.3.4 tells you what you need to know for this application.

tnks a lot for your reply

You need to isolate the slave device from the I2C bus since it is causing interference with the signals.
Adafruit have published a good application note about level shifting in I2C busses using MOSFETs, and it also contains a bit about bus isolation:

2.3.4 Isolation of the powered-down “Lower voltage” section.
An additional feature of the level shifter circuit in figure 2 is the isolation of the “Lower voltage” section when
  VDD1 is switched off. In that case VDD1 is about 0 Volt and the MOS-FET’s [sic] are switched off because VGS is
  below the threshold voltage. The “Higher voltage” section is not hindered and stays operational. To assure a
  noise margin, the MOS-FET’s should have a minimum threshold voltage VGS(th) of e.g. 0.4V and VDD1 must
  stay below this value. The isolation feature can also be applied if no level shifting is required, VDD1 and VDD2
  may have the same value, e.g. both 3.3V or both 5V.


text:
Read value from a file inside SD card
it's possible to read value from a file inside sd card?
I'm trying to start with the sample code
/*
  SD card read/write

 This example shows how to read and write data to and from an SD card file
 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4

 created   Nov 2010
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe

 This example code is in the public domain.

 */

#include <SPI.h>
#include <SD.h>

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

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

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing1 1, 2, 3.");
    myFile.println("testing2 1, 2, 3.");
    myFile.println("testing3 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

but here he read all the contnent of the file, i want to read only testing 3 part . Thank's for help

Yes it's possible. Please be more specific in what your actual question is. As now, it's too vague to be answerable.

Do you have any part of this working? For example, do you have a device with an SD card slot? Is it attached to your Arduino? Can you read or write anything? Please try and make a start, and when you get stuck, post a specific question, with code.

it's possible to read value from a file inside sd card? - of course it is. Why would you connect one otherwise?

i found this solution with use of strcmp:
when i read the file i compare the result str coming from file flux
/*
 SD card read/write

This example shows how to read and write data to and from an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4

created   Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

#include <SD.h>

File myFile;
char buf[10];

void setup()
{
// Open serial communications and wait for port to open:
 Serial.begin(9600);
  while (!Serial) {
   ; // wait for serial port to connect. Needed for Leonardo only
 }

 Serial.print("Initializing SD card...");
 // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
 // Note that even if it's not used as the CS pin, the hardware SS pin
 // (10 on most Arduino boards, 53 on the Mega) must be left as an output
 // or the SD library functions will not work.
  pinMode(10, OUTPUT);

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

 // re-open the file for reading:
 myFile = SD.open("test.txt");
 if (myFile) {
   Serial.println("test.txt:");

   // read from the file until there's nothing else in it:
   while (myFile.available()) {
      myFile.read(buf,2);
       if(strncmp(buf, "12", 2) == 0)//for lenght i use 2 becouse im looking for a number with 2 digit
       {
           Serial.println("Match!");
           }
          break;
       }
   }
   // close the file:
   myFile.close();
 } else {
  // if the file didn't open, print an error:
   Serial.println("error opening test.txt");
 }
}

void loop()
{
  // nothing happens after setup
}

You have 2 options for doing this, depending on what exactly you want to read and how your file is arranged.

Read from the beginning until you find what you want. Throw away (just don't keep) what you don't want.
Use the File::seek(uint32_t) method to jump to a specific byte in the file and read from there. Only useful if you already know where in the file your data is.

how with reply number 1? Thank's

Exactly as with the example code. You just have to have the program examine what is read and make a decision on if it wants it or not.

yes, but I'm little bit noob, how? tnks again

Here's a clue: A File is a Stream. So is Serial. What you can do with Serial you can do with File.

an example please

Your posted question already has an example of reading from the file.


text:
Simplified timezone shapefile suitable for Arduino?
Is there a library or shape file available that allows an Arduino to approximate a timezone based on a latitude/longitude coordinate? There is a timezone shape file available, but it's too detailed and too large. I am hoping someone knows of a simplified version small enough for an Arduino and/or a library that's able to handle this task.

It isn't what you asked for, but would web services like in http://stackoverflow.com/a/16086964/1653571 be feasible?  I'd try to use UTC and avoid timezones and DST if I can get away with it, and make the display TZ a user-configured option if I had to.

Really looking for an actual solution. If you look at timezone shapes graphically, they really aren't that complex if you are willing to overlook, say, detecting a wrong timezone when you're within 10km to a border. In that case, the timezone shapes reduce to probably no more than a few dozen shapes with maybe a dozen vertices each. Something an Arduino can handle.

Foursquare have an open-source tool to do that. https://github.com/foursquare/shapefile-geo


text:
Arduino controlled light dimmer software
I found this software:
/*

AC Voltage dimmer with Zero cross detection
Author: Charith Fernanado   http://www.inmojo.com

Adapted by DIY_bloke
License: Creative Commons Attribution Share-Alike 3.0 License.
Attach the Zero cross pin of the module to Arduino External Interrupt pin
Select the correct Interrupt # from the below table
(the Pin numbers are digital pins, NOT physical pins:
digital pin 2 [INT0]=physical pin 4 and digital pin 3 [INT1]= physical pin 5)
check:   http://www.inmojo.com

Pin    |  Interrrupt # | Arduino Platform
---------------------------------------
2      |  0            |  All -But it is INT1 on the Leonardo
3      |  1            |  All -But it is INT0 on the Leonardo
18     |  5            |  Arduino Mega Only
19     |  4            |  Arduino Mega Only
20     |  3            |  Arduino Mega Only
21     |  2            |  Arduino Mega Only
0      |  0            |  Leonardo
1      |  3            |  Leonardo
7      |  4            |  Leonardo
The Arduino Due has no standard interrupt pins as an iterrupt can be attached to almosty any pin.

In the program pin 2 is chosen
*/
int AC_LOAD = 3;    // Output to Opto Triac pin
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

void setup()
{
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

//the interrupt function must take no parameters and return nothing
void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
  // For 60Hz => 8.33ms (10.000/120)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

  int dimtime = (75*dimming);    // For 60Hz =>65
  delayMicroseconds(dimtime);    // Wait till firing the TRIAC
  digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  delayMicroseconds(10);         // triac On propogation delay
                 // (for 60Hz use 8.33) Some Triacs need a longer period
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}

void loop()  {
  for (int i=5; i <= 128; i++){
    dimming=i;
    delay(10);
   }
}

But don't uderstand this part:

(10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

I know 10000us is 10ms, and we need to wait less then 10ms to dim light.
But don't understand why here we has -10us and /128.
Anyone know why is that?

-10uS because of the 10uS delay at the end of the loop, and /128 because he has decided there will be 128 possible dimming levels.

Why he put dalay 10uS on the end of loop? And how he know number for dimming levels?

It states why there is a 10uS delay - it's the triac on propagation delay. And how did he "know" to use 128 dimming leves? He didn't. He decided to use 128 dimming levels. He could have chosen another value, but 128 is enough dimming levels for most people and leaves a big enough delay granularity for easy timing.

Aha i understand now for levels. but still unclear with 10uS delay... Why triac need that 10uS?  It is very small value why is it importante?

Crudely put, it's the time it takes the triac to switch on.


text:
Is my Arduino Uno broken?
I think I broke my Arduino Uno as I was playing with it. I connected an ultrasonic range finder to it and uploaded a sketch to it. It was working fine until I accidentally touched the ICSP headers for the USB interface (the pins near the USB port). Now,everything is still working but my computer cannot detect it and it does not show up in the device manager or the IDE. Please tell me if it is broken and how to fix it.
BTW, I just bought it and just started using it after another Arduino had the same problem.

What have you tried? At the very least I'd try unplugging the Arduino and rebooting the computer (or in some way forcing a reset on the USB). The Uno may be particularly sensitive, but I've not seen a problem like this with any of my Arduino (and clone) boards. Do you live someplace where static electricity is a problem (I don't).

touching the ISP header or port should not have caused damage. Can your PC detect other usb devices on the same port?

Get down to just the bare Arduino board, disconnect everything, and see what you get..  the Ultrasonic sensor could easily be pulling more power than your USB can supply, only about 500mA.

I have tried deleting the arduino software and downloading it again, I also unplugged the arduino and rebooted my PC but it. I also tried installing older versions of the IDE but it still did not work. My PC cannot detect any other USB devices on the same port. I tried disconnecting everything but it still does not work.

Try other USB port and another computer. If you wish you could try and reprogram the 16u2. If it does not respond it's dead but you can always either replace it or use the Arduino for things that do not require serial.

It did not work. I just bought an arduino mega instead.

Please tell me if it is broken and how to fix it.

See Have I bricked my Arduino Uno? Problems with uploading to board
Those tips may also help with fixing problems with your Mega (if you ever have them). ;)


text:
Can I leave AVcc disconnected?
I am using ATmega8A standalone but analog pins (Port C) have not been use.
Due to ATmega8A does not have a PRR (Power Reduction Register) to disable ADC and TWI.
I would like to know, is it a work around solution to reduce the power consumption if AVcc is not connected?

You can disable the ADC on the ATMega8 the normal way. Though not the extra way that the PRR does. But I've found that the PRR doesn't do a whole lot. Disabling ADC, timers, and BOD and making the MCU sleep as much as possible is like 99%.

Unless the MCU allows you to apply power selectively (not the case of ATmega), failure to power some of the pins will result in some voltages applied in reverse internally, resulting in internal shorts.

No, the datasheet says power must be connected to Avcc. This is from the '328P, Atmega8A is similar but with less memory:
(Microchip is taking forever to open the Atmega8A datasheet for me).

5.2.7  AVCC
  AVCC is the supply voltage pin for the A/D Converter (ADC), PC[3:0], and PE[3:2]. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter.

https://www.microchip.com/wwwproducts/en/ATmega8A

No. You must connect AVcc even if you're not using the ADC.  According to the datasheet:

AVCC is the supply voltage pin for the A/D Converter, Port C (3:0), and ADC (7:6). It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. Note that Port C (5:4) use digital supply voltage, VCC.


text:
Playing audio files with sine wave from arduino
So, when searching for a way to play audio files through the Arduino, I came across this site: How to play WAV audio files with Arduino Uno and MicroSD card
This seems like a really good library (although I haven't had the time to really play around with it yet). Has anyone used this before, and, if so, is it a good library to use, or do you know of better ones out there which you would recommend?

The library works fine, and you'll find details from the developer of the PCM audio library here.

http://playground.arduino.cc/Code/PCMAudio

I used some time ago the TMRPCM library that the tutorial you linked used and I was very satisfied.
It doesn't take too much space and it has some really unique and neat features like the possibility to use two speakers instead of one to reproduce stereo audio (Unfortunately you need a more powerful AVR IC, surely not an UNO board/328 IC for this feature if you don't want to occur in bad reproduction)
From GitHub's wiki:

All 328 based boards: Arduino Uno, Nano, Duemilanove, etc
Mega Types: 1280, 2560, etc
No Due support currently.

You can only have WAV files on the SD but they can be very large (other libraries limit you to a specific maximum size/duration) and you need to connect the SD to the arduino via SPI (as far as I know it is the only way to communicate directly with an SD card).
Also, you will need to convert the files to 8 bit WAV (so it's faster and easier for the arduino to reproduce the sound) with sample rate from 8 to 32khz, mono audio.
Be careful just because you'll need to power the SD with 3.3 volts otherwise you'll fry the entire card.

Most of the extra features require more memory, more program space, and in some cases, more processing power for playback Some of them are still being fine tuned. Please keep this in mind when enabling these features.

If you want to take a look, go to this page for more informations on the advanced features
A last thing that I have to say is that the functions are really straightforward:
TMRpcm audio;
audio.play("filename");    plays a file
audio.play("filename",30); plays a file starting at 30 seconds into the track
audio.speakerPin = 11;     set to 5,6,11 or 46 for Mega, 9 for Uno, Nano, etc.
audio.disable();           disables the timer on output pin and stops the music
audio.stopPlayback();      stops the music, but leaves the timer running
audio.isPlaying();         returns 1 if music playing, 0 if not
audio.pause();             pauses/unpauses playback
audio.quality(1);          Set 1 for 2x oversampling
audio.volume(0);           1(up) or 0(down) to control volume
audio.setVolume(0);        0 to 7. Set volume level
audio.loop(1);             0 or 1. Can be changed during playback for full control of looping.


text:
CC3000 - Send GET request to an app, or sub-domain, on Heroku
I am working with Arduino UNO + AdaFruit CC3000 Wi-Fi shield. I ran it with a lot of websites and webpages, but for now I am going to get sub-domain from Heroku, and it has no IP address. The sub-domain is myapp.herokuapp.com.
So, how can I send a GET request to such an application like that?
Here's the code :
 // Library headers section
 #include <Adafruit_CC3000.h>
 #include <ccspi.h>
 #include <SPI.h>
 #include <string.h>
 #include "utility/debug.h"

 // Constants area
 #define ADAFRUIT_CC3000_IRQ  3 // must be an interrupt pin (2 or 3)
 #define ADAFRUIT_CC3000_VBAT  5 // any pin
 #define ADAFRUIT_CC3000_CS  10 // any pin

 //use hardware SPI for remaining pins
 // Uno: SCK=13, MISO=12, MOSI=11
 Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,      ADAFRUIT_CC3000_IRQ,
                                          ADAFRUIT_CC3000_VBAT,      SPI_CLOCK_DIVIDER);
 #define WLAN_SSID  "Ibtikar.AP2"
 #define WLAN_PASS  "#ibtik@r#"
 // set security type
 // WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA, WLAN_SEC_WPA2
 #define WLAN_SECURITY  WLAN_SEC_WPA2
 #define IDLE_TIMEOUT_MS  3000 // amount of time to wait with no date      recieved
                               // before rejecting/closing the collection
 #define WEBSITE  "myapp.herokuapp.com"
 uint32_t ip;
 void setup() {
   // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
/* Initialise the module */
    Serial.println(F("\nInitializing..."));
    delay(100);
    if (!cc3000.begin())
    {
      Serial.println(F("Couldn't begin()! Check your wiring?"));
      while(1);
    }
    Serial.print(F("\nAttempting to connect to "));           Serial.println(WLAN_SSID);
     if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
       Serial.println(F("Failed!"));
       while(1);
     }
    Serial.println(F("Connected!"));
    /* Wait for DHCP to complete */
    Serial.println(F("Request DHCP"));
    while (!cc3000.checkDHCP())
    {
       delay(100); // ToDo: Insert a DHCP timeout!
    }

   /* Display the IP address DNS, Gateway, etc. */
   while (! displayConnectionDetails()) {
     delay(1000);
   }

    ip = 0;
   // Try looking up the website's IP address
   Serial.print(WEBSITE); Serial.print(F(" -> "));
   while (ip == 0) {
     if (! cc3000.getHostByName(WEBSITE, &ip)) {
       Serial.println(F("Couldn't resolve!"));
     }
     delay(500);
   }
   cc3000.printIPdotsRev(ip);

   // Optional: Do a ping test on the website
   Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip);      Serial.print("...");
   int replies = cc3000.ping(ip, 5);
   Serial.print(replies); Serial.println(F(" replies"));
 }

 void loop() {
    /* Try connecting to the website.
      Note: HTTP/1.1 protocol is used to keep the server from closing the           connection before all data is read.
   */
    Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
   if (www.connected()) {
     www.fastrprint(F("GET "));
     www.fastrprint(F(" HTTP/1.1\r\n"));
     www.fastrprint(F("Host: myapp.herokuapp.com"));
     //www.fastrprint(WEBSITE);
     www.fastrprint(F("\r\n"));
     www.println();
   } else {
     Serial.println(F("Connection failed"));
     return;
   }
   Serial.println(F("-------------------------------------"));
   unsigned long lastRead = millis();
   while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
     while (www.available()) {
       char c = www.read();
       Serial.print(c);
       lastRead = millis();
     }
   }
   www.close();
   Serial.println(F("-------------------------------------"));

   /* You need to make sure to clean up after yourself or the CC3000 can           freak out */
   /* the next time your try to connect ... */
        Serial.println(F("\n\nDisconnecting"));
   cc3000.disconnect();
   delay(1000);
 }

 /**************************************************************************/
 /*!
     @brief  Begins an SSID scan and prints out all the visible networks
 */
 /**************************************************************************/

 void listSSIDResults(void)
 {
   uint32_t index;
   uint8_t valid, rssi, sec;
   char ssidname[33];

   if (!cc3000.startSSIDscan(&index)) {
          Serial.println(F("SSID scan failed!"));
          return;
   }

   Serial.print(F("Networks found: ")); Serial.println(index);
   Serial.println(F("================================================"));

   while (index) {
     index--;

     valid = cc3000.getNextSSID(&rssi, &sec, ssidname);

     Serial.print(F("SSID Name    : ")); Serial.print(ssidname);
     Serial.println();
     Serial.print(F("RSSI         : "));
     Serial.println(rssi);
     Serial.print(F("Security Mode: "));
     Serial.println(sec);
     Serial.println();
   }
   Serial.println(F("================================================"));

   cc3000.stopSSIDscan();
 }

      /**************************************************************************/
 /*!
     @brief  Tries to read the IP address and other connection details
 */
 /**************************************************************************/
 bool displayConnectionDetails(void)
 {
   uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

   if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv,      &dnsserv))
   {
     Serial.println(F("Unable to retrieve the IP Address!\r\n"));
     return false;
   }
   else
   {
     Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
     Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
     Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
     Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
     Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
     Serial.println();
     return true;
   }
 }

You don't need to know the IP address; the getHostByName() method takes care of resolving the website to an address. It seems 2 lines are missing from your code:
    #define WEBPAGE "/index.html"  // change the string to the webpage you want

at the top, and:
   www.fastrprint(WEBPAGE);

right after www.fastrprint(F("GET "));. Without these lines, you've failed to indicate the specific webpage you wish to GET. Anyways, when i tried to open myapp.herokuapp.com, I got a message saying that its offline for maintenance, so you'll most likely fail to retrieve anything.


text:
Can I change VCC pin to 3.3V on a 5V Arduino Pro Micro?
I'm using a 5V Arduino Pro Micro (schematic).
For my project, I'm using the VCC pin to output power to an external device.  I need VCC to output 3.3V to the external device.  Can I open jumper SJ1 to reduce the voltage of the VCC pin without affecting the operation of the other parts of the unit?

No. If you change the voltage to 3,3 Volt you also have to change the crystal to 8MHz and reprogram the ATmega32u4 to meet the new frequency.

How other Arduinos handle that were one can switch between running at 3.3 and 5V (e.g. Olimexina 32u4)?

Running the atmega32u4 at 3.3V @16Mhz is outside the "Safe Operating Area" is indicated in the datasheet on page 381. Maximum freq. is around 12Mhz at 3.3V. I myself would just try it and see if it works reliable enough. The chip makes are usually quit conservative about their ratings.

I'm pretty sure that, despite the schematic provided, you will find that the 5V Pro Micro actually has a 5V regulator onboard. So even if you open the jumper, it will still be powering the Atmega32u4 at 5V (technically 5V minus diode voltage drop and regulator dropout voltage).
You could change the regulator for a 3.3V one using a hot air station and solder paste and open the jumper, but as other posters have commented, you would still be running the Atmega beyond spec at 16MHz and 3.3V.

You can, actually albeit 32u4 at 16MHz at 3.3V is outside of the safe operating area, it worked for me perfectly. Also for others :) google for it.

I had the same issue on my cheap 5V @ 16Mhz Pro Micro from ebay. I have the 16Mhz crystal and a voltage regulator marked S2PC.
The J1 was not bridged and I was only getting 3.3V on the digital pins... wait a sec that should be 5V!!
I Went ahead and bridged the J1 jumper and now I am getting 5V on my digital pins! Not sure what is going on behind the scenes with the J1 jumper open with this hardware but I'm thinking it may have been overclocking the chip while running at the lower voltage.
Going to let it run over night and see if something doesn't blow but it looks like they may have just forgot to bridge that J1 whilst mass producing both the 3.3V and 5V versions of this board.


text:
How to use code for OV7670 on Arduino Uno
I want to interface my OV7670 camera (without FIFO) to my Arduino Uno. I have browsed internet quite a lot about it and found people either saying it's not possible or they just give me the link to this github repository (As this guy has done exactly what I want). As the author of this repository is a man of few words, he did not help me very much. I just want to know how to use this to get image sent to my PC serially. I only know how to use Arduino IDE in windows platform and no other platform.

rename main.c to .ino, and change int main(void){ to void loop(void){

Hello, I did exactly that and now it shows this error.
sketch_apr17a.cpp.o: In function loop': H:\arduino-1.0.3_1/sketch_apr17a.ino:122: undefined reference to camInit()'
H:\arduino-1.0.3_1/sketch_apr17a.ino:124: undefined reference to setRes(unsigned char)' H:\arduino-1.0.3_1/sketch_apr17a.ino:125: undefined reference to setColor(unsigned char)'
H:\arduino-1.0.3_1/sketch_apr17a.ino:126: undefined reference to wrReg(unsigned char, unsigned char)' core.a(main.cpp.o): In function main':
H:\arduino-1.0.3_1\hardware\arduino\cores\arduino/main.cpp:11: undefined reference to `setup'

Apply the fix in http://stackoverflow.com/a/21276414 to 0v7670.h

Hey, gerben. What I did is just changed the name of the main.c to .ino and copied the content of ov7670.c to that sketch and compiled and it compiled succefully. All I want to know is, can I do it this way?

I am ComputerNerd. I read this post and realized the real problem and why I am having difficulty helping you. You are asking the wrong question. What you should be asking is "how do I compile it using GNU Make and Avr-Gcc on Windows?". Instead you are asking "how can I use this code in the Arduino IDE?".
The answer to what you should be asking is simple. Use what you already have. The Arduino IDE ships with Avr-gcc and (maybe) GNU Make. Just run the programs directly. Better yet download MinGW and compile GCC to target the AVR yourself.

Thanks ComputerNerd, I was not able to ask more technically right question but I anyway got the solution about running your code in Arduino IDE.

ComputerNerds work is good, but it is has only code and limited description. I have prepared detailed instruction using his code. You can try it: How to use OV7670 and Arduino uno

I have successfully compiled the project in arduino IDE, simply concatenated main.c and ov7670.c ov7670.h into .ino file
didn't test it with the camera yet, but it uploaded to my arduino (Duemilanove)
Tell me if it worked for you...
see here:
https://github.com/eranws/ov7670-no-ram-arduino-uno


text:
Diagnosing crashed Arduino Uno
I have an Arduino Uno connected to a motor controller over I2C. The Arduino accepts commands from a Raspberry Pi via the USB serial line.
I'm trying to diagnose a problem where the Arduino will become completely unresponsive. It's programmed to respond to a "ping" request every N seconds, and for some reason I can't identify, it seems to crash and no longer respond to any commands. However, the motor controller continues powering the motors.
Everything is powered from a 12V Li-Po battery, but everything is located behind 5V regulators. When this problem happens, the battery is fully charged and the motors aren't sourcing much current, and neither the motor controller or Raspberry Pi are effected, so I've ruled out a brownout.
My theory is there's some subtle programming error in my Arduino code that's causing an "exception", but I don't know how to identify it. I've tried adding special code to allow me to trigger one of these, by indexing an array outside of its limits or calling a null function pointer, but the Arduino stubbornly refuses to crash when I try to explicitly make it.
How do I diagnose an Arduino becoming unresponsive?

and for some reason I can't identify, it seems to crash and no longer respond to any commands. - how long does this take? Minutes? Seconds? Hours?

Assuming you don't have access to a debugger, the most common way is to add debug logging. The ususal algorithm to solve those problems is more or less like this:
do {
    add_logs_in_suspicious_places();
    wait_until_it_crashes();
    analyze_logs();
} while( ! i_know_why_it_crashes() );

If you cannot add any debug logging because of a flawed system design (lack of I/O, etc) you've commited a captial engineering crime and this is your punishment. :)

There is an excellent post by Nick Gammon that covers a wide array of possible problems. Look into this, as might be useful.

If you have spare pins, add debugging LEDs. For example, toggle one at the start of loop, another at the start of another function, and so on. When the Arduino "crashes" the state of the LEDs should provide a hint as to where in the code it is.

but the Arduino stubbornly refuses to crash when I try to explicitly make it.

Typically you are indexing outside an array or using uninitialized memory. Your debugging code has moved the problem around enough to stop it happening (or appearing to happen).
If you amend your question and post your code we might spot something.


text:
Using a analog multiplexer to use 9 serial input sensors?
I have 9 sensors, they will send a datastring to my Arduino through Tx/Rx (every 3½ seconds, pre-programmed). The only problem is that there's only one Tx/Rx port on an Arduino Uno. Is it possible to use an analog multiplexer to "make" more Serial ports? Because the sensors send something every 3½ seconds, there's no need to be fast.
EDIT: It's a Temperature and Relative Humidity Sensor

what sensor? can you add a link?

Not that it matters particularly, but every 3-5 seconds or 3.5 seconds?

exact model of the sensor please

No. Not unless you can change your communication protocol to be a "call-and-response" protocol.
Basically, the problem is this: when do you switch to which serial device? Unless all the devices have their timing synchronised there is no way of knowing - so how do you control your analogue multiplexer in that situation...?  You can't.
You would need to have some method of the master switching the multiplexer to a specific peripheral, then send a message to that peripheral saying "Send me your data now".
You would be better off investigating other boards with more UART ports, such as the Mega2560, and having multiple boards.
The Mega2560 has 4 UART ports. You can have 4 sensors per board (5, if you want to use SoftwareSerial or, better, AltSoftSerial), so you could get away with two boards.
One board acts as normal, communicating on the UART ports to 4 sensors, and also acts as an I2C or SPI master (the choice is yours). The second board communicates to 4 more sensors on UARTs and one further on using AltSoftSerial etc. It also acts as an I2C or SPI slave device.
The "slave" board just runs autonomously gathering data from the sensors it is directly connected to and storing those values.  The "master" then periodically asks the "slave" board for the latest data.

Thanks for the answer and my apologies for the late answer.
I just tried a multiplexer, because some people said that I would work. I can receive info from all the 9 sensors. The sensor sends a datastring and I filter the temperature and relative humidity and then I switch to the next sensor. It works quite well, the only problem is that you can't request the datastring, so you should wait till the datatstring is sent


text:
How do I create a state machine for my purpose?
I am new to Arduino.
I have a motor which drives a sliding door back and forth. The motor is connected to an H bridge which has two control pins (direction, speed). I have a switch which is intended to activate the motor for a set amount of seconds to open the door fully. When the switch is deactivated, the motor reverses for the same duration as opening.
I have written some basic code using the 'if' argument, but my issue is that the code under the 'if' argument loops when my switch is activated/deactivated whereas I want it to run once per switch activation. Looking online I saw that a state machine may be my solution, but my lack of expertise with coding means I cannot create a state machine. This is my code:
const int Switch = 2;
const int hbridge1 = 13;
const int hbridge2 = 12;
const int threshold = 400;

int buttonState = 0;

void setup() {

  pinMode(hbridge1, OUTPUT);
  pinMode(hbridge2, OUTPUT);
  pinMode(Switch, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {
  int buttonState = digitalRead(Switch);
  Serial.println(buttonState);

  if (buttonState == HIGH) {
    digitalWrite(hbridge1, HIGH);
    digitalWrite(hbridge2, LOW);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW); //I only need the motor to activate for four seconds, but 'if' loops it infinitely
  } else {
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, HIGH);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW); //Same issue  here
  }

;
  delay(1);
}

to open it when it is switched on .... to open what? ... the switch?

code under the 'if' argument loops infinitely ..... that is not correct .... code in the loop() function loops infinitely

look at the BlinkWithoutDelay example sketch .... it shows how to time an event .... you also need to store the value of buttonState and run the code only when it changes (store the new value of buttonState at the end of the code)

Creating a few boolian variables could help with this.
bool opening = 0
bool closing = 0

const int Switch = 2;
const int hbridge1 = 13;
const int hbridge2 = 12;
const int threshold = 400;

int buttonState = 0;

void setup() {

  pinMode(hbridge1, OUTPUT);
  pinMode(hbridge2, OUTPUT);
  pinMode(Switch, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {
  int buttonState = digitalRead(Switch);
  Serial.println(buttonState);

  if (buttonState == HIGH && opening == 0) { //variable "opening" is tested
    opening == 1  //variable "opening" is set to on
    closing == 0  //variable "closing" is set to off
    digitalWrite(hbridge1, HIGH);
    digitalWrite(hbridge2, LOW);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW);
  }
    else if (buttonState == Low && closing == 0){ //variable "closing" is tested
      opening == 0    //variable "opening" is set to off
      closing == 1    //variable "closing" is set to on
      digitalWrite(hbridge1, LOW);
      digitalWrite(hbridge2, HIGH);
      delay(4000);
      digitalWrite(hbridge1, LOW);
      digitalWrite(hbridge2, LOW); //Same issue  here
  }
  delay(1000) // delay is in milliseconds. So 1000 = 1 second
}

These new variables are set when the code is ran the first time. Therefore, no looping.

A schematic will help to create a solution. Are you using a resistor, like 10K, to pull the switch pin low? If the button is not pressed and the code keeps looping through like it is pressed, I recommend adding the resistor. You may need to add another component though. Like a micro-switch on the frame of the door that gets tripped while it is closed. Or a button to close the door. Without that every loop through the code will think the switch is held low and activate the motor. Which might burn out the motor or trip a fuse.
if(buttonstate == high){
//open door
}
else{
if(microswitch == high){
//H-bridge pins low, low
{
else{
//close door
{

simulate this circuit – Schematic created using CircuitLab

Thank you for your response. I am using the inbuilt pull up resistor to pull the switch pin low. As for the microswitch, it is a good idea however for my purposes I would like to control the motor using a fixed duration (I have timed how long it takes for the motor to open/close the door using a stopwatch). When the switch is low, activate the HBRIDGE1 pin for closing duration then halt till the switch is activated. When the switch is high, activate HBRIDGE2 pin for opening duration.

every time void loop() loops it will look at the switch and see it is low and activate the else{} loop of the if. So the door will be closed and it will do else{} you might need something more. like
if(buttonstate == high){
//open
//delay
//close
}
else{
//h bridge low, low
}

I'll do that until I can work out how to make a state machine. Thanks.

K.I.S.S. Keep It Simple Stupid. I think that is the simplest solution. It will open, delay, close, then if it is low it will sit with the motor in break mode


text:
How is a long int stored in an 8 bit Arduino register
Assume the following code in C:
long int a = 262143;

which in binary will be 111111111111111111 (18 bits).
If an atmega328p register can hold 8 bits, how is the above represented in the register?
Compiled Assembly:
    .file   "a.c"
__SP_H__ = 0x3e
__SP_L__ = 0x3d
__SREG__ = 0x3f
__tmp_reg__ = 0
__zero_reg__ = 1
    .text
.global main
    .type   main, @function
main:
    push r28
    push r29
    rcall .
    rcall .
    in r28,__SP_L__
    in r29,__SP_H__
/* prologue: function */
/* frame size = 4 */
/* stack size = 6 */
.L__stack_usage = 6
    ldi r24,lo8(-1)
    ldi r25,lo8(-1)
    ldi r26,lo8(3)
    ldi r27,0
    std Y+1,r24
    std Y+2,r25
    std Y+3,r26
    std Y+4,r27
    ldi r24,0
    ldi r25,0
/* epilogue start */
    pop __tmp_reg__
    pop __tmp_reg__
    pop __tmp_reg__
    pop __tmp_reg__
    pop r29
    pop r28
    ret
    .size   main, .-main
    .ident  "GCC: (GNU) 8.2.0"

It isn't.  It's split into four 8-bit values, each representing a quarter of the bits.  Each value is stored in a separate register or memory location (depending on what is being done with it).
Software then combines them together to act as a single 32-bit value.

Then how would a single instruction look like? isn't an instruction supposed to be 8 bits in length in this case?

There is no "single instruction".  You should compile some code and look at the resultant assembly language - you'll find it's many instructions long.  This is why 32-bit CPUs are more efficient than 8 bit.

I added the assembly code above, so I guess ldi r24,lo8(-1)     ldi r25,lo8(-1) are doing that

and ldi r26,lo8(3) since you're working with 18 bits not 16.  0xFF is -1 in two's complement, so you have 0x03 ff ff which is 0b111111111111111111.

one last question, what does the above code do exactly? it populates 3 registers with 2  lower 8 bit of -1 = 111111 and 1 lower 8 bit of 3 = 000011 ?

Yes. "ldi" is "LoaD Immediate".  You end up with r24 = 0xFF, r25 = 0xFF and r26 = 0x03.

One more off topic question (hope I can ask it properly). instructions are stored in RAM right, in this case an 8 bit instruction is somewhere in RAM and CPU loads it. How does CPU know where the instruction ends given a RAM address? how does it know the different between an instruction and a small integer length which has lower bit counts? Basically how doesn't it keep reading the RAM and knows where to stop

Fun fact: the compiler supports int64_t and uint64_t on a arduino uno. That is a variable of 64 bits (8 bytes) on a 8 bit microcontroller.

@Joshl No - instructions are in flash, not RAM, and flash is 16 bits wide.  Each instruction either fits in one 16 bit word or two 16 bit words depending on the instruction. The CPU knows how "long" each instruction is by the fact that the instruction itself will contain information about what needs to be fetched from where.

It's actually 4 registers (r27:r24), and 4 bytes of stack: (SP+1 to SP+4). Not sure why the stack is used. Maybe the variable was volatile, or the code was compiled at -O0...

@EdgarBonet The stack is used because r24-r27 are in the "call clobbered" category. They're just used temporarily to place the values into memory since you can't LDI direct into memory. Registers 18-27, 30 and 31 can only be used for temporary storage since any function called is allowed to change the value and not restore it. 2 to 17, 28 and 29 are "call saved" - any function must restore them after use. Whether the compiler decides to use memory or "call saved" registers for its variables depends on what it's being used for and what else is going on.

https://gcc.gnu.org/wiki/avr-gcc#Call-Used_Registers

I am aware of the call saved / call clobbered distinction. My point is: if you don't make a volatile, then it is optimized away by the compiler at any optimization level other than -O0.

@EdgarBonet no it isn't.  It can be, but whether or not it is depends entirely on both what a is being used for, and what other variables are around. There's limited registers that can be used. If a is considered less important it won't waste a dedicated group of registers on it  You cannot second guess what the optimizer will do just on the strength of a single variable.

I can. I have read the compiler's generated assembly.

It probably was compiled with no optimization anyway. That assembly can't have been produced from Arduino code, so has no validity on this site anyway. So it's very much down to whatever the OP typed on the command line, and so is outside the scope of this site.


text:
How to get Baite Pro Mini working?
I have recklessly bought the Baite Pro Mini and I find it difficult to upload any program. I use Ubuntu Linux, but out of frustration I am ready to install Windows, if it is necessary.
I've read the information from the blog http://nerdralph.blogspot.ca/2014/01/baite-pro-mini-review.html . Too bad, that the blog owner didn't put much details. Can anyone here fill some blanks for me?

How exactly should I connect the Arduino device to the computer?
I have a converter USB to serial pl2303HX:  which I tried to connect with the Baite Pro Mini in almost any plausible permutation of the wires, but never got any result.

edit:
Here is the description of pins of the pl2303HX:
(source: fasttechcdn.com)
I did connect it the following way:
Baite Pro Mini      pl2303HX
GND
GND  <------------> GND
VCC  <------------> +5V
RXI  <------------> TXD
TXC  <------------> RXD
DTR

I also tried the permutation with different GND pin. I also tried pressing the reset button on the Baite Pro Mini around the time of hitting the "Upload" button on the Arduino standard compiler.
I believe my failure might have something to do with the absence of DTR pin on the converter that resets the board just before upload. Are my worries justified? Is there anything I can do?

Which exactly Arduino bootloader do I need?

How to connect USBASP to the Beite Pro Mini?

GND to GND, VCC to VCC, TX to RX and vice versa.

@IgnacioVazquez-Abrams That was my second try (not first... ;-) ) and it didn't work. I believe my failure might have something to do with the absence of DTR pin on the converter that resets the board just before upload. Are my worries justified? Is there anything I can do?

@IgnacioVazquez-Abrams I've updated the question

I have several clone Pro Minis I got from several sources on ebay for ~ £2 ($3) each. I also use Ubuntu (10.04 on this old PC but it's fine).
I started with a USB converter similar to yours and it was a bit hit-and-miss choosing when to press the reset to upload. Once I got connections right and worked out when to press reset it became a more reliable procedure but still a pain.
I realised that it would be better to use the auto-reset from DTR so I got a cheapo USB to serial from ebay which claimed to be FTDI (or compatible?) though I didn't know what that meant at the time. With a small converter board to make the right connections it works well.
Your connections look good so if you haven't damaged anything it's probably a matter of when to press reset. Windows won't help!
You must choose the correct board in the Tools menu of the Arduino IDE - Pro Mini with correct AVR chip, speed and voltage. I use programmer AVR ISP (I think)

His connections look bad - gnd & Vcc are adjacent on the processor board and separated by 2 pins on his converter.
A reset does not seem to be needed when using the Baite processor AND Baite USB module.

@RussellMcMahon I didn't mean with my diagram to show the actual layout of the cables, only the labels on one side and (in random order) the labels on the side of the controller and which pin was connected where.

I am waiting for a delivery of the USB converter that supports the reset (has a DTR pin). I hope it will solve my problems. The chip itself doesn't seem to be broken; when powered the blue diode is blinking exactly the same as it was the first day.

Your connections are incorrect if you are "straight through" connecting.
Gnd & Vcc are adjacent on the processor board and separated by 2 pins on your converter.
If you find Gnd, Vcc, TX, RX on USB module and processor then you should

Connect Gnd to Gnd
Connect Vcc to Vcc
Connect ........TXD to RXD and
 ........................RXD to TXD
Ensure that you have the correct USB converter drivers loaded.

A reset does not seem to be needed when using the Baite processor AND Baite USB module.

I have a number of Baite Pro Minis working perfectly.
In my experience (3 or 4 sales so far) Baite's products are usually of acceptable quality .
Connecting "almost any plausible permutation of the wires" is a fine way to attempt to destroy the converter and/or the BPM. Logical connection should work - if you have not damaged something.
Connect as Ignacio says.
Note that you connect BPM-TX to USB-converter-RX, and RX to TX and **NOT RX to RX). The BPM has connections shown on the PCB.

Baite provide this diagram

Your converter module has a different pinout which needs to be allowed for.

You must also have drivers on your system for the USB to serial bridge IC used on your converter. The Baite converter uses a CH340G IC. Your may or may not.

Thank you for your beautiful answer. Don't pay attention to the layout of the pins on the right side, I don't use the "straight through" connection. Pay attention only to the labels. It is cumbersome to draw crossed lines in ASCII.


text:
Connect function generator to Arduino
How do I connect a function generator that generates an analog signal to an Arduino Uno?
I don't know how to begin, so could you also tell me the settings for the function generator, e.g. its amplitude, frequency, etc, that won't damage my Arduino?
I plan to visualize the output on Processing.

(source: sonoma.edu)

I haven't connected it yet, am scared to break the board.

From googling i know it should be connected to pin 8 on arduino.

What do you want to achieve? Please describe the overall circuit.

From googling i know it should be connected to pin 8 on arduino. - all of the pins can take inputs. If you are trying to measure analog inputs you mean pins A0 through to A5. Do you have a specific reason for mentioning pin 8?

I have that same function generator! make sure you ground your ardunio to the FG, & output dc values not over 3.3V. you can set a dc offset to keep the wave above 0V.

Confirm with an oscilloscope
When I connect my function generator I usually always make sure that the output is in the range 0 to 5V, with my oscilloscope. The default is probably more like ±2.5V - but I don't have an Agilent so you would have to check. Press the Ampl button to check. (Mine reads 5VPP).

You can see from the above image that we indeed have (roughly) 5VPP - and that there is a -2.56V component, which will damage the Arduino, being negative.

Add an offset
So press the Offset button and add a 2.5V DC offset. Now the voltage jumps 2.5V and is between 0 and 5V:

The scope confirms that the minimum is 80mV and the maximum is 4.96V, which is in range for an Arduino pin (assuming you are running an Arduino at 5V, which is not always the case).
Now you should be safe to experiment with different frequencies and wave-forms. Just leave the Amplitude and Offset alone. :)

Extra precautions
You could feed the function generator through an input protection circuit, just in case you absent mindedly forget to carry out the appropriate steps.

The zener diode will conduct negative voltages to ground (dissipated through the 1k resistor) and will also limit positive voltages to around 5.1V.

I don't know how to begin, so could you also tell me the settings for the function generator, e.g. its amplitude, frequency, etc, that won't damage my Arduino?

That is not an Arduino question. That is a question about how to operate the function generator. Please check the users manual. You need to set the voltage output (DC + AC) so that it matches the Arduino.
An analog signal should go to an analog pin on the Arduino (not pin 8). It is also important to connect GND.
Cheers!

Using the built in USB interface would make things a lot simpler... :-)

Depends on how the OP wants to connect the function generator. My interpretation is somewhat different; Function Generator => Analog Pin (Arduino) => Processing (Serial).

Good point! :-)

Looking at the Agilent 33220A 20 MHz Waveform Generator User's Guide, I can see that the Function Generator has a USB port. If you have, or can get hold of, a USB Host shield for the Arduino, you should be able to link the two together physically. Then, using the USB Host Library for Arduino, you could get the two talking to each other.
Alternatively, if you fancy a bit more hard work, then you could get a MAX3421E, and wired it up yourself as an interface, but I wouldn't recommended it.
Note: If you have an Arduino Due (I know that you say that you have an Uno, but just in case) then you could use the USBHost library to connect the two directly, without the need for a USB Host shield.
Regarding, getting the two to talk together, that may not be exactly easy. From the manual I can see that the PC software can auto-configure the function generator, however, for receiving data it may not be so easy. You appear to have to send a GTL command to get the data sent to the USB (p251, and onwards, of the manual). Good Luck! :-)

I can see that the Function Generator has a USB port. - I think he wants to generate test signals, not control the function generator.

@NickGammon - Yes, re-reading the question, I can see that I got a little carried away! :-)

authors: Ηλεκτρολόγος Μηχανικός


text:
How do I check if a password is right? (keypad input)
Im having a problem with my arduino code.Im trying to make an alarm system with a pir sensor.So when the pir activates and the buzzer starts buzzing i want to be able to type a set password in the keypad and the buzzer should stop buzzing. since my passcode is 4-digit (1331) I wrote this code, but it`s not working.
 while(i<=4,i++)
{
char key = keypad.getKey();

pass.append(key);
}
if(pass.evaluate())
{
  digitalWrite(buzzer, LOW);
    keypad.waitForKey();
    delay(6000);
}

My idea is that the program checks 4 times for the pressed key and adds it to the guessed password (im using the password library and the password is defined as well as int i=0;)
But for some reason when I type 1331 the buzzing continues. Please help me with that project and excuse my grammar, English is not my native language.
edit:
the full code:
#include <Password.h>
Password pass = Password( "1331" );

#include <Keypad.h>
int sensor = 11;
int buzzer = 10;
int i = 0;

const byte rows = 4; //four rows
const byte cols = 4; //four columns
char keys[rows][cols] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[rows] = {8, 7, 6, 9}; //connect to the row pinouts of the keypad
byte colPins[cols] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

void setup() {
pinMode(sensor, INPUT);
pinMode (buzzer, OUTPUT);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
keypad.waitForKey();
digitalWrite(buzzer,HIGH);
  delay(125);
  digitalWrite(buzzer, LOW);
  delay(6000);

}

void loop() {

  char state = digitalRead(sensor);
  if (state == HIGH)
  {
    digitalWrite(buzzer, HIGH);
    while(i<4,i++)
    {
    char key = keypad.getKey();
    //keypad.waitForKey(); not sure if i should use that

    pass.append(key);
    }
    if(pass.evaluate())
    {
      digitalWrite(buzzer, LOW);
        keypad.waitForKey();
        delay(6000);
    }

  }
      }

Please post a minimal, complete, verifiable example.

You might want to add some delay, or wait till the button is released. Otherwise, when you press for example 1, it will keep appending 1s till it reaches 4.

This is completely the wrong way of doing a loop. Since Arduino uses C++ I made this test program:
#include <stdio.h>

int main (void)
  {
  printf ("starting\n");
  int i = 0;
  while(i<=4,i++)
     {
     printf ("%i\n", i);
     }
  printf ("done\n");
  return 0;
  }

This prints:
starting
done

Note that the loop is executed zero times. This is because you used the "comma operator".
From https://en.wikipedia.org/wiki/Comma_operator you can see:

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

In other words, your loop adds one to i and checks if it is zero (before adding one). Thus the loop terminates immediately.
A better construct would be:
for (i = 0; i < 4; i++)
   {
   // whatever
   }

That is the standard C/C++ way of doing a loop a fixed number of times.

Also, most keypad libraries return NO_KEY if the user hasn't pressed a key.
You should test if keypad.getKey() returns NO_KEY and if so do nothing.
All your code would have done (if it had executed 4 times) was get 4 times NO_KEY (in a few microseconds) which would not be the correct password.

Without knowing how the pass.* works, it will be impossible to pinpoint the problem.
'key' gets an ASCII value. Is that would you are expecting?
Does pass.* reset (start over) once 4 digits?
Just a guess, but I believe that *.waitForKey() does not consume the key.
The algorithm only gets the key four times; then, it checks.

Password pass = Password( "1331" ); that`s how pass. works.

Could you just write me another algorithm to check for the password? I think this one is not good.

There's nothing wrong with the excerpt you posted. The problem is with code you haven't posted. As I requested, please provide a minimal, complete, verifiable example of your code, and then someone may be able to help. We don't know how you have your equipment connected, what libraries you're using and so on, so we cannot test our code or be sure it will work for you.

This is classical indexing problem:
while with <= 4 actually runs five (5) rounds.
So, use < 4.

Ok. I didint have access to my pc so I wrote what I remembered of my code. Here is the full one

... Unless i starts at 1, which we can't tell because we have a snippet of code without context.

I wrote what I remembered of my code - please don't post "remembered" code. Wait until you are at your PC and post the actual code. Posting "remembered" code just wastes everyone's time.

Assuming i starts at zero, while(i<=4,i++) executes zero times, not 5 times.

In case anyone was wondering, heres the code I came up with and now it works.
#include <Keypad.h>
int sensor = 11;
int buzzer = 10;
int red = 12;
int i = 0;
String Pass = "1331";
String tempPass = "";

const byte rows = 4; //four rows
const byte cols = 4; //four columns
char keys[rows][cols] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[rows] = {8, 7, 6, 9}; //connect to the row pinouts of the keypad
byte colPins[cols] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

void setup() {
pinMode(sensor, INPUT);
pinMode (buzzer, OUTPUT);
StartingBuzz();
keypad.waitForKey();
digitalWrite(red,HIGH);
digitalWrite(buzzer,HIGH);
  delay(200);
  digitalWrite(buzzer, LOW);
  delay(60000);
}

void StartingBuzz()
{
digitalWrite(buzzer, HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer, HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
  }

void UnlockBuzz()
{
  delay(200);
       tone(buzzer,3250,200);
       delay(300);
       tone(buzzer,3500,200);
       delay(300);
       tone(buzzer,4000,200);
  }

void loop() {
  i=0;//resets the password-checking loop.
  tempPass = "";//resets the guessed password.
  char state = digitalRead(sensor);
  if (state == HIGH)
  {
    digitalWrite(buzzer, HIGH);
    A:
    {
    while(i < 4)
    {
    char key = keypad.getKey();
    if(key != NO_KEY)
    {
      tempPass += key;
      i++;
      }
    }
    }
    if(Pass == tempPass)
    {
      digitalWrite(buzzer, LOW);
      digitalWrite(red, LOW);
      UnlockBuzz();
      keypad.waitForKey();
      digitalWrite(buzzer,HIGH);
      delay(200);
      digitalWrite(buzzer, LOW);
      digitalWrite(red, HIGH);
      delay(60000);
    }
    else
    { tempPass = "";
       i=0;
      goto A;
      }

  }
}


text:
SPI with a level converter in the other end of connection
I have an Arduino MEGA hooked up with a NRF24L01, and working nicely, talking with another Arduino Uno. It works as described, power supply to 3.3V, and SPI lines (MISO,MOSI,CLK) connected directly to the Arduino;
However, when I hook up a level converter in the end (5V to 3V, bidirectional) (making the NRF module in the middle, like in a T connection), the module stops working, and I don't know why. How does the level converter module is interfering in the connection? Is there any way I can prevent this and use it?
I intend in adding in the future, modules that talk in 3.3V SPI;
This is the level converter I'm using:

(source: at-the.space)
I suspect it is because of the pullups (5 think that these 10kΩ resistors are pull-ups, but I'm a noob in that part), but I really don't know if that is the problem, as the seller advertises it as being compatible with SPI, I2C, and UART. I have successfully used these for a UART.
I have checked Slaving multiple Arduinos via SPI and tried using an external 5V supply, and a 3.3V supply, but no dice.. However, the 3V side has no connections to it; But, being bi-directional, I don't think there is a problem with this...
I found that 74HCT245D works very well for this, but I'd like to know why with the level converter from JY-MCU this won't work.
Providing the library and connections just in case (the module works without the level converter):

Library & sketch comes from Optimized High Speed NRF24L01+ Driver Class Documenation.
Connection:

NRF2401 Pinout:
NRF24l01 http://ralphfox.at-the.space/imglink/nrf24l01.jpg
My connection:
Arduino with NRF24l01 and Level Converter  http://ralphfox.at-the.space/imglink/nrf_bb.png

making the NRF module in the middle, like in a T connection - what do you mean by that? Can you post a schematic of what you have done, exactly?

How is ground connected? Arduino, converter, module?

@NickGammon Sorry, i have added the connection for arduino, thanks.

@MikaelPatel Added the connection, please check it, thank you.

You have put the NRF24 on the wrong size of the converter.

@MikaelPatel Hmm, i'm mostly sure i tried both sides.. but anyway i thought in putting in the 5V side of the converter, because the arduino is sending and receiving the data through the 5v digital pins; I'll try to re-connect them to the 3v side, with the arduino on 5v side..

@MikaelPatel Yep, no dice :/ i just got home, putting the NRF24 on the 3.3v side gave me the same result as in the 5v.. I'm thinking the issue might be electrical, not logical; maybe it's better to have this topic moved over to electronics?

I don't realy see on presented circuit how your level-converter is connected with other components but I would suggest to check twice the 4-bit SPI signal directions. I guess that converter pins connected to one of MOSI/MISO   should be swapped.

@soerium there is none connected yet; I tried putting one side of the MISO/MOSI on the 3.3v, but that caused the same line to rise to 5v; an non 5v tolerant module on that line would suffer... Remember that the nRF24 is on the 5v side of the level shifter, together with the arduino (same 5v bus); Thanks for the reply thought!

More than probably your level shifter is not fast enough.
A level shifter uses a mosfet to copy signals from one voltage level to the other, but each mosfet has a latency or, if you prefer, a rise time.
Your board probably doesn't use a fast switching mosfet and so the SPI protocol (which is a quite fast one) is not copied correctly.
On top of that you actually don't need a level switcher for the nRF24 modules: the power pin must be limited to 3.3V, but the signal pins are 5V tolerant.
This means you only need a 3.3V voltage source and all the remaining connections can go directly (and safely) into your Arduino board.
UPDATE: the speed concept still applies, it doesn't matter which side of the connection you are using. A mosfet has a little capacitance which slows down the signal transmission: higher the capacitance, slower the maximum data rate.
The cheap chinese level shifter is not designed for high speed communication, while the Texas Instrument device is clearly designed for high speed.
If you look at the SN74HCT245 datasheet you'll notice the switching speed is reported for 50pF capacitance and ranges from 8ns to 16ns: that's the time needed to build enough charge in the switching circuit.

For other devices, you could increase the SPI clock divider to get slower SPI signals. Or voltage divider resistors (which might be faster).

@Paul voltage divider resistors are definitely slower than the level shifter, consider a generic mosfet as a voltage divider in the order of the milliohms: an equivalent voltage divider will be very close to a short. The SPi clock divider is definitely a good advice though, even if not always applicable.

Ah, I always consider resistors to be "instant". But that'd be my mistake (: lowering SPI clock should be applicable in almost every scenario though? But yeah, don't try to fix it in software. ...especially if it lowers your speed (:

@RobertoLoGiacco Sorry for the late reply, i'm on another timezone it seems;As stated in the question, i am not using the level switcher on the nRF24, i was going to use the level switcher to add non 5v tolerant modules(3.3v) to the same SPI line; Sorry if i was not clear enough. I fail to see how the slow level shifting is hitting the nRF24 as the wireless module is on the 5.5v; could you explain please? I solved by using a 74HCT245D; but the question still stands, "why i am not able to use the level shifter?" Thanks for your reply.

5 minute limit to edit... by 10 seconds, damm :/   ; the question would be "why i am not able to put the level shifter on the same bus the nRF24 is?"

@RalphFox I hope my update satisfied your comments, in which case... you know... ;-)

AVR's like all digital have their limits. In this case you're dealing with source resistances that need to charge multiple gate capacitances through series resistances (wires and metal contact connections. Specifically an Absolute MAX 40mA/pin, some milliohms in your copper wire and PCB traces, and pico to nano Farad capacitances, plus depending on how High Speed the SPI is (the spec does not list an upper limit), you will be also contending with frequency limiting parasitics. At MHz frequencies, your wire and PCB traces will have higher resistances due to "skin" effect, where the electrons migrate to the surface of the wire when transferring. Depending on frequency of the wire, adding just a single gate could degredate rise/fall times enough to corrupt data, as the SPI library (whichever you choose) and the SPI peripheral within the AVR probably won't be as sophisticated as a PC based one. The AVR & the SPI library lacks sophistication in that neither has provisions to detect and compensate for extra gate capacitance on the bus line, nor could they compensate for china jumper wires which are quite small (9x40ga) wiring.
There are many factors which could corrupt your SPI project that are coming into play to limit performance.
You should probably do some internet research on high speed bus anatomy if you intend on pushing the SPI bus on the arduino to it's limits.
I think the gate capacitances are combining with source resistance and skin effect and your 40mA/pin is not in fact 40mA per pin but more like 10-20mA is hitting all gate capacitances when skin effect is considered (it effectively raises the resistance of the wire sufficiently to then be a factor).
If connecting the JY-MCU converter AND running SPI at minimum speed corrects communication, then the extra gate capacitances are the factor you should change to higher performance versions. There's the 74AS series with gate times down to 1.7nS and fMAX up to 40MHz!
Hope this helps.


text:
Is it possible to change pin operation from output to input within the Arduino loop (event-driven)?
Is it possible to change pin operation from output to input within the Arduino loop (event-driven)?
I would like to change the operation of a couple of Arduino pins from input to output during execution of the Arduino loop in an event-driven way. Is this possible please?

How do you mean "in an event driven way"? The Arduino has no events - maybe you are using some other software?

I mean that the functioning of certain pins as input or output would 'depend' upon some condition, some event happening one one of the other input pins.

The answer above is correct but the syntax is wrong (atleast to my knowledge).
The correct syntax is pinMode(pin, mode) copied from the original arduino.org post.Note:If I am wrong pls correct me

Yes.
Just call pinMode([pin], [mode]) whenever you want to change from input to output or output to input.
How to decide when to do that is entirely up to you. You can do it any time you choose using any stimulus you like.


text:
changing analog pins data logging using sdFat library
Background:
My goal is to use sdFat library, more precisely AnalogBinLogger example.
I want to log data from changing analog pins for example, I want to log from pin 0 to pin 3 for 5 minutes and then from pin 4 to pin 6 for another 5 mins and then from pin 7 to pin 9 for another 5 mins. that is going to be continuously which means I am going to get rid of the part where you have to enter "r" to start logging.
Regarding the time, I managed to figure it out, I am just using the value of the variable count, if my sampling rate is 1000 samples/sec for example then 5 minutes will be 1000*60*5 and the change will be done in this line:
if (Serial.available()) {
  // Stop ISR calls.
  adcStop();

to
if (count >1000*60*5) {
  // Stop ISR calls.
  adcStop();

and this worked fine.
My problem is with the changing pins:
const uint8_t PIN_LIST[] = {1};

I changed this line to
uint8_t PIN_LIST[3] = {};

First I removed the word const, because it's not going to be constant anymore, and I just declared an empty array, and second I am changing the pins in the loop.
Here is the loop after I got rid of doing the serial input:
void loop(void) {
int i;
for (i=0;i<=12;i+3)
{
  PIN_LIST[] = {i,i+1,i+2};
  logData();
  Serial.println("done");
 }}

The problem is I get this error :

AnalogBinLogger.ino: In function 'void loop()':
AnalogBinLogger:808: error: expected primary-expression before ']'
token
AnalogBinLogger:808: error: expected primary-expression before '{'
token
AnalogBinLogger:808: error: expected `;' before '{' token

The line 808 is:
PIN_LIST[] = {i,i+1,i+2};

So this is the only error, any help please?
The code is so long (800+ lines) if this information is not enough and you need me to explain a part then just tell me.

in case someone has the same problem
it seems like after you initialize an array this way
uint8_t PIN_LIST[3] = {};
you won't be able to assign all the values at once:
PIN_LIST[] = {i,i+1,i+2};
instead you assign each individual value

PIN_LIST[0] = i;
PIN_LIST[1] = i+1;
PIN_LIST[2] = i+2;

and now it worked : )