text:
Write a condition to execute 2 switch-case functions?
I'm new to programming and using Arduino products, and was wondering if someone wouldn't mind assisting me with a project I'm trying to tackle?
If you review my code below, I have 3 conditions within my "idle" case, and the program is constantly looking for any of those 3 conditions. If the first condition is met, then case 1 is called; if the second condition is met, then case 2 is called; if the third condition is met, then case 3 is called. All 3 cases return to the "idle" case once done running.
What I would like to do is find some way to insert the "warning" case if any of the conditions are met, BEFORE going to case 1, case 2 or case 3, without writing the functions of the "warning" case over each time for each of the other 3 cases. Essentially, the flow would be like this:
condition 1 --> warning --> case 1 --> case idle;
condition 2 --> warning --> case 2 --> case idle;
condition 3 --> warning --> case 3 --> case idle:
void loop() {
  static byte theState = idle;
  switch (theState)
  {
    case idle:
      if (voltageA0 > 1.0) {
        theState = case1;
      }

      if (voltageA1 < 2.0) {
        theState = case2;
      }

      if (voltageA2 > 3.5) {
        theState = case3;
      }
      break;
    case warning:
      digitalWrite(7, HIGH);
      delay(5000);
      digitalWrite(7, LOW);
      delay(0);
      break;
    case 1:
      digitalWrite(8, HIGH);
      delay(2000);
      digitalWrite(8, LOW);
      delay(0);
      theState = idle;
      break;
    case 2:
      digitalWrite(9, HIGH);
      delay(2000);
      digitalWrite(9, LOW);
      delay(0);
      theState = idle;
      break;
    case 3:
      digitalWrite(10, HIGH);
      delay(2000);
      digitalWrite(10, LOW);
      delay(0);
      theState = idle;
      break;
  }
}

Also, if there is a more efficient way to do this, code-wise, I'm all ears!

Simplifying the code before posting it is generally a good thing. But if you change it so much that it becomes mostly unrelated to the original one, then a proper answer to the question may not be applicable to your real problem. Judging from your comments to Look Alterno's answer, this is exactly what happened. The blocking code you posted is a very different beast from the non blocking one you are using. Please, edit the question to make it relevant to your actual problem. This would be more useful than trying to explain in comments the extent to which the codes differ.

There is something incoherent in your code. It is structured as a finite
state machine, and yet you are using delay() within it. In this kind of
scenario, the whole purpose of a state machine is to avoid using
delay(), so that your program never blocks. If your program happens to
not have anything better to do than delaying, then you can forgo the
state machine and write much simpler code. For example:
void warn_and_flash(byte pin)
{
    // Flash the "warning" LED.
    digitalWrite(7, HIGH);
    delay(5000);
    digitalWrite(7, LOW);

    // Flash the requested LED.
    digitalWrite(pin, HIGH);
    delay(2000);
    digitalWrite(pin, LOW);
}

void loop()
{
    if (voltageA0 > 1.0) warn_and_flash(8);
    if (voltageA1 < 2.0) warn_and_flash(9);
    if (voltageA2 > 3.5) warn_and_flash(10);
}

I agree. Imagine you are writing code for a motor car, and the driver puts on the left indicator, which is supposed to flash once every second. Do you really want to the car to ignore the other inputs (brakes, accelerator, air conditioning) for an entire second while you delay for one second? I think not.


text:
Wireless serial communication. Sending 4 different continuous values
I am trying to control 4 motors using 2 joysticks.
I want to send continuous analog values of 2 joysticks (x & y both).
I am using bluetooth HC-05. I am using the basic logic that is sending a character before each analog value and thus sending all 4 values.
My problem here is at the reception end, data is not received correctly. Error rate is very high.
Is their any other way or improved program to do that?
//this is my part of the code at the transmitter side

#include <SoftwareSerial.h>
int a,b,c,d;
int ry = A0; // forward backward
int rx = A1;//rotate
int lx = A3; //right left
int ly = A4;
SoftwareSerial blu(10, 11); // TX,RX

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

void loop()
{

   a = analogRead(ry)/4;
   d = analogRead(rx)/4;
   c= analogRead(ly)/4
   b = analogRead(lx)/4;

   blu.write("w");
   blu.write(a);
   blu.write("x");
   blu.write(b);
   blu.write("y");
   blu.write(c);
   blu.write("z");
   blu.write(d);
      }

}

// Code at the reciever side

#include <SoftwareSerial.h>

SoftwareSerial mySerial(12,13); // tx,rx

void setup()
{
  Serial.begin(9600);
  mySerial.begin(9600);
  digitalWrite(gnd1 , LOW);
  digitalWrite(gnd2 , LOW);

  pinMode(motor1, OUTPUT);
  pinMode(motor2, OUTPUT);

  pinMode(dir1, OUTPUT);
  pinMode(dir2, OUTPUT);
  pinMode(dir_1, OUTPUT);
  pinMode(dir_2, OUTPUT);

}

void loop()
{
    if (mySerial.available())
  {
    a=mySerial.read();
        if(a=='w' || z=='x' || a=='y' || a=='z')
        {
          if(a=='w')
        c_b=mySerial.read();
        b=map(c_b,0,255,-255,255);
        motorspeed1(b);
      }
   if(a=='x'){

            int c_c=mySerial.read();
            b=map(c_c,0,255,-255,255);
            motorspeed2(c);

          }
if(a=='y'){
 int c_d=mySerial.read();
            d=map(c_d,0,255,-255,255);
            motorspeed3(d);
  }
if(a=='z'){
 int c_e=mySerial.read();
            e=map(c_e,0,255,-255,255);
            motorspeed3(e);

}
}

//motor speed function takes care of the direction and the pwm. my problem is at the receiving end the values are not proper . error is very high mySerial.read() gives false values

Can you post the parts of the code that send and parse the messages? how about examples of what is being received? Can you tell if the error rate is due to the protocol or interference?

The problem could be baud rate, not correctly taking data or anything. As @BrettM said, we need more information. Also you say 4 motors and 2 joysticks. Do you have X1&Y1 and X2&Y2? You could send 6 bytes: Start byte,4 data bytes(0..255) and stop byte

guys i have included the code. thanks for the reply

source: Stack Exchange

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

sort: votes


text:
Programming an Array of ATTiny
I am designing a board for my electronics project and i am using a number of ATTiny85 for it. The ATTiny's will be SMD so i will not be able to remove them for programming.
Moreover all of the pins of my uCs will be used for connections (apart from reset).
Is it possible in this case to achieve that, any ideas and suggestions are welcome
EDIT: Well, Vcc and Ground will be common, i will be using an external oscillator for all of them, the reset pin will be free, the other three pins will be used for gpio communication between the attinys.
I am connecting about 10 attiny in a daisy chain kind of thing

Lots more detail needed. You may be in substantial 'trouble' here and may not. How many uCs? What state are the MOSI/MISO/SCK in on other processors when you program one of the,? Are they "hard connected (wire) and do they have to be? - eg could you add resistors between uCs so you can drive a MISO or MOSI or ... pin high or low ehen it is held in a fixed state on other boards? May it be possible to have an "enter programming" mode where all processors explicitly deload all commoned pins as much as possible during programming of 1 of N. | If you reset ALL uC's and SCK is able to be ...

... clamped low at all but one IC then you could program one only most signals applied to all except SCK which is low for all but the target uC. You MAY be able t do similaar;y and clamp MISO low on all but one but that is getting dangerous as all will clock in the all-0 MISO state. This probably does no harm but would need to be checked. ||| It will be possible to do something which meets your need with minimal disturbance of the design BUT we need much better details in order to be able to interact with you usefully. [I was in Mumbai a few days last March. I'd like to visit longer someday.]

See table 3 in AVR910 ICSP App Note - resetting all uCs and clamping (or pulling) MOSI high or low on all except target uC should safely isolate all others from programming action. So the ability to isolate MOSI as required on all except target uC would address your requirement. Loading can still be an issue.

@RussellMcMahon I think you have given lots of relevent info here and you should form it up into an answer. As far the the board designing is concerned the entire design is upto me so i can add resisters wherever required as long as it does not cause drop in high and low levels. As far as design is concerned one of the three pins left (MISO MOSI and SCK), one will be common to all uCs (10 Attiny85 that is) and others will form daisy chain. My concern is that all  of them will not be input (one input from previous and one output to next. As far as driving is concerned i am not worried )

but as you pointed out having another input on same line is an issue. I am willing to add other resistors, capacitors, but adding any other IC will be a problem. It would be highly preferable to not have any jumpers or switches of the kind because we are trying to make the circuit so that any novice can program it. I would love if you want to get into electrical design concepts (me studying EE ofcourse). Do visit college if you come to mumbai again, you may find pretty interesting stuff here :)

As long as whatever you're connecting the MISO, MOSI, and SCK pins to doesn't mind being driven externally, you can still program the ATTiny in-circuit - just break out those pins with reset to a standard 6 pin header and program them that way.
If one or more of those pins can't be driven externally (eg, because they're connected to another device that drives them and has no output disable), you'll need to add a tristate buffer IC between the MCU and the other device, or some jumpers you can remove when you want to program them.

The pins i am connecting them are MISO, MOSI and SCK of other ATTiny, so will putting other attiny in reset work?? i do not want to add a tristate buffer IC :P

Sure - as long as you separate the reset pin for each MCU, it doesn't matter if they share the SPI pins; only the one the programmer holds in reset will get programmed.

@Rishabh Note that your query re reset and Nick's answer reflected opposite understandings between you of the state of reset during programming.

@Rishabh - Here is Atmel's ICSP programming guide. http://www.atmel.com/images/doc0943.pdf.|It notes "To enter and stay in Serial Programming mode, the AVR microcontroller reset line has to be kept
active (low). Also, to perform a Chip Erase, the Reset has to be pulsed to end the Chip Erase
cycle. To ease the programming task, it is preferred to let the programmer take control of the target
microcontroller reset line to automate this process using a fourth control line (Reset)." ie the device being programmed has reset asserted and the ones not being programmed are NOT reset. ...

@Rishabh You need to look at the loads provided on MISO MOSI and SCK by the other processors when they are not being programmed. IF a given line is an input all MAY be well. If it is an output you may have problems. Even inputs plus enough cabling etc plus a low drive capability programmer may cause problems. If you want assistance with the electrical aspects here you need to provide a more detailed description. How to connect them may be mainly Arduino related but you are getting into the lectrical design aspects. (I'll play :-) ).

@RussellMcMahon We're not in the lands of TTL anymore! A programmer with 5mA output drive capability is going to be absolutely up to the task of driving a few CMOS inputs. Good point RE reset and making sure the others aren't driving, though.

Well you need access to pins 0 & 1 to program them, so you either do it off-board, or design in a way to access them - perhaps a PCB hole you can wire to temporarily, or a link you can fit/remove that changes the connection.
You will probably need to program them before the rest of the board gets filled up?
You havn't said what you will be connecting to these pins nor how many is an "array" which kind of limits how specific we can be here!

Sorry, but this is not a meaningful answer.

Lookin' forward to your answer then... I don't quite see why you feel that way though, you DO need to access those pins & if you're going to wire up an array of linked processors, you have a problem - hence the question. It is short on detail to provide a terribly definitive reply though.

Quite simply, you have not addressed the question actually asked.  Also, your one specific statement about pins is not accurate for the ISP programming that is the topic.  When a question is short on detail, start with comments - not a change of topic "answer".

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


text:
Can't upload to my Nano after updating to Arduino AVR Boards 1.6.21
I recently had the Arduino IDE notify me of available boards updates, so I updated. Since then when I try to upload to my Nanos it fails:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x01

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I installed Arduino IDE 1.0.6 and found that I can upload to all my Nanos with that IDE version.
How can I upload to my Nanos using Arduino AVR Boards 1.6.21?

The latest version of the Arduino IDE for windows is 1.8.5. What version are you running? What does "not work" mean?

Does not work needs more clarification. Can you even open the IDE? Does a sketch compile, but fail to upload? Does it upload, but the Arduinio doesn't run/operate?

Provide the actual error messages

what i mean is, since i updated the IDE a few days ago! none of my boards will not work with the updated IDE. i am using 1.8.5 sorry all 5 boards would not work, i have even tried a new NANO board i received today, and even it still will not work!! with 1.8.5 out of the 6 boards i have, i have only been able to get 3 nano's and 1 chinese arduino uno to work and that is only because i have downloaded the IDE 1.0.6 my original arduino uno r3 and another Chinese board still will not work! thank's for getting back to me :-) much appreciated.

Define "Not work". That phrase covers a multitude of possible issues.

Sorry i see, the IDE starts up ok! but when i upload a sketch, it compiles the program no problem, then just keeps the green bar on for about a minute then it gives out the error: programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x8a
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
and that is with a brand new board!

Did you select the correct port in the IDE?

yes for both the nano and uno they both use com 3 but i have tried other com's and it just will not work, in IDE 1.0.6 'iv'e just tried it, it uploads no problem, and the lights on the board flash.

Please take a minute to read the question now that I have edited it. That is how you are supposed to ask a question. Not the sloppy garbage you wrote. Please make a better effort in your future use of Stack Exchange.

Arduino recently changed the bootloader they ship on their official Nano boards. This required a change in the hardware definition for the Nano, which was the sole reason for the Arduino AVR Boards 1.6.21 release.
The new Nano hardware definition is not backwards compatible with Nanos that use the previous ATmegaBOOT bootloader. For this reason a new menu option was added: Tools > Processor > ATmega328P (Old Bootloader). If you select that option the uploads to your Nanos will work again.

just tried ATmega328P (Old Bootloader) still does not work :-(

it works, when i changed it, it was on com port 1, i just changed it to com port 3 and it work's now, thank you very much, i thought i had done all my boards in lol really thanks. :-)

Just tried the (Old bootloader) option after uninstalling and installing Arduino IDE.  Really terrible problem.  Couldn't figure it out. All the other boards (pro micro, mkr zero, etc) were working but not Nano.  Really annoying but so glad I found this solution.  Thanks!

I also had similar issues after upgrading my Ubuntu system.
Selecting 3.3V for the Mini board did the trick, For the Nano, the old loader worked.

Check weather your arduino nano is Chinese having CH340G chip. If the chip is there then you have to install CH340G drivers in your computer..

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


text:
Serial Monitor not properly interpreting data from my NodeMCU V3
I've just received several LoLin NodeMCUs from a 'cheap Chinese ebay vendor'.  They're working well except for the fact that I'm getting garbage in the Arduino IDE Serial monitor.
I am able to:

Load and run sketches
Use the NodeMCU as a webserver and
connect to it from a computer/smartphone/etc
Everything you else you would expect an ESP8266 to do EXCEPT

I am not able to get readable data to display in the Serial Monitor.
Some Details:
-My computer is running Linux Mint so I understand that drivers shouldn't be a problem
-The NodeMCU board has instructions printed on it to
           1) Install CH340G driver
           2) Use 9600 baud rate
           3) Connect to WiFi
-I have not tried issuing an AT command to slow the default baud rate down to 9600 (as suggested in answer to another question on this forum).  Since the NodeMCU standard rate is 115200 and it's only talking to my computer and not another Arduino, I didn't think that would be required.  {Could that be the answer to my problem?}
-I've tried all the standard baud rates between 9600 and 115200.  None produced readable outputs.
-I've connected stabilized external 5 and 3.3 V power sources to the board and added some caps for extra smoothing.
I'm running the simplest sketch I could think of to send data back the Arduino Serial Monitor:
int LEDState = LOW;
int pinNum = D7;  //LED on D7 will flash while loop is running

void setup()
{
  Serial.begin(15200);
  pinMode(pinNum, OUTPUT);
}

void loop()
{
  digitalWrite(pinNum, HIGH);
  Serial.println("T");  // send the Letter T to the serial output
  for (int c = 0; c < 10; c++)
  {
    Serial.println(c); // send the count 0 to 9 to the serial output
    delay (200);
    LEDState = blinkLED(pinNum, LEDState); // blink the LED to demonstrate that the loop is running
  }
}

int blinkLED(int pinNum, int State)
{
  if (State == LOW)
  {
    digitalWrite(pinNum, HIGH);
    State = HIGH;
  }
  else
  {
    digitalWrite(pinNum, LOW);
    State = LOW;
  }
  return State;
}

I've tried all the various line endings (CR/LF, CR, LF, nothing at all).  No success with any of them.

When you upload a sketch to you NodeMCU board the AT firmware is erased (the sketch you upload becomes the firmware) so AT commands don't apply. You should have the baud rate menu in the bottom right corner of the Serial Monitor set to 115200 since that is the speed you set with Serial.begin(115200).

That's not the simplest sketch to send serial data to Serial Monitor. Instead, try this:
void setup(){
    Serial.begin(9600);
}

void loop(){
    delay(500);
    Serial.println("Hello World");
}

Upload and open Serial Monitor at 9600 baudrate. Your AT firmware is already erased, never expect 'OK' response for 'AT' command. If Serial Monitor displays 'Hello World', then your board is okay. Then, you have to reflash AT firmware if needed.

I seem to have found a solution to my own problem.  I poached a code snippet from another post on this forum (which I don't seem to be able to find now or I would happily give credit for) and inserted it into my sketch.  Works like a charm.
The code snippet resets the baud rate to 9600 within the program itself.  I upload the sketch at 115200 baud, but then switch to 9600 baud to talk to the Serial Monitor.
I've been running this code on the NodeMCU for 14 hours now and it's still going strong.
My next steps will be to insert this code into the rest of the Example Sketches that use the Serial Monitor and see if they all work on the NodeMCU V3 now.
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX

int LEDState = LOW;
int pinNum = D7;  //LED on D7 will flash while loop is running

void setup() {
//   ***  Additional Code that fixed my problem  ****
  Serial.begin(9600);
  ESPserial.begin(115200);
  ESPserial.println("AT+IPR=9600");
  delay(1000);

  // Start the software serial for communication with the ESP8266
  ESPserial.begin(9600);

  Serial.println("Ready");
  ESPserial.println("AT+GMR");

// ***   End of additional code

  pinMode(pinNum,OUTPUT);

}

void loop() {
  digitalWrite(pinNum, HIGH);
  Serial.println("T");  // send the Letter T to the serial output
  for (int c = 0; c<10;c++)
  {
    Serial.println(c); // send the count 0 to 9 to the serial output
    delay (200);
    LEDState = blinkLED(pinNum, LEDState); // blink the LED to demonstrate that the loop is running

  }

}

int blinkLED(int pinNum, int State)
   {
      if (State == LOW)
        {
          digitalWrite(pinNum, HIGH);
          State = HIGH;
        }
        else
        {
          digitalWrite(pinNum,LOW);
          State = LOW;
        }
        return State;
   }


text:
Controlling a stepper with MATLAB
I am trying to control a 28BYJ-48 stepper motor + ULN2003 motor driver module  (this is a picture) using MATLAB.
I tried to follow the instructions on this page, but these instructions are specific to Adafruit MotorShield, and I couldn't understand how to modify the code to fit my motor/driver.
Specifically:

How do I wire my motor/driver/Arduino?
How do I modify this command:
shield = addon(a, 'Adafruit\MotorShieldV2')

Do I need to flash my Arduino with any libraries?

Adafruit Motor Shield V2 itself generates signals that are required for motor control.
ULN2003 motor driver module requires signals at the input. This is a significant difference.
Example of use this driver with MATLAB. Not need to flash Arduino any libraries.
a=arduino('com3','uno);

pins={'D8', 'D9', 'D10', 'D11'};
steps={'1100', '0110', '0011','1001'};

steps_size=size(steps,2);                        %steps = 4

for i = 1:50

    step = steps{mod(i,steps_size)+1};      % step=1,2,3,4

    for j=1:4
        writeDigitalPin(a, pins{j}, str2double(step(j)));
    end

    %pause(0.01);

end

Wiring example (Copied from CheapStepper v0.2)


text:
Timer 2 interrupt with ATmega328p and make measurement in ISR

I am working in my project and i want to use Timer2 interrupt every 100ms to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.
I read in some article that using delay instruction is not as good as using timers'Interruptions so, I tried this code put it didn't work properly :
void setup(){

cli();

  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2  = 0;
  OCR2A = 99;
  TCCR2A |= (1 << WGM21);
  TCCR2B |= (1 << CS21);
  TIMSK2 |= (1 << OCIE2A);
sei();

Serial.begin(9600);
}
void loop()
{
Serial.print(digitalRead(1));
Serial.print(' ');
Serial.print(digitalRead(2));
Serial.print(' ');
Serial.print(digitalRead(3));
Serial.print(' ');
Serial.print(digitalRead(4));
Serial.print(' ');
Serial.print(digitalRead(5));
Serial.println(' ');

}

Where is your ISR?

in fact I dont know where i put the ISR interupt service routine where i have to put measurement instruction .

Enabling the interrupt without writing a ISR is pointless.

i know that but where  in the code i put the ISR?I think i have to put it in the loop

i want to use Timer2 interrupt every 100ms to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5. - your code does not reflect those intentions.

yes i mean i want to see in my screen new measurement every 100ms ,
I don't want to use delay instruction.

I am sorry mr nick put i know more in 8051 cause we use assembly but in arduino it's hard.

Before trying to use an ISR, why not start with simple things?

ISR(TIMER2_COMPA_vect){ ..code here.. }. However with your current setting the ISR gets called once every 0.5ms.

Well let's start from the start ...

Analog readings

to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.

Serial.print(digitalRead(1));

That is not reading analog pin A1, it is reading digital pin 1. If you want to read A1 you need:
Serial.print(analogRead(1));

Check the time
By far the simplest thing would be to simply check the time and take a reading when 100 ms is up.
Example:
void setup()
{
  Serial.begin(115200);
}  // end of setup

unsigned long lastReading;
const unsigned long INTERVAL = 100;  // ms

void loop()
{

  // is time up?
  if (millis () - lastReading >= INTERVAL)
    {
    lastReading = millis ();  // when we took this reading
    Serial.print(analogRead(1));
    Serial.print(" ");
    Serial.print(analogRead(2));
    Serial.print(" ");
    Serial.print(analogRead(3));
    Serial.print(" ");
    Serial.print(analogRead(4));
    Serial.print(" ");
    Serial.print(analogRead(5));
    Serial.println();
    }  // end of if time up

  // do other things here

}  // end of loop

I increased the baud rate to 115200. Why use 9600 when you are trying to print 5 x 4 characters every 100 ms?

Using timers
If you really want to use timers (and I don't see what they achieve here) I have a page about timers that describes using them, and interrupts, in some depth.
The very least you would need is a timer 2 "compare A" interrupt like this:
ISR (TIMER2_COMPA_vect)
  {
  // Timer 2 has reached its comparison value
  }


text:
Why did my program stop working when I eject the serial cable like it did an auto reset?
Arduino Uno based on 328p micro-controller board only works while I am inserting the serial cable between the board and the computer and I can control the speed of my two motors and every thing is work properly, but when I eject the serial cable it works badly and there is no control, is that some thing occurs like auto Reset?
There is always 5 volt feeding the Arduino, I get 5 volt regulated from the battery using "5v regulator", this regulated voltage is always connected to the Arduino board.

What is powering the arduino when its not connected to the computer? the arduino might be browning out without the usb power.

there is always 5 volt feeds  the arduino, i get 5 volt regulated from the battery using "5v regulator", this regulated voltage always connected to the arduino board.

5V is good, but it's not enough. Power (in this context, current) matters.
You mention 2 motors. Those things tend to draw relatively a lot of current.
Are you sure that the battery you are using can support the power requirements of the system?

@lgor Stoppa my 2 Motors feeding directly from the battery which  is 11.30 v, i know that I have just to feeds the arduino  by 5v.so no relation between the number of Motors I use.

Yes you can use the 12V battery I have found this in th Arduino Uno specs: Input Voltage (recommended) 7-12V
Input Voltage (limit) 6-20V

Try increasing the voltage of the power supply. Maybe there might be a problem with the current. The Arduino has a 5V regulator on-board, try using a 9V battery. MAKE SURE THAT YOU CONNECT TO THE DC BARREL CONNECTOR.
Good luck!

can I use 12V Battery to Feeds The arduino.

@omran You should be able to.

If you have a problem with current, a 9V battery doesn't supply much (current).


text:
counting pulses from encoder on interrupt 0 pin every 50 ms
I want to calculate the number of pulses coming from motor1 encoder pin2 (Int0) as input , and motor 2 encoder pin3 (Int1), I am working now for the first motor (just for the first motor ) so I set timer 2 to count 50 ms then throw flag in this moment I have to send the number of pulses to my screen, but not succeeded cause i see   on my screen zeros and ascii caracters but not the  number of pulses.:this my code .
 volatile int  pulses = 0;

 int flag=0;
 int setbit = 0;
 int encoder_in = 2;
 void count() {

       pulses++;
     }

  void setup()
   {

 Serial.begin(115200);
 pinMode(encoder_in, INPUT);
digitalWrite(2, HIGH); //Enable pullup

// initialize timer2
 noInterrupts();           // disable all interrupts

TCCR2A = 0x00;
 TCCR2B = 0x07;
TCNT2 = 0x64;
//EIMSK = 0x03;     // Enable external interrupt INT0
//EICRA = 0x0f;    // Trigger INT0 on falling edge

 TIMSK2 |= 0x01;  // enable timer compare interrupt
interrupts();             // enable all interrupts
attachInterrupt(0,count,RISING);

 }
  ISR(TIMER2_OVF_vect)
{
TCNT2 = 0x64;            // preload timer
 setbit=setbit+1;
  if(setbit==5)
  {
  flag=1;
 setbit=0;

   }
}

 //ISR(EXT_INT0_vect)
 //{ pulses++; }

 void loop()
{

 if (flag==1)
 {

   Serial.println(pulses);
    pulses=0;

  }
  }

i see on my screen zeros and ascii caracters not number of pulses.

Try changing volatile int  pulses = 0; to volatile int  pulses = 1; and see if you now get 1s printed. Also which ascii characters do you see? Can you give us a sample output.

Do you have anything attached to pins 0 or 1 of the Arduino?

Your technique looks convoluted to me. How about this?
volatile bool counting;
volatile unsigned long events;

unsigned long startTime;
const unsigned long INTERVAL = 50;  // ms

void eventISR ()
  {
  if (counting)
    events++;
  }  // end of eventISR

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (2, INPUT_PULLUP);
  attachInterrupt (0, eventISR, RISING);
  }  // end of setup

void showResults ()
  {
  Serial.print ("I counted ");
  Serial.println (events);
  }  // end of showResults

void loop ()
  {
  if (counting)
    {
    // is time up?
    if (millis () - startTime < INTERVAL)
      return;
    counting = false;
    showResults ();
    }  // end of if

  noInterrupts ();
  events = 0;
  startTime = millis ();
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  counting = true;
  interrupts ();
  }  // end of loop

Explanation
Using a timer to detect when 50 ms is up isn't particularly helpful in this case. You can't do printing inside an ISR, so you would have to set a flag that can be checked in the main loop.
If you are going to check a flag anyway, you may as well just check if the time is up, as my code does.
Inside the ISR, I stop adding to events if the flag counting is false. This is to stop events being changed at the exact moment it is being printed.

that's work thank you Mr Nick, but I tried to calculate for both Motor but it not Works , I Tried  many Times but not works, may you  can see my code:

whats the "Return" instruction in loop() exactly do.
I am working to calculate for the second Motor but it not work.

may you can see my code - amend your question to add this new code so I can see it.

whats the "Return" instruction in loop() exactly do - it returns from the loop() function, which then gets called again.

Check the Baud Rate in Serial Monitor. If baud rate is not correct i.e. 9600 bps then it will show garbage.
Remove the Timer and Wire Libs
add this code in void setup()
attachInterrupt(0,void_counter,RISING);

the above is for the the external interrupt input.
and attach your sensor/incoming pulse wire on Pin 2 on arduino.
make a new function like this
void_counter(){
pulses++;
}

I agree with this. But it is more appropriated as a comment.

Also he already enabled the Interrupt, but by registers

i did this change before and now too i did what you told me, but  I still see characters like {0¤0, A,P,. . }

I see the pulses on oscilloscope but still I cant see the number of pulses on my monitr


text:
Using arduino to power another usb device
Can I configure an Arduino Uno as a power source to recharge a USB device while being powered by another external power device? I asked ChatGPT for input and it gave me this code:
#include <USBHost.h> // Include USB host library if needed for specific board/shield
void setup() {
  // Initialize USB power if required (for boards with USB Host capability)
  #ifdef USB_HOST_ENABLED
    USBHost.begin(); // Only needed for USB Host shields or boards with host support
    Serial.begin(9600);
    Serial.println("USB power enabled.");
  #endif
  // Enable power to the USB port (depends on board; most Arduinos provide this automatically)
  Serial.println("System ready. USB power is being supplied.");
}

void loop() {
  // Continuously provide power to the USB port
  // No specific commands are needed for simple powering.
  // If needed, monitor the USB or other pins.
  delay(1000);
}

Does this make any sense?

https://arduino.stackexchange.com/q/96277

You are planning to plug a (say) 12V power source into the Arduino Uno power jack, and then plug something into the USB port, hoping that the Arduino's voltage regulator would provide 5V at the USB port?
I tested with my Uno, and under those circumstances it did indeed provide 5V at the USB port. However, it isn't designed to do that, and USB chargers generally negotiate with the plugged-in device via the data lines. Depending on the device, it may ignore the 5V and not charge.
Also you would be limited to a slow charge rate (say 500 mA) which may result in a slow charge.

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


text:
Sending SMS once with arduino GPRS SIM900 if an input is HIGH
I faced a problem to send 1 SMS if an input is HIGH and if it is LOW no SMS will be sent. The code not working, just sends SMS when I turn the GPRS on and after that nothing happens.
Please check this link to see the code : the code
Thank you for helping in advance.

Please avoid laziness and repost the complete question here, rather than asking everyone to go to another SE site to look at it; thanks.

repost the complete question here - AKA cross-posting. Is cross-posting a question on multiple Stack Exchange sites permitted if the question is on-topic for each site? - answer is NO.

You need to attach an interrupt to the pin which is getting HIGH and then the function connected to the interrupt will have the code to send the SMS.
Just init the GPRS with connecting to the network then just wait for the interrupt to send anything.


text:
won't verify a simple code
When I tried to verify a simple “Hello world” program I get the following message:
class hardwareSerial has no member named printin.

What does it mean?

pretty simple fix here, but in the future, please post your code as well as any errors.

Try using println instead of printin.  It stands for print line.


text:
Capture output from external device using Arduino Uno
I was unable to find this question anywhere but I want to use my Arduino Uno to capture the output of a Code 39 signal coming out of a separate device. Currently, my setup is similar to this:

I have a biometric hand reader that outputs a Code 39 signal along D1 while D0 stays at a constant 0 which can be seen here:

Ultimately, I want to use the Arduino Uno to take the input from the data line and convert the Code 39 signal to ASCII. The process should functions like this:

User enters their code into the hand reader and hand reader measures their hand
Reader outputs Code 39 signal to Arduino and software on Arduino converts barcode format to ASCII.

Note: I believe the Code 39 signal will represent something similar to this *12345*. The user ID code will always be five digits. * represent the start and stop characters for Code 39 barcode format

Arduino sends ASCII code to computer which checks remote database to ensure user is valid

I have my correct pins set as follows:
#include <SoftwareSerial.h>
#define D1 3
#define D0 2

void setup() {
    pinMode(D1, INPUT);
    pinMode(D0, INPUT);
}

Is it possible to either print out the binary representation of the signal via the Serial console or write to a file that I can view later on? My idea is to use the loop function to listen for the signals via digitalRead()
void loop() {
    digitalRead(D1);
    digitalRead(D0);
}

The last part is the thing I'm having an issue with since I can't seem to get the information printed to the serial console or written to a file. I tried this but it didn't work:
void loop() {
    foo();
}

void foo() {
    digitalRead(D1) == HIGH ? Serial.print("0") : Serial.print("1");
    Serial.println("");
    digitalRead(D0) == HIGH ? Serial.print("0") : Serial.print("1");
}

Any ideas on how to make this happen or is it impossible? I want to see the output of device so I can verify it's outputting what I think it is.
Lastly, I am using Visual Studio with the Visual Micro plugin so I can attempt to debug my code. I also have a OS X machine that has the Arduino IDE installed on it if I need a Mac for anything.
Addendum: I don't have ready access to an oscilloscope. However, I have tested this device on an oscilloscope and I did have output that seemed all wrong. I want to see what the arduino says it is to verify things before I continue with this project.

This is going to be extraordinarily difficult unless you have some more information about the other device.

Added updates! I explain how everything should work and included the type of devices I am using. Please let me know if anything needs clarification!

See if you can find existing code for interfacing a mag stripe reader - though your problem is simpler as the simulated swipes probably have a consistent speed.  You could also look at the receive half of the software serial implementation for ideas, though the signaling you are trying to receive is different.

@ChrisStratton I agree. I tried looking for conversions for Code 39 specifically but I found classes that included many other barcode formats. The conversion from Code 39 to ASCII is pretty straight forward though -- 12 bits can represent A-Z0-9%*-+. Thanks for pointing me in the right direction though!

I filled in some explanation to your problems at the beginning of my answer. If this doesn't work for you, we can work out better solutions, e.g. using a buffer.

First, let's find, what's wrong with your method. You try to poll the signal pins continously and write them out to serial. Default serial rate is 9600. Which means, that you can transmit approx. 900 characters per second. Looking at your oscillogram we can tell, that the signal you want to analyse has a base clock of roughly 2.5 kHz. Which means you definitely won't be able to sample every change of level with your method.
You can in fact use the loop() function to listen for changes, i.e. poll the signal, when you increase your serial baud rate. But I suggest using interrupts.
My suggestion is a three step process.

get the signal thoroughly recorded with all relevant information about the signal. This includes transmission to your PC via serial interface.
Analyse the signal offline. i.e. after having it received on your PC
Adapt your arduino code to decode it further before transmitting it to your PC

let's get to part 1):
read Arduino documentation on interrupts
the interrupt allows you to prevent interference of your two tasks (reading the inputs and writing to serial).
What is the interesting information? I think it's the waveform (i.e. the signal in best resolution you can deliver). You can sample your waveform at a high rate, but the resulting data volume will overwhelm your serial output. Fortunately your signal has some obvious characteristics. Which are:

obeys some timing (i.e. a clock)
has a limited transmission length (protocol frame)
has a limited transmission rate (as can be seen from oscillograph)

The best way to keep as much of the signal information by reducing the amount of serial transmission is to record the time of every level change.
Updates: buffer used, buffered output after receiving timeout
#define RECVTIMEOUT 2000 // we think, more than 2000 usec is end of transmission
#define MAXEVENTS 100

uint8_t inpin=2;
volatile unsigned long timestart=0;
uint8_t transmitLevel=LOW;

volatile uint8_t state=0; // little state machine: 0=nothing happened yet, 1=receiving data, 2=receiving timeout
volatile uint16_t tstamps[MAXEVENTS]; // we store timestamps of received symbols here
volatile uint16_t levels[MAXEVENTS]; // we store levels of received symbols here
volatile uint8_t index=0; // we save index of data here.
uint8_t count=0; // counter for later use.

volatile bool conflict=false; // will be set, if transmission conflicts with receive function.

void pinchange() // the ISR (interrupt service routine)
{
    switch(state)
    {
    case 0:
       timestart=micros();
       tstamps[index]=0;
       levels[index]=digitalRead(inpin);
       state=1;
       ++index;
    break;
    case 1:
       tstamps[index]=micros()-timestart;
       levels[index]=digitalRead(inpin);
       ++index;
    break;
    case 2:
       conflict=true;
    }
}

void setup()
{
    Serial.begin(115200); // high serial rate. don't forget to set the same in your IDE
    attachInterrupt(0, &pinchange, CHANGE); // the controller needs to know, where your ISR is.
}

void loop()
{
    switch(state)
    {
    case 1:
       if (index > 20)
       {
          if (micros()-timestart > RECVTIMEOUT)
          {
             state=2;
          }
       }
       if (index >= MAXEVENTS)
       {
          state=2;
       }

    break;
    case 2:
       for (count=0; count<index; ++count)
       {
         Serial.print(tstamps[count]);
         Serial.print(";");
         Serial.println(levels[count]);
       }
       if (conflict)
       {
         Serial.println("too less time to send data");
       }
       index=0;
       conflict=0;
       state=0;
    }
 }

This should output a fine csv with all your signal edges in microseconds, which you can paste directly to your favourite spreadsheet application. This is only for one signal. For analysing both, you have to enhance it accordingly.
Update 1
part 2)
from the gained data of our previous code version (snippet for brevity)
time signal timedifference
2614592 0   468
2615056 1   464
2615524 0   468
2616496 0   972
2616960 1   464
2617956 0   996
2618960 1   1004
2620424 1   1464
2621352 1   928
2622324 1   972
2623320 0   996

we can see two things.

The code in my first version of the answer didn't work properly. Every 1 should be followed by a 0 in column 2 and vice versa. This is apparently not true, which leads us to the conlusion, that we missed some events.
time differences seem to be multiples of roughly 470 μs. We can consider this as the length of a symbol.

So what's wrong with the code? I used noInterrupts() to stop Interrupts for copying the data. I hoped, there won't be level changes in this short period of time, but apparently this was not true. How to fix it? We better find another way to register the events and transfer them.
I recommend sticking to the interrupt technique, but changing the way we store the events and reading it out. Let's use a buffer big enough for all events of a transmission. After a transmission we can send all data without hassle via serial to the PC.
What can we expect? 0s and 1s should be transmitted alternating, with reasonable timings. If we can prove this, we can change the main loop again for decoding code 39.
part 3)

write code which stores a word of code 39 in a buffer
another code which decodes that word into a byte when the buffer is full
transmit that byte via serial

(many improvements possible).

Hi Ariser, a few things that I'm seeing: 1. I set the transfer rate and adjusted it in the serial monitor but I'm only seeing about 57 changes when I should see, at minimum, 60 changes. Any idea why that might be the case? Again, the format is Code 3 of 9. The output should be a user's five digit user code with start and stop characters. Like this: *12345* P.s. sorry it took me forever to reply! I had holiday off and now I'm finally back at work

Humm, I feared that. I thought, the occasion of receiving a pin change while blocking interrupts was very rare, but I'm proved wrong. Were you able to extract the clock from the received data? I'll update my answer, but it takes some time to brew something usable.

I don't know what you mean by "extract the clock from the received data"

If you get the timing information via serial monitor, you can calculate the clock frequency, because the time between two adjacent level changes must be either one or two clock cycles long. Once you have the length of a clock cycle, it is easier to build some code to decode the data on the arduino instead of transmitting every bit to the PC.

Well, I copied the code you had and used that. I got an output but I can't really make sense of it. I know the device outputting the signal is transferred at 9600 baud. Here is that data: Trial 1 and Trial 2. I appreciate all your help!

Ok, I can make some sense of it. I'm currently typing some more into the answer. Another question: The transmission of the user ID is triggered directly by your action (authentication), isn't it?

Yes. User types in their code and scans their hand. The hand scanner just verifies the users hand dimensions for internal purposes only.

Let us continue this discussion in chat.


text:
How do I activate emulation in the Coddeblocks Arduino IDE
I stumbled upon this question here, so I tried the Codeblocks alternative. After opening an Arduino Project, and leaving all options to default, I ran the Arduino version of the Hello World. A popup opened that requests a serial port to move on. What error did I do?
If more details are needed I'll answer the comments. Thanks in advance!

A serial port seems like a reasonable thing to ask for, are you sure it was in error?

Because it was an emulator rather than an launcher.

I have not done extensive testing with the simulator but here is what you do open code blocks start a new project. Then under the target choose simulator. See the picture for details.
I just tested it out for the simple program but this looks pretty cool.


text:
Serial, Numbers sent as Floating Point and Characters are different at 1e-8 level
I have some code that generates random numbers on the Arduino, it then sends these random numbers firstly, using Serial.print(float data,int lenght) and as a floating point number using the following function
void send_float (float arg)
{
  // get access to the float as a byte-array:
  byte * data = (byte *) &arg;

  // write the data to the serial
  Serial.write (data, sizeof (arg));
  Serial.println();
}

I then receive this data using python, take the absolute difference of the two values, discard any differences less than the length with which I send the string and output the rest to the screen.
I observe two things, a) Fluctuations of the order with which I send the data (ie. if I send to 6 decimal places then I see fluctuations of ~1e-6), this is reasonable and b) I see fluctuations of absolute value 1e-8 or lower independent of what accuracy I send the string.
Even if I send the string to 11 decimal places, when I compare against the float I see fluctuations up to but not above 1e-8.
Why? This doesn't make any sense. My full code is actually the answer to an old unanswered stack exchange question

The precision of a float is around 7.2 decimal digits. https://en.wikipedia.org/wiki/Single-precision_floating-point_format

This is a somewhat dumb question but, in case anyone else searches it as pointed out:

The precision of a float is around 7.2 decimal digits. en.wikipedia.org/wiki/Single-precision_floating-point_format –  BrettAM

So in python the number goes float -> double -> decmial, whereas on the arduino the number goes float -> decimal. The additional step of the double in the case of python causes the discrepancies. But anything after the 7th decimal place is nonesense anyway.


text:
Why is my interrupt code not working?
Background
I'm trying to write code to read signals from a six-channel RC receiver on an Arduino Mega 2560. Currently I am keeping the code to just read one channel to make things easy to troubleshoot. The problem is my shared variable is not updating, leading me to believe that my interrupt service routine is not detecting any rising edges.
I thought my receiver was broken, so I tested it using the standard Arduino attach interrupt function. It worked perfectly, so my receiver is fine.
I used Serial.print() to see if my volatile channel variable was updating (that is, change its value to the channel 1 flag value). It was not updating, so my ISR must be wrong. You can find the original code in the blog post.
What's wrong? I'm out of ideas.
#include <PinChangeInt.h>

//Pin assignment
#define channel1PIN 10

//Bit flags
#define Channel1FLAG 1

//Flag holder
volatile uint8_t bFLAGUPDATESHARED;

//Shared variables: Accessed by the interrupt service routine and read in 'void loop'.
volatile uint16_t unCHANNEL1SHARED;

//Start time variables: These are used to set the start time of the rising edge of
//a pulse. They are only accessed by the ISR, and thus they are unsigned integers and
//not volatiles.

uint32_t ulCHANNEL1START;

void setup()
{
  Serial.begin(9600);
  Serial.print("RC Channel PWM Read Interrupt Test");

  //PinChangInt library function. Used to set attach interrupts.
  PCintPort::attachInterrupt(channel1PIN, calcCHANNEL1, CHANGE);
}

void loop()
{
  //In-loop variables to hold local copies of channel inputs.
  //This is static so it retains values between call loops.
  static uint16_t unCHANNEL1IN;

  //The in-loop copy of the bSHAREDFLAGUPDATE volatile flag holder
  static uint8_t bFLAGUPDATELOCAL;

  //Check to see if any channels have received signals. If so, copy
  //shared variables to local in loop variables.
  if (bFLAGUPDATESHARED)
  {
    //Switch off interrupts when I copy shared variables to local variables
    noInterrupts();

    bFLAGUPDATELOCAL = bFLAGUPDATESHARED;

    if (bFLAGUPDATELOCAL & Channel1FLAG)
    {
      unCHANNEL1IN = unCHANNEL1SHARED;
    }

    bFLAGUPDATESHARED = 0;
    interrupts();
  }

  Serial.println(unCHANNEL1IN);

  //Clear local update flags copy as all values have been copied to local variables
  bFLAGUPDATELOCAL = 0;
}

void calcCHANNEL1()
{
  if (digitalRead(channel1PIN) == HIGH)
  {
    //If pin goes high, start timer and set ulCHANNEL1START to timer start
    ulCHANNEL1START = micros();
  }
  else
  {
    //If it is not rising, it must be falling so set shared
    //variable to current time-start time
    unCHANNEL1SHARED = (uint16_t)(micros() - ulCHANNEL1START);

    //Tell that channel 1 has received a signal
    bFLAGUPDATESHARED |= Channel1FLAG;
  }
}

Try simplifying your code. Have the ISR light up an led, for example. I don't see anything inherently wrong.

I figured it out. For some reason, it only works on pins 10,11 and 12. I don't know why though. PinchangeInt should work on any digital pin

But you are using pin 10? Anyway; glad you got it working.

Only some ports on the Atmega2560 support pin-change interrupts, specifically ports B, E (bit 0), J (bits 0 to 6) and K.
Looking at the reference schematic that means that these pins on the board are supported:
     Chip
Name  Pin  Pin on board
-----------------------

Port B

PB0 - 19 - D53 (SS)
PB1 - 20 - D52 (SCK)
PB2 - 21 - D51 (MOSI)
PB3 - 22 - D50 (MISO)
PB4 - 23 - D10
PB5 - 24 - D11
PB6 - 25 - D12
PB7 - 26 - D13

Port E

PE0 - 2 - D0 (RXD0)

Port J

PJ0 - 63 - D15 (RXD3)
PJ1 - 64 - D14 (TXD3)
PJ2 to PJ6 - not connected on board

Port K

PK0 - PK7 - (89 - 82)  - A8 - A15

Thus you can see that D10 to D12, which you say works, are in that list. Other random ones would not be.

SoftwareSerial
You can see confirmation on the page for SoftwareSerial where it says:

Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

This is because SoftwareSerial uses pin-change interrupts to detect incoming serial data, and thus the disclaimer on that page about which pins it will work with.

Atmega2560 pin-outs

PinchangeInt should work on any digital pin

Note that the Atmega328P (as used in the Uno) has less ports, and all are available for pin-change interrupts on that board.

This can't be right. The page first linked by OP claims pins 2, 3, 18, 19, 20, and 21 can be used for interrupts. These map to PE4, PE5, PD3, PD2, PD1, and PD0, according to https://goo.gl/DvHEUA  and https://goo.gl/xAwBGM For my part, I'm more concerne with whether PORTC can be used, as in ros_arduino_bridge: https://goo.gl/rq6yQO

The linked page refers to external interrupts however the OP is using pin change interrupts as you can see from #include <PinChangeInt.h>. The pin change interrupt pins are the ones I listed.

I see. I had an inkling that might be the distinction, but assumed that all pins capable of external interrupts would also be capable of pin change, though not the other way around.

On the ATmega1280/2560, only ports B, J, F, and K have pin change interrupt capability. These map approximately to pins 10 through 15, 50 through 53, and A6 through A15 (although part of port J is unmapped to Arduino pins, therefore PCINT11 through PCINT15 are unavailable on the Arduino Mega/Mega 2560).


text:
Arduino unable to read from XBee Series 2
An XBee Series 2 is set to Router AT whose TX and RX pins are connected to an Arduino Nano's Rx and Tx pins respectively. The Arduino is connected to a Mac OSX via USB.
A second XBee Series 2 is connected to a Windows system via USB. It is set to Coordinator API mode.
Using the sketch below on the Arduino, a packet is sent from the Router AT XBee to the Coordinator API XBee, which is seen by XCTU as a Explicit RX frame. However the Arduino LED should blink once if it received a reply packet (should it?)
On another test, I wrote a script to send a frame for the Coordinator API XBee to send to the Router AT XBee. Once again the Arduino LED does not blink, and nothing is seen using Arduino's Serial Monitor.
Testing the Coordinator API XBee
Using the same script to send a packet from Coordinator API XBee to itself, the packet was received as well as a delivery confirmation packet. This shows that both the Coordinator API XBee and the script are working.
// Delivery confirmation
received:  { type: 144,
  remote64: '0013a20040a74613',
  remote16: '0000',
  receiveOptions: 1,
  data: [ 116 ] }

// Received the packet sent to itself
received:  { type: 139,
  id: 1,
  remote16: '0000',
  transmitRetryCount: 0,
  deliveryStatus: 0,
  discoveryStatus: 0 }

Testing the Arduino Sketch Code
Using the same Arduino sketch which continuously sends API frames to the Coordinator, I connected the Router AT XBee's RX pin to Arduino's RX pin, so the frames the Arduino are sending out are going back into its RX pin.
This causes the Arduino's LED to light up! So there is nothing wrong with the code.
Problem: Does this mean the Router AT XBee is not configured properly? I do not think its TX pin is damaged because XCTU can still read the settings off this XBee. Any ideas on how we can troubleshoot this?
Arduino Sketch (Connected to Router Xbee)
#include <XBee.h>

XBee xbee = XBee();
uint8_t payload[] = { 0, 0 };

// SH + SL Address of receiving XBee
XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x40a74613);
ZBTxRequest zbTx = ZBTxRequest(addr64, payload, sizeof(payload));
ZBTxStatusResponse txStatus = ZBTxStatusResponse();

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

    Serial.begin(9600);
    xbee.setSerial(Serial);
}

void loop() {
    xbee.send(zbTx);
    delay(1000);

    xbee.readPacket();
    if (xbee.getResponse().isAvailable()) {
        // Response received, blink LED once
        Serial.println('resposne!');
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
        delay(1000);
    }
}

I'm a little confused about how you're sending the Router AT packet to the Coordinator in API mode. Sending out via AT is a Serial.print("sample");. Whereas the sketch you have above only shows us the Coordinator's outwards bound packet. Does that library handle AT mode as well? And what about addresses? You don't need to explicitly set the address outwards of the Coordinator (although it wouldn't hurt), the Coordinator should/can broadcast it's message. Can you confirm the ATDL of the Router is 0x0 or 0xFFFF if ATDH is 0x0.

Just as another afterthought, do put the pertinent XBee settings in the post to confirm you've got it right.  Copy them from the digi software. I just confirmed from https://code.google.com/p/xbee-arduino/ that the library doesn't work in AT mode. Also, it does require ATAP=2 so that's something else to check.

@Madivad I'm so sorry, the arduino code is for Router AT Xbee, not Coordinator XBee. Made the change in the question

As I mentioned in my comments to your question, if you are using this library
then it doesn't actually support AT mode. In fact, AT mode (otherwise known as Transparent Mode) is simply attached to the Serial port and accessed directly through the Serial object.
Example: put this into your Arduino attached to the AT Router.
#define LED 13

void setup() {
    pinMode(LED, OUTPUT);
    Serial.begin(9600);
    Serial.println("\nXBee AT communications test");
}

void loop() {
  static unsigned long previous = millis()/1000;
  if(previous != millis()/1000){
    previous = millis()/1000;
    char buffer[5];
    sprintf(buffer,"%04i",previous);
    Serial.println(buffer);
   digitalWrite(LED, !digitalRead(LED));
  }
}

Then open the console on the XCTU software on the API Coordinator watch the packets.

You will see above the received packets from the router. Because the coordinator is in API mode, you see it like this. (In AT mode, you will see the raw packets.
Ichose numbers to send because they are easy to read in this form. Packet 0102 appears in the packets data as 30 31 30 32 0D 0A
In AT mode there is no packet confirmation, validations, status or anything. They are all handled "transparently".
As a side note, I've seen many references that both XBees need to be in the same mode. That is, in fact, incorrect. If we modify our source to include Serial.read you would see data the other way as well.
edit: I thought I would add communications between AT Router and API Coordinator. I have modified the code in the Router to receive a constructed packet from the Coordinator via the XCTU software.
#define LED 13

boolean serialComplete = false;
char bufferIn[64];
char bufferOut[5];
int count=0;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);
    Serial.println("\nXBee AT communications test");
}

void loop() {
  static unsigned long previous = millis()/1000;
  if(serialComplete) {
    Serial.println(bufferIn);
    serialComplete=false;
    count = 0;
    memset(bufferIn,0,sizeof(bufferIn));
    digitalWrite(LED,!digitalRead(LED));
  }
  if(previous != millis()/1000){
    previous = millis()/1000;
    sprintf(bufferOut,"%04u",(uint16_t)previous);
    Serial.println(bufferOut);
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    if (inChar == '\n' || inChar == '\0') {
      bufferIn[count++]=0;
      serialComplete = true;
    } else {
      bufferIn[count++] = inChar;
    }
  }
}

Then in XCTU construct a packet for the Coordinator. I'm using version 6.1.0.

and click "the create frame using form generator tool"

here is the packet being received by the router. I am only sending 9999 nul terminated.

Then once the pair are running, you can send the constructed packet from the XCTU software and it will be received by the router.

#include <XBee.h>
uint8_t text[] = {'H', 'e', 'l', 'l', 'o',' ','T','H','I','S',' ','I','S',' ', 'A','R','D','U','I','N','O'};
XBee xbee = XBee();
XBeeAddress64 remoteAddress = XBeeAddress64(0x00000000, 0x0000FFFF);//64 address of remote xbee:
ZBTxRequest zbTx = ZBTxRequest(remoteAddress, text, sizeof(text));// api 2 Tx request frame
ZBRxResponse zbRx = ZBRxResponse();// reading remote xbee response:
void setup()
      {
        Serial.begin(9600);
        xbee.setSerial(Serial);
        Serial.println("starting up yo!");
      }
void loop ()
      {
         xbee.readPacket();// This will read any data that is available:
         if (xbee.getResponse().isAvailable())//Now, to check if a packet was received:
          {
            if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE)
              {
                xbee.send(zbTx);//sending data to remote xbee:
              }
          }
      }


text:
DS18B20 Temperature Sensor return as float function returning null 50% of the time
I just got an DS18B20 Temperature sensor and am trying to modify the example code to use a function instead. Below is my getTemp function. It's working but returning results with a 0 value part of the time for example:

Temperature = 72.39
  Temperature = 0.00

If I add Serial.print(fahrenheit); within the function I am always provided with the correct temperature. I though this may have to do with needing a delay but adding delay(5000); in my loop didn't help.
I'm assuming it's something simple I'm not understanding about how floats return.
#include <OneWire.h>

// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library

OneWire  ds(2);  // on pin 10 (a 4.7K resistor is necessary)

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

float getTemp(char tScale) {
  byte i;
  byte present = 0;
  byte type_s = 0;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    ds.reset_search();
    delay(250);
    return false;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();

  }

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  if (tScale == 'C') {
    return celsius;
  }
  else if (tScale == 'F') {
    return fahrenheit;
  }

}
void loop(void) {
    Serial.print("Temperature = ");
    Serial.println( getTemp( 'F' ) );

}

Edit:
Interesting enough, adding an if statement to the loop fixes this, however. I'd still like to understand what is going on:
void loop(void) {
  if ( getTemp( 'F' ) == 0 ){
    Serial.print( "Temperature = " );
    Serial.println( getTemp( 'F' ) );
  }
}

Could you please clarify what you mean by 'fixes it' in your edit? Since your getTemp() occasionally returns 0, it's clear that you filter for zero by checking for getTemp('F') == 0.

I guess what I mean is that if getTemp is set to 0 then the correct temperature is being displayed to serial (never showing Temperature = 0.00 It only returns the actual temperature.

So you skip the problematic instances of !ds.search(addr) (by just polling the sensor twice in close succession), ignoring the underlying problem. :)

There are apparently a lot of alleged "DS18B20" devices on the market which do not meet the timing of the published spec.  To try to use them you will need to slow things down.  You can somewhat offset the time cost of doing so by running in a lower bits mode, but some of the published example code which appears to handle various bit widths in fact horribly misinterprets anything but the widest, and has to be fixed.  No, I don't have a repaired copy at hand to quote from.

@Chris Stratton: I think it's a good idea to look into the actual issue of the DS18B20 communication failing. BandonRandon: Why don't you try the DallasTemperature library? It even comes with a Tester sketch and other useful stuff.

You have intermittent communication problems.
Your address search occasionally fails and getTemp() returns false. In C++ (and many other languages) false will be implicitly cast to (int) 0, (float) 0.0f, and so on.
Your getTemp() function  also is difficult to debug because the multiple return statements have different meaning.
After the delay(250); you do a return false; in order to skip the rest.
In the example at https://www.pjrc.com/teensy/td_libs_OneWire.html the meaning of the return statement(s) is different. There the return happens within the void loop() function, where it simply means to interrupt the current execution (without returning a value) and continue with the next loop.
While it is generally okay to have multiple return, it can sometimes be problematic and I recommend to avoid it.
If you want to clean this up while still preserving the ability to detect a fault, you have a couple of options (order from most to least recommended):

do the setup/checking in a different function (and only call the second one if the first one succeeded), i.e. if (isReady()) { Serial.println(getTemp()); }
set a separate error variable, i.e. error = true; return 0; (and then check error later)
define a 'default' value that you interpret as an error (and never expect to be a temperature), i.e. return NAN; // not a number

Is there actually a reason why you use the sensor the hard way and not employ a library for it (like you do with OneWire)? There are Dallas temperature libraries that employ OneWire, e.g. https://github.com/milesburton/Arduino-Temperature-Control-Library.

Rather than -460.0f, which looks like a silly value, I would return NAN (i.e. not a number). It more clearly conveys the meaning of “not a valid value”. Serial.print() displays it as “nan”.

Yeah, out-of-range was just the first thing I came up with. And since it's my least recommended solution, I still regard it as inferior, even when using NAN. I edit my answer accordingly.

Thanks switched to the Miles Burton Library and everything is working as expected and my code looks much cleaner.


text:
Over voltage on Arduino and Ardumoto
I am using Arduino Leonardo and Ardumoto to drive 2 12v motors running at 1.3 amps each.
I purchased a rechargeable battery of 12V with 5AH
I first started by plugging in the battery to the Arduino via the barrel jack. Arduino then sparks and is fried.
I read somewhere that I wasn't supposed to hook it up to the Arduino and to hook it up to the VIN ports in the Ardumoto. I purchased a new Arduino and plugged in the Positive and negative from the battery to the ports and now the Ardumoto board fried (copper lining on board burnt off).
I'm reading online and from what I've gathered, the Ardumoto can handle a max of 18 volts and a maximum of 2 amps per each output. I'm obviously missing something and would not like to fry my boards next time.
Please assist?

Are you sure you got the polarity right?

Would you post a diagram (a photo of something hand drawn will be fine) and, maybe photos of your wiring?

Were the motors connected up at the time? Any chance of a short there?

That connector on the ardumoto is directly connected to VIN. And so is the barrel jack on the leonardo. The only reason it is preferred to use the vin on the ardumoto, is that the vin trace on the arduino board is not made for 4 amps. But in both cases nothing should have blown up like it did. You can maybe still fix the board by soldering a wire between the vin header just next to the screw terminal, and the vin-pin that goes down into the arduino. That way you bypass the blown trace.

From your description, everything should be wired correctly. It should not have failed.
Unfortunately, testing this sort of thing with a 5 amp-hour lead-acid battery is not a great way to get started, since a battery that large can source a lot of current, and doing anything wrong will likely produce immediate and spectacular failure.
Really, the only think I can think of is that you have the polarity of the output lugs/pins on the battery backwards. Buy a $5 multimeter, and check them.


text:
Is my Arduino UNO fried?
The title sums it all up. While testing  the new proximity detector I bought off of Amazon, a spark flew from some random area and my Arduino's On LED went off while its Loop LED stayed in a dim state. I am here to ask you guys if this basically counts my Arduino as fried and that I need a new one, or if I should wait and see if it works again, being that I wrote this 5 minutes after the thing happened.
Thanks in advance,
afroraydude

It's hard to tell without further testing. Do the following:

Remove the Uno from the faulty circuit, making sure you remove all the wiring from the Arduino board.
Plug the Uno into the USB port. Does the ON LED light up? Does the built-in LED on D13 blink three times? (this should happen if you had the optiboot bootloader)
Remove the USB cable and plug the Uno to a 9V source through the barrel power connector. Do the same test above.
Can you upload the Blink sketch? If you can, does it make D13 LED blink once a second?

Report your findings by updating your question.

I did the unplugging and stuff, the ON LED is dim now, and the LED on D13 does not blink 3 times, it just stays on but is dim. I cannot upload the Blink Sketch, the computer does not get the Arduino on the COM port.

That's really bad... I think that this is enough evidence that it's fried. Can you check with a digital multimeter what's the voltage on Vin, +5V and 3V3 pins?

The microprocessor also gets warm, forgot to mention that.

Definitely fried. Post your circuit so we can tell you what went wrong.

i cannot due to the stuff i used, external stuff, i have realized that i shorted it

Don' get all fustrated now. It might be just the chip, the arduino chip is fairly cheap, and can be removed by lightly wiggle a screwdriver below it, buy one like $5 and replace it and burn a new bootloader on it.


text:
A question on physical locations of the registers in ATmega328P
When I read about registers I always encounter the following illustration:

So there are 32 registers in the above diagram. They are processor registers.
But in the data-sheet of ATmega328P at page 428 there is a section called "Register Summary".
Here in that list there are much more than 32 registers. Do the rest of the registers physically stay somewhere else?
Lest's take an example of ADMUX register. Where is that register physically inside the DIP? It is not one of the 32 registers? And if stays somewhere else how does it connected to the ALU?

Physical location or memory location? The datasheetss has the later.

I mean is ADMUX one of those 32 reg?

In the table that you refer to, ADMUX is mapped to memory location 0x7C.

No, R0 to R31 are General Purpose registers for use in your application. The compiler usually takes care of using them appropriately. All the other registers are special purpose and can only be utilised explicitly. Those registers form the state machine of the MCU.

Is GPIO a subset of SFR?

And are they all SFT and 32 tegistrts all inside sram?

You are confusing CPU registers and SFRs, Special Function Registers.
CPU registers only exist within the CPU core. SFRs exist within the RAM bus's memory map.
CPU registers are used by the CPU to execute instructions and do calculations, etc. SFRs are a part of the logic of the rest of the chip and directly affect the working of the various peripherals.
As far as the CPU is concerned an SFR is just a bit of SRAM, but it affects physical workings when written to, and reflects physical states when read from.

Chapter 8.3 in the ATMEGA328P datasheet (ver 10/2014) has a memory map of SRAM. Here it uses the term IO Register and Extended IO Register to refer to the Special Function Registers.

Every manufacturer has their own name for them. SFR is an accepted standard name for the concept.

Are those 32 registers called GPIO?

No. They are called registers. They are the internal memory of the CPU. You have very limited access to them in C, but in assembly they are all you have for doing any form of calculations with.

Some wrote under my question that they re called general purpose registers. Is that right?

Yes, since the CPU can use them for any purpose it needs. Really, unless you are writing assembly language programs, you don't even need to know about the existence of these 32 registers. They are like the spark plugs in your car - you don't need to know about them to be able to drive it.


text:
How is a local variable address retrieved/returned inside the CPU of Arduino?
How is the address of a local variable retrieved in Arduino's ATMEGA328 micro-controller?
Lets say somewhere inside the main we have lines as:
int x = 5; //a variable declared and value of 5 stored in SRAM ??
int  *p; // a pointer is declared
p = &x; // p holds the address of the variable x

What happens above is &x retrieves the address of the variable x.
But how does this happen in a lower level?
Which function retrieves the address of a variable and how does it do it?
How does that function know the address of the variable x?
I'm wondering what happens step by step after the instruction comes to the instruction register.
edit: Another question for int x = 5; is 5 stored at CPU register or SRAM?
.

LDS. It doesn't, the compiler does.

oh do you mean when the code is running inside the micro-controller the address "was" retrieved already before by the compiler and the instruction code operating inside the microcontroller holds that address already? im sorry i just want to clarify. very new to subject.

Yes, the compiler maintains a symbol table for all symbols in the code. And for any actual dynamic addresses there are indirect opcodes that work with those.

Are you asking: how does a compiler translate C++ code into assembler? This is rather a broad question. Perhaps better suited to Stack Overflow.

But how does this happen in a lower level? - you are asking how a compiler works. This is really nothing to do with the Arduino per se.

Disassemble your program and you will get your answer, at least for that particular program. You will find instructions on how to disassemble here and elsewhere on the Web.

Just as an experiment, I tried the following:
void bar(int *);

void foo()
{
    int x = 5;
    int *p;
    p = &x;
    bar(p);
}

And here is what gcc translated that into (comments mine):
__SP_H__ = 0x3e
__SP_L__ = 0x3d
__tmp_reg__ = 0
foo:
    push r28            ; save r28
    push r29            ; save r29
    rcall .             ; make room on the stack
    in   r28, __SP_L__  ; copy SP into r29:r28 = Y: LSB...
    in   r29, __SP_H__  ; ... and MSB
    ldi  r24, lo8(5)    ; store x in a register: LSB...
    ldi  r25, 0         ; ... and MSB
    std  Y+2, r25       ; copy x into the stack: MSB
    std  Y+1, r24       ; ... and LSB
    movw r24, r28       ; r25:r24 = Y
    adiw r24, 1         ; r25:r24 = Y+1 = &x
    call bar            ; call bar(&x);
    pop  __tmp_reg__    ; release the two bytes...
    pop  __tmp_reg__    ; ... of stack space
    pop  r29            ; restore r29
    pop  r28            ; restore r28
    ret                 ; return

Expanded comments:
The instruction rcall is normally used to call another function. Here
it's calling the following instruction, so it doesn't affect the program
flow. It's only a trick: as rcall saves the return address into the
stack, it makes the stack grow by two bytes, and is used here as an
optimized way of reserving to bytes of stack space for storing x.
Next you see the stack pointer being copied into the r29:r28 register
pair, also known as “Y pointer”. The stack pointer is a CPU register
holding the address of the top of the stack, namely of the first free
slot. As the stack grows towards the bottom of the RAM, at this point
it looks like this:
address | SP = Y | Y+1 | Y+2  | Y+3 | Y+4 | Y+5  |  Y+6  |...
--------------------------------------------------------------
data    | (free) | room for x |  saved Y  | return addr. | ...

Next you see the value of x being placed first in a register pair
(r25:r24), then on the stack at the addresses Y+1 and Y+2.
The instruction mowv copies a register pair, so now you have a copy of
the stack pointer in the pair r25:r24. The instruction adiw adds an
immediate value (here, 1) to a register pair, so that now r25:r24 holds
the address of x. Finally, the function bar() is called: per the
calling convention, the argument is to be passed in the r25:r24 pair.
A few final remarks:

I passed the pointer to another function just to make gcc believe that
I am actually using that pointer, otherwise it would optimize out
the whole code into a function that does noting but return.
You don't need to create a pointer variable to hold the address of
x: calling just bar(&x) compiles into the very same assembly.
Most local variables are assigned to CPU registers. Only because I am
using the address of x did this variable get stored in the stack.
The compiler output is very sensitive to the surrounding code, the
compiler version, the optimization options, and so on. So you should
consider all this as only an example.
If you do not completely understand what each instruction is doing,
you should now take a look at the AVR Instruction Set Manual

That manual says: "Registers concatenated with the X-, Y-, and Z-registers enabling indirect addressing of the whole data space on MCUs with more than 64KB data space, and constant data fetch on MCUs with more than 64KB program space" Does that mean X Y Z registers are never used in an ordinary Arduino UNO since it has ATMEGA328 which has only 2KB RAM?

@user16307: You are quoting the description of the RAMPX, RAMPY and RAMPZ registers, which are not the same as X, Y and Z. The ATmega328P does not have RAMP registers.

Another question for int x = 5; is 5 stored at CPU register or SRAM?

That depends entirely on how the compiler optimizes your code. If you never refer to x in your code the compiler may discard that statement entirely. Or it might use a CPU register. It might use RAM.

To answer your question you first have to understand what exactly happens when a function is called.
The very first operation, in what is known as the function prologue, a stack frame is allocated. This stack frame contains, amongst other things:

The return address of the function
Copies of any CPU registers that the function uses
Storage space for any local variables

This may be through the use of a dedicated PUSH instruction or by manual manipulation of the stack pointer and writing of data direct to memory, depending on the CPU architecture.
During this process the compiler says "This variable is stored at stack offset X" for each variable. From that point on there is no "variable" as such, only a stack offset. All accesses to the variable are actually accesses to the memory at the location it already knows about within the stack frame.
When you then access the address of a variable you are basically saying "instead of getting me the contents of this memory address, just give me the memory address". Since the compiler already knows what that offset is it just adds it to the address of the stack frame and gives you that.
So if your stack frame is at 0x500 (for example) and the variable x is at offset 0x004:

Accessing x gives you the contents of address 0x500 + 0x004
Accessing &x gives you the value 0x500 + 0x004

Assigning p to &x creates another variable in the stack frame (which could be at offset 0x006 say). To that variable is assigned the value 0x500 + 0x004 (or 0x504 of course).
However, that is all from the point of view of a non-optimising compiler.  The compiler itself may go "There is no need to store this value in memory, I have enough registers to keep it internally". So it doesn't actually allocate anything on the stack for the variable, it just "remembers" it in a register. That makes the function shorter and faster since there are less memory accesses.
There are a couple of variable attributes that affect how these decisions are made. The first is volatile which tells the compiler that "this variable must be stored in RAM and, further to that, don't trust that the value in RAM is the same since I last looked at it". This is essential for variables shared between the main loop and an interrupt context, since the compiler doesn't know if the interrupt is going to change the value of the variable.
volatile int foo;

The second is the register attribute.  This suggests to the compiler that it might like to store this variable in a register to make things faster. This flag is seldom seen any more since the optimiser generally does a much better job of working out which variables would fit better in a register than a human can. It's very much a deprecated attribute now.
register int foo;

I'm mostly asking what happens inside the uC after the compilation. When the micro-controller running the program counter(PC) starts to fetch instruction codes to  Instruction register So you see there is a movement here. Im talking about this movement inside the uC. I can understand  how the program data ca be sent to a CPU register by the micro code. It decodes the data from the instruction register and does its job. But what kind of instruction makes the micro code to retrieve the address of a variable stored and how does it do is mystery to me. But I will reread your answer again and again

There is no instruction that retrieves the address of a variable. There is no variable. There is only the address at which the compiler has placed the contents of the variable (the offset in the stack frame). It's what you do with that address that counts. You can use it as a number (it's just a number after all) or you can retrieve the value from memory at that address.

The address is the variable. The variable is the address. We just give it a name for our own convenience. The compiler just knows it as (SP+4) (for example).


text:
CC3000 Blocking All Wireless Communication
I'm trying to send an email using an Arduino Uno and a Sparkfun CC3000. When I plugged in the arduino to the computer with the code I wrote for it, all wireless communication in the room I was in went down. This includes both computers that were there, my cell phone, even my Pebble Watch got disconnected. Any idea on why this happened and how to fix it? I replicated this numerous times to make sure it wasn't a fluke.
Here is my code
PingTest.ino
CC3000 Ping Test
Shawn Hymel @ SparkFun Electronics
February 1, 2014
https://github.com/sparkfun/SFE_CC3000_Library

Connects to the access point given by the SSID and password and
waits for a DHCP-assigned IP address. Pings the give website or
IP address and waits for a response.

The security mode is defined by one of the following:
WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA, WLAN_SEC_WPA2

Hardware Connections:

 Uno Pin    CC3000 Board    Function

 +5V        VCC or +5V      5V
 GND        GND             GND
 2          INT             Interrupt
 7          EN              WiFi Enable
 10         CS              SPI Chip Select
 11         MOSI            SPI MOSI
 12         MISO            SPI MISO
 13         SCK             SPI Clock

Resources:
Include SPI.h and SFE_CC3000.h

Development environment specifics:
Written in Arduino 1.0.5
Tested with Arduino UNO R3

This code is beerware; if you see me (or any other SparkFun
employee) at the local, and you've found our code helpful, please
buy us a round!

Distributed as-is; no warranty is given.
****************************************************************/

#include <SPI.h>
#include <SFE_CC3000.h>
#include <SFE_CC3000_Client.h>
#include <Client.h>
#include <Temboo.h>
#include "TembooAccount.h" // Contains Temboo account information

// Pins
#define CC3000_INT      3   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       9   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno

// Connection info data lengths
#define IP_ADDR_LEN     4   // Length of IP address in bytes

// Constants
char ap_ssid[] = "comcast";                  // SSID of network
char ap_password[] = "gooddays";          // Password of network
unsigned int ap_security = WLAN_SEC_WPA2; // Security of network
unsigned int timeout = 30000;             // Milliseconds
char remote_host[] = "www.sparkfun.com";  // Host to ping
unsigned int num_pings = 3;    // Number of times to ping

// Global Variables
SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);
SFE_CC3000_Client client = SFE_CC3000_Client(wifi);

int numRuns = 1;   // Execution count, so this doesn't run forever
int maxRuns = 10;

void setup() {

  ConnectionInfo connection_info;
  IPAddress ip_addr;
  IPAddress remote_ip;
  PingReport ping_report = {0};
  int i;

  // Initialize Serial port
  Serial.begin(115200);
  Serial.println();
  Serial.println("---------------------------");
  Serial.println("SparkFun CC3000 - Ping Test");
  Serial.println("---------------------------");

  // Initialize CC3000 (configure SPI communications)
  if ( wifi.init() ) {
    Serial.println("CC3000 initialization complete");
  } else {
    Serial.println("Something went wrong during CC3000 init!");
  }

  // Connect and wait for DHCP-assigned IP address
  Serial.print("Connecting to: ");
  Serial.println(ap_ssid);
  if(!wifi.connect(ap_ssid, ap_security, ap_password, timeout)) {
    Serial.println("Error: Could not connect to AP");
  }

  // Gather connection details and print IP address
  if ( !wifi.getConnectionInfo(connection_info) ) {
    Serial.println("Error: Could not obtain connection details");
  } else {
    Serial.println("Connected!");
    Serial.print("IP Address: ");
    for (i = 0; i < IP_ADDR_LEN; i++) {
      Serial.print(connection_info.ip_address[i]);
      if ( i < IP_ADDR_LEN - 1 ) {
        Serial.print(".");
      }
    }
    Serial.println();
  }

  // Perform a DNS lookup to get the IP address of a host
  Serial.print("Looking up IP address of: ");
  Serial.println(remote_host);
  if ( !wifi.dnsLookup(remote_host, &remote_ip) ) {
    Serial.println("Error: Could not lookup host by name");
  } else {
    Serial.print("IP address found: ");
    for (i = 0; i < IP_ADDR_LEN; i++) {
      Serial.print(remote_ip[i], DEC);
      if ( i < IP_ADDR_LEN - 1 ) {
        Serial.print(".");
      }
    }
    Serial.println();
  }

  // Ping IP address of remote host
  Serial.print("Pinging ");
  for (i = 0; i < IP_ADDR_LEN; i++) {
    Serial.print(remote_ip[i], DEC);
    if ( i < IP_ADDR_LEN - 1 ) {
      Serial.print(".");
    }
  }
  Serial.print(" ");
  Serial.print(num_pings, DEC);
  Serial.println(" times...");
  if ( !wifi.ping(remote_ip, ping_report, 3, 56, 1000) ) {
    Serial.println("Error: no ping response");
  } else {
    Serial.println("Pong!");
    Serial.println();
    Serial.print("Packets sent: ");
    Serial.println(ping_report.packets_sent);
    Serial.print("Packets received: ");
    Serial.println(ping_report.packets_received);
    Serial.print("Min round time (ms): ");
    Serial.println(ping_report.min_round_time);
    Serial.print("Max round time (ms): ");
    Serial.println(ping_report.max_round_time);
    Serial.print("Avg round time (ms): ");
    Serial.println(ping_report.avg_round_time);
    Serial.println();
  }

  // Disconnect
  if ( wifi.disconnect() ) {
    Serial.println("Disconnected");
  } else {
    Serial.println("Error: Could not disconnect from network");
  }

  // Done!
  Serial.println("Finished ping test");

}
    TembooChoreo SendEmailChoreo(client);
void loop() {
  if (numRuns <= maxRuns) {
    Serial.println("Running SendEmail - Run #" + String(numRuns++));

    //TembooChoreo SendEmailChoreo(client);

    // Invoke the Temboo client
    SendEmailChoreo.begin();

    // Set Temboo account credentials
    SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT);
    SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
    SendEmailChoreo.setAppKey(TEMBOO_APP_KEY);

    // Set profile to use for execution
    SendEmailChoreo.setProfile("Testofsoftware");

    // Identify the Choreo to run
    SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");

    // Run the Choreo; when results are available, print them to serial
    SendEmailChoreo.run();

    while(SendEmailChoreo.available()) {
      char c = SendEmailChoreo.read();
      Serial.print(c);
    }
    SendEmailChoreo.close();
  }

  Serial.println("\nWaiting...\n");
  delay(30000); // wait 30 seconds between SendEmail calls
}

It could be that your code is making it respond to all ARP WHOHAS requests with a big "ME!!!!" regardless.  Impossible to say without seeing your code though.

@Majenko, ok, I'll post my code

Could you include in your answer the output you get in the serial monitor?

It would definitely be useful to see the  serial printouts. I'm a little curious at how this works, I've used the Adafruit_CC3000 which works in a very similar way, although I've never tried to send emails from it before. Is it just me or are you connecting and disconnecting from the wifi in your setup(), and then trying to send an email from the loop()? Does this work? I would have thought not...

I'll try to get a readout later but basically, sometimes the cc3000 will run a ping test, sometimes it won't connect. It can't do anything with consistency.

Does getConnectionInfo always work? Same to the dnsLookup? (output results!) This:  IPAddress ip_addr; also looks like a pointless variable as you get connection_info.ip_address later on. I notice the code is the standard example & this is exactly the same, apart from the email/loop part. Have you tried running it just with the setup code? (i.e. just have a delay in the loop)

Because of the limited information given any answers given will be by nature limited. However, I can suggest several troubleshooting tips.

Tips

Verify that username and password used are exactly right(punctuation, spaces, etc.). Where you putcomcast you should put the name of the network not the name of the provider. I am not sure if you have done this or not.
Make sure network is in fact WPA2.
In order to debug the issue make sure if you are getting nothing through serial to set it to the baud rate of 115200.
If you are using the breakout board make sure you correctly wired it and check any solder points:

Make sure you have the correct libraries installed.  Also, try sample code from the examples. Libraries can be found here.

Many of these seem obvious but can through someone off. So try these and let me know the results. A lot of information about setup can be found here.
EDIT Try removing the
if ( wifi.disconnect() ) {
    Serial.println("Disconnected");
  } else {
    Serial.println("Error: Could not disconnect from network");
  }

block. It appears that you are disconnecting before going into the main loop. This would obviously make it impossible to send an email. The reason pining would work sometimes would be that wifi.disconnect() is called sometimes but not all the time. To narrow the issue try an example code from the library.

all of that was checked and double checked. It's all correct

See EDIT above. I really need more info about you setup to properly answer your question.

not a direct answer but the sparkfun hookup guide connects pin 8 (SDCS) to the chip select for the SD card. If this line is floating, I'm not sure of the impact.


text:
AnalogWrite custom voltage

I want to get a low voltage on output pin of Arduino mega. I have connected Pin 46 to A3, and wrote 120 value to 46 port. Expected was to get 2-3v on A3 input pin. Instead I always get 1023 values as input. Am I doing something wrong ?
void setup(){
  Serial.begin(9600);
  pinMode(46, OUTPUT);
  pinMode(A3,INPUT);
  }

void loop(){
  analogWrite(46,120);
  Serial.println(analogRead(A3));
  }

You could substitute an Arduino Due and connect to pin DAC1 or DAC2 (located between A11 and CANRX), 12-bit-resolution DAC's :)

The analog outputs aren't real analog outputs, they are PWM.
That means that they rapidly switch from OFF to ON and back to OFF again.  The analog value is the ration of OFF time to ON time, known as the Duty Cycle.
You can convert that rapid switching to a real voltage by passing the signal through a low pass filter.  The simplest form is the RC filter:


text:
Servos and ultrasonic at the same time
So recently I started making a sonar out of ultrasonic HC-SR04 sensor and servo motor. The idea was to slowly rotate servo 180 degrees while measuring distance.
Soon after I noticed that regular pulseIn() command could wait 20ms while doing nothing. So I started learning interrupts. I came up with a code which sends TRIG signal and records sending time with micros() function. When an interrupt occurs on ECHO pin, we subtract current time with TRIG time and get time of round trip of the sound.
The code works as intended without servos connected, but it behaves interestingly ! I always get distance which is 8 cm bigger than actual distance. So I had to subtract 8 cm every time ! Also I noticed that max reliable range decreased , using pulseIn() I could measure distance of 400cm, and with mine code it starts to show weird numbers after 150cm...
So i thought that 150cm is enough for me, and tried to run the code with servos attached. everything ran as intended, until the servos started to move. Now I was getting distance along with pretty much random numbers, periodically positive and negative.
I could just use one the fancy libraries out there, but I am curious what am I doing wrong, why i need to subtract 8cm each time , why my reliable range decreased so much, and most importantly why am I getting weird values while servos are on ?
CODE :
#include <Servo.h>

#define ECHO 2
#define TRIG 7

 Servo servo;
 int distance;
 volatile long echoTime = 0;
 long trigTime = 0,sendTime = 0,timeServo = 0;
 bool scanning = false;
 byte servoDir = -1,servoAngle = 0;

void setup()
{
  servo.attach(12);
  Serial.begin(115200);
  pinMode(ECHO,INPUT);
  pinMode(TRIG,OUTPUT);
  attachInterrupt(digitalPinToInterrupt(ECHO), echo_interupt, FALLING);

}
void loop()
{
  // SERVO

   if((millis() - timeServo > 10)){
     if(servoAngle <= 0 || servoAngle >= 180)servoDir = -servoDir;
     servoAngle += servoDir;
     servo.write(servoAngle);
     timeServo = millis();
   }

  // GETTING RESULTS
  if(echoTime > 0){
    distance = echoTime - trigTime;
    distance /= 58;
    echoTime = 0;
    trigTime = 0;
    Serial.println(distance - 8);
  }
  // SENDING PULSE
  if(millis() - sendTime > 20){
  digitalWrite(TRIG,LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG,HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG,LOW);
  trigTime = micros();
  sendTime = millis();
  }
}

 // INTERUPT
void echo_interupt(){
  echoTime = micros();
}

8cm is 233µs of sound travel time.  There and back again would be 466µs.  466µs, at 16MHz, is around 7400 instructions.
When an interrupt is triggered you don't get an instant response.  First the built in interrupt function is called. That then looks to see if you have registered an interrupt function.  It then calls that interrupt function.
All that takes time, and when you're working with microseconds it makes a big difference.
And then you have to go and get the current micros() value, which again takes time to do.
So it all adds up to a delay.  Not ideal.
For greater accuracy you should investigate using input capture which will start a timer running when you send the trigger and the timer will automatically stop the nanosecond the echo is received.  From that you can calculate a much more precise distance.
As for why you are getting strange results with the servos on?  Most likely because you are moving the receiving head while the pulse is being received.  I made a similar system while playing once and found that the best results were achieved by moving the head to the desired position, waiting a moment for any vibration to settle, do the ping and get the result, then move the head to the next position.
Oh, and by the way, the HC-SR04 is (from memory) only really rated for up to 2m - I have never achieved anything more than around 1.8m with any accuracy.

Great, now I can work on time calculation. Regarding strange results, ultrasonic head wasn't mounted on servo at all, it was in different place and standing still, only connected to the same Arduino board. I'll work on time calculation , perhaps it could solve the problem.

@boofati: You could bypass the arduino library and declare your real isr. Here's a short tutorial: http://www.avr-tutorials.com/interrupts/avr-external-interrupt-c-programming

@Majenko: the downside of input capture is that it uses an IP block, so it doesn't scale easily - unless you consider adding more AVRs as scaling :-)

@IgorStoppa Or switching to a real microcontroller instead ;)

@Majenko: then where is the fun? Yes, any Cortex M-something could do it much better, but really, then there is no more challenge :-)

@IgorStoppa You want challenge?  Then break into a navy base and nick the sonar systems from a submarine in dry dock ;)

Apparently someone has been playing MGS too much :-D

@Majenko - the Arduinos I have here are real. :P

I had problems with Servo library and VirtualWire. They both use the same internal timer. The solution was to change Servo.h to ServoTimer2.h lib.