# Question
Title: How to connect a a three state switch (ON-OFF-ON) to arduino?
I have created a car that can detect obstacle and change its direction, but now I want to add a bluetooth module to control it and I want to switch between the two circuits using a three state switch (ON-OFF-ON), so how can I do that and how can I upload two different codes on the arduino. Here is a fritzing diagram, (the pins for the bluetooth will be changed).

Sensor:

Bluetooth:

And here is the code for the sensor:

```
   #define echopin  8 // echo pin
   #define trigpin 9 // Trigger pin

   int maximumRange = 30;
   long duration, distance;

    void setup() {
        Serial.begin (9600);
        pinMode (trigpin, OUTPUT);
        pinMode (echopin, INPUT );
        pinMode (4, OUTPUT);
        pinMode (5, OUTPUT);
        pinMode (13, OUTPUT);
        pinMode (6, OUTPUT);
        pinMode (7, OUTPUT);
    }

    void loop ()
    {
        digitalWrite(trigpin,LOW);
        delayMicroseconds(2);

        digitalWrite(trigpin,HIGH);
        delayMicroseconds(10);

        duration=pulseIn (echopin,HIGH);

        distance= duration/58.2;
        delay (50);
        Serial.println(distance);
    }

        if (distance >= 30 ){
            digitalWrite(4,HIGH);
            digitalWrite(5,HIGH);
            digitalWrite(6,LOW);
            digitalWrite(7,LOW);
            delay (200);
        }
        else if (distance >=15 && distance <= 25) {
            digitalWrite (4,HIGH);
            digitalWrite (5,LOW);
            digitalWrite (6,LOW);
            digitalWrite (7,LOW);
            delay (1000);
        }
        else if (distance < 15){
            digitalWrite (4, LOW);
            digitalWrite (5, LOW);
            digitalWrite (6,HIGH);
            digitalWrite (7,HIGH);
            delay (1000);
            digitalWrite (4,LOW);
            digitalWrite (5,HIGH);
            digitalWrite (6,LOW);
            digitalWrite (7, LOW);
            delay (1000);
        }
    }

```

Please write in the most details and write any code as I am still a beginner.

# Answer
As stated by st2000, it's not common practice to have two separate programs running on one microcontroller.

The solution is simple, use the switch to "switch between" behavior.

```
if(switch is on){
  //Automatic
}else{
  //Bluetooth
}

```

*You should also use functions, to make your code more readable.*

This might work:

```
#define echopin  8 // echo pin
#define trigpin 9 // Trigger pin
#define switchPin 10

int maximumRange = 30;
long duration, distance;

void setup() {
  Serial.begin (9600);
  pinMode (trigpin, OUTPUT);
  pinMode (echopin, INPUT );
  pinMode (4, OUTPUT);
  pinMode (5, OUTPUT);
  pinMode (13, OUTPUT);
  pinMode (6, OUTPUT);
  pinMode (7, OUTPUT);

  pinMode(switchPin, INPUT_PULLUP);
}

void loop ()
{
  if (digitalRead(switchPin)) { //If the switch is pressed.
    automaticLoop();          //Do the automatic control.
  } else {                   //If not pressed.
    bluetoothLoop();          //Do the bluetooth control.
  }
}

void measureDistance() {
  digitalWrite(trigpin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigpin, HIGH);
  delayMicroseconds(10);

  duration = pulseIn (echopin, HIGH);

  distance = duration / 58.2;
  delay (50);
  Serial.print("Distance is: ");
  Serial.println(distance);
}

void automaticLoop() {
  measureDistance();

  if (distance >= 30 ) {
    digitalWrite(4, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    delay (200);
  }

  else if (distance >= 15 && distance <= 25) {
    digitalWrite (4, HIGH);
    digitalWrite (5, LOW);
    digitalWrite (6, LOW);
    digitalWrite (7, LOW);
    delay (1000);
  }
  else if (distance < 15) {
    digitalWrite (4, LOW);
    digitalWrite (5, LOW);
    digitalWrite (6, HIGH);
    digitalWrite (7, HIGH);
    delay (1000);
    digitalWrite (4, LOW);
    digitalWrite (5, HIGH);
    digitalWrite (6, LOW);
    digitalWrite (7, LOW);
    delay (1000);
  }
}

void bluetoothLoop() {
  //Code for bluetooth.
}

```
> 1 votes

# Answer
While a simple concept, having 2 different selectable programs (sketches) in 1 Arduino is not the way the Arduino paradigm works.

Most Arduinos contain an Atmel processor. This processor contains a boot loader program. This program only knows how to deal with 1 other program (the sketch). In order to switch between 2 different programs (sketches) you would have to re-write this boot loader.

But you still have to deal with the creation of the 2nd program. In order to do this you need to change the SDK used to create the 2nd program (sketch). Specifically, you need to link the 2nd program (sketch) so that it can operate out of a different location in the Atmel processor's memory.

It would be far easier to combine the two programs (sketches) into a single program (sketch). Then use your switch to change the program's (sketch's) behavior.
> 0 votes

# Answer
I'm trying to give you some more general advice.

**How to combine two Arduino sketches into one** There is no general rule, how to do this. But there are some common problems to solve.

1. Code has to be merged for setup and loop independently
2. You can have only one setup() and one loop() when finished.
3. If there are variables with same names in both sketches, you have to rename those in one of them.
4. If you operate with delays, be aware, that delays sum up and retard processing of your loop accordingly.
5. Having your code merged in most cases you need additional variables to transfer information from one code part to another.

**How to use two different hardware setups with one Arduino** There are some general rules, too:

1. Except for some meticulously and intricately designed electronics, you can use each port only once. You have to move hardware to another port if they are conflicting.
2. If you run out of ports, you may have to use port expanders or some logic circuitry to gain more inputs and outputs
3. Check if your hardware does not overload your arduino power supply. some shields and modules can easily suck up the available power.
> 0 votes

---
Tags: arduino-uno, programming
---


title: Creating an Arduino Tic Tac Toe game

text:
# Question
Title: Creating an Arduino Tic Tac Toe game
I'm trying to create a Tic Tac Toe game using the Arduino Uno. Since the Uno has a limited amount of pins to use, I am trying to see if there is a configuration that would make the project possible.

For the button detection circuit I am using a simple voltage divider and an analog pin. I made the following in a circuit simulator:

Now for the LEDs, since the Uno only hosts 9 pins, and we need 18, we need some sort of wizardry to get something working. I came up with the following design using the circuit simulator:

I would use 9 of these, one connected per Arduino pin. Since only one of the LEDs in each of the 9 sets should be on, this type of circuit should allow the Arduino to control all of the 18 LEDs. In the simulation I get about 5mA draw from each side (with 5v and GND).

However my problem is that the LED setup doesn't work. The lights are extremely dim. At first I simply thought that 5mA was not enough for the LED. I decided to measure the current going through the LED and found that it was about 0.8mA. What happened to my 5mA calculation? After all, isn't Arduino pin able to handle about 40mA? Am I asking for too much current?

Where have I gone wrong with this? Thanks in advance for any help.

tommis15

# Answer
> 1 votes
I was working with it more and I found that my mistake was that I was using pin 0 and 1 to test (serial) and switching to pin 2 and above works.

# Answer
> 0 votes
You should really provide more info: \- your program \- what exactly you are trying to achieve (you seem to be driving two leds per 'board position'. What do they represent?) and schematics.

It would also help if you measured the voltage level at the pin in both the ON and OFF state and mentioned it here.

However, one thing that should be noted (hopefully before it is too late) is that your 40mA/pin assumption is wrong. First of all, 40mA is the absolute maximum rating for one pin (i.e. the value you should stay clear of). Secondly, although one isolated pin can source or sink close to 40mA, the total of all GPIO pins should stay below 200 mA. See also http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations .

---
Tags: arduino-uno, led
---


title: WiFi module ESP8266 + Arduino Uno

text:
# Question
Title: WiFi module ESP8266 + Arduino Uno
I'm trying to connect a WiFi module, ESP8266-01 to an Arduino Uno. But, as I've understood, this module will only work with 3.3 V. Since all of the data pins use 5 V, one of the solutions is to use a voltage regulator, such as LM2596.

My questions are:

* Does anyone know if there already exists a tutorial that describes the way this WiFi module can be connected to an Arduino Uno?
* For a simple server, would I need to use several voltage regulators (since there are quite many pins)?
* Since Rx is the receiver, it would not need a voltage regulator because that pin can handle up to 5 volts?
* Is there any need for an external power source, such as a cell?

# Answer
> 5 votes
> Since all of the data pins use 5 V, one of the solutions is to use a voltage regulator, such as LM2596.

You do not want a voltage regulator you need a **level shifter**.

You can buy them cheaply or make them up with a transistor or MOSFET.

I gather the ESP8266 has a Tx (transmit) **to** the Arduino. You probably don't need to level-shift that, as the Arduino Uno will interpret 3V upwards as a HIGH. For the Rx (receive) **from** the Arduino you need to level-shift the data pin (possibly a voltage-divider might work) since the 5V from the Arduino needs to be converted down to 3.3V.

The ESP8266 Vcc and CH\_PD can go to the Arduino **3.3V** pin.

Disclaimer - I haven't done this, I am summarizing what I read on various web pages. Read some of the answers on the pages you get when you do a Google search for more details.

---

## References

# Answer
> 2 votes
Check out the ESP-Link project over on Github. It has a pretty decent implementation of communicating with an Arduino via UART. As mentioned in another comment you will need a 5v-3.3v level shifter. But if you want to make things a little less messy you could just get a 3.3v Arduino mini for probably around the same price as the level shifter. Esp-link is built with the esp-open-sdk so you will have to spend some time setting up the toolchain if you haven't already.

I'm working on a project right now using a Moteino + ESP-12E and it's working great. However I'm planning on porting the RFM69 library and removing the Arduino portion completely. I would recommend doing the same if you can. The link below shows how to use the ESP with a port-expander (using SPI) so you can have more GPIO with the ESP. https://github.com/MetalPhreak/ESP8266\_MCP23S17

# Answer
> 0 votes
If you want a simplest solution, **you can just connect your 5V pin of Arduino to the 3.3V external power supply**. It will work just fine on 3.3V and all of its GPIO pins will be 3.3V too.

**Warning:** You must be careful because if you plug your Arduino to the USB wire, you will instantly get the 5V on all the pins, so you will burn your ESP. So you will have to disconnect ESP during programming.

The easiest (and safe) way for me in this scenario is to just use a standalone ATMEGA328P-PU chip on a breadboard and connect it manually. You just have to plug in 4 capacitors, a 16M oscillator and a resistor and upload sketch using a programmer (like USBasp) and "Upload using a programmer" button. You can then safely run everything on 3.3V because the programmer has a jumper and can work on 3.3V too and you don't have to use ANY level shifters and or voltage dividers. In my case they were not even working (I don't know why). You connect such "environment" once on a breadboard and you can safely work with it later. Let me know if you need more info on this.

**Warning:** If you work with SPI bus (MISO, MOSI, SCK), like an SD card reader for example, then you must secure the SPI lines of the device (card reader) with resistors, because you may also burn your chip if 2 opposite signals are directed to the same line by 2 separate devices. I've burned my 328P like this once.

**Warning:** Don't use a programmer for supplying power to your circuit. It can work for programming, but when your ESP starts connecting to WiFi it will require much more power than the programmer can provide! In best scenario it will just not work and hang up or reset.

---
Tags: arduino-uno, wifi, pins, voltage-level, esp8266
---


title: Breadboard Arduino not loading sketches

text:
# Question
Title: Breadboard Arduino not loading sketches
I have put together a breadboard version of the arduino by following the tutorial on arduino's main website https://www.arduino.cc/en/Main/Standalone.

I have done everything exactly how that tutorial explains it and have double checked my work to ensure I didn't mess up a connection somehow. I have a usb mini breadout board that I am connecting from the breadboard to my computer and the pin outs are as follows:

* GND -\> Breadboard GND
* 5v -\> Breadboard + rail
* TXO -\> IC pin 2
* RXI -\> IC pin 3
* GND (GRN) -\> IC pin 1 through .1μF cap

When I go to the arduino IDE and select the arduino duemilanove setting and upload a sketch I come out with this error:

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding

```

I am using a pre-bootloaded atmega328 chip and have switched it out with two others to make sure it wasn't the switch, but that didn't help either.

Any ideas on what might be the problem?

# Answer
1. Make sure you have a 16Mhz crystal attached to your board at the XTAL locations properly.
2. If you dont have one already, connect a 0.1uf capacitor (ceramic or metal film) to the reset pin for auto reset capabilities.
3. The `avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00` issue is probably due to reset problems, where the arduino is not communicating to the computer. However, there are other possible reasons for this error. http://forum.arduino.cc/index.php?topic=28223.0
4. Double check that TX on the arduino is connected to Rx on the computer and Rx on the arduino is connected to Tx on the computer

If problems keep persisting, post more information so we can help you more.
> 1 votes

# Answer
To expand upon what was previously mentioned in comments, there are a number of things that need to be done before you can program an ATmega via a serial connection:

* you need to have a bootloader flashed on the chip
* you need to provide a clock source (internal or external) matching the fuse settings and the rate expected by the bootloader
* your programming software must use the same baud rate as the bootloader is expecting
* you need to have reset the chip recently enough before starting the upload that the bootloader has not timed out - either manually or via a small capacitor to your logic level serial connection's DTR or RTS line

You commented that your chip came from Sparkfun and was sold as having a bootloader. The programmed ATmega328p's they list claim to have the Uno's bootloader, so most likely these need to be programmed at 115200 baud like an Uno. You instead said that you had selected the Duemilanove setting, which would mean you were trying to use a baud rate of 57600.
> 1 votes

---
Tags: arduino-uno
---


title: Arduino not in sync unique error

text:
# Question
Title: Arduino not in sync unique error
When I try uploading to my Arduino/Genuino UNO I get the following not in sync error with "unique" resp(resp=0X54) or (resp=0X81) please solve ... I have to submit my project tommorow......

> error message: avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x54 avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 2 of 10: not in sync: resp=0x54 avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 3 of 10: not in sync: resp=0x54 avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 4 of 10: not in sync: resp=0x54 avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 5 of 10: not in sync: resp=0x54 avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 6 of 10: not in sync: resp=0x54 avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 7 of 10: not in sync: resp=0x54 avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 8 of 10: not in sync: resp=0x54 avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 9 of 10: not in sync: resp=0x54 avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 10 of 10: not in sync: resp=0x54 Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

\[!\[enter image description here\]\[2\]\]\[2\]

# Answer
You have a BT module attached to Arduino Tx Rx pins. That's the culprit. Disconnect anything from Tx and Rx pins of arduino while uploading code. Once the code has been uploaded, re-connect the BT module.

Edit:

Since this didn't solve your problem, you need to pin point the issue. If you have removed everything from Arduino and still not able to upload the code - either your drivers are not up to date or your arduino is faulty.

Test the arduino:

Try uploading blinky sketch. Didn't succeed? Restart arduino IDE and try again. Didn't succeed? Restart PC and try again. Didn't succeed? Re install arduino and try again? Didn't succeed? Try on a friend's PC? No luck? Arduino is faulty.

Note: This answer is for the exact schematic you have given. If you have done something else, there might be other reasons why you are not able to upload the code. Post a real picture of what exactly you are doing and we might be able to help you further.
> 3 votes

# Answer
NOTE

That schematic shows you are trying to power the motors from the Arduino's 5V power supply. That is a 'bad idea' unless they are good quality, low-current, motors.

The electrical noise from the motors may cause the Arduino to reset, and run the same program from the beginning until it reaches the part where the motor's electrical noise resets it.

Worse, current drawn if the motors stall may damage the Arduino's power supply. The Arduino's voltage regulator is supposed to protect itself from damage, but it doesn't always succeed. This is rare, but I have had students break it.

I have elevated this comment to an answer to warn other people against trying to use the schematic in the question.
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: RGB Led strip pot control burned my arduino?
I made this exact build on my Arduino, with the following differences:

* I'm using Arduino Nano
* Transistors I use are 2N2222A
* I'm running everything on 12V except Arduino, I use LM317 to feed Arduino 6v

Here's the build:

Here's what happened. First, it started to get strange voltage, arduino would light up even when disconnected from power. After that, Arduino kind of got fried, when I connect it to USB, nothing happens. I can give it 6v to VIN and ground it with the rest, but turning potentiometers only dims the onboard LED of the Arduino and that's it.

Now I'm going to go and pick up a new nano, however, I'd prefer not to fry that one, so figuring out why this one burned would be nice.

PS. The image shows RGB LED instead of RGB LED Strip because 123d doesn't have strip component.

# Answer
> 1 votes
First, as Majenko said, you need resistors between the arduino output pins and the transistor bases. Start at something like 330 Ohm. Second, what is the value of the potentiometers? If it is too low you would be drawing too much current from the 5V pin to the ground. Third, you should power the arduino with at least 7V, assuming you power it through the Vin pin or the power jack. 6V is considered too low. I assume the pins connected to the potentiometers are initialised as inputs. Otherwise, it would be possible to burn your arduino by having them source/sink too much current (i.e. by turning the potentiometers to one end or the other).

# Answer
> 0 votes
Looking at the datasheet for the 2N2222A at http://www.onsemi.com/pub\_link/Collateral/2N2222A-D.PDF The 2N2222A base will draw 50 ma at 2volt. You are giving them more than that. The maximum allowed output from the Arduino is 40ma. So check the 2N2222A's they are probably burnt out as well as the Arduino. Next time put in a limit resistor of 1k to the 2N2222A bases. Try pulling out the 2N2222A's and see if your Arduino powers up ok.

---
Tags: arduino-nano, rgb-led
---


# Question
Title: Integer goes garbage after iteration. struct pointer manipulation messed up other variables in memory
I'm writing a library for Charlieplexed LED display (trying to write a common one actually). The library is working quite fine. In my arduino sketch, I'm using an integer to keep track of the LED, currently on. The integer value increases with time and the LED(s) glow one by one. The problem is, after couple of iterations, this integer value just goes out of chart (in Serial monitor, it has garbage values).

```
MatrixCharlieplex mch(Pins, 5, MXCHARLIE_CA); // instance of Class
int i = 0, j = 0;
boolean busy = false;
unsigned long time;
void setup() {
  //Serial.begin(9600);
  time=millis();
}
void loop() {
  if(millis() - time > 100){ // runs every 100 ms interval // corrected from (millis() > (time + 100))
    time=millis();
    blink();
  }
}
void blink(){
  if(!busy){
    busy = true;
    //Serial.print("i:\t");
    //Serial.println(i);
    //Serial.print("Node:\t");
    //Serial.println(i+1);
    mch.TurnOn(i+1);
    increase();
    busy = false;
  }
}
void increase(){
  i = (++i % 20); // resets after every 20 intervals
}

```

Output:

```
i:  16
Node:   17
i:  17
Node:   18
i:  18
Node:   19
i:  19
Node:   20
i:16 <-- Stopped working here. it should be "i:    0" & "Node:    1"
    16
Node:   17
    17
Node:   18
    18
Node:   19
    19
Node:   20
16
    16
Node:   17
    17
Node:   18
    18
Node:   19
    19
Node:   20

```

The sketch can also be found here

***Update:*** There were no hardware-fault. The problem lies in the struct variable declaration as pointers.updated the question & posted answer. The files in the github links have also been updated.

# Answer
After much trial and error effort, I've found the solution.

There was no problem in the hardware side (I ran the sketch with serial monitor after detaching the LED-matrix and all non-crutial hardwares. Thanks @jantje and @NickGammon fot the tips).

Apparently Arduino is not capable of handling **pointers** in advanced ***Oops*** fashion. The library itself used it heavily, specially **"struct pointers"** as function parameters and as return types (Arduino messed up these pointer values with other variable declarations in memory). After removing those pointers from the code and replace them with normal variables, the code runs well.

```
// correct definition
typedef struct {
    uint8_t vcc;
    uint8_t gnd;
} DiodeNode;

// wrong implementation
DiodeNode* node = new DiodeNode();
node->vcc = x;
node->gnd = y;

// correct implementation
DiodeNode node = (DiodeNode){x, y};
// or
DiodeNode node;
node.vcc = x;
node.gnd = y;
return node; // from functions etc.

```
> 0 votes

# Answer
If you have a Charliplexing board like mine (or even if you made your own) the problem could be electrical. If you turn on a lot of LEDs you may exceed the current consumption allowed and then the processor hangs or resets.

I suggest current-limiting resistors like this:
> 1 votes

# Answer
First thing to do is find out whether your problem is electrical or not.
This can be done by removing the electrical parts not crucial to run the code.
If the problem is code related try using another board to eliminate some hardware malfunction on your board.
Doing these steps will give you some insight on the root cause of the problem.
> 0 votes

---
Tags: arduino-uno, pointer
---


title: build fixed size strings from floats

text:
# Question
Title: build fixed size strings from floats
This is likely a duplicate, but I couldn't find the original question. This is really basic, but just can't figure it out.

I'm trying to combine a few char arrays together. This is what I've tried so far.

```
float a = 12.3456;
float b = 5.4321;
bool c = true;

char a_string[4];
dtostrf(a, 4, 1, a_string);

char b_string[4];
dtostrf(b, 4, 1, b_string);

char c_string[2] = {'0', '\0'};
if (c) {
  c_string[0] = '1';
}

char output[12] = "-----------";

output[0] = a_string[0];
output[1] = a_string[1];
output[2] = a_string[2];
output[3] = a_string[3];

output[4] = ' ';

output[5] = b_string[0];
output[6] = b_string[1];
output[7] = b_string[2];
output[8] = b_string[3];

output[9] = ' ';

output[10] = c_string[0];

Serial.println(output);

```

Results in an empty string in seems.

If I remove the second dtostrf(), and change b\_string\[0\] ... to a\_string\[0\] Then I get `12.3 12.3 1`. Doesn't seem to like having dtostrf() called more than once, but it seems like the function I want, since it allows me to set a fixed strint size. The output I'd be looking for is `12.3 5.4 1`

another approach

```
String a_string = String(a, 1);
String b_string = String(b, 1);
String c_string = String(c);

String output;
String space = " ";

output.concat(a_string);
output.concat(space);
output.concat(b_string);
output.concat(space);
output.concat(c_string);

Serial.println(output);

```

This outputs `12.3 5.4 1`. Is there a way to make the String fixed width? I'm looking for

`12.3 5.4 1` instead of

`12.3 5.4 1`

What's the proper way of doing this?

## EDIT

---

After trying to use the @Majenko's answer I sometimes get garbage values printed. Any ideas why?

```
float a = analogRead(A1) / 1023.;
float b = analogRead(A2) / 1023.;
bool c = analogRead(A3) / 1023;

char* output = createString(a, b, c);
Serial.println(output);

char* createString (float _a, float _b, bool _c)
{
    char a_string[5];
    dtostrf(_a, 4, 1, a_string);

    char b_string[5];
    dtostrf(_b, 4, 1, b_string);

    char out[12];
    snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);
    return out;
}

```

and the output:

```
 0.6  1.0 0
 0.6  1.0 0
 0.6  1.0 0
 0.6  1.0 0
 0.6  1.0 0
 0.6  1.0 0
 0.�tS
�
 0.6  `S
�
 0.6  1.0
}
 0.6  1.0 0
 0.7  1.0 0
 0.6  1.0 0
 0.6  1.0 0

```

using

```
  Serial.print(a_string);
  Serial.print(" ");
  Serial.print(b_string);
  Serial.print(" ");
  Serial.println(c);

```

doesn't produce the errors

# Answer
The simple way would be to format the string with `sprintf` \- however `sprintf` on the Arduino lacks floating point support (although it is possible to enable it).

So if you convert your floating point numbers into strings first (remember to provide room for the NULL terminating character!) you can then use `sprintf` to format those converted numbers into what you want:

```
float a = 12.3456;
float b = 5.4321;
bool c = true;

char a_string[5];
dtostrf(a, 4, 1, a_string);

char b_string[5];
dtostrf(b, 4, 1, b_string);

char out[12];

snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);

```

`%4s` is replaced by a string which is padded to at least 4 characters wide. The padding is to the left of the string. If you want the padding to the right you can use `%-4s` instead.

---

# Addendum:

In your new posted code you are making a fundamental error:

```
char out[12];
snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);
return out;

```

`out` is a local variable to the function. Its memory is allocated on the stack. You fill that with data and then return the address of that location on the stack. As soon as you leave the function that memory allocation is lost. Yes, the data is still there, but the moment you call another function that memory gets overwritten with the call frame of the new function you have called - thus corrupting your data.

You have two main options:

1. Make `out` global
2. Make `out` static

The effect of the two options is pretty much the same, except that in the second option the scope of `out` is restricted to the function which means you can use the *name* `out` elsewhere without it conflicting. In both options though the memory allocated to `out` is in the BSS not the stack and thus won't get overwritten.
> 3 votes

---
Tags: string, float
---


# Question
Title: Is there a way to combine a 3-axis accelerometer/gyroscope into one value?
I have a three-axis accelerometer that reads me its x, y, and z components. This results in three graphs. Is there a way to "combine" these components into one reading, hence, one graph? Same question holds for a gyroscope.

The datasheet for my device is here:

# Answer
The answer is: technically, yes, it is possible. The combined result is called Quaternion. This is what is typically used in 3D programs.

But most likely that is not what you had in mind.

Usually one can do a simplification and reduction of dimensions when in presence of some constraint.

Imagine that your moving object is bound to a planar surface: no matter how you tilt and rotate and pan it, it is still a 2D surface, plus a quaternion indicating the rototranslation.

But, once you have established the coefficients applied to the rototranslation, it is 2D.

Similar 1D case: imagine that your moving object is bound to some well-known geometrical shape, say a circumference. Once you have established how the circumference is oriented in the 3D space and its radius, you can express the position of your device by indicating either the angle or the distance from a reference point on the circumference.

In both cases you can simplify the representation because of constraints that do not allow for real 3d movement.

But if your device is a flying drone that can rototranslate freely within certain boundaries (max horizontal range, min/max altitude), there is no way that you can simplify the 3d coordinates.

If, instead, your question was related to the protocol used to read info from the accelerometer, you are bound to the protocol defined in the datasheet, by the manufacturer.
> 1 votes

---
Tags: accelerometer, gyroscope
---


title: Did I fry my servo?

text:
# Question
Title: Did I fry my servo?
I got a new servo a few days back (RC Servo, Futaba FP-S148). I first tested it out with the Sweep sketch on Arduino, powering it with the Arduino 5v and GND pins only. It was working, just fine.

Today I was trying to use it in my robot and I tried powering it with 2 LiPo batteries (Samsung ICR16850 2200mAh, from an old laptop battery) connected in series, giving 8.32v. As soon as I connected my servo, it started rotating randomly, I had not connected it to my Arduino yet. I quickly took it out.

Next, I used a L7805 to get 5.13v regulated supply out of my batteries that I used earlier. When I connected my batteries to the servo, and the servo to the Arduino, uploaded the sketch, the servo started behaving rather strangely, it first did a complete turn and then stopped. Only a humming sound came from the servo. Strange thing is, whenever I connect one of my Multimeter leads to the power cables, the servo immediately turned in the opposite direction only as long as only lead was in contact with either the positive or negative wire. Otherwise, the servo just gives a humming sound.

I stripped down the servo and checked the motor. It is working fine. Moreover now the servo doesn't even makes the humming sound. It just sits there, no movement, no sound.

Have I fried my servo? Or is it some other issue?

# Answer
> 1 votes
> As soon as I connected my servo, it started rotating randomly,

The random movement could be from a floating control line, i.e. random voltages signals are being interpreted as random positions, and the servo is responding.

> I stripped down the servo and checked the motor. It is working fine. Moreover now the servo doesn't even makes the humming sound. It just sits there, no movement, no sound.

Assuming it was put back together properly, then it sounds like the control circuitry has been damaged.

> I had not connected it to my Arduino yet. I quickly took it out.

Have you tried it on the sweep example again, or a servo tester? It could be working.

> Strange thing is, whenever I connect one of my Multimeter leads to the power cables, the servo immediately turned in the opposite direction only as long as only lead was in contact with either the positive or negative wire.

Sounds like you are accidentally sending it control signals with your multimeter.

---

Your servo is dead if:

* it is properly connected and doesn't respond to any control signals
* it is properly connected and responds randomly to control signals
* it is properly connected and responds randomly to a grounded control line

n.b. unconnected (floating control lines could cause random behavior in an otherwise good servo).

# Answer
> 0 votes
Since a servo is basically the combination of this components:

1. Motor
2. Gearbox
3. Position sensor (i.e a potentiometer)
4. Motor control electronics (e.g some useful stuff to protect the system and to relate d.d.p. over it's node to position =\> angle\[i.e could by just an operational ampifier\])

The unusual behaviour could have been raised by a single component of the system, most likely the variable resistor. There's no guarantee of sucess, but maybe we can use this event to discover soimething! My advce is try to discover the potentiometer used by the producer of the servo by looking at related datasheet. Then solder/attach temporarly an half-value or a quarter-value, resistor if the servo change it's orientation consider a replacing, if not just get rid f it.

Hope helps :)

Reference https://www.pololu.com/blog/15/servo-servo-motor-servomotor-definitely-not-server

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


title: Hardware Interrupts Issues

text:
# Question
Title: Hardware Interrupts Issues
My program has a hardware interrupt to digital pin 2, it is an IR obstacle detection sensor which gives “open collector” signal. My program is executing an array — “for” loop. At some point it has to wait for the input from the IR sensor, so I am using a “while” loop to pause and wait for the input.

When the program gets the signal from the sensor at which point the interrupt occurs, the program collects the data (millis) and goes on for another round. Everything works fine, but I would like to limit the time that the program is waiting for the interrupt signal, let’s say to 5 or 10 seconds. I do not want it to just sit there forever if the signal is not coming for some reason. So what I am trying to do is to trigger the same interrupt pin (2) by another digital pin. I set this pin (7) on OUTPUT wrote a little “if-then” statement so it will go HIGH when the time is up and connected this pin (7) to pin 2.

The scheme works partially. When the pins are connected and the time limit is reached the pin 2 gets signal and gets triggered. But the IR signal seems to be disabled and not functioning while it is waiting for the time limit. I tried to connect pull-up and pull-down resistors to no avail. It seems that when the pins are linked the IR signal disappears. I do not even get any voltage readings on that wire. If I disconnect the pins the IR signal works again and I get voltage readings on the wire.

Can anyone tell me what is going on and how can I make it work. Is even possible? Or what I have concocted is just plain silly?

Thank you!

# Answer
> 0 votes
It is likely that the Arduino's digital output is of a totem poll type. That is, it is both actively being driven high and low. And when high, is probably over powering the IR sensor's signal. You should not use this setup!! As it could possibly short out both your processor and IR sensor.

Instead you could emulate an open collector Arduino output. By switching the second pin from a digital input to a digital output sending 0 then back to a digital input. (Never set this pin to digital output and send a 1 as this could short to ground through the IR open collector.)

I am assuming that the IR sensor, when activated, is momentarily pulling a pull up resistor low through the open collector to ground. Let us know if this is incorrect as the above description would then not apply.

# Answer
> 0 votes
Wouldn't it be easier just to have the interrupt call a function, that you also call after 5 seconds are up? This sounds a round-about way of doing it.

If you *must* do this, setting your other pin to output is not correct, because then the IR sensor and your other pin (7) are fighting each other. You should set the pin to *input*, and when you want it to do something briefly make it OUTPUT, and send HIGH. Then send LOW, and go back to INPUT.

However this might still make the output pin "fight" the IR sensor pin.

---

> But the IR signal seems to be disabled and not functioning while it is waiting for the time limit.

Naturally, as your output pin is holding the line low.

---

If the sensor just uses a pull-down resistor (and not actively drive the line low) then my scheme should work.

---

However a simpler scheme is just to set a flag in the ISR, (which you test for in the main loop) and if the flag isn't set within your timeout period, do whatever you want to do if it times out. Then you don't need to try to trigger the interrupt yourself.

---
Tags: arduino-uno
---


# Question
Title: How to use the analog comparator to determine when an analog pin has reached a certain voltage?
I am trying to find some information on how to use the analog comparator on an Atmega328 to detect when an analog pin has reached a certain voltage (3.16 volts).

I cannot find any example code that says how to do this, although I have read that the analog comparator can compare the voltage on an analog pin with the voltage output by a PWM pin. I do not understand how this would work as the PWM pins do not output an analog voltage, but a pulse width modulated square wave. Is it possible to use the comparator to compare with a certain voltage this way?

I have tried polling with `analogRead()`, but it is too slow for my application.

# Answer
> 5 votes
I have a page about the analog comparator that has code:

```
volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop

```

This is for a fixed reference voltage, for example:

# Answer
> 1 votes
You need a low-pass filter between the PWM output and the comparator input. This will allow you to produce an analog voltage from the PWM output, which can the be used as a reference voltage for the comparator.

Typically, a simple RC LPF is sufficient. Choose a large time constant relative to your PWM frequency (the Arduino defaults to 490Hz) so that you don't have ripple in your reference voltage.

---
Tags: atmega328, analogwrite
---


title: Split string into an array of string

text:
# Question
Title: Split string into an array of string
I have a SIM900 module connected to an Arduino Uno, using an AT command for listing the SMS I get this output, how can i split this based on (`,`) to store each data in an array?

```
AT+CMGL="ALL"

+CMGL: 2,"REC READ","+639321576684","Ralph Manzano","16/04/25,21:51:33+32"
Yow!!!

OK

```

# Answer
You could try to use `strtok`. Code from my mind and not tested:

```
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char string[] = "AT+CMGL=\"ALL\"\n"
    "\n"
    "+CMGL: 2,\"REC READ\",\"+639321576684\",\"Ralph Manzano\",\"16/04/25,21:51:33+32\"\n"
    "Yow!!!\n"
    "\n"
    "OK\n";
    char delimiter[] = ",\n";

    // initialize first part (string, delimiter)
    char* ptr = strtok(string, delimiter);

    while(ptr != NULL) {
        printf("found one part: %s\n", ptr);
        // create next part
        ptr = strtok(NULL, delimiter);
    }

    return 1;
}

```

Outputs:

```
found one part: AT+CMGL="ALL"
found one part: +CMGL: 2
found one part: "REC READ"
found one part: "+639321576684"
found one part: "Ralph Manzano"
found one part: "16/04/25
found one part: 21:51:33+32"
found one part: Yow!!!
found one part: OK

```
> 6 votes

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


# Question
Title: UNO's digital pin continue to read 1 for a while
I'm doing some tests and I notice a bad things with digitals pins. I have a wire that sends 1 signals. If i connect it to a reading pin, I read 1 - and it's ok. But if i disconnect it, for 5-6 seconds Arduino continues to read 1 instead of 0! How can I stabilize it more quickly?

# Answer
Digital inputs should either be low or high. In this image acceptable input voltages on the left represent common TTL voltages based on a 0 to 5 volt range:

It is bad practice to leave a digital input floating. A floating or disconnected input implies the voltage is unknown. I suspect in your case a small amount of input capacitance held a charge for several seconds. Once leaked off the input appeared to change from 1 to 0. Even though you know what might be happening, you should not depend on it as it is unreliable behavior.

If connecting a SPST switch use a pull up (or pull down) resistor to pull the input pin to the opposite voltage the switch is pulling. In this image the switch is connected to ground so the resistor is connected to positive voltage as a pull up:

The fist image comes from this Logic Level tutorial.
> 5 votes

# Answer
St2000 's reply above gives the background, which is valid for any digital input, not just the Arduino pins.

However, in the specific case of the Arduino, one more thing should be noted: You can skip the use of an external pullup resistor by configuring the pin to use the internal pullup resistor:

```
pinMode(pin, INPUT_PULLUP) ;

```

This assumes, of course, that it is easy to modify the part of your circuit that is connected to your input pin to have the following two states:

```
- ground
- high impedance (floating)

```

If, for example, it is a switch you are reading, just connect one pin of the switch to your arduino pin and the other to GND.
> 0 votes

---
Tags: digital
---


# Question
Title: How to build a high-frequency (>20kHz) driver for LEDs?
I'd like to build a LED lighting for my house. I've made preliminary tests and I've realized that my 12V transformer emits a considerable electric hum at the Arduino's PWM frequency range (PWM signal from Arduino gets amplified by external amplifier powered by the transformer).

I know, that I can reduce the audible noise if I will drive the PWM at higher frequency, beyond the human ear's audible range.

AFAIK Arduino itself is not able to give me 8-bit PWM at the \>20kHz range. Do you know any feasible hardware high frequency PWMs that will work with the Arduino?

# Answer
> 1 votes
I am not into hardware but the way we handle it was by using a external PWM designed for LEDs and control that, using an Arduino. The LED driver we used was a TLC5940, see TLC5940 16-Channel LED Driver With DOT Correction and Grayscale PWM Control. This one is controllable using the SPI bus.

There are several libaries implementing the protocol, i.e PaulStoffregen/Tlc5940.

See Playground from Arduino - TLC5940 for more information.

# Answer
> 2 votes
Just change the timer prescaler to a lower value.

E.g. timer2 (PWM pins 3 and 11) has the prescaler set to clock/64 and runs at around 500Hz. So changing it to clock/8 will result in 4kHz. (Sorry, no clock/16 available).

```
TCCR2 &= ~_BV(CS22);//clear CS22 bit
TCCR2 |= _BV(CS21);//set CS21 bit

```

---
Tags: led, pwm
---


# Question
Title: How can I interface HMC5883L compass board to a smartphone with OTG?
Friends... I have an idea to attach the **compass sensor (HIMC5883L)** with my **android smartphone** using arduino, but I don't clearly know how to do this. I mean I want to make an OTG compass for smartphone for map navigation etc.(Many Smartphones have compass but mine have not). If anyone had do this or know how to do this, please guide me. Thanks!

# Answer
A cheaply available USB OTG adapter cable (ask eBay) will connect the Arduino to the phone.

You can then connect the compass sensor to your Arduino and write a sketch to retrieve the data from it and send it through the USB serial connection.

Then you need to write some software for the phone to receive and interpret the serial data and display it as a compass. That is unless you are happy just to have a simple text display (like the Arduino's Serial Monitor) with the compass information showing in it, in which case there is off-the-shelf software that would do that (search Play)
> 0 votes

---
Tags: arduino-uno, android
---


title: Post Data To a Web Service From Arduino

text:
# Question
Title: Post Data To a Web Service From Arduino
If you want to submit sensor data such as temperature to a remote server/database somewhere you need to use some kind of call to a web server since it isn't possible to connect directly to a database from the Arduino.

How do you post data to a JSON web service from an Arduino that's connected to the Internet?

# Answer
> 4 votes
There is the aJson library that allows you to work with JSON objects in Arduino.

However, depending on the complexity of your program, I would just do it manually to save memory. You may be able to just copy the functions you want out of the library.

Then check out the WebClient library which has an example for making a POST request at the bottom.

# Answer
> 1 votes
Check this from Arduino docs.

In the "Post method request" code example just define your JSON as plain text like `char jsonData[] = "{name: 'yourName', data: 'yourData'}"` for example, and then call `byte postPage(char* domainBuffer,int thisPort,char* page,char* thisData)` function passing "jsonData" variable defined before for "thisData" parameter.

It worked for me, hope it helps.

---
Tags: web-service
---


title: Measure current and consumption

text:
# Question
Title: Measure current and consumption
I'm trying to measure kWh with an Arduino that I have connected to a ESP8266 that communicates this value to a web server I have. And I've been trying to find the best and easiest way to go about this.

I'm thinking that I can hook a PMAC903 up to the Arduino using the interrupt pins and measuring the pulses, but I don't really know how I'm supposed to do that? Will it even work? Is this the way it's normally done? I can't really say I've found an easy solution to measure current.

You can find documentation for the PMAC903 here and I'm currently in possession of an Arduino Uno that I'm using.

# Answer
> 2 votes
The state of this meter can be read in 3 ways:

* Pulse, this is very easy to implement. But depending on the stability of the hardware u can miss pulses leading to inaccurate values. In this way u have to calculate the meter value yourself.
* RS485, this is a communication bus not default on arduino. But given this link https://arduino-info.wikispaces.com/RS485-Modules i think it is doable but not easy. This will read the value from the meter.
* M-Bus: There is special hardware needed to interact with it. This is the industry standard of doing it. It's not cheap. But u can link many meters together. This will read the value from the meter.

Depending on your time/knowledge/other requirements u have to make a chose what way your going to use.

---
Tags: arduino-uno, current
---


# Question
Title: DVD drive stepper motors with polulu a4988 on Arduino
I am new to arduino, I started learning about it today and i'm stuck. I ripped out a small stepper motor from an old DVD drive. I got a polulu a4988 driver and I have wired it up as follows:

```
/*     Simple Stepper Motor Control Exaple Code
 *
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *
 */
// defines pins numbers
const int stepPin = 3;
const int dirPin = 4;

void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
}
void loop() {
  digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction
  // Makes 200 pulses for making one full cycle rotation
  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
  }
  delay(1000); // One second delay

  digitalWrite(dirPin,LOW); //Changes the rotations direction
  // Makes 400 pulses for making two full cycle rotation
  for(int x = 0; x < 400; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
  }
  delay(1000);
}

```

But nothing happens, the motor doesn't even vibrate. Any idea what could be wrong?

# Answer
According to Pololu's website, the VMOT pin needs at least 8V to function. Try a 12V **switching** (important!) wall wart supply that can supply at least 1A instead of your USB supply. Avoid supplies that can deliver currents \>3A, as they are overkill for a small stepper motor and can be dangerous if shorted. Be sure to put a large (100uF is good) capacitor across that supply to prevent voltage spikes. To prevent damaging the motor from the higher voltage, follow the information Pololu provides on setting the current limit and set it to about 350mA. If you notice the motor is too hot to touch, try 200mA.
> 3 votes

---
Tags: arduino-uno, stepper
---


# Question
Title: Can't figure out how to distribute the power
so I'm making a project, kind of BB-8 droid replica, and I stumbled upon a problem. Since I am using two RC brushless motors, ESC's and batteries, I want to make my Uno board fed up from those batteries. Also, I want to use inductive charging set that would charge both batteries. Can anyone tell me or give some kind of scheme how should I distribute the power from batteries and what additional boards should I buy?

# Answer
> 1 votes
The best option is to connect the 5V/2A output of the UBEC to the 5V pin on the Arduino. In my experience, 7.4V is not enough to feed into the input jack on an Arduino especially if it is from a battery, as the voltage will drop when current is being drawn by other loads. I have built an Arduino controlled robot using a 6V NiMH battery and brushed DC gearmotors (so no ESCs or UBEC) and used a $5 5V 1A step-up/step-down converter so that even if the battery voltage dropped below 5V, it could still power the board. However, since you have a UBEC that is not in use, use it. **Note that if you put voltage into the 5V pin, disconnect it when you are connecting the arduino over USB or you might damage your board.**

As for inductive charging, I don't know of any off-the-shelf solution designed for charging a 2S lithium ion battery. The best option for charging would probably be an easy way to open the ball to access the batteries.

---
Tags: power, battery
---


# Question
Title: Is it possible to start audio playback when headphones gets plugged in?
I want to have 6 audio jacks IN waiting for connection to start some WAV/OGG playback as soon as a headphone plugs in. In fact, I'd like to have simultaneous playback in 6 lines.

I've seen in the market some stuff that you can add buttons to different actions (play, pause, stop, etc). So far I believe this might be possible and affordable with Adafruit's Audio FX (which are stand-alone, Arduino-programmable WAV/OGG decoder circuits).

But,

> Is it possible to start audio playback when headphones gets plugged in? HOW?

Is that an event? like pressing a button?

Does it need some "hacking" between GND lines maybe?

# Answer
A lot of 3.5mm jacks come with built-in normally-closed contacts, and their state can be tested through the pins of the jack with a multimeter or sensed by your MCU like any other switch. There are usually 2 pins each for the **ring** (pins 2 and 4 below) and the **tip** (pins 3 and 5), each pair connected to the other and one pin for the **sleeve**. The insertion of the headphones' connector breaks the connection between each pair, so that only one pin of each pair is actually connected to the connector's tip and ring.

You can connect the tip (pin 3) of each jack to digital input pins and connect the other pin of the pair (pin 5) to Vcc; you only need to read the tip because if the tip contacts are closed, it means nothing is fully plugged in yet. When no connector is plugged in, input pin reads HIGH from the tip since it is connected to Vcc through pin 5. When the headphones are plugged in, it breaks the 3-5 connection, and the tip now floats. Its voltage is indeterminate; it will probably sit somewhere near the middle of the 0-5V range, but we can't be sure. To remedy this, there are 2 possible approaches I can see:

* You use an **analog** input pin, instead of a digital pin. This way, you can read the very voltage at the tip; if its ADC value is above 900 perhaps, you can conclude that its HIGH and therefore nothing is plugged in, whereas if its below 600, you can conclude that the tip is floating and a headphone is plugged in. However, this method will require an input pin per headphone. The Uno has 6 analog pins, so this will take up all of them. If you aren't already using any of them, this method may be good enough. You could also use an analog GPIO expander.
* You can use a digital input pin for the tip (pin 3) *but* instead of pulling pin 5 to Vcc, you connect it to a digital output pin. You can connect the pin 5 of each headphone set to this common output pin. To test if a particular jack has headphones plugged into it, you read the associated input pin and check if this is the same as the current value of the common output pin (saved to some variable). If it is, you toggle the output pin and again check the input pin to see if it mirrors the new value of the output pin; just additional confirmation. If everything checks out, then nothing is connected to the jack yet. If either test fails, you can reasonably conclude that headphones are plugged in.

Now that you know headphones are plugged in, you can call the appropriate function to begin playback through the right jack. Of course, all this assumes you'll be working with the jacks directly and not through some module. If you use the Adafruit Soundboard, you can check out the L (Left Channel) pin, which corresponds to the tip. I don't know if it's actually connected to the jack so you'll have to experiment and find out.
> 5 votes

---
Tags: audio
---


# Question
Title: No response from device when trying to communicate with it via RS-232
I have an Arduino Uno with an RS-232 shield, and a servo drive that communicates via CAN or RS-232. I'm trying to communicate with this drive using an RS-232 cable, but I'm getting no response. I'm using the SoftwareSerial library on the Arduino to use digital pins 3 and 2 as rx and tx. Only pins 2 (RxD), 3 (TxD), and 5 (GND) of RS-232 are used to communicate with the drive. 19,200 is the default baud rate for the drive. The drive is powered with a dedicated power supply. The drive is supposed to echo every character received back to the sender.

I've had success using a simple Java program to communicate with the drive using the same kind of cable (although with a USB-to-serial converter). The drive echos all characters back, and the motor responds to the commands sent to the drive. The cable used has a female DB9 connector on one end (to communicate with the desktop) and a custom 3 pin connector on the other (to communicate with the drive).

I've also had success with the same Java program communicating with the Arduino (also with the converter). This cable has a female DB9 connector on one end (to communicate with the desktop) and a male DB9 connector on the other (to communicate with the Arduino).

But I've had no success exchanging data between the Arduino and the drive. There is no response back from the drive nor does the motor respond to any commands. The cable used for this has a male DB9 connector on one end (to communicate with the Arduino) and a custom 3 pin connector on the other (to communicate with the drive).

Each cable has been tested with a voltmeter to confirm that pins on one end are connected to the correct pins on the other end.

I'm at a loss here. Is there something I'm missing?

For your consideration, here is the Arduino code. It is the same whether it is connected to the desktop or the drive.

```
#include <SoftwareSerial.h>
#include <SPI.h>

const int rx = 3;               // software serial receive pin
const int tx = 2;               // software serial transmit pin
const int baudRate = 19200;     // 19,200 bits per second for read and write serial functions

SoftwareSerial serial(rx, tx);

/*
 * Initial, one-time setup
 */
void setup()
{
    Serial.begin(baudRate);     // open hardware serial communications
    serial.begin(baudRate);     // open software serial communications

    serial.println("MO=1;");      // start motor
    serial.println("JV=30000;");  // set velocity to 30,000 counts/second
    serial.println("BG;");        // begin movement
}

/*
 * Executes every tick
 */
void loop()
{
    if (serial.available())
    {
        Serial.write(serial.read());
    }

    if (Serial.available())
    {
        serial.write(Serial.read());
    }
}

```

Also, here is the Java code.

```
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class TwoWaySerialComm
{
    public TwoWaySerialComm()
    {
        super();
    }

    void connect(String portName) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned())
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

            if (commPort instanceof SerialPort)
            {
                SerialPort serialPort = (SerialPort)commPort;
                serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();

                (new Thread(new SerialReader(in))).start();
                (new Thread(new SerialWriter(out))).start();

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    /** */
    public static class SerialReader implements Runnable
    {
        InputStream in;

        public SerialReader(InputStream in)
        {
            this.in = in;
        }

        public void run()
        {
            byte[] buffer = new byte[1024];
            int len = -1;
            try
            {
                while ((len = this.in.read(buffer)) > -1)
                {
                    System.out.print(new String(buffer, 0, len));
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    /** */
    public static class SerialWriter implements Runnable
    {
        OutputStream out;

        public SerialWriter(OutputStream out)
        {
            this.out = out;
        }

        public void run()
        {
            try
            {
                int c = 0;
                while ((c = System.in.read()) > -1)
                {
                    //System.out.print(c);
                    this.out.write(c);
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
    {
        try
        {
            (new TwoWaySerialComm()).connect("COM4");  // COM4 is port of USB-to-serial converter
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

```

# Answer
> 1 votes
I've found the issue. The serial cable I was using was too long, introducing resistance to the signal. That's it!

---
Tags: arduino-uno, motor, softwareserial, rs232
---


# Question
Title: Flickering LCD when using > 5v power supply on a Pro Mini
I have a Pro Mini wired up to an LCD via an I2C board. At http://www.arduino.cc/en/Main/ArduinoBoardProMini it says the pro mini can accept up to 12v on the RAW pin as it has a voltage regulator on board. When I plug a 12v power supply into the raw pin, the LCD works fine initially, then slowly degrades into flickering more and more. It also does this with a 9v power supply. At 5v it works perfectly. Any ideas what's going on?

# Answer
If the LCD has a backlight you are absolutely over heating the regulator on that board by running it at 9 or 12V: At 12V with 100mA for the backlight and using 175C/W thermal resistance for the regulator: Tj = 25C + ((12V - 5V) x 100mA x 175C/W) = 147C That regulator goes into thermal limit at 125C.
> 3 votes

---
Tags: lcd, arduino-pro-mini
---


title: Soldering headers screwed up Trinket?

text:
# Question
Title: Soldering headers screwed up Trinket?
Last week I purchased a couple of Trinkets from Adafruit (5v micro-USB). The first thing I did was solder the headers to one of them. I did the whole setup process w/ the Arduino IDE and didn't have any issues, until I actually tried uploading the "Blink" example.

When I plug in the Trinket, I get the pulsing red light, but when I try to upload during that, I get:

```
avrdude: error: usbtiny_send: Input/output error (expected 64, got -5)
avrdude: verification error, first mismatch at byte 0x0004
         0x1d != 0x36
avrdude: verification error; content mismatch

avrdude: error: usbtiny_transmit: Input/output error

```

Then, if I press the reset button, I can't get it to "pulse" again. The red light just dimly turns on and stays constant.

I tested the other Trinket I ordered (that has *not* been soldered yet) and it works perfectly fine.

So, did I somehow screw up something when soldering the headers? Or do I have a faulty Trinket?

For reference, here's the trinket in question...

# Answer
There are what appear to be burn or melt marks on the 5 pin component labeled QTSO and on the diode near the USB pin. That could be a sign of damage due to soldering, reverse polarity, or excessive current draw through the voltage regulator (a short circuit).

Based on the fact that the light stays on solid when the reset button is pressed, it sounds like it could also a different issue. First, turn on verbose output in the arduino IDE and post the full output when you try to upload.

Next, try disconnecting **everything** except the USB cable while uploading the program. If that does not fix it, it is most likely that the bootloader is corrupted. This has happened to me on multiple occasions for no apparent reason and it is pretty easy to fix.

If repairing the bootloader does not fix this, it is most likely that one or both of the components mentioned above are damaged.
> 1 votes

# Answer
On this side it doesn't seem like there's a solder bridge, although it's possible there is one on the other side if you were heavy handed on the solder.

Since you did the verification with the other unit this can't be a software or usb cable issue.

So indeed it's coming from the trinket itself. I think your best bet is to desolder the pins and check the upload again. If it's failling, try flashing a new bootloader. And if it's still not working then I guess either it was faulty from the start or you did damaged a component during the soldering.
> -1 votes

---
Tags: adafruit, electronics
---


# Question
Title: Gesture sensing TV coffee table - what sensors would you use?
A 32 inch flat screen was embedded in a coffee table and covered by a protective layer of glass. Sensors around the edge of the glass surface need to be able to detect the precise location of an object on the glass so that a mouse cursor can be controlled with a stylus.

What sensors would you use to ensure accuracy of stylus location above the screen?

# Answer
> 2 votes
Perhaps if you drop the monitor an inch or 2 away from the glass you can use a Frustrated Total Internal Reflection (FTIR) IR scheme. But at that shallow angle it will be tricky and may require several cameras around the edges.

added later...

Should mention the parallax problem given there is a gap of an inch or more between the monitor and the touch screen. FTIR is better when you project the image onto the touch screen.

If you don't mind lower resolution, I believe the micro dose dispenser soda machines use a capacitive touch wire mess embedded in the transparent plastic front panel. Although micro dose dispensers appear to only need to emulate about 100 to 200 buttons. Not enough to control a mouse with any accuracy. But enough to control a GUI designed with such constraints.

Loose high resolution capacitive touch screens can be bought with out a monitor. However they tend to be much smaller then 32 inches.

---
Tags: sensors, ir
---


title: Producing a sine wave with the DAC?

text:
# Question
Title: Producing a sine wave with the DAC?
Its being a few days i am trying to achieve something that I dont really know if possible. Using the `Samd21` chip(`Arduino Zero`), I am using a timer and a `DAC` to produce a sine wave.

The required frequencies are **100Khz to 3Mhz**. I know its sounds too much, but according to my calculations its possible- I would like to know if I am wrong with my software approach.

Pseudo is this :

1.I create a look-up table of a sine wave = array of a sine samples that holds N samples 2.I use a timer with a pre scale of 1, where the clock speed is 48Mhz 3.Each timer tick I produce from the DAC 1 sample from the sine wave 4.To change frequencies I am changing the timer top counter value.

If we try to speak about the max frequency, according to Nyquist , a 3MHz sine must be sampled with at least 6MHz sample rate, and my sine array has 15 samples, means 45Mhz sampling rate.(=good)

Then the sine frequency is :

```
sineF= TimerF*sineSamples = TimerF*15

```

Than means I need a timer frequency of :

```
TimerF=15*sineF = 15*3Mhz=45MHz

```

So, both are good, the timer max f can be 45Mhz, and the sampling rate is good according to Nyquist.

The only concern here, is **if the DAC can do that(speed)**, and if changing the timer frequency fast enough (even every period) is acceptable.

Is this whole software approach true ? If its not, producing a square wave probably possible,since it requires much less speed, but then, can you turn it into a nice clean sin wave with filters?

Thanks.

# Answer
First, I have to say I am not familiar with the Zero hardware, so I am answering in quite general terms. Hopefully you will also get some answers with hardware-specific information. That being said, here are my first thoughts:

1. Your approach seems reasonable to me, but you are too optimistic regarding the achievable sampling rate.
2. DACs are usually fast. It's unlikely that the DAC will limit the frequency you can achieve.
3. You cannot achieve a sampling frequency of 45 MHz in software with a CPU running at 48 MHz: your code to output a sample would have to run in less than 1.07 CPU cycles.
4. You may achieve a higher sampling rate with an array of 16 samples rather than 15, as wrapping the array index modulo 16 can be optimized by the compiler into a bitwise AND, which is likely to be faster than computing `index%15`.
5. Fastest would probably be to use a busy loop with constant execution time and interrupts turned off (I know how to do that on AVR, but not on ARM). Problem is: the program cannot do anything else than outputting samples.
> 2 votes

---
Tags: signal-processing, digital-analog-conversion
---


# Question
Title: Can send AT+ commands, but can't upload sketch to ESP8266 via Arduino Uno
Connected a generic ESP8266 to an Arduino Uno.

I can send AT commands fine and generate a normal response, but cannot upload sketches to the ESP8266. I have "Generic ESP8266 Module selected as the board. Tried everything e.g. switching Tx and Rx, connecting GPIO0 and GPIO2 to to Vcc or ground, but to no avail.

Arduino IDE spits this out -

```
esptool v0.4.5 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    stat C:\Users\Michael\AppData\Local\Temp\build7227402767538495982.tmp/wifi_setup.cpp.bin success
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed

```

# Answer
> 1 votes
You mention:

> connecting GPIO0 and GPIO2 to to Vcc or ground

I've had success with this sequence:

* GPIO0 to gnd (and hold momentarily)
* RST to gnd (then let go, while holding GPIO0 to gnd)
* let go of GPIO0 from gnd (e.g. let it float again)

To do a firmware flashing, you need to hold GPIO0 to ground for the duration of the flashing process, so the sequence would be slightly different.

You can do this just prior to "build and upload" in the Arduino IDE—provided the build process doesn't take too long. It will sometimes still fail, in which case reset the ESP8266 (RST to gnd momentarily) and restart the sequence.

I've found a little test/development harness (like this one http://www.buildcircuit.com.au/esp8266-test-board) is very handy for doing this repeatedly.

# Answer
> 0 votes
I have been hooking the ESP8266 straight up to my PC and programming it in NodeLua. Of course it depends on what you want to do, but consider dropping the Arduino and just using the ESP8266.

# Answer
> 0 votes
You don't need an Arduino UNO to program the ESP. You just need an USB to UART adapter (CP210x or FTDI one) and the Arduino IDE. Hook the ESP rx and tx to the tx an rx of the adapter and you are ready to go. Here is an detailed explanation how to program ESP using arduino

If you don't have an USB to UART bridge you can use the Arduino board as bridge: check this

---
Tags: arduino-uno, wifi, esp8266
---


title: memory game arduino

text:
# Question
Title: memory game arduino
so I have a project which is to make a simple memory game using Arduino where the LEDs have to blink in a certain pattern and the player has to imitate the same pattern but unfortunately I'm having so much trouble with the code I want to make an if statement to check whether the button was pressed or not if it was it continues to check on the second button and if it wasn't the red led (which means wrong) has to turn on this is how i started:

```
enter code here

const int button1 = 2;          // 1st button controls Blue LED
const int button2 = 3;          // 2nd button controls Yellow LED
const int button3 = 4;          // 3rd button controls Green LED
const int button4 = 5;          // 4th button controls Red LED
const int led1 = 7;             // Blue LED
const int led2 = 8;             // Yellow LED
const int led3 = 9;             // Green LED
const int led4 = 10;            // Red LED
const int correctLED = 6;
const int wrongLED = 11;
int val = 0;

// Variables
int buttonState[] = {0,0,0,0};         // current state of the button
int lastButtonState[] = {0,0,0,0};     // previous state of the button
int buttonPushCounter[] = {0,0,0,0};

void setup() {
  // initialize inputs :
  randomSeed(analogRead(0));
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);
  pinMode(button4, INPUT);

  // initialize outputs:
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  // initialize serial communication for debugging:
  Serial.begin(9600);
        }
  }

 void loop() {
       digitalWrite(7, HIGH);
       digitalWrite(8, HIGH);
       digitalWrite(9, HIGH);
       digitalWrite(10, HIGH);
       digitalWrite(7, LOW);
       digitalWrite(8, LOW);
       digitalWrite(9, LOW);
       digitalWrite(10, LOW);

       digitalWrite(7, HIGH);
       delay(500);
       digitalWrite(7,LOW);
       delay(500);
       digitalWrite(8, HIGH);
       delay(500);
       digitalWrite(8,LOW);
       delay(500);
       digitalWrite(9, HIGH);
       delay(500);
       digitalWrite(9,LOW);
       delay(500);
       digitalWrite(10, HIGH);
       delay(500);
       digitalWrite(10,LOW);
       delay(500);

       val = digitalRead(2);  // read input value
       if (val == HIGH) {         // check if the input is HIGH            (button released)
       digitalWrite(wrongLED, LOW);  // turn LED OFF
       } else {
       digitalWrite(wrongLED, HIGH);  // turn LED ON
       }
       val = digitalRead(3);  // read input value
       if (val == HIGH) {         // check if the input is HIGH           (button released)
       digitalWrite(wrongLED, LOW);  // turn LED OFF
       } else {
        digitalWrite(wrongLED, HIGH);  // turn LED ON
       }
       val = digitalRead(4);  // read input value
         if (val == HIGH) {         // check if the input is HIGH (button released)
       digitalWrite(wrongLED, LOW);  // turn LED OFF
       } else {
       digitalWrite(wrongLED, HIGH);  // turn LED ON
       }
       val = digitalRead(5);  // read input value
       if (val == HIGH) {         // check if the input is HIGH (button released)
       digitalWrite(wrongLED, LOW);  // turn LED OFF
       } else {
         digitalWrite(wrongLED, HIGH);  // turn LED ON
       }
       digitalWrite(correctLED, HIGH);

       }
       }

```

# Answer
> 2 votes
For this kind of thing you don't really want to be worrying about "is this button and then this button pressed" etc. That thinking is very much "of the moment" in that it is all about what is happening now - not what has gone on in the past.

You need to be thinking about the sequence of button presses that you have seen so far - not what is happening right now.

Say you have three buttons. Let's assign a number to each of them - say they are buttons 1, 2 and 3.

And you have 3 LEDs - let's call them A, B and C.

So you light and extinguish the LEDs in a specific order, say BAC, and you expect the buttons to be pressed in the same order - 213.

You can't be checking all the time for "If 2 is pressed then 1 is pressed then 3 is pressed" because, basically, where are you in that sequence at any one instance in time? Instead you need to go: "A button has been pressed. I'll store that fact." And then: "Have three buttons been pressed? Yes. Do their numbers match?"

Basically like a PIN code for your bank card, or a password for your computer. It's not what you are pressing now, it's what it remembers you pressing in the past.

And the simplest way of doing that is to literally allocate numbers to the buttons. When a button is pressed you assign a number representing that button to a variable. Then append that number to the list of numbers you have seen recently. When that list is the right length you compare it. Just like entering a password.

You can even compare what you have so far with a portion of what you expect to catch incorrect presses early.

So say you have an expected value of "213" stored in a string. You also have an empty string. When you press a button you append that number to the string - so say you press "212" you could then append and compare the string like this:

```
Button  Input  Expected
2       2      2         Correct
1       21     21        Correct
2       212    213       Incorrect - erase input content
2       2      2         Correct
1       21     21        Correct
3       213    213       Correct - next round please.

```

# Answer
> 2 votes
Format and extra braces aside there are other issues with your code, too many to fit in a comment.

1. You have used led1, led2 etc in the setup routine and the resorted to numbers in the loop function.
2. At the start of loop() you turn the leds high then low, you won't see this because the processor is faster than your eye, you need a delay statement after the last high and last low.
3. You can make you code more elegant by writing a function that takes the pin as a parameter and toggles the led high then low and call this rather than repeating 4 lines of code.

> ```
> void togglePin(int pinNumber, int interval)
> {
>    digitalWrite(pin, HIGH);
>    delay(interval);
>    digitalWrite(pin, LOW);
>    delay(interval);
> }
>
> ```

4. When it comes to reading values you have blocks of repeated code, again these could be a separate function, which will make your code easier to read and understand.

When you have done that you might want to so a bit of research on 'switch debouncing' because I'm guessing you might have issues with that too.

# Answer
> 1 votes
Your code as written will have both the `wrongLED` and `correctLED` on. It will also continuously loop showing the sequence.

# Showing the Sequence

To show the sequence once at the start, put it in the setup function. Read more about the setup function here: http://www.arduino.cc/en/Reference/Setup

# Detecting the Button Presses

You want to detect each press of the buttons. For this you will need **edge detection code**. There is an Arduino example built into the IDE and information describing the function here: http://www.arduino.cc/en/Tutorial/StateChangeDetection
To add to the Arduino explanation, you can either detect the rising edge (ie. the transition from a LOW to a HIGH) or the falling edge (ie. the transition from a HIGH to a LOW). I personally prefer the following code to detect a rising edge:

```
if ( (lastButtonState == LOW) && (buttonState == HIGH) )

```

where `buttonState` would be assigned by a `digitalRead` and `lastButtonState` would record the value of `buttonState` at the end of the loop function (ie. just before it reads in the button states again).

Using your global arrays you could write:

```
buttonState[0] = digitalRead(button1);
buttonState[1] = digitalRead(button2);
buttonState[2] = digitalRead(button3);
buttonState[3] = digitalRead(button4);

if ( (lastButtonState[i] == LOW) && (buttonState[i] == HIGH) )

```

where `i` is a number between 0 and 3. You could use a for loop to cycle through the 4 available buttons.

# Recording the Button Presses

The StateChangeDetection example above counts the number of button presses. Instead, you want to record 4 button presses. To do this create a global variable called `pressNumber`. Create it with the initial value of 0.

Create an integer array of 4 elements called \`userSequence'.

Every time the if statement detects a rising edge, store the button number in the `userSequence' at position`pressNumber`and then increment the`pressNumber\`.

When `pressNumber` reaches 4, the user has entered his/her guess.

# Evaluating the Guess

This only occurs once the user has entered the guess. Start off by creating a boolean variable and assign it TRUE. Cycle through the elements in the `userSequence` array and compare the users guess to the correct answer. If the user gets one wrong set the boolean variable to false. At the end, turn on the red LED or green LED depending on the state of the boolean variable (ie. if it is true turn on the green LED, otherwise turn on the red).

# Final Notes

* As Matt suggests, try refactoring portions of code into functions. It makes the code more readable and reduces the complexity of the code.
* You can use the variables for the pin numbers of the buttons and LEDs in the `digitalWrite` and `digitalRead` functions. Eg:

digitalRead(button1); digitalWrite(led1);

---
Tags: arduino-uno
---


title: How to read data using Arduino SPI

text:
# Question
Title: How to read data using Arduino SPI
in the datasheet, it's stated that I should apply 32 serial clocks to get the 32 bits of data. How can I program this is Arduino?

# Answer
You call `SPI.transfer()` four times, each time saving the returned value to a variable after proper bit shifting.

```
uint32_t val;
val = SPI.transfer(0xff);  //0xff is a dummy
val |= (uint32_t)SPI.transfer(0xff) << 8;
val |= (uint32_t)SPI.transfer(0xff) << 16;
val |= (uint32_t)SPI.transfer(0xff) << 24;

```

I assume the least significant byte is received first. Make sure the SPI mode is the right one, as indicated in your datasheet.

If the slave can't handle being deasserted between bytes (which is what `SPI.transfer()` will do at the end of the transaction), then you can either try st2000's hardware SPI approach or use bitbanged SPI with `shiftIn()`.
> 3 votes

# Answer
Sparkfun has a good explaination of what SPI is:
https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi

The Arduino IDE has a SPI library that comes with the IDE.
http://www.arduino.cc/en/Reference/SPI

The library comes with two examples:
Using SPI to read a Barometric Pressure Sensor
Controlling a Digital Potentiometer Using SPI
> 1 votes

# Answer
Objective is to read 32 bits using the (unknown) device's SPI port.

If the device will tolerate the SPI Chip Select line activity (going from inactive to active to inactive for each 8 bit byte read) you should be able to get the desired 32 bits of data by performing 4 consecutive 8 bit SPI reads.

However, if the device will not tolerate the above SPI Chip Select line activity (that is, if the device requires the SPI Chip Select to be active for the entire 32 bit SPI transaction), you can not separate the 32 bit transaction into 4 individual 8 bit SPI transactions with out controlling the SPI Chip Select line. The following code example illustrates how this is done:

```
void loop(){
//transfer 0x0F to the device on pin 10, keep the chip selected
SPI.transfer(10, 0xF0, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, keep the chip selected
SPI.transfer(10, 0×00, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, store byte received in response1, keep the chip selected
byte response1 = SPI.transfer(10, 0×00, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, store byte received in response2, deselect the chip
byte response2 = SPI.transfer(10, 0×00);
}

```

The above example comes from the Arduino SPI library web page and is a 16 bit (not 32 bit) transfer. To code up a 32 bit transfer, continue to call the SPI.transfer method using the SPI\_CONTINUE parameter.

added later...

It appears people are discouraging use of the DueExtendedSPI methods. And SPISettings and SPI.beginTransaction() are to be used? If so this page show example code where the code is explicitly controlling the SPI Chip Select line (look for slaveAPin & slaveBPin). Note how the code is reading 24 bits from slave A and writing 8 bits to slave B. To read 32 instead of 24 bits, we need to alter a segment of the code (along with a few other supporting changes) in this fashion:

```
...
  SPI.beginTransaction(settingsA);
  digitalWrite (slaveAPin, LOW);
  // reading only, so data sent does not matter
  val0 = SPI.transfer(0);
  val1 = SPI.transfer(0);
  val2 = SPI.transfer(0);
  val3 = SPI.transfer(0);
  digitalWrite (slaveAPin, HIGH);
  SPI.endTransaction();
...

```
> 0 votes

---
Tags: spi
---


# Question
Title: Use distance sensor to trigger LED strip and stay on while the person is in range
I'm trying to use a distance sensor to trigger an LED light, as you can see below. However, I also want the LED to stay on/white when a person is within the 38 inches range. How should I do that?

```
//Tell the Arduino IDE to include the FastLED library
#include <FastLED.h>

//Setup the variables for the HC-SR04
const int trigPin = 9;
const int echoPin = 6;
//Setup the variables for the NeoPixel Strip
#define NUM_LEDS 60 // How many leds in your strip?
#define DATA_PIN 4 // What pin is the NeoPixel's data line connected to?
CRGB leds[NUM_LEDS]; // Define the array of leds

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}

void loop() {
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(2);
  digitalWrite(trigPin, LOW);

  // Read the signal from the sensor: a HIGH pulse whose
  // duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  if (inches <= 38)  {
    for ( int colorStep = 0; colorStep < 256; colorStep++ ) {
      int r = 255 - colorStep;
      // Redness starts at zero and goes up to full
      int b = 255 - colorStep;
      // Blue starts at full and goes down to zero
      int g = 255 - colorStep;
      // No green needed to go from blue to red
      // Now loop though each of the LEDs and set each one to the current color
      for (int x = 0; x < NUM_LEDS; x++) {
        leds[x] = CRGB(r, g, b);
      }
      // Display the colors we just set on the actual LEDs
      FastLED.show();
      delay(10);
    }
  } else if (inches > 38) {
    fill_solid( &(leds[0]), NUM_LEDS /*number of leds*/, CRGB::Black);
    FastLED.show();
  }
  delay(1000);
}

long microsecondsToInches(long microseconds) {
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second). This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

```

# Answer
if (inches \<= 38)

That You might want to change. Try using "while(inches \<= 38)" and moving sensor calculations to that loop. When ever the distance stays less than You want the light should stay on.
> 1 votes

---
Tags: sensors, led, rgb-led
---


# Question
Title: It seems as if there is a 220K pull-down resistor on analog pin 0
So I am building a project that uses the analog pins for precise measurements of resistance through a voltage divider and I have been having some seemingly unsolvable problems with nonlinear response to linearly changing resistances when using the A0 pin to measure.

I first realized this was the problem when I had a voltage divider consisting of a 76.8K and 100K 1% resistors with Vout connected to A0, and I was consistently getting wrong values. I measured the output voltage of the voltage divider and got 1.7V, instead of the ~2.7 volts I should be getting with my supply. When I disconnected the wire to A0, the voltage rose to the expected level.

I disconnected power and measured resistance between the analog pins of the Atmega328 I was using and ground and found that A0 had 220K of resistance, while all other pins measured as infinite. When using the other pins, the voltage divider returned the expected values and was able to measure a wide range of resistors with values just as accurate as my multimeter. I know I have changed a lot of low-level things with code (analog reference, the comparator, ADC clock prescalers, using analog pins as outputs, etc.) but I don't think any of this could persist while the chip is not powered on. Does doing any of these things connect a resistor in the way I was describing, and is there anything that could cause this to stay "stuck" this way?

# Answer
> 1 votes
They don't connect a resistor as such, but analog input pins do have an *impedance* which can affect your readings.

If your output impedance (the resistance of your resistors) is within about a tenth of the impedance of the input pin then you will (and have) noticed skewing of the results. This is normal. The input impedance is somewhere in the region of 1MΩ - 10MΩ.

You have to keep your output impedance to a value below the order of a few tens of kΩ to minimise the effect the measuring of the value has on the value.

If you want to measure higher resistances then you will need to buffer the voltage with a very high impedance op-amp buffer.

Incidentally, your volt meter probably has an input impedance in the region of 10GΩ - around 1000x higher than the Arduino's ADC.

---
Tags: atmega328, hardware, digital-analog-conversion
---


title: Reserve /dev/ttyUSBx

text:
# Question
Title: Reserve /dev/ttyUSBx
I have multiple Arduinos that I want to control using Python. My problem is that when I plug my Arduinos into the computer, they get assigned the port `/dev/ttyUSBx` where `x` increments with each one I connect.

Is there any way to reserve a certain number for a certain Arduino so that I can hard code that into the Python script? If not, can I scan the port to figure out which Arduino it is?

# Answer
Yes. You need to create new unique names for them using udev rules.

By using the unique serial number, along with the VID and PID of the board you can use udev to create a symbolic link to a device name of your choice. Best to keep it to something that the Arduino IDE recognises if you want to access the link from within there for programming (otherwise you can choose what you like).

Rules are stored in /etc/udev/rules.d and take the form of `.rules` files with various instructions in. One example, that should do what you want, is:

```
SUBSYSTEMS=="usb", ATTRS{product}=="Arduino Uno", ATTRS{serial}=="6493832323135111C0A1", KERNEL=="ttyACM*", SYMLINK+="ttyACM50", MODE="0666", GROUP="plugdev"

```

Of course, tweak it to your personal requirements.

Once you have crafted your rules be sure to restart udev:

```
sudo systemctl restart udev

```

or

```
sudo /etc/init.d/udev restart

```

and plug your board in.

Genuine Arduino devices usually use /dev/ttyACM\* not /dev/ttyUSB\*. If you have /dev/ttyUSB\* then you are either on a very old device (with an FT232 chip) or a cheap Chinese clone.

If the latter then your mileage may vary somewhat.
> 4 votes

---
Tags: port-mapping
---


# Question
Title: I want to run jvm on arduino.What minimum configuration do I need?
If Arduino IDE itself is built on Java can I run JVM on the Arduino? If yes how should I do it?

# Answer
> 1 votes
Search for "embedded java". Oracle supports it for ARM cores, which is what some of the arduino-like boards such as the Teensy 3.X have, but I doubt they have enough resources to support it.

There is haiku-vm (google it!) that's designed with AVR processors in mind, but I don't know how actively it is being worked on.

Googling "embedded java avr" yields a tremendous amount of results; did you even try that?

---
Tags: arduino-uno, programming, electronics, java
---