# Question
Title: CC3000 Blocking All Wireless Communication
I'm trying to send an email using an Arduino Uno and a Sparkfun CC3000. When I plugged in the arduino to the computer with the code I wrote for it, all wireless communication in the room I was in went down. This includes both computers that were there, my cell phone, even my Pebble Watch got disconnected. Any idea on why this happened and how to fix it? I replicated this numerous times to make sure it wasn't a fluke.

Here is my code

```
PingTest.ino
CC3000 Ping Test
Shawn Hymel @ SparkFun Electronics
February 1, 2014
https://github.com/sparkfun/SFE_CC3000_Library

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

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

Hardware Connections:

 Uno Pin    CC3000 Board    Function

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

Resources:
Include SPI.h and SFE_CC3000.h

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

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

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

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

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

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

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

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

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

void setup() {

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

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

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

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

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

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

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

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

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

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

    //TembooChoreo SendEmailChoreo(client);

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

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

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

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

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

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

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

```

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

---

## Tips

1. Verify that username and password used are exactly right(punctuation, spaces, etc.). Where you put`comcast` you should put the name of the network not the name of the provider. I am not sure if you have done this or not.
2. Make sure network is in fact WPA2.
3. In order to debug the issue make sure if you are getting nothing through serial to set it to the baud rate of `115200`.
4. If you are using the breakout board make sure you correctly wired it and check any solder points:
5. Make sure you have the correct libraries installed. Also, try sample code from the examples. Libraries can be found here.

---

Many of these seem obvious but can through someone off. So try these and let me know the results. A lot of information about setup can be found here.

**EDIT** Try removing the

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

```

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

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

---
Tags: arduino-uno
---


# Question
Title: How to read data from a rotary encoder with ATmega328
I'm using a home made "bare bones" Arduino, made with the ATmega328, and I need to read angle data from a geared DC drill motor, turning at speeds between 0 and 450 RPM. This is so I can use it as feedback for an angle control system implemented on the Arduino.

I've not yet bought the encoder. I'm waiting until I find a suitable one which works easily with Arduino.

I have already written the control algorithm. I'm using state variable feedback, and the algorithm depends on a `getAngle()` function that I have not written yet. This function is inside an if statement that executes every 0.2 seconds. It needs to return the angle of the DC motor in degrees.

**My questions:**

* How can I implement this `getAngle()` function using a rotary encoder?
* What is an example of a rotary encoder that is suitable for this application?
* Will it be better to use the interrupt pins of the Atmega328, or use some other method?

I have seen a few library's on Arduino Playground that claim to make reading angle data easier, but how do I use them? I need something that is fast (it, and the control algorithm operations, both needs to finish before the 0.2 seconds sample time), and more importantly it needs to be easy to implement. I'm coming up to the project deadline so I don't want to have to spend a whole day figuring out how to implement this `getAngle()` function.

Thank you!

# Answer
You will have to use interrupts or otherwise the encoder might be rotating but your Arduino is doing something else than reading the encoder. By using interrupts, the encoder counter is always updated when the encoder moves. This also means that the interrupt function has to be very short so that it only takes a few cycles to complete and thus leaves the majority of the Arduinos computing time for your sketch.

Here is a code that I've used in many applications from CNC handwheels to servos and for reading extremely accurate angle sensors. It is dead simple, uses two interrupts to read the quadrature signal (A & B channel) and also makes use of Arduinos built in pull-up resistors to keep the channels held high for reliable readings.

Assuming that your encoder is an open-collector output and works with 5V, you only need to connect 5V and GND to it and then the A channel to the first interrupt pin #2 and channel B to #3. That's it for the hardware.

This code goes at the start of your sketch, right before setup() function:

```
const signed byte encoderDirections[] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
volatile long encCount = 0;

```

It defines a constant array that is used for finding the direction that the encoder has turned based on the previous value and the current value. It is defined as constant as it is never changed. Also a global variable calle encCount is defined as a long type variable so that the encoder can count in both directions. It is absolutelu imperative to declare it as volatile so that the compiler and the microprocessor never try to do any "shortcuts" when you use this variable, but instead always loads it from its respective memory address. This is done so because the interrupt can fire at any time and change the variables value without any other function knowing it.

Next, in your setup() function you will want to include these lines to make the Arduino pins as inputs with the internal pull-up resistors connected. The latter two lines attach the interrupts 0 & 1 (hardware pins pins 2 & 3) so that whenever the pin state changes (low to high or vice versa), it halts the microprocessors operation and jumps to the encoder\_interrupt function immediately.

```
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
attachInterrupt(0, encoder_interrupt, CHANGE);
attachInterrupt(1, encoder_interrupt, CHANGE);

```

Last you will need the actual interrupt function that reads the encoder and updates the counter value.

```
void encoder_interrupt() {
  static unsigned int oldEncoderState = 0;
  oldEncoderState <<= 2;
  oldEncoderState |= ((PIND >> 2) & 0x03);
  encCount += encoderDirections[(oldEncoderState & 0x0F)];
}

```

First this defines a variable that holds the previous encoder value that was read from the pins 2 & 3. This is declared as static, so the value is stored in memory even when this function exits so that it can be used the next time the interrupt routine is run.

The second line moves the previous interrupt channel values two bits to the left (multiply by 4) to make room for the new values.

The third line is an interesting one. It reads the PIND, meaning all the pins at D register, which holds many Arduino pin states, including the pins 2 & 3 that we are interested in. Next it shifts this value 2 bits to the right (divide by 4) to "drop" the pin 2 & 3 states to the lowest bits of this byte. Then it AND's this byte with 0x03 to zero everything else but the lowest two bits that now contain the interrupt channel states. Lastly these two bytes are OR'd with the previous encoder state values to obtain a 4 bit number.

On the forth line this 4 bit number is AND'd with a 0x0F to make sure the highest 4 bits are zero to make sure this number is truly a 4 bit number that stays between 0..15, as it is used as an index for the constant array we defined at the start of the program to get the encoders direction of rotation and this is then added to the counter variable.

And now you have an accurate and extremely fast way of reading a two channel encoder to keep track of its position.

If you want to calculate an angle from the encoders current position, you could do a function like this, but you have to know the line count of your encoder and multiply it by 4 so you know the encoder pulse count per revolution. For example, a 100 line rotary encoder gives out 400 pulses per revolution. I assume that there is a constant defined as follows at the start of program:

```
const int LINE_COUNT = 400;

```

Also, this function assumes that the encoder could have turned more than one revolution and you just want the angle from some reference spot in degrees. Do take in to account that the long type variable will overflow after +-2 147 483 648 pulses as it is a 32 bit signed variable.

```
float getAngle() {
  long curCount = encCount;  // Store the current count.
  while(curCount < 0) {
    curCount += LINE_COUNT;
  }
  while(curCount >= LINE_COUNT) {
    curCount -= LINE_COUNT;
  }
  return (curCount / LINE_COUNT * 360.0);
}

```

First the encoder count is copied to a one use variable. then two while statements make sure the values is positive from 0 to LINE\_COUNT-1, so it basically reduces the count to what it would be with just under one revolution. Then it returns the number of degrees by calculating the current position as a fraction of a one revolution count and multiplies this with 360 to get the degrees.
> 4 votes

# Answer
Your encoder choice will probably be driven by the mechanical requirements and the precision you need:

* Runs occasionally, and briefly to 450 RPM or runs continuously, and often at the higher speeds?
* Do you need position to e.g., within 3 degrees (7 bits)? Or 1/3 degrees (10 bits)? Or are you willing to count pulses from an index mark (this gets more complicated if the direction of rotation can change).

An n-bit encoder can probably be read whenever you need a position sample, so interrupts would probably not be necessary. With an index wheel (a pulse every x degrees, plus a separate pulse at 0 degrees, e.g.) you would probably benefit from tracking the position at interrupt level and letting the main loop simply access the last known position.

Your `getAngle()` implementation depends totally on the choices you make above. If you use a Gray-coded encoder wheel, you'd need to convert the code to a binary fraction and multiply by 360 to get degrees. If you use an index wheel, `getAngle()` just reads the current pulse-count maintained by your interrupt routine and converts it to degrees. But you need an interrupt routine to count angle-pulses and reset the count on the index pulse (not especially hard to do).

Fixed-point arithmetic is pretty fast. Floating point takes longer. Depending on what else, besides position-keeping, your code needs to do, and how math-heavy it is, whether you can afford floating point. The floating point library will take more code space, too, but my guess is you'll be constrained by time more than by code-space.
> 1 votes

# Answer
There is no such thing as an encoder that "works well with Arduino" - encoders are encoders, and there are several basic types. As @JRobert said, you need to make an appropriate choice, and an encoder that will *mechanically* couple well with your drill motor is probably your primary criteria, and of course an encoder that can spin unrestricted (some are only for an angular range like 180 or 270 degrees); my guess is you'll want to put the encoder on the ungeared motor, rather than the geared output of whatever it is you're driving, to get good feedback from a cheap (i.e. relatively small number of 'pulses per rev') encoder. Search on DigiKey, Mouser, online hobby stores, etc. Then just deal with whatever type of encoder it is, hack its electrical interface into the Arduino: http://www.digikey.com.au/product-search/en?pv69=848&FV=fff4001e%2Cfff80033&k=encoder&mnonly=0&newproducts=0&ColumnSort=0&page=1&stock=1&quantity=0&ptm=0&fid=0&pageSize=25

This (2-signal quadrature) encoder library for Arduino is superb, by Paul Stoffregen @ pjrc.com: https://www.pjrc.com/teensy/td\_libs\_Encoder.html For best results you'll want the 2 'quadrature encoder' outputs to go into 2 interrupt inputs on the Arduino, and there are only 2 available. There is an option to run this library on only 1 IRQ-capable input (the other can go into any input), or even no IRQ-capable pins, but performance will suffer.

Sampling at only 5/second isn't much - don't be afraid to increase that substantially - 10 to 50 / second.

You also might want a PID control algorithm, depending on what your actual aims are. the "PIDLibrary" by Breatt Beauregard on the Arduino Playground website is excellent.

Coding your 'getAngle()' function shouldn't be hard - for a rotary quadrature encoder, X pulses from the encoder corresponds to 1 revolution. The 'encoder library' you end up using may provider more than 1 pulse output per actual pulse output from the encoder. Do that math. Simple.
> 1 votes

# Answer
You are mixing two related ideas together. Keeping track of encoders is best done with at least one interrupt in my experience. Whether or not you should use 2 or can get away with none depends on the speed of the shaft. In my experience, RPMs generally encountered at the hobby level can be handled by 1. So your interrupt code is interrupted by phase A rising or falling (Pin Change Interrupt). At that point it read phase B, depending on the combination of A and B you are either going forwards (interrupt count+) or backwards (interrupt count-). You know by specifications how many pulses you will have in a 360 degree rotation, and by modulo math, (e.g. x % 360) you will know how many degrees you are currently at.

The concept of sampling rate has to do with how often you read the current interrupt values, but they themselves will always be accurate and realtime.

Keywords to google volatile. Also use signed long integers, not unsigned (don't ask how I know :| )

Not sure why the other answer suggested a PID, I didn't see anything in your question that would need it. For holding an angle you are more likely to use acceleration and deceleration, not PID.

Search google, you might find a way to build your own encoders.
> 1 votes

---
Tags: motor, interrupt, rotary-encoder
---


# Question
Title: AC ceiling fan speed control using arduino Uno R3
How can I control an AC ceiling fan speed using Arduino Uno R3? I cannot understand the key behind controlling AC voltage using Arduino (though I know how to on/off ac appliances using arduino and relays).

# Answer
> 2 votes
**Controlling the speed of an AC motor is not an easy undertaking, and messing around with mains voltages if you're not experienced and know what you're doing can be fatal.**

Now that's the disclaimer out of the way, on to your question.

Unlike DC, you cannot use PWM to control the average power of AC. That is, after all, what PWM does - the on-off ratio creates a percentage of the power - but it can only be done if the incoming power is of a steady state.

For AC there are two ways of reducing the output power - either reduce the voltage, which can be done with resistors (look inside a multi-speed fan and you'll see resistors to change the speed); or chop up the AC waveform, which is a little like PWM but more specialized.

If you only want specific speeds then you could pre-define them using resistors and switch different resistor combinations in and out using relays. It's crude, but simple, and also probably the safest option for the beginner.

If you want proper variable speed, though, then you're going to have to chop up the waveform. The theory is quite simple: Start where the waveform crosses 0V in either direction, with the output on, and turn it off again at some percentage of the way through the cycle.

Like PWM it's the on-off percentage that defines the output power (and thus the speed), but timing is critical - you must start the PWM sequence at 0V and it must last exactly one cycle.

A number of simple circuits work in the opposite way - they remain off until the input waveform reaches a certain point, then switch on, until they reach the zero-crossing point. While simple, these circuits aren't good. The reason being that the sudden rise from 0V to the "trigger" voltage when the output becomes live can cause large spikes and noise in the circuit, which can cause lights to blow etc. It's the same effect as why bulbs most often blow when you turn them on, not when they have been running for a while - it's that very rapid rise from 0V to a high voltage which causes them to be over-stressed and blow.

So any circuit you choose should really be a proper one which turns on at 0V and turns off after a period, not turn on at a voltage and turn off at 0V.

---
Tags: power
---


# Question
Title: How to protect my arduino, while hotplugging its power supply and other related electronics
The unsolved: when I connect power and signal lines to my Arduino - while power is on - I potentially kill it. I have fried 2 so far.

Situation:

* I have build an DMX-controlled lighting fixture, which consists of the fixture and a Controller Box.
* The fixture houses 2 Arduino's (5V), 2 steppers, 2 drives (36V), 2 fans (24V) and some temperature sensors.
* The controller box houses 1 Arduino, amongst other electronics.

The controller box receives DMX and does calculations an send controls via I2C to the fixture.

There is a 8 pole connector between fixture and controller box.

```
1 - GND
2 - 5v
3 - 24v
4 - 36v
5 - CLK (i2c)
6 - SDA (i2c)
7 - signal line (used as charge pump)
8 - reset

```

All wires are shielded(but the shield is only connected AFTER the initial pins make contact)

When the power on the controller box is ON and i connect the light Fixture with the 8-pole connector my arduino goes to heaven.

My own idea's so far:

1. Voltage spike, because the connection wires is grounded after it connects the pins.
2. Some strange flyback? via the Arduinos in the light fixture? I connected everything straight to the 5v pins, not using the regulator.
3. no idea

Any help on a way to search for the most likely cause of the problem would be greatly appreciated.

# Answer
If you ever drive an I/O more than a diode drop above or below its power supply rails, the internal ESD protection structure will begin to conduct. The internal structure is only there to keep the part alive during normal handling, i.e. in a factory but not for the situation described above. If the current in this structure is allowed to go high enough, it looks like an SCR and "Latches" up. When latch up occurs the device, like an SCR, will keep conducting as much current as the power supply rails are capable of until the current is removed and usually results in device destruction. The way around this is to limit the current that may flow into a pin, and prevent current from forward biasing the ESD structure: http://www.tayloredge.com/reference/Electronics/EMIESD/InputProtection.pdf
> 1 votes

# Answer
There's usually a number of scenarios that can cause hardware to go *poof* when you plug it in to a live system. Most of them you have managed to identify, so I won't go into detail here.

Suffice it to say that creating hot-pluggable devices isn't as straight forward as you would at first guess.

There are two main critical things to consider when designing your system:

* Suppression

Invest in TVS diodes to suppress ESD. All the IO pins that connect to the outside world that will be liable to be disconnected or connected at any time should be protected by adequate suppression. Any inputs should also ideally be tied to a default state with pullup or pulldown resistors so they aren't left floating.

* Connector

The connector itself is pretty critical. Hot-plug connectors typically have different pins of different lengths so that they connect in a specific pre-determined order. Normally you want your ground and shield to connect first. Then your power supplies, and finally your IO pins. Doing it in any other order is asking for trouble - such things as back-powering through the IO pins if the supply hasn't been connected.

If you can't use a proper hot-plug connector then there are ways you can simulate it internally. You can add hardware (buffers, reed relays, FETs, whatever, depending on your signals) which normally isolate the signals from the MCU, and only when the MCU is powered up and ready does it then activate the buffers to allow the signals through. Of course, the buffers themselves have to be able to withstand any possible back-powering etc while the plug is being inserted.

One other small trick is to ensure that all your IO lines have a series resistor in them. This limits the maximum current that can ever go in or out of a pin (at a specific voltage of course) to a level that is safe for the hardware. 470Ω - 1KΩ are good values.
> 0 votes

---
Tags: voltage-level, electricity
---


# Question
Title: To what extent is Javascript used in robots?
I originally discouraged my friend against the use of Javascript in his robot project because I didn't know any use for Javascript outside of web developement but then I saw this book on amazon. Since I wouldn't want to mislead him could someone help me develop a better understanding of how often Javascript is used when making robots with an Arduino?

# Answer
> 0 votes
It wouldn't be my first choice for programming of robotics, but it's certainly doable.

Thanks to NodeJS, JavaScript (or ECMAScript as it is properly known) has broken free of the browser and is now a general programming language.

Thanks to the BeagleBone Black (and others), which runs most of its systems by default through NodeJS, including its web-based IDE, you can program the whole board with ECMAScript.

So yes, you *can* do robotics with ECMAScript, and there are platforms which *do* allow you to do robotics with ECMAScript.

Would you want to do it in a real industrial environment?

As I said - it wouldn't be my first choice.

---
Tags: node.js
---


# Question
Title: How to use an PCF8574P with the simplest code possible
i'm having few PCF8574P which i want to use with my arduino and multiplex them however i have no idea how to use the I2C BUS and the IC in general. There are few libraries but they're fairly complex. Is there any library which makes writing and reading from the PCF8574P easy?

# Answer
Have you given Rob Tillaart's library from the Arduino Playground a try? The demo sketch might look a bit overwhelming, but at it's simplest, all your sketch should need to have to make a led blink like the standard arduino 'blink' sketch is

```
#include "PCF8574.h"
#include <Wire.h>

// adjust addresses if needed
PCF8574 PCF_38(0x38);  // add led to P0 (pin 4) (used as output)

void setup()
{
//your setup code here
}

void loop()
{
    //turn P0 (pin 4) of the I/O expander on and off once a second
    PCF_38.write(0, 1);
    delay(1000);
    PCF_38.write(0, 0);
    delay(1000);
}

```

I don't have any of these parts handy so I can only give generic advice.
> 2 votes

---
Tags: arduino-uno, pins, i2c
---


title: how to multi merge code

text:
# Question
Title: how to multi merge code
i do have sketch from various people out there who have build nice code to do what i need done BUT not for my application and well they grant us permission to use and or modify their code so this is what i attempt to do with your help.

# Answer
Unfortunately there is no easy way to do this. All you can hope to do if you see multiple sketches, which if combined would achieve your desired goal, is to splice the code into a single sketch (by copying and pasting), and hope that there are no conflicts resulting from the merging of the different sets of code.

For simple things like two sketches using the same pins, you may be able to fix that by changing which pins are used (unless they are special purpose pins such as PWM or hardware interrupts).

For harder to diagnose problems like two libraries not working if used the same sketch, that is almost impossible to resolve unless you know the hardware or library well enough. Best option there is to find another that does the same job, but differently.
> 2 votes

---
Tags: arduino-ide
---


# Question
Title: Could an `analogWrite` command and its variable output values be used to power multiple leds with same intensity?
I seem to be getting the right response on single LED but with multiple LEDS or a relay connected LED strip the voltage outputs seem to be insuffiecient. What kind of analogWrite values does an LED respond to?

# Answer
> 0 votes
Single LEDs like the standard 5mm leds work from low voltages such as 1.7 - 2.1v, so can be directly driven via an Arduino pin (through a resistor to prevent excess current draw which would damage the pin).

LED strips such as automotive LED strips (12v) require the use of a relay if you are simply switching the LEDs on and off. You can't run the relay directly from an Arduino pin, you will need to use a transistor to act as a buffer between the relay and the Arduino to prevent damaging the Arduino. Instead of the motor and diode in the below diagram, you connect your 12v led strip.

If you want to control intensity, you will need to use a transistor, or a mosfet (mosfets are easier). You can then use AnalogWrite to control the intensity of the LEDs via the MOSFET. You will need to connect the control pin for the MOSFET to one of the PWM-capable pins on the Arduino (the pins which have the ~ mark next to them), otherwise you will only be able to switch the MOSFET on and off, similar to the Relay. This site has a good guide on how to do this with a MOSFET. It also has a guide on how to use a transistor, but I can't include the link yet due to not enough reputation points. It shows both the code needed, and how to connect the components to the Arduino.

---
Tags: led, voltage-level, analogwrite
---


title: Arduino stk500_getsync(): not in sync

text:
# Question
Title: Arduino stk500_getsync(): not in sync
We have an arduino pro mini, we are trying to trying to upload sketch the controller but we are prohibited, as the arduino attempt to upload the sketch, it display an error of: not in sync.

We are pretty new in this are, so any help would be much appreciated.

Our setup is: -Breadboard -Connection to adapter: USB Serial. -Arduino Pro Mini as a controller

Through the Arduino Programming Client.

The processor and the port are setup op properly.

The strange thing is, it has worked sometimes these past days..

Much Thanks.

Mieer

# Answer
> 0 votes
If your error is intermittent, check all of your wiring to ensure there is nothing loose, and try hitting the 'reset' button the Arduino as the compile message changes to uploading, in case your serial adapter isn't resetting the Arduino properly.

---
Tags: serial, arduino-pro-mini, accelerometer
---


title: Troubleshooting DC motor

text:
# Question
Title: Troubleshooting DC motor
I worked on the starterkit project #9 motorized pinwheel, and the motor worked just fine.

I then tried to add a potentiometer, and now the motor won't rotate at all any more (neither in the current nor in the project's baseline configuration). I also tried connecting the motor to the 9V battery directly, to no avail.

I did check the battery by briefly connecting a LED right away. The motor apparently also still generates current if I turn it manually (checked with a directly connected LED either).

What else can I do to check what's wrong with the motor? Is it possible that I somehow accidently killed it with my attempts with the potentiometer?

# Answer
> 1 votes
If your motor doesn't work when connected to the 9V battery, either the battery is flat (which is likely since you were able to connect the LED without destroying it!! - they are a 2.5-3v part, not a 9v part) or the wiring to the motor is damaged. When you connect the motor directly to a 9v battery, it should turn pretty fast - may also work if you connect it to between 2 & 4 AA batteries.

9v batteries don't have that much energy in them... you would be better off with a battery pack with 6 AA batteries in it.

---
Tags: motor
---


# Question
Title: Mouser/DigiKey part number for female "stacking" headers?
Adafruit has this wonderful product: http://www.adafruit.com/products/85

What are these actually called? I've looked all over the place in Mouser and DigiKey and can't find them (now, granted, it's impossible to find anything in DigiKey since they discontinued their printed catalog, but I'm digressing...)

They are great for putting other things that are on breakout boards on a tightly-packed breadboard and still be able to attach probes.

Also, sometimes, the board you are trying to attach is this:

As you can see, there is a dip switch blocking the 8-pin header. This is fine for its final resting place (on a board with a socket), but putting it on a breadboard is a bit of a pain. I have quite a few of those, so even though the aforementioned adafruit part is pretty cheap and I could get a bunch, I'd rather know what the real part is called so I can get the sizes I need.

PS: In case you are wondering, and you like old-style nixie tubes, that's http://www.tayloredge.com/storefront/SmartNixie/DataSheets/Datasheet\_SmartNixie.pdf.)

# Answer
A Digikey.com search for `samtec SSQ` includes numerous longtail stackable headers (as well as some shorttail, or non-stackable). However, looking at Digikey's prices suggests to me that adafruit.com's price is a bargain unless you are purchasing thousands of pieces.

Also see an arduino.cc thread on this topic.
> 3 votes

# Answer
They're actually called "Wire-Wrap Headers" and they pre-date the Arduino probably by at least 50 years or so.

They used to be used to create circuits between chips and components by wrapping wire around the pins and routing it to other connectors:

They have since been adopted as stackable headers on boards like the Arduino shields.

Being such old technology not many people make them any more, though thanks to their popularity on things like the Arduino they are starting to appear more and more from normal electronics supply companies.
> 2 votes

# Answer
If you are already ordering from Digi-Key, they do carry the same set of stackable headers from Adafruit. It's just a bit hidden in an accessories family. Otherwise it looks like Samtec is the only company Digikey carries that makes this style of connector. Some dual-row long tail headers can be found using the term stackthrough, but this is mostly used in conjunction with PC104 connectors.
> 1 votes

# Answer
You can find stackable headers on eBay (ie. 141063314400 , 191576393028 , 271841707614). Futurlec also sell them pretty cheap - about half-way down the page.
> 1 votes

# Answer
That DIP switch is also connected to the 4 address pins so you could cut the switch off, plug it into a proto board and then set the address by selectively grounding those pins.
> 0 votes

---
Tags: prototype
---


# Question
Title: Supplying near perfect DC signals from Arduino UNO
My problem seems very simple but has been impossible to find a straight forward answer searching online. I need my Arduino to output different DC voltages from six ports (probably PWM ports), like 2 V from port 3, 2.1 V from port 5 and so on. And then be able to quickly change to like 4 V from port 3, and 4.1 V from port 5 and so on. But these DC signals need to be near perfect for the highly sensitive sensor I am working with. Everywhere I've searched says to use the PWM outputs and then an RC filter but the ripple from this process is concerning, can I get the the ripple to be under a few mV amplitude? Is there more smoothing I can do beyond a simple RC lowpass filter?

TLDR: I basically need a DC voltage generator that can select between 1 and 5 volts at 0.1 V intervals, and I need to be able to do it with output from the Arduino and some external hardware that will provide a near perfect DC signal to a sensor.

# Answer
> 0 votes
Would 0-4.095V in 1mV (or 0.5mV 0-2.047V) steps do for you? Then why not use some MCP4822 SPI SAC chips? You get 2 channels on each 8-pin chip (DIP chips are available, yes), and if you need a different voltage range you could always amplify it with a simple op-amp buffer.

So 6 ports would be 3 chips, which would entail using SCK, MOSI and three CS pins, so 5 pins in all.

# Answer
> 1 votes
(1) A multipole active lowpass filter works wonders.
Something like a 5 pole Bessel filter will probably meet your need. That needs two active stages (1 input RC pole +2 +2 ). You can use transistors in emitter follower mode with some reservations but using 2/4 of a quad opamp per filter is easier overall. I can't spare the lookup time just now (later maybe) but AD & LT and NatSemi all have good free active filter design programs.

(2) A Simple sample & hold per channel will give you steady output limited only by the drift of the opamp used. You can buy commercial S&H ICs or use std opamps. I've used even the venerable LM324 for this but there are much better - you apply the voltage via a switch to a cap\[acitor at a unity gain buffer input and then turn off the switch. Again, the "switch can be as simple as an ancient CD4016 or CD4051 but much better more modern ICs are available.

With 1 x CD4051 and 2 x LM324 (or better) you can feed 8 x S&H and update them occasionally top compensate for drift. If you add another CD4051 with identical addressing but working backwards you can read back the current capacitor voltage and "nudge" it with a simple digital on signal via a diode and high R resistor if it is slightly off. You can even do ALL signal setting this way if required with NO PWM (or you are effectively implementing adaptive PWM without formally doing so). You eg use 4 driver lines - a fast and slow drive high and a fast and slow drive low. Each is just a digital pin + a resistor and a diode. Select one output channel with the output mux (CD4051 or whatever, and the return mux connects it to your ADC. Pump it up to about right with fast-high, top it off with slow-high and correct with slow-low if needed, then step the mux to the next channel and the S&H cap looks after it. Note that the return channel to the ADC must not load the cap significantly while reading.

If this answer attracts significant interest I can add detail and suggestions re more modern components etc. If not, the above is all a keen person needs to look into the concept.

---
Tags: arduino-uno, sensors, pwm
---


# Question
Title: Reading and Writing on different clock edges with Arduino SPI interface
I'm trying to simulate a certain µController to characterize and measure a certain chip.

I need to write my data on the negative edge of the master clock and read the data coming from the slave in the positive edge of the master clock. Is there any way I can have this kind of freedom in my code? Or do I have to do it manually without using the predefined SPI interface?

Also, I would like to have my master clock running continuously without going idle… is there a way to do that too?

# Answer
To set the spi to shift out on falling edge and shifting in on rising edge of the clock you need to set the spi mode to 0 or 2 (depends on idle clock polarity).

More info here

To continuously generate clock signal as far as I remember you will need to write to the SPI dummy values.
> 1 votes

---
Tags: spi
---


title: Create a Li-Polymer Battery Charger

text:
# Question
Title: Create a Li-Polymer Battery Charger
I want to Create a battery Charger with the Arduino with real time battery status. I don't have any idea how to do that same time as the charging.

> **I know to use a serial monitor to get battery status but not to charge.**

I would like to know how to do that simultaneously so that I don't over charge the battery.

* This is the battery for Lumia 822
* Nokia BP-4W 1800mAh 3.7v 6.7Wh

# Answer
**(1) A simple method**

BEST method is to use a proper charger - they are not high cost if you look around and doing it properly extends precious battery life.

Next best in this context is my "better" method in 2. below.

BUT, given the system you say you are using now, the following very simple method will greatly improve your result and ave your battery from an early death.

You need a 1 Ohm resistor and a voltmeter that you can trust to read a 4.1V votage accurately. Without these the simple method risks battery damage or destruction - just as your present method does.

Warning: Straight connection to a USB port is very unwise but may be viable if the port current-limits.

* If the current is ever higher than the rated maximum then battery destruction may occur.
* If the battery voltage ever exceeds 4.2V at room temperature battery damage WILL occur and battery destruction may occur.

Worst case a badly treated battery can turn into a flaming inferno in seconds.

A usably OK result can be gained by:

(1) Calculate Imax = same mA as battery mAh capacity.
LOWER is OK. Higher is not.
eg 1200 mAh battery = 1200 mA max and say 1000 or 500 or lower mA is OK.

(2) Connect a ONE OHM resistor in USB to battery line.

(3) Connect **discharged** LiPo battery to USB port via 1 Ohm.

(4) Measure voltage across the resistor. The voltage will be 0.001 Volt for every mA that flows. eg
1000 mA gives 1.000 Volt 789 mA gives 0.789 V. 1234 mA gives 1.234 V. etc.

If the measured mA is LESS THAN Imax in (1) above then this is OK to charge with.

(5) Use Arduino analogRead() function WHILE CHARGING to measure battery voltage.
BE SURE that the voltage that you read with the Arduino matches what a quality meter says.
When Vbattery (measured from Bat + to Bat- AT the battery) measures 4.1 V STOP CHARGING, remove voltage.
Battery will be perhaps 70% charged and will have a long cycle life (if not already damaged).

For 10 bit ADC = 1024 counts total (0-1023) then
for 5V reference 4.1V count = 4.1/5 x 1023
= 838 counts.
Using 830 counts to start with is safer.

When battery is at the upper charge limit, and **before** removing Vcharge, measure voltage at battery with calibrated quality meter. Result should be 4.1V using above system.

Even with a quality calibrated meter NEVER exceed 4.2V - and 4.1V is better.

The BEST method is to use a proper charger - they are not high cost if you look around and they extend precious battery life.

.\_______________________________

**(2) A better method:**

LiIon (Lithium Ion)and LiPo (Lithium Polymer) batteries are functionally the same for charging purposes. I'll use the term "LiPO" from here on. I'll assume single cell batteries as most in cellphones and similar are. If the terminal voltage is between about 2.5V (should really be higher) and 4.3V they are single cell,

LiPo batteries have 4 main charge areas.

* Under about 2V = dangerously dead. Discard
* 2V to about 3V = under voltage - charge very slowly
* 3V to 4.2V = charge at CC = Constant Current.
* On reaching 4.2V charge at CV = Constant Voltage until current reduces "automatically" (under battery chemistry control) to about 1/4 x max rate.

Max charge rate is set by the manufacturer but is almost always the numerical mAh rating in mA. eg for a 1000 mAh battery max rate is 1000 mA. For a 3300 mAh battery it's 3300 mA etc. In a very few cases it is lower - maybe =half standard values and for a very small number of cells its higher - assume you do not have those.

Max voltage **MUST NOT** exceed 4.2V at room temperature. Lower, say 4.1V, does no harm and increases battery cycle life while slightly reducing capacity per charge.

The battery mAh rating is known as "C".
If C = 1200 then a cahrage rate of 1200 mA = C/1,
a charge rate of 300 mA = C/4,
a charge rate of 12 mA = C/100 etc

An easy charging method that gives long cycle life and about 70% to 80% of max possible capacity and a fast charge is

* Determine max charge rate = C = Imax = same mA as battery has mAh capacity.
* If Vbattery is \< 3V, charge at C/20 or less until Vbattery reaches 3V.
If Vbattery never reaches 3V it is dead.
* When V\_battery = \>= 3V, charge at C/1 until Vbattery = 4.2V ( or 4.1V)
* Finished!.
* Remove applied voltage. DO NOT EVER leave 4.2V applied to a charged battery.

A more usual method that is only slightly harder is.

* Monitor charge current.
* Charge as above until Vbat = 4.2V.
* While holding Vbat at 4.2V monitor charge current. This will fall as the battery absorbs additional charge.
* When Icharge falls to C/2 or C/4, stop charge. C/4 adds slightly more charge than C/2 but shortens cycle life.
* Again - DO NOT leave 4.2V applied to battery once charged. Doing so will destroy the battery rapidly. Remove all voltage once charged.

.\______________________________

**Battery University:**

Charging Lithium Ion & LiPo

Increasing lifetime

Index

.\______________________

### Q&A

> Q: This is a 3.7v battery by giving 4.2v will it destroy it or are you referring 4.2v to explain the concept.

Read the above material and the battery university pages.

4.1 V ABSOLUTE MAXIMUM is what I recommended.

* Most LiPo single cell batteries are labelled as 3.6 V or 3.7 V as that is approximately the **average voltage** across the discharge cycle.
* When **fully charged** they are at **about 4.2 V (or 4.1 V if you take my advice -** which you should :-).
* As they discharge the voltage falls and by the time they get to just above 3 V they are essentially fully discharged. They should never be discharged below 3 V as it damages them and there is only a tiny amount of energy left.

So 4.1 V ABSOLUTE MAXIMUM is good
MEASURED WHILE CHARGING and
AT the battery terminals or very close to them.
ie no long leads or resistors or connectors.

If using an Arduino to measure battery voltage, connect an Arduino ground lead to battery negative with as short a wire as practical and the ADC +ve input to the battery +ve at the battery connection point.

So once more: A LiPo battery labelled as 3.6V or 3.7V can and should be charged to 4.1V maximum and never discharged to below 3V.
> 4 votes

---
Tags: arduino-uno, voltage-level, battery, electronics
---


title: giving delay function to output

text:
# Question
Title: giving delay function to output
I want my arduino to give the output at a specified delay .The delay is calculated from a polynomial equation.

```
unsigned long t=40*Vin*Vin-760*Vin+4320;
delay(t);
digitalWrite(ledPin,HIGH);

```

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

# Answer
> 1 votes
I suggest you look into using a hardware timer rather than using delay(), I suspect it will give you more accurate timing.

Timer configuration is not as straight forwards as using delay - they don't work in milliseconds or microseconds, but instead in multiples of clock cycles, which (I find) makes configuring them a little difficult to understand, but it is possible to set the interval of a timer within its own interrupt routine.

Another advantage to using timers is that your code can do other things whilst waiting between interrupts.

Have a read here for more information and simple examples: http://playground.arduino.cc/code/timer1 or just Google "Arduino timers" for other examples and explanations.

# Answer
> 0 votes
Perhaps you had in mind something like this fragment, which will raise `ledPin` for the time you calculated (in msec) then lower it again?

```
// ...
unsigned long t=40*Vin*Vin-760*Vin+4320;
digitalWrite(ledPin,HIGH);
delay(t);
digitalWrite(ledPin,LOW);
// ...

```

---
Tags: programming
---


# Question
Title: Passing arguments to LCD.print through another function
I'd like to write a function like this:

```
void lcdPositionPrint(int row, int col,  content) {
    lcdPosition(row, col);
    LCD.print(content);
}

```

but I'm not certain how to declare "content", because it might be a string, or an int, or who knows what, just as it is for the "Serial.print" function or the LCD.print() function. Is there an easy way to do this?

# Answer
> 1 votes
There isn't really a great way to do it, but there are a few ways to get it to work. Most of the problem here is that there is actually a different `LCD.print` function for every data type. You aren't really calling the same function, your calling different functions that share the same name.

**You could use templates.** They are a powerful system built into C plus plus for generating functions and avr-gcc supports them well. With them, you can make the compiler generate all the necessary versions of your function for you. Your function would then look like this:

```
template<typename T>
void lcdPositionPrint(int x, int y, T content) throw() {
  lcdPosition(row, col);
  LCD.print(content);
}

```

That part about `throw()` isn't doing anything except keeping the ".ino" preprocessor from messing the template function up. You can call the templated function like normal, or with an explicit type

```
lcdPositionPrint(0,0,"hello");
lcdPositionPrint<float>(0,0,32.0f);

```

**You could also use the preprocessor.** Your function is very simple, so you could just as easily make it a preprocessor macro that just places you code you want in the file whenever your "function call" appears. It looks like this:

```
#define lcdPositionPrint2(row,col,content) \
    do { lcdPosition(row, col); LCD.print(content); } while (0)

```

The `\` there tells the preprocessor that the next line is also part of the macro, and you will need one on every line but the last of your function. Wrapping it in a `do` loop that immediately ends makes it nicely substitute into more situations. Micros don't scale up well, but they are a bit simpler for quick debugging situations. The code is duplicated in each call location instead of being bundled into functions though.

# Answer
> 1 votes
One way to do this is to use generics. And we also need to use an unnamed namespace to get around the IDE's "helpfulness":

```
namespace {
    template<typename T>
    void lcdPositionPrint(int row, int col, T content) {
        lcdPosition(row, col);
        LCD.print(content);
    }
}

```

This will cause the compiler to create one function for each type passed in `content` that the function is actually called with.

---
Tags: programming, avr-gcc
---


title: How to implement a 2D lookup table?

text:
# Question
Title: How to implement a 2D lookup table?
This is my first post to this forum. I am fairly experienced in electronics, but am in the process of learning C, Arduino coding, and how to use microcontrollers in general for various applications.

I have a toy-like 5 degree of freedom (DOF) robot arm that is currently controlled using the OEM hand-held switch box. It is a basic electromechanical robot arm to illustrate the fundamentals and it uses DC motors to drive the joint motions. The direction of motion is controlled by changing the polarity of the applied voltage. The manufacturer did offer an "interface board" and SW to be able to hook up the arm and control it using a computer program. However, this approach was fairly dated and their SW was not compatible with windows 8.1. I wanted to experiment and use an Arduino Uno Rev 3 and 5V DC relay PCBs to develop my own interface system.

Basically, the HW aspect was straightforward and is working fine. The Arduino SW also is working fine. I am playing around with 2 variations of the program: 1) One program that simultaneously moves up to 3 joints and 2) A sequential joint movement program where each joint only moves after the other has finished moving. One **note** about the simultaneous program is that I am using the "internal" batteries in the robot's base (only 3V each direction) and thus can not realistically move more than 3 joints at the same time without putting too much load on the source voltage.

**Ok, now to my question!** As it stands now, the program works well, but is not intuitive. Each joint has 2 relays associated with it: one for each direction of travel. There are 5 joints total in the robot arm. I am able to use the program easily since I know directly (from setting up the HW and then the SW) which relays correspond to which Arduino pins and of course which relays correspond to each joint. I'd like to make the program more intuitive where instead of "2,2,0,0,3,4" input string for example, the user would do something like "B,CCW,S,CW" where B is for B = base, CCW = is counter clockwise etc.

Please note that in the numerical only input string "2,2,3,4" for example, the 2nd value corresponds to the duration in seconds that the relay will be ON (and thus the joint moving). The robot arm is not very sophisticated in that it doesn't have encoders for position feedback. The simplest way (and the method which the OEM interface board uses) to interface this arm and make a program where the arm will move in a "hands-off fashion" was to use relays and program delays (to create time durations of joint movement". The numerical only input works really well currently and it was very easy to use examples to figure out how to parse a comma separated string.

I understand (I think) from looking at the examples how to parse a comma separated text string and pull from it the input values.

BUT, I am uncertain how to use those input values and then associate them in the SW with the correct relays (Arduino Pins)!

I have already tried seeking help with this but am unable to understand this thread: http://forum.arduino.cc/index.php/topic,94701.0.html

Basically, I need a 2D table where the joint and direction are input and then the SW associates one particular relay with those inputs. Please see the table below for a graphical example of what I tried to say above.

One possible solution that I **dread** and saw mentioned was to use a ton of **if else-if statements....** I dread this since I want to be able to input any joint in any order and thus it seems like when the code parses the input string for the ith relay, it would have to check ALL of the conditions to see which joint it is, which direction etc. For example, I think I could minimize the # of if statements needed if I only entered in the input commands in a certain order: base first, shoulder next, etc. Doing so however, limits the intuitiveness of the program.

Thank you all for reading this! I hope this isn't too challenging!

# Answer
I suggest you turn this into a simple 1D table by using two different separators, for example ‘:’ between joint and direction, and ‘,’ between consecutive movements. Then, instead of “B,CCW,S,CW” you would type “B:CCW,S:CW”. For parsing the string, you split at the commas, and consider the pieces between the commas as single items. In other words, “B:CCW” would be the name for relay 2, and you do not try to split it further.

Here is a simple method to map the strings to the relays:

```
const char * const relay_names[] = {"", "B:CW", "B:CCW", "S:UP",
    "S:DN", "W:CW", "W:CCW", "E:UP", "E:DN", "G:OP", "G:CL"};

// Return the relay number.
int get_relay(const char * name)
{
    for (int i = 1; i <= 10; i++)
        if (strcmp(name, relay_names[i]) == 0)
            return i;
    return -1;  // meaning invalid
}

```
> 2 votes

# Answer
Another thing you can consider is to define a *struct*. This is a compound variable that contains other variables of different types.

You could define a *struct* to describe the joints of an arm:

```
struct arm {
    int base;
    int shoulder;
    int elbow;
    int wrist;
    int grip;
};

```

Which you can then assign as variables:

```
const struct arm left_forward = { 1, 3, 7, 5, 9};
const struct arm left_reverse = { 2, 4, 8, 6, 10};

```

You can then get at different pins by using such things as:

```
digitalWrite(left_forward.shoulder, HIGH);

```

Another trick is to make your struct contain a *union* and an *anonymous struct* so you have multiple ways of accessing the pins:

```
struct arm {
    union {
        struct {
            int base;
            int shoulder;
            int elbow;
            int wrist;
            int grip;
        };
        int pins[5];
    };
};

```

You can now get at `left_forward.shoulder` and `left_shoulder.pins[1]` and they point to the same thing.

You can create an array of these structures now:

```
const struct arm left[2] = {
    { 1, 3, 7, 5, 9},
    { 2, 4, 8, 6, 10}
};

```

So now you have `left[0].shoulder` and `left[0].pins[1]` both for the left shoulder moving forwards.

Another option, which might be far more logical, is to turn the whole thing inside out. Define a "pin pair" structure that defines the two pins for a joint:

```
struct pinpair {
    int forward;
    int reverse;
};

```

Then an arm consists of 5 "pin pairs":

```
const struct pinpair leftarm[5] = {
    {1, 2},
    {3, 4},
    {7, 8},
    {5, 6},
    {9, 10}
};

```

So to move the left shoulder forward it would be `leftarm[1].forward` and to move the wrist backward would be `leftarm[4].reverse`.

Of course, you could combine the two and have a struct of named structs for each joint if you wanted (`leftarm.shoulder.reverse`. I'll leave you to work out the syntax for that from the examples above).

Now for your "control string". How to deal with that. Well, I would "pre-parse" it into an array of numbers. Compile it into "byte code" if you will.

Start with an empty array that would be big enough to store the data you want, then work your way through the string.

Tokenize it (hint: strtok() is good for this) and check each piece of the string against others. Unfortunately it's not something you can easily automate, and you'd either have to loop through an array of strings to compare each one to, or use a series of "if" statements.

For each item that you match you then assign a "command code" to - a number you can then easily associate with a specific action or joint. For instance, "B" may equate to command 0, "S" to 1, ""E" to 2, etc - which just happen to coincide with the array slices for the joints.

The directions could then be other codes (keep them outside the range of your array so you can identify them), maybe 16 and 17 (hint: think about the hexadecimal representation of those and how you could use that to your benefit). It can also be useful to mark the end of the array with a special token to say "this is the end" - say 255 (0xff).

Then once you have parsed the string and got your list of numbers, which may be something like `{ 0, 16, 1, 17, 255 }`, you can then "execute" it. Just step through each entry, if it's \< 16 then it's a command, if it's \>= 16 then it's a direction, and if it's == 255 then it's the end of the command list. It's then up to you to drive the right pins for the right periods to execute those commands.
> 3 votes

# Answer
In C/C++, multi-dimensional arrays are represented as arrays of arrays of arrays ..., for the number of dimensions needed (the last subscript varying most rapidly as you step through the stored elements in RAM).

The array you described is a sparse array; not all cells hold valid data. To simplify (and that's a relative term!) the storage and the code, I would arbitrarily assign each joint a forward and a reverse direction, reducing your 10-row sparse array to a dense array of only 2 rows. You can then, if you wish associate joint-relative motionss (up/down, open/close, etc.) with forward/reverse. Then you can find the pin # for a given joint relay by the joint name and direction as `RelayPin[<direction-name>][<joint-name>]`. A downside is that writing `RelayPin[DIR_OPEN][JNT_ELBO]` looks like nonsense but actually executes, though maybe not in the direction you think you meant.

This code snippet defines a 2D array of joint-relay pin numbers, with an example of enabling one of the relays:

```
// Number of joints and directions
#define NDIRECTIONS 2
#define NJOINTS 5

// Basic joint-motion directions
#define _DIR_FWD 0
#define _DIR_REV 1

// Aliases for joint-motion directions
#define DIR_CW _DIR_FWD
#define DIR_CCW _DIR_REV

#define DIR_UP _DIR_FWD
#define DIR_DN _DIR_REV

#define DIR_OPEN _DIR_FWD
#define DIR_CLOSE _DIR_REV

// Joint table indices
#define JNT_BASE 0
#define JNT_SHOU 1
#define JNT_ELBO 2
#define JNT_WRIS 3
#define JNT_GRIP 4

// Joint table - each element is a digital pin number
uint8_t const RelayPin[DIRECTIONS][JOINTS] = {
//  B  S  E  W  Ga
   {1, 3, 7, 5, 9}, // forward
   {2, 4, 8, 6, 10},    // reverse
};

// Example of enabling motion to raise the shoulder:
digitalWrite(RelayPin[DIR_UP][JNT_SHOU], HIGH)  // raise shoulder

```
> 0 votes

# Answer
The other answers have presented some good techniques that are flexible enough to be adapted to other, similar problems. By contrast, the following method is specialized to work with the particular chart of joint-letters and relay-numbers mentioned in the question. (It can be modified for other relay-number sequences, as noted in program's comments.)

Rather than requiring entry of verbose text like CCW, or obscure abbreviations like DN, OP, and CL, it accepts a + or a - to set motor direction, with “+” corresponding to choices CW, UP, and OP, and “-” corresponding to other choices. For example, the question's sequence “B,CCW,S,CW” could be written as any of “B-S+”, “b-s+”, “B- S+”, “B-,S+”, etc (ie, case is ignored, and spaces and commas are ignored before a joint-letter).

Note, the code as shown assumes each command-list line starts with a number that gives desired delay time in tenths of a second. For example, “23 e-s+” would run E down and S up for 2.3 seconds. The command-list “47” would sit idle (no motors on) for 4.7 seconds.

```
#include <ctype.h>
void operateRelays(char *cmdList) {
  char *joints = "BSEWG", *c=cmdList, *j;
  byte relay, delaytenths= 0;

  while (*c && isdigit(*c)) // Get # of tenths-of-seconds to delay
    delaytenths = 10*delaytenths + *c-'0';

  for (; *c; ++c) {
    while (*c && !isalpha(*c)) ++c; // Ignore non-alphas before joint
    if (!*c) break;     // At end of command list, break
    for (j=joints; *j; ++j)
      if (toupper(*c) == *j) break;
    if (!*j) break;     // Ab-exit if joint-letter not found
    if (!*(++c)) break;     // Advance to + or -
    relay = 2*(j-joints) + 1 + (*c != '+'); // The last term is 0 or 1
    digitalWrite(relay, HIGH);
    // If relay numbers aren't contiguous as in question, just use
    // an array (like: byte relays[] = {2,1,5,4,6,3,7,9,10,8};)
    // and in above statement say digitalWrite(relays[relay-1], HIGH);.
  }
  delay (100*delaytenths); // Wait specified time
  for (relay=1; relay<11; ++relay) // Turn motors off
    digitalWrite(relay, LOW);
}

```
> 0 votes

---
Tags: relay
---


# Question
Title: Controlling a 240v AC high current relay
Should I use 2 relays, one for the hot wire and one for the neutral ? I'm talking about 16A.

# Answer
Use 1 relay, more precisely a DPST (Double pole, single throw) type. You'll only need 1 signal to drive both, and be sure that both lines are switched off. Electrical installation regulations require double throw relays/switches for certain applications, e.g. in wet rooms like bathrooms.

Note that relays are more delicate devices than they appear to be. A 16A relay may not always be suitable for switching 16A. They have to be **derated** according to their type of load. And that is almost everything. Not only for capacitive or inductive loads you'll have to limit the current to a fraction of the rated 16A, but even for incandescent lighting (due to the high current peak when switching on). See the manufacturer's datasheet or application documents for the amount of derating.
> 1 votes

# Answer
As mentioned in the comments, if switching both, and the neutral relay fails open, unpredictable things may happen.

If you really want to switch both then use a two pole relay which switches both the live and the neutral together.

For instance, I use these relays:

> http://uk.farnell.com/finder/22-22-9-012-4000/relay-modular-dpst-no-12vdc-20a/dp/1169296

20A, 250VAC contact rating, double pole.
> 0 votes

---
Tags: current, relay
---


title: SoftwareSerial problems

text:
# Question
Title: SoftwareSerial problems
Hi we are using an Arduino Micro and working with a Bluetooth device and a Rfid Scanner from Sparkfun(ID-20 LA). For that we implemented 2 SoftwareSerial objects and the Serial port for the Serial Monitor. If we use one SoftwareSerial object and the normal Serial everything works fine. For example we can send and receive things over Bluetooth. But when adding another SoftwareSerial object( Rfid then ) One of them doesn't work.

Starting with the Rfid SoftwareSerial ends up to the same result.

We've also already tried to change the ports and so one.

Every help is appreciated. Thanks in advance.

The Code ( this is already the third programm nothing has changed )

```
#include <SoftwareSerial.h>

SoftwareSerial rf(11, 12);
SoftwareSerial bt(8,9);

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

}

void loop() {
  if(Serial.available())
  {
   while(Serial.available())
     Serial.write(Serial.read());

   Serial.println("");
  }

  if(rf.available())
  {
   while(rf.available())
     Serial.write(rf.read());

   Serial.println("");
  }

  if(bt.available())
  {
   while(bt.available())
     Serial.write(bt.read());

   Serial.println("");
  }
}

```

# Answer
Taken from http://www.arduino.cc/en/Reference/SoftwareSerial:

Limitations

The library has the following known limitations:

```
If using multiple software serial ports, only one can receive data at a time.

```

If your project requires simultaneous data flows, see Paul Stoffregen's AltSoftSerial library. AltSoftSerial overcomes a number of other issues with the core SoftwareSerial, but has it's own limitations. Refer to the AltSoftSerial site for more information.

If you look at SoftwareSerial's code, you'll understand the limitation:

```
/* static */
inline void SoftwareSerial::handle_interrupt()
{
  if (active_object)
  {
    active_object->recv();
  }
}

```

Basically, the code waits for an interrupt to detect state changes on the pin, and directs it to the "active" serial object.

Hope this helps.
> 3 votes

# Answer
Under the known limitations in the `SoftwareSerial` documentation:

> If using multiple software serial ports, only one can receive data at a time.

It's still possible to use multiple instances of `SoftwareSerial`. However, when you want to use a specific one, you need to call the `listen()` member function. This will allow it to receive data until you call that function on a different instance.

One very important thing to understand is that data is not queued in the background. If information arrives while a SoftwareSerial port is not listening, it simply gets discarded.

There may be alternative software serial libraries which suit your needs, depending on how they use interrupts. Alternatively, you could use a different Arduino which has multiple hardware serial ports (such as the Mega).
> 0 votes

---
Tags: serial, bluetooth, communication, softwareserial, arduino-micro
---


title: Arduino to mysql database?

text:
# Question
Title: Arduino to mysql database?
I found a lot of methods on the internet and I was wondering what would be the best method to send data from sensors connected to Arduino to a MySQL database in a WAMP server continuously.

# Answer
There is no absolute "best" way, there is only the way that "works best for your situation".

In a nutshell, the different methods that I can think of, and their pros and cons, are:

* Simple HTTP GET with parameters

Quick to implement, light weight, but not very secure or robust. Perfectly fine for things like "send the temperature once a minute" etc, but crafting very long GET requests with lots of parameters can severely impact on both your RAM and your sanity.

* HTTP POST request

Like the GET request it's fairly simple to implement, but needs more RAM since you need to know the size of the data you're sending first so you can send a `Content-length` header. You can send much more that way though, assuming you have the resources for it.

* SOAP

This is basically HTTP POST but with a specially XML formatted body. It has the advantage that it's a standard protocol for transferring data and commands around the place, so there are plenty of resources to help you. The main problem is crafting the XML at the Arduino side.

* Custom TCP

Connect to a special port to communicate with your own software. You define all of the protocol, but you have to write all (or most) of the software too. This can be more like a serial connection to your computer but through the network. Good for sending larger amounts of data, such as images from a camera, etc.

* Custom UDP

If you want to send lots of small values very frequently this is probably the best bet. Harder to implement than most of the others, but the light-weight nature of UDP means you can send data much more rapidly. Of course, with UDP, you run the risk of losing packets since it's very much a "fire and forget" protocol - you send a packet and hope it gets there. Fine if you don't mind missing the odd bit of data, say for higher speed temperature logging. Of course, you have to write the server side software yourself, but there's plenty of resources to help you with that online.

So it's really not a case of "best" but "most suitable". Define what the data is and how often you want to send it, then think about how complex you are willing to get with your programming.

Nine times out of ten a simple HTTP GET request fits the bill.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: How can I indicate that I am using ATmega2560 so that Arduino libraries understand it?
I am developing AVR microcontollers in Atmle Studio and sometimes I am using Arduino libraries(such as LiquidCrystal).

When I initialize `LiquidCrystal lcd(12, 11, 5, 4, 3, 2);` I don't think Arduino Libraries use registers and ports of ATmega2560, although I am building my code with the device selection ATmega2560 option of Atmel Studio. Atmel Studio works in order to program 2560 but how can I tell Arduino libraries that I am using 2560?

# Answer
> 2 votes
There are two things that have to be considered here.

One is telling the code what board you are using, so it can compile in the right optional parts, and the other is getting the right pin mappings.

The first can be covered simply with a compilation flag:

```
-DARDUINO_MEGA2560

```

That defines the macro `ARDUINO_MEGA2560` which is used in some places to know which board you are using.

Second is the pin mappings. These are stored in the file `pins_arduino.h` and each board variant has its own copy. You need to ensure that this file (and be sure to get the right one) is included in your code in the right places to ensure that the pins can be mapped right. If you are including the whole Arduino core (which it sounds like you must be in order for things to even have a hope of working) then you just need to ensure that you have the compiler set up to include the right copy of the `pins_arduino.h` file.

That means making sure you have an include path in your compile command line which points to where the `pins_arduino.h` file is before anything else Arduino core related.

```
-IC:\Path\to\arduino\mega2560\variant

```

or

```
-I/path/to/arduino/mega2560/variant

```

---
Tags: arduino-mega, avr, atmel-studio
---


# Question
Title: Reading and interpreting Serial information
I am trying to use a Raspberry Pi to control a ESC and for that I am sending the instructions for the ESC using serial. My problem is that when i send the instructions i can not interoperate them, and by interoperate I mean check what the first letter is and then remove it and make the Arduino output a PWM signal. My problem is when I use the serial monitor to send an instruction it firstly comes up on several lines, and when I try and look at the first letter of the string the if statement thinks it is true for all inputs of "FirstLetter" my function to get the serial input it

```
String readSerial()
{
  char SerialInput;
  String Data = "";
  if (Serial.available())
  {
    SerialInput = Serial.read();
    Data.concat(SerialInput);
    //Serial.println(Data);
  }
  return Data;
}

```

the function that should interoperate the information from readSerial() is

```
void DecodeInput()
{
  String input = readSerial();
  if (input != "")
  {
    char FirstLetter = input.charAt(1);
    if (FirstLetter = 'U')
    {
      Serial.println("Hello World");
      //input.setCharAt[0, '');
      //SetPower('U', Power);
    }

```

# Answer
> 1 votes
Two things immediately jump out at me:

```
char FirstLetter = input.charAt(1);

```

charAt(1) is the *second* letter, not the first - the first is charAt(0).

```
if (FirstLetter = 'U')

```

That is saying "If I have been successful in assigning the value 'U' to FirstLetter then..." - "=" is assignment, you need "==" for comparison.

Also your `readSerial()` function is complete junk. It's not doing anything at all like you think it is. You should read this to better understand Arduino serial reading: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

# Answer
> 0 votes
You may want to look at the Firmata protocol, and not re-invent the wheel. Although doing so (re-inventing the wheel) is a good learning exercise, so is understanding something already written.

http://www.arduino.cc/en/Reference/Firmata

Then move on to the cool stuff that uses it.

---
Tags: arduino-uno, serial
---


title: Arduino OR operator

text:
# Question
Title: Arduino OR operator
I have been trying OR conditional operator in a if condition statement in my arduino program and the result is not what I expected.

My program:

```
// three variables assigned to const int datatype as the
// pin numbers they are assigned to are  going to remain
// constant through out the program.
const int led1=10;
const int led2=11;
const int led3=12;

void setup(){
  // assigning the pins as input/output.
  pinMode(10,INPUT);
  pinMode(11,INPUT);
  pinMode(12,OUTPUT);
}

void loop(){
  control();
}

void control()
{
  int task1 = digitalRead(led1);
  int task2 = digitalRead(led2);
  if (task1==HIGH || task2==HIGH)
  {
    digitalWrite(led3,HIGH);
  }
  else
  {
    digitalWrite(led3,LOW);
  }
}

```

if the 'IF' conditional statement used without 'OR' operator is working fine that is not including both the tasks instead only one task either task1 or task2, else it is working without errors but the result is not as expected. hardware part is all fine. i reckon that there is a problem with the OR || operator.

# Answer
> 0 votes
Your code is correct for what you described you want it to do - raise `led3` when either or both of `led1` or `led2` is high, and make it low otherwise. Some things to check:

* Do the push-buttons pull their respective pins HIGH? (Pulling LOW is more common).
* Are the pins pulled to ground with a 5K or 10K resistor, and not left floating, when the respective button is not active?
* Real buttons need to be de-bounced. They behave as if their contacts bounce several times before making contact (even though that isn't really what happens). If this is an experiment and you hold the button down, even briefly, you should get proper results without de-bouncing, but it's something to be aware of as you move on.

# Answer
> 0 votes
If you aren't getting the expected result, as JRobert suggested you should look at your hardware. Ensure pull-ups/downs are being used correctly, your interpretation of your hardware's logic is correct (positive/negative logic), and maybe even use a simple sketch to check that everything is working correctly. Firstly I would simplify the control function. You could try replacing the OR with a bitwise OR, or changing your variables to booleans. Realistically, more code and a diagram illustrating your implementation would help us reproduce and troubleshoot this with you. I'm a little confused as to whether pins 10 & 11 are LEDs or Buttons. I would be happy to help you get a test program together if you can provide more detail. :)

```
void control()
{
    boolean task1 = digitalRead(led1);
    boolean task2 = digitalRead(led2);

    // Note that the if isn't needed
    digitalWrite(led3, (task1 || task2));

    // If your buttons use negative logic
    // digitalWrite(led3, (!task1 || !task2));
}

```

For humour-sake when I hit a problem that doesn't make sense, I rework my logic to break down the problem and output in stages, or use the Serial library to output what is going on periodically.

Typically for inputs and outputs I define a structure which buffers everything per IO, and write my code with a loop-based mentality, much like how a game loop is implemented in video games. It is easy to print and trace when troubleshooting, and the positive/negative/default-state logic is abstracted. This will help you get started if you are curious.

---
Tags: programming
---


title: Creating a clock using Arduino

text:
# Question
Title: Creating a clock using Arduino
I want to make a large clock, 16 inch x 7.5 inch, which will display dd Month yyyy. What would be the best way to do this? Does Arduino have a built in clock, and I'd just need logic to turn on/off LEDs on a display that already has dd Month yyyy? Do such displays exist which I can connect to Arduino?

# Answer
> 1 votes
Presuming you intend to have a more or less standard clock the hardest part of project will be accurate timekeeping. This functionality is generally reffered to as RTC i.e. Real Time Clock.

This is probably best offloaded to a dedicated IC, this provides many benefits. The foremost is that small inexpensive modules can be bought that include, a reasonably accurate crystal, the timekeeping IC and a backup battery, so your clock doesn't forget the time when unplugged.

A good place to get started would be here it goes over using one such chip to get the time (and date).

From there you can apply your own creativity for the clock interface.

One possible option is making a wordclock interface but setup for dates.

# Answer
> 1 votes
Usually displays with pre-determined shapes for numbers and/or letters are LCD or quite specific parts. It's entirely doable to just use standard Alpha-Numeric LED displays, there's many tutorials and explanations to be found, if that's something you think you need, you can ask more directly towards that and many of us will probably be happy to explain.

The Arduino has its own little clock frequency. Most are probably powered by some manner of crystal making them quite accurate. Some may have an actual watch crystal running some kind of real-time timer/clock. These matters are device dependent and cannot be answered by me, as I never used an Arduino. In the basis every Atmel (the controller brand Arduinos use) can be used to maintain a clock and calendar, even the Tiny10 can, given a stable enough external clock source.

On most simpler Atmels (and as such simpler Arduinos) you will have to maintain the numbers and how they translate to the displays yourself, that last part especially if you want your own design in the display. But you'll probably be able to get a reasonably accurate pulse that you can use to update the values with the right interval. On the larger/more complex chips and/or Arduinos you might get a (near) complete calendar unit that can basically maintain itself and allow you to just read the values. But then those will be more expensive and able to do many, many much cooler things, so that might be a bit of a waste for just a clock and doing the calendar stuff yourself is very good exercise for getting to know the processors you are working with.

For more assistance you will need to be much more specific about what Arduino/Atmel you are using and exactly what manner of display you want: Are blocky number/letter like those in radio's and alarm clocks okay, or do you want something self-designed or more flowy? Are you willing to actually use a dot-type display and learn to use that (no that hard, to be honest, but very different from segment), allowing you to display anything that fits the dots? Like smiley-like graphics, Chinese characters to some extend, etc.

# Answer
> 1 votes
If you are willing to go the “barebones” route, you can turn an ATmega328P (the MCU at the heart of the Arduino Uno) into a very accurate RTC by hooking a watch crystal to it's clock pins. Given proper calibration, you can get an accuracy of **a few seconds per year**.

This would require some coding though, and is not as straightforward as using an off-the-shelf RTC. C.f. this answer for the details.

# Answer
> 0 votes
It is possible to use the RTC. Another option is to use the Arduino Yun. This has a OpenWRT (Linux) running alongside the Atmel and is a little bit more expensive than the cosyt of the RTC and an Arduino. However, you can query the Linux side for the time with the Arduino command:

```
String GetDateAndTime (void) {
  Process time;
  String junkString = "";
  time.runShellCommand("date +\"%F %T\"");
  while(time.available()) {
    char c = time.read();
    junkString += c;
  }
  junkString = junkString.substring(0,junkString.length()-1);
  return(junkString);
}

```

And you can update the Linux clock periodically using the code:

```
/**************************************************************************/
// Update Clock on the OpenWRT Side using NTP
// command kinda swiped from:
// http://karlduino.wordpress.com/2014/01/14/set-clock-on-arduino-yun/
void forceNTPUpdate()
{
  Process date;
  String junkString;
  date.runShellCommand("ntpd -qn -p 0.pool.ntp.org");
  junkString = "";
  while(date.available()) {
    char c = date.read();
    junkString += c;
  }
}

```

Update the clock when the code starts to set the time and update as needed to keep things as accurate as you like.

---
Tags: rtc
---


title: lilypad works with wrong baudrate

text:
# Question
Title: lilypad works with wrong baudrate
I wrote a simple code on lillypad with fdti module as below:

```
void setup(){
Serial.begin(57600);
}
void loop(){
 Serial.println("ddd");
 delay(500);
}

```

but it gives wrong characters at serial port window of arduino ide at 57600 baudrate. But I changed baudrate to 115200 at same window it gives right string as "ddd". Other baudrates do the same thing. What is the solution or where is the problem. I couldnt understand why baudrate shift occurs

# Answer
> 3 votes
The baud rate shift occurs because of a mismatch between the speed your program thinks the chip is running at and the speed the chip is actually running at.

You may also have noticed that `delay(500)` is too fast and actually lasts as long as `delay(250)` would.

By the numbers involved it looks like the board is running twice as fast (115200 / 57600 = 2) as your board definition says it is - maybe you're using an 8MHz definition for a 16MHz board, or a 1MHz definition for a 2MHz board, etc.

Make sure you have the right board definition selected in the IDE for your board.

---
Tags: serial
---


title: Arduino Yun does it have a RTC?

text:
# Question
Title: Arduino Yun does it have a RTC?
Does the Arduino Yun does it have a RTC?

And if so is it connected to the Atheros AR9331 or the ATmega32u4?

If there there is no RTC, can I connect a DS1307 to the Atheros AR9331?

# Answer
> 5 votes
> the Yún doesn’t have a real time clock IC on board, so it can’t keep time when is powered off. Instead, it synchronizes with time servers automatically when it powers up and connects to a network using NTP.

*(Arduino Blog)*

Therefore, the **Yun does *not* have a onboard RTC.**

> If there there is no RTC, can I connect a DS1307 to the Atheros AR9331?

Probably not. It comes in a LPCC package, which has the solder joints on the bottom. This needs to be soldered by reflow. The Yun does not have any pins connected directly to that chip. You're probably thinking of the ATmega32u4, the actual Arduino chip. The other one is for a router.

**To get the time, you have two options:**

* **Use the time from the time server**

A few notes:

> The Yún must be connected to a network to get the correct time. If you used the web-based WiFi interface to configure the Yún for the network, make sure you've selected the proper time zone.
* **Connect it to a DS1307** (I find this Adafruit tutorial helpful) You'll need only two pins to use this board. One note: there is a way to connect up to 121 I2C devices using these two pins. However, that gets a little more complicated.

# Answer
> 0 votes
What happens with your Arduino YUN is that it has an internal clock which sincronizes with a computer (at least this is what I do). However I have read that it can be automatically but I could not do that; have you got a probable solution?

---
Tags: time, arduino-yun
---


title: ping pong with two Arduinos over serial

text:
# Question
Title: ping pong with two Arduinos over serial
I have two Arduino boards and want to make them communicate with each other over serial. The code I have used for the two boards is almost identical.

* Every one second the "A" board sends a "ping" message over serial.
* The "B" board receives the "ping" message and responds with a "pong" one.
* The "A" board receives the "pong" message and prints it on screen.

**Board A - ping code**

```
String inputString = "";
boolean stringComplete = false;

void setup() {
  Serial.begin(9600);
  inputString.reserve(200);
}

void loop() {

  Serial.print("ping");

  if (stringComplete) {
    Serial.println(inputString);
    inputString = "";
    stringComplete = false;
  }
  delay(1000);
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == 'g') {
      stringComplete = true;
    }
  }
}

```

**Board B - pong code**

```
String inputString = "";
boolean stringComplete = false;

void setup() {
  Serial.begin(9600);
  inputString.reserve(200);
}

void loop() {

  if (stringComplete) {
    Serial.println("pong");
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == 'g') {
      stringComplete = true;
  }
 }
}

```

The code seems to work, but not exactly as expected. I initiate the serial monitor of the board "A" and expect to see every one second:

> pingpong

Instead I see this:

> pingpong
>
> pong
>
> pong
>
> ....

which means that the pong message is repeated more than one time per second. But I want the "B" board to transmit the "pong" message only when it receives the "ping" one.

Why is this happening? Is there an error in the code? Is there a detail about the serial protocol which escapes me?

Any thoughts would be appreciated.

# Answer
The problem is with your protocol and also with how you are using the serial.

You are using the same serial channel both for your communication protocol *and* for the reporting of the results. What you see the B end sees.

So A sends `ping`, and when it sees the letter `g` it responds with `pong`. You then print that `pong` to the serial, so end B sees `pong`. It gets the character `g` and thinks "That was a ping, I'll respond with a pong", so it does - it sends `pong`, which you then receive and duly print - starting the sequence over yet again.

You either need to separate out the communication and the reporting, or make your protocol look for the whole string "ping" so it never inadvertently responds to a "pong" when it shouldn't.

Here's a good resource about reading serial strings on the Arduino: http://hacking.majenko.co.uk/reading-serial-on-the-arduino
> 4 votes

---
Tags: serial
---


# Question
Title: Unable to power an Arduino Pro Mini through the RAW pin
I've recently bought an Arduino Pro Mini, the 3.3V and 8MHz version. The first time I powered it, using the VCC pin, all worked. But, as soon as I attempt using the RAW pin instead, nothing lights up... Is my regulator broken ? Or is this a typical issue ?

# Answer
> 4 votes
I am not completely familiar with that specific board, but according to the schematic there is a solder jumper which is used to isolate the RAW voltage regulator from the rest of the system "for low power applications".

I don't know off hand if that comes pre-soldered or not, but check it to make sure it is connected, otherwise the RAW input will do nothing.

---
Tags: power, arduino-pro-mini
---


title: Trouble reading V_BG

text:
# Question
Title: Trouble reading V_BG
I would like to read MUX 14 with the ADC. On page 263 of the Atmega328 data sheet it shows 1110b on the MUX corresponding with reading V\_BG.

I need to read this so I can calibrate my sensor readings taken with the 5v reference to those taken with the 1.1v reference. Because the 5v power supply may vary and the 1.1 is more stable, I need to be able to translate the readings taken with a 5v reference based on how the internal 1.1v is read.

Based on the code for analogRead, I wrote this:

```
int readVBG(int _analogReference) {
  uint8_t low, high;
  ADMUX = (_analogReference << 6) | 14;
  sbi(ADCSRA, ADSC);
  while (bit_is_set(ADCSRA, ADSC));
  low  = ADCL;
  high = ADCH;
  return (high << 8) | low;
}

```

\_analogReference is either 1 or 3 depending on the reference voltage desired.

I expect to read 1023 when \_analogReference is 3 and about 225 when \_analogReference is 1. Instead I get smaller values which I'm guessing are from a floating (unconnected) analog pin.

# Answer
> 0 votes
The problem is that a 2ms delay is required after setting the ADMUX bits before starting the conversion. Thank you Majenko for the link.

```
int readVBG(int _analogReference) {
  uint8_t low, high;
  ADMUX = (_analogReference << 6) | 14;
  delay(2); // Wait for voltage to settle
  sbi(ADCSRA, ADSC);
  while (bit_is_set(ADCSRA, ADSC));
  low  = ADCL;
  high = ADCH;
  return (high << 8) | low;
}

```

The above code is specifically for the Arduino UNO. Majenko's link above has #ifdef statements which support other devices.

---
Tags: analogread
---


# Question
Title: Adjusting variables in code without reprogramming?
I'm a teacher, working on eliminating some difficulties of Arduino in the name of getting to the fun stuff. Namely, I am building a small Arduino powered device that will collect simple data from sensors like a DHT11, or an accelerometer. That being said, I want to pass simple settings (sample rate, sensor type, etc.) into the device with out reprogramming the board out right. I'm worried I'm over thinking the challenge. Initially, I wanted to pass the settings over serial in Python script, then save the settings to EEPROM and read them when rebooting...but sending strings over serial from Python is proving to be challenging, let alone the EEPROM.

Long term, this will run on an ESP8266 and I'd try to make a simple interface for entering the SSID and password for the Wifi network we want to connect to. Simply plug in the board over USB, run some simple little Python app that asks for SSID, password, maybe sample rate, sensor type and hit configure.

Is there an easier way to build a user interface for adjusting variables in code already running on an Arduino?

# Answer
If the number of choices is limited (device types, a few selections of sample rate), you might consider a bank or two of DIP switches.
> 3 votes

# Answer
Take a look at firmata, which allows you to remotely set pins. There are some robotic frameworks built around it such as as Cylon.JS that are doing similar things, but you are not over thinking it. If anything probably under thinking it.

The Arduino programming environment is about as simple as it gets. It would be hard to have something easier. Perhaps some of the Graphic interfaces like those with a LEGO robotics set would be closer to what you want?
> 1 votes

# Answer
To avoid the serial input and hit the ground running; you could add a simple hardware input like a potentiometer, rotary encoder, or push button that cycled through settings. I would use the Arduino Serial Library to make the configuration viewable on a computer in the IDE serial monitor or terminal. As long as you pull up/down the buttons and separate the inputs properly, a push button and rotary encoder would be easy to keep modular so that it could be safely plugged in and unplugged without an issue. You could also make an interactive menu over the serial interface which asks you for each parameter. The simplest way would be to detect a button press in your application which would take you to 'config mode', which prompts the user for input via the serial monitor. Once everything is entered, save to EEPROM and restart.

If you are determined to take the Serial scripted approach for programming, and are having difficulty with Python, you could repost or update your question to include your code and explain where you are having trouble, or use a different language. I prefer C#, because I use it for so many different things (From websites to XBOX games), and it lends itself well to rapid development. Java would be another good choice particularly if you would like to integrate with Android ;). All of these are easy to integrate with a GUI.

It sounds like you are having difficulty dealing with strings - and don't feel bad about this, strings can be a complex thing because of how they are construed and work. Check out some examples, and re-implement them to suit your application. Try breaking your strings up into characters (which are a byte in size, easy to fit in EEPROM!) and send them byte by byte - this might be simpler.

Saving to EEPROM is trivial and well covered in the Arduino documentation. One thing to keep in mind is that the EEPROM is accessed and used in bytes! What does this mean? - Well, if a larger variable is to be stored, like an int (16 bit on Arduino Uno) it must first be split in half. To do this you would use bit shifting. To give you a quick idea on how this is done, see functions below - note this assumes you only ever save integers to EEPROM (this is in the way I choose to address the memory):

```
// Include EEPROM library
#include <EEPROM.h>

// location is an int from 0-511 using Arduino Uno with 1KB of EEPROM
void SaveValue(unsigned int location, unsigned int value)
{
    // Find addresses to store each half of the integer
    unsigned int saveLocationLower = location * 2;
    unsigned int saveLocationUpper = saveLocationLower + 1;

    // Split the integer into two parts
    byte lowerValue = value;
    byte upperValue = (value >> 8);

    // Save both parts
    EEPROM.write(saveLocationLower, lowerValue);
    EEPROM.write(saveLocationUpper, upperValue);
}

int LoadValue(unsigned int location)
{
    // Find both locations to read using same method as above
    unsigned int saveLocationLower = location * 2;
    unsigned int saveLocationUpper = saveLocationLower + 1;

    // Read both locations
    byte lowerValue = EEPROM.read(saveLocationLower);
    byte upperValue = EEPROM.read(saveLocationUpper);

    // Assemble both halves and return value
    return lowerValue + (upperValue << 8);
}

```

If you are feeling really outgoing and adventurous, and have good luck with the C# route - you could check out Microsoft's latest Arduino offerings - they are pretty cool. It makes it easy to integrate Arduino devices with Windows 10 and Phone apps.
> 1 votes

---
Tags: serial, sensors, esp8266
---


# Question
Title: I guess, pull-up/down resistors fried. What can i do?
Arduino Mega ADK is working well but it is not working circuit in which pull-up/down resistors. It is generating wrong results. I guess, pull-up/down resistors fried. What can i do?

# Answer
If you want internal pullup or pulldown resistors on input pins, you can use external ones to do the same job as internal ones if you wish to. Generally, if you use say 100 k Ohms from a pin to V+ or ground then it will act as a pullup or pull down respectively on an input pin, but have much effect on an output pin - which is what you want to happen.

However, it is unlikely that 'fried internal resistors is the reason for code not working and, if this is the case, there is probably unknown and unknowable other damage as well. Pull up/down resistors are usually not actually resistors. They are FETs with high Rds\_on values that look resistor like when on. Anything that "fries" them has a reasonable prospect of doing other damage as well.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Powering an Arduino Pro Mini directly from a LiPo
I've recently purchased an Arduino Pro Mini, 3.3V version. I've planned to use it in a diy remote: I've empty a ps2 remote, just left the buttons, and the board will be inside. The remote will be wireless: I use an xbee, which also fit inside the ps2 controller. To power it, I use a one cell Lipo, which will empower the Arduino and the XBee, here comes my issue: As you've seen, there will be many things an a single ps2 controller, so I try to minimize connections and external components. But, the XBee will take more than the maximum 150mA provided by internal regulator of the Arduino. So, either I use an external regulator, or I directly plug the lipo in the VCC pin if the Arduino. Can the board survive? If the voltage is greater than 3.3V, will it damage the board?

# Answer
The only thing about the 3.3V Pro Mini that is actually 3.3V is the 3.3V regulator. The main chip (pretty much the only other component) is good for anything from 1.8V up to 5.5V.

Running direct from a 3.7V LiPo or Li-Ion will be perfectly fine. You might want to disconnect or otherwise disable the regulator though to reduce current consumption - the latest Minis have a solder jumper *SJ1* for doing just that, but older versions you may want to actually cut the 3.3V OUT pin of the regulator or de-solder it entirely.
> 6 votes

---
Tags: arduino-pro-mini
---