text:
Integrating two Arduino Ethernet libraries in one sketch
I am trying to integrate two different Arduino Ethernet libraries, EtherShield and UIPEthernet in one sketch.
EtherShield library is used to control LEDs via Android mobile application. While UIPEthernet is used to control the same LEDs via Web Server.
Both codes run perfectly when they're uploaded individually. But I need them to run in a single sketch. So I combined them in one sketch. That's where my problem is. They're not running smoothly anymore. My mobile app can only turn one LED off then the app will crash. Accessing my Arduino's web server gives me error as well (but before it is really, really working T.T)
Help me, please.
This is my code
// ========== UIPEthernet library
#include <Dhcp.h>
#include <Dns.h>
#include <ethernet_comp.h>
#include <UIPClient.h>
#include <UIPEthernet.h>
#include <UIPServer.h>
#include <UIPUdp.h>

// ========== EtherShield library
#include "EtherShield.h"
#include "ETHER_28J60.h"

// ========== MOBILE
//static uint8_t mac[6] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
//static uint8_t ip[4] = {192, 168, 15, 97};
static uint16_t port = 80;

ETHER_28J60 e;

// ========== WEB
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 15, 97 };
byte gateway[] = { 192, 168, 15, 1 };
byte subnet[] = { 255, 255, 255, 0 };

String inString = String(35);

int i;  // Used for looping
String Room;

int pin[] = { 0, 2, 3, 4, 5 }; // Lock pin num 0 in array is not used
int numOfRooms = 4; // Number of rooms
String value[] = { "OPEN", "OPEN", "OPEN", "OPEN", "OPEN" }; // Startup all rooms are closed

EthernetServer server(port);
String data;

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

  // ========== MOBILE
  e.setup(mac, ip, port);

  // ========== WEB
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();

  // Set pin mode
  for (int j = 1; j < (numOfRooms + 1); j++)
  {
    pinMode(pin[j], OUTPUT);
  }

  Serial.println("\n[ WEB + MOBILE ]\n");
  Serial.println("Serial READY");
  Serial.println("Ethernet READY");
  Serial.println("Server READY\n");
}

void loop()
{
  webModule();
  mobileAppModule();
}

void mobileAppModule()
{
char* params;
if (params = e.serviceRequest())
{

  //ROOM 311
  if (strcmp(params, "?cmd=1") == 0)
  {
        digitalWrite(pin[1], HIGH);
        Serial.println("ROOM311 is OPEN\n");
  }
  if (strcmp(params, "?cmd=2") == 0)
  {
        digitalWrite(pin[1], LOW);
        Serial.println("ROOM311 is CLOSE\n");
  }

  //ROOM 312
  if (strcmp(params, "?cmd=3") == 0)
  {
        digitalWrite(pin[2], HIGH);
        Serial.println("ROOM312 is OPEN\n");
  }
  if (strcmp(params, "?cmd=4") == 0)
  {
        digitalWrite(pin[2], LOW);
        Serial.println("ROOM312 is CLOSE\n");
  }

  //ROOM 313
  if (strcmp(params, "?cmd=5") == 0)
  {
        digitalWrite(pin[3], HIGH);
        Serial.println("ROOM313 is OPEN\n");
  }
  if (strcmp(params, "?cmd=6") == 0)
  {
        digitalWrite(pin[3], LOW);
        Serial.println("ROOM313 is CLOSE\n");
  }

  //ROOM 314
  if (strcmp(params, "?cmd=7") == 0)
  {
        digitalWrite(pin[4], HIGH);
        Serial.println("ROOM314 is OPEN\n");
  }
  if (strcmp(params, "?cmd=8") == 0)
  {
        digitalWrite(pin[4], LOW);
        Serial.println("ROOM314 is CLOSE\n");
  }

  //
  if (strcmp(params, "?cmd=9") == 0)
  {
        digitalWrite(pin[1], LOW);
        digitalWrite(pin[2], LOW);
        digitalWrite(pin[3], LOW);
        digitalWrite(pin[4], LOW);
        Serial.println("All rooms are now CLOSED\n");
  }

  e.respond();
  }
}

void webModule()
{
     EthernetClient client = server.available();

 if (client)
 {
 // An HTTP request ends with a blank line
 boolean current_line_is_blank = true;

 while (client.connected())
 {
  if (client.available())
  {
    char c = client.read();
    // If users have gotten to the end of the line (received a newline
    // character) and the line is blank, the HTTP request has ended,
    // so users can send a reply

    if (inString.length() < 35)
    {
      inString.concat(c);
    }

    if (c == '\n' && current_line_is_blank)
    {

      // Send a standard HTTP response header
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();

      client.println("");

      client.println("<title>CONTROL PANEL</title>");

      client.println("");

      client.println("
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
COLLEGE OF ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
COMPUTER ENGINEERING LABORATORY
");
      client.println("

");
      client.println("

");
      client.println("
");
      client.println("

CONTROL PANEL

");

      client.println("<form method=get>");

      for (i = 1; i < (numOfRooms + 1) ; i++)
      {
        Room = String("ROOM") + (i + 310);

        if (inString.indexOf(Room + "=OPEN") > 0 || inString.indexOf("All=OPEN") > 0)
        {
          Serial.println("\n" + Room + " is OPEN");
          digitalWrite(pin[i], HIGH);
          value[i] = "CLOSE";
        }
        else if (inString.indexOf(Room + "=CLOSE") > 0 || inString.indexOf("All=CLOSE") > 0)
        {
          Serial.println("\n" + Room + " is CLOSE");
          digitalWrite(pin[i], LOW);
          value[i] = "OPEN";
        }

        client.println("
" + Room + "     <input type='submit' name=" + Room + " value=" + value[i] + " style='height: 50px; width:100px;' />

");
      }

      client.println("

All <input type='submit' name='All' value='OPEN' style='height: 50px; width:100px;' />    <input type='submit' name='All' value='CLOSE' style='height: 50px; width:100px;' />");
      client.println("</form>");

      for (i = 1; i < (numOfRooms + 1); i++)
      {
        if (value[i] == "ON")
        {
          i = i + 310;
          client.println("

Room " + String(i + 310) + " is OPEN
");
        }
        else if (value[i] == "OFF")
        {
          client.println("

Room " + String(i + 310) + " is CLOSE");
        }
      }
      client.println("
");
      client.println("
");
      client.println("");
      break;
    }

    if (c == '\n')
    {
      // we're starting a new line
      current_line_is_blank = true;
    }
    else if (c != '\r')
    {
      // we've gotten a character on the current line
      current_line_is_blank = false;
    }
  }
}

    // give the web browser time to receive the data
    delay(1);
    inString = "";
    client.stop();
    }
}

MOBILE means code for Arduino-Android
WEB means the code for Web Server

You can't.

The code has both libraries trying to run on the same port which is not allowed (in fact you couldn't even do that on a computer). You could try setting one to one port and the other to another port, but that might not work because...
These libraries most likely are both expecting to be the only code accessing the hardware and they will step over each other and cause problems. Sharing hardware between different pieces of code is an advanced programming topic not suited for beginners and would involve rewriting significant portions of these libraries.

The best course of action is to either re-implement your app functionality to use the UIPEthernet Library, or re-implement the webpage using the EtherShield library. You should be able to do this because your app interface is supplying parameters (e.g the "?cmd=" part) and the webpage is not. You should be able to set it up so that if it has "?cmd=" in the request, it should perform the command, otherwise it should return the webpage.


text:
Why are some of my GSM modules not taking commands?
I posted a couple weeks ago about having a GSM error. I moved past it and the code seemed to be working on my GSM module (I think a SIMCOM). But then I needed to create some more systems and out of a total of 8 GSM modules, my code and setup only work on two of them - despite the fact that they should be identical and from the same supplier.
The following code (thanks to this genius post) works without error to send and receive SMS on two of the boards:
#include <SoftwareSerial.h>
char inchar; // Will hold the incoming character from the GSM shield
SoftwareSerial SIM900 = SoftwareSerial(2,3);

void setup() {
  Serial.begin(19200);
  initializeGSM();
}

void initializeGSM() {
  SIM900.begin(19200);
  Serial.println("Turned on");
  SIM900.print("ATEO\r");
  Response();
  SIM900.print("AT\r");
  delay(1000);
  Response();
  SIM900.println("AT+CMGF=1\r");  // set SMS mode to text
  Response();
  delay(1000);
  SIM900.println("AT+CNMI=1,2,0,0,0\r");
  delay(100);
  Response();
  delay(5000);  // give time to log on to network.
  Serial.println("Ready...");
}

void Response() {
  int count = 0;
  delay(1000);
  Serial.println(SIM900.available());
  while(1) {
    if(SIM900.available()) {
      char data =SIM900.read();
      if(data == 'K'){Serial.println("OK");break;}
      if(data == 'R'){Serial.println("GSM Not Working");break;}
    }
    count++;
    if(count == 100){Serial.println("GSM not Found");break;}
  }
}

void loop() {
  RecSMS();
  delay(2000);
}

void RecSMS(){...}

So again, the above code works to set up the module on 2 modules. On the other 6, it simply hangs during the Response() call. SIM900.available() returns 0 and then says "GSM Not Found." So I tried to initialize the TX pin during setup as:
digitalWrite(2, LOW);

Which then gives me a promising SIM900.available() value of about 63, which corresponds to what a confirmation would be. However, when I print the "data" variable containing the byte read off the GSM module/SIM card, I get a couple bits of garbage like the following output:

Has anyone experienced this problem and knows a way to properly initialize the GSM module?

GSM module running at a different baud rate?

Is there a way to determine which baud rate it's running at? Or reset it?

Experiment by trying different common "standard" baud rates - if you find that a different one works then that's your problem. If not, then it's not.

I tried all of the baud rates from 2400-115200 and they all produced similar outputs. I also tried changing the jumper pin on the GSM module to change the TX/RX pins but that did not work either.

In your initialize-func after sending the AT+CMGF=1 you have the Response() before the delay(). I wonder if that matters.

It may well be worth to actually print the error codes instead of only check if there is an error. You can even try manually sending AT commands, to verify that they work. When I worked with GSM units, I found that they are extremely picky on the amount of power they require in peaks. Be sure your supply is capable and add a capacitor that can take a very short 2A burst.

I am owner of this blog whose link you shared, so first of all, I am felling happy that you got something out of it. Now secondly, this code you got from my post is incomplete.
You need to buy that one in order to get the complete code. The code I designed is using AT commands but the above code which you have mixed with your own code is using the Arduino library that's why it's not giving the correct results.
So, either use the complete code from my website or use the Arduino library code only because it has the commands for checking the response, you don't need to use my code to get the response.

source: Stack Exchange

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

authors: المهندس اليماني

sort: votes


text:
Serial does not work when LiquidCrystal library is used
I have been struggling with a LCD for 6 hours straight - I've had many problems including random characters showing up, and this time (not quite sure what changed, I tried so many things) as soon as I instantiate a LiquidCrystal object the Arduino stops sending on the Serial port. On the following code, commenting the instantiation of lcd makes "Starting" and "Printing" appear in the serial terminal - otherwise nothing is displayed. Either way, the LCD is desperately blank (black spaces on the entire first line, and I tuned the contrast when random characters were displayed).

// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
//RS EN D4 D5 D6 D7
//LiquidCrystal lcd(2, 3, 4, 5, 9, A5);
//RW to GND, VSS to GND, VCC to 5V, V0 to wiper of 5V-to-GND 10k potentiometer

void setup() {
  Serial.begin(9600);
  Serial.println("Starting");
  //lcd.begin(16, 2);
}

void loop() {
  //lcd.setCursor(0, 1);
  //lcd.print(millis() / 1000);
  Serial.println("Printing");
}

I'm using this Arduino Pro Mini, and this LCD. Note that on the Arduino, pins 10 11 12 and 13 are used for a SD (which works), and 6 7 8 are used for a RS232 driver (which is disabled).
Honestly I'm sending a message in a bottle, I'm out of ideas...
The wiring is as explained in the code, I checked it 5 times and it is matching. There is a 10k pot on GND-VO-5V of the LCD, and I haven't wired the backlight.
Edit1: With the LCD active (all lines uncommented) I probed all LCD pins with a 'scope and when it is triggered in Normal, I can see that they all have a pulse every time the LCD is updated (I added a delay in the loop to make it more obvious). HOWEVER pins 9 and A5 take much longer than the others to get back to a high state, around 3 microseconds. Why? It might explain why the LCD doesn't work, but I don't see how it can explain the apparent freeze.
Edit2: Okay, I desoldered pins 9 and A5 and placed the wires on pins A2 A3 instead. The square waves are all square now, and the Serial works - no idea why. And back to square 1, as the LCD prints random characters now...

Do you get the same behavior when the SD and RS232 hardware is detached from the Pro Mini?  Also, if you change lcd.print(millis() / 1000) to lcd.print(millis() & 1024 ? "ABCDEFGH" : "IJKLMNOP"); delay(1024); what does it display?

Jwpat7 that line was the issue for the garbage characters that I ended up having after solving this particular issue, well done. For this specific issue, apparently pins 9 and A5 weren't fast enough, no idea why.

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


text:
Passing the input from one pin to another as output without polling?
I am trying to pass the input from one pin to another pin as output. Effectively I want to create a blind passthrough. The end goal is to connect two Arduinos and a series of test points together like the diagram below. I want Arduino B to shuffle which test points are connected to which pins on Arduino A on startup.
+-----------+       +-----------+     +-------------+
|           |       |           |     |             |
| Arduino A <-------> Arduino B <-----> Test Points |
|           |       |           |     |             |
+-----------+       +-----------+     +-------------+

I figure one way to do this is to poll the input pins in the loop() and then change the output pins accordingly but I would prefer if the voltage changes just passed right through without it affecting timing.
Update:
For some clarification:

All signaling is digital
I'm looking to "route" around 10-12 test points to Arduino A ideally but 6 at a minimum

How many test points are you planning to test at once? And, for a "test" do you need to measure both an input and an output? Eg. apply 3V to pin A0 and see what happens on pin D3? Something like that? How many simultaneously?

In addition to Nick's questions, are you working with digital signals or analog? If analog, do you have any particular bandwidth requirements?

The plan is to use around 10-12 test points with up to 6-8 active at once. I would like to be able to measure input and output as well. Digital signals.

If this is all digital, what is a "test point" exactly? Why can't Arduino B just generate the test signals, and just connect the pins directly?

The project is to create a puzzle for people to practice some things on. I want the person working on the puzzle to have around a dozen test points available to them to use to communicate to Arduino A. Ideally which test points are the "right" (active) ones will change dynamically each time they turn on the boards.

You could use an analog multiplexer such as the 74HC4051 (8 channels) or the 74HC4067 (16 channels) like this:

Arduino B could alter the multiplex selector (A/B/C) pins to route the signal from the test points to a specific pin on Arduino A. If you are wanting to see the result of the signal on a different pin then a second multiplexer would be required (ie. one to send data to a pin, the second to see the result on a different pin).
I have a post about the 74HC4051 multiplexer / demultiplexer which gives more details about using it.
When I tested it I found only about a 5 ns delay in timing:

Ignacio's answer about a crossbar switch sounds like a more elaborate form of multiplexer. Personally I haven't used one of them.

A multipliexer/demultiplexer is a many-to-one/one-to-many switch. A matrix switcher is a many-to-many switch, which fits the scenario OP described. You could replicate a matrix by just having an array of multiplexers, but depending on how many inputs and outputs he is dealing with there will probably be more address lines to drive than will be practical from an Arduino. I guess you could get around that with shift registers, but then it becomes a question of whether it is easier to have a complex mesh of 74xx series chips, or to just buy a matrix IC.

Agreed, but I can't find many matrix switches in my searches. Do you have a part number that could be suitable?

http://mouser.com/Semiconductors/Communication-Networking-ICs/Analog-Digital-Crosspoint-ICs/

You did better than me. :) Anyway, most of them seem to need SMD soldering skills - and the ones with a reasonable number of points (eg. 16 x 16) are quite expensive (eg. $70 or $180). We probably need more information from the OP as to how many s/he needs to switch. I can't see a 2x2 matrix being particularly useful here.

Analog Devices has a bunch: http://www.analog.com/en/parametricsearch/10630#/p4577=No Usually you can get them on an evaluation board to help breakout the pins for prototyping, but sometimes the price of the boards can be expensive. That is one advantage to 74 series, they are cheap and breadboard friendly.

You could roll your own with a CPLD. Needs additional skills and tools though.

I need to connect ~10-12 test points to pins ideally or 6 at a minimum. All digital. Could this be better accomplished with an FPGA acting as the router and sitting between the test points and the Arduino?

No Arduino is capable of doing this. You need to be looking at a crossbar/crosspoint/matrix switch IC instead.

You can reduce latency by using interrupts to detect input changes instead of polling in loop(), if you're dead set on using an Arduino instead of adding switching hardware (as suggested in other answers).
See attachInterrupt() for details, and beware that different Arduino models differ greatly in how many pins support interrupts.
Alternately, you can speed up the polling approach by using direct port access (e.g., PORTB and PORTD registers) instead of the simpler Arduino read and write functions.  This will bypass some wrapper code and also let you manipulate multiple pins in parallel.

I think some of the hardware people have mentioned in the other answers is more what I need, but interrupts and direct port access will be very helpful for another part of the project. Thanks!

Because this is digital I would like to add a third option in addition to Ignacio's and Nick's great suggestions. Use a logic device such as an FPGA or CPLD. This will require some extra knowledge and set up to get it working, but it is well suited for the functionality you are looking for.

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


text:
Why does my LCD display random characters?
I've been struggling with my LCD for hours, and after solving more different issues than I can remember, I'm out of ideas for this one.
My LCD is showing random characters, see the picture below (the last character blinks, some characters change and over time there are slowly more and more characters). I'm starting to wonder if the LCD I chose has a driver compatible with the LiquidCrystal library, what do you think? If so what can I do to avoid buying another one?

Here is the code:
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
//RS EN D4 D5 D6 D7
LiquidCrystal lcd(2, 3, 4, 5, A2, A3);
//RW to GND, VSS to GND, VCC to 5V, V0 to wiper of 5V-to-GND 10k potentiometer

void setup() {
  Serial.begin(9600);
  Serial.println("Starting");
  lcd.begin(16, 2);
}

void loop() {
  lcd.setCursor(0, 1);
  lcd.print(millis() / 1000);
  Serial.println("Printing");
  delay(1000);
}

I'm using this Arduino and this LCD. Note that I'm using pins 10,11,12,13 for a SD (which works) and 6 7 8 for a MAX232 (which is disabled).
Any ideas?

Did you set the library to 4 pin mode? And have you tried sending some regular text, like "hello" instead of the output of a function

I'm not sure whether the LiquidCrystal library supports using the "analog pins" A2 A3 that way. Can you test your LCD using the standard pin configuration (obviously not using the SD or any other interfering devices). The LCD itself looks like a common HD44780 type, so pin configuration is more likely the cause than some exotic device driver.

The LiquidCrystal library includes known-good example code, that's part of what Arduino is for. Go ahead and use that as a diagnostic to check the LCD works, before attempting the non-standard connection.

Thanks. The above code is an example on the official website, I've just added the delay() so it should work... I've checked and A2 and A3 are sending digital signals just like the other pins so it looks fine. Passerby, isn't it sufficient to call the constructor with 6 arguments to select 4 pin mode?

A lot of people having this issue had EMC issues - The 5V is supplied by a boost converter from a battery but I've observed the supply rail and it's a solid 5V...

Have you made sure you don't have any floating input pins?

The pins not labelled on the picture are left unconnected - should I ground them? All examples I've seen left them unconnected

Stupid question but the picture looks like you just pushed the wires in the holes. You did solder them, didn't you?

Please don't migrate this post to Arduino SE for now - too late!

check 2 and 3 :) again your soldiering is bad, well from what I know if there is "?" this sign you must check your connections

The connections are through hole, it doesn't matter which layer I solder them on, and they are soldered on the bottom. I've checked and the top pads are connected.

It could be because "millis()/1000" generates a "number", and not the "string" (or "char"). Try to add ",DEC" in your lcd.print(), something like "millis()/1000,DEC" to convert it to "decimal". Generally, it depends on the library, how they implement this function.
Good luck,
Mike

You and Passerby were right about this, I ruled it out because it was an official example but it is obvious that their example was wrong. I changed that to "ABC...Z" and then "123...90" and both worked flawlessly. Thanks!


text:
Arduino: Record value of the encoder only once at the instant the PS2 joystick reads 128 (when at rest)
I'm working on a project where I need my arduino to detect the value of encoder at the instant the reading of the joystick change to 128.  When the joystick is at rest, the reading is 128 which also means, my robot will hold its position/brake. Values above or below 128 correspond to the motor moving forward or backward.
I actually want to record the encoder value exactly at the first instant my arduino reads 128, so that I can apply PID position control so that my robot can brake or hold its position against gravity. The first instant when the joystick reads 128, that is the encoder value that I'd like to set as the Setpoint.
Here's some explanations for implementing PID in Arduino.
http://playground.arduino.cc/Code/PIDLibraryConstructor
For instance the joystick readings go from 140, 137, 131, [128], 128, 128, 133, 139, 131, [128], 128 and at the same time, the encoder gives out corresponding values. I need the encoder values at the Joystick value of 128 in the square bracket, [] in the example above.
If I use the code below, it will just run the statements in {} whenever it sees 128, which is not what I want. FYI, the motor sometimes tend to backdrive, and this gives different encoder value also at 128. What I only need is the first encoder value at the first reading of 128 whenever I encounter it.
void loop()
{

  int pwmSpeed;

  int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

  Input = encoder0Pos;

  if (Y_axis == 128)
  {

    Setpoint = encoder0Pos;
    myPID.Compute();
    analogWrite(pwm, Output);

  }

  else if (Y_axis > 128)
  {
    pwmSpeed = Y_axis;
    digitalWrite(dir,HIGH);           // set DIR pin HIGH or LOW
    analogWrite(pwm, pwmSpeed);            //analogWrite(pin, value)
  }
  else
  {
    pwmSpeed = abs(Y_axis-255);
    digitalWrite(dir, LOW);
    analogWrite(pwm, pwmSpeed);

  }

}

Thanks.
//New edited code is shown below:
What do you think of the code? Did I do it correctly? I will test it once I get back to the lab.
If 128 is detected, encoder value is stored in Setpoint and then Pid.compute() is executed for as long as 128 is detected. For this duration, Pid.compute() will compute the error = Setpoint - Input and use Pid formula to calculate the Output that can be found in the analogWrite(pwm, Output). Motor will work to maintain its position at Setpoint.
However if other than 128 is encountered, it will just execute the 'else if' and 'else' statement to move the robot forward or backward.
global g_detect128 = false;

void setup()
    {
//any code here
    }

void loop()
{

  int pwmSpeed;
  int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

  Input = encoder0Pos;

 if (!g_detect128 && Y_axis == 128)
    {
    Setpoint = encoder0Pos;
    g_detect128 = true;
    }

  if (Y_axis == 128)
  {

    myPID.Compute();
    analogWrite(pwm, Output);

  }

  else if (Y_axis > 128)
  {
    pwmSpeed = Y_axis;
    digitalWrite(dir,HIGH);           // set DIR pin HIGH or LOW
    analogWrite(pwm, pwmSpeed);            //analogWrite(pin, value)
  }
  else
  {
    pwmSpeed = abs(Y_axis-255);
    digitalWrite(dir, LOW);
    analogWrite(pwm, pwmSpeed);

  }

 if(Y_axis != 128)
    {
    g_detect128 = false;
    }

}

Why was this question migrated here? It seems like a pure programming problem. It should be sent to StackOverflow where I feel confident they would know how to respond to it.

@NickGammon Also, it already had a (correct) answer. Why bounce it all over Stack Exchange?

I apologize if this is sent to the wrong section. If I have further question, should I proceed here or should I post at stackoverflow?

@goddar If it's pure programming, StackOverflow. If it's something particular to do with Arduino (hardware or software), post here. If it's general electronics/circuit related, then post on EE.

If you only want to catch this event once - when it first hits 128, you just need a global variable to flag when you've seen it:
boolean g_bSeen128 = false;

void setup()
{
    // ... whatever
}

void loop()
{
    // ... your existing code

    // catch first time we see 128
    if (!g_bSeen128 && Y_axis == 128)
    {
        // ... do whatever you need here. e.g.
        Setpoint = encoder0Pos;
        myPID.Compute();
        analogWrite(pwm, Output);

        // stop the event being caught next time
        g_bSeen128 = true;
    }

    // from comments below - to just ignore consecutive 128's, add this:
    if (Y_axis != 128) g_bSeen128 = false;

    // ... your existing code

}

If you only want to do something if the input changes, no matter what it is, you can keep track of the last input:
int g_nLastInput = -1;

void setup()
{
    // ... whatever
}

void loop()
{
    // get input
    int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

    // if input has changed ...
    if (Y_axis != g_nLastInput)
    {
        // ... save latest input
        g_nLastInput = Y_axis;

        // now process the change, e.g.
        if (Y_axis == 128)
        {
            // ... do something special for 128
        }
        else
        {
            // ... do something else for other inputs
        }
    }
}

I'm not sure what you're trying to do with the PWM when you get inputs either side of 128, it seems to me that you might want to go in one direction if the input is less than 128 and go in the other direction if it's greater than 128. In either case, the magnitude of your PWM speed should just reflect how far you are from 128 in either direction. So subtracting 128 from your input will give a delta that is +/- 128 and we can scale its absolute value to 0..255 for the PWM setting.
If that's correct, an alternative way of coding your original logic might be like this:
void loop()
{
    // get input
    int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

    Input = encoder0Pos;

    // if input has changed ...
    if (Y_axis != g_nLastInput)
    {
        // ... save latest input
        g_nLastInput = Y_axis;

        // now process the change
        int nDelta = Y_axis - 128;

        if (nDelta == 0)
        {
            // i.e. Y_axis is 128
            Setpoint = encoder0Pos;
            myPID.Compute();
            analogWrite(pwm, Output);
        }
        else
        {
            // choose direction
            digitalWrite(dir, (nDelta > 0) ? HIGH : LOW);

            // set PWM speed scaled to 0..255
            analogWrite(pwm, abs(nDelta) * 2);
        }
    }
}

Thanks Roger. That answers my question above. I think the way I program it is wrong.  What I really want is to record the encoder value as the Setpoint whenever it encounter the first value of 128 at any time during the operation. Then I want to feed that Setpoint (intended stop position) and the Input(current encoder position) to the Pid.compute() so that it will hold its position at the Setpoint. For example, if the readings are 130, [128], 128, 128, 140, 132, [128], 128. What if initially the joystick moves the motor, brake, then move again and then brake?

@goddar Ok, then after the if that I showed you, you just need to add if (Y-axis != 128) g_bSeen128 = false; So that will ignore consecutive 128's but will pick up new instances. I've updated the answer.

goddar, what should happen in that 130, [128], 128, 128, 140, 132, [128], 128 sequence?  Should the encoder be read twice, after 130 and after 132?  Or just once, after 130?

In the example, I would like to read the encoder value whenever arduino receive 128. I highlighted the ones I need to read with the square bracket, [ ] . So it will read twice in that example, first reading is at 1[28] after 130 and 2nd reading is after 132. What is your concern jwpat7? May I know?

Hi Roger or anyone else, how about other methods to achieve the what I want in my question above? This is for my knowledge since we're already discussing this topic.

@goddar I've just expanded my answer so you can see how to filter out all duplicate readings, so you only respond to a change of input. If you then want to do something different for a particular input, say 128, you can just test for that value inside the outer if condition.

Hi Roger, based on your latest code, thats indeed a better way to program it. Ive never thought of that. The goal is for my robot to follow my joystick and its signal will determine how fast my robot moves uphill or downhill. Then whenever I release my joystick, it will outputs value of 128. All the while when my arduino reads 128, I want it to hold its position/brake. This is when arduino will continuously execute the pid.compute (). This will go on until I move my joystick again to move the robot again. It seems that the code will execute the pid.compute () only when it encounter the first 1

Continued from above...it seems that the code will execute pid.compute () only when it encounters the first 128. Is there a way for it to execute the pid.compute () the whole duration when arduino sees 128?

Roger, I typed out the new code above based on your suggestion earlier. The description on how I intend it to work is stated above the new code. Could you please have a look? I'd like to hear your opinion whether it will work according to my description.


text:
Issue while connecting ESP8266 with Arduino Mega. It always says “Module have no response.”
I am having Issue while connecting ESP8266 with Arduino Mega. It always says "Module have no response."
Please check and correct me if I am wrong anywhere.
I am using below code and and wiring diagram is

My Code:
//#include <SoftwareSerial.h>
   //use mega Serial 2 for serial monitor; Serial 1 on pins 19 (RX) and 18 (TX);// Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX).
   #define SSID "SopraSteria"
   #define PASS "1234567890"
   #define DST_IP "220.181.111.85" //baidu.com
   //SoftwareSerial dbgSerial(10, 11); // RX, TX
   void setup()
   {
     // Open serial communications and wait for port to open:
     //serial 2 is to esp8266
     Serial2.begin(115200);//9600 (mine), 57600, 115200
     Serial2.setTimeout(2000);

     //serial 0 is to usb
     Serial.begin(115200);

     while(!Serial);
     while(!Serial2);

     //dbgSerial.begin(9600); //can't be faster than 19200 for softserial
     //dbgSerial.println("ESP8266 Demo");
     Serial.println("ESP8266 Demo on Mega2560");

    while(Serial2.available()>0)
    Serial2.read();

     delay(1000);
       //test if the module is ready
     Serial2.println("AT+RST");
     //delay(1000);
     //delay(1000);
     Serial.println("Resetting module");
     Serial2.flush();
     //Serial.println(Serial2.read());
     //if(Serial2.find("ready"))
     if(Serial2.find("Ready")||Serial2.find("ready"))
     {
       //dbgSerial.println("Module is ready");
       Serial.println("Module is ready");
     }
     else
     {
       //dbgSerial.println("Module have no response.");
       Serial.println("Module have no response.");
       //while(1);
     }
     delay(1000);
     //connect to the wifi
     boolean connected=false;
     for(int i=0;i<5;i++)
     {
       if(connectWiFi())
       {
         connected = true;
         break;
       }
     }
     if (!connected){
      //while(1);
      Serial.println("Not Connected.");
     }
     delay(1000);
     //print the ip addr

   Serial2.println("AT+CIFSR");
     Serial.println("ip address:");
     while (Serial2.available())
     Serial.write(Serial2.read());

     //set the single connection mode
     Serial2.println("AT+CIPMUX=0");
   }
   void loop()
   {
    //connectWiFi();
     String cmd = "AT+CIPSTART=\"TCP\",\"";
     cmd += DST_IP;
     cmd += "\",80";
     Serial2.println(cmd);
     Serial.println(cmd);
     Serial.println(cmd);
     if(Serial2.find("Error")) return;
     cmd = "GET / HTTP/1.0\r\n\r\n";
     Serial2.print("AT+CIPSEND=");
     Serial2.println(cmd.length());
     if(Serial2.find(">"))
     {
       //dbgSerial.print(">");
       Serial.print(">");
       }else
       {
         Serial2.println("AT+CIPCLOSE");
         //dbgSerial.println("connect timeout");
         Serial.println("connect timeout");
         delay(1000);
         return;
       }
       Serial2.print(cmd);
       delay(2000);
       //Serial.find("+IPD");
       while (Serial2.available())
       {
         char c = Serial2.read();
         //dbgSerial.write(c);
         Serial.write(c);
         //if(c=='\r') dbgSerial.print('\n');
         if(c=='\r') Serial.print('\n');
       }
       //dbgSerial.println("====");
       Serial.println("====");
       delay(1000);
     }
     boolean connectWiFi()
     {
       Serial2.println("AT+CWMODE=1");
       String cmd="AT+CWJAP=\"";
       cmd+=SSID;
       cmd+="\",\"";
       cmd+=PASS;
       cmd+="\"";
       //dbgSerial.println(cmd);
       Serial2.println(cmd);
       Serial.println(cmd);
       delay(2000);
       if(Serial2.find("OK"))
       {
         //dbgSerial.println("OK, Connected to WiFi.");
         Serial.println("OK, Connected to WiFi.");
         return true;
         }else
         {
           //dbgSerial.println("Can not connect to the WiFi.");
           Serial.println("Can not connect to the WiFi.");
           return false;
         }
       }

Well, you seem to be wired into Serial1 yet you're using Serial2 to communicate...

I am using Serial2 with pin 16, 17. this diagram is my reference but using serial2

And are you using the same ESP module? There's lots of different ones.  The one pictured there is the ESP-01

Yes Majenko I am using the same one.

Have you tried different baud rates? Different versions of the AT firmware have different baud rates set as default. You need to make sure you match them up.

if(Serial2.find("Ready")||Serial2.find("ready")) cannot match the second possibility until is has either matched the first, or the first has timed out, because this method consumes characters while seeking a match.  It might be better to grab whole lines and then test them, though you could also "cheat" by doing a find for "eady" which would match either.

Your transmitter and receiver pins need to be crossed, rx->tx and tx->rx. As a mnemonic, the two ends of the antenna point to the board edge with the receiver pin and it is that pin that needs the voltage divider. While you're at it, it would be a good idea to tie the RST pin high, as well as the CH_PD. I use one 10K pullup for both.
Recent versions of these boards are shipped with their baud rates set to 115200. Since you're using a hardware UART on the Mega board, you can send/receive to it at that rate.
Note to readers using a software UART (SoftwareSerial): First thing, change the board's baud rate to 9600 and communicate with it at that rate. You can use SoftwareSerial to make the change as it sends at 115200 reasonably reliably, but its receive function can't keep up at that rate).
You can confirm your connections and baud rate with:
EspSerial.println("AT");
You should receive `OK' in reply.

I took your code as a starting point and got it to work with some small modifications. I am providing my version below for your review. I had to add a bunch of delays. I am also communicating with the ESP8266 at 19200 baud.
I have not optimized the timing yet but I was able to run this code for 24 hours straight with no issues. I am using Pins 6 and 7 on the Arduino for COMM to the ESP8266.
#include <SoftwareSerial.h>
#define SSID "YOURSSID"
#define PASS "YOURPW"
#define DST_IP "220.181.111.85"

SoftwareSerial Serial2(6, 7); // RX, TX

void setup() {

// Open serial communications w ESP8266
Serial2.begin(19200);
Serial2.setTimeout(5000);

// serial 0 is to usb
Serial.begin(115200);
while(!Serial);
while(!Serial2);

Serial.println("ESP8266 Demo on Mega2560");

while (Serial2.available() > 0)
Serial2.read();
delay(1000);
while (Serial2.available() > 0)
Serial2.read();

//test if the module is ready
Serial.println("RESETTING ESP8266 WIFI CHIP");
Serial2.write("AT+RST\r\n");
delay(2500);
while (Serial2.available() > 0)
Serial.write(Serial2.read());

delay(2500);
while (Serial2.available() > 0)
Serial.write(Serial2.read());
Serial.println("");

//  connect to the wifi
boolean connected=false;
for(int i=0;i<5;i++) {
if(connectWiFi())
{
connected = true;
break;
}
}

if (!connected){
Serial.println("Not Connected.");
}

Serial2.println("AT+CIFSR");
delay(2000);
while (Serial2.available())
Serial.write(Serial2.read());
delay(2000);
while (Serial2.available())
Serial.write(Serial2.read());

//  set the single connection mode
Serial2.println("AT+CIPMUX=0");
delay(2000);
while (Serial2.available())
Serial.write(Serial2.read());
delay(2000);
while (Serial2.available())
Serial.write(Serial2.read());
}

void loop() {

String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += DST_IP;
cmd += "\",80";
Serial2.println(cmd);
Serial.println(cmd);
delay(5000);

if(Serial2.find("Error")) return;

cmd="GET / HTTP/1.0\r\n\r\n";
Serial2.print("AT+CIPSEND=");
Serial2.println(cmd.length());
delay(2000);

if(Serial2.find(">"))      {
Serial.print(">");
}
else {
Serial2.println("AT+CIPCLOSE");
Serial.println("connect timeout");
delay(2000);
return;
}
Serial2.print(cmd);
delay(2500);

while (Serial2.available()) {
char c = Serial2.read();
Serial.write(c);;
if(c=='\r') Serial.print('\n');
delay(5);
}

Serial.println("");
Serial.println("====");
delay(2000);
}

boolean connectWiFi() {

String cmd;
int iIP;

iIP = 0;
Serial2.println("AT+CWMODE=1");
delay(5000);
while (Serial2.available())
Serial.write(Serial2.read());

cmd="AT+CWJAP=\"";
cmd+=SSID;
cmd+="\",\"";
cmd+=PASS;
cmd+="\"";

Serial2.println(cmd);

delay(2000);
Serial.println("Line 1");
while (Serial2.available() > 0)
Serial.write(Serial2.read());

delay(2000);
Serial.println("Line 2");
while (Serial2.available() > 0)
Serial.write(Serial2.read());
if (Serial2.find("OK")) {
Serial.println("WIFI OK was received!");
iIP = 1;
}

if( iIP == 1 ) {
Serial.println("OK, Connected to WiFi.");
return true;
}
else  {
Serial.println("Can not connect to the WiFi.");
return false;
}

}

As shown in the Fritzing diagram, you have connected the ESP8266 to the Mega's Serial1 pins (18 and 19), but in the program, you try to interact with Serial2 (pins 16 an 17). For this to work, your wiring and your program must match.

@ChrisStratton - I think that, prior to your edit, the answer was somewhat short and seemed more appropriate as a comment, hence my comment. Now, with the expanded and "explicit" edit, my comment is no longer valid. :-) well done for spotting it (as Majenko also did) and I shall give the answer a vote up

Good point, it's only repeating something already observed in comments long before.  Upvote removed.

@ChrisStratton - Also... it seems (after re-reading the reply to Majenko's comment) that the Fritzing diagram is not totally accurate, and that pins 16 and 17 are actually being used, rather than 18 and 19 as shown in the diagram: I am using Serial2 with pin 16, 17. this diagram is my reference but using Serial2. So... that renders this answer as being invalid. I shall attempt to remove my upvote as well.


text:
How to count the time until the next day of the week?
I wants to do in Arduino countdown that shows how many days, hours and minutes remaining to Friday 12:00.
In my program I used a function in php strtotime('next friday') which thus could calculate differential timestamp and show how much time is left until Friday 12:00.
Is there a function strtotime('next friday') in Arduino?
I have RTC which gives me just the current date and time, but does not show the current day of the week.
EDIT:
I have a solution
We have day of week. We multiplied by 86400.
We have an hour. We multiply by 3600.
We have a minute. We multiplied by 60.
Add everything.
Subtract this from 604800.
nextFriday  = 604800-((dayofweek * 86400)+(now.hour()*3600)+(now.minute()*60)+now.second());
Important, Friday is the number of the week "0". Friday = 0; Saturday = 1; etc...

Mosts RTCs have a dayOfWeek field.

In C/C++ it is strtotime("next friday") - note the double quotes. Single quotes do something quite different.

The key to working with time is to have a known "base" time to calculate everything relative to.  This is called the epoch.  Different systems use different epochs, and each has advantages and disadvantages.
I generally use the UNIX epoch in my programming (chiefly because I am a UNIX nut), which is the first of January, 1970 (01/01/1970).  This is year, month, day, hour, minute and second 0.
From that you can then calculate the number of seconds between the epoch and any other time you choose as long as it is later than the epoch.
To calculate the day of the week for any given date you first need to know the day of the week for the epoch (for UNIX that's a Thursday) then work out how many days there are between the epoch and the target time.
Calculating real times in terms of seconds can be somewhat tricky due to leap years and daylight savings, but there are plenty of algorithms in the public domain, and many RTC libraries include functions to convert to/from epoch times.
For instance, the Arduino Time Library has functions to calculate weekdays, and to convert to "time_t" format (seconds since epoch) which can be used to work out differences in times.  For instance, if you know that it's Tuesday and you want next Friday then you know that Friday is 3 days in the future - so you can get the current time in seconds from the epoch then add to that 3 days' worth of seconds (3 × 60 × 60 × 24) to that time to get the same time of day next Friday.

There are generic examples, e.g. Determination of the day of the week - Wikipedia.

In the C language expressions below, y, m and d are, respectively, integer variables representing the year (e.g., 1988), month (1-12) and day of the month (1-31).

        (d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7

Also see StackOverflow - C Program to find day of week given date.

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


text:
ACS712 inacurrate reading. Wild jumping
I'm trying to use my 30A ACS712 on my OSD (it has ATMEGA16L).
But it is very unstable, 0 amps goes from 450 to 445, but that isn't that bad, but when I put 10A of current through it jumps from 440 to 380.
I already searched on google and tried to add filter cap between acc and gnd, but it didn't help and acs712 and osd have different power supply than the load.
Any help is welcome.

Are you trying to sense AC or DC current? (yes, I know that's RAS Syndrome)

DC and I connected acs712 directly to atmega16l

This is not a simple chip to use.  These parts of the data sheet may help you understand what is happening.  It is internally an analog device and needs clean power.  I would highly recommend you download the Allegro data sheet, it has a lot of information that will help you.  Below is a short section of the data sheet, The first paragraph should give you a hint that the output voltage will be about 2.5V with a 5V unipolar power supply.
"Quiescent output voltage (VIOUT(Q)). The output of the device
when the primary current is zero. For a unipolar supply voltage,
it nominally remains at VCC⁄ 2. Thus, VCC = 5 V translates into
VIOUT(Q) = 2.5 V. Variation in VIOUT(Q) can be attributed to the
resolution of the Allegro linear IC quiescent voltage trim and
thermal drift.
Electrical offset voltage (VOE). The deviation of the device output
from its ideal quiescent value of VCC / 2 due to nonmagnetic
causes. To convert this voltage to amperes, divide by the device
sensitivity, Sens.
Accuracy (ETOT). The accuracy represents the maximum deviation
of the actual output from its ideal value. This is also known
as the total output error. The accuracy is illustrated graphically in
the output voltage versus current chart at right."
I realize this does not answer your question but it does give you a good starting point to resolve your problem.  Hopefully you or a buddy has some analog experience, that will help a lot.  Oh Yes clean power supplies are imperative for this to work.


text:
Encoding an entire Byte for File Reading
I'm using an Arduino Yun to read from a data file, which will then populate a data structure. The file.read() function "returns: The next byte (or character), or -1 if none is available."
This functionality is identical to the SD.read() function in the SD card library.
The data file will never have any value that exceeds 1 byte with all numbers in the range 0-255. If I print these numbers as a long string in the data file, each character is read as a byte. So I need to call file.read() 3 times to read in a single 0-255 value. And then do some additional processing to construct the final 8-bit value for storing.
I could reduce this to 2 calls by printing the Hex code in the data file, but this isn't much of an improvement.
Is there a way to encode a full byte in a single character?
Effectively , is there a particular way I can format my data file so that I can read in an 8-bit unsigned value in a single call to file.read()?

"Is there a way to encode a full byte in a single character?" I have no idea what you're asking here. Characters (in single-byte encodings) normally fit a byte regardless.

You need to save the values into a binary file, instead of converting the values to a human readable string, and saving that string.

There's two parts to what you want to do, writing the file in the right form, and reading that format file.
The format of file is known as raw binary. Every byte in the file can store a separate value between 0 and 255, or between -128 and 127, dependin on how you interpret the data.  At the end of the day, every byte in a file is just a collection of 8 bits yielding 2^8 = 256 combinations. What those combinations actually mean is more of a human thing than a machine thing.
We, as humans, have decided upon three main representations of those bytes: unsigned numbers from 0 to 255, signed numbers from -128 to 127 (lookup two's complement) and finally ASCII characters.
ASCII characters are more of a lookup table placed over one of the other two representations. Some systems use unsigned bytes and some signed bytes for the basis of that lookup tabe.
Writing text into the file results in looking up the corresponding byte values for each character in that text and placing those values in the file. When you read the file the reverse is done - the byte values are read and you look them up in the ASCII table to find the corresponding letters.
To store just numbers between 0 and 255 it is far more efficient to bypass that ASCII table and store the values directly as bytes. How you do that is entirely dependent on what language you are writing your software in. Since you haven't mentioned what that language is I can't advise you on that front' only give some examples in languages I know.
Such as in C you would store your data in an array of unsigned char or uint8_t. You then use the write() function to write raw data to the file.
In Perl you might use the pack() function to store your values as bytes in a string then write that string to a file.
When reading the data you are presented with a raw value. That may be given to you as a signed or an unsigned value depending on the underlying system. I don't know what the yun is off hand. Converting from whatever is handed to you by thr file.read() function to what you expect it to be though is a very simple matter, and is called casting.
int in = file.read();
uint8_t bval = (uint8_t)in;

The bit in brackets is the cast which converts the value in the integer in into a uint8_t (Unsigned INTeger 8-bit Type) which corresponds to whatever you wrote as an unsigned char or uint8_t at the other end.

This is a fragment (untested) of how you can do it:
char datafile[512];
int ch;
int index = 0;

while ((ch = file.read()) != -1) {
  datafile[i] = (char)ch;
  if (++i == 512)
    break;
}

I was having trouble with char as the standard ASCII encoding does not handle numbers greater than 127, resulting in errors when printing.


text:
Uno as a composite USB HID keyboard
I'm looking to create a USB device that would  be basically a HID keyboard. I am able to do that with Uno. I flash new firmware with a HID keyboard descriptor and on the arduino side I loop and check for button presses. Based on butotn presses I send the report.
What I would like to add to this is option to send some data from a PC and based on that data do something (like turn an LED on.)
Here is an example:
loop() {
  check_and_send_buttons();
  uint8_t inputByte = get_input(); //new
  handle_input(inputByte); //new
}

I'm on Linux and I tried sending some data via hidrawX but that did not work out.
Any ideas?
I'm willing to also write new device driver for Linux if needed.

On UNO R3 the HID protocol is handled by the secondary AVR present on the board. Which is the one talking to the PC. So what you should modify is the code implementing the USB protocol on the secondary AVR.
The main (328p) AVR interacts with it through the serial port.
You do not need to alter the Linux driver, since it already supports the driving of the usual LEDs (CAPS, Num Lock, Scroll Lock), if these are enough for you.
So, to recap:
1) enhance the HID implementation to understand LED status commands coming from the PC
2) report such changes over serial
3) on the primary AVR, monitor for such messages coming over serial port from the secondary AVR and use them to drive the LEDs.


text:
Verify RGB Led Cube equipment
I'm preparing this kit on eBay to create the following instructable - http://www.instructables.com/id/4x4x4-RGB-LED-Cube/
But I have doubts about 0.1uF and 22pF capacitors since the once on eBay are 50v. Also MOSFETs - instructable uses IRF9531 but the ones I found on eBay are IRF9540N.
Is the equipment I added on eBay compatible with instructable?

Capacitor ratings don't really matter in your case, as you are using only 5 volt. Only their values (F) do.
Though the crystal you selected has an indication it needs 20pF load capacitors, not 22pF. 22pF is probably still fine. (Also note the ±20% accuracy, so between 17.6 and 26.4pF)
The IRF9531 and IRF9540N have the same pinout. They are also pretty similar in specs. The IRF9540N is slightly better even.
Note that the ATMega328p doesn't have the bootloader pre-installed. It's not that hard to do yourself though.
The EEPROM you selected is an SMD version. Kind of hard to work with if you are still a beginner. Better use a DIP version instead (that one is a bit more expensive, but 4 times the size)
I'd suggest you add an USB to Serials Adapter to the list, so you don't need the Arduino Uno every time you want to reprogram it, and use the Uno for something more useful.

Thank you very much for the answer, everything is clear now.

For a crystal with 20pF load capacitance you need 40pF capacitors.
The formula used is:

Cx1 = Cx2 = 2(CL - Cpara)

CL is 20pF and Cpara is the parasitic capacitance of the circuitry involved. Under most amateur circumstances that can be ignored.

Possibly that's the reason he uses 22pF capacitor with 20pF crystal, leaving 10% for parasytic capacitance


text:
Can both the 3.3V and 5V pins on the Arduino be used at once for power?
I'm supplying power to Arduino via PC USB.

Yes.
Here's a block diagram of how the Arduino power is arranged:

As you can see the USB power is fed through a FET (P-channel MOSFET) to isolate it when there is external power applied (as decided by the comparator COMP).  External power is fed through a 5V regulator and is fed to the same point as the USB power.  Thus you get the same 5V at the same point regardless of if you have USB or Barrel Jack power.  From there the 5V (wherever it comes from) is fed into a 3.3V regulator.  The 5V pin on the Arduino is connected directly to the 5V point where the USB and the 5V regulated input are connected. The 3.3V pin is connected directly to the output of the 3.3V regulator.
So no matter what input power arrangement you use - barrel jack, USB power, battery connected to the V IN pin (not shown, but connects to the barrel jack), or regulated 5V into the 5V pin, you get access to the same 5V and 3.3V power on the 5V and 3.3V power pins.


text:
ESP8266 failure to connect to router
I'm trying to get a ESP8266 board with 2x4 pins to work. I'm connecting it to an Olimexino 32u4 (Leonardo-compatible), configured to use 3.3V. This simple snippet I use to transfer everything to the PC (CH_PD is connected to D8, /RST to D9):
void setup() {
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  delay(2000);
  // initialize both serial ports:
  Serial.begin(9600);
  Serial1.begin(115200);
  delay(10000);
  digitalWrite(9, HIGH);
  digitalWrite(8, HIGH);
}

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

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

When launching, I see following output:
<"random" bytes>
Ai-Thinker Technology Co. Ltd.

invalid

Performing a reset shows more:
AT+RST

OK

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 1396, room 16
tail 4
chksum 0x89
load 0x3ffe8000, len 776, room 4
tail 4
chksum 0xe8
load 0x3ffe8308, len 540, room 4
tail 8
chksum 0xc0
csum 0xc0

2nd boot version : 1.4(b1)
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

ŒÂÕ�MEM CHECK FAIL!!!
äsl�‚rô
Ai-Thinker Technology Co. Ltd.

invalid

The mode is set to station:
AT+CWMODE?

+CWMODE:1

OK

Listing the access points works fine:
AT+CWLAP

+CWLAP:(3,"ap-1",-91,"01:23:45:67:89:ab",1)
+CWLAP:(3,"ap-2",-88,"cd:ef:01:23:45:67",2)
+CWLAP:(3,"ap-3",-74,"89:ab:cd:ef:01:23",11)

OK

But logging in to my Fritzbox router fails (WPA2):
AT+CWJAP="ap-2","mypassword"
WIFI CONNECTED
+CWJAP:1

FAIL
WIFI DISCONNECT

First I thought the reason is the low signal, but even moving directly beside the Fritzbox shows the same result (though with higher signal value in AT+CWLAP).
I've tried nearly everything, e.g. AT+CWMODE=3, AT+RST, AT+RESTORE). Nothing changes. When using a wrong password, I'm getting no "WIFI CONNECTED" messages at all.
Could it be a power problem (that the Olimexino can't provide up to 200mA at the 3.3V line?
Connecting from my smartphone to the ESP8266 in one of its access point modes (2 or 3) works fine. If there were power problems, wouldn't then the access point mode fails as well?

It looks like the ESP8266 could not obtain the IP address over DHCP (it was enabled in the ESP8266, but the Fritzbox was configured for a limited range only .200 - .209). When setting the IP explicitly:
AT+CIPSTA="192.168.92.82","192.168.92.254","255.255.255.0"

OK

and then trying to connect, it worked:
AT+CWJAP="ap-2","mypassword"
WIFI CONNECTED
WIFI GOT IP

OK

Pinging also works now: :)
AT+PING="arduino.stackexchange.com"

+39

OK

In my case when I try to connect to my router, I get the following output:
AT+CWJAP="myssid","mypassword"
WIFI CONNECTED
+CWJAP:1

FAIL
WIFI DISCONNECT

The reason is that the ESP8266 I have is setup with DHCP disabled by default. To enable it you can try the following:
AT+CWDHCP=1,1

If that works, you will get this message:
OK
WIFI GOT IP

Old old old post I know, but pretty sure this is the (more universally) correct answer, rather than the accepted one.

I had this same problem and spent an embarrassing number of hours trying to fix it before coming across this post.
I did a AT+RESTORE followed by AT+UART_DEF=9600,8,1,0,0 since, as expected, my module expected communication on 115200 after the restore.
Then... as if by magic, everything works now...
AT+CWJAP="ssis","pwd"
WIFI CONNECTED
WIFI GOT IP

!

I really don't know what was wrong that the RESTORE fixed... I must have screwed up the module by experimenting with various commands somehow.

I had many headaches related with this CWJAP:1 error and few others like Ok in return for change IP number command but actually the IP number still the same as before !!! The solution: The AT+RESTORE command to bring the ESP8266 back to the factory defaults... When not logical things happens for unknow reason probably is due to some internal register has dirty values inside and only a AT+RESTORE can normalize them...


text:
Connect my arduino with ethernet shield to new router
I just changed the router for my webserver and I'm having trouble to connect my arduino with the LAN.
I'm using a router which uses Zhone technology, and I've been working with NetGear for a while without problems.
The procedure I've done so far is:

Connect the arduino with the ethernet and run the DhcpAdressPrinter example
Once I got the adress, in my case 192.168.1.125 I run the WebServer example, using the IP assigned by the DHCP.
In the serial monitor, I see it has started the program with the correct IP.

Problem: WHEN PUTTING THE IP INTO A BROWSER, NOTHING CHARGES
More info:

In my router page (192.168.1.1) I can see that each ethernet port has
assigned a MAC adress, I don't really understand why.
I also can see that the arduino has been successfully added to the DHCP with the IP assigned and the MAC adress that I wrote on the code
Finally, add that I've read in another website that sometimes the problem is due to the fact that the router just let the access to some specific MAC adress, but i'm not sure.

Any help will be apreciated! Thanks!

Did you try to strip down the problem to a tiny test snippet to share?

Can other devices on the same ethernet connections communicate with your PC?

If there is something maybe wrong with your MAC, you should: 1)Make sure your cellphone can connect normally. w) change your IP to your cellphone's, and close your phone's wifi connection. Then try arduino program again. This idea mainly is based on using your phone's known-as-available mac.

Finally, I was capable to solve it by just creating a port forwarding with the IP that was assigned by the DCHP.
It looks like my router for security reasons don't let you comunicate with other devices within the lan, so it's necessary to open a port and access the device through it!

Sounds like "wireless isolation" to me - which is where I was heading with my comment above.

Yes you are right Makenko, I think this is the correct term :)


text:
Display unresponsive in one sketch, while working in another
I'm using a DOGM163 Display. It works in a DEMO sketch provided by the manufacturer but not in my sketch. This is strange, because I am using the same library specific commands as in the example.
I think of the following possibilities:

Something inside the other libraries I use in my sketch is hindering the dogm from working (perhaps by fiddling around with the ports connected to the display).
I've got a power problem which surfaces when doing more than just that demo.
Timing is botched.
Something with my wiring is wrong. Perhaps in conjunction with 1).

I'm using:
#include <Arduino.h>
#include "newsched.h"
#include "dplan.h"
#include <EEPROM.h>
#include <PinChangeInt.h>
#include <dogm_7036.h>
#include <SPI.h>
#include <OneWire.h>
#include "lampcontrol.h"

Power seems to be ok, as I'm receiving all debug messages via serial correctly.
The display is sharing its port with a port expander and a SD-port. But removing the SD-port doesn't change the problem.
Update (Part1)
Here comes the code, which works:
http://pastebin.com/eXUVzeV8
This is a slightly modified manufacturer example. But it does what it should do. It displays the demo text.
Here comes, what doesn't work:
Main sketch
newsched.h
newsched.cpp
display.h
display.cpp
menu.h
menu.cpp
The other source files, 19 in total!, can be posted on request, but as you can see from newsched.cpp I already disabled most of the code to narrow down the error.
What exactly means "not work"? Not work means, the display seems to be turned off. The LED backlight is on, but you cannot see the grey character boxes (due to display bias), which appear in the working code sample.
Update 2
Schematic:

What you should do next is show us your wiring (schematic) and sketch.

My initial response is that this is too broad to be answered. For one thing you say it "works" in one case but "not in my sketch" in another. A lot more detail would be helpful, describing what "work" and "not work" refer to, exactly. For more help I would suggest posting the code (or a link to it if it is very long) and also your debugging messages, which you say you got. Presumably if you got debugging messages it "works" to some extent (that is, it doesn't hang completely). But removing the SD-port doesn't change the problem. - again, what problem?

That sounds like a mighty complex program with that number of files. Have you considered you might simply be running out of memory? I notice you have never used _F(...) around any of your string constants to lock them into flash...

I added a bunch of code and schematic now. Let me know, if you want to see more source files...

@Majenko: No, that _F-feature is new to me. String constants are predominant in the menu class. The other classes deal with small portions of measurement data and control tasks. What makes the project big is the use of a lot of peripherals over the three stooges: SPI, I2C and 1-wire bus. To keep the overview I make a class at least for each peripheral unit. Now, I'll have a look onto the F-thing...

The _F() thing stops the strings being copied into RAM.  It's a macro that makes then into PROGMEM items so that PROGMEM-enabled functions are used to access them instead of non-PROGMEM ones that require the string to first be copied into RAM to access them. It's all because the Flash and RAM are on completely separate data/address buses.

Ok, got it. It's just a PROGMEM macro. How convenient.

To my discomfort the F-macro only works where the functions are overloaded appropriately. Which is not the case for the display routines. But the hint was good, as I had forgotten the fact, that strings are copied to ram at program start.


text:
safety for power electronics
I'm quite new to Arduino. I have build a number of projects successfully, like potentiometers, serial communication, DAC, sensors, motors etc.
I use a laptop to power my Arduino project and Atmel Studio to program and upload to the Arduino. I have created a project with 2 motors and I have successfully used a separate power supply (a transformer) to power the motors.
Now I want to continue my experiments but I'm afraid of the possibility to cause any problem to my laptop.
When I made the circuit with the 2 power sources (laptop for the Arduino, transformer for the motors) I had to connect the 2 grounds together.
So my question is that:
Can someone explain me or point me to some information about power electronics so to be absolutely sure that I won't cause any problem to the laptop?
Should I use optocouplers, or diodes etc? Is there a way to avoid the 2 grounds connection? What is the reason to connect both grounds (of the 2 power supplies) in the first place?

Connecting the grounds together is required since without that there would be no circuit for the current to flow through.  Take this simple block diagram for instance:

In the top diagram there are two complete circuits - the green one (Arduino's 5V power) and the blue one (device's 12V power).  The communication between the Arduino and the Device can't happen because there is no circuit (red).
In the bottom diagram the red circuit has been completed by joining the grounds together.  That means that the current has some way to get back to where it came from (which current always has to do) so the signals you send can actually get through.
To avoid having to connect the grounds together you need something called Galvanic Isolation.  This involves using some method that is not electricity to connect the two circuits together.  That could be using light in the form of an opto-coupler, or magnetism in the form of a transformer, or even something even more physical like a relay.  In that situation you have an arrangement like this:

The ground connection that was part of the red circuit above has now been sliced in half (red and orange now) and the isolation device is responsible for passing the signal from one side to the other.
Galvanic isolation is highly desirable when:

You are controlling a different type of current (e.g., using DC to switch AC)
You are working with voltages considerably higher than your drive voltage (e.g., switching mains)
You have different ground potentials (e.g., you have a long distance connection)

Galvanic isolation is also useful for long cable runs. For example, MIDI uses optocouplers. With a long cable, you might get earth loops.

@NickGammon Isn't that what point 3 in my answer says?

Oh yeah, sorry. Well I'll let it stand because it mentions MIDI. I didn't quite pick up "long distance connection" as "long cable run". Plus I threw in the "earth loops" keywords. :)

@NickGammon Can't hurt ;)


text:
Connect Arduino to MySQL database online problem

I'm trying to connect Arduino with MySQL database on my online server.
I manage my project to work on WampServer locally on localhost, but when I try to move everything online I have problem... on the serial monitor I get the message that the server is connected and my sensor readings, but I can't put them in to my database on my online sever.
Here is my code:

dbconnect.php
<?php
$MyUsername = "*******";  // enter your username for mysql
$MyPassword = "*******%";  // enter your password for mysql
$MyHostname = "*************";      // this is usually "localhost" unless your database resides on a different server

$dbh = mysql_pconnect($MyHostname , $MyUsername, $MyPassword);
$selected = mysql_select_db("tanjamayaarduino",$dbh);
?>

add_data.php
<?php
    // Connect to MySQL
    include("dbconnect.php");

    // Prepare the SQL statement
    $SQL = "INSERT INTO tanjamayaarduino.temperature (sensor ,celsius, light, moisture1, moisture2) VALUES ('".$_GET["serial"]."', '".$_GET["temperature"]."','".$_GET["light"]."','".$_GET["moisture1"]."','".$_GET["moisture2"]."')";

    // Execute SQL statement
    mysql_query($SQL);

    // Go to the review_data.php (optional)
    header("Location: review_data.php");
?>

Arduino code
#include<Ethernet.h>
#include<SPI.h>
const int temperaturePin = A3;    //LM35 Temperature sensor
const int lightPin = A2;          //LDR photoresistor sensor
const int moisture1Pin = A4;          //Moisture1 sensor
const int moisture2Pin = A5;          //Moisture2 sensor

// **** ETHERNET SETTING ****
// Arduino Uno pins: 10 = CS, 11 = MOSI, 12 = MISO, 13 = SCK
// Ethernet MAC address - must be unique on your network - MAC Reads T4A001 in hex (unique in your network)
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x3A, 0xDC };
// For the rest we use DHCP (IP address and such)
IPAddress ip(192, 168, 2, 121);
EthernetClient client;
//IPAddress server(192, 168, 2, 100); // IP Adres (or name) of server to dump data to
// IP Adres (or name) of server to dump data to  (godaddy baza server 37.148.204.140) (User: tanjamayaarduino@188.121.42.33) (goddady glavna adresa na hostingot 188.121.46.1)
//IPAddress server(188, 121, 46, 1);
char server[] = "188.121.46.1";

int  interval = 5000; // Wait between dumps

void setup() {

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

  Serial.println("Tweaking4All.com - Temperature Drone - v2.0");
  Serial.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
  Serial.print("IP Address        : ");
  Serial.println(Ethernet.localIP());
  Serial.print("Subnet Mask       : ");
  Serial.println(Ethernet.subnetMask());
  Serial.print("Default Gateway IP: ");
  Serial.println(Ethernet.gatewayIP());
  Serial.print("DNS Server IP     : ");
  Serial.println(Ethernet.dnsServerIP());
}

void loop() {
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)==1) {
    float tem = getTemp();
    Serial.println( tem );
    float lig = getLight();
    Serial.println( lig );
    float mois1 = getMoisture1();
    Serial.println( mois1 );
    float mois2 = getMoisture2();
    Serial.println( mois2 );

    Serial.println("-> Connected");
    if (client.connected()) {
      // Make a HTTP request:
      client.print( "GET /advertacs/test/arproekt/add_data.php?");
      Serial.println("-> add_data");
      client.print("serial=");
      client.print( "TempSensor" );
      client.print("&&");
      client.print("temperature=");
      client.print( tem);
      Serial.println("-> add_temp");
      client.print("&&");
      client.print("light=");
      client.print( lig);
      Serial.println("-> add_light");
      client.print("&&");
      client.print("moisture1=");
      client.print( mois1);
      Serial.println("-> add_mois1");
      client.print("&&");
      client.print("moisture2=");
      client.print( mois2);
      Serial.println("-> add_moi2");

      client.println( " HTTP/1.1");
      client.println( "Host:" );
      client.println(server);
      client.println( "Connection: close" );
      client.println();
      client.println();
      client.stop();
    }
  }
  else {
    // you didn't get a connection to the server:
    Serial.println("--> connection failed/n");
  }

  delay(interval);
}
float getTemp() {
  float temperatureC = (5.0 * analogRead(temperaturePin) * 100.0) / 1024; //converting from a 0 to 1023 digital range to 0 to 5 volts (each 1 reading equals ~ 5 millivolts
  return temperatureC;
}
float getLight() {
  float light;
  light = analogRead(lightPin) ;
  return light;
}

float getMoisture1() {
  float moisture1;
  moisture1 = analogRead(moisture1Pin) ;
  return moisture1;
}
float getMoisture2() {
  float moisture2;
  moisture2 = analogRead(moisture2Pin) ;
  return moisture2;
}

Why all the && in your URL?

Oh, and do you know the term SQL Injection Attack?

Thanks for security tips:),  as I sad I'm very new to coding, when I used this code locally without "&&" sings wasn't working, so I put them... btw I try it now without "&&" sings still not working... any idea?

You should reduce the && to just & not remove them altogether.

ok, I remove it &... still not working

What do your webserver logs tell you?

My server is on Godaddy... in Acces Logs folder there is nothing from today... last log is from 18.09.2015

Well I'd give up now then ;) We moved away from GoBadly because they are just so flipping useless. So no logs probably means no communication. Chech you are really connecting to the right address and with the right Host: entry, and if you have the technology and skills, some Ethernet sniffing could be useful.

Ok thank you for every thing, I'll keep trying... maybe I will make it :(

After Wales have finished creaming Uraguy I will try your code on my system and analyse the ethernet data to see what is being sent. By the way, wrap all your string literals in _F()

I just spotted an error in your code... println("Host: ");

ok... I corected in client.println( "Host:188.121.46.1" ); ... still no result... just to chek with you... mu server ip is the master IP on my hosting when I go in control panel... not the numbers that are given in Admin URL (phpMyAdmin), becouse they are different

No, you misunderstood my pointing out of the error. The error was the use of println instead of print, so the server name (not the ip) was ending up on the next line and breaking the header formatting.

still no result ...can I send you user and password brom my database to your email, so you can check it?

I am back at my computer now and I can craft a proper answer for you.

I see that you have posted this question as an answer here, as the user tanja

There are two basic things wrong with your code.  First is the formatting of your headers - you have mistakenly used client.println for sending the first part of the Host: header, so it becomes split onto two lines:
client.println( "Host:" );
client.println(server);

Secondly you are using the server's IP address instead of the actual host name in the Host: header. That means the server can't work out which website you are wanting to talk to and just rejects your request.
You need to have something more like:
client.print("Host: ");
client.println(servername);

where servername is the name of the server (www.website.com) not the IP address.  You can put it all in one line if you don't ever want to change the website name, since it makes it slightly harder to find and edit:
client.println("Host: www.mywebsite.com");

Dear Majenko No luck, I give up :( I tried every thing that you told me still no luck.. Thank you for your effort, I will send you the info on your email

Making those changes worked for me locally. So if you made the changes correctly then there must be either a problem with the server or you are communicating to the wrong address.

First of all, are you now connected to SQL? If so, and it still doesn't work... Have you tried to escape your ", so instead of:
$SQL = "... VALUES ('".$_GET["serial"]."', '".$_GET["temperature"]."',...')";

doing something like:
$SQL = "... VALUES ('\".$_GET[\"serial\"].\"', '\".$_GET[\"temperature\"].\"',...')";

If it still doesn't work, once you send to SQL with your code, print on screen what you are effectively sending, copy it with your mouse, paste it in your phpadmin-sql console and execute it. There you should see any helpful tips on what is really happening.
Hope this helps!


text:
How to loop over objects or pass object to function?
I'm not sure if this is more of an C++ question, but I've looked up both and still have no idea.
I have a sketch which controls 6 stepper motors using the AccelStepper library and in order to shorten the code, I would like to simply loop over them, or pass them to a function individually. They are all initialised with different parameters and then placed in an array.
However I get the error "conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested" or "conversion from ‘SomeClass (*)()’ to non-scalar type ‘SomeClass’ requested" depending on what I try.
I've got experience with C and Java, not much C++ and I thought it would be a straightforward array of pointers, but I can't get the right combination.
I've made a cut down version that I try to compile with gcc to demonstrate either approach. I've removed all attempts at pointers with & or * to explain what I want:
SomeClass classA();
SomeClass classB();

// error: conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested
SomeClass things[2] = {classA, classB};

int init(class SomeClass thing) {
    std::cout << "Setting up thing ";
    thing.setFoo(100);
}

int main() {

    for (int i=0; i < 2; i++) {
        things[i].setFoo(100);
    }

    // could not convert ‘classA’ from ‘SomeClass (*)()’ to ‘SomeClass’
    init(classA);

    return 0;
}

And just for completeness my class files which are simplified versions of the AccelStepper class:
SomeClass.h:
#include <stdlib.h>

class SomeClass
{
public:
    SomeClass();

    void    setFoo(float foo);
};

SomeClass.cpp:
#include <stdlib.h>
#include <string>
#include <iostream>
#include "SomeClass.h"

SomeClass::SomeClass()
{
}

void SomeClass::setFoo(float foo)
{
    std::cout << "foo ";
}

I hope someone doesn't mind explaining what is probably really simple and obvious! :)

There's a couple of fundamental errors in your sketch.  Mainly your construction of your class instances:
SomeClass classA();
SomeClass classB();

Those are taken as functions that return a SomeClass object, not SomeClass constructors.  Instead they should just read:
SomeClass classA;
SomeClass classB;

As for the rest, you are much better off using pointers to the classes - it makes passing them around so much easier.  For instance, your array would look like this:
SomeClass *things[2] = {&classA, &classB};

That is an array of pointers to the objects.  It just stores the addresses that they are at, rather than duplicating the objects into new objects within the array.
Your loop would then run like this:
for (int i=0; i < 2; i++) {
    things[i]->setFoo(100);
}

Note the use of -> instead of . because you are using a pointer to the object.
Similarly your init() function would be like this:
int init(SomeClass *thing) {
    Serial.println("Setting up thing");
    thing->setFoo(100);
}

init(&classA);

However, if you're never going to use the contents of your array with it you could use a reference instead of a pointer:
int init(SomeClass &thing) {
    Serial.println("Setting up thing");
    thing.setFoo(100);
}

init(classA);

That performs the same job as a pointer but leaves you with what looks like a real object rather than a pointer to the object - in fact it's just aliased the object name to a new one at the same address so you can still access it the same using .

Thanks for your answer! I should have included a more complicated constructor, the actual objects are created as eg:
AccelStepper stepperA(AccelStepper::HALF4WIRE, motorPinA1, motorPinA3, motorPinA2, motorPinA4);
Does this still hold with the above?

From my C experience, this looks like a pointer to an array of pointers: SomeClass *things[2] = {&classA, &classB}; Is it different in C++?

No, it's just an array [] of pointers *.  If it was a pointer to an array of pointers it would be SomeClass **things[2] - exactly the same as in C.

If your constructor takes parameters then you add parameters. If it doesn't you don't. It is a little confusing and I have no idea why they did it that way.

@Majenko thanks for your answer. It has been a great deal of help. I was wondering, however, instead of having an array of pointers with references to class objects, couldn't we just have an array of these objects and reference them like myObj &obj = arr[idx];?


text:
Arduino Delivering less power
I connected 4x716 Coreless DC Motors on pin 13,12,11,10 and 1xGY-521 to  Arduino Pro Mini 328, 5v but speed of propellers is not enough to produce enough torque to lift the quad whereas when i connect then  directly to 3.3v LiPo battery the quad has lift but because of no flight control it moves randomly.
I checked the voltage of pin 13,12... they have output as 0.5-0.6v, I think this is the reason quad is not lifting.
I am using following code
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

int p1 = 13;
int p2 = 12;
int p3 = 11;
int p4 = 10;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
    pinMode(p1, OUTPUT);
  pinMode(p2, OUTPUT);
  pinMode(p3, OUTPUT);
  pinMode(p4, OUTPUT);
  digitalWrite(p1, 0);
  analogWrite(p2, 0);
  analogWrite(p3, 0);
  analogWrite(p4, 0);

  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);

   digitalWrite(p1, HIGH);
  analogWrite(p2, 250);
  analogWrite(p3, 255);
  analogWrite(p4, 255);

  delay(333);
}

Atmega328 output pins are rated at 40 mA absolute-maximum current, and the 328's total current through Vcc and ground pins is 200 mA absolute max.  Eg, see table 29.1 in the Atmega328 specs.
Although some sources rate a high-speed 716 coreless dc motor at 40 mA, other sources rate it at 100 mA.  In either case, it exceeds normal I/O pin capability. You should use FETs or other drivers between Arduino output pins and the motors rather than trying to drive the motors directly from digital output pins.
Edit: Regarding the comment, “But most projects i've seen don't use any drivers, Why so ?” I replied:

Perhaps they are using slightly higher voltage to the Pro Mini, eg 3.7 V up to 5 V, which after accounting for voltage drop in the i/o pin circuits may deliver enough voltage to the motors. Note that a driverless circuit ie direct drive from the i/o pins operates the 328 out of its safe operating area (SOA), but it may be close enough to the safe area to usually work.

For example, some of the 716-based quadcopter pages I looked at say they used 4.2 V LiPo batteries.  Also note, 716 seems to be a fairly generic motor designation; it refers to the motor's 7 mm diameter and 16 mm length.  As a generic designation it has been used for several different motors, some of which produce less power.  For example, in thread #1710948 on rcgroups.com, people refer to different RPMs, less lift, etc. for various motors, and the importance of shaving grams off of the copter's weight to allow it to fly.
Another item that matters when drawing high current from an Atmega328 is which ports are used; and for some devices, it matters whether drive is high-side or low-side, ie whether current is sourced or sunk.  The Atmega328 spec sheet (Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf) says “Each output buffer has symmetrical drive characteristics with both high sink and source capability”, but for several kinds of drivers less voltage is lost with low-side drive than with high-side.  Ie, you could try connecting the motor's V+ lead to Vcc and its V- lead to the i/o pin, and inverting the on-off logic in the sketch. (I don't know if this will make any difference at all in how well things work.)
Regarding which ports are used, the footnotes to Table 30-1, “Common DC characteristics”, spell out various combinations of ports where total current draw must not exceed a limit (100 mA in some cases, 150 mA in others).  On the Uno and Pro-Mini, digital outputs marked 10 through 13 (as used for motor control in the question's sketch) are port B Atmega pins, with a footnoted total-current limit for the group.  If you move two of the motor drives to outputs marked 2...4 or D2...D4, then a different total-current limit will apply.  (Again, I don't know if this will make any difference at all in how well things work.)  Refer to Table 30-1 footnotes for details.
As noted in Gerben's comment, having flyback-diodes for the motor circuits is a good idea. This consists of placing power diodes across the motors, cathode to V+, anode to V-, to prevent energy stored in the motor's inductance from producing extreme i/o pin voltages each time the motor is turned off.
Edit 2: Regarding “which diode, FET to use and where [to] learn about them”, electronics-tutorials.ws is an accurate and helpful presentation about FET digital circuits.  In particular, see the section called “An example of using the MOSFET as a switch”.
Which FETs to consider depends in part on your electronic-circuits fabrication skills.  Note that surface mount devices (SMD parts) usually weigh less than other versions of parts, which is important for a lightweight quadcopter.  However, some people find SMD parts difficult to work with.  In my opinion, the main difficulty is holding parts in their proper places while soldering them, due to small size.  (Eg, a SOT-23 SMD transistor package is on the order of 3mm x 2mm x 1mm, and a diode may be half as big.)  If you have good soldering skills and a way to hold parts in place while soldering, you should be ok, either using a printed circuit board or air-wiring parts using wire-wrap wire (ie, 30 AWG wire, about 0.25mm diameter).
Some typical logic-level-input SMD FETs are shown in mouser.com's online catalog.  Note that in that list, RDS_on decreases a bunch as unit price increases slightly.  For example, the FDN359BN would have under 0.1 ohm resistance when operated with Vcc = 3.7 V and currents < 100 mA.  Voltage drop running a 40 mA motor should be about 4 millivolts.
Some typical SMD Schottky diodes also are shown in mouser.com's online catalog.  I think even the cheapest of these would work ok.  Of course you'll need to adapt all these suggestions to your own skills, sources of parts supply, and budget.

But most projects i've seen don't use any drivers, Why so ?

Also; don't forget to add flyback-diodes to the motors.

I've added a few more paragraphs of explanation

Cool....Added to knowledge, I have used a paper body so that is only possible light weight and motors
RPM: 20000 +/- 2000
Voltage: 3.7V DC
Shaft: 4mm x 1mm
Continous Current: 40mA
Can you please point to some resource where i can find which diode,FET to use and where can i learn about them ? I am pretty new to electronics

@Anonymous, see edit

In my opinion, the main difficulty is holding parts in their proper places while soldering them - I would second that. However that is merely a mechanical problem, and can be solved in various ways. A couple of years ago I wouldn't have touched a SMD device, but now I am happily soldering SMD LEDs, resistors, etc.

@NickGammon,  I too like SMD parts and use them a lot, since they are small, cheap, versatile, and don't require thru-holes on home-made boards.  However,  “merely a mechanical problem” might not give the positioning problem enough respect.  Simple solutions exist (like using solder stencils and solder paste and an oven, or using a vacuum pickup, or using micropositioners) but without aids like that, holding SMD parts with the necessary accuracy (say .01" or less) for soldering can be hit-or-miss.

I was thinking of 2 or 3 pin parts. The ones with lots of legs are certainly a challenge. :)


text:
To know the state of USB (Serial) connection (connected or not connected)
if (Serial.available()) {
        digitalWrite(7, HIGH);
} else {
        digitalWrite(7, LOW);
}

It doesn't seem to be so simple.
My testing LED turns on when the USB connection with another program is established, but it doesn't turn off (LOW) when that program exits.

Cross posted on Arduino Forum and a second time.

How about having the other program send data to Arduino and Arduino knowing the connection is lost when new data isn't received? I have no idea what Arduino code would do that but just an idea.

That sounds simple enough.
const unsigned long MESSAGE_TIMEOUT = 10UL * 1000;  // 10 seconds

void setup ()
  {
  Serial.begin (115200);
  while (!Serial) ;  // wait for Serial to become active
  Serial.println ("Starting");

  }  // end of setup

unsigned long lastMessage;

void processInput ()
  {
  while (Serial.available ())
    {
    char c = Serial.read ();
    // do something with the data
    }  // end of while loop
  }  // end of processInput

void loop ()
  {
  if (Serial.available ())
    {
    lastMessage = millis ();  // remember when we last got input
    processInput ();  // now handle the input
    }

  if (millis () - lastMessage >= MESSAGE_TIMEOUT)
    {
    // we don't seem to be receiving data
    }

  }  // end of loop

And an issue on the Python side... http://arduino.stackexchange.com/questions/16220/pyserial-serial-write-doesnt-work

The problem here is twofold.
Firstly, on Arduinos that don't have a direct USB connection, (i.e., boards like the Uno, Mega, etc that use a separate chip to manage the USB connection) you have no way of knowing if the USB is open or not.  That information simply isn't there. The main chip just receives UART serial data (not USB data) as it arrives and that is that.
Secondly, even on the boards that have a direct USB connection (Leonardo, etc) there is no proper way to know if the port has been opened or not.  The CDC/ACM protocol simply doesn't have that kind of information (a bit short sighted of them really).  The closest you can do is monitor the DTR and/or RTS signals that are encapsulated in the USB data stream.  It is down to the host operating system (and maybe even your own program) to exert those signals properly, so isn't foolproof even then.
To check the status of those lines in your sketch you can examine the boolean operator of the Serial object:
if (Serial) {
  // I am connected
} else {
  // I am not connected
}

But as I say that can only work on boards like the Leonard - the other indirect boards think they are always connected, since there is no such thing as a connection in UART terminology, only data.

How about having the other program send data to Arduino and Arduino knowing the connection is lost when new data isn't received? I have no idea what Arduino code would do that but just an idea.

That method is known as keepalive.

"method" as in a function, or technique? Any example somewhere?

Technique.  How you do it depends on what you are doing serial-wise at the moment.

I'm lighting a LED when there's a USB connection between a PC program ans Arduino.

That's very interesting. It doesn't give even the slightest hint what you are doing. Ask a new question. Describe your sex al data flow and protocol. Ask how you might best implement a keepalive system in it.

There's no need for a new question. This is a simple question, I need to know the state (connected/not connected) of USB connection between a PC program and Arduino and tell the state by flashing a LED. What more do you want? There's either an answer to the question or there isnt.

I have given you the answer to that. Now you are asking about how to work around the fact that there is no way of knowing. The amount of extra information you will have to provide in order to get an answer to that will change the current question beyond recognition and will invalidate this and any other answer. This is not open to discussion. If you want information about something other than what you asked then you ask another question providing in detail what has been asked for. Comments are for clarification of the existing question not for asking new ones.

There is no way of knowing? Then why did you say "That method is known as keepalive"? when I thought of some way? There either is no way or there is some way. Can you answer that, here or in a new post (which I feel will be marked s dublicate).

That has nothing to do with knowing if it is connected or not - it is merely a method of determining if the connection is alive and working. The two are very different and require completely different ways of thinking. Just ask the new question. I am not discussing this any more.

What is the difference between "connected" and "alive and working"? I'll need to know that to ask the question properly. Maybe I even asked the wrong question to begin with by using the wrong term.

The difference is the difference between "is" and "was". You know the term (keepalive) and what you need to tell us (your existing serial protocol, what your programs do and how that pertains to the serial).

"The difference is the difference between "is" and "was"". That wasnt clear at all...

Go ask the question.


text:
How Add Piezo Buzz to Pong Sketch
I am junior high teacher teaching students how to program using Arduino. I know the basics of programing but the students wanted to program a game which is a little above my skill set. I am using the following sketch (http://www.itopen.it/arduino-pong-with-8x8-led-matrix-and-max7219/) to introduce them to programing games. Thanks to this site I understand most of the code. However I would like to add a line of code that will make a piezo buzzer buzz every time the "ball" hits the pad. I think the code should look something like the code bellow, but I am not sure if it is correct or where I would put it.
#define buz 8 // number of pin buzzer connected to
     if (HIT_CENTER || HIT_RIGHT || HIT_LEFT) {
        digitalWrite(buz, HIGH);
        delay(100);
        digiralWrite(buz, LOW);
        }

Any help would be appreciated.

The condition HIT_CENTER || HIT_RIGHT || HIT_LEFT will always be true.  (All three of those HIT_ values are non-zero constants.)
Instead, you need to test if getHit() is non-zero.  (To see this, search the sketch for occurrences of HIT_RIGHT or HIT_LEFT.)
The sketch sets up an event timer (via ball_timer = timer.every(BALL_DELAY, moveBall); in setup()) so that ball position will update every 200 ms.  The loop() sequence is: Use timer.update() to service timer events.  Use setPad() to read the paddle position.  Use drawGame() to update the game picture. Somehow use checkLoose() to see if game is over.  Use delay(GAME_DELAY) to wait 10 ms.
Given that structure of loop(), throwing in a 100 ms delay to wait for a buzzer would mess up the game play.  You could turn on the buzzer and set up a timer event for turning it off, each time the ball hits the paddle.
More straightforwardly, since a 10 ms beep is likely to be adequately long, you could test for a hit just before delay(GAME_DELAY), and always turn the buzzer off just after that delay.  In other words, before the delay say:
if (getHit()) digitalWrite(buz, HIGH); and after the delay say digitalWrite(buz, LOW);.
This supposes that writing HIGH to buz turns on the buzzer and that writing LOW turns it off.

Method 1:
here is what i would have done is use this code snippet we can get the state of HIT,,,if it is not equal to HIT_NONE ,buzz it
 #define buz 8
 if(getHit()!=HIT_NONE){
    digitalWrite(buz, HIGH);
    delay(10);
    digitalWrite(buz, LOW);
    }

This is the simpler version where in delay is small,Beaware using delay will completely halt processor operation ,buttons ,joystick serial ports etc everything will be halted.
Method 2:With Flexible Delay
  #define buz 8
  unsigned long previousMillis = 0;
  const long interval = 200;   /////Specify the delay you want here
  void loop()
   {
     unsigned long currentMillis = millis();  //start timer
     /*
         Remaining Code Is Left As It Is
     */
   }

       ///////////Code Snippet Without Using Delay
   if(getHit()!=HIT_NONE){
   digitalWrite(buz, HIGH);
   if (currentMillis - previousMillis >= interval)
        {
            previousMillis = currentMillis;
            digitalWrite(buz, LOW);
        }
   }

But where to add these functions???
Use getHit() to implement ,,,just like below
  int getHit() {
  if(yball != 6 || xball < xpad || xball > xpad + PADSIZE){
    return HIT_NONE;          //returns in case of hit failure so no
                              // buzzer ring
     }
        digitalWrite(buz, HIGH);    //If it has not returned yet makes
        delay(10);                  //sure that it is a successful hit
        digitalWrite(buz, LOW);     //buzzer ring
  if(xball == xpad + PADSIZE / 2){
    return HIT_CENTER;
     }
   return xball < xpad + PADSIZE / 2 ? HIT_LEFT : HIT_RIGHT;
 }

yet again u can replace those 3 lines with below one to be more flexible
digitalWrite(buz, HIGH);
if (currentMillis - previousMillis >= interval)
     {
         previousMillis = currentMillis;
         digitalWrite(buz, LOW);
     }
}

hope this helps.