# Question
Title: Use of two external power sources for a power cell - charger
I have a SparkFun Power Cell - LiPo Charger/Booster and want to use the external 5V charge capability. Now my question:

Can I directly hook up a DC jack (for a 5V power supply) **and** an inductive charging circuit to the external charge pins of the Sparkfun Power Cell LiPo Charger Module or should I use a slide switch so that **either** the power supply via the dc jack **or** the inductive charging module can power the Sparkfun Power Cell LiPo Charger? I prefer the first option, but I have concerns that the inductive charging module is damaged when for example the power supply is hooked up...

Have anybody experience with an similar setup?
Thank you in advance for your answers.

# Answer
> 1 votes
A switch would be the best way of preventing damage, but you could also use diodes to prevent power flowing back to the PSU or Inductive circuit.

I tried something similar once using transistors to prevent both circuits operating at the same time, but never managed to get it to work. You could practice any solutions on a breadboard with some LEDs.

---
Tags: power, inductive
---


# Question
Title: Arduino connecting relay has no power output
I'm a newbie trying to control something through a relay. I've tried two relays with two different setups.

# Setup 1

External 12V dc input to the relay (SRD-12VDC-SL-C) and signal pin from arduino to the IN pin, GND of ext. power supply to the GND of the Arduino, NO and COM to the load object (i.e. an LED).

# Setup 2

Similar to setup 1, but using SRD-05VDC-SL-C, 5V from Arduino (Vin from Arduino also tested).

# Test program

Modified version of the 'blink' example.

# Symptom

1. The load object has been verified to be working before the testing.
2. Both setup can be verify the input is working, the power led and switch led of the two relay module are lighted as expected, and I can hear the click sound while switching.
3. No output can be obtained, both from the load object and using a multimeter.

# Update

Sorry, I'm supposed to upload a Fritzing schematic, but I can't find a proper relay as I'm using.

1. The DC+ (red) of the relay is connected to the external ATX 12V.
2. The DC- (black) of the relay is connected to the external ATX ground.
3. The IN (blue) of the relay is connected to the Arduino pin 8.
4. The external ATX ground (white) is connected to the Arduino ground.
5. The NO (red) of the relay is connected to the load object Vcc.
6. The COM (black) of the relay is connected to the load object ground.

# Sketch

A simple modified version of Blink example is used for testing.

```
const int relaySignalPin = 8;

void setup() {
  // put your setup code here, to run once:
  pinMode(relaySignalPin, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(relaySignalPin, HIGH);
  delay(1000);
  digitalWrite(relaySignalPin, LOW);
  delay(1000);
}

```

# Question

I have no idea on why there's no voltage can be obtain between NO and COM while the switch is on, what's wrong with my setup?

# Answer
It sounds, from your textual description (*please* post a schematic or at least a photo of your setup) that you aren't providing power to the relay.

A relay doesn't have a *power output*. It never *provides* power - it is merely a magnetically operated switch. It is used to switch an external source of power on and off.

Treat the NO and COM pins as either side of a normal button or switch and wire it accordingly - that is (for example) connect COM to the positive of your power supply, NO to one side of your load, and the other side of your load to the negative of your power supply.

You can share the same power supply as you are feeding to the logic / drive side of the relays.
> 1 votes

# Answer
So basically there are two wires connected to the same positive 12v source, one connected to VCC on the input side of the relay board and the other connected to the output side common terminal. And there are three connections from the same negative 12v source, one connected to the ground of the relay board, one connected to the ground of the arduino, and the other connected to the ground of the load. Then, of course, the connection to the relay to one of the digital pins of the arduino.

Well I'm pleased to report it works!

Now to discover what the jumpered COM/GND connection on my relay board does or does not do. I will report back.
> 0 votes

---
Tags: arduino-uno, relay
---


# Question
Title: Arduino IDE menu doesn't display properly (missing letters)
I have just installed newest version of Arduino 1.7.10 from arduino.org.
It has this problem that its menu are not displaying properly - when I hover mouse over items in menu they either disappear completely or some of the letters are missing. Sometimes the whole menu (like 'tools' menu) won't even display. Dialog windows (like "Do you want to save your changes") also suffer from this problem.

I have Windows 7 and I just installed newest version of Java to see if this helps, but it doesn't.
Have any of you had such problem?

# Answer
I've never had this problem, but here are some things you might want to look at.

* Did you install it from an administrator account and use "run as administrator"? If not, uninstall and reinstall.
* Its possible that you are missing a font, god knows which one. Go and look at the Arduino source on GitHub(?) and find any TTF files and install them.
* Does this version support Windows 7?
* What version did you have previously? Did you uninstall it before installing this?
* If you didn't have a version before this one, uninstall this version go and get 1.5 or 1.6 and install that, then install 1.7 over the top.

Good luck, and keep monitoring the Arduino.org forums because if it is a problem with the app then they will start screaming quite quickly.
> 1 votes

---
Tags: ide
---


# Question
Title: Can I use Arduino Nano V3 to program another arduino (Pro Mini)?
I was planning to buy serial to USB converter (FT232RL) to be able to program Arduino Pro Mini. But the shop nearby offers Arduino Nano V3 at almost the same price. Could I use this Arduino instead (and gain new microcontroller platform for free ;-)?

# Answer
> 2 votes
**Yes!**

Yes, you can substitute the Arduino Nano V3 for the Arduino Uno and follow the instructions here, providing that the Arduino Pro Mini is a 5V version. (Otherwise, you will have to do some voltage conversion.)

Both boards have the same SPI pins as the Arduino Uno. The connections would be as follows:

Arduino Nano --\> Arduino Pro Mini
5V -------------------\> Vcc
GND ----------------\> GND
D10 -----------------\> RESET (10uF between RESET & GND)
D11 -----------------\> D11
D12 -----------------\> D12
D13 -----------------\> D13

The process detailed in the link can be summarized as follows:

1. Load the `ArduinoISP` sketch into the Arduino that you will use as programmer. You find it under `Examples` \> `11. ArduinoISP` \> `ArduinoISP`.
2. Select the serial port of the Arduino Nano (target): `Tools` \> `Port` \> corresponding port number.
3. Wire up the two Arduinos as described.
4. In the `Tools` menu, set the programmer to the `Arduino as ISP`.
5. Select the target board: `Tools` \> `Board` \> `Arduino Pro Mini`.
6. Open the program to be loaded to the Arduino Pro Mini and program it by selecting `Sketch` \> `Upload using programmer`

---
Tags: programming, arduino-nano, arduino-pro-mini, programmer
---


# Question
Title: Is it possible to have an array of int arrays?
I have a huge number of arrays, each with a series of numbers each referring to an LED on a strip. I want to be able to address each one by a number, so the logical solution to that for me was to make the whole thing into an array. Can that be done, or is there a better work around that can be implemented?

# Answer
Yes you can have arrays inside arrays.

The array would be declared as:

```
int arrayName [ x ][ y ];

```

where `x` is the number of rows and `y` is the number of columns.

The example below declares and initializes a 2D array with 3 rows and 10 columns:

```
int myArray[3][10] = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
                       { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 },
                       { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 } };

```

To access the value of 27 (and save it into myValue):

```
myValue = myArray[2][6];

```
> 7 votes

---
Tags: array
---


# Question
Title: Networking multiple Arduino Megas and updating their programs from one master
Is it possible to link multiple Arduino Megas using RS485, for example, and update the program on client Megas from one master Mega, as well as for them to communicate with each other? Whilst I found multiple examples of networks, nothing comes up for programming the boards other than through a PC

Thanks for any pointers!

# Answer
In principle, yes, you can do it. It's what existing bootloaders do -- they take code over the serial port, or USB, load it to flash, and then branch to it. Not to mention OTA.

So yes, you can modify the bootloader to use different pins, talk rs485, come up with code-integrity checks, specify particular bit patterns to signal "reboot" or "now load new code", and so on. If you have enough flash, you can even keep two copies, a working and a new, like most OTA code does.

I am not aware of a ready-made library that does that. If I wanted to roll my own, I would start by studying the OTA code.
> 0 votes

---
Tags: firmware
---


# Question
Title: System Is not Functioning Error. Windows XP, Arduino Uno R3, C# Listen SerialPort
Can anyone help me with this issue.

We created an arduino project. We listen microswitch. If switch click, Arduino send basic serial data. And C# application read serial port.

This solution is working but after more times (3Hours, 5Hours,..) system stoped. Error message is "a device attached to the system is not functioning" Solution: Usb remove and retry plug system is going to running.

We are try putty.exe maybe problem C# project but don't working.

If microswitch click don't flash "TX" or "RX" led.

```
const int button = 3;

uint64_t bounceTime = 50;
uint64_t holdTime = 250;
uint64_t doubleTime = 500;

uint64_t lastReading = LOW;
uint64_t hold = 0;
uint64_t single = 0;

uint64_t onTime = 0;
uint64_t lastSwitchTime = 0;

void setup() {
 pinMode(button, INPUT_PULLUP);
 Serial.begin(9600);
}

void loop() {

 int reading = digitalRead(button);

 if (reading == HIGH && lastReading == LOW) {
   onTime = millis();
 }

 if (reading == HIGH && lastReading == HIGH) {
   if ((millis() - onTime) > holdTime) {
     hold = 1;
   }
 }

 if (reading == LOW && lastReading == HIGH) {
   if (((millis() - onTime) > bounceTime) && hold != 1) {
     onRelease();
   }
   if (hold == 1) {
      delay(5000);
      reading = digitalRead(button);
      if(reading==LOW){
              Serial.println("B");
      }
     hold = 0;
   }
 }
 lastReading = reading;

 if (single == 1 && (millis() - lastSwitchTime) > doubleTime) {
   single = 0;
 }

}

void onRelease() {
 if ((millis() - lastSwitchTime) >= doubleTime) {
   single = 1;
   lastSwitchTime = millis();
   return;
 }

 if ((millis() - lastSwitchTime) < doubleTime) {
   single = 0;
   lastSwitchTime = millis();
 }

}

```

# Answer
> 1 votes
I assume that by "USB" you mean "USB-to-serial adaptor".

Try running the same code without any serial communications, just have an LED do the equivalent of printing, and power it from a good power supply. If it runs for more than five hours, the problem is with the USB adaptor and/or your PC (Windows XP? Really?), and hence not relevant to this forum.

If the code crashes, then maybe you have a marginal board, or there is some other environmental factor that's giving you trouble. The code looks OK on first glance.

---
Tags: arduino-uno, serial, c#
---


# Question
Title: Code doesn't seem to work when trying to program 2 sensors
Can anyone help me with this issue

I'm trying to program two FSR sensors through typing this code but I've realized that one is working instead of two.

The logic behind the code is that if you were to squeeze both sensors at the same time it will print out an output on the serial monitor acknowledging that both sensors have been squeezed. I have got only one to work by using this code.

The first sensor is connected to the A0 pin on the arduino and the second sensor is connected to the A1 pin

This is the code that I've written

```
/* FSR simple testing sketch.

 Connect one end of FSR to power, the other end to Analog 0.
 Then connect one end of a 10K resistor from Analog 0 to ground
 For more information see www.ladyada.net/learn/sensors/fsr.html */

int fsrPin = 0;
int fsr2Pin = 1;   // the FSR and 10K pulldown are connected to a1
int fsrReading ;
int fsr2Reading;   // the analog reading from the FSR resistor divider

void setup(void) {
    // We'll send debugging information via the Serial monitor
    Serial.begin(9600);
}

void loop(void) {
    fsrReading = analogRead(fsrPin);
    fsr2Reading = analogRead(fsr2Pin);

    Serial.print("Analog reading = ");
    Serial.print(fsrReading);
    Serial.print("\t");
    Serial.print(fsr2Reading);

    // We'll have a few threshholds, qualitatively determined
    if (fsrReading < 10) {
        Serial.println(" - Nothing");
    } else if (fsrReading < 200) {
        Serial.println(" - Light");
    } else if (fsrReading < 500) {
        Serial.println(" - Lightness");
    } else if (fsrReading < 800) {
        Serial.println(" - Medium");
    } else if (fsr2Reading < 1100) {
        Serial.println(" - No-Pressure");
    } else if (fsr2Reading < 1400) {
        Serial.println(" - Light-touch");
    } else if (fsr2Reading < 1700) {
        Serial.println(" - Light-squeeze");
    } else if (fsr2Reading < 2000) {
        Serial.println(" - Medium-squeeze");
    } else {
        Serial.println(" - Big-squeeze");
    }
    delay(1000);
}

```

So could anyone tell how to edit this code correctly in order to get two sensors to work?

The one connected to the A0 pin is working but not the other

# Answer
> 1 votes
As JFPoilpret says you if logic is wrong. It might make it easier if you took that whole if block out and made it into a function that accepted the value from the sensor as a parameter.

```
void CheckReading(int reading)
{
    if (reading < 10) {
        Serial.println(" - Nothing");
    } else if (reading < 200) {
        Serial.println(" - Light");
    } else if (reading < 500) {
        Serial.println(" - Lightness");
    } else if (reading < 800) {
        Serial.println(" - Medium");
    } else {
        Serial.println(" - Big-squeeze");
    }
}

```

Notice that the values only go up to 800, going larger than 1023 won't work anyway.

# Answer
> 1 votes
Try changing the pins to use A0 and A1, as pins 0 and 1 relate to the digital pins.

```
int fsrPin = A0;
int fsr2Pin = A1;   // the FSR and 10K pulldown are connected to a1

```

As has been mentioned by Matt, make sure you also only test for values between 0 and 1023.

You are also missing the pinMode, which sets the pins as input/output in the setup function

```
void setup(void) {
    // We'll send debugging information via the Serial monitor
    Serial.begin(9600);
    pinMode(fsrPin, INPUT);
    pinMode(fsr2Pin, INPUT);
}

```

# Answer
> 0 votes
@Rich1234 I have taken your code, JFPoilpret's, Holmez's and my answers and put them altogether. Hopefully this explains what we mean and will give you something to work from. It does compile, but I don't know if it works, because I don't have two sensors to try it with. The code is by no means perfect, but its a start. If there are any problems, give us a shout.

```
/* FSR simple testing sketch.
 Connect one end of FSR to power, the other end to Analog 0.
 Then connect one end of a 10K resistor from Analog 0 to ground
 For more information see www.ladyada.net/learn/sensors/fsr.html */

const int fsrPin = A0;      // Change to A0 so it refers to the correct pin
const int fsr2Pin = A1;     // Change to A0 so it refers to the correct pin
// int fsrReading ;     // Change Not required
// int fsr2Reading;     // Change Not required

// Function     : Read the data from the pin and write a meaningful description to the serial output.
// Parameters   : The analog pin to read from.
// Returns      : The value read from the pin
int checkReading(int pin)
{
    const int reading = analogRead (pin);       // Get the reading from the pin. (const because it won't change within the scope (life) of this function)
    Serial.print(reading);
    Serial.print(" - ");
    if (reading < 10) {
        Serial.println("Nothing");
    } else if (reading < 200) {
        Serial.println("Light");
    } else if (reading < 500) {
        Serial.println("Lightness");
    } else if (reading < 800) {
        Serial.println("Medium");
    } else {
        Serial.println("Big-squeeze");
    }
    return reading;
}

void setup(void) {
    // We'll send debugging information via the Serial monitor
    Serial.begin(9600);
    pinMode(fsrPin, INPUT);     // Change to define the pin 'direction'
    pinMode(fsr2Pin, INPUT);
}

void loop(void) {

    Serial.print("Analog reading A0 = ");
    checkReading(fsrPin);
    Serial.print("Analog reading A1 = ");
    checkReading(fsr2Pin);

    delay(1000);
}

```

---
Tags: arduino-uno
---


title: IR sensor does not work well on carpets

text:
# Question
Title: IR sensor does not work well on carpets
I have facing a problem since long and cannot solve it. I built Arduino car and place 2 IR sensors shown in image, to check down distance to avoid falling from stairs. One is at back and other at front. On hard surface they work well but on carpet always give wrong reading like no object there which translates unsafe to move and my car stops. How can we solve this problem? I also tried Ultrasonic but it has same problem on carpets or fabric.

I tested this that on carpet it was giving a big distance reading but when I place a white paper, suddenly it was fixed and detected surface.

# Answer
You may have noticed that this product is no longer available from well known parts distributors like adafruit.com, sparkfun.com or trossenrobotics.com. I would recommend using a Sharp distance sensor designed for the distances you are interested in:  It is about 10 times the price, but produces a variable voltage that you can read with the Arduino's ADC. Then you can compensate for floor irregularities in your code.

If you care to experiment, I obsurved that the better distance measurement devices angle the emitter and sensor to light up & observe the same spot at the desired operating distance:

You might try this with your current sensor. However, it does not appear the manufacture left you enough lead length to make such an adjustment.
> 1 votes

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


# Question
Title: Send information (such as a string) over digital pins
I wan't to send information from my arduino digital pins to another arduino's digital pins like a string, or a char. Can I do this without something like Software Serial?

The reason I am asking is because I am wanting to send information from several serial devices to my raspberry pi from an arduino. Thing is, that Raspberry pi only has one set of UART pins, so I was thinking because I have extra arduino uno's, why not send then information to the arduino and have it write the received information to the raspberry pi's digital pins..

Now that I am writing this, I think I will connect the 2 arduinos via a serial connection, and use software serial to write out to the raspberry pi, in three different stages, to get the information to the pi.

The reason I am using the PI is I want to display this information on a large screen with many different options, in short the GPU capabilities are what I am using the PI for, that and Processing.

**Question still stands though, can you send information over digital pins?**

# Answer
> 1 votes
Yes, you can send information to/from your arduino digital pins using a method called Bit Banging. Wikipedia (lots more on Google!)

You can use the Arduino to output as an ad hoc serial port or parallel port. The serial could be asynchronous (UART/RS232/I2C) or synchronous (such as SPI).

The down side is you will have to write a fair bit more software to send/interpret the data.

From your description I gather that data is only going one way - from the Arduino to the Pi. I personally would bit bang SPI as I think this would be the easiest and would not require exact timing.

# Answer
> 2 votes
The RaspberryPi is a fairly complete linux computer. As such it can be a USB Host to many USB Devices. If you need more serial ports simply buy FTDI equipped USB to serial cables, plug them into a USB hub and plug that into the RaspberryPi.

# Answer
> 2 votes
There are many different ways of communicating.

In addition to serial you can use a protocol like SPI or I²C. If the Arduino are in close proximity I²C enables many devices to communicate on a common bus.

---
Tags: arduino-uno, serial, digital, processing-lang, raspberrypi
---


# Question
Title: Power supply change change gps readings?
I was powering a GPS Sensor from the 3v3 pin of a raspberry pi and my reading for my GPS sensor had some strange symbols in the mix, but when i switched to the 3v3 on the arduino, my reading came back to normal. This wasted several hours of my time.

Any idea why i would get weird readings when using a different power source?? (even though it is the same voltage)

Note: Both the raspberry pi and the arduino are getting their power form the USB that is connected to my PC.

# Answer
The Pi can only supply ~50mA from 3.3V. This is unlikely to be enough to run GPS.

In addition USB can only supply 500mA. This is marginal at best, and below the recommended minimum for Pi.
> 1 votes

---
Tags: arduino-uno, serial, power, softwareserial, raspberrypi
---


# Question
Title: error: invalid conversion from 'char' to 'char*' [-fpermissive]
I have written a simple code to read data from capacitive keypad and display it on LCD.

I am getting the data from keypad in following data structure.

```
char phoneNumber[PHONE_DIGITS];

```

and then displaying the data on LCD as

```
   LcdString(phoneNumber[i]);

```

where my LCD string function is

```
void LcdString(char *characters)
{
  while (*characters)
  {
    LcdCharacter(*characters++);
  }
}

```

There is a type cast error

> error: invalid conversion from 'char' to 'char\*' \[-fpermissive\]

How can I debug it?

# Answer
> 1 votes
You're calling your function with a single char, specified by phoneNumber\[i\], but your function is expecting an array.

If you change your call to:

```
LcdString(phonenumber)

```

then that will pass the entire array.

Are you trying to say that you're storing multiple phone numbers? i.e. a two dimensional array? Check out the String reference for more details: https://www.arduino.cc/en/Reference/String

---
Tags: data-type
---


# Question
Title: My Arduino UNO turns LED ON forever when I connect it to my Laptop
My Arduino UNO Board keeps the LED light turned on forever whenever I connect it to my PC. And, when I try to upload even a sample sketch, it says `avrdude: stk500_recv(): programmer is not responding`.

How can I fix this error?

# Answer
When you connect the device, if you hear the Windows "found device" sound, then you need to check your COM port driver, as it's very likely that the COM port number may have changed. On your Desktop or in File Manager, right click "This PC" or "My Computer", and select "Manage" from the submenu. That will bring up the Computer Management console. On the left, select "Device Manager". That will bring up your list of devices. In the list look for "Ports (COM & LPT)".

If you don't see, "Ports", then click "View" and check "Show hidden devices". If this is the only Arduino that you've ever used, you should only see one listing. Make note of the COM Port Number the driver is using. *It's possible that the port number may have changed since you first used the device. Plug-n-play will do this if you plug the cable into a different USB port that may be using a different USB controller, etc.*

Then in your Arduino IDE, click "Tools", then expand "Boards" and select "Arduino/Genuino UNO" board, then re-click "Tools", and hover over "Port", and select the port number that is assigned to the Port that you found in Device Manager.

If that doesn't work, then you may have a problem with your driver. Some of the "cheap chinese board" use a different FTDI chipset, so the plug-n-play windows driver may not work. In that case, the manufacturer should point you to the correct driver. Download their provided driver, then you can update the driver in Device Manager.
> 1 votes

---
Tags: arduino-uno, atmega328, avrdude, atmega16u2
---


# Question
Title: Bluetooth sending values from two joysticks
Is there any good way of sending values from two joysticks from arduino A to arduino B? I tried sending using if statements, so if the Y- or X-axis' value changed then it would send that, but the servo motor on Arduino B went a little bit crazy.

Here's what I've done so far:

```
//Master Code
void loop()
{
      yVal = analogRead(yAxis);   // read the value of the Right Joystick (value between 0 and 1023)
      yMap = map(yVal, 0, 1023, 0, 255);
      xVal = analogRead(xAxis);     // read the value of the left Joystick (value between 0 and 1023)
      xMap = map(xVal, 0, 1023, 0, 110);

  if(Serial.available() && !(xVal > 505 && xVal < 510)){
      Serial.print('X');
      delay(10);
      Serial.write(xMap);
      }
  if(Serial.available() && !(yVal > 500 && yVal < 520)){
      Serial.print('Y');
      delay(10);
      Serial.write(yMap);

    }
    delay(10);
}

```

And the Slave code:

```
//Slave code
void loop(){
  while(Serial.available())
  {
    c = Serial.read();
    delay(5);
    val = Serial.read();
    if(c == 'X'){
        digitalWrite(13, LOW);
        myServo.write(val);
    }else if(c == 'Y'){
        digitalWrite(13, HIGH);
    }
    }

}

```

Edit: I was thinking that maybe I should do something like a start and stop bit for X and Y?

Edit2: I wrote an if statement in Arduino B because it was reading the value -1, I don't know why, but after the if statement the servo motor hasn't been going crazy and the program works now. I still would like to know if I can do this in a better way. Thanks in advance!

# Answer
# Arduino A

You can read the values from two joysticks as normal and send it like this. This method ensures of no data loss. Ensure that you read the values and store them in appropriate variables and then send it over serial.

```
// Setting Sensor pins
const int potPin = A0;
const int pot1Pin = A1;

// Creating variables
uint8_t pot;
uint8_t pot1;

void setup() {
// Declearing the pinModes' for sensors
  pinMode(potPin, INPUT);
  pinMode(pot1Pin, INPUT);
// Begining Serial Communication
  Serial.begin(9600);

}

void loop() {
// reading from the sensors
  pot = map(analogRead(potPin),0 ,1023, 0, 255);
  pot1 = map(analogRead(pot1Pin),0 ,1023, 0, 255);

//Packing the Serial message
  Serial.print("U*"); //A header
  Serial.print("A");  //a token to indicate the message payload
  Serial.print(pot);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("B");  //a token to indicate the message payload
  Serial.print(pot1);
  Serial.println("");

}

```

# Arduino B

After the data are packed and sent over the serial. You need to unpack it with the other Arduino/device

The code will look like this:

```
String data; //Store each line of Serial communication
String pot1String = "0", pot2String = "0";
float pot1, pot2;
void setup()
{
  //initialize Serial communication
  Serial.begin(9600);
  //read first package
  if (Serial.available() > 0)
  {
    data = Serial.readStringUntil('\n');
  }
  //Disregard the first reading
  data = "0";
}

void loop() {
  //start reading from serial
  if (Serial.available() > 0)
  {
    data = Serial.readStringUntil('\n');
  }
  String payload = "";
  if (data != "0")
  {
    int offset = data.indexOf("U*"); //This is the header (0x552A)
    if (offset >= 0)
    {
      payload = data.substring(offset + 3, data.indexOf('\n'));
      char value = data.charAt (offset + 2);
      switch (value)
      {
        case 'A':
          pot1String = payload;
          break;
        case 'B':
          pot2String = payload;
          break;
      //Add more case as the project grow
      }
    }
  }
  //convert strings to float
  pot1 = pot1String.toFloat();
  pot2 = pot2String.toFloat();

// Continue with the rest of your project

}

```
* Make sure to use the same baud rate in both sketches

Hope this helped. Ask me if you have farther questions
> 1 votes

# Answer
When using the ADC to control servos I get much better results when I process the ADC values through an exponential smoothing function:

There is less jitter. However there is more lag. You can tune the function by changing alpha between 1 (no history, effectively no smoothing at all) to 0 (no new data is averaged in, effectively not changing). Pick 0.5 to start with. If there is too much jitter pick smaller numbers until the jitter is reduced and the lag is still tolerable.
> 0 votes

---
Tags: arduino-uno, bluetooth
---


# Question
Title: How do you extend the wires from the arduino board to both fsr sensors to be placed on both chairs (one for each)
I’m trying to figure out how to extend the wires for both force sensitive resistors so that it could be place on each chair, one sensor on one chair and the other sensor on the other chair

This is how this was originally connected

So what would be the best way to extend both cables to place both sensors on each chair

# Answer
In ADC sampling there will always be noise. Longer cables may increase that noise. Sensors with lower resistance tend have less noise. For these reasons it would be better to start from a schematic, part numbers and / or specifications rather than a picture.

There are a number of ways to reduce noise. Hardware solutions include twisted pair and shielded cables. Software solutions include averaging multiple samples and removing outliers.

If all you are asking is if you can use longer cables, the answer is yes as long as you can tolerate the or compensate for additional noise if any.
> 1 votes

# Answer
In order to extend the wires you will need:

and if you want to do a better job than bread board then you can use a Strip board to solder your resistors on and some headers to connect your wires.

You should not get any noise in ideal situation.

I don't know where you from so I just posted the links to the store I usually buy from. you can find these items on ebay or similar. Plus you will need a crimping tool as well.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: What is the proper way to send data through http using sim908?
**Preamble**:

I have a `sim908` shield and I'm trying to send some data periodically to a server using `AT commands`. For every command, I wait for the response to check if everything is working. Actually the sketch works but, often, I noticed errors during http request.

**State of the art**:

Here it is the sequence of AT commands (not the entire code) into the loop:

1) Check the Network Registration and, if necessary, wait

```
AT+CREG?

```

2) Set params for GPRS connection (no user or password required)

```
AT+SAPBR=3,1,"Contype","GPRS"
AT+SAPBR=3,1,"APN","web.omnitel.it"

```

3) Get current bearer

```
AT+SAPBR=2,1

```

4) If bearer == 0,0,0,0 (not assigned) get a new bearer

```
AT+SAPBR=1,1

```

5) Init HTTP

```
AT+HTTPINIT

```

6) Set CID and URL

```
AT+HTTPPARA="CID",1
AT+HTTPPARA="URL","www.someurl.com/service.php?p1=1&p2=2"

```

7) Execute the HTTP command (POST)

```
AT+HTTPACTION=1

```

8) Close HTTP connection

```
AT+HTTPTERM

```

**Question**:

Why HTTP init (step 5) or HTTP posting (step 7) often fails? What is wrong in this procedure? I'm missing something? There is a way to make the procedure more stable?

Thank you in advance :)

**Important update**:

If occurs an error during sending data via HTTP, is a great idea to renew the bearer (step 4)

**Answers to the comments**:

**a)** Shield has an antenna and it works. If I try to disconnect the antenna, code still search the network (step 1) untill I reconnect the antenna.

**b)** Some times I have this error initializing HTTP (step 5):

> AT+HTTPINIT
>
> +CME ERROR: 3

Some times I have only "OK" as response posting data (step 7) instead of:

> +HTTPACTION:1,200,xxx

Or this response:

> +HTTPACTION:1,600,0

**c)** I have error at step 4 (AT+SAPBR=1,1) only if I execute the command when I have yet a bearer. The error in this case is:

> AT+SAPBR=1,1
>
> +CME ERROR: 3

For this reason I do a check (step 3)

# Answer
> 4 votes
You mention two different error messages.

**1. AT+HTTPINIT fail**

You get +CME ERROR 3. Which means "operation not allowed".

This can be due to an improperly closed HTTP setup. If you get this error (or just always do before setting up), call `AT+HTTPTERM` to be sure that it's closed.

**2. AT+HTTPACTION=1**

I notice you're trying to do a `POST`message, while your variables are in the URL (which is `GET` style afaik).

I've found a source that states you need to call `AT+HTTPDATA` with apropriate values.

> Tell the module that you will be sending 192 bytes of data and it can timeout after 10 seconds of inactivity.

After that, the device will say `DOWNLOAD`, and you can send the `POST` body.

> After this command you get the DOWNLOAD URC then you can type in 192 bytes of data within 10 seconds. The typed data is filled in a local buffer of the module and is not yet posted to the server. In the post body is the multi part form data which contains the necessary headers and data to post a file with name data.txt with 10 bytes of data. `AT+HTTPDATA=192,10000`

And after that you can send the `POST` message.

> Execute the HTTP POST command so that the buffer contents are POST to the server `AT+HTTPACTION=1 OK`

You will get a return message that states the HTTP code (200 'OK') and the amount of bytes received in the return message.

> `+HTTPACTION:1,200,141` This URC means that the data was successfully posted to the server and received 141 bytes of data. which is the server response to your HTTP POST

You can use `AT+HTTPREAD` to receive these bytes.

> The below command tells the module that we want to read the received data AT+HTTPREAD The below is the data received from the server +HTTPREAD:141 Successfully dumped 0 post variables. View it at http://www.posttestserver.com/data/2015/10/07/07.41.291690063480 Post body was 0 chars long. OK

(Scroll a fair bit down in the source, the first part is on `HTTP GET`: http://www.raviyp.com/embedded/194-sim900-gprs-http-at-commands)

You could also omit this by using `HTTP GET` since it's somewhat easier.

If all else fails, you can set up a `TCP IP` connection with the GSM module and manually set up the HTTP GET/POST message.

---
Tags: http
---


# Question
Title: How do I pass an Int Array into void for a foreach loop?
I know its probably an odd question...but I found a workaround for a foreach loop in C. I have a whole bunch of int arrays that I would like to be able to pass into a void, which has that foreach loop in it. This is my code right now:

```
int example[] = {1, 2, 3, 4, 5};

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

    #define foreach(item, array) \
        for(int keep = 1, \
            count = 0,\
            size = sizeof (array) / sizeof *(array); \
            keep && count != size; \
            keep = !keep, count++) \
        for(item = (array) + count; keep; keep = !keep)
    }
}

void Words (int w[]) {
    foreach(int *v, w) {
        Serial.println(*v);
        delay(500);
    }
}

void loop () {
    Words (example);
}

```

However when I run it, it only returns the first number of the array, I need all 5 of them. I know theres all sorts of additional things that could be it, like the * or & symbol but I really don't understand what they do. Any ideas as to how to get that to work?

# Answer
What you want will not work the way you think: in C++ (just like in C), arrays and pointers are almost the same, and the compiler won't be able to make a distinction between

```
void f(int* array)

```

and

```
void f(int array[])

```

In particular, inside `f()` the compiler won't be able to know the actual size of `array`: for the compiler `sizeof array` will always be the same as `sizeof(int*)`, i.e. just the size of a pointer, always 2 bytes on Arduino UNO, whatever type it points to.

If you want your `foreach` macro to work correctly, you have to pass it the actual array count of items as an additional argument:

```
#define foreach(item, array, size) \
    for(int keep = 1, \
        count = 0;\
        keep && count != size; \
        keep = !keep, count++) \
    for(item = (array) + count; keep; keep = !keep)

```

And also pass the count of items in `Words`:

```
void Words(int w[], size_t size) {
    foreach(int *v, w, size) {
        Serial.println(*v);
        delay(500);
    }
}

```

In `loop()` you can use `sizeof example`, because the compiler knows what its size is, from its initialization (an array of 5 integers, i.e. 10 bytes):

```
void loop() {
    Words(example, sizeof example / sizeof example[0]);
}

```

You could even define a macro to compute the count of items in an array:

```
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))

```

It will work **as long as you use it with an argument that is completely known by the compiler**:

```
void loop() {
    Words(example, ARRAY_SIZE(example));
}

```

# Important comments on your original code

You mentioned that you want to "*save space*", but defining a macro will not help in this regard, as a macro is **NOT** a function, hence **its *binary code* will be repeated everywhere it is used**. It can just help make your *source code* shorter and possibly clearer.

The way you defined your macro seems weird and overly complex to me: why use 2 `for` loops when you need only one? It would have been possible to define it in a simpler way, for example:

```
#define foreach(type, var, array, size) \
    for(type* var = array; var != array + size; var++)

```

It would be used as follows:

```
void Words(int w[], size_t size) {
    foreach(int, v, w, size) {
        Serial.println(*v);
        delay(500);
    }
}

```

Using C++ templates may probably help too, but this is an advanced topic. I'd recommend reading first some good book about C++ before digging into templates.
> 1 votes

# Answer
Adding to the reasons why it's a bad idea to define that macro:

* If you want to keep your code readable, inventing syntactic sugar and implementing it with macros is the wrong way of going about it. If the language designers did not do provide a construct, there is probably a reason. This is particularly true if you are not a complete master of the language.
* Premature optimization is *always* a bad idea. First, modern compilers are very good about optimizing stuff. Second, unless you have measured the performance of your code in great detail and deemed the performance unacceptable, you are wasting effort and making the code harder to maintain. Third, what you *think* may be an optimization may result in worse code in a future version of the compiler, or in a different hardware architecture. The list goes on.
* Never use preprocessor macros unless there is no other way of doing what you want to do (there usually is). There are countless articles detailing why you should not, but here is a short summary: macros pollute the global namespace, are hard to test and thus hard to debug, have no type checking, introduce subtle (and not-so-subtle) bugs, obscure calling semantics, and generally make the code unreadable. That we are having this discussion here is proof enough :)
* In this particular example, you are relying on the fact that the array `example[]` is *defined* (meaning: declared and storage is allocated, and in this case initialized, for it) in the same translation unit as your macro. Had this not been the case, `sizeof` would not have worked
* If you want to inline code, use inline functions. If you want to define constants, use `const`. And so on.

In your case, you are far better off declaring your arrays as `vector<int>` and using either iterators or the *range for* in combination with *auto* type declarations:

```
#include <vector>
std::vector<std::vector<int>> example = {
  {3, 1, 4, 1, 6},
  {2, 7, 1, 8, 2, 8, 1, 8},
  {5, 7, 7, 2}};

...

  for (auto v: example) {
    for (auto i: v) {
      // do something with i
    }
  }

```

Isn't this a lot more readable than your foreach macro?

Needless to say, you need to make sure that your tool chain supports C++11; the 1.6.7 version of the Arduino IDE running on Linux definitely does.

Obviously, there are occasional reasons to break the rules I mentioned above, but until you know *exactly* what you are doing, it's better not to.
> 0 votes

---
Tags: arduino-uno, programming, c, array
---


# Question
Title: SPISettings was not declared in this scope
I'm trying to compile a simple I2C example to read data from an MPU-6050 accel/gyro sensor, but I'm getting the compilation error:

```
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:27:8: error: 'SPISettings' does not name a type
 static SPISettings settings;
        ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'void Sd2Card::chipSelectHigh()':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:167:9: error: 'class SPIClass' has no member named 'endTransaction'
     SPI.endTransaction();
         ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'void Sd2Card::chipSelectLow()':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:176:9: error: 'class SPIClass' has no member named 'beginTransaction'
     SPI.beginTransaction(settings);
         ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:176:26: error: 'settings' was not declared in this scope
     SPI.beginTransaction(settings);
                          ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'uint8_t Sd2Card::init(uint8_t, uint8_t)':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:269:3: error: 'settings' was not declared in this scope
   settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
   ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:269:53: error: 'SPISettings' was not declared in this scope
   settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
                                                     ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:275:7: error: 'class SPIClass' has no member named 'beginTransaction'
   SPI.beginTransaction(settings);
       ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:279:7: error: 'class SPIClass' has no member named 'endTransaction'
   SPI.endTransaction();
       ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'uint8_t Sd2Card::setSckRate(uint8_t)':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:518:14: error: 'settings' was not declared in this scope
     case 0:  settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break;
              ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:518:66: error: 'SPISettings' was not declared in this scope
     case 0:  settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break;
                                                                  ^
make: *** [.build_ano/uno/SD/src/utility/Sd2Card.o] Error 1
Make failed with code 2

```

I've commented-out all code until it compiled without error, and I found that the error is caused by the line:

```
#include <Wire.h>

```

So my minimal code to reproduce the error is:

```
#include <Wire.h>

void setup(){
}

void loop(){
}

```

Why is this include throwing this error? Why is it trying to compile code for accessing an SD card when I have no code that uses that?

I'm using Arduino 1.6.1 and targeting the Uno. I found I can fix this error by copying version 1.0 of the Wire library into my local sketch folder.

# Answer
If fixed this by deleting this built-in library

```
/usr/share/arduino/libraries/SD

```

but then I received the error:

```
/usr/share/arduino/libraries/Robot_Control/ArduinoRobot.cpp:25:2: error: 'Serial1' was not declared in this scope
  Serial1.begin(9600);

```

so I deleted these libraries as well:

```
/usr/share/arduino/libraries/Robot_Control
/usr/share/arduino/libraries/Robot_Motor

```

which appear to be buggy in the 1.6 Arduino release. It's still unclear why any of these libraries were being used, since I wasn't including any of their files.
> 1 votes

# Answer
Try a later version of the IDE. Try making a completely new sketch (don't just delete things from your current one). It looks to me like it is trying to compile things it shouldn't.

> /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp

That doesn't seem relevant to your empty sketch.
> -1 votes

---
Tags: arduino-uno, compile, wire-library
---


title: How to request data via I2C?

text:
# Question
Title: How to request data via I2C?
How do you program an Arduino Uno to request data over I2C, sending parameters defining the request?

I'm trying to program Arduino A to read a sensor value from another Arduino B, and it first needs to tell B which sensor to report, but I can't find any easy way to do this with Arduino's Wire library. There doesn't seem to be anything like `Wire.requestFrom(addr, 1235, 2)` which would then call a handler on the slave the looks like `onRequest(sensor_id)`.

I found this page on how to push data one way to a slave, and I found this page on how to request data from a slave without specifying any input, but I can't find anything in between.

Is the solution to use the first method to set the parameters, and then the second to get the data? If so, that seems very circuitous. Is there a more direct method?

# Answer
> 0 votes
Its the way the protocol is designed. From the very first byte that is sent, you already indicate if you want to read or write data. You can't do both. The protocol is a lot more straightforward this way, one transaction at a time. Plus it gives the feel of a data frame, with START and STOP bits delimiting the frame (not regarding repeated STARTs).

But even for a full-duplex protocol like SPI, you've already said that the master must first send certain parameters to the slave. Nothing can be sent by the slave until it has received these parameters and processed them, full-duplex comms or not. Only after this, can it reply with the requested data.

The Wire methods are designed to send data in one direction at a time, as it should be. You could, of course, create a function like the one in your question, but it would inevitably involve the same process of first writing to the slave and then reading.

---
Tags: i2c, wire-library
---


title: Multiplying Arrays

text:
# Question
Title: Multiplying Arrays
I have an issuing multiplying two one dimension arrays together. Each array is an unsigned long that is storing values of factorials. The last row is completely off. My code is below also with a screenshot of the output.

```
void setup() {
//----------------------------- start serial monitor
Serial.begin(9600);

Serial.println("Factorial Table");
//----------------------------- declare variables
unsigned long fact = 1;
unsigned long r[5];
unsigned long c[5];
unsigned long product[6][6];
//----------------------------- load facotirals into array(s)
for (unsigned long d = 1; d <= 5; d++)
{
    fact = fact * d;
    r[d] = fact;
    c[d] = fact;
}
//----------------------------- multiply factorials
//                              and load into new array

for (int row = 1; row <= 5; row++)
{
    for (int col = 1; col <= 5; col++)
    {
        product[row][col] = r[row] * c[col];
    }
}

//----------------------------- print factorials

for (int prow = 1; prow <= 5; prow++)
{
    for (int pcol = 1; pcol <= 5; pcol++)
    {
        Serial.print(product[prow][pcol]);
        Serial.print(" ");
    }

    Serial.println(" ");
}

```

}

# Answer
In C and its progeny, array indices start at 0. `unsigned long r[5]` declares an array of five longs; the array elements are `r[0]` through `r[4]`. Your loop, however, varies the array index from 1 though 5. `r[5]` is accessing whatever happens to lie in memory beyond `r[4]`

Here is a much better version of your code. Note, among other things, the coding style. Remember that you write programs for other *humans* to read!

```
const int kSize = 5;
void setup() {
  unsigned long r[kSize];
  unsigned long product[kSize][kSize];
  unsigned long fact = 1;
  for (int d = 0; d < 5; ++d) {
    fact *= d + 1;
    r[d] = fact;
  }
  for (int row = 0; row < 5; ++row) {
    for (int col = 0; col < 5; ++col) {
      product[row][col] = r[row] * r[col];
    }
  }

  Serial.begin(9600);
  Serial.println("Factorial Table");
  for (int row = 0; row < 5; ++row) {
    for (int col = 0; col < 5; ++col) {
      Serial.print(product[row][col]);
    }
    Serial.println();
  }
}

```

See the difference? Style points to note:

* no unnecessary comments. In fact, the code is readable enough that no comments are necessary.
* No unnecessary space.
* The array size is used in several places; it's better to define it as a constant. There is also no reason to specify anything other than `int`; a good optimizer will detect that you are never using values of more than 5, and will optimize the code accordingly.
* You don't really need two separate arrays, since they have the same values.
* You obviously don't need to first store and then print, but I assume you are doing this to learn.
* I didn't initialize the Serial port and didn't print the header until i was ready to print. Group logically-related statements together. (OTOH, you might have been thinking that at some point you might want to insert print statements before there, so putting Serial.begin first thing in your code might have been better.

While there are lots of styles around, https://google.github.io/styleguide/cppguide.html is good enough for Google, so it's good enough for me :)

Here is a better way to initialize the array of factorials:

```
  r[0] = 1;
  for (int d = 1; d < kSize; ++d) {
    r[d] = r[d - 1] * (d + 1);
  }

```
> 4 votes

---
Tags: arduino-uno
---


title: TFT screen to change sketches

text:
# Question
Title: TFT screen to change sketches
I have an Uno + WiFi 101 thermometer and I'd like to be able to take it places and easily change WiFi network SSIDs and passwords. Can I use a TFT screen to make these changes to a sktech or am I stuck using a PC and IDE for this kind of thing?

Can someone provide a sample sketch of what this might look like? I want to know it's something that's possible before I spend the money on a TFT.

It's possible (let's face it, LIKELY) that I fundamentally misunderstand the capabilities and limitations of the TFT screen. Sorry for the noobish question.

# Answer
> 1 votes
A TFT screen is just a screen. You can't modify SSIDs and passwords with it, any more than you can by poking your PC monitor (unless perhaps you have a touch-screen\*). To modify things you would need:

* An input device (eg. a keypad)
* A method of displaying what you are entering (this is where the screen would be handy)
* A method of storing the new information. You could store things like passwords in EEPROM.
* Code to make all that work.

* Some distributors sell touch-screen interfaces designed to go on top of screens - this might conceivably be what you are thinking of. However you still need the touch-screen, and code to make the touch-screen, **and** the TFT screen, work.

---
Tags: arduino-uno, wifi, tft
---


title: Burn new bootloader without crystal

text:
# Question
Title: Burn new bootloader without crystal
I am considering purchasing these ATmega328 s from 3 pack ATmega328P.

The company says they come with the Arduino UNO bootloader. I do NOT have any 16 MHz crystals, and I would like to make the chips run on the 8 MHz internal crystal.

I have an Arduino Duemilanove.

Is it possible to burn the minimal setup bootloader from here onto the bootloaded chips without using a crystal?

# Answer
> 1 votes
I've done just that on a Arduino Pro Mini of mine.

You need to change the fuses to have the chip use the Internal Oscillator, instead of a crystal. After that you just program the 8-MHz version of the bootloader. Like the one used in the `Arduino Pro Mini 3.3V`.

The only problem is that **you need to connect a crystal, to change the fuses to not use the crystal**. Though it doesn't need to be 16Mhz. Anything between 1 and 16MHz will do.

But since you need to change both the fuses and the bootloader, there is no advantage to buy chips with the bootloader preinstalled.

I'd just buy some bare chips without the bootloader.

PS $4.66 is on the high side for an ATMega328P-PU.

---
Tags: bootloader
---


# Question
Title: How to connect an LED to Arduino LilyPad Mp3
can anyone help me with connecting LED to Arduino LilyPad Mp3 in a way, that each switch (1 of 5) light up a different LED?

I tried connecting an LED between the switch and the board, then the LED light up, but the speaker does not play the audio file.

I also tried connecting an LED directly to the speaker, then LED lights up and the speaker plays the sound file, but the problem is that all of the LED´s light up at the same time....

# Answer
> 0 votes
You might try connecting the anode side of your LEDs through a current limiting resistor to the positive side of the supply. Then connecting the cathode side of the LED to the switched pin on the Arduino LilyPad Mp3. So, in this diagram:

...that would be the pads where the switches are connected.

The current limiting resistor depends on the specifications of the LED. Check the voltage and current required to light the LED. Subtract the voltage needed from your supply voltage. Then use the V=IR equation and solve for R. That is, V = the voltage difference between your supply and what is needed by the LED and I is the current (probably in milliamps, so watch your math!) that the LED needs to light up properly. You will probably need small current limiting resistors somewhere around between 100 and 800 ohms.

Added later...

Thanks to @Gerben we have a diagram of what I was describing:

In Gerben's diagram he has used the regulated 3 volt output of the Arduino LilyPad Mp3. We can double check all the pin labels using a diagram from Sparkfun:

You should be able to repeat this circuit for each switch. Sparkfun has an LED tutorial here. But I'm not very happy with their guess approach when picking out a current limiting resistor. Ah, this tutorial is much more to the point.

So, if we assume the LEDs you are using need 3mA @ 3V (remember to use values for YOUR LEDs!) and use this equation (Vs = supply voltage and Vf = LED voltage):

...then we set it up like (3 - 3) / (0.03) which is zero. That's because I was using LEDs that work at 3 volts. But if I used LEDs that worked at 3mA at 1.8V then I need... (3 - 1.8) / (0.03) = 40 ohm resistors. Or there about. As most resistor values are on a log scale I suspect there should be a 47 ohm available.

---
Tags: led, switch
---


# Question
Title: Arduino nano to esp8266 level shifting needed?
I want to connect an Esp8266 Wifi module to an Arduino nano. I am wondering if I need to implement level-shifting for the Arduino TX line to Esp RX line?

I find different schema's on the net. Some with, some without level-shifting:

With: http://community.blynk.cc/t/robot-with-esp8266-shield-and-arduino-nano/3316/8

Without: Arduino Nano v3.0 with ESP8266

Some use a capacitor between GND and Esp CH\_PD pin, others use a 10K resister between the 3.3V and the CH\_PD pin (https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/)...

What is the most basic but required setup for a Arduino Nano and a Esp8266? (I have Esp8266-12e modules)

Thanks!

# Answer
> 1 votes
The **arduino nano v3**'s logic is 5v, and the ESP8266's logic is 3.3V, so you need to do level shifting between both. Using a voltage divider drains more current (guess not an issue in this case) and it's ok only when going from 5V to 3.3V (when the signal must be shifted from 3.3V to 5V in the links you provide, it looks like it's based on that 3.3V is still considered "HIGH" on a TTL signal).

I personally prefer using a level shifter, it just complicates a bit the Bill Of Materials, but you won't have to debug the level shifting part.

And better than that, using an arduino mini pro @3.3v working directly at 3.3V gets rid of this hassle.

# Answer
> 1 votes
You could use a simple diode, between the Arduino TX and ESP RX. That's what the Adafruit Huzzah uses.

It takes advantage of the internal pull-up on the RX pin of the ESP. The diode will allow a LOW, to pull the signal low, through the diode. But it will block a HIGH 5 Volt signal from going into the ESP.

---
Tags: arduino-nano, esp8266, voltage-level
---


title: How to connect relay

text:
# Question
Title: How to connect relay
How to I connect the pins of one channel relay to control and led which is connected to pin 13 of an arduino uno.can you tell me the steps which pin will go to which pin

# Answer
> 1 votes
Wiring Diagram to Pin 13 for a single relay? This might help.

# Answer
> 1 votes
I believe that the Arduino ground should be common with the 12v source ground. I may be wrong, though that's the way it works for me. Also be aware that some of these relay cards work when the pin is LOW, others when the pin is HIGH. Mine energises when the pin is HIGH, though all tutorials I had read until the last had the relay switching on with a LOW pin.

# Answer
> 0 votes
It looks like http://www.elesof.com/electronics/product/one\_6v\_spdt\_relay\_board , http://shop.ciseco.co.uk/jqc-3f-t73-5v-pcb-relay/ and it probably works like http://www.electronics-tutorials.ws/blog/relay-switch-circuit.html

I'd bet that the I/P line connects to the center pin on the transistor through one of those resistors. If so, I'd put a 5V 100mA source on the GND +5 pins on the side, then I'd use a jumper from the +5 on the end to the I/P on the end, and see if it triggers the relay as expected.

If so, I'd siconnect the jumper and I'd connect the end terminal's GND to the arduino GND, and (maybe?) pin 13 to the I/P line and expect the Blink tutorial that blinks the Arduino's LED to click the relay in time.

If you are asking which are the outputs and which are the inputs of the relay board, I can't tell from the pictures. Look at the bottom of the board and compare it to the datasheet of the relay: http://langir.com/pdf/pcb-relay-T73.pdf --

I'd bet that screw terminals are the outputs, connecting to the right hand pair of outputs, and the center of the left hand three inputs. And that the control terminals are the pin connectors, with the I/P conneting through the transistor to one end of the coil, with the other end of the coil going to the +5V/12V pin connector. There are likely two sets of pin connectors to provide for a separate coil/relay supply on the GND,5V12V connector versus a signal or signal plus power on the GND,I/P,5V/12V pin connector. I'd bet the same-named pin connectors are electrically identical. i.e. GND=GND and 5V/12V=5V/12V.

If you are controlling other than low voltage devices with this, I suggest you make certain you are safe before applying potentially dangerous currents.

---
Tags: relay
---


title: How to sleep a whole circuit?

text:
# Question
Title: How to sleep a whole circuit?
I have just completed my first project, a clone of the Simon game of the eighties. The main parts of the circuit are an ATMega328, a 1602 2x16 LCD, and a small joystick. It is powered directly from 3x1.5V batteries with solder bridges connecting all power pins on each part directly to the batteries. Therefore, if I sleep the ATMega, it won't change a thing comsumption-wise, as the LCD will still be powered.

What are (my first project, I am very unknowledgeable) the possible strategies to sleep the whole circuit?

I thought of using an ATMega pin as a positive lead for the joystick and LCD. Is that feasible?

Another strategy would be to interface some component (a relay?) between the battery and LCD, and command that component from an ATMega pin. Does someone know the right part for the job (I have a 220V relay in my parts, but it seems overkill)?

Lastly, even though it seems unlikely, is there a possible strategy without using any ATMega pins, as I currently use every single one (4 buttons, 4 leds, joystick x, y, and button, 1 buzzer, and 6 pins for the LCD, for a total of 18) except Rx and Tx?

# Answer
The first and most smart solution is to use a switch between the batteries and everything else. This way, you slide the switch in the off position and the whole circuit is completely detached from the batteries: power consumption: 0.

If you can't (because, for instance, you want it to automatically power off after a while) you can use a transistor (PMOS, for instance) instead of the switch. you have then to put a complementary transistor (NMOS) on its gate, then a button in parallel to it. Just another passve component is required: a resistor (value e.g. can be 100k). When you press the button, the circuits becomes momentarily powered on. You will have to pull the nmos gate to a logic 1 with the atmega to keep the circuit powered. When you want to turn everything off, pull the pin to a logic 0 and your circuit will immediately shut down.

If, third solution, you want to give the atmega complete control over the powering, it needs to be always on. You can then omit the complementary transistor and use a reverse logic on the pin (so 0 = on, 1 = off) and then you can do whatever you want with the power (turn on and off whenever you want). **edit**: as a comment suggests, it can be better to put a resistor to set the appropriate voltage on the gate at power up. Even if the commenter told to put a pull-down, I suggest you to put a pull-up (pull-down = normally on, pull-up = normally off). **edit 2** as Paul suggested, there could be cases in which you need to be able to turn on and off automatically the circuit, and then store it for longer times without consuming battery. In this case it could be a good idea to put something (a mechanical switch, a jumper, a detachable wire) to completely detach the battery even from the arduino (even if, in this case, you can just remove the batteries from the housing).

Here is a small paint-made sketch to show the solutions. If you have any questions just ask ;)

EDIT: If you want to let the atmega control the power, you'll have to give him a way to do so. Which means.. You should use a pin. If you want you can use safely the RX and TX pins, as long as you don't enable the serial interface. If you need more pins, you can try to optimize your pins usage (for instance using a 4:1 multiplexer for the buttons you will have 2 control pins and 1 input, for a total of 3 pins, instead of 4), even if I think that the best solution is to use a port expander. for instance in the past I used the MCP23017, which has a I2C interface, or the MCP23S17, with a SPI interface. You will have to use the serial interface you choose (I2C: 2 pins - SCL and SDA, SPI: 4 pins - MISO, MOSI, SCK, SS, but they are the same pins used for programming), and then you will have 16 more pins for your uC

EDIT BY foivaras:

The same result can be achieved utilizing an NMOS instead of a PMOS.This would have an advantage over PMOS solution if power line was \>5v and arduino was powered by a dc to dc converter. On this scenario, PMOS solution would need one more transistor to work. Notice that the NMOS has to be placed on the low side of the power line and it will cutoff the power to joystick and lcd with 0v and enable the power with 5v on its gate.(See 4th image)

COMMENT BY fra87

This solution is not a valid alternative in my opinion. Usually interrupting ground is a bad idea, because usually the rest position of the I/O pins is ground: if you interrupt the ground for the LCD, for instance, you will have +5V on the VCC pin, and a floating ground, but you will have 0V on all the I/O pins, possibly damaging the internal circuits. Moreover having a floating ground is bad in terms of noise protection.

The only advantage COULD be in the particular case explained by the editor, which is a DC/DC converter powering the arduino but not the LCD and the Joystick. This is a strange setup, though, and the proposed solution is better at a first glance (requires one less transistor), but is wrong. For instance, let's suppose the joystick is powered at 12V. If you detach the ground, the joystick will "shut down", which means that all its pins will float up to 12V. This means that on the arduino pin you will see 12V: you can damage it.

So, in the end, I discourage this solution. The only case when you can need it is when you are in a hurry and do not have any feasable PMOS: even in this case, however, I suggest you to replace the NMOS with a PMOS as soon as possible.

Just one more note: edits to the posts, in my opinion, should be done to improve the quality of the answer, by better formatting the content, removing orthographic errors and so on. If someone needs to add some comments or other solutions, it's better to use the comments or add another answer to the thread
> 4 votes

---
Tags: lcd, atmega328, sleep
---


title: Running Arduino IDE in terminal?

text:
# Question
Title: Running Arduino IDE in terminal?
Is there any way to use Arduino in the terminal? I have a USB 802.15.4 board that works with Arduino, but I don't want to use the IDE with it, I want to use the terminal.

# Answer
1.) You can configure the arduino ide to use an "external editor". This means the arduino ide runs als usual but reloads the opened file for compiling and uploading. This is when you want to keep the original arduino ide.

2.) You can use the ino projekt which gives you a cli interface to manage your arduino projects. The quickstart guide gives a good overview of the project.

```
ino init -t blink
ino build
ino upload
ino serial

```

You can of course make all needed modifcations for differend boards and communication. I think the second option is what you are looking for ;)
> 1 votes

# Answer
The most popular method these days is to use arduino-builder.

This seems to be the official Arduino command line interface now, and can do most things the IDE can do short of actually editing your code for you.

It is a set of GO scripts, so you will need GO installed.
> 0 votes

---
Tags: terminal
---


title: FHT doesn't work with the example code

text:
# Question
Title: FHT doesn't work with the example code
I'm trying to use the FHT librairy from (http://wiki.openmusiclabs.com/wiki/ArduinoFHT). I used the example code provided on the link, which is the following :

```
#include <FHT.h> // include the library

#define LIN_OUT8  1
#define FFT_N     64

void setup()
{
  /*Turn off timer0 for lower jitter -
    delay() and millis() killed*/
  TIMSK0 = 0;
  /*set the adc to free running mode*/
  ADCSRA = 0xe5;
  /*use adc0*/
  ADMUX = 0x40;
  /*turn off the digital input for adc0*/
  DIDR0 = 0x01;

  Serial.begin(115200);

}

void loop()
{
  while(1)
  { // reduces jitter
    cli();  // UDRE interrupt slows this way down on arduino1.0
    for (int i = 0 ; i < FHT_N ; i++)
    { // save 256 samples
      while(!(ADCSRA & 0x10)); // wait for adc to be ready
      ADCSRA = 0xf5; // restart adc
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int k = (j << 8) | m; // form into an int
      k -= 0x0200; // form into a signed int
      k <<= 6; // form into a 16b signed int
      fht_input[i] = k; // put real data into even bins
    }
    fht_window(); // window the data for better frequency response
    fht_reorder(); // reorder the data before doing the fft
    fht_run(); // process the data in the fft
    fht_mag_lin8(); // take the output of the fft
    sei();
    Serial.write(255);
    fht_lin_ou8[0];
    Serial.write(fht_lin_out8, FHT_N/2);
  }
}

```

But I get the following error: `fht_lin_ou8' was not declared in this scope`

I canot resolve this probleme, ans help would be appreciate

# Answer
May be you should try to replace :

> fht\_lin\_ou8\[0\];

with :

fht\_lin\_out8\[0\];
> 1 votes

---
Tags: audio
---


# Question
Title: reading pwm signal doesn't work correctly
my goal is to read a pwm signal from a rc receiver. For that i tried to use an arduino.

i ran this code on the arduino:

```
#define Pin 3

int pwm_value;

void setup() {
  pinMode(Pin, INPUT);
  Serial.begin(9700);
}

void loop() {
  pwm_value = pulseIn(Pin, HIGH);
  Serial.println(pwm_value);
}

```

Now i connected the 3rd pin with the output of the receiver. But instead of printing the correct pwm values they get printed completely crazy. Sometimes they are under 10 and sometimes they are over 10000. The receiver outputs the correct signal.

I also noticed that if i just touch the pin with my finger or if i only connect a single jumper cable without anything at the end, the arduino will read a pwm signal.

I have realy no idea to solve that. Can you please help me?

Thank you!

# Answer
> 1 votes
check if the problem is the fact you have set `9700` baud rate on your sketch while the commonly used `9600` is supported from arduino IDE.

---

I slightly modified your code and it works for me. Check if this works for you:

```
#define Pin 3
#define Source 5
unsigned long  pwm_value;

void setup() {
    pinMode(Source,OUTPUT);
    pinMode(Pin, INPUT);
    Serial.begin(9600);
    analogWrite(Source,500);
}

void loop() {
    pwm_value = pulseIn(Pin, HIGH);
    Serial.println(pwm_value);

}

```

when you connect pin3 with pin 5 you should get a consistent value on Serial(=967).

### About getting signal on floating pins

Getting a signal on a floating pin is normal. When you have a cable attached it acts like an antenna. When you touch it, you are the antenna!

---
Tags: pwm
---


# Question
Title: Proper use of * and & when passing objects in methods
Coming from C#, pointers are somewhat foreign although I am grasping the concept. Is it proper to construct methods in the following manner and passing the object (as a parameter) constructed by reference? If not, then please answer how to do this properly.

Initialize the object

```
Adafruit_VS1053_FilePlayer musicPlayer =
    Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

```

Method: (use the * for pointer?)

```
boolean initializeMusicPlayer(Adafruit_VS1053_FilePlayer *mp, uint16_t baudRate) {

    musicPlayerSerialPort.begin(baudRate);
    // initialise the music player
    if (!mp->begin()) { // initialise the music player
        Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
        return false;
        //while (1);
    }
    Serial.println(F("VS1053 found"));

    mp->sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working

    if (!SD.begin(CARDCS)) {
        Serial.println(F("SD failed, or not present"));
        return false;
        //while (1);  // don't do anything more
    }
    Serial.println("SD OK!");
    // Set volume for left, right channels. lower numbers == louder volume!
    mp->setVolume(20, 20);

    if (!mp->useInterrupt(VS1053_FILEPLAYER_PIN_INT)) {
        Serial.println(F("DREQ pin is not an interrupt pin"));
        return false;
    }
    return true;
}

```

Call the method (Use the ampersand to pass the currently created one by reference?)

```
if(initializeMusicPlayer(&musicPlayer, 9600) == true) {
    tempString = tempString + "MusicPlayer initialized!";
    Serial.println(tempString);
    //when adding lcd, print the above to lcd and remove the serial print
}

```

# Answer
> 7 votes
The method you have implemented, *passing by pointer*, is one of the two normal methods, yes. The other is *passing by reference* and is specific to C++, not C.

Under the hood the end result is the same between the two methods, by the syntactic "sugar" is very different and the latter can be preferable for that reason alone.

Your method:

```
void function(whatever *ob) {
    ob->method();
}

function(&myObject);

```

The *pass by reference* method:

```
void function(whatever &ob) {
    ob.method();
}

function(myObject);

```

As you can see the need to convert the object into a pointer with `&` is now gone. That makes it much easier for people lacking in programming skills to use it since it hides the whole pointer mechanism from them.

Also, internally your function now treats `ob` as just another object using `.`, rather than a pointer to an object and needing to use `->`. Note that you can only use the reference operator in a function prototype, not a variable or anything like that - it's purely for passing objects and variables to functions. If you want to then go and store the pointer in a variable you still then have to get the address:

```
void function(whatever &ob) {
    myObjectPointer = &ob;
}

```

As you see it gets confusing with the two different uses of `&`. Basically though: if it's in a function prototype, it's the `pass by reference` operator. If it's anywhere else, it's the `get the address of` operator (or a logical AND of course).

Storing the pointer can be useful if you want to then do other things later on with the same object, especially if you are yourself working with a class. For instance, I often write code similar to the following:

```
class foo {
    private:
        bar *ob; // Pointer to other object of type "bar"
    public:
        foo(bar *inob) : ob(inob) {}
        foo(bar &inob) : ob(&inob) {}

        void something() {
            ob->doSomething();
        }

        void somethingElse() {
            ob->doSomethingElse();
            ob->evenMoreThings();
        }
};

```

You then have a choice of constructors:

```
bar myBar;
foo myFoo(myBar);

// ... later ...
myFoo.something();

```

or

```
bar myBar;
foo myFoo(&myBar);

// ... later ...
myFoo.something();

```

and the user doesn't have to remember which they need to use - whichever they try will work.

---
Tags: arduino-mega, c++
---


# Question
Title: Is it possible to make 4hz readings with the DS18S20 temperature sensor?
My current code that doesn't convince me:

```
#include <OneWire.h>

int DS18S20_Pin = 3; //DS18S20 Signal pin on digital 3
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
//Temperature chip i/o
OneWire ds(DS18S20_Pin);  // on digital pin 3

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

void loop(void) {
  if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        float temperature = getTemp();
        Serial.println(temperature);
    } //just here to slow down the output so it is easier to read

}

float getTemp(){
  //returns the temperature from one DS18S20 in DEG Celsius

  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
      //no more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }

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

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

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

  ds.reset_search();

  byte MSB = data[1];
  byte LSB = data[0];

  float tempRead = ((MSB << 8) | LSB); //using two's compliment
  float TemperatureSum = tempRead / 16;

  return TemperatureSum;

}

```

the outcome of few seconds of recording:

```
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31
22.31

```

EDIT: I inserted the suggestion of @frarugi87 and I inserted the sensor in my pants to test it:

```
22.50
22.50
22.50
23.69
23.69
23.69
23.75
23.75
23.75
23.75
23.75
23.75
23.81
23.81
23.81
23.81
23.81
23.81
23.81
23.81
23.81
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.87
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
23.94
24.00
24.00
24.00
24.06
24.06
24.06
24.19
24.19
24.19
24.25
24.25
24.25
24.31
24.31
24.31
24.44
24.44
24.44
24.50
24.50
24.50
24.56
24.56
24.56
24.56
24.56
24.56
24.62
24.62
24.62
24.69
24.69
24.69
24.75
24.75
24.75
24.81
24.81
24.81
24.87
24.87
24.87
24.87
24.87
24.87
24.94
24.94
24.94
25.00
25.00
25.00
25.00
25.00
25.00
25.06
25.06
25.06
25.12
25.12
25.12
25.12
25.12
25.12
25.19
25.19
25.19
25.25
25.25
25.25
25.25
25.25
25.25
25.31
25.31
25.31
25.37
25.37
25.37
25.44
25.44
25.44
25.44
25.44
25.44
25.50
25.50
25.50
25.50
25.50
25.50
25.56
25.56

```

I still find the change of temperature slow

# Answer
I would expect some variations in temperature, but I would not say that is a problem caused by the 4Hz readings. You can test my assumption by reading every 3 seconds, does the temperature value change or is it still the same?

I see two potential problems:

1. your DS1820 is defect.
2. from your code I assume that you use parasitic power. In that case the chip consumes power from the data wire ( one wire ;-) ) through a pull up resitor (~4.7 kOhms). If you do not provide a special handling, to drive more current while the DS1820 is converting or copying data to EE or from EE memory to the scratchpad, then there will be (most likely) voltage drops. Then the Temperature conversion will not happen and you read the old value from the scratchpad in your read cycle.

You can test point 2 by adding VCC to the DS1820, and do not use parasitic power. If that is your problem, you can fix it with a switching FET Transistor, that provide more current (see DS1820 Datasheet from Maxim) or by using an additional VCC wire.
> 1 votes

# Answer
Not sure if this is the only problem, but when shifting bytes you will lose the msb. This can be solved by casting the variable to an int.

And moreover you don't need the two variables `MSB` and `LSB`.

Try to correct it with this:

```
float tempRead = ((((int)data[1]) << 8) | data[0]); //using two's compliment

```
> 0 votes

# Answer
> Is it possible to make 4hz readings with the DS18S20 temperature sensor?

Yes, but only at 9-10 bits resolution. See Table 2. Thermometer Resolution Configuration. At full resolution, 12 bits, the conversion time is 750 ms. With the commands, reset, etc, this gives just over 1hz.

I guess this also gives you a hint on what to fix in your sketch.

Cheers!
> 0 votes

# Answer
The rate of change of the temperature reading depends on the thermal properties of the sensor package, not on the rate at which you read it. The less expensive, plastic packaged sensors that most of us use will be the slowest to respond to change just because that is the thermal nature of the plastic. Do note that the ground pin of that package has more influence than the package itself, so do your best to ensure the ground pin is exposed to the temperature you're trying to measure, or is at least thermally insulated from the surrounding air, unless the air temperature is what you are trying to measure. If you need faster response to temperature change, you'll need to pay attention to keeping the entire device at or close to the temperature of interest and insulated from surrounding temperatures.
> 0 votes

---
Tags: electronics, temperature-sensor
---


# Question
Title: Voltage divider producing unexpected voltage
I'm trying to run a neopixel strip and an arduino from the same power supply using a voltage divider to get 5V to the strip.

Here are the values for my voltage divider:

R1 = 1500 Ω

R2 = 1000 Ω

Vin = 12 V

resulting in:

Vout = Vin\*(R2/(R1+R2)) = 12\*(1000/(1500+1000)) = 12\*(1000/2500) = 12\*0.4 = 4.8

When the divider is connected at its inputs but not at its outputs, I measure the expected 4.8V across R2. But as soon as I connect the neopixels, I only get about 1.6V.

Could anybody explain this || Suggest a possible solution?

# Answer
> 2 votes
Since you are connecting your pixel strip in parallel with R2, the correct formula is

```
Vout = Vin × (R2∥Rp) / (R1 + (R2∥Rp))

```

Where Rp is the resistance of the pixel strip and

```
R2∥Rp = R2 × Rp / (R2 + Rp)

```

is the combination of R2 and Rp in parallel. From this you can see that an output voltage of 1.6 V is consistent with a strip resistance of 300 Ω.

This is, however, somewhat oversimplified, as the I(V) characteristic of the LED strip is probably non-linear, thus not really equivalent to a resistor.

---
Tags: voltage-level, neopixel
---


# Question
Title: Can I use these cheap GSM module with arduino?
I found two cheap GSM module on ebay but didn't know that I can use them with Arduino or not. Will you help me please?

Here are the link-

http://www.ebay.co.uk/itm/Smallest-SIM800L-GSM-Module-Micro-SIM-Board-Quad-band-Port-Onboard-Antenna-/111789339320?hash=item1a0729f2b8

http://www.ebay.co.uk/itm/SIM900A-Development-Board-Extension-Module-GSM-GPRS-Antenna-TTL-e/281517486292?\_trksid=p2045573.c100033.m2042&\_trkparms=aid%3D111001%26algo%3DREC.SEED%26ao%3D1%26asc%3D20131017132637%26meid%3D70128bc79b60410d862b64d36cc479b3%26pid%3D100033%26rk%3D1%26rkt%3D4%26sd%3D281517486292

# Answer
> 0 votes
Both seem to have the pin header for a serial port. So chances are that they can take standard AT commands. I've seen many modems using additional AT commands for special functions, but they all supported also the basic AT commands.

# Answer
> 1 votes
The SIM900A won't work in the UK, it's dual band.
The SIM800L is cheap as there is no power regulation on board. IIRC it requires 3.4V - 4.5V, min 2 amp supply. Check the data sheet to be sure.

# Answer
> 1 votes
You can actually use the sim900a and 900a mini in the uk but you will have to download firmware and flashing tools that you will find with a web search, not for the beginner though, an 800l is your best bet with a SMA Female JACK Connector to U.FL/IPX Converter Pigtail Cable F1445K so you can attach an sma antenna

cheers Stuart

---
Tags: arduino-uno, gsm
---


# Question
Title: wrong leds lit in matrix display - wrong coding?
I wrote the following code for displaying a bitmap (small size) on a LED matrix (formed using APA102 led strip):

```
//for 24-bit bitmaps

// the header files for the RGB data

 #include <FastLED.h>
 #include "redarray.h"
 #include "greenarray.h"   //g data header file (hex or dec)
 #include "bluearray.h"   //b data header file (hex or dec)*/

//matrix parameters

#define MatrixWidth 36 //columns
#define MatrixHeight 7 //rows
#define numled (MatrixWidth * MatrixHeight)

//pin details

#define datapin 7

#define clockpin 8

CRGB leds[MatrixWidth * MatrixHeight];

const bool  MatrixSerpentineLayout = true;

 void setup() {

     FastLED.addLeds<APA102, datapin, clockpin>(leds,numled);
     FastLED.clear();
  }

void loop() {

  for(uint8_t x=0 ; x<MatrixWidth ; x++)  {

      for(uint8_t y=0; y < 3; y++) {

            leds[XY (x, y)].setRGB(redarray[x][y],greenarray[x][y],bluearray[x] [y]);

           FastLED.show();

           delay(1);
         }
      }
   }

      uint16_t XY( uint8_t x, uint8_t y)
 {
   uint16_t i;

     if( MatrixSerpentineLayout == true) {
       if( y & 0x01) {
        // Odd rows run backwards
          uint8_t reverseX = (MatrixWidth - 1) - x;
          i = (y * MatrixWidth) + reverseX;
     } else {
       // Even rows run forwards
          i = (y * MatrixWidth) + x;
    }
   }

  return i;
}

```

The following is the data in one of the header files - its of same type for the other two colors.

const unsigned char redarray\[36\]\[3\] PROGMEM = { 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, };

The matrix is in a serpentine form (evident from the XY function in code). I am using an Arduino Due. The problem is that the code compiles and runs...but the bitmap is incorrect. Although I am sure, I am somewhat along the correct path because some LEDs do light up as they should as per the bitmap. But most of them are wrongly lit.

Could you somebody plz guide where I am going wrong with the coding? I fear there is some mistake in reading the color data from array and allocating it to leds\[XY(x,y)\].I do not know how a 2D array is read or dealt with by Arduino.

Thanks!

# Answer
Initialize your arrays like this:

```
int a[3][4] = {
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

```

...you can read more about it here.

Added later...

The following explanation came from here:

Arrays that are not explicitly divided into rows:

```
int M[4][5] = {10, 5, -3, 9, 0, 0, 32, 20, 1, 0, 0, 8};

```

...are filled like this:

```
int M[4][5] =
{
  {10,  5, -3, 9, 0},
  { 0, 32, 20, 1, 0},
  { 0,  8,  0, 0, 0},
  { 0,  0,  0, 0, 0}
};

```

As only you understand your data you will have to verify if your data is populating the array as you expect.
> 1 votes

---
Tags: arduino-due, rgb-led
---


title: Switching Many Switches with one Input

text:
# Question
Title: Switching Many Switches with one Input
I have a situation where I need to select between two signals, lets say 1A or 2B and route it to output 3C. I need to do this six times (2A or 2B to output 2C, 3A or 3B to output 3C, etc.).

These all need to switch based on one output from my chip.

What sort of component do I need for this? I think it's something like a 2:1 spdt multiplexer, but something doesn't seem quite right.

I've been looking at a bunch of data sheets and I cannot seem to find a chip which switches many 2:1 switches based on ONE input. Does such a thing exists? Or am I just way of the mark here? Not sure.

Any help appreciated.

Thanks.

# Answer
> 4 votes
Almost, you will need two 74157 (or similar chips) to switch 8 pairs of TTL level logic signals down to 8 individual signal.

---
Tags: multiplexer, switch
---


# Question
Title: How to set float to variable with 7 digits after the decimal point in arduino?
Example:

```
float x = 3154681.124 / 100000; //x = 31.54;

```

I want x to be:

```
x = 31.5468112;

```

# Answer
> 1 votes
The `float` type has slightly over 7 digits of precision. See https://en.wikipedia.org/wiki/Floating\_point.

> I want x to be:
>
> ```
>    x = 31.5468112;
>
> ```

Bad luck. That's 9 digits of precision. You can get around 7 digits by converting it appropriately, eg. as Majenko said:

```
  float x = 3154681.124 / 100000; //x = 31.54;
  Serial.println(x, 7);

```

However that printed:

```
31.5468101

```

It got 7 digits right, as advertised.

---

You can use the BigNumber Library that I wrote. Available from GitHub.

Using that, you can get all the precision you want, within reason:

```
#include "BigNumber.h"

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  BigNumber::begin (7);  // 7 digits after the decimal place

  BigNumber x ("3154681.124");
  BigNumber y = x / BigNumber ("100000");

  Serial.println(y);
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

Output:

```
31.5468112

```

# Answer
> 2 votes
```
float x = 3154681.124 / 100000; //x = 31.54;

```

`x` is now `31.5468112` (or close to).

```
Serial.println(x);

```

Output: `31.54`

Why? Because `Serial.println` defaults to 2 decimal places for floats.

> Syntax
>
> `Serial.println(val)`
>
> `Serial.println(val, format)`
>
> Parameters
>
> `val`: the value to print - any data type
>
> `format`: specifies the number base (for integral data types) **or number of decimal places (for floating point types)**

So the solution: specift 7 decimal places when you print:

```
Serial.println(x, 7);

```

---
Tags: arduino-uno, arduino-ide
---


title: Wifi101 ad-hoc network

text:
# Question
Title: Wifi101 ad-hoc network
I've reviewed the WiFi101 library but have found no way to make the 101 an ad-hoc network. Am I missing something? I'd like to be able to emulate the RedFly example: http://notebook.kulchenko.com/embedded/storing-wifi-configuration-in-eeprom-on-arduino

Can the 101 become an ad-hoc network? I understand the security problem with the ad-hoc capability so it would make sense that Arduino prohibits it.

# Answer
> 1 votes
Apparently you can have an ad-hoc network, you can see the example on the github here: https://github.com/arduino-libraries/WiFi101/blob/master/examples/AP\_SimpleWebServer/AP\_SimpleWebServer.ino

It shows how to create an open ad-hoc network, for a secured one, you might need to check the datasheet + the method implement "beginAP".

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


title: Arduino Nano - Unknown USB device

text:
# Question
Title: Arduino Nano - Unknown USB device
I just bought an Arduino Nano v3.0 (compatible? +- 5$) and I cannot connect it to my computer (Windows 8.1 64bit, Arduino IDE 1.6.8 installed).

The Arduino was bought as a clone but shows GRAVITECH.US on the front. It has a FTDI FT232RL chip (1412-G B8908572) on the back.

When connecting the Arduino the power leds burns the TX and RX led flash a few times (really shortly) and then die. Then the yellow L leds blinks once per second continiously.(power to the Arduino comes from the USB cable, not from external power)

In the system tray I get a message saying

```
"The last USB device you connected to this computer malfunctioned,
and Windows does not recognize it."

```

In the device manager I get a node under Universal Serial Bus Controllers:

```
Unknown USB Device (Device Descriptor Request Failed).

```

When examining the properties of the device, the device-status is:

```
Windows has stopped this device because it has reported problems. (Code 43)
A request for the USB device descriptor failed.

```
* I tried to reset the device
* I tried different USB cables
* I used another Windows 8.1 PC without Arduino IDE installed
* I used an old XP computer

All give same error.

I read about the bricking of clones by the recent FTDI drivers... I downloaded the FT\_Prog tool V3.0.60 to check the PID, but the tool simply does not find the Arduino...

I'm out of ideas... does anyone have some left?

Thanks in advance!

Michiel

# Answer
I found the issue! There is a bug in the Arduino hardware: https://ketturi.kapsi.fi/2014/04/how-to-fix-moody-arduino-nano/

You need to bridge pins 25 and 26 of the FTDI chip (located at the back of the Arduino) to ground the pin 26 TEST signal. If I connect these pins then it works just fine!
> 2 votes

# Answer
I've had this issue before. You can try reuploading the bootloader. If that doesn't work, maybe try re-installing the drivers.
> 0 votes

---
Tags: arduino-nano, usb, windows
---


title: How to put 2 variables in a macro?

text:
# Question
Title: How to put 2 variables in a macro?
In a previous question (Append Text to Variable Names: Please Help Me Shorten This Code) I learned that in order to shorten this code:

```
fanSpeed = readEEPROM(AT24C32_ADDRESS, 1, fanSpeedPos);

```

I could define a macro at the top of the script like this:

```
#define readEE(VAR) VAR = readEEPROM(AT24C32_ADDRESS, 1, VAR ## Pos)

```

And then just use the following shorter code:

```
readEE(foo);

```

Which would be expanded out to:

```
foo = readEEPROM(AT24C32_ADDRESS, 1, fooPos);

```

---

My current question is: **How can I write a macro that accepts 2 arguments instead of just 1?** I couldn't find much information about this concerning Arduinos, so I studied about how to do it in C++ (like from here: http://en.cppreference.com/w/cpp/preprocessor/replace) but it was too complicated for me to understand.

In particular, I would like to learn if it's possible to shorten the following code:

```
void writeToEE(byte location, bool value, bool &var) {
  writeEE(loc, value); var = value;
}

```

(*Sidenote*: the `writeEE` function looks like this: `void writeEE(uint8_t entry, uint8_t data) { writeEEPROM(AT24C32_ADDRESS, 1, entry, data); }`. Since the first 2 arguments are almost always constants, that's why I shortened it with another function).

Since whenever I'm using `writeToEE`, the "entry" variable name is always the "data" variable name with "Pos" appended, I would ideally like to do this (pseudo-code):

```
#define wrEE(VAR, VAL) VAR = writeToEE(VAR ## Pos, VAL, VAR)

```

so that when I write this:

```
wrEE(fanSpeed, 3);

```

it will be expanded out to:

```
writeToEE(fanspeedPos, 3, fanspeed);

```

I just don't know how to pass the 2nd argument ("VAL") into the macro, which is the value being stored in the "fanSpeed" variable, in the "fanSpeedPos" location in the EEPROM. When I try to compile my pseudo code example (was hoping to get lucky!), I get the following error message: "void value not ignored as it ought to be"

# Answer
> 0 votes
In the parameter list of the `#define` for the macro, separate the second argument from the first with only a comma. For example:

```
#define wrEE(speed,var) writeToEE((etc))

```

The "void value not ignored as it ought to be" error message is a consequence of trying to store the `void` result of `writeToEE`. The solution is to not try to store it.

In C, variable, parameter, and constant names are case-sensitive.

---
Tags: c++
---


# Question
Title: What is the output of Software Serial .read() function
Hi I am new to arduino development i was using esp8266 using software serial library

> here is the code

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

SoftwareSerial monitor(2, 3); // RX, TX

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

  sendDebug("AT");
  delay(5000);
  Serial.println("Hello");
  if(monitor.find("OK"))
  {
   Serial.println(monitor.available());
   Serial.println((int)monitor.read());
   Serial.println((int)monitor.read());
    Serial.println(monitor.available());
   Serial.println("RECEIVED: OK");
    //connectWiFi();
  }
  else
  {
    Serial.println("RECEIVED: None");
  }
}

void loop(){

}

void sendDebug(String cmd){
  monitor.println(cmd);
  Serial.println("Command: "+cmd);
}

```

> Output

```
Command: AT
Hello
2
13
10
0
RECEIVED: OK

```

*All I know is `monitor.available()` return the available bytes that can be read and i can also deduce that these two **bytes** are **O** and **K** but the integer value doesn't corresponds to the **ascii** value of **O** and **K***

can anyone explain what is actually getting printed on the serial monitor what is **13** and **10** ? ??

# Answer
> 1 votes
It is just like https://www.arduino.cc/en/Serial/Read :

The `monitor.find("OK");` already consumed the 'O' and the 'K' bytes, (see https://www.arduino.cc/en/Serial/Find ) then there were two bytes .available(), a 13=CarriageReturn and a 10=LineFeed, both returned by successive `monitor.read()`s, then zero more bytes in monitor.available().

---
Tags: serial, arduino-ide, softwareserial, arduino-pro-mini
---


# Question
Title: How do I connect velostat to an arduino?
I have some velostat that I'd like to hook up to an Uno. At the risk of sounding dense...how do I do that?

Ultimately wanting to get readings of pressure from the velostat, just not sure how or what wires to connect where.

# Answer
Usually a variable resistance sensor is used in a voltage divider circuit:

In the above example a thermistor is connected to the positive supply and a pull down R1 is connected to ground. The voltage where they meet is measured using one of the Arduino's analog inputs pins.

Choosing R1 is tricky. If it is too large compared to the variable resistance sensor the voltage fluctuation at Vout will be too small to measure. The same problem exists if R1 is too small compared to the variable resistance sensor. Also, you need to mind the current through the sensor. If the combined resistance of R1 and the sensor is too small the current may damage the sensor, over heat R1 and / or put a heavy drain on your power source.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: connect arduino to battery with 12V motor
I am looking at this(instructable with circuit picture) tutorial for making a self-balancing robot. However, I am confused about how the battery connects to the arduino. I know the 12 V must go to the motors to power them yet the diagram shows wires connecting to the Arduino through some kind of green device. I assume this connects to the power supply . However I do not have this green device and I don't know how to connect to the power supply. How should I get a charger cable and solder on the battery wires to the charger? If so are there any tutorials? Is the connection to the Arduino necessary?

(please look at the Firizing diagram in the instructable) Thanks

# Answer
> I am looking at this(instructable with circuit picture) tutorial for making a self-balancing robot. However, I am confused about how the battery connects to the arduino.

Well, it seems he has attached a 9V battery through a voltage regulator, to the Arduino. Which is bullshit.

You can put the 9V directly into the barrel-jack of the Arduino. You actually should. Putting 5V on the barrel jack is not within the specs. (https://www.arduino.cc/en/main/arduinoBoardUno)

> I know the 12 V must go to the motors to power them yet the diagram shows wires connecting to the Arduino through some kind of green device. I assume this connects to the power supply . However I do not have this green device and I don't know how to connect to the power supply.

Well, the motors only get 9V in this diagram (which might work neverthless). But bear in mind that 9V batteries won't last long.

I'm not sure what you mean by "Green device", the HC-05 or the L293D? Anyway, the L293D are quadruple high-current half-H drivers, which basically is a way to switch 12V on/off/invert based on the 5V inputs (from Arduino). You could do this with some circuitry, but I suggest picking up a "motor driver (arduino)"

> How should I get a charger cable and solder on the battery wires to the charger?

You can't charge regular 9V batteries.

> Is the connection to the Aruino necessary?

The specific connection he shows? No. Power to the Arduino board? Yes.
> 0 votes

---
Tags: motor, battery, voltage-protection
---