# Question
Title: Self answering a Intercom and playing louldy for person to response
We have two labs - one in 1st floor and other at 2nd floor. We are connected by intercom - both the labs has one device each. The issue is that the person who sits near the intercom is busy through out day answering the intercom and reaching out to the person for whom the call is made for.

This is very tiresome and hence I wish to automate this. I have an Arduino Mega 2560 board. My plan is to make Arduino receive the call ask for the person whom the caller is reaching out and play the name loudly over speaker in all rooms of labs (to attended the phone). If the user does not turns up even after 3 repeated times of calling - disconnect the call. If the user answers the phone by picking up the receiver then turn the conversation speaker mode off until call has not ended.

I have Arduino Mega 2560 board which has 4 serial ports but I am not user what would be the circuit to make this functionality workable? What are the extra h/w required and concept of its implementation.

# Answer
Let's try to break it down to several components:

* **Interfacing with POTS** (Plain Old Telephony System): There is a nice article by Joe Doll describing how to interface an Arduino and POTS. POTS involves high voltage during both idle and ringing time (48 V DC, superimposed 90 V AC) and the circuit itself is mostly analog. You can find the required parts and their values in his article, which goes down into the nasty details in a spectacular fashion. Here is the analog circuit, involving the Arduino, from his post:

Consider that there are other projects performing similar task in a different manner, like this one, and this one which specifically explains how to record sound from an old rotary phone.

* **Play/Record sound from Arduino Mega 2650:** There are many projects that describe how to Play or Record sound using Arduino. Most involve a SD card to store the wav files. There is also the option of an MP3 shield, that comes with a pre-built SD card slot, such as this one. They are fully documented and are easy to interface with.
* **Code that encapsulates the Logic**: Here you could decide how many times the Arduino should play the recorded name, and what happens if the user won't answer. The disconnection will be done utilizing the POTS interface you created in bullet #1. In addition, you should handle the logic of what happens when the user does answer. It is not clear what you mean by 'receiver', but if you plan to have a remote extension or similar, some extra work will be required.

As a side note, it might be easier to create/re-use a walkie-talkie kind of wireless communicator, accompanied by an Arduino, to signal or broadcast the names of the people called. This might not include reuse or interfacing with the current intercom device, but by thus I believe it will make development easier and faster.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: USB BUB II - Misconnection and no longer uploads
I accidentally misconnected a USB BUB II to a Arduino RBBB (atmega 328), and it no longer uploads code. Here are the symptoms, I think the BUB II is fried. I am using Ubuntu 14.10.

* Code won't upload with error `ser_recv(): programmer is not responding`
* The RBBB board will reset is I hit the button. Evidenced by the LED flashing in port 13
* Prior code runs as expected
* dmesg behaves normally upon USB connection
* When I short the Rx and Tx terminals of the BUB II, I can send instant reply messages via the Serial Monitor

Does this sound like the USB BUB II is broken? Or is is possible that some component on the RBBB board is fried?

# Answer
> 1 votes
Well, I asked too soon. I tend to do this.

I had to switch the board configuration to Arduino Uno and it worked

---
Tags: ftdi
---


# Question
Title: Control arduino with keybaord via computer
I'm brand new to arduino but I'm trying to figure out how to set up a WASD steering system for my robot I made.

I have the physical setup all ready but I don't know the code to use that would allow me to use my computers keyboard. I would like to still have my keyboard attached to my computer while I do this. *I.E. I don't want to manually plug the keyboard into arduino*.

I asked this on Robotics stack exchange but they said to ask here.

A list of functions/blocks Iof code that is applicable would be the best answer, but I'll take anything that'll get my bot moving :)

**Edit** I'm using a wireless keyboard, but my arduino is connected via USB.

# Answer
The problem with using the keyboard is the device would have to be tethered to your computer. If you mean for this "robot" to be an explorer, that limits its choices. If it's an arm or something that stays in place, you're fine using the typical serial libraries to monitor your keyboard for input like Chris suggests.

Unfortunately, I don't know of any way to simply plug in the USB keyboard and take in keys. Usually, serial communication is processed between two systems much like two people texting each other. When you see the light blinking on your phone, you know you have a text and how to open it to retrieve the message. In the case of the Arduino, it's checking for a flag bit called RX for the received message and flags a bit for transmitting a message (TX). Each system then pulls down its message and interprets it. In the case of your sketch, you'll be looking for this flag and schedule an action whenever it's checked. Read about Serial communications here and work through the examples to get a feel for it. Because you probably want a real-time response, it might be worth your while to check out interrupts, as well. These are sudden events that get flagged (such as receiving your text) and get handled immediately instead of waiting for the program to refresh and search for the values manually. As a final note, baud rates are the calculated time frames you and your recipient agree on. It would be difficult to receive a full message if you kept cutting off your friend, so it is with computers. This stuff can kind of be tricky at first, but keep at it. Nothing is more ridiculously satisfying than getting that response character from your device.

There's a neat tutorial for getting your Arduino to work through your iPhone here, but it requires an ethernet board, which means a router and wireless board.

Without knowing what you intend to do with it, it's hard to say how to help, but I hope this gets you into it.
> 1 votes

---
Tags: robotics, code-optimization
---


# Question
Title: SMlib State Machine Library not working as expected
I have the following setup and sketch.

The problem is that when I click the button it works sometimes, but other times it executes On Off straight after On as if it's executing twice.

This is after pressing the button only 7 times:

```
Off
On
Off
On
Off
On
Off
On
Off

```

I thought that was the whole point of a state machine? That it continues to execute the next state (not multiple times at random).

Very very confused with this one.

```
//http://www.arduino.cc/playground/uploads/Code/FSM.zip
#include <FiniteStateMachine.h>
//http://www.arduino.cc/playground/uploads/Code/Button.zip
#include <Button.h>
//http://www.arduino.cc/playground/uploads/Code/LED.zip
#include <LED.h>

const byte NUMBER_OF_STATES = 2; //how many states are we cycling through?

//initialize states
State On = State(ledOn);
State Off = State(ledOff);

FSM ledStateMachine = FSM(On);     //initialize state machine, start in state: On

Button button = Button(2, INPUT_PULLUP); //initialize the button (wire between pin 12 and ground)
LED led = LED(13);                 //initialize the LED
byte buttonPresses = 0;            //counter variable, hols number of button presses

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

//poor example, but then again; it's just an example
void loop(){
  if (button.uniquePress()){
    //increment buttonPresses and constrain it to [ 0, 1 ]
    buttonPresses = ++buttonPresses % NUMBER_OF_STATES;
    switch (buttonPresses){
      case 0: ledStateMachine.transitionTo(On); Serial.println("On"); break;
      case 1: ledStateMachine.transitionTo(Off); Serial.println("Off"); break;
    }
  }
  ledStateMachine.update();
}

//utility functions
void ledOn(){ led.on(); }
void ledOff(){ led.off(); }
//end utility functions

```

# Answer
Maybe you need some sort of **debouncing**? There's a tutorial on the Arduino site that I think will sort your problem out.
> 3 votes

# Answer
It doesn't look like the state machine is a problem here. More likely it's a problem of the button bouncing, as you don't have any code or circuitry to guard against it.

A button is typically a very simple component which doesn't necessarily make/break connections cleanly. Sometimes it will have a brief intermittent connection, making it look like it's been pressed/released multiple times. This is referred to as bouncing.

There's lots of material online about debouncing, whether in hardware or software. The top answer here may help:
> 1 votes

---
Tags: led
---


# Question
Title: When I open a COM port some pins on Arduino Uno goes low for about 2 seconds
I have no idea why this is happening, but after I open COM port to talk with my Arduino (I click "Open" in RealTerm), the state of some pins goes from high to low for about 2 seconds and then goes back to high. Here's my code:

```
void setup()
{
  pinMode(5, OUTPUT);
  digitalWrite(5, HIGH);
  Serial.begin(9600);
}

void loop()
{
}

```

In this case pin 5 will behave this way. I've checked it also for pin 6 and pin 8 and they behave in the same manner. I suppose more pins act like that. Why is this happening?

# Answer
What you see is expected: that's because opening the USB connection to the UNO will automatically trigger a reset of the ATmega chip of the board, hence your sketch will be executed from scratch, ie `setup()` will be called again then your `loop()` repeatedly.

Hence what you observe in detail:

1. open USB connection from PC
2. open USB connection on Arduino UNO
3. UNO USB chip (an ATmega16u2) triggers a RESET of the MCU (an ATmega328P-PU)
4. On reset, the MCU sets all pins to INPUT, i.e. high impedence, **hence no voltage can be measured on any pin**
5. Then the bootloader starts, performs some intialization and starts your sketch
6. Your sketch executes first `setup()`, so your pin is put in OUTPUT mode and set to HIGH: **its voltage is thus measurable (5V)**
7. your sketch `loop()` gets executed "forever" i.e.until a new reset or power supply disconnection
> 3 votes

# Answer
The arduino is reseting because of the serial port initializing. If you want to avoid it, you can put a 120 ohm resistor between 5v and reset.

Source
> 0 votes

---
Tags: serial
---


# Question
Title: How to change input pin of FreqCounter Arduino Uno/Dumilanove library?
The following link to the library defines arduino pin 5 for input pin for signal.
https://www.pjrc.com/teensy/td\_libs\_FreqCount.html

But the problem is I'm using an 16x2 LCD display with the arduino pin 5. The display needs pin 5 to work. So the question can solved in two ways,to both of which I don't know the answer.
1. Change LCD pin number to other pin. (Tried it was a failure. I've probably done it wrong)
2. Change the input pin for the freqcount library.

Any idea how to get past this bottleneck?

# Answer
The library makes use of the hardware peripheral Timer 1 which has its input on pin 5 of the Uno.

It can't be changed. You have no choice in that.

You will have to move the LCD to another pin instead.
> 0 votes

---
Tags: lcd, frequency
---


title: Simple Text input using 5 buttons

text:
# Question
Title: Simple Text input using 5 buttons
So I have to get this function done but I'm not so bright and got confused. (excuse me! I'm total noob)

The function is basically inputing text using five buttons, directional buttons and an ok button. The up and down buttons will be used to cycle through letters (a-z), and the left and right buttons will be used to control which array to cycle letters.

The control will be:

* up button (up): ASCII-1 (z, y, x...)
* down button (dw): ASCII+1 (a, b, c...)
* right button (ri): array\[i\] ~\> i+1 (go to next character/array)
* left button (le): array\[i\] ~\> i-1 (go to previous character/array)
* ok button (ok): confirm text and changes the limit to stop function looping

I can't get it work with this code I write.

```
void intext()
{
  int lim=16;
  lcd.setCursor(0,1);
  lcd.print(input);
  for(i=0; i<lim ; )
  {
    if(digitalRead(dw)==HIGH)
    {
      if(input[i]<'a')
        input[i]='z';
      if(input[i]>'z')
        input[i]='a';
      input[i]=input[i]+1;
      delay(1000);
    }
    if(digitalRead(up)==HIGH)
    {
      if(input[i]<'a')
        input[i]='z';
      if(input[i]>'z')
        input[i]='a';
      input[i]=input[i]-1;
      delay(1000);
    }
    if(digitalRead(ri)==HIGH)
    {
      delay(1000);
      i=i+1;
    }
    if(digitalRead(le)==HIGH)
    {
      delay(1000);
      i=i+1;
    }
    if(digitalRead(ok)==HIGH)
    {
      lim=i+1;
      delay(1000);
    }
  }
}

void loop()
{
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Type your text:");
  intext();
  lcd.setCursor(0,0);
  lcd.print("Success!!");
  lcd.setCursor(0,1);
  lcd.print(input);
}

```

The result I wanted it to be is like this: first you got the "type your text:" on the first row and blank in the second row. our cursor is in the first column of the second row, so we can cycle through the alphabet letters. if you press right you can edit the next column of second row. you can get to the previous column in second row by pressing left. you can input up to 15 characters. after done typing pressing ok will stop the typing and you will see "Success!!" in the first row and typed text in the second row.

Please help. I'm stumped. Thank you.

# Answer
> 1 votes
Several issues in the code you posted:

* Every change to the text you do inside the `for` loop, will not be reflected to the LCD until the for loop will end (when `i<limit` will no longer be a true statement). You might want to add an additional code, inside the `for` loop and outside any of its conditional statements, that will repeatedly set the cursor and print `input` to the LCD. Something similar to the code you have prior to the `for` loop:

```
void intext()
{
  ... // rest of the code until the for loop

  for (int i; i<limit; )
  {
    ... // all the conditions for up/down/left/right/ok

    lcd.setCursor(0,1);
    lcd.print(input);
  }
}

```
* Another problem is that when the user clicks *left*, the counter should be decremented, not incremented, and you should check for left boundary:

```
if(digitalRead(le)==HIGH && i>0) // left boundary check added
{
   delay(1000);
   i=i-1; // and not i=i+1;

}

```
* After clicking *Ok*, and since the `for` loop does not increment `i`, the condition in the `for` loop (`i<limit`) will stay true, and the loop will not end until the user will click *Right* once more. To mitigate this, change the following

```
if(digitalRead(ok)==HIGH)
{
  lim=i; // and not: lim=i+1;
  delay(1000);
}

```

Otherwise, the user will have to click *Right* for completion, to increment `i` once more.

* **jfpoilpret** comment about pull up/down is very important. Make sure you use pull up/pull down resistors in order to prevent input debounce (more details inside this link).

---
Tags: button, string
---


# Question
Title: What is the best vehicle platform to begin with (e.g. tracked, four-wheel drive)
Despite many articles on the topic of vehicle platforms, none of them seem to recommend the best one to start with. Later on I am sure I will seek an exact kind of chassis for autonomous vehicle construction, but now I am looking to learn the basics of this area of the Arduino world. If you could give me a simple recommendation for the general category of vehicle platform to use it would be much appreciated. I will be using an ultrasonic distance sensor coupled with a servo motor to detect obstacles, so it is a very simple project. Thank you so much.

# Answer
SparkFun's Magician Chassis is a very simple, very flexible chassis for starting out. Also comes as part of the RedBot Kit.
> 2 votes

---
Tags: sensors
---


# Question
Title: What should be the delay to be given for reading accelerometer
I have five accelrometer sensors (MMA 7361) connected to the analog channels of Arduino Duemilanove. I am using the following code to read the data. (I am reading from only one axis from each sensor.)

```
#include <avr/io.h>
#include <avr/wdt.h>

int sensorValue = 0; // value read from the pot

void setup()
{
    Serial.begin(9600); // initialize serial communications at 9600 bps:
}

void loop()
{
    // read the analog values:

    int i=1;

    Serial.print("ACS#");

    for(i=0;i<5;i++)
    {

        sensorValue = analogRead(i);
        Serial.print(sensorValue);
        Serial.print("#");

        delay(10);
    }

    Serial.println("");

}

```

I am using a delay of 10 after reading each sensor. What should the value of the delay I should be using after reading one sensor to get the correct values from the sensors?

# Answer
A delay is not needed.

What can be more beneficial, though, is making a dummy reading between each real reading. This gives the ADC more of a chance to settle on the right reading without the Sample and Hold capacitor being influenced by the previous reading.

The simplest way is just to duplicate your `analogRead` line so it's done twice.
> 1 votes

---
Tags: accelerometer
---


title: coding standards for bigger projects

text:
# Question
Title: coding standards for bigger projects
I'm starting a decently sized project around arduino/ATMELavr, and I came to wonder if there are any commonly accepted C/C++ coding standards or style guidelines specifically aimed at embedded C++/arduino.

I've worked mostly with python recently, and came to love the PEP8 guidelines, and the associated pep tool (which checks syntax consistency with the style guide). Similarly, I've used jslint and similar tools for javascript, as I find they help keeping your code base homogeneous, and avoid wasting time and commits on silly typos, and arguing over where the braces should go.

Any similar tools for C++ or more specifically arduino C++?

# Answer
In my experience (15 years in industry, 30 total), **this does not matter**. What matters is having good developers who understand code written in ANY valid style. I currently work at a large bank, and there's 2 different bracket styles being used in our code, and nobody cares. Good developers don't care about this. We care a lot more about the code being valid, error-free, and efficient. If you do that, I don't care where your brackets are.

Yes, there are style guides for C++ but you don't need to use them. This is a good one though...

http://google-styleguide.googlecode.com/svn/trunk/cppguide.html

I am not aware of any style tools that integrate into Arduino IDE. There are some style tools that integrate into Eclipse though - and if this is important to you and your team, I strongly suggest using Eclipse for development. The Arduino IDE isn't really for large projects.

http://astyleclipse.sourceforge.net/ \- but Eclipse doesn't really need this, it has a pretty good built-in formatter.
> 0 votes

---
Tags: programming, c++, coding-standards
---


title: Generating PWM signal 1-2 ms @ 333 Hz

text:
# Question
Title: Generating PWM signal 1-2 ms @ 333 Hz
I'm currently working with the `Talon SR Speed Controller` and it requires a specific Input PWM Signal of `1-2 ms @ 333 Hz` and an input resolution of `10-bit (1024 steps)`. Currently I use the `Servo` library to handle these requirements, but was having some issues of the motors jumping their dead-band from forwards to backwards really fast causing the motors to rock back and forwards a few millimeters. If the `servo1.write(pwmValue);` isn't my issues please let me know?

If there is a way to specifically achieve the 333Hz PWM signal for 4 motors of the same Uno or Due (most likely will transfer to a Due in a few days) I would like to implement that.

From my understand I can modify the timers registers for the arduino specifically, but don't know exactly how to do that or to achieve 333Hz. If someone could please help me understand this I would greatly appreciate it.

**Speed SR Speed Controller Information:**

```
Input voltage 6-28 VDC
Continuous current 60 A
Peak current 100 A
Input PWM signal 1-2 ms @ 333 Hz
Input resolution 10-bit (1024 steps)
Output resolution 10-bit (1024 steps)
Output switching frequency 15 kHz
4% neutral dead band

```

# Answer
I am playing on a Arduino UNO, you would have to compare the datasheets to determine differences.

For my research on this answer I am looking at:

Also:

* we know PWM pins are D3, D5, D6, D9, D10, D11
* I am using D11 for this since I can attach my oscilloscope to the MOSI pin of the ISCP
* D11 maps to PB3 (MOSI/OC2A/PCINT3) (see datasheet or this cool gfx)

---

## Normal usage

First, let's see what happens when we set an arbitrary PWM on pin 11

```
int DUTY = 25;
analogWrite(11, DUTY * 256 / 100);

```

results in:

1. Freq: ~487Hz
2. Duty: ~25%
3. Time: ~2.05ms

This first point I will make is that with the given 490Hz the PWM duration is actually 2ms which seems to be close to what you want (you said between 1-2ms), maybe my misunderstanding there.

---

## Playing with pre-scalers

From several of the links posted above, you will see that you have different pre-scalers available depending on which timer you are using: eg.

**Pins 5 and 6: controlled by Timer 0 in fast PWM mode (cycle length = 256)**

```
Setting     Divisor     Frequency
0x01        1           62500
0x02        8           7812.5
0x03        64          976.5625
0x04        256         244.140625
0x05        1024        61.03515625

TCCR0B = TCCR0B & 0b11111000 | <setting>;

```

**Pins 9 and 10: controlled by timer 1 in phase-correct PWM mode (cycle length = 510)**

```
Setting     Divisor     Frequency
0x01        1           31372.55
0x02        8           3921.16
0x03        64          490.20
0x04        256         122.55
0x05        1024        30.64

TCCR1B = TCCR1B & 0b11111000 | <setting>;

```

**Pins 11 and 3: controlled by timer 2 in phase-correct PWM mode (cycle length = 510)**

```
Setting     Divisor     Frequency
0x01        1           31372.55
0x02        8           3921.16
0x03        32          980.39
0x04        64          490.20
0x05        128         245.10
0x06        256         122.55
0x07        1024        30.64

TCCR2B = TCCR2B & 0b11111000 | <setting>;

(All frequencies are in Hz and assume a 16000000 Hz system clock.)

```

These are relatively simple to setup and use (the setting is at the bottom of each of the above code blocks), but you have to be mindful of playing with the pre-scaler of timer0 (which controls `millis()` and `delay()`). So if you have a choice, steer clear of timer0, or pwm pins 5 and 6.

Example of using just the inbuilt pre-scalers without any additional libraries:

```
#define PIN 11
void setup(){
    pinMode(PIN,OUTPUT);  // not absolutely required
    int DUTY = 20;
    TCCR2B = TCCR2B & 0b11111000 | 6;
}

void loop() {
  static long counter = 0;
  if(millis()%10==0){
      counter++;
      analogWrite(PIN, counter%255);
  }
}

```

I know you can manipulate the frequency better than that, and I have been playing with this for hours and then I finally stumbled upon the final link (which believe it or not, I found via YouTube!).

---

## Using an External Library

To use the PWM library you will need to download it from Google Code, save/import/get it into your library folder, and restart the IDE. Once you do that, you can explicitly set the frequency (within limits, 333Hz is within those limits), and you should be set.

Code example:

```
#include <PWM.h>
int32_t frequency = 333;

#define PIN 10

void setup(){
    pinMode(PIN,OUTPUT);
    int DUTY = 20;
    InitTimersSafe();                    // won't touch timer0
    SetPinFrequencySafe(PIN,frequency);  // again, not timer0
    pwmWrite(PIN, DUTY * 256 / 100);
}

```

There is even a `pwmWriteHR` which allows for higher resolution, but that does not work with timer2 (which is only an 8-bit timer).

The matching, non-safe (ie initialises and uses timer0 as well) functions are:

```
InitTimer();  // and
SetPinFrequency(PIN,frequency);

```

The only limitation I have found so far is that it doesn't work with PWM pin D11. I have tested D3, D9 and D10 (they all worked fine), but I did not get around to testing D5 or D6.

Good luck, I hope this helps.
> 4 votes

# Answer
This will command a Talon SR from an Arduino. I used an Uno and had the Talon hooked up to a CIM motor & gearbox and it ran fine. I don't understand the code well enough to know if it's generating the 1-2ms PWM signal you asked about and your control resolution will definitely be limited to roughly 1% of range - all I know is that it works.

First, make sure your wiring is set up:

Black PWM wire goes to GND Red PWM wire goes to 5V (right next to GND on the Arduino) White PWM wire goes to pin 3 (or some other Arduino PWM pin)

Then try this code:

```
#include <Servo.h>  //This comes with the Arduino

int talon_pin = 3;

Servo talon;

/* The 'Servo.h' library allows you to control motors and servos by passing any value between
0 and 180 into the "write" method (talon.write() in this program).
For a motor:   0 is full power in one direction,
             180 is full direction in the opposite direction,
              90 is stop.
For a servo:   0 is all the way one direction,
             180 is all the way in the opposite direction,
              90 is the middle.
*/

int talon_max_forward = 180;  //this might not actually be forward
int talon_max_reverse = 00;    //this might not actually be reverse
int talon_stop = 90;          //this is definitely stop (if the Talon is calibrated right)

void setup() {
  talon.attach(talon_pin);  //This tells the arduino to control this pin like it's a servo/motor
}

void loop() {
  talon.write(talon_max_forward);   //full power one way
  delay(2000);                      //wait 2 seconds
  talon.write(talon_stop);          //full power the other way
  delay(2000);                      //wait 2 seconds
  talon.write(talon_max_reverse);   //full power one way
  delay(2000);                      //wait 2 seconds
  talon.write(talon_stop);          //full power the other way
  delay(2000);                      //wait 2 seconds
}

```

The Talon I used was fresh out of the box and had never been calibrated before, so the "stop" didn't actually stop - it just moved slowly.

To calibrate it, use a paper clip or pen / pencil to press and release the CAL button on the Talon (next to the LED). You have to press AND release when commanded to stop (after going full + and full - in between), but the motor doesn't turn when the button is pressed. I calibrated by running the program above with the motor attached, waiting for the motor to "stop", then pressing and holding for 8 seconds. If you have trouble hitting it, increase one of the delays after a talon\_stop command.
> 1 votes

# Answer
You'll need to edit the library file, Servo.h.

Find the line...

`#define REFRESH_INTERVAL 20000 // minumim time to refresh servos in microseconds`

And change the refresh interval - 20000us (20ms) is the standard 50Hz rate.

Change it to 3003 to get 333Hz rate.

This will permanently change the Servo library to 333Hz. If you need 50Hz servos, it would be best to duplicate the Servo library to Servo333 or something.

You will not be able to run both at the same time as they use the same timers.

(This is based on the standard Servo library in arduino 1.06)
> 0 votes

---
Tags: arduino-uno, arduino-due, pwm
---


title: Programming Arduino

text:
# Question
Title: Programming Arduino
I'm new to electronics. Professionally I'm a software developer. I want to know whether it is possible to program Atmel AVR 8-bit and 32-bit Microcontrollers using Arduino IDE. If yes could any one guide me on the process or direct me to any site where I can learn about it.

# Answer
Yes, it is possible. In fact, this is how the whole 'Arduino' concept works - programming 8/32 bit AVR microcontrollers with the Arduino IDE.

> program Atmel AVR 8-bit and 32-bit Microcontrollers using Aurdino IDE

This has two parts actually:

**1. Generate compiled HEX targeting AVR**

Using the Arduino IDE you could utilize the Arduino libraries (aka working with assist utility functions like `digitalWrite` for example), which are built on top of the AVR tool-chain. The official Arduino IDE comes with pre-built support for several 8-bit/32-bit Atmel AVR micro-controllers, the full list of supported boards can be found on the Arduino official website or in this Wikipedia page. **You did not specify a specific MCU**, therefor you should check if the MCU you would like to work with is in that list.

**2. Uploading an Arduino sketch to a compatible AVR**

Arduino IDE uses avrdude under the hood. avrdude is

> an utility to download/upload/manipulate the ROM and EEPROM contents of AVR microcontrollers using the in-system programming technique

(From their website).

The best place to start is the official Arduino.cc website, in the 'Getting Started' section. If you haven't picked any specific Atmel AVR chip yet, consider that each has slightly different features, size, I/O pins etc. so make sure to research a bit before purchasing one (reference the table in the Wikipedia link above to compare between the different kinds).
> 2 votes

# Answer
http://arduino.cc/ is good place to start. It includes articles about how to get started, library references, and user forums. The Arduino IDE will certainly get you started, but as an experienced developer you'll most likely hit its limitations pretty quickly.

Later, or quite possibly sooner(!) you can use same toolset (compiler, loader, libraries) in several less limiting environments: Eclipse IDE, edit/make at the command line, and Atmel's AVR Studio. C and C++ are mainstream; I've seen references to the existence of (but never tried) AVR Forth and AVR python.

Though you'll see occasional references to an 'Arduino language' it's really nothing more than C++ with some attempt to be smart about detecting references to library packages and auto-inserting the relevant `#include`s. You probably won't want to take advantage of such shortcuts, and keep to good programming practices, if you think you'll ever want to move up from the Arduino IDE.

I personally use Eclipse (supplementing with a few command line tools) and I'd recommend it once you've tried the Arduino IDE.
> 1 votes

# Answer
Just to complement the other responses. You can program some AVR chips using the Arduino IDE, but for it to work out-of-the-box just by using a USB cable it needs to be an Arduino or "Arduino compatible" board, mostly because these come with the Arduino Bootloader.

The bootloader is a small piece of software that runs at power-up and is responsible to load your program into the chip (as well as other configuration stuff, for more info read the previous link). If the AVR chip does not have the bootloader already flashed, then you will have to use a programmer (connected to its ISP pins) to burn it first.

So, it's not like you can just buy random AVR chips or development boards online and start using them. But taking in consideration the wide selection of official boards and "Arduino compatible" ones, you should be able to find something to fit your needs.
> 0 votes

---
Tags: programming
---


# Question
Title: Arduino communicating back and forth with PHP server
I am researching to find the best method to work with in order to control the arduino from a web interface (hosted on a web server using PHP) and also sending data from arduino to webserver and save to mySql.

2 methods which I have found that a lot use are save the data to a text file or in the url.

Which is the best or are there any better methods?

# Answer
I would suggest your best bet would be to pass messages back and forth via JSON, via Get/Post http request.

So to send data, you send a POST request (to the PHP server) with your data in JSON in the content. To get instructions, you send a GET request to the PHP server and get a contents field with JSON in it.
> 3 votes

# Answer
Another method is to use MQTT. That's a protocol often used for embedded messaging. Find here the (one of the?) arduino client.

As a server you can install mosquitto either on the same system running the web server, or on a different one.

Than the communication logic with php will be done with mosqitto-php

advantages:

* decoupling the web server(s) from the arduino(s)
* lightweight protocol for the arduino
* easy interface with more applications (eg, storing data in mysql, independently of the web server, or any new in the future)

disadvantages:

* few more work setting up the mosquitto server.
> 1 votes

# Answer
It sounds like your first need is a way to send the bytes back and forth. A secondary question will be what that data should consist of (eg: text commands, binary commands, etc). Let's tackle the "how" first.

You have described two dynamics to the communication between server and Arduino:

1. The arduino "sends data to the server" where PHP code will save it to MySQL; if your Arduino can be an internet client (eg: has an ethernet or wifi interface), it could use GET or POST (or PUT) HTTP calls to php code. GET is easiest, but normally GET calls shouldn't change the server, only query it -- but many people make exceptions for small devices and small amounts of data which can be encoded in the URL.
2. The web server "controls the Arduino". Unless the Arduino sets up an internet server, it is going to have to poll the web server from time to time to find out what it should do (ie: to be controlled). It can pretty easily use a GET to fetch some text which it can interpret.

I'm guessing that HTTP will be the easiest path for communicating, because you probably understand that if you are a PHP programmer, and because it can often get through firewalls more easily if that matters; but a simple TCP socket or UDP datagrams are also possible.

Once you can send blocks of bytes between the server and the Arduino, you can focus on what those bytes should contain. That could be simple text commands, or some binary protocol, or even the MQTT protocol transactions that another answer references. You haven't given enough info to help select the protocol and format, so I'm assuming you are mostly looking at this time for the method of communicating, as described above. If you want to ask about the format of what to send back and forth once you have the data flowing, please make that a new question. You can test the basics by just sending a "Hello" text string between server and Arduino.
> 1 votes

# Answer
Buy a uart wifi such as WiFly series chip. You can control e chip via UART AT command. The chip capable of sending http post get to/from a server.

See this guide as an example

http://the.machini.st/posts/35
> 0 votes

# Answer
If it's not too much data, a textfile as a database should suffice, if you want something more scalable; I'm quite impressed with node.js: http://weworkweplay.com/play/raspberry-pi-nodejs/
> 0 votes

---
Tags: arduino-uno, ethernet
---


# Question
Title: Several SIM with Arduino GSM/GPRS shield
For some purpose we need to communicate with Arduino using more that one SIM card, but still like to use an only GSM shield.

So, the idea is to use several SIM holders, to commutate each of six SIM wires to the sim we currently use. But it is still the question

1) How we should handle the gsm module itself? Is it okay for it if the SIM wire will be commutated to another SIM when it is in the middle of something? May be we should power off the module before, but it unclear how to do it programmatically when it is installed on the top of Arduina Mega 2560

2) should we commutate all six wires, or may be there are few signal ones and another shouldn't be never commutated?

3) what is the best way to do this commutation? Relays/transistor switches and so on?

# Answer
You should reset the shield, and keep reset, while switch sims. The reset is on pin 7.

If you look at the schematic, you can see there are only 3 lines, plus a GND and VDD. The GND and VDD you can probably share between the different sims. The SIM\_RST, SIM\_SCK and SIM\_DATA need to be switched.

I think you should use a MUX for that, but that is not my area of expertise. Note that at least the DATA line is bi-directional.
> 1 votes

---
Tags: arduino-mega, shields, gsm, electronics
---


title: Weird Arduino timer behaviour

text:
# Question
Title: Weird Arduino timer behaviour
I am trying to output something every one second with the following code.

```
volatile uint64_t timerCounts = 0;
double timenow,pretime;
void setup()
  {
     Serial.begin(19600);
     noInterrupts();
     TCCR2A = TCCR2B = 0;
     TCNT2 = 0;
     OCR2A = 124; //Zero Relative 125
     TCCR2B = B00001101;  //prescaler = 1024
     TIMSK2 |= (1 << OCIE1A);
     interrupts();

     Serial.print("Begin... \n");
  }

  //**********************************************************************
  //  Timer2 Interrupt Service is invoked by hardware Timer 2 every 0.008s
  //  16Mhz / 125 / 1024 = 125 Hz    0.008s

  ISR(TIMER2_COMPA_vect)
  {
     timerCounts++;
     if (timerCounts == 125){
        Serial.print("1s");
        timerCounts = 0;
     }
  }  // end of TIMER2_COMPA_vect

  void loop()
  {

  }

```

In the above code, I have set the `OCR2A`(output compare register) to 124\`\`, which is well below `256`(2^8). A user defined counter is also used.

However, when I execute the programme, the interval between consecutive outputs is less than 1 second.

When I change it to timer 1, the interval becomes roughly 1 second. When I change it to timer 0, the interval becomes longer than 1 second.

Anyone knows why?

Thanks.

# Answer
OCR2A doesn't do anything because the timer is in 'normal' mode. In normal mode the timer will just count to 256, not 125. Which would mean the you get a serial.print every 2.05s.

You need to use CTC mode. Do this by setting the `WGM21` bit to 1.

```
TCCR2A = _BV(WGM21);

```
> 1 votes

---
Tags: arduino-uno, pwm, timers
---


# Question
Title: How to make arduino show cpu usage with 10 leds?
So i want to make arduino show my computer cpu usage with leds, for example if 10% then 1 led will light, if 50% then 5 leds, if 80% then 8 leds...

# Answer
There's three basic steps you need to cover:

1. Get the CPU usage of your computer
2. Communicate that to the Arduino
3. Have the Arduino respond to the data

We can't really help you with step 1. That's outside our remit. You should head over to StackOverflow for that. How you would do it depends on your host OS since each one has its own way of reporting it.

For step 2 you would need to write software for your computer, incorporating what you have learned from step 1. Once you have the correct data you need to send it over to the Arduino through its serial connection. You'd need to come up with a good way of doing that, but probably just sending the usage percentage as plain ASCII text separated by new-lines is probably simplest.

Step 3 would entail reading in the data you sent in step 2, deciding what the numbers you have got mean, and then turning on the relevant LEDs.

Another option, which might simplify things a little, might be to use something like Firmata, where your PC sends the instructions to turn the LEDs on and off, and the Arduino just becomes a kind of dumb interface that doesn't do much on its own.
> 3 votes

---
Tags: led
---


# Question
Title: Arduino Leonardo on Win 8.1 COM port disappeared
I've been using an Arduino Leonardo on my Windows machine for a few days now without too much trouble but today the COM port disappeared. I've been able to successfully send sketches to the arduino and execute them so everything was working until recently. When I look in Device manager on the control panel there is no com port listed for the arduino. If I reset the device then a com port shows up briefly with "Arduino Leonardo BootLoader" but after a few seconds that disappears. I've tried USB2.0 and USB 3.0 ports on my PC and a different cable but to no avail. I don't have anything listed under "Other Devices" and I'm out of ideas for what could be the trouble. I'm trying to get it recognised now as just the leonardo with nothing connected to any pin. Any ideas of what to try?

# Answer
Strange, it's resolved itself/I resolved it. I don't know whether what I did was actually responsible for solving this but I'm back in business: * I reset the board so that the bootloader appeared as a com port * I set the arduino IDE to use the port that appeared for the bootloader * I uploaded a simple sketch and pressed reset during the "upload phase" so that the port appeared during the upload * the upload completed successfully and the arduino was back in the com port list

I'd still be interested to understand what I did that caused the problem in the first place but I suppose something was corrupted on the board?
> 1 votes

# Answer
Do note that on some example sketches the setup of the "Serial." function requires that there is special check for the serial port to be recognized/enabled (for the Leonardo only). Have you actually run a serial sketch to see if the com port comes back?

Did you load any other software or run virus checks that might have interfered with the special USB/Com driver?

You might try unloading and reloading the special driver used with the USB. Be sure to use the one specifically for Win8.
> 0 votes

---
Tags: serial, arduino-leonardo, communication
---


# Question
Title: Do addressable RGB's need to be programmed differently from normal RGB's?
I bought these rgb's from Sparkfun, however I have no idea how to hook them up or how to program them. Obviously the data sheet was somewhat helpful, however I have no idea how the IC's in the LED's work themselves or how to control them separately, or even how to string them together. My best guess is currently going for what the led's appear as in the example picture by connecting the first and last pins and putting the respective Vcc and ground pins to Vcc and ground.

Is there any good examples for hooking these up and coding them, or a basic understandable explanation for how they work?

Thanks, I can't find a great resource yet.

# Answer
These are much different than "normal" RGB LED: they use the **WS2812** chip, which is the same as the chip used in famous Adafruit "neopixels" strips, rings...

Wiring is simple. For all LEDs:

* GND to 0V
* VDD to 5V

For the first LED (connected to Arduino):

* DIN to any Arduino logical output pin
* DOUT to the 2nd LED you want to address (on its DIN pin)

For all but the first LED:

* DIN to the previous LED DOUT
* DOUT to the next LED DIN (or left floating for the last LED)

Programming neopixel is quite hard because timing of sent commands must be very precise.

I highly suggest to use Adafruit libraries for that.
> 3 votes

---
Tags: led
---


title: RGB fade program

text:
# Question
Title: RGB fade program
I'm working on a function to fade RGB LEDs smoothly from one color to the next, so I thought I'd use a for loop to increment each RGB value according with the set value. I've made the for loop as following:

```
for (redFadeCurrent, greenFadeCurrent, blueFadeCurrent;
   ((redFadeCurrent != redFadeTarget)&&
   (greenFadeCurrent != greenFadeTarget)&&
   (blueFadeCurrent != blueFadeTarget));
   redFadeCurrent = redFadeCurrent + redStep,
   greenFadeCurrent = greenFadeCurrent + greenStep,
   blueFadeCurrent = blueFadeCurrent + blueStep) {

    analogWrite(ledRedPin, redFadeCurrent);
    analogWrite(ledGreenPin, greenFadeCurrent);
    analogWrite(ledBluePin, blueFadeCurrent);
    Serial.print("Red: ");
    Serial.print(redFadeCurrent);
    Serial.print(" Green: ");
    Serial.print(greenFadeCurrent);
    Serial.print(" Blue: ");
    Serial.println(blueFadeCurrent);
    delay(3000);

    if (redFadeCurrent>redFadeTarget) {
        redStep = -1;
    }
    else if (redFadeCurrent<redFadeTarget) {
        redStep = +1;
    }
    else {
        redStep = 0;
    }

    if (greenFadeCurrent>greenFadeTarget) {
        greenStep = -1;
    }
    else if (greenFadeCurrent<greenFadeTarget) {
        greenStep = +1;
    }
    else {
        greenStep = 0;
    }

    if (blueFadeCurrent>blueFadeTarget) {
        blueStep = -1;
    }
    else if (blueFadeCurrent<blueFadeTarget) {
        blueStep = +1;
    }
    else {
        blueStep = 0;
    }

```

Problem is, when one of the values hit the target the code leaves the for loop. I'm guessing the condition `((redFadeCurrent != redFadeTarget)&&(greenFadeCurrent != greenFadeTarget)&&(blueFadeCurrent != blueFadeTarget))` does not work.

Is there any way to work around this?

Thanks is advance.

# Answer
> 2 votes
You are correct, the problem is the condition inside the `for` statement.

Let's examine what happens when the *red* LED hits its fading target, which is, say, 100 (for the sake of the example, I will fabricate the other values):

```
for (...; (100 != 100) && (90 != 100) && (80 != 100) ; ... )

```
* (100 != 100) -\> **FALSE**
* (90 != 100) -\> **TRUE**
* (80 != 100) -\> **TRUE**

**FALSE** && **TRUE** && **TRUE** -\> **FALSE**

The condition inside the `for` evaluates to `FALSE`, therefor the loop will exit.

If you want the loop to continue as long as there is at least one LED which hasn't hit the fading target, you should change the `AND` to `OR`:

```
((redFadeCurrent != redFadeTarget) || (greenFadeCurrent != greenFadeTarget) ||
   (blueFadeCurrent != blueFadeTarget))

```

Let's examine what happens now with the same values:

```
for (...; (100!=100) || (90 != 100) || (80 != 100) ; ...)

```
* (100 != 100) -\> FALSE
* (90 != 100) -\> TRUE
* (80 != 100) -\> TRUE

**FALSE** || **TRUE** || **TRUE** -\> **TRUE** ==\> The loop will continue.

And what will happen when all the colors hit the fading targets?

```
for (...; (100!=100) || (100 != 100) || (100 != 100) ; ...)

```
* (100 != 100) -\> FALSE
* (100 != 100) -\> FALSE
* (100 != 100) -\> FALSE

**FALSE** || **FALSE** || **FALSE** -\> **FALSE** ==\> The loop will stop since the condition will not evaluate to `TRUE`.

---
Tags: led
---


# Question
Title: Homemade soil moisture analog value reading jumping from 0 to max
I made a soil moisture sensor out of two metal poles, adjustable resistor, for a project I am making. The first run with the project the sensor worked amazing and gave clear and concise readings, 0-800 depending on water. I then unhooked the sensor and left it in the soil while I fine tuned the code (added warnings to the areas that would read to low), and while testing the code without the sensor being hooked up my arduino uno (Sparkfun Pro Mini) would read a value of 330(area). I thought this strange but didnt worry about it.

Well I hooked up my sensor (just power, ground, and to the A1 pin) and now my readout for the readings jump from 0 to 800, 0 to 512, 0 to another random number. I commented out everything in the code BUT the part that sets up the pin and displays the analog reading and its still the same issue. I also checked all my wires, changed the resistor setting, changed to a 10k single resistor, nothing changed.

Does anyone have any idea on what could be wrong?

# Answer
> 1 votes
You are constantly running .5mA through 2 nails in wet earth. What are they made of, that won't undergo some electrolysis in 1/2 hour? Gerben appears to have hit the, er, nail on the head in one, above.

You can avoid this to an extent by using a.c. drive to the probes, which reverses the effect so they only tarnish at about the normal rate for metal X in soil.

---
Tags: programming, sensors, analogread
---


title: Why are LED 0 and 1 on as well?

text:
# Question
Title: Why are LED 0 and 1 on as well?
I was just playing around a bit and ran into a strange problem. LED 3, 5, 6, 9 and 10 are on, as intended. For some reason LED 0 and 1 are on as well. Can someone explain why this is happening?

```
int ledPins[] = {3, 5, 6, 9, 10};
int pinCount = sizeof(ledPins);

void setup(){
  for (int i = 0; i < pinCount; i++){
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop(){
   for (int i = 0; i < pinCount; i++){
     digitalWrite(ledPins[i], 1);
   }
}

```

# Answer
> 12 votes
The behaviour of your program is undefined because you're reading past the end of your array.

In C/C++, the `sizeof` operator always gives you the size of something in **bytes**. It doesn't directly tell you the number of items in an array. Since `int` is usually 2 bytes for Arduino programming, the `pinCount` variable is actually being initialised to **10** (5 items x 2 bytes each).

The result is that each `for` loop is actually doing 10 iterations. The first 5 iterations are OK, reading correctly from the `ledPins` array. However, the rest of the iterations are reading whatever data happens to be in memory after that. This means it could be trying to initialise and switch on any pin, potentially including 0 and 1.

I can't guarantee that this is the source of the problem, but it's certainly very important to fix.

The solution is quite easy though. Divide the total size of the array by the size of a single element:

```
int pinCount = sizeof(ledPins) / sizeof(int);

```

# Answer
> 4 votes
You haven't initialised the other pins at all; or included your circuit, but clearly you have LEDs on more pins than those defined (5 defined, 7 on).

The other LEDs are, therefore, in an undefined state - and may well be attached to pins set 'on' by default in your circuit. You probably need to either move 0/1 off the serial interface or explicitly set them 'off'.

---
Tags: led
---


# Question
Title: Unable to connect to Linux Environment (Linino AR9331 Interface) in Arduino Yun
I was trying to reset my Arduino Yun (WLAN button pressed for more than 30 seconds), but it just kept on blinking for about 10 minutes. Then I finally got impatient and restarted the Yun. After the restart, there was no WLAN (blue) or USB (white) LED blinking or glowing anymore. I am unable to connect through the Wifi network, the Yun does not create it's own Wifi network and unfortunately when connected via Ethernet, I can still not navigate to arduino.local or 192.168.240.1.

So I have a feeling that somehow only the AVR is still functioning (because I can still upload sketches) and nothing else.

I have updated the firmware to the latest version (OpenWrt-Yun 1.5.3). Is there a way to connect or reset, if the Ethernet does not work? Can I upload a sketch to check in the console if the Linino interface still functions.

Thanks in advance!

# Answer
Try uploading YunSerialTerminal example, opening the serial monitor and pressing the YUN RST button. You should see the linux side starting.

If it starts but it looks somehow bricked, you could try following the http://arduino.cc/en/Tutorial/YunUBootReflash tutorial.
> 0 votes

---
Tags: arduino-yun, ethernet
---


# Question
Title: Power consumption issue. I made project using atmel-328p
I made project using atmel-328p. I want to run it over a year. I am using power\_down mode & 5500 mAh li-ion battery still battery discharges in 1 day. I am using standard code as explain on arduino site. code is:

```
String uniqueid;
char value;
volatile int NbTopsFan; //measuring the rising edges of the signal
uint32_t Calc;
int hallsensor = 2;    //The pin location of the sensor
int power = 4;
// ph sensor
define SensorPin 0          //pH meter Analog output to Arduino Analog Input 0
define Offset 0.00            //deviation compensate
unsigned long int avgValue;    //Store the average value of the sensor feedback
// temp sensor
OneWire  ds(8);
byte i;
byte present = 0;
byte data[12];
byte addr[8];
int HighByte, LowByte, SignBit, Whole, Fract, TReading, Tc_100, FWhole;

int wakePin = 3;                 // pin used for waking up
int sleepStatus = 0;             // variable to store a request for sleep
int countsleep = 0;                   // counter

void wakeUpNow()        // here the interrupt is handled after wakeup
{// execute code here after wake-up before returning to the loop() function
 }
void rpm ()     //This is the function that the interupt calls
{
 NbTopsFan++;  //This function measures the rising and falling edge of the
//hall effect sensors signal
}
void setup()
{
 pinMode(hallsensor, INPUT); //initializes digital pin 2 as an input
Serial.begin(9600); //This is the setup function where the serial port is
pinMode(power, OUTPUT);
//initialised,
 attachInterrupt(0, rpm, RISING); //and the interrupt is attached
//initialised,
  //and the interrupt is attached
// temp sensor pin 8
        if ( !ds.search(addr))
        {
           //       Serial.println("temp sensor is not connected");
        delay(1000);
        ds.reset_search();
        return;
        }
        if ( OneWire::crc8( addr, 7) != addr[7])
        {
       //      Serial.println("CRC not valid!");
       delay(1000);
       return;
        }
pinMode(wakePin, INPUT);

  attachInterrupt(1, wakeUpNow, LOW); // use interrupt 1 (pin 3) and run function

}

void sleepNow()         // here we put the arduino to sleep
{
  countsleep = 0;
ADCSRA = 0;

   set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    sleep_enable();          // enables the sleep bit in the mcucr register
                             // so sleep is possible. just a safety pin
  // turn off brown-out enable in software
  MCUCR = bit (BODS) | bit (BODSE);  // turn on brown-out enable select
  MCUCR = bit (BODS);        // this must be done within 4 clock cycles of above

 sleep_cpu ();

    attachInterrupt(1,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                                       // wakeUpNow when pin 2 gets LOW

    sleep_mode();            // here the device is actually put to sleep!!
                             // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

    sleep_disable();         // first thing after waking from sleep:
                             // disable sleep...
    detachInterrupt(1);      // disables interrupt 0 on pin 2 so the
                             // wakeUpNow code will not be executed
}

void loop()
{

  countsleep++;
  delay(1000);                           // waits for a second
// compute the serial input
  if (Serial.available())
  {
    String content = "";
    char character;
// to read serial data coming
        while(Serial.available()>0)
          {
              character = Serial.read();
              content.concat(character);
          }
      String uniqueidread = content.substring(0,16);
      String parameter = content.substring(16,17);
      String checkuuid = content.substring(0,3);
      String putinsleep = content.substring(0,5);
       if (uniqueidread == uniqueid && parameter == "5")
{         //    Serial.flush();
digitalWrite(power,HIGH);
 NbTopsFan = 0;      //Set NbTops to 0 ready for calculations
 sei();            //Enables interrupts
 delay (1000);      //Wait 1 second
 cli();            //Disable interrupts
 Calc = (NbTopsFan * 60 / 7.5); //(Pulse frequency x 60) / 7.5Q, = flow rate

  digitalWrite(power,LOW);
          getTemp();
          delay(1000);
          getTemp();
          //   printTemp();
      Serial.print("Temp is: ");
           if (SignBit)
           {
                Serial.print(" - ");
           }
           if( Whole == 0)
           {
              Serial.print("temp sensor is not connected");
           }
           else
           {
              Serial.print(Whole);
              Serial.print(" C / ");
              Serial.print(FWhole);
              Serial.print(" F");
            }
              Serial.print(", Current Reading = ");
     Serial.print (Calc, DEC); //Prints the number calculated above
            Serial.print(" L/hour");
   phvalue();
            Serial.println("S=m");
              delay(100);
              sleepNow();
}

         if ( content == "sleep")
         {
          Serial.println("S=m");
          delay(100);     // this delay is needed, the sleep
          sleepNow();     // sleep function called here
         }
}

  if (countsleep >= 10)
  {
      Serial.println("T=m");
      delay(100);     // this delay is needed, the sleep
                      //function will provoke a Serial error otherwise!!
      sleepNow();     // sleep function called here
  }
}
      void getTemp()
          {
              int foo, bar;

              ds.reset();
              ds.select(addr);
              ds.write(0x44,1);

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

              for ( i = 0; i < 9; i++) {
                data[i] = ds.read();
              }

              LowByte = data[0];
              HighByte = data[1];
              TReading = (HighByte << 8) + LowByte;
              SignBit = TReading & 0x8000;  // test most sig bit

              if (SignBit) {
                TReading = -TReading;
              }
              Tc_100 = (6 * TReading) + TReading / 4;    // multiply by (100 * 0.0625) or 6.25
              Whole = Tc_100 / 100;          // separate off the whole and fractional portions
              Fract = Tc_100 % 100;
              if (Fract > 49) {
                if (SignBit) {
                  --Whole;
                } else {
                  ++Whole;
                }
              }

              if (SignBit) {
                bar = -1;
              } else {
                bar = 1;
              }
              foo = ((Whole * bar) * 18);      // celsius to fahrenheit conversion section
              FWhole = (((Whole * bar) * 18) / 10) + 32;
              if ((foo % 10) > 4) {            // round up if needed
                   ++FWhole;
              }
            }
void printTemp(void)
{
         Serial.println("");
         Serial.print("Temp is: ");
         if (SignBit)
         {
              Serial.print(" - ");
         }
         Serial.print(Whole);
         Serial.print(" C / ");
         Serial.print(FWhole);
         Serial.print(" F");
}
void phvalue()
{
    int buf[10];                //buffer for read analog
    for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
    {
      buf[i]=analogRead(SensorPin);
      delay(10);
    }
    for(int i=0;i<9;i++)        //sort the analog from small to large
    {
      for(int j=i+1;j<10;j++)
      {
        if(buf[i]>buf[j])
        {
          int temp=buf[i];
          buf[i]=buf[j];
          buf[j]=temp;
        }
      }
    }
    avgValue=0;
    for(int i=2;i<8;i++)                      //take the average value of 6 center sample
      avgValue+=buf[i];
    float phValue=(float)avgValue*5.0/1024/6; //convert the analog into millivolt
    phValue=3.5*phValue+Offset;                      //convert the millivolt into pH value
    Serial.print(" pH:");
    Serial.print(phValue,2);
    Serial.print(" ");
}

```

# Answer
You need to first check the individual current consumption of all elements:

* pH sensor,
* temp sensor,
* water flow sensor
* xbee.

Since many of these just have an output pin in addition to +V & GND, this means those have a permanent current consumption that, overall, may possibly drain your battery.

You should then check the datasheets for all these components and see the minimum current consumption (and conditions for this consumption to be achieved).

If the total minimum current for these components is too high for your system, then you can possibly:

* use an available ATmel digital output pin to power them (and unpower them just before switching the ATmel to low power mode); that's possible only if you stay within current limitations of the MCU (there are current limitation per pin, 20mA IIRC, and total current for the whole MCU)
* if current consumption is above ATmel limits then you can still use the method above but add a MOSFET in-between so that you limit ATmel current consumption

I strongly advise you this link from Nick Gammon, which is comprehensive and complete.
> 4 votes

---
Tags: power, interrupt, atmega328, sleep
---


# Question
Title: Arduino Uno with SD, Cardinfo sketch how to list only visible files
There are two files (that can be seen on my computer) on my sd card, `6.bmp` and `example.txt` (the latter written from my arduino). I have them connected to my arduino via LCSTUDIO breakout board (which surprisingly caused me no trouble at all).

When I run the example "cardinfo" sketch, the files it lists includes those two files along with tons of others, which I assume are just invisible from a personal computer.

How would I list only the files that can be seen from my computer (i.e. aren't inside any directory, but are just plain in the SD card)?

Using arduino UNO

# Answer
Simple Answer: Don't think you can

Long Answer: Dont think you can, because, unlike an OS like windows, mac, linux, etc. The arduino just tales all the files. You could save those two files and format it as FAT16 though, then add the 2 files back on the sd and there you go.
> 0 votes

---
Tags: arduino-uno, sd-card
---


# Question
Title: The Arduino robot tutorials describe a cord comming with the official robot, now I'm confused
I recently got the Arduino Robot and have been looking at the examples for the RobotLibrary. As I looked, I found something quite confusing (for me at least), a few of them describe connecting a sensor (like an IR sensor or Ultrasonic sensor) to a port with a cable that was provided with the robot. But I never received a cable. Which got me to question, what type of cable is this, because it is not the same cable you would use on an UNO, at least not according to the pictures. So does anyone know what type of cables these are and/or where I can get them? Thanks :smiley-mr-green:

Here are the pictures btw:

And the next one:

# Answer
Usually, Arduino gives you the minimal board and sends you on your way. Reading over the instructions, I think they mean a cable that would have come with the IR sensor. That three-tone cord you see in the pictures are actually just three wires. You connect them as described if they came with the sensors. More likely, if they did not, you can use your own wires to connect these. Just be sure that you understand which is the ground (GND), power (+5V or some other +V), and signal. Usually, ground is denoted by the darkest color: black or brown; power is usually red, and signals can be any light color. USUALLY (READ about your device before you plug it in) ground and power are side-by-side for IR sensors, and signal is on the outside. Take a few minutes to Google up your device before plugging it in if you don't have documentation.

Good Luck!
> 1 votes

---
Tags: hardware, robotics
---


# Question
Title: Why client.stop causes some significant delay to do another task in a loop?
```
void setup() {
    Serial.begin(9600);        // Initialize serial communications with the PC

    // disable SD SPI
    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);

    // disable w5100 SPI
    pinMode(10, OUTPUT);
    digitalWrite(10, HIGH);

    SPI.begin();                // Init SPI bus
    mfrc522.PCD_Init();        // Init MFRC522 card
    //Serial.println("Scan a MIFARE Classic PICC to demonstrate Value Blocks.");

    Ethernet.begin(mac, ip); //we used a STATIC address to start ETHERNET

    // print your local IP address:
    Serial.print("My IP address: ");
    for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(Ethernet.localIP()[thisByte], DEC);
        Serial.print(".");
    }
    // give the Ethernet shield a second to initialize:
    delay(1000);
    Serial.println("connecting...");
}

void loop() {

    // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
    MFRC522::MIFARE_Key key;
            key.keyByte[0] = 0xFF;
            key.keyByte[1] = 0xFF;
            key.keyByte[2] = 0xFF;
            key.keyByte[3] = 0xFF;
            key.keyByte[4] = 0xFF;
            key.keyByte[5] = 0xFF;

    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }
    // Now a card is selected. The UID and SAK is in mfrc522.uid.

    // Dump UID
    //Serial.print("Card UID:");
    //Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : "");

    // In this sample we use the second sector (ie block 4-7). the first sector is = 0
    // scegliere settore di lettura da 0 = primo settore
    byte sector         = 0;
    // block sector 0-3(sector0) 4-7(sector1) 8-11(sector2)
    // blocchi di scrittura da 0-3(sector0) 4-7(sector1) 8-11(sector2)
    byte valueBlockA    = 0;
    byte valueBlockB    = 1;
    byte valueBlockC    = 2;
    byte trailerBlock   = 3;
    byte status;
    // Authenticate using key A.
    // avvio l'autentificazione A
    //Serial.println("Authenticating using key A...");
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK)
    {
        Serial.print("PCD_Authenticate() failed: ");
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
    }

   //No KEY B Authentication
   int val1 =(mfrc522.uid.uidByte[0]);
   int val2 =(mfrc522.uid.uidByte[1]);
   int val3 =(mfrc522.uid.uidByte[2]);
   int val4 =(mfrc522.uid.uidByte[3]);

   String valA=String(val1);
   String valB=String(val2);
   String valC=String(val3);
   String valD=String(val4);

   uID=valA+valB+valC+valD;
   Serial.print(uID);
   Serial.println();
   counter=counter+1;
   Serial.print(counter);
   //}
   Serial.println();

   // Halt PICC
   mfrc522.PICC_HaltA();

   // Stop encryption on PCD
   mfrc522.PCD_StopCrypto1();

   if (counter>first)
   {//delay ifs
       // enable w5100 SPI
       if (client.connect(server, 80)) { //start of IF
           Serial.println("connected");
           client.print("GET /accessdenyrfid.php?rfid="); //dont make these println
           client.print(uID);   //dont make these println
           client.print("&&");
           client.print("ip=mech1");

            //client.print( ip );
            //client.print("&&");
            //client.print("ipkey=");
            //client.print( ipkey );

            client.println(" HTTP/1.1");   //println
            client.println("Host: ");    //println
            client.print(server);//don't make println
            client.println("Connection: close");  //println
            client.println();   //terminates the query
            Serial.print("SENT");
            Serial.println();
            first++;
            Serial.print(first);
            Serial.println();
            // add this
            while(client.connected()) {
                while(client.available()) {
                    char ch = client.read();
                    Serial.write(ch);
                }
            }

           client.stop();
           client.flush();

       } //end OF IF
    }//delay ifs
}

```

The code above works perfectly with another php. that either saves or denies a card into a database. The arduino sends and receives data back and forth from and to php in less than a second. But the problem is that whenever the function client.stop is called. It takes approx. 8 seconds before another data is sent in the loop function. I need the loop to continue with just 2 second interval, which is enough or even faster. I don't think that the mysql query in the php is the one that makes it longer cause all the queries are made before the delay starts. (The server has already sent it's response, before the delay starts, which i think is in the client.stop.) Please help me on other alternatives on stopping the client or any way I can do this faster. Thanks, I'm really in trouble right now. I'm using Arduino UNO. Data sent back and forth are just a couple of letters and numbers.

# Answer
I would bet the problem relies on

```
if (counter>first)

```

As seems like you never reset counter, there might be weird things going on
> 1 votes

---
Tags: arduino-uno, ethernet
---


# Question
Title: How to make MEMS IR Thermal Sensor - D6T-44-L06 work with Arduino?
I am working on project that my team need to detect the presence of the people. At first, we tried with motion sensor but it wasn't the way that we want it to work. We want to detect presence of the people even they don't move.

We decide to go with Omron Thermal Sensor D6T-44-L06. However, there lacking of tutorial or simple code online that actually show how to connect that Omron thermal sensor with Arduino. How can I interface this with Arduino?

# Answer
> 1 votes
Yes should be really easy to implement, as it work like almost all i2c sensor; this manual as also some code example, the chip address, and finally the registry address; that is all you need. http://www.mouser.com/pdfdocs/D6T01\_ThermalIRSensorWhitepaper.pdf

---
Tags: sensors, arduino-yun, temperature-sensor
---


title: Decoding a RS232 message in Arduino

text:
# Question
Title: Decoding a RS232 message in Arduino
I have an Arduino Mega with an MaxBotix (MB7066) sonar attached, the sonar has the ability to send serial data with it's reading. It uses a asynchronous RS232 format, except the voltages are 0-Vcc. The output should be a capital "R" (ASCII), followed by four digits(ASCII) and a carriage return (ASCII 13). The baud rate is 9600, 8 bits, no parity with one stop bit. What I get from the device is as follows: (sonarSerial.read() while sonarSerial.available())

```
43
192
6
6
179
89
30
0

```

What do I have to get to the information? Or is my sensor just retuning garbage? Please see the code below:

```
#include <SoftwareSerial.h>

#define pin1 3
#define pin2 5 //pwm
#define pin3 6 //analog
#define pin4 10 //RX for sonar, TX for arduino
#define pin5 11 //TX for sonar, RX for arduino

SoftwareSerial sonarPort(pin5,pin4);

void setup(){
   Serial.begin (9600);
   pinMode(pin1, OUTPUT);

   pinMode(pin4, OUTPUT);
   pinMode(pin5, INPUT);
   sonarPort.begin(9600);
}

void loop(){
  digitalWrite(pin1, HIGH);

  digitalWrite(pin4, LOW);
  digitalWrite(pin4, HIGH);
  delayMicroseconds(20);
  digitalWrite(pin4, LOW);

  long pulse = pulseIn(pin2, HIGH)/58;
  Serial.print("PM Result: ");
  Serial.println(pulse);

  String buffer = "";
  sonarPort.listen();
  while(sonarPort.available() > 0){
      int inByte = sonarPort.read();
      buffer += inByte; buffer += " ";
      if(!sonarPort.available()){
          Serial.print("Serial result: ");
          Serial.println(buffer);
      }
  }
  delay(500);
}

```

# Answer
I contacted MaxBotix with the problem and for my surprise their technical support is really great:

> The Arduino is set up to natively read TTL serial data.The MB7066 outputs its serial data in the RS232 format. Do not worry; this problem can easily be fixed. You can use an inverter such as the MAX232. You can also follow the following tutorial to make your own https://github.com/simonmonk/raspirobotboard/wiki/Rangefinder-Adapter.
>
> Another option would be to test using this code section SoftwareSerial sonarSerial(rxPin, txPin, true); //define serial port for recieving data, output from maxSonar is inverted requiring true to be set.
> 1 votes

# Answer
In the bitstream of your ASCII data the pattern for "R" (01010010b) does never occur.
So obviously something is wrong in your system and/or setup. Have you already considered the information given here http://www.maxbotix.com/articles/034.htm?

I would connect the sensor to a PC to check whether it's working correctly using a standard terminal software.
> 0 votes

---
Tags: serial, arduino-mega
---


title: Resetting an Arduino with a timer

text:
# Question
Title: Resetting an Arduino with a timer
I want to run an Arduino autonomously - but although I apply a watchdog sometimes the systems hangs and can only be restarted by physically interrupting the power-supply (or hitting reset). So I need an external source to do that either after x hrs or based on a condition.

Instead of using another Arduino with a MOSFET or relay I am asking myself if this couldn't be done smarter with a pure electronic component like a timer or a capacitor. I could set a pin of the Arduino on high while it is active and let this charge a capacitor or something similar - if the time/energy exceeds a certain amount (because it hangs) this would connect the reset-pin of the Arduino to ground.

Any idea how this could be achieved and what component should be used?

# Answer
The following 555 circuit will produce a 170 ms low-going pulse every 24.2 hours. You can adjust the values of the components using this calculator if you want different timing parameters.

Since the reset line of a microcontroller is configured for open-drain (meaning you can connect several inputs to it, which is a good thing since we are taking advantage of that), we need to drive it with a open-drain output. That is what the buffer on the bottom of the circuit is for, to convert the push-pull output of the 555 to open-drain. A typical buffer is one section of a 7407.
> 4 votes

# Answer
Here is the circuit I use which depends on a heartbeat from the arduino and resets the arduino if 8 pulses are missed and also enables the arduino code to know that an external watchdog reset occured

```
and the Arduino code which can be incorporated into your sketch

//Watchdog
#define ResetDetect 8       // watchdog detect pin, HIGH if a watchdog reset has occured
#define heartbeat 9         // heartbeat pin
int pulseState = LOW;       // pulseState used to set the heartbeat pin
long lastbeat = 0;          // will store last time the heartbeat pin was updated
long HeartBeatFreq = 500;   // interval at which to blink (milliseconds)
boolean ResetHappened;      // Set to true if a watchdog reset has occurred

void setup(){
  pinMode(ResetDetect, INPUT);    // set Watchdog Reset sensing pin as input
  digitalWrite(ResetDetect, HIGH);// and turn on pullup
  pinMode(heartbeat, OUTPUT);     // set the heartbeat pin as output:

    // Check if Restarting after Watchdog Reset
    // NB must come before heartbeat resets external counter
    int ResetSet = digitalRead(ResetDetect);
    if (ResetSet == HIGH){
      ResetHappened = true;
    }
    else {
      ResetHappened = false;
    }
}

void loop(){

  // Heartbeat resets external watchdog when pin goes high
  if ((long)( millis() - (lastbeat + HeartBeatFreq)) >= 0) {
    lastbeat = millis();
    // if the LED is off turn it on and vice-versa:
    if (pulseState == LOW)
      pulseState = HIGH;
    else
      pulseState = LOW;
    // set the LED with the ledState of the variable:
    digitalWrite(heartbeat, pulseState);
  }
}

```

If there are long running sections of code the 'heartbeat' could be put into a function and that function called in the appropriate places to avoid unintended timeouts/resets
> 4 votes

# Answer
Why not use the in-ship watchdog timer ?

I found in the Atmel ATmega328 (used for example in the official Arduino Uno board) official datasheet some references :

```
http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet.pdf

```

We can find on page #5 two blocks named "Watchdog Timer" and "Watchdog Oscillator" on the upper left corner. No need of additional circuits, soldering or any connections.

These blocks are bad documented on the Arduino official website but usable (I did it).

Some docs with code examples :

Regards
> 1 votes

---
Tags: reset
---


# Question
Title: Concatenate two non constant char arrays in Arduino
I have two non constant char arrays. One is "buff" and other is "buffa". I get values in buffa via rf transmitter of other Arduino and I want to append those data to the data inside of buff. Then I will send all data to other Arduino. So I don't want to send two different char arrays. I want to send them all at once as just one array.

I TRIED SPRINTF BUT IT DOESNT WORK.

```
char buffa[144];
    char buff[1000];

void loop() {

  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;

  sprintf(buff,"<status>\n");

    if (vw_get_message(buf, &buflen)) { // check to see if anything has been received
      int i;
      for (i = 0; i < buflen; i++) {
        buffa[i] = (char) buf[i];  // the received data is stored in buffer

      }
    }

  distance1 = getDistance(initPin1, echoPin1);
  sendData(3, distance1);

  sprintf(buff, "%s", buffa);

delay(5000);
 const char *msg0 = buff;

 vw_send((uint8_t *)msg0, strlen(msg0)); // Send control character
 vw_wait_tx();

 Serial.print(msg0);

}

```

# Answer
Assuming the data in buffa is a c-style string (i.e. null-terminated), replace

```
sprintf(buff, "%s", buffa);

```

with

```
strcat( buff, buffa );

```
> 3 votes

---
Tags: c
---


title: Cannot control servo with button.

text:
# Question
Title: Cannot control servo with button.
I am unable to get a button on my arduino board to control a servo. I'd like the servo to rotate 90 degrees on button push, but it is unresponsive.

Is there a flaw in my code or is it wiring?

```
#include <Servo.h>  // servo library

const int button1Pin = 2;  // pushbutton 1 pin
Servo servo1; // servo control object

void setup()
{
  pinMode(button1Pin, INPUT);
  servo1.attach(9);

  // Set servo 1 to output?
}

void loop()
{
  int button1State;
int position;

button1State = digitalRead(button1Pin);

if (button1State == LOW);
{
  servo1.write(90);  // move servo
}

}

```

# Answer
The problem is that `servo1.write(90)` does not do what you think it does.

`servo.write(angle)` tells the servo to go to that position, not to move by that many degrees. What you need is to set one angle when the button is not pressed, and a different angle when the button is pressed.

Normal hobby servos can move about 180 degrees. Where 0 is depends on how the servo horn is positioned. Which direction of rotation is positive depends on the manufacturer.

try something like this to set one position when the button is pressed and a different one when it is not:

```
if (button1State == LOW);{
    servo1.write(45);  // move servo
}
else {
    servo1.write(135);
}

```
> 1 votes

---
Tags: arduino-uno, servo
---


title: Arduino CC3000 websocket client

text:
# Question
Title: Arduino CC3000 websocket client
I am working for arduino websocket client with CC3000 wifi board from adafruit. I have usde this websocket example as a reference and modified to work with cc3000 wifi board. I am not able to connect to echo.websocket.org. My code shows client is not connected and unavailable to communicate after sending the upgrade headers. Here is the serial monitor response for the code:

```
echo.websocket.org -> Errno: 1
174.129.224.73-------------------------------------
Client connected
Sending websocket upgrade headers
Analyzing response headers
client not connected
client not available

```

here is the Arduino sckech:

```
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include <WebSocketClient.h>
#include "utility/debug.h"

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
SPI_CLOCK_DIVIDER); // you can change this clock speed

#define WLAN_SSID       "UNSTOPPABLE"           // cannot be longer than 32 characters!
#define WLAN_PASS       "8878333344"
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

#define IDLE_TIMEOUT_MS  3000      // Amount of time to wait (in milliseconds) with no data
// received before closing the connection.  If you know the server
// you're accessing is quick to respond, you can reduce this value.

// What page to grab!
#define WEBSITE      "echo.websocket.org"
//#define WEBPAGE      "/testwifi/index.html"

// Here we define a maximum framelength to 64 bytes. Default is 256.
#define MAX_FRAME_LENGTH 64

// Define how many callback functions you have. Default is 1.
#define CALLBACK_FUNCTIONS 1

Adafruit_CC3000_Client www;
WebSocketClient webSocketClient;
/**************************************************************************/
/*!
 @brief  Sets up the HW and the CC3000 module (called automatically
 on startup)
 */
/**************************************************************************/

uint32_t ip;

void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  Serial.print("Free RAM: ");
  Serial.println(getFreeRam(), DEC);

  /* Initialise the module */
  Serial.println(F("\nInitializing..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }

  // Optional SSID scan
  // listSSIDResults();

  Serial.print(F("\nAttempting to connect to "));
  Serial.println(WLAN_SSID);
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

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

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

  cc3000.printIPdotsRev(ip);

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

  /* Try connecting to the website.
   Note: HTTP/1.1 protocol is used to keep the server from closing the connection before all data is read.
   */
  www = cc3000.connectTCP(ip, 80);
  if (www.connected()) {
    /*    www.fastrprint(F("GET "));
     www.fastrprint(WEBPAGE);
     www.fastrprint(F(" HTTP/1.1\r\n"));
     www.fastrprint(F("Host: ")); www.fastrprint(WEBSITE); www.fastrprint(F("\r\n"));
     www.fastrprint(F("\r\n"));
     www.println();*/
  }
  else {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("-------------------------------------"));

  /* Read data until either the connection is closed, or the idle timeout is reached. */
  /*  unsigned long lastRead = millis();
   while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
   while (www.available()) {
   char c = www.read();
   Serial.print(c);
   lastRead = millis();
   }
   }
   www.close();
   Serial.println(F("-------------------------------------"));*/

  /* You need to make sure to clean up after yourself or the CC3000 can freak out */
  /* the next time your try to connect ... */
  /*  Serial.println(F("\n\nDisconnecting"));
   cc3000.disconnect();*/
  // Handshake with the server
  webSocketClient.path = "/";
  webSocketClient.host = WEBSITE;

  if (webSocketClient.handshake(www)) {
    Serial.println("Handshake successful");
  }
  else {
    Serial.println("Handshake failed.");
    while(1) {
      // Hang on failure
    }
  }
}

void loop(void)
{
  String data;
  if (www.connected()) {

    /*   data = webSocketClient.getData();

     if (data.length() > 0) {
     Serial.print("Received data: ");
     Serial.println(data);
     }*/

    // capture the value of analog 1, send it along
    pinMode(1, INPUT);
    data = String(analogRead(1));

    webSocketClient.sendData(data);

  }
  else {

    Serial.println("Client disconnected.");
    while (1) {
      // Hang on disconnect.
    }
  }

  // wait to fully let the client disconnect
  delay(3000);
}

```

If anybody can guide me where I am wrong then it would be great help.I have taken reference code from brandenhall/Arduino-Websocket

# Answer
here the problem is i am not receiving anything from server. My client disconnected from the server after sending the Upgrade headers. that's why in wire-shark i am not getting anything from server I think so. here is code which do handshake with server.The problem is i am not receiving anything from server. My client disconnected from the server after sending the Upgrade headers. that's why in wire shark i am not getting anything from server I think so. here is code which do handshake with server:

`bool WebSocketClient::analyzeRequest() {
 String temp;
 int bite;
 bool foundupgrade = false;
 unsigned long intkey[2];
 String serverKey;
 char keyStart[17];
 char b64Key[25];
 String key = "------------------------";
 randomSeed(analogRead(0));
 for (int i=0; i<16; ++i) {
 keyStart[i] = (char)random(1, 256);
 }
 base64_encode(b64Key, keyStart, 16);
 for (int i=0; i<24; ++i) {
 key[i] = b64Key[i];
 }
 Serial.println(F("Sending websocket upgrade headers"));
 socket_client->print(F("GET "));
 socket_client->print(path);
 socket_client->print(F(" HTTP/1.1\r\n"));
 socket_client->print(F("Upgrade: websocket\r\n"));
 socket_client->print(F("Connection: Upgrade\r\n"));
 socket_client->print(F("Host: "));
 socket_client->print(host);
 socket_client->print(CRLF);
 socket_client->print(F("Sec-WebSocket-Key: "));
 socket_client->print(key);
 socket_client->print(CRLF);
 socket_client->print(F("Sec-WebSocket-Protocol: "));
 socket_client->print(protocol);
 socket_client->print(CRLF);
 socket_client->print(F("Sec-WebSocket-Version: 13\r\n"));
 socket_client->print(CRLF);
 Serial.println(F("Analyzing response headers"));
 //here it got disconnected
 while (socket_client->connected() && !socket_client->available()) {
 delay(100);
 Serial.println("Waiting...");
 }
 // TODO: More robust string extraction
 while ((bite = socket_client->read()) != -1)
 {
 temp += (char)bite;
 if ((char)bite == '\n')
 {
 #ifdef DEBUGGING
 Serial.print("Got Header: " + temp);
 #endif
 if (!foundupgrade && temp.startsWith("Upgrade: websocket"))
 {
 foundupgrade = true;
 }
 else if (temp.startsWith("Sec-WebSocket-Accept: "))
 {
 serverKey = temp.substring(22,temp.length() - 2); // Don't save last CR+LF
 }
 temp = "";
 }
if (!socket_client->available()) {
 delay(20);
 }
 }
key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
 uint8_t *hash;
 char result[21];
 char b64Result[30];
 Sha1.init();
 Sha1.print(key);
 hash = Sha1.result();
 for (int i=0; i<20; ++i) {
 result[i] = (char)hash[i];
 }
 result[20] = '\0';
 base64_encode(b64Result, result, 20);
 // if the keys match, good to go
 return serverKey.equals(String(b64Result));
}`
> 1 votes

---
Tags: arduino-uno, wifi, code-review
---


title: Variable current switch by human touch

text:
# Question
Title: Variable current switch by human touch
Two goals:

1. Make an LED turn on when a person touches two conductive pads (e.g. two square of aluminum foil)
2. Make the RGB LED change color depending on how hard the pads are squeezed. I will figure out the color algorithm later. For now I just need to be able to sense variable conductivity/capacitance/current (one of those?).

I have an Arduino LilyPad. I know this can be done because I've seen it before (just don't remember the code or circuit). Example image:

I know the human body is conductive, so I'm not quite sure why the LED won't go on when I contact the conductive pads. My only hypothesis is that the resistance is too high, but that must mean *some* current is going through, no?

Thanks.

# Answer
> 1 votes
I am going to make this answer as simple as I can, the body is not THAT conductive, you gotta use something like a touch sensor.

# Answer
> 1 votes
Okay; to start with, the Arduino Playground has a how-to guide, the components are commonplace - either recycle a high-resistance resistor from junk or buy one from eg Maplin at 38p.

This works as follows: You charge the capacitor with one output, through a resistor. This charges the capacitor in RxC seconds - C is very small, typically 10^-11 or so, so a decent sized resistor helps make it slow, in computer terms. Ensure this is held on for long enough to charge fully. You can use one charge pin for many touch sensors.

You then drop the charge pin to 0, and see how fast the sense voltage drops; this will be affected by fingers etc, giving a time value reflecting the degree of contact; normally this is used as a threshold on/off, but does allow for some pressure sensitivity. You need one R/C/sense-pin per switch.

---
Tags: wires, potentiometer
---


title: Arduino and Raspberry Pi - 5V/3.3V I2C

text:
# Question
Title: Arduino and Raspberry Pi - 5V/3.3V I2C
This topic have been covered in various places, but I still think it hasn't been thoroughly explained anywhere. Doing google search on connecting Arduino to Raspberry Pi via i2c gives for example, this page.

While apparently this should work, there is a factual error there: on arduino side, pins used for i2c do have internal pull ups, and they are activated by `Wire` library.

Digging further, I've found following information:

> However, it turns out that these are weak (high-resistance) pull-ups; the Pi has strong pull-ups which dominate those on the Arduino, making direct connection safe.

What does safe mean? And how weaker are those pullups compared to raspberry pi ones?

Let's check:

* rpi i2c pullup: 1K8
* arduino i2c pullup: 20K-50K from datasheet (if I'm looking correctly, I'm using ATmega8), though the above page states 10K.

What can I make of those values? My (intuition rather than) basic knowledge hints me something along the lines:

If the i2c is floating, it means the 5V is connected with 3.3V and there are only those pullups along the way, so:

* calculate voltage drop between 5 and 3.3: 1.7V.
* calculate voltage drop across rpi pullup proportionally to voltage drop across arduino pullup: 1800 / 30000 = 0.06, meaning 0.102V across rpi pullup and 1.598 across arduino pullup, so the actual pulled up voltage is gonna be 3.3V + 0.102V = 5V - 1.598V = 3.402V?

Though I'm pretty sure I'm doing some terrible math here and someone is gonna have good laugh:)

So, my question is not whether it's safe (as it's been proved), but rather *why* is it safe considering the internet resources are inaccurate on this matter.

# Answer
> 1 votes
If you are sure to disable pull up on arduino side you are safe, as i2c works in open-drain mode, but the logic level "high" of arduino is about 3.2v, so it would be unstable.

Otherwise i2c pin of rasp are NOT 5v tolerant, so you must be sure the voltage on the bus does not exceed operative limit; as you calculated ~3.5v should be good on raspi, but please check on datasheet.

Also, you should check the total current on the bus, but as atmega resistor as so high,it should not pose a problem with raspi (but may give problem with passive i2c, that you can solve with a external pull up)

---
Tags: i2c, voltage-level
---


# Question
Title: Possible arduino burned (5V shorted to Vin), explanations and suggestions
Please apologize my english. I am working in a project using an original arduino uno, one generic servo (no factory marks) and one HC-SR04 sensor.

I make a circuit like the one here: http://s24.postimg.org/43jra5l9h/mycircuit\_bb.png (\[url=http://postimg.org/image/lgu1p0gkh/\]\[img\]http://s24.postimg.org/lgu1p0gkh/mycircuit\_bb.jpg\[/img\]\[/url\], sorry, upload of image not allowed due reputation)

As you can see from the picture I accidentally connected green into Vin instead of GND. (If the image won't load, that means that my positive is connected to arduino 5V and the ground of the circuit is connected to arduino Vin)

Now my board turn on the lights but I am unable to execute the program already in the microcontroller as aslo I cannot upload a new program to it. (It gives some error message of failed to connect).

I think I burned the microcontroller(mc) by short circuiting 5V and Vin.

That said, I have three questions:

1 - Is there any way to find out if I really burned my board using just a low budget multimeter? And if I did, which parts I need to replace? I have access to some spare ATMEL mc and I think I could replace and reprogram them by using another arduino board. However, I am affraid that I may have burned few other items and just by replacing the mc will not give me back all the funcionallities of a new board.

2 - I have basic knowledge of electronics, could someone explain to a beginner like me which impact did that mistake could/have make in all components of the circuit? (Arduino board, the servo and the sensor)

3 - Even before the accident, the circuit just work well for few minutes. I read tons of pages and tried a lot of suggestions, most of them related with power supply (capacitors to avoid flutuations, One battery just for the servo, one battery just for the sensor...) and none gave me good results. I am wondering what are the alternatives to power up this simply circuit, in particular I am looking for this possibilities: Complete external power supply (by using AC to DC adapters), Complete internal power supply (Using just batteries) and a mix of those two (Using AC to DC and batteries). I have no access to a external DC power supply generator other than batteries.

# Answer
> 1 votes
If you have another Uno then your best bet is either:

1) Swap the suspect processor into the known good board, test it.

2) to buy a replacement chip (ATMega 328-PU), use this link to flash it, if it works you win, if not you can at least use the new processor again.

I have done this myself & it worked well, it isn't easy to be sure any other way as the chip needn't fail in a predictable manner. The chances are it will take a large current if it's dead, until it burns out & goes open circuit. Once the magic smoke has come out you know it's dead... the Arduino power supply is reasonably capable of looking after itself so your chances are good.

---
Tags: arduino-uno
---


title: Multiple 7 segment displays blinking

text:
# Question
Title: Multiple 7 segment displays blinking
i just set up 2 displays ( 3 digit 7 segments ), and the displays seems to be blinkin ( i know they are suppose to blink but so fast that the human eye cannot detect it ).

I'm using the SevSeg Library and this is how my code looks:

```
void setup() {

   byte numDigits = 3;
   byte digitPins[] = {2, 3, 4};
   byte segmentPins[] = {5, 6, 7, 8, 9, 10, 11, 12};
   sevseg1.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);

   byte digitPins2[] = {14, 15, 16};
   byte segmentPins2[] = {17, 18, 19, 20, 21, 22, 23, 24};
   sevseg2.begin(COMMON_ANODE, numDigits, digitPins2, segmentPins2);

}

void loop() {

  while(true){
     sevseg1.setNumber(number,0);
     sevseg2.setNumber(number,1);
     sevseg1.refreshDisplay();
     sevseg2.refreshDisplay();
  }
}

```

I need to add 2 more 3 digits 7 segment displays so i was wondering what is it that is causing the blinking.

Im using Arduino Mega.

# Answer
> 1 votes
First of all, you have a `while(true)` in your loop, that makes no sense. The loop already loops for ever.

You are also changing the number every time the `loop()` is run, making it flicker. If you follow the Arduino library example, you can see they only use `setNumber` every so often and use `refreshDisplay` every time the code runs through the `loop()`.

Also, you didn't `setBrightness`, which shouldn't be a problem since the library probably sets a default value, but I'd advise on including it in your code to eliminate unforeseen problems.

Try this code and let me know if it works:

```
#include "SevSeg.h"

SevSeg sevseg1; //Instantiate a seven segment controller object
SevSeg sevseg2;

void setup() {
  byte numDigits = 4;
  byte digitPins1[] = {2, 3, 4, 5};
  byte segmentPins1[] = {6, 7, 8, 9, 10, 11, 12, 13};
  byte digitPins2[] = {14, 15, 16};
  byte segmentPins2[] = {17, 18, 19, 20, 21, 22, 23, 24};

  sevseg1.begin(COMMON_ANODE, numDigits, digitPins1, segmentPins1);
  sevseg1.setBrightness(90);

  sevseg2.begin(COMMON_ANODE, numDigits, digitPins2, segmentPins2);
  sevseg2.setBrightness(90);
}

void loop() {
  static unsigned long timer = millis();
  static int deciSeconds = 0;

  if (millis() >= timer) {
    deciSeconds++; // 100 milliSeconds is equal to 1 deciSecond
    timer += 100;
    if (deciSeconds == 10000) { // Reset to 0 after counting for 1000 seconds.
      deciSeconds=0;
    }
    sevseg1.setNumber(deciSeconds, 1);
    sevseg2.setNumber(deciSeconds, 1);
  }

  sevseg1.refreshDisplay(); // Must run repeatedly
  sevseg2.refreshDisplay(); // Must run repeatedly
}

```

---
Tags: arduino-mega, led, display
---


title: Problems stacking Arduino Shields

text:
# Question
Title: Problems stacking Arduino Shields
I'm trying to stack the Adafruit Data Logger Shield https://learn.adafruit.com/adafruit-data-logger-shield/overview onto a CuteDigi Sim900 GPRS Shield so that I can upload data (collected eventually by a GPS breakout) to a server at certain intervals.

The problem is that I can't seem to get the two shields to play nicely together. I'm a beginner with the Arduino and electronics in general, so hopefully this is just a noob issue.

When I power on the GPRS Shield, the data logger stops outputting the Date/Time to the serial monitor. And when I turn the GPRS Shield off, the serial monitor continues again and shows the Date/Time from the data logger.

They don't share any pins that I'm aware of, and I've tried connecting a 7.4V li-po for external power with no success.

Any help is greatly appreciated!

# Answer
Make sure you are using a software serial port for the GPRS shield.

If you aren't using the software serial port, then you are probably running into an issue with trying to read data over the only UART (serial) port while two devices are tryiing to use it.

It looks like there are two jumpers next to D0/D1 on the GPRS shield, I can't tell but I think if you remove those, the shield will use software serial over D7/D8. If you do this, you'll have to code your program to use a software serial. This wiki page on the GPRS shield if you need help with that.
> 1 votes

---
Tags: shields, hardware
---