# Question
Title: Can Digital/Analogue pins double as power supplies?
I'm doing research into if the Arduino Uno has enough power pin slots to power multiple components, and I'm unsure if it's possible to convert some of the pins from the Digital and Analogue sections to be power/ground. Anyone know\>

# Answer
> 7 votes
Only for very light loads (a few mA).

But why would you want to? The number of power pins doesn't dictate the number of devices you can power. Power pins can have as many things connected to one pin as you like. As long as you stay within the board's total power budget you are fine.

# Answer
> 0 votes
Yes, for most modules that use modest power, it can be handy to treat modules as shields, in cases where pins can align. You just set each pin on the common 4-pin module connector as needed and plug them in. I've done this several times with DHT22 modules, and it's fun "plug and play"ing on such a low-level.

With an UNO, you get a generous 40ma per output, though I would use a real power rail for anything over 100mw or so.

To make a pin act as VCC:

```
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);

```

To make a pin act as ground:

```
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);

```

the other advantage to this is being able to switch the module on/off with `digitalWrite()` (from `HIGH` to `LOW`) to save power or reset flaky sensors.

---
Tags: pins
---


title: How many pins are needed for a sensor?

text:
# Question
Title: How many pins are needed for a sensor?
I'm currently looking to buy an Arduino, but never touched robotics before. Would anyone be able to give me an idea how many pins a sensor such a magnetometer would use? This is for Arduino Uno.

Sorry if this is stupid, just really have no idea how to approach Arduino design without having one here and can't get one for a few weeks at the least.

Thanks!

# Answer
Below image is the answer to your question.

According to this image, magnetometer required four pins of arduino.

GND of magnetometer ----\> Arduino GND

Vcc of magnetometer ----\> Arduino 3.3 Volt

SDA of magnetometer ----\> Arduino Analog Pin 4

SCL of magnetometer ----\> Arduino Analog Pin 5

I hope it will help you.
> 6 votes

# Answer
> Would anyone be able to give me an idea how many pins a sensor such a magnetometer would use?

Here below image provides the connection and pin requirements for magnetometer...

According to image magnetometer will require 4 pins of Arduino 2 pins of supply i.e +3 volt and Ground and other two pins will be any two Analog pins of Arduino.

And to connect other sensors with Arduino, you can find datasheet of desired sensor and can find how many pins that sensor is going to use.
> 3 votes

# Answer
> How many pins are needed for a sensor?

As many pins as are needed for that sensor.

*Every* sensor is different. The datasheet or manual for the sensor or the chip or other device that the sensor is based around will tell you how the interface to it works - what each pin does, how you use it, etc.

It is up to *you* to read that documentation and learn how the sensor works to then be able to plan how best to connect it to your Arduino.

Some sensors require specific connections, such as the two I2C pins in your example sensor. Others may need the SPI pins. Then there are sensors that use analog inputs. That may be one pin for, say, an LDR, or three pins in the case of a 3-axis accelerometer.

In short: RTFM.
> 3 votes

# Answer
One, maybe two. It's impossible to say for sure without a concrete example.

I would recommend looking up the type of sensor(s) you want to use, and read the data sheet(s). Things you'll want to consider are things like operating voltage (3.3v or 5v), current draw (\>40mA?), are any additional passive components required (capacitors, resistors, ...), etc.

Data sheets will describe in great detail, how to use a specific device.
> 2 votes

# Answer
Broadly speaking, look for sensors/outputs that use I2C or SPI interfaces. If you use I2c, you can wire all your sensors with two digital pins. This is especially important with multi-axis sensors that would otherwise chew up 3-6 pins each.

I2C is probably easier because SPI need one extra pin per device, in addition to the 2 base pins. Still, that's about 10 devices on one UNO, IF you spend the extra $1 or $2 on the SPI/I2C sensors/LCDs/etc instead of going for what at first seems like a cheaper part.
> 0 votes

---
Tags: pins
---


# Question
Title: Arduino as Slave to Return Multiple Values
I'm having trouble trying to get my two Arduino Unos to communicate with each other over i2c. I'm trying to have the master request for analog values from the slave by sending a request to the slave device for one of the six ADC pin values.

**Master Code**

```
#include <Wire.h>

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

void loop()
{
  Wire.beginTransmission(0x22); // Start communication with Arduino slave at address 0x22

  for(byte i=0;i<4;i++)
  {
    Wire.write(i);              // Request data from analog pin 'i'
    delay(5);                   // Give the slave a moment to sample ADC and respond
    while(Wire.available())
    {
      byte c = Wire.read();
      Serial.println(c);        // Print returned value to serial window
    }
  }

  Wire.endTransmission();       // End communication with Arduino slave
  delay(500);
}

```

**Slave Code**

```
#include <Wire.h>

void setup() {
  Wire.begin(0x22);
  Wire.onReceive(receivedHandler);
}

void loop() {
}

void receivedHandler() {
  byte data = Wire.read();
  byte analogValue;

  if(data == 0) analogValue = analogRead(A0)>>2;
  else if(data == 1) analogValue = analogRead(A1)>>2;
  else if(data == 2) analogValue = analogRead(A2)>>2;
  else if(data == 3) analogValue = analogRead(A3)>>2;
  else analogValue = 0;

  Wire.write(analogValue);
}

```

I can see that the data is being received by the slave, but the slave is not sending any data back, so I'm a bit confused how to send data back to the master. For the master there is "Wire.requestFrom(address, num of bytes)" to request a specific number of bytes, and for the slave "Wire.onRequest()" which will call a handler function to send back the number of bytes requested by the master, but for my application I won't be able to return more than 1 byte at a time.

# Answer
> 0 votes
Bidirectional communication in I2C is a two stage thing.

First you have to tell the slave which pin (or register) you want to read. Then you have to read it.

A typical master sequence would be:

```
Wire.beginTransmission(0x22);
Wire.write(1);
Wire.endTransmission();
Wire.requestFrom(0x22, 2);
byte b1 = Wire.read();
byte b2 = Wire.read();

```

And of course your slave has to respond to the `write()` and remember which pin is being selected, then separately respond to the `requestFrom()` and return the data corresponding to the pin that was selected earlier.

---
Tags: i2c
---


# Question
Title: DS3231 AT24C32 IIC making digital outputs not work
I have just taken the code from

https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/wiring-and-test

to get DS3231 AT24C32 IIC to work fine with my Aduino and its working fine.

I have then taken
https://learn.adafruit.com/adafruit-arduino-lesson-4-eight-leds and expanded it to work with three 74HC595 Shift Register. And this is working fine with all three sets of LEDS lighting up one after an other like in the demo.

So I do not think there is anything wrong with my wiring.

When I merge the two demos together, all the output pins on my this shirt register just give out positive current constantly.

I have walked through each line of the code and the problem is caused by

```
if (! rtc.begin()) {

```

if I take out that if statement everything works. But since that is the bit that starts the clock I want that.

So how do I get the DS3231 started and not have all the pins on the third shift register high?

Also if it matter it is an official Leonardo board.

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

RTC_DS3231 rtc;

int latchPinOne = 5;
int clockPinOne = 6;
int dataPinOne = 4;

int latchPinTwo = 11;
int clockPinTwo = 10;
int dataPinTwo = 8;

int latchPinThree = 3;
int clockPinThree = 13;
int dataPinThree = 2;

byte leds = 0;

void setup()
{
#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  pinMode(dataPinOne, OUTPUT);
  pinMode(latchPinOne, OUTPUT);
  pinMode(clockPinOne, OUTPUT);

  pinMode(dataPinTwo, OUTPUT);
  pinMode(latchPinTwo, OUTPUT);
  pinMode(clockPinTwo, OUTPUT);

  pinMode(dataPinThree, OUTPUT);
  pinMode(latchPinThree, OUTPUT);
  pinMode(clockPinThree, OUTPUT);

  Serial.begin(9600);
  Serial.println("Start");

  delay(3000); // wait for console opening
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
}

void loop()
{
  leds = 0;
  for (int i = 0; i < 8; i++)
  {
    bitSet(leds, i);
    updateShiftRegister();
    delay(500);
  }
}

void updateShiftRegister()
{

  digitalWrite(latchPinOne, LOW);
  shiftOut(dataPinOne, clockPinOne, LSBFIRST, leds); // send the data
  digitalWrite(latchPinOne, HIGH);

  digitalWrite(latchPinTwo, LOW);
  shiftOut(dataPinTwo, clockPinTwo, LSBFIRST, leds); // send the data
  digitalWrite(latchPinTwo, HIGH);

  digitalWrite(latchPinThree, LOW);
  shiftOut(dataPinThree, clockPinThree, LSBFIRST, leds); // send the data
  digitalWrite(latchPinThree, HIGH);
}

```

# Answer
> 3 votes
This looks like a classical case of pin conflicts when merging several sketches.

In this case it is hidden by the fact that TWI SDA and SCL are separate pins on the Arduino Leonardo. But they are also connected to pins 2 and 3 (not A4 and A5 as on Arduino Uno).

Selecting other pins (latch/data) for the third shift register should help.

Cheers.

---
Tags: shift-register
---


title: Temperature sensor bugs

text:
# Question
Title: Temperature sensor bugs
My project is based on a moving fan using DHT11 sensors. I have used 2 void loops and the IDE is showing an error

> "exit status 1 redefinition of 'void loop()'"

One doubt: Can we use 2 void loops in the code? Please see and identify the errors.

2nd doubt: `dht DHT;` shows error

> "exit status 1 'dht' does not name a type" for my version of Arduino 1.8.1

```
#include <DHT.h>
#include <DHT_U.h>
#include <Adafruit_Sensor.h>

 // Including library for dht
#include<LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
#define dht_dpin 12
dht DHT;
#define pwm 9

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

void loop() {
  // put your main code here, to run repeatedly:
  // put your setup code here, to run once:
  lcd.begin(16, 2);
  lcd.clear();
  lcd.print(" Fan Speed");
  lcd.setCursor(0,1);
  lcd.print(" Controlling");
  delay(2000);
  analogWrite(pwm, 255);
  lcd.clear();
  lcd.print("Circuit Digest ");
  delay(2000);
}

void loop() {
  DHT.read11(dht_dpin);
  int temp=DHT.temperature;
  lcd.setCursor(0,0);
  lcd.print("Temperature:");
  lcd.print(temp);   // Printing temperature on LCD
  lcd.print("oC");
  lcd.setCursor(0,1);
  if(temp <26 ) {
    analogWrite(9,0);
    lcd.print("Fan OFF");
    delay(100);
  } else if(temp==26) {
    analogWrite(pwm, 51);
    lcd.print("Fan Speed: 20%");
    delay(100);
  } else if(temp==27) {
    analogWrite(pwm, 102);
    lcd.print("Fan Speed: 40%");
    delay(100);
  } else if(temp==28) {
    analogWrite(pwm, 153);
    lcd.print("Fan Speed: 60%");
    delay(100);
  } else if(temp==29) {
    analogWrite(pwm, 204);
    lcd.print("Fan Speed: 80%");
    delay(100);
  } else if(temp>29) {
    analogWrite(pwm, 255);
    lcd.print("Fan Speed: 100%");
    delay(100);
  }
  delay(3000);
}
}

```

# Answer
Here, below is updated version of your code.

Before running this code, you have to download DHT library. Just click on `Click Here` and you find good explanation & library of DHT11 Sensor. Becuase this library I usually preferred for my code. So, please download it and then run my code.

Click Here

And two void() loop never used. Put your all logic in one void() loop.

Note: This is not tested code. So if you face any problem then update me.

```
#include <dht.h>                // DHT library
#include<LiquidCrystal.h>       // LCD library

LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

dht DHT;

#define DHT11_PIN 12

#define pwm 9

float temp;

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

  pinMode(pwm, OUTPUT); //Pin as OUTPUT
}

void loop()
{

 int chk = DHT.read11(DHT11_PIN);
 temp = DHT.temperature;
 Serial.print("Temperature = ");
 Serial.print("\t");
 Serial.print(temp);
 delay(1000);

 lcd.begin(16, 2);
 lcd.clear();
 lcd.setCursor(0, 0);
 lcd.print("Fan Speed");
 lcd.setCursor(0, 1);
 lcd.print("Controlling");
 delay(2000);
 lcd.clear();
 lcd.setCursor(0, 0);
 lcd.print("Circuit Digest");
 delay(2000);
 lcd.clear();
 lcd.setCursor(0, 0);
 lcd.print("Temperature:");
 lcd.setCursor(10, 0);
 lcd.print(temp);

 lcd.setCursor(0, 1);

 if(temp < 26 )
 {
    analogWrite(pwm, 0);
    lcd.print("Fan OFF");
    delay(100);
 }
 else if(temp == 26)
 {
    analogWrite(pwm, 51);
    lcd.print("Fan Speed: 20%");
    delay(100);
 }
 else if(temp == 27)
 {
    analogWrite(pwm, 102);
    lcd.print("Fan Speed: 40%");
    delay(100);
 }
 else if(temp == 28)
 {
    analogWrite(pwm, 153);
    lcd.print("Fan Speed: 60%");
    delay(100);
 }
 else if(temp == 29)
 {
    analogWrite(pwm, 204);
    lcd.print("Fan Speed: 80%");
    delay(100);
 }
 else if(temp > 29)
 {
    analogWrite(pwm, 255);
    lcd.print("Fan Speed: 100%");
    delay(100);
  }
}

```
> 1 votes

---
Tags: arduino-uno, arduino-ide, debugging, debug
---


# Question
Title: What is the definition of these arduino commands, and how do they affect the circuit?
I don't know if I am allowed to ask this question because really I could just look this up on google. The reason I'm asking here is because in google when you look up the definitions for the following commands, they treat you like you have good knowledge of arduino boards work. I however want to be treated as a beginner who just started learning arduino boards.

So I want to know the definitions of the following commands in a way that I could learn and teach new beginners without getting them confused.

So I want to know the clear definitions of these following commands:

**analogWrite and also why does it have a limit of 255? what does this 255 mean?**

**analogRead and also why does this have a limit of 1023? what does this mean?**

**digitalWrite and also how does this differ from analogWrite?**

**digitalRead and also how does this differ from analogRead?**

**Loop and setup also what is the void before it?**

**Variables and also how they are declared?**

**Map and also what does it map and how?**

**Serial.write and also how does this differs from analogWrite and digitalWrite?**

**If/else commands and when they should and shouldn't be used?**

Like I said, I do not know whether the question is appropriate, but could be helpful to all the beginners learning Arduino.

# Answer
> 4 votes
These are a lot of different questions. However, you can find most of the Arduino related answers in the official reference: Arduino reference Guide

Some other answers:

* how to declare variables:

e.g.

```
int x;

```

SerialWrite sends data to the serial port/UART, analogWrite and digitalWrite puts a voltage to a pin (simplified).

AnalogWrite is normally used for a value that has a range (like the intensity of a led), digitalWrite for an On/Off state (can also be for a led but just on/off).

if/else commands can be used to make a program make a decision.

e.g.

```
if (a == 10)
{
    Serial.println("10");
}
else
{
    Serial.println("Not 10");
}

```

void means 'nothing' ... in principle it means the functions (setup and loop) do not return any value. You can also define functions which return a value, e.g.

```
int add(int a, int b)
{
    return a + b;
}

```

Read in any C/C++ manual about the commands, get a beginner programmers handbook.

The limit of a pin, means the value cannot be more than 255 or 1023. This means that the range of the value you can get/set is between 0 and 255 or 1023. The map command can be used to make a value within the range required.

---
Tags: arduino-uno, serial, analogread, analogwrite, map
---


# Question
Title: 7805 powered Atmega328 Stops working when input of 7805 exceeds 7volts
I am developing a circuit with atmega328, the MCU is powered by a LM7805. The input of 7805 is given by a variable supply. Till the input of 7805 is 7volts, the output voltage is 4.9volts and current is around .75amps. Now if the input voltage of 7805 is increased, the current also increases and the MCU stops working(sometimes work with being reset after a few seconds), please help me out guys... i need to connect those circuits to my car battery, so it must work with 12volts.

I added capacitors and diodes as per Majenko mentioned. Now the situation is a) The circuit is working at 12V, b) With single C817 , output voltage of mcu is 3.5V, c)I used 56 ohms resistance, which is giving 1.2V to the input of C817, d) The Collector to Emitter resistance of C817 is 1520 ohms when turned on, this is creating a voltage drop of 3volts. e) This output is turning the led on, but being unable to switch the relay.

**Circuit Upate**

This the modified circuit, which solves the problem. But i have some questions, in the modified circuit if BC547 is used then its not working because the collector voltage which should be around 0.2 remains 1.8 volts, but replacing the BC547 with BC337 solves the problem(Collector voltage becomes around 0.3).

# Answer
> 1 votes
It looks like the reason for the MCU drawing high current is operating the LEDs in half a dozen optical isolators without current-limiting resistors. The part number of your isolators apparently is PC817, for which the suggested LED current is 5 to 20 mA at about 1.2 to 1.4 forward volts. But if you don't limit the current, they are likely to draw 50 to 100 mA each when turned on. Add a series resistor, say 220 to 330 Ω, in series with each isolator.

At this point, it's possible you may have damaged your ATmega328 by overheating it, due to drawing too much current from its outputs. You probably should run some tests with simple sketches to see if they all work ok.

Note, it probably would make sense to use a buck regulator rather than a linear regulator in the 12 V environment. MP1584-based buck regulator boards (“Mini DC 4.5~28V to DC 3.3V MP1584 3A Step-down Converter Regulator Module”), about 2x2 cm, are about a dollar on ebay and handle 2 amps typically.

# Answer
> 1 votes
There are a number of basic but vitally important components missing from your schematic. Namely input and output capacitors on the voltage regulators, which would result in oscillation and thus overheating (which would then shut them down through thermal overload), decoupling capacitors on the main chip, reverse biased diodes across the relay coils (maybe as well a small capacitor would be beneficial in parallel), and resistors to limit the current through your opto isolators.

Here is a version of your schematic with the missing components added in red. I have omitted the values - your job is to *read the datasheets* and work out the correct values to use.

---
Tags: arduino-uno, atmega328, voltage-level, current
---


# Question
Title: How to Store the results from a Ping Sensor in a variable
I need your suggestions and help with my Ping Sensor. I have an Arduino Uno with a Parallax Ping sensor and a motor.

My ping sensor is set to to start the motor when the nearest object is \<= 10cm. That works fine. Now, I'd like the motor to start only if the values of the sensor are progressing in a decreasing manner i.e 15, 14, 13, 12, 11, 10 but do nothing if the values are progressing in a increasing manner.

I was thinking if I stored the last 3 pings as variables and using an if/else statement but I don't know how to implement it.

How can I implement this, or if you have any other suggestion, please help me. Thank you

Here is what i have so far:

```
/* Ping))) Sensor

   This sketch reads a PING))) ultrasonic rangefinder and returns the
   distance to the closest object in range. To do this, it sends a pulse
   to the sensor to initiate a reading, then listens for a pulse
   to return.  The length of the returning pulse is proportional to
   the distance of the object from the sensor.

   The circuit:
    * +V connection of the PING))) attached to +5V
    * GND connection of the PING))) attached to ground
    * SIG connection of the PING))) attached to digital pin 7

   http://www.arduino.cc/en/Tutorial/Ping

   created 3 Nov 2008
   by David A. Mellis
   modified 30 Aug 2011
   by Tom Igoe

   This example code is in the public domain.

 */

// this constant won't change.  It's the pin number
// of the sensor's output:
const int pingPin = 7;
const int motorPin = 9;
//Yomis code
//int pings[3] = {-1,-1,-1};
//int i;
//bool Increasing(int p1, int p2, int p3)
//{
//  if(p1 < p2 && p2 < p3){
//    return true;
//  }
//}
//
//bool Decreasing(int p1, int p2, int p3)
//{
//  if(p1 > p2 && p2 > p3){
//    return true;
//  }
//}
//
//end of yomis code
void setup() {
  // Set up the motor pin to be an output:

  pinMode(motorPin, OUTPUT);

  // initialize serial communication:
  Serial.begin(9600);
}

void loop()
{

  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

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

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

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

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(1000);

//        //Yomis code
//        if (cm <= 10)
//        {
//          Serial.println();
//          Serial.println(pings[0]);
//              Serial.println(pings[1]);
//              Serial.println(pings[2]);
//          Serial.println();
//          if(Increasing(pings[0],pings[1],pings[2]))
//          {
//            int Speed1 = 100;  // between 0 (stopped) and 255 (full speed)
//            int Time1 = 3000;  // milliseconds for speed 1
//            analogWrite(motorPin, Speed1);  // turns the motor On
//          }
//        }
//        else
//        {
//          analogWrite(motorPin, LOW);
//        }
//
//        //End of yomis code

  if (cm <= 10) {

    int Speed1 = 150;  // between 0 (stopped) and 255 (full speed)
    int Time1 = 2000;  // milliseconds for speed 1

    int Speed2 = 250;   // between 0 (stopped) and 255 (full speed)
    int Time2 = 3000;  // milliseconds to turn the motor off

    analogWrite(motorPin, Speed1);  // turns the motor On
    delay(Time1);                   // delay for onTime milliseconds
//    analogWrite(motorPin, Speed2);  // turns the motor Off
//    delay(Time2);                   // delay for offTime milliseconds
  }
  else if (cm > 10) {
    analogWrite(motorPin, LOW);  // turn the motor off
  }
  else {
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();

    delay(100);
  }

}

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

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

```

# Answer
The general idea of your code is fine, but it can be tweaked to make it more efficient.

Firstly, your function `increasing(int p1, int p2, int p3)` can be simplified to `increasing(int *pingArray)`. This way you pass a *reference* to the function, rather than three `int`s. If you decide later that your `pings` array needs to hold more values you don't have to change the function arguements. However, if you're going to be experimenting with different lengths of the `ping` array you need to make sure you change the code *within the function* to reflect this. An easy way to stay on top of it is with `#define`:

```
#define MAX_PINGS 3       // Put this at the start of your code somewhere

int pings[MAX_PINGS];     // When you come to declare 'pings'
for (int x=0; x<MAX_PINGS; x++)
    pings[x] = -1;        // Whatever each element is initialised to.

// Your 'increasing' function
//   (... and the same for 'decreasing', if you decide to use it!)
bool increasing(int *pingArray)
{
    // CODE GOES HERE
    // and it doesn't matter how long pingArray / pings is
    // because you have 'MAX_PINGS' defined.
    return true;
}

// You call the 'increasing' function as you'd expect:
if (increasing(pings))
{ /* stuff */ }

```

Now to the concentrating:

Your initial work is good but from what I've read on ultrasonic sensors, and from experience with any generic sensor, is that the readings aren't going to be perfect. The real world is a noisy place and you aren't going to get nice, accurate distance readings. Finding the average is a simple technique, but you will need to find an optimal solution yourself. Once you have your nice row of average values you can then determine if the distance is increasing or decreasing or neither.

Thus you have two steps:

# Average the distance

Create an array (`dist`, for now) and use it to find the average distance your sensor is from an object.

```
#define MAX_DIST 5

int dist[MAX_DIST];    // create an array, no need to initialise.
double distAverage;    // average distance, could be 'int' instead.
int distIterator = 0;  // 'dist' will be a CYCLIC BUFFER. woooOOOOooo.

// As you get the distance from your sensor, update 'dist' and
// then calculate the running average.

dist[distIterator] = microsecondsToCentimeters(duration);
distIterator++;
if (distIterator == MAX_DIST) distIterator = 0;
distAverage = 0.0;
for (int x=0; x<MAX_DIST; x++)
    distAverage += dist[x];
distAverage /= MAX_DIST;

```

I hope you understand the cyclic buffer principle - if you don't you can google it! A key point about the way the code above is constructed is the use of that `#define MAX_DIST 5`. You can change that single number to anything and your code will change along with it. You will discover that there is an optimum number; I can't tell you what it is (but I recommend it remains odd).

Now that you have a nice *reliable* distance measurement, you need to find if it is increasing or decreasing...

# Average the averages

As you have worked out, you need an array of values to determine if the distance is increasing. Bring in, again, the cyclic buffer.

```
#define MAX_DIST 5     // these could also be 'const int's
#define MAX_AVRG 3     // but my preference is this way

int dist[MAX_DIST];    // create an array, no need to initialise.
int distIterator = 0;  // 'dist' will be a CYCLIC BUFFER. woooOOOOooo.
int distAvrg[MAX_DIST]; // create an array of averages.
int avrgIterator = 0;  // wwwwoooOOOOooo ? Not this time.

// There's no single 'distAverage' anymore; the result dumps straight
//into 'distAvrg[avrgIterator]'...

dist[distIterator] = microsecondsToCentimeters(duration);
distIterator++;
if (distIterator == MAX_DIST) distIterator = 0;
distAvrg[avrgIterator] = 0.0;
for (int x=0; x<MAX_DIST; x++)
    distAvrg[avrgIterator] += dist[x];
distAvrg[avrgIterator] /= MAX_DIST;
avrgIterator++;
if (avrgIterator == MAX_AVRG) avrgIterator = 0;

```

Now you have an array of your averages. Winner.

From here you can create your `increasing`/`decreasing` function. I'll leave most of this up to you, but consider the following:

* The contents of `distAvrg` may not be perfectly smooth;
* The longer any of the arrays, the more reliable the average;
* The longer the array, the slower the response of the 'machine';
* Using `int` rather than `double` for `distAvrg` may help 'numb' some of the fluctuations in averages;
* Because `distAvrg` is a cyclic buffer, when analysing it *make sure you start at the correct element!* **HINT:** If you add your increase/decrease function *after* all the code above rather than amongst it, `avrgIterator` will always point to the *oldest* average value;
* If the `distAverage` array gets beyond three of four elements, you should definitely *pass it by reference* to the relevant functions; this is what I did in the first codeblock I wrote. It's beyond this answer to explain why you should do it other than "it's more efficient". This is a general rule for any large chunk of data, but you'll learn more as you go along.

The simplest algorithm for determining whether the `distAvrg`s are increasing or decreasing is to run through from oldest to newest and count how many *increases* there are and how many *decreases* there are:

```
int direction = 0;
for (x=oldest ... x=newest)
{
    if (x > x+1) direction++;
    if (x < x+1) direction--;
}

```

The above is pseudo-code - you'll have translate it yourself. You end up with a value of `direction` that is a positive number (increase), a negative number (decrease), or zero. The actual value of `direction` will help you determine the speed of the increase/decrease, if it's relevant.

---

# A possible solution:

> \** EDIT \** As pointed out by @EdgarBonet, `double` and `float` are 'expensive', in that they take up a lot of computing cycles to be dealt with. The Arduino website recommends avoiding them if you can. The alternative is to use scaled `int`s. For example, multiplying the return value from `microsecondsToCentimetres()` by 10 will give you the equivalent of one decimal place's worth of extra precision. No other code needs to change unless you're outputing the value on an LCD or similar and want it in centimeters. Dividing by 10 is conveniently the distance in millimeters, which is why I picked it, but there's no reason you can't scale by a different factor. Just be aware that there is a maximum (and mirrored minimum) value that `int` can hold, but I doubt you're going to hit it unless you scale by an unnecessarily high factor.

Let's say `MAX_AVRG` is `6`. This gives five *changes* between distances to look at. The simplest function for determining an increase is:

```
bool increasing(int * DIST)
{
    int dir = 0;

    for (int x=1; x<MAX_AVRG; x++)
    {
        if (DIST[x] > DIST[x-1])   // change this to < for DECREASE
            dir++;
        else
            dir--;
    }

    if (dir > 0)
        return TRUE;
    else
        return FALSE;
}

```

The 'decrease' version is identical, save for the single commented line. The `for` loop starts at the *second* sample and checks against the *previous* sample, which is why `x` starts at 1, not 0 as 'usual'. The return value will be `true` if `distAv` has increased more times than it has decreased, and vice versa for decreasing().

Let's say distAve = { 1, 2, 1, 3, 4, 5 }. In the function:

```
distAve   1   2   1   3   4   5
            ^   ^   ^   ^   ^
start       |   |   |   |   |    dir = 0
increase   -'   |   |   |   |    dir = 1
decrease       -'   |   |   |    dir = 0
increase           -'   |   |    dir = 1
increase               -'   |    dir = 2
increase                   -'    dir = 3

dir > 0 therefore INCREASE.

```

But what if distAve = { 5, 4, 3, 2, 1, 6 } ? If `increasing()` will now return `false` because there are four decreases vs one increase, except the final distance indicates that the sensed object has ended up at an increased distance than when it started.

```
int distance(int * DIST)
{
    int overallDistance = 0;
    for (int x=1; x<MAX_AVRG; x++)
        overallDistance += (DIST[x] - DIST[x-1]);
    return overallDistance;
}

```

Now you have an explicit value for the overall distance change.
> 0 votes

# Answer
Okay but why is everyone arguing about const and #define. That's clearly not the real problem that the person who posted the question is asking, so i'm kind of lost. @chaaarlie2. What exactly does averaging the averages do, since the distances have already been averaged to find the correct distance.
> 1 votes

# Answer
I would use subtraction to find a decreasing series you can subtract the new ping output from the previous one in every loop this way you can scale to a longer series without allocating more memory for the array

assuming you have defined somewhere:

```
/*use whatever number you want here*/
#define SERIES_LENGTH 3

```

declare globally:

```
int prevPingSample;
int decCount = 0;

```

than in your loop:

```
int pingSample = analogRead(sensorPin) //or however else you sample the sensor
if (prevPingSample > pingSample)
{ /*if the new reading is smaller than the previous -  the series is decreasing*/
 decCount = decCount + 1;
}
if (decCount >= SERIES_LENGTH)
{
    //move motor code
}
else
{
    decCount = 0;
}
//and whats left is to update the previous ping sample for the next loop
prevPingSample = pingSample;

```
> 0 votes

# Answer
A simpler solution. Use a variable to detect the trend and another for previous distance. Initialized to false and a very large number respectively.

Once a new distance is available the two variables are updated. If the trend is decreasing and the distance is less than your desired distance activate the motor.
> 0 votes

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


# Question
Title: Problem when using PROGMEM on array holding notes for speaker on Arduino
The problem I've been having is a little weird. I'm trying to set up audio for my Arduino project and have been playing around with the example included in the IDE. The problem is whenever I try to make the array of notes go into PROGMEM, it makes the outputted note higher than the one I put in. I don't want it to do that. In case it is relevant, the code I have is as follows:

```
    #define tuneSize 2
    // notes in the melody:
    const int melody[tuneSize] PROGMEM /*This is what's screwing it up*/= {
      NOTE_AS3, 0
    };

    // note durations: 4 = quarter note, 8 = eighth note, etc.:
    int noteDurations[tuneSize] = {
      6, 16
    };

    void setup() {
      // no need to repeat the melody.
      // iterate over the notes of the melody:
      for (int thisNote = 0; thisNote < tuneSize; thisNote++) {

        // to calculate the note duration, take one second
        // divided by the note type.
        //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
        int noteDuration = 1000 / noteDurations[thisNote];
        tone(8, melody[thisNote], noteDuration);

        // to distinguish the notes, set a minimum time between them.
        // the note's duration + 30% seems to work well:
        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);
        // stop the tone playing:
        noTone(8);
    }
}

```

(Pitch.h can be found in the Arduino example tab under digital)

My circuit has an 8 ohm resistor on pin 8. That's it.

The only thing I can think is that since the PROGMEM is slower, the data doesn't get to the speakers as fast thus making the output weird. Does anyone know how to fix this issue? Also, just having it on SRAM is not ideal because I'm working with a display and the lib it uses uses a lot of SRAM.

# Answer
You can not directly dereference something ("access an array") that is in flash memory. You have to use pgm\_read\_xxx functions from \<avr/pgmspace.h\> .

In your case you should probably write something like this:

```
tone(8, pgm_read_word(&melody[thisNote]), noteDuration);

```

Pgm\_read\_word reads two bytes. You could also call that inside your tone() function, the function would take the pointer in flash as an argument.

I would also recommend you using integer types from \<stdint.h\>, because they have defined sizes. Pure int is most likely 32-bit on your PC, but 16-bit on the AVR (I have learned this the hard way when my algorithm ran fine on the PC but gave totally junk output on the AVR).
> 3 votes

---
Tags: programming, progmem
---


# Question
Title: Data sent via UART Bluetooth different than SerialMonitor
I am using a 9-axis accelerator on an Arduino Uno (Atmega 328P processor) with a BLE Nordic rRF8001 chipset.

I am trying to send the accelerometer data via bluetooth to a smart phone (android).

The problem I am having is that the data shown on the serial monitor (which is correct, is not the data that is received via bluetooth. I think it has something to do with either the casting of the variables or that I am screwing up when converting the formats. Below is where I'm currently at and what I have tried.

The error I'm having is that the accelerometer data shown on the serial monitor screen (which is correct):

1. A\_x: -0.12 A\_y: 0.53 A\_z: 0.83
2. A\_x: -0.12 A\_y: 0.53 A\_z: 0.83
3. A\_x: -0.12 A\_y: 0.53 A\_z: 0.83

Does not agree with what the smart phone receives: (See image 1)

If I hard code in the x,y,z values in the arduino sketch

1. float x = (float) 0.52;
2. float y = (float) 0.52;
3. float z = (float) 0.52;

I get the following results (see image 2):

And here is the Arduino sketch I am working with:

```
//-------------------------------------------------------------------------------
//  TinyCircuits 9 Axis and Nordic BLE TinyShield Example Sketch

#include <Wire.h>
#include "RTIMUSettings.h"
#include "RTIMU.h"
#include "RTFusionRTQF.h"
#include <SPI.h>

#include "lib_aci.h"
#include "aci_setup.h"
#include "uart_over_ble.h"
#include "services.h"

#if defined (ARDUINO_ARCH_AVR)
#define SerialMonitorInterface Serial

#elif defined(ARDUINO_ARCH_SAMD)
#define SerialMonitorInterface SerialUSB
#endif

#define DISPLAY_INTERVAL 100

RTIMU *imu;                                           // the IMU object
RTFusionRTQF fusion;                                  // the fusion object
RTIMUSettings settings;                               // the settings object

unsigned long displayInterval = 50;
unsigned long lastDisplay;
unsigned long lastRate;
int sampleCount;

#define BLE_DEBUG false
uint8_t ble_rx_buffer[21];
volatile uint8_t ble_rx_buffer_len = 0;
volatile uint8_t ble_can_sleep = false;
volatile uint8_t ble_connection_state = false;

#ifdef SERIAL_POR_MONITOR
  #define SerialMonitor SERIAL_PORT_MONITOR
#else
  #define SerialMonitor Serial
#endif

void setup(void)
{
//  SerialMonitorInterface.begin(230400);
  SerialMonitor.begin(230400);

  int errcode;

  while (!SerialMonitor);

  Wire.begin();
  imu = RTIMU::createIMU(&settings);                        // create the imu object

  SerialMonitorInterface.print("ArduinoIMU starting using device "); SerialMonitorInterface.println(imu->IMUName());
  if ((errcode = imu->IMUInit()) < 0) {
    SerialMonitorInterface.print("Failed to init IMU: "); SerialMonitorInterface.println(errcode);
  }

  if (imu->getCalibrationValid())
    SerialMonitorInterface.println("Using compass calibration");
  else
    SerialMonitorInterface.println("No valid compass calibration data");

  lastDisplay = lastRate = millis();
  sampleCount = 0;

  // Slerp power controls the fusion and can be between 0 and 1
  // 0 means that only gyros are used, 1 means that only accels/compass are used
  // In-between gives the fusion mix.

  fusion.setSlerpPower(0.02);

  // use of sensors in the fusion algorithm can be controlled here
  // change any of these to false to disable that sensor

  fusion.setGyroEnable(true);
  fusion.setAccelEnable(true);
  fusion.setCompassEnable(true);
  BLEsetup();
}

void loop() {
  aci_loop();//Process any ACI commands or events from the NRF8001- main BLE handler, must run often. Keep main loop short.
  unsigned long now = millis();
  unsigned long delta;

  if (imu->IMURead()) {                                // get the latest data if ready yet
    fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
    sampleCount++;
    if ((delta = now - lastRate) >= 1000) {
      /*SerialMonitorInterface.print("Sample rate: "); SerialMonitorInterface.print(sampleCount);
        if (imu->IMUGyroBiasValid())
        SerialMonitorInterface.println(", gyro bias valid");
        else
        SerialMonitorInterface.println(", calculating gyro bias - don't move IMU!!");
      */
      sampleCount = 0;
      lastRate = now;
    }
    if ((now - lastDisplay) >= displayInterval) {
      lastDisplay = now;
      RTVector3 accelData = imu->getAccel();
      RTVector3 gyroData = imu->getGyro();
      RTVector3 compassData = imu->getCompass();
      RTVector3 fusionData = fusion.getFusionPose();
      char sendBuffer[30] = " ";
      uint8_t sendLength = 0;
      //displayAxis("Accel:", accelData.x(), accelData.y(), accelData.z());        // accel data
      //displayAxis("Gyro:", gyroData.x(), gyroData.y(), gyroData.z());            // gyro data
      //displayAxis("Mag:", compassData.x(), compassData.y(), compassData.z());    // compass data
      //displayDegrees("Pose:", fusionData.x(), fusionData.y(), fusionData.z());   // fused output
      float x = (float)(accelData.x() );//* RTMATH_RAD_TO_DEGREE);
      float y = (float)(accelData.y() );//* RTMATH_RAD_TO_DEGREE);
      float z = (float)(accelData.z() );// * RTMATH_RAD_TO_DEGREE);
//      float x = (float) 0.52;
//      float y = (float) 0.52;
//      float z = (float) 0.52;
      sendLength = sprintf(sendBuffer, "% 2.3d % 2.3d % 2.3d", x, y, z);
      if (sendLength > 20)sendLength = 20;
      if (!lib_aci_send_data(PIPE_UART_OVER_BTLE_UART_TX_TX, (uint8_t*)sendBuffer, sendLength))
      {
        SerialMonitorInterface.println(F("TX dropped!"));
      }
      SerialMonitorInterface.println();

      SerialMonitor.print(" A_x: "); SerialMonitor.print(x);
      SerialMonitor.print(" A_y: "); SerialMonitor.print(y);
      SerialMonitor.print(" A_z: "); SerialMonitor.println(z);

    }
  }
}

```

Any thoughts on why the data sent over BLE is incorrect?

# Answer
The problem has nothing to do with the bluetooth. It is purely down to how you are formatting the data:

```
% 2.3d % 2.3d % 2.3d

```

`d` is a signed integer. You can't format a floating point value as a signed integer, it just messes up.

Also I don't think the Arduino's `sprintf` even has floating point support by default (it makes it all too big).

So you will need to find another way to format your data. Maybe use `dtostrf()` instead.
> 1 votes

---
Tags: arduino-uno, serial, bluetooth, android
---


title: Persistence of user input after reboot

text:
# Question
Title: Persistence of user input after reboot
I am creating an application where user input is required. After a user browses through available choices (via buttons and LCD) depending on the choice of the user a function is run from several available.

When the user reboots the Arduino, it starts from the default function, making the user reselect the choice they want..

Is there a way to have persistence of the choice of the user after a reboot? So that, when a user makes a selection, after a reboot, the arduino will have this selection (=the function that corresponds to this selection) by default.

Maybe if the user input (the buttons) write to an EEPROM or something like this? So that the arduino reads the value from the component?

If such a solution exists, due to limitations i would like to have only one wire for communication with the device.

EDIT: I am using Arduino Due

# Answer
Better than that: Zero wires.

The Arduino has EEPROM built in.
> 3 votes

---
Tags: power, arduino-due, eeprom
---


# Question
Title: Ways to turn a knob with a stepper motor and an ATMEGA32u4
Hey all I am wondering what would be the best items to purchase for me to be able to turn this know (continuous) below:

As I mentioned above, I would need the stepper motor to have a continuous rotation in order for it to work with either of these dry food dispensers above.

There is a decent tutorial HERE but really doesn't give much information about how they went about building it and the mentioned Yocto-LatchedRelay seems over priced for something that can be done with just a stepper motor and some logic behind it.

I plan on using a ATMEGA32u4 with this project. I will have a total of 6 of these to control.

So any suggestions on what would be best for this type of project would be great and I look forward in hearing them! :o)

**I'm just needing to know what kind of servo torque I would need in order to turn that without issues of it getting stuck mid-ways.**

**update**

i spoke to the original creator of that web site project that i linked to and this is what they had to say about the parts that were used:

> We used a small geared Maxon motor (great but expensive hi-tech stuff).
>
> motor RE-max 13 Ø13 mm, Precious Metal Brushes CLL, 1.2 Watt, with cables Part-No.: 203888
>
> gear Planetary Gearhead GP 13 A Ø13 mm, 0.02 - 0.35 Nm, Metal version Part-No.: 110316
>
> Torque was on the low side: it was enough for regular cornflakes but clearly insufficient for muesli :-)
>
> The problem is not only about finding a motor with enough torque, it's also about finding a motor small enough to fit in the dispenser.
>
> Here are the files. The pulleys were 3D printed, but the bracket was laser cut in 3mm acrylic glass.

Are there any servos that have a hole in the middle so that i can slide it over the turning rod and screw down to tighten on it in order to spin it as if you were spinning it yourself with the handle?

Something like this:

# Answer
Looks to be a screw driven by a motor through a set of greats. It doesnt matter if the motor is a regular (dc) motor or a stepper.
> -1 votes

---
Tags: arduino-mega, motor, arduino-leonardo, stepper
---


# Question
Title: How can I add two different programs of bldc motor and servo motor in one so that they work in parallel?
This is for the servo motor:

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

Servo servo_test;
//initialize a servo object for the connected servo
int angle = 0;

void setup() {
  servo_test.attach(9);
}

void loop() {
  for(angle = 0; angle < 180; angle += 1) {
    servo_test.write(angle);
    delay(15);
  }
  delay(1000);
  for(angle = 180; angle>=1; angle-=5) {
    servo_test.write(angle);
    delay(5);
  }
  delay(1000);
}

```

This is for the bldc motor with esc:

```
#include <Servo.h>

Servo esc_signal;

void setup() {
  esc_signal.attach(12);
  esc_signal.write(30);
  delay(3000);
}

void loop() {
  esc_signal.write(55);
  delay(15);
}

```

# Answer
Depending on how the code is driven. The simplest would be to simply run loop1 and loop2 in the new loop.
> -1 votes

# Answer
Try out this code. It may be helpful.

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

Servo servo_test;  //initialize a servo object for the connected servo
int angle = 0;

Servo esc_signal;

void setup()
{
  servo_test.attach(9);

  esc_signal.attach(12);
  esc_signal.write(30);
  delay(3000);
}

void loop()
{
  servoFun();
  bldcFun();
}

void servoFun()
{
  for(angle = 0; angle < 180; angle += 1)
  {
      servo_test.write(angle);
      delay(15);
  }
  delay(1000);

  for(angle = 180; angle>=1; angle-=5)
  {
      servo_test.write(angle);
      delay(5);
  }
  delay(1000);
}

void bldcFun()
{
  esc_signal.write(55);
  delay(15);
}

```
> -1 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino TCP Server establishes connection with client but does not receive data
I am trying to send and receive data with the **TCP** server but I am not receiving data.

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

// Parametros de conexion a red WIFI.
const char* ssid = "bits";
const char* password = "12345";

// Start a TCP Server on port 5000
WiFiServer server(5000);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid,password);
  Serial.println("");
  //Wait for connection
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 Serial.println(WiFi.localIP()); // IP

  // Start the TCP server
  server.begin();
}

void loop() {
  TCPServer();
}

void TCPServer () {
   WiFiClient client = server.available();
    if (client) {
      Serial.println("We have a new client");
      Serial.println("Hello, client!");
        if (client.available() > 0) {
            char thisChar = client.read();
            Serial.println("We got data");
            Serial.println(thisChar);
            delay(200);
        }
    }
}

```

**Test Capture**: In the capture it is seen that the code is executed until the following instruction.

```
Serial.println("We have a new client");
Serial.println("Hello, client!");

```

# Answer
I found the solution by modifying the code

```
void TCPServer () {
   WiFiClient client = server.available();
  if (client)
  {
    Serial.println("New Client");

    while(!client.available()&&client.connected())
    {
    delay(1);
    }

    String linea1 = client.readStringUntil('r');
    Serial.println(linea1);
  }
}

```
> 0 votes

# Answer
You have created a TCP server. You need to connect other clients to it to start data send and receive process between them. If you just simply run this and wait, then you probably won't get anything because nobody is attempting to connect to it.
> 1 votes

---
Tags: c++, arduino-ide, esp8266
---


# Question
Title: What bootloader does the Arduino Micro come with?
I've been looking to modify the Arduino Micro bootloader (specifically changing the VendorID and ProductID) of the Arduino. What bootloader comes pre-installed on the Arduino Micro? and how would I go about building and uploading a modified bootloader?

# Answer
> 2 votes
Try looking at https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/caterina/Descriptors.c

Inside that is:

```
/** Device descriptor structure. This descriptor, located in SRAM memory, describes the overall
 *  device characteristics, including the supported USB version, control endpoint size and the
 *  number of device configurations. The descriptor is read out by the USB host when the enumeration
 *  process begins.
 */
const USB_Descriptor_Device_t DeviceDescriptor =
{
    .Header                 = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device},

    .USBSpecification       = VERSION_BCD(01.10),
    .Class                  = CDC_CSCP_CDCClass,
    .SubClass               = CDC_CSCP_NoSpecificSubclass,
    .Protocol               = CDC_CSCP_NoSpecificProtocol,

    .Endpoint0Size          = FIXED_CONTROL_ENDPOINT_SIZE,

    .VendorID               = DEVICE_VID,
    .ProductID              = DEVICE_PID,
    .ReleaseNumber          = VERSION_BCD(00.01),

    .ManufacturerStrIndex   = 0x02,
    .ProductStrIndex        = 0x01,
    .SerialNumStrIndex      = NO_DESCRIPTOR,

    .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS
};

```

...

```
/** Product descriptor string. This is a Unicode string containing the product's details in human readable form,
 *  and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
 *  Descriptor.
 */
const USB_Descriptor_String_t ProductString =
{
    .Header                 = {.Size = USB_STRING_LEN(16), .Type = DTYPE_String},

    #if DEVICE_PID == 0x0036
    .UnicodeString          = L"Arduino Leonardo"
    #elif DEVICE_PID == 0x0037
    .UnicodeString          = L"Arduino Micro   "
    #elif DEVICE_PID == 0x003C
    .UnicodeString          = L"Arduino Esplora "
    #else
    .UnicodeString          = L"USB IO board    "
    #endif
};

```

> and how would I go about building and uploading a modified bootloader?

You would run the Makefile which is in the same directory as the above file. Then send the resulting .hex file to your device.

---
Tags: bootloader, arduino-micro
---


# Question
Title: Can I make a USB Device with only data output
**This is about how USB ports/devices work**

Lets say i have a USB port on my computer

If I have an arduino board or something similar, am I able to connect output to Data+ and sort of make my own USB keyboard. **What I aim to achieve is send without having to receive**

**1)** Would I need to connect it to both D+ and D- so it forms a circuit in order for the USB port to read the data? (or would the data simply be read and then disappears so I don't have to worry about two wires?)

If Yes: **2)** If I manage to forcefully push electricity through the wire onto the Data pins, would I only need one wire?

Else: **3)** is this physically impossible and the whole universe would explode if I tried?

# Answer
D+ and D- are not send and receive. The two signals are complementary to each other and bidirectional.

They form a *low voltage differential pair*. When one is high the other is low and vice versa.

Both have to be connected for USB signals to get through.

The data is sent down both wires at once, but only in one direction at a time (half duplex).

There is far more data going through USB than the data you are sending. The data you see is the end result of a complex protocol negotiation between your device and the host.
> 3 votes

# Answer
USB is a host-managed protocol. A USB device *must* be able to receive in order to operate, since the host notifies the device when it should send data back to the host.

The D+ and D- lines are *not* independent; the signaling state of the line is determined by examining *both* lines regardless of whether the host or the device is transmitting.

USB Made Simple
> 3 votes

---
Tags: usb
---


# Question
Title: How many pins does this circuit (HMC5883L) use?
I've been told 2 by a friend but this looks to only use one?

https://www.adafruit.com/product/1746

# Answer
Below image is the answer to your question.

According to this image, magnetometer required four pins of arduino.

GND of magnetometer ----\> Arduino GND

Vcc of magnetometer ----\> Arduino 3.3 Volt

SDA of magnetometer ----\> Arduino Analog Pin 4

SCL of magnetometer ----\> Arduino Analog Pin 5

A4, A5 on Uno are SDA, SCL, required for hardware-based I2C.

I hope it will help you.
> 8 votes

# Answer
It is I2C so 2 pins.

Optionally it can use a third pin to indicate data ready.
> 3 votes

# Answer
It depends what you think of as a pin.

You have VIn and Gnd, SCL and SDA are the 4 main pins you will need to connect. The 3.3V and RDY pin don't seem to be connected in any of the pics I can see.

So the answer is 2 pins plus 2 power.

Oh from the page on how to use it, https://learn.adafruit.com/adafruit-hmc5883l-breakout-triple-axis-magnetometer-compass-sensor/wiring-and-test: "This 3-axis magnetometer breakout is thankfully very easy to use. It only requires 2 power pins and 2 data pins."

Interestingly it doesn't appear to use pull up resistors, which most I2C device require, so the might be built into the board.
> 3 votes

# Answer
Here below image provides the connection and pin requirements for magnetometer...

According to image magnetometer will require 4 pins of Arduino 2 pins of supply i.e +3 volt and Ground and other two pins will be A4 & A5 pins of Arduino.

And to connect other sensors with Arduino, you can find datasheet of desired sensor and can find how many pins that sensor is going to use.
> 0 votes

---
Tags: sensors, pins
---


title: ATTiny85 VirtualWire AnalogRead 1

text:
# Question
Title: ATTiny85 VirtualWire AnalogRead 1
My **ATTiny85** is connected to a **433 transmitter** and an **analog sound sensor**. The 433 is working fine (using **VirtualWire**) but when I send the reading from the sensor all I receive is a 1.

What I would like to receive is the value between 0 and 1024 like when I print the sensor to serial. I cannot check it because the ATTiny85 had no serial out.

My code is a combination of snippets I found online, I am not happy with all the magic to format the data that needs sending. I would also like to send "Reading: 637" in stead of just the number but I find the concatenation Google results extremely complicated.

Should this code send the sensor data like 672? Could there maybe be some Fuse setting blocking the AnalogRead?

```
#include <VirtualWire.h>

const int transmit_pin = PB0;
const int sensor_pin = PB4;
int sensor_data;
char sensor_msg[4];

void setup()
{
  vw_set_tx_pin(transmit_pin);
  vw_setup(2000);
}

int count = 1;

void loop()
{

  sensor_data = analogRead(sensor_pin);
  itoa(sensor_data,sensor_msg,4);
  vw_send((uint8_t *)sensor_msg, strlen(sensor_msg));
  vw_wait_tx(); // Wait until the whole message is gone
  _delay_ms(1000);
  count = count + 1;

}

```

**Receiver Code as requested**
This is a Pro Mini (clone) and it has an LCD attached so I can see what is going on.

```
#include <VirtualWire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);

const int receive_pin = 11;
char* testje;
void setup()
{
    delay(1000);
    Serial.begin(9600); // Debugging only
    Serial.println("setup");

    // Initialise the IO and ISR
    vw_set_rx_pin(receive_pin);
    vw_setup(2000);  // Bits per sec

    vw_rx_start();       // Start the receiver PLL running

    lcd.init();
    lcd.backlight();
    lcd.home();
    lcd.clear();
    lcd.print("hello");
    delay(1000);
    lcd.clear();
}

void loop()
{
  char buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;

  if (vw_get_message(buf, &buflen)) {
    int i;
    // Message with a good checksum received, print it.
    Serial.print("Got: ");

    for (i = 0; i < buflen; i++) {
       Serial.print((char)buf[i]);
    }
    Serial.println();
    Serial.println(buf);
    lcd.clear();
    lcd.print(buf);
  }
}

```

# Answer
> 0 votes
I would double check the pin numbers for the attiny. They look like port bit numbers but that might just work by chance.

```
const int transmit_pin = PB0;
const int sensor_pin = PB4;

```

A quick double check with the attiny/pins\_arduino.h give:

```
// ATMEL ATTINY45 / ARDUINO
//
//                 +-\/-+
// Ain0 (D5) PB5  1|    |8  Vcc
// Ain3 (D3) PB3  2|    |7  PB2 (D2) Ain1
// Ain2 (D4) PB4  3|    |6  PB1 (D1) pwm1
//           GND  4|    |5  PB0 (D0) pwm0
//                 +----+

```

As you have found they should be defined as:

```
const int transmit_pin = 0; // Physical pin 5
const int sensor_pin = 4;   // and pin 3

```

This type of issue could be avoided by using strong data typing and object oriented design. Please see for instance Cosa ATtinyX5.hh and GPIO.hh.

Cheers!

Here is something that does basically the same as the sender. Cosa supports attiny and Arduino boards "out-of-the-box".

---
Tags: attiny, virtualwire
---


# Question
Title: Programming Other Atmel chips using Arduino
Is it possible to burn Arduino code on any other third party Atmel products using an another Arduino ? And if its possible then how ?

# Answer
> Is it possible to burn Arduino code on any other third party Atmel products using an another Arduino ? And if its possible then how ?

Do you mean if the "Arduino as ISP" sketch and an Arduino would work to flash another Atmel AVR MCU? If so the answer is yes but I guess that you also want to generate code for the new MCU. In that case there is some work to be done before that is possible.

Start by reading about how to install additional cores and the guideline for a custom core. Then select an custom core to study. Here you will find the files you need to provide to support a new AVR based MCU.

Cheers!
> 1 votes

---
Tags: arduino-ide, arduino-nano, atmel
---


# Question
Title: Why my Galileo isn't getting a IP address?
I have an Ethernet cable connected to my router. I connected the other end to my laptop and got a successful connection. When I plug it into my Arduino Galileo gen2, even with Ethernet port green light on, I got nothing when I run this:

```
delay(1000);
system("ifconfig eth0 > /dev/ttyGS0");

```

This is my output:

```
eth0      Link encap:Ethernet  HWaddr 00:00:00:00:00:00
      BROADCAST MULTICAST  MTU:1500  Metric:1
      RX packets:0 errors:0 dropped:0 overruns:0 frame:0
      TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
      Interrupt:41 Base address:0x8000

```

What I'm doing wrong?

# Answer
I really don't know why, but after I initialized the Ethernet interface`ifconfig eth0 up` it started working properly. I don't know why this time this command was needed and the others didn't.
> 0 votes

---
Tags: ethernet, arduino-galileo
---


# Question
Title: Using AA batteries to power Arduino and GPS unit
I'm more of a software guy, so I need your help to figure out the power issue with my Arduino.

What I would like to do is using a GSM/GPS unit (Ai-Thinker A7) with Arduino Nano as a car tracking system. I have USB cables in the car, so I can plug it into my Arduino and power both while I'm driving. To power the unit while I'm not driving, I thought using rechargeable batteries would be a good idea. I'm planning to use GPS via SMS activation, so I hope fully charged batteries will be enough to power it for at least a week. But I'm confused about a couple of things.

Rechargable batteries are 1.2V. So technically I can use 5 of them and power my Arduino and the GPS unit (which requires 5V), right? However, for a similar unit at Adafruit they say that a LiPo battery is a must. Well, I think it is because GPS unit draws more power while using GPS and stuff. So, in this case are AA batteries out of the question? Will I fry anything if I build the system as follows?

If AA batteries happen to be fine, do I need another piece in my design, such as this one?

At last, I have no idea if I need any diode, capacitor, resistance or sth else for this system. I would appreciate further comments about my design.

# Answer
> 2 votes
I suggest using 6 or 8 AA's (eg 6 alkalines or 8 NiMH) and a MP1584EN DC DC Power Stepdown Buck Converter (about a dollar on ebay, 1.5 to 3 times that on Amazon). Note, the hole pattern does not match up with breadboard spacing:

The batteries would tie in via a couple of diodes (preferably Schottky), as shown below. When the 12 V supply is off, the converter would be powered by 9.6 V from eight rechargeable AA's. When the 12 V supply is on, no current is drawn from the AA's. The converter output should be adjusted to 5V before being connected to the Nano or other devices it powers.

Using a buck regulator has two advantages vs a linear regulator: battery current is lower (allowing the battery pack to be more efficient as it discharges) and less energy is wasted as heat.

Note, it might make sense to remove the power LED from the Nano, to save 3 to 5 mA of current.

simulate this circuit – Schematic created using CircuitLab

---
Tags: arduino-nano, gsm, battery, gps, system-design
---


# Question
Title: Why does my Arduino Nano send the wrong voltage on a digital output PIN?
Adruino nano powered by 12v through **VIN** pin.

Normally I expect ~12v on digital output pin, when i write HIGH to this pin, and ~0v when i write LOW. But what I have instead

```
digitalWrite(pin, HIGH); // I have 1.5v on pin
digitalWrite(pin, LOW);  // I have 0.5v

```

Algorithm is quite simple - On push button toggle output pin state. Connections:

* **VIN** \- +12v
* **GND** \- ground
* **d2** \- input pin (0 0, 12 - 1, button);
* **d3** \- output pin (we change state of this pin)

Input works as expected.

simulate this circuit – Schematic created using CircuitLab

# Answer
> 5 votes
The microcontoller in an Arduino operates on 5 Volts (or perhaps 3.3 Volts). An on-board voltage regulator reduces the 12 Volt input to 5 volts for the ICs on the board.

Connecting the pull-up resistor (R1 in your drawing) to 12 Volts may damage the microcontroller (especially if it is really 100 Ohms as your drawing shows). The pullup resistor must be connected to the 5 Volt pin on the Arduino board.

The output voltage of an Arduino pin should be near 5 Volts, but may be less if you place a heavy (high-current) load on it.

# Answer
> 1 votes
The arduino is powered by 12v but regulates down to 5v or 3v for the microcontroller. Then your output pin current is important. Anything over 20mA will result in a large voltage droop due to the ESR of the pin. Highly depends on your circuit and your full code.

# Answer
> 1 votes
As others have said, you should not pull d2 to 12 V. You are sending about (12 V − 5 V) ÷ 100 Ω = 70 mA into the high-side diode that protects that input pin. This diode is only rated for 1 mA, thus you will likely fry it in a short time.

To avoid the damage, you could increase the value of R1 in order to lower that current to a safe value, but it would be simpler and safer to completely remove the resistor and use the internal pullup instead, as in

```
pinMode(2, INPUT_PULLUP);

```

As for the measured output on d3, you expect 5 V when the pin is written `HIGH`. Your 1.5 V reading is suspicious. My guess is that you forgot to

```
pinMode(3, OUTPUT);

```

In this case, writing the pin to `HIGH` does not have the expected effect. Instead, it activates the internal pullup, which should make the pin read 5 V, but then even a very small load (about 0.1 mA) can make the voltage drop to 1.5 V.

If you are really getting 1.5 V while the pin mode is set to `OUTPUT`, then you are really pulling far too much current from the pin. My guess would be around 130 mA (a 26 Ω output resistance is typical). The **absolute maximum rating** for the pin is 40 mA, so again, you are going to fry something.

---
Tags: arduino-nano
---


# Question
Title: Can I connect a PWM pin on one Arduino to an analog input on another?
I was considering several different ways to send simple data from one Arduino to another when I though, why not connect a PWN pin of one Arduino to the analog pin on another? I could send simple messages for one to the other by setting different values on the PWM pin. This seems like it would work, except for the fact the the PWM pins mimic voltages with pulses.

Is this a reliable way to link two Arduinos, If I only want to communicate 4 states? Also, will I need to include some additional components in the connection (resister, capacitor, etc.)

All it needs to do is send a 2v pulse for yes and a 5 v pulse for no. It needs to do this about 6 times an hour.

# Answer
Yes, you can do this with "a little programming" or more easily by adding two cheap components.

If you connect a say 47k resistor from PWM\_Out to Analog\_In and a say 100 uF capacitor from Anaolg\_In to ground you will be able to read the equivalent analog value to an accuracy of around 1%. Read it N times (maybe 10 times) with a delay of say 12 ms between reads and average it for a better result. This works because the PWM period is **about** 1 mS so delaying for a period of multiple cycles but not an exact multiple means you sample semi randomly.

For the sort of resolution that you want (4 levels) a MUCH smaller capacitor could be used (maybe 1 uF.) But even a 100 uF capacitor is cheap.

You could instead use PWM out (analogWrite) and a digitalRead.
Perform say 100 digital reads with say 12 ms between reads (so about 1.2 seconds total) and keep two counts - PinWasHigh and PinWasLow for (obviously) high or low conditions. The contents of PinWasHigh tells you what % of reads was high. Due to random sampling you cannot rely on this for 100 levels but determining say 10 levels should give good accuracy. The sum of PinWasHigh and PinWasLow should total 100 as a sanity check.

While use of a serial port (hardware or software) or SPI allows more data transfer per time and without much effort, this simple analog method is good enough for many applications.
> 7 votes

# Answer
It is possible, but not the best idea. The analog inputs require a reasonably stable input - this can be achieved with a RC filter to smooth the PWM output. This would work for reasonably slow data rates.

You would be better to use one of the many communication protocols supported by Arduino (serial, SPI, I²C).
> 5 votes

# Answer
For greater precision, less code, faster execution and no need for capacitors read the PWM "analog" signal on the other Arduino from a **digital input** pin with

`pulseIn(pin, HIGH, timeout)`

The timeout is optional (1 second by default). As soon as the line goes high, a timer engages and automatically stops the instant the line goes low.

The primary reason to use PWM communcation (as opposed to i2c, SPI, etc.) is to broadcast to an unlimited number of devices simultaneously without the need for a clock signal or acknowledgement.

We are currently using this method of communication for neural networks composed of separate tiny processors for each neuron substructure (one processor for each synapse and activation function).
> 4 votes

# Answer
Full solution to receive **PWM** signal and convert **to** a like **analogRead()** one. Its based on @Cortex\_systems answer and Id like to share it to help others with a more comprehensive answer.

```
int var = pulseIn(digitalPin, HIGH, 4200);
if (var == 0 && digitalRead(digitalPin) == 1) {
    var = 2100;
}
var= map(var, 0, 2100, 0, 1023);

```

Here is the why:

* You can not just read PWM signal to analog pin in arduino. We will receive the PWM in a digital pin with its *pinMode set to input* and read it with pulsIn(pinNum, high/low, timeout).
* pulseIn() records the length of the pulse. Longest pulse in PWM is 2100 microseconds.
* Timeout is set to 4200 for 2 cycles of PWM. Without this it will wait for a new high and freeze the code in cases that PWM is 0 or 255.
* At max and min this will read 0, so in that case check with digitalRead() to determine and adjust.
* Finally, map the result so it appears like an analogRead().

Note! This adds a delay of up to 4.2 milliseconds to code.
> 1 votes

---
Tags: pwm, analogread
---


# Question
Title: Assigning float to 10 decimal place for longitude,latitude
I'm quite a novice in arduino programming. I am doing a small home project and I am using sim808 to obtain GPS data.

My question is quite simple but i can't find any solution online.

```
Serial.print("latitude :");
Serial.println(sim808.GPSdata.lat, 10);
Serial.print("longitude :");
Serial.println(sim808.GPSdata.lon, 10;

```

This code display Longitude and Latitude data on serial monitor to 10 decimal place perfectly.

But when after setting the Longitude and Latitude to float.When I use this code, I don't get a valid gps data.

```
Longitude = (sim808.GPSdata.lon, 10 );
Latitude = (sim808.GPSdata.lat, 10 );

```

Please help, Thanks.

(edited) I understand my error in coding for the above.

In fact, I am using a DF robot shield sim 808 for vehicle tracking. I am uploading my GPS data, longitude, latitude and speed to Ubidots. The only difficulty is in saving accurate data.

I am using this codes

```
Longitude = sim808.GPSdata.lon;
Latitude = sim808.GPSdata.lat;
Speedperkm = sim808.GPSdata.speed_kph;

client.add("Longitude", Longitude);
client.add("Latitude", Latitude);
client.add("Speed per Km", Speedperkm);

```

The code is working fine but only GPS data of 2 decimal place is being uploaded. If data of up to 6 decimal place is uploaded then the system will more accurate.

That my problem that I am trying to solve.

# Answer
> But when after setting the Longitude and Latitude to float.When I use this code, I don't get a valid gps data.

Some statements in C/C++ are not what they might seem. The value of the statements:

```
Longitude = (sim808.GPSdata.lon, 10 );
Latitude = (sim808.GPSdata.lat, 10 );

```

Are actually the same as:

```
sim808.GPSdata.lon;
Longitude = 10;
sim808.GPSdata.lat;
Latitude = 10;

```

Which is then optimized to:

```
Longitude = 10.0;
Latitude = 10.0;

```

That is, when using list notation, the value of the expression is the same as the value of last expression in the list.

The other answers have covered the fact that float and double on Arduino (AVR-GCC) are only 32-bit, and that gives 6 to 9 significant decimal digits precision.

Cheers!
> 3 votes

# Answer
You always should calculate with the maximum resolution (not rounding to 10 digits), so use:

```
Longitude = sim808.GPSdata.lon;
Latitude = sim808.GPSdata.lat;

```

For printing you can use the code you have.

```
Serial.print("latitude :");
Serial.println(sim808.GPSdata.lat, 10);
Serial.print("longitude :");
Serial.println(sim808.GPSdata.lon, 10);

```
> 1 votes

---
Tags: programming, gps, tinygps, float
---


# Question
Title: Replacing BT module with 433 MHz transreceiver module
I have made a prototype where I can send data from one arduino to another via Bluetooth(hc-05), they are working fine, but now I want to replace the BT module with RF module, how can I do that???

# Answer
Yes, use VirtualWire or RadioHead. You might need to "evolve" your protocol to handle message fragmentation and loss. RadioHead has support for that.

Cheers!
> 1 votes

---
Tags: arduino-uno, bluetooth, rf, hc-05
---


# Question
Title: Problem Uploading to arduino nano (atmega 328p)
I am using Arduino 1.8.1 and arduino nano (mega 328p) and ftdi driver. In device manager it seems no problem, because it is detected as COM99. But it says a problem while uploading to the board as picture given. Please Helpp..

# Answer
> 0 votes
Looking at the error in the end about the invalid library, it seems a configuration problem and not a communication problem.

Try:

* Close and reopen the Arduino IDE (and check again)
* Remove the library and add it again (in the Manage library options in the menu), close/reopen the Arduino IDE (and check again)
* Reinstall the Arduino IDE (and check again)

---
Tags: arduino-nano
---


# Question
Title: Can i burn an Arduino sketch .hex directly using USBASP?
I am unable to upload sketches to my Arduino Uno board using the upload option in the IDE. I have done quite a few tests to find the reason but everything seems to be working fine when tested separately. I found that I can program the ATMega328 board when placed on a breadboard using an USBASP progammer and avrdude. So will it work if I burn the .hex generated in Arduino IDE using avrdude and USBASP by placing the ATMega on a breadboard? I would then want to replace the IC on the UNO board back for my application. Thanks for your time and help in advance.

# Answer
> 0 votes
Sure you can - but you don't even need to remove the chip from the Uno.

The 6 pin header at the end of the board (used for SPI) is also the ISP header for the main chip. Just plug your USBASP into there (you can get adaptors for it for $0.99 off eBay) and program it direct.

I think there's even an option in the IDE's menu to select the USBASP as the programmer (or there used to be on earlier versions).

---
Tags: arduino-uno, uploading, isp, usbasp
---


title: Problem uploading to board

text:
# Question
Title: Problem uploading to board
```
avrdude: stk500_getsyn(): not in sync_resp=0*00
avrdude: stk500_disable: protocol error, expect=0*14,resp=0*51

```

These are the errors occurring when I am trying to upload to the board.
I've tried all the suggestions that suggested in this. When I am trying to burn the bootloader the same error is showing.

# Answer
> 1 votes
I don't know if I got the exact error (maybe another sync error), but what helped in my case (in this order, try again every time):

* Reinsert the USB cable
* Use a different (shorter) USB cable
* Put the USB cable in another USB port
* Restart the Arduino IDE
* Restart the computer
* Reinstall the Arduino IDE
* Go to device drivers (control panel), check for COM ports, remove Arduino and reinstall

---
Tags: uploading, arduino-duemilanove
---


# Question
Title: is it possible to write two threads in arduino & switch between data & AT command mode dynamically?
I need to recieve data from a android phone and also estimate distance of phone from the HC 05 module , So i want to write two threads or functions. In one part i want recieve data from android phone store it in a variable and in other enter AT command mode to see RSSI of the phone.

# Answer
You can switch between command and "online" modes, but you cannot use both at once. While in command mode you can't be receiving data, and while in online mode you can't be sending commands.

You would have to periodically switch between the two in your program at a time when you know you won't be receiving data (or you don't mind losing that bit of data).

And no, the Arduino doesn't have the concept of threads. There are a number of libraries that do emulate threads to a certain extent, but they are (usually) cooperative multi-tasking (one "thread" has to manually "yield" to another) and as such are pretty pointless, since you can get the same effect with a decent finite state machine.
> 2 votes

# Answer
Receiving serial characters is partially done in hardware and partially in the Arduino firmware. The only thing you need to do here is: \- check if you've received a full message. \- handle the message (if a full message has been received)

For the ultrasonic sensor, you'll have to: \- Start a measurement. \- wait for a response. \- convert the response.

You can't do these exactly at the same time. But none of these will/should take up 100% of your "processor time". So we'll have to "share the time" of your microcontroller.

Though, timing may be critical in some of these parts. So for this, we will have to make sure that there is no delay in, for example, handling the ultrasonic sensor. (I'm not sure, and can't check since I'm on my phone, if Arduino uses interrupts for receiving characters from serial, which may mess up my logic below if these interrupts aren't prioritized well or the time an arduino RX interrupt takes so long it will influence your ultrasonic sensor readings significantly.)

But, you'll want to handle the ultrasonic responses as fast as possible, since this timing indicates the distance between an object. And you don't want to use processor speed while waiting for the result.We will probably want to use an interrupt here (if polling doesn't give a good enough result). See the Arduino page in interrupts, or use a HC-sr04 library that is non-blocking or interrupt/event-based

Now you can, if the ultrasonic sensor doesn't require any attention. Check and handle your serial buffer. (I believe there even is an option in the Arduino library to set a callback for a line end).

By doing the above. You can be sure that your ultrasonic readings are stable. And as long as the ultrasonic routines don't consume all processing time (which they shouldn't), you'll have time to handle your serial messages. Also have a look at state machines and non-blocking code, to avoid making your "subroutines" block eachothers execution while waiting for a result.
> 2 votes

---
Tags: arduino-uno, bluetooth, hc-05
---


title: smaller program bigger sketch

text:
# Question
Title: smaller program bigger sketch
I'm working on a program composed by several classes.
I reduced the size of a single class of (more or less) one hundred lines (4kb of stuff)
I expected a smaller sketch but surprisingly it is increased in size (few bytes).
How is it possible?It's something about the compiler?

# Answer
> 1 votes
A compiler translates c/cpp to target assembly language.

To keep it short, some c/cpp language statements or keywords can be used to shorten the code (in c/cpp)... but the mechanics behind all that to translate to assembly can generate more instructions than you thought.

It would maybe be easier to explain if you put some example...

---
Tags: compiler, sketch-size
---


title: Sending serial bits in arduino

text:
# Question
Title: Sending serial bits in arduino
I am a newbie in Arduino and serial communication. I am working on a project that use Arduino to send data bits to an actuator using RS232 communication protocol. In order to control the actuator, an instruction consists of 6 bytes must be sent with 9600 baud, no hand shaking, 8N1 format.

Here are the instructions: Byte 1 - Device, Byte 2 - Command, Byte 3 - Data(LSB), Byte 4 - Data, Byte 5 - Data, Byte 6 - Data(MSB)

For example to send 1, 20, 1, 1, 0, 0 (Move the actuator to absolute position of 257 microsteps) This is my draft code. How can I send start and stop bit? I am confused on sending start and stop bit. The Serial.write() is sending binary data as a byte. Does it mean that I write Serial.write(20), the compiler will send the data in 00010100 binary format? I am quite frustrated with serial communication.

# Answer
The start and stop bit are already included as part of the UART protocol. When you send a byte it first sends the start bit, then the byte, then the stop bit. You don't need to do anything to make those bits send.

`20` is actually sent as `0001010001`

So your code will just be a series of `Serial.write()` calls for each byte you want to send.

```
Serial.write(1);
Serial.write(20);
Serial.write(1);
Serial.write(1);
Serial.write(0);
Serial.write(0);

```

Or as an array:

```
uint8_t data[6] = {1, 20, 1, 1, 0, 0};
Serial.write(data, 6);

```
> 4 votes

# Answer
Read the language reference: https://www.arduino.cc/en/Reference/Serial
..and for write(): https://www.arduino.cc/en/Serial/Write
....notice that it "writes" the bytes or buffers you define. You have already defined the baud rate and started the serial channel, then all you need to do is pass the characters or strings you want to send to the write function.

In your application it may be best to build a 6 character command string and send it all at once as a string. You must then remember that With "write" you are responsible for "writing" the cr and lf which is probably needed as a command terminator in your receiving device.

For your kind of application it may also be possible to use "println" which appends a cr/lf automatically for you. It depends on your protocol.
> 2 votes

---
Tags: serial
---


# Question
Title: Receiving message from arduino through wifi
I am new to arduino . I went through the basics . I want to receive message from arduino uno r3 in my laptop(ubuntu) . I have esp8266 wifi module . Arduino and esp8266 connection done . How do I proceed further ?

# Answer
> 0 votes
Download the ESP8266 extension for the Arduino board in Arduino IDE,desktop. Then select the example code for ESP8266, use the Server example. If you wanna access your board outside your home then you need to open a port in your router.

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


# Question
Title: Master doesn't receive the correct values in a master/slave SPI link
I've been struggling for 3 weeks looking for a solution to my problem concerning SPI communication.

So, I need to establish a SPI communication between two Arduino devices: for instance, the master sends a letter 'a' to the slave; the slave receives it and does some processing. In my case, it should set one of his 8 pins to high then read all pins and send the report back to the master.

The part where the master sends 'a' and the slave processing it works fine but the master doesn't seem to receive the correct values. Instead it always receives 0.

Here's the code:

---

# Slave:

```
#include <SPI.h>;

volatile byte command = 0;
byte ett =8; //nbr of test points
byte motif= 0b000000000 ; //intiatition of my varible which will contain my pin's states
byte end[8] = { 2,3,4,5,6,7,8,9}; //array containing the pins

void setup (void) {
  Serial.begin (9600);
  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);
  // turn on SPI in slave mode
  SPCR |= _BV(SPE);
  // turn on interrupts
  SPCR |= _BV(SPIE);
}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect) {
  byte c = SPDR;
  switch (command) {
    //////////////Slave traitement/////////////
    // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  case 'z': ////case 'z", set all pins to INPUT
    for (int i=0; i<8; i++){
      pinMode (end[i], INPUT);
    }
    break;

  case 'a': // //if 'a' : Set one pin to high then read all pin's satete to verify if there is any open circuit or short circuit
    for (int j = 0; j < ett; j++) {
      pinMode(end[j], INPUT);   // set all pins as INPUT
    }
    motif = 0;
    pinMode(end[0], OUTPUT);  // Set one pin as OUTPUT
    digitalWrite(end[0], HIGH); // Set the output pin to HIGH
    Serial.println();
    Serial.print(" ");
    for (int k = 0; k < ett ; k++) { // scan
      if (digitalRead(end[k]) == HIGH) {
        // if pin == HIGH add '1' to my vector
        Serial.print("| ");
        motif = motif + 1; // +1
      } else { // if pin == LOW
        Serial.print(". ");
      }
      motif = motif << 1; // shift left
    }
    Serial.print(" -MOTIF LU= ");
    Serial.print(motif, BIN);
    SPDR = byte (motif); //SPDR is the SPI Data Register: it contains the data that will be sent to the Master
    Serial.print(" ");
    break;
  }
}

void loop (void) {
  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH)
    command = 0;
}

```

# Master:

```
#include <SPI.h>

byte CS0=10;
byte CS1=9;

void setup (void) {
  Serial.begin (9600);
  Serial.println ();
  digitalWrite(SS, HIGH);  // ensure SS stays high for now
  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();
  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);
}  // end of setup

byte transferAndWait (const byte what) {
  byte a = SPI.transfer (what);
  delayMicroseconds (1000);
  return a;
} // end of transferAndWait
///traitement au niveau du maitre

void loop (void)  {
  byte esclave0_testpin0;
  /////////////Set the first slave's pin to High then read all pins
  digitalWrite (CS0,LOW); //activate the slave
  transferAndWait ('a'); // set first slave's pin to high
  esclave0_testpin0 = transferAndWait ('z'); //read all slave's pins and report it in the variable esclave0_testpin0
  digitalWrite (CS0,HIGH); //disactivate the slave
  Serial.println ("test_0");
  Serial.println (esclave0_testpin0, BIN);
  delay (1000);  // 1 second delay
}  // end of loop

```

# Answer
In slave, **command is always 0**. You problably meant:

```
void loop(void) {
    command = (digitalRead(SS) == HIGH ? 0 : 1);
}

```

and at ISR:

```
ISR (SPI_STC_vect) {

    byte input = SPDR;
    byte output = 0;

    if (command) {

        switch (input) {

            case 'a':
                //...
                break;

            case 'z':
                //...
                break;
        }
    }

     // send data back
     SPDR = output;
}

```

As a best practice, avoid to implement the logic within the ISR and use global *volatile* variables to pass state changes to the code in the main loop. Probably you will have to implement a circular buffer to receive from and send to the SPI bus...
> 1 votes

---
Tags: arduino-uno, communication, spi
---


# Question
Title: Using an Arduino and multiplexer for writing to multiple outputs
I'm attempting to use the multiplexer setup in this article with my Arduino Uno to control the output of LED's, as a way to fully understand the principles of multiplexing.

I'm working to modify the code in the article to switch from reading potentiometer values to writing voltage values to the LED's.

Below is the modified sketch; the biggest modified change is the loop in the `writeMux` function:

```
//Mux control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux in "SIG" pin
int SIG_pin = 3;

//Voltage value to write to the LEDs
int testValue = 255;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
}

void loop(){
  for(int i = 0; i < 9 ; i ++){
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[10][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
//    {0,1,0,1}, //channel 10
//    {1,1,0,1}, //channel 11
//    {0,0,1,1}, //channel 12
//    {1,0,1,1}, //channel 13
//    {0,1,1,1}, //channel 14
//    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  analogWrite(testValue, SIG_pin);

  //return the value
  return 0;
}

```

Below is a photo of my circuit:

However, none of the LED's light up.

I'm fairly certain that this is more of a problem with the code rather than the circuit...any advice is appreciated!

# Answer
> 2 votes
According to the analogWrite() documentation, apparently the trouble are that you have swapped the args.

The syntax are `analogWrite(pin, value)`, so, the piece

```
//read the value at the SIG pin
analogWrite(testValue, SIG_pin);

```

may work if you simply change to

```
//read the value at the SIG pin
analogWrite(SIG_pin, testValue);

```

That with respect to code, and i hope it helps you. At the other hand, the circuit, may be a bit dangerous (and can damage the Arduino or the mux) to use LEDs without a current limiter series resistor (330 - 1K Ohm would be nice values, 1/4 W). At least, by a light sight in a datasheet of the CD74HC4067, shows max currents of +/- 25 mA per pin. Similar currents can be driven by the Arduino (Atmega 328P).

So, all depends on the internal construction of the 4067, if are a transparent mux, maybe just with a single resistance in the `SIG_pin` in that range of resistances, would be fine.

**Edit - Some Circuit Troubleshooting**

There are some other little tests that you can do after that change in code:

1. Open the wire that goes from the Arduino to the common of the mux, then place at the output of the same Arduino pin, a LED-resistor series. Then change in program only the value of `testvalue` at the beginning of the code and check if the led changes their intensity according to that. That would be an Ok for that pin of the Arduino.
2. Reply the previous step to each of the channel pins. According to the code, you should see an increasing 1 Hz, 4 bits counter (rather, a BCD counter) in thet formed 4 led array. That would be an OK for the channel selection pins.
3. Remove the leds and connect back the opened lines.

Any fail in steps 1 or 2 may indicate that the pin are damaged but you can use another analog pin and other pins for the channels respectively. But if at step 3 it doesn't works, may be a damaged 4067 or a little hidden bad connection...

---
Tags: arduino-uno, led, analogwrite, multiplexer
---


# Question
Title: How can I split a string into multiple parts?
I currently gather a string via bluetooth to my arduino and the string only has 5 different letters. "HELLO". I now wish to store these individual letters in a string on their own. Right now i have this code:

First I create a single string:

```
String readString;

```

Then I read my BTLEserial which is where I get the value that is being sent to the arduino and i store it in my string:

```
char c = BTLEserial.read();
readString += c;

```

`readString` now has the value "HELLO". Now i want to split it and what I have tried is to do it like this:

```
String stringOne = readString.substring (0,1); //H
String stringTwo = readString.substring (1,2); //E
String stringThree = readString.substring (2,3); //L
String stringFour = readString.substring (3,4); //L
String stringFive = readString.substring (4,5); //O

```

But with this i do not get the correct values in each string.

Appreciate every help I can get! :)

# Answer
> 2 votes
An array is 0 indexed, which means that number 5 is out of index. "Hello" should be index valued 0-4 and not 0-5.

Here is a better code to try out:

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

void loop() {

String recivedMessage = "";

// Read
while (Serial.available())
{
    recivedMessage += Serial.read();
}

// Print debug
Serial.print("recivedMessage: ");
Serial.println(recivedMessage);

//// Uncomment the row under if you are not sure that the splitting is working
// recivedMessage = "Hello";

// Split
char first  = recivedMessage.substring(0, 1)[0];    // H
char second = recivedMessage.substring(1, 2)[0];    // E
char third  = recivedMessage.substring(2, 3)[0];    // L
char forth  = recivedMessage.substring(3, 4)[0];    // L
char fifth  = recivedMessage.substring(4)[0];       // 0

// Print debug
Serial.print("Cut message: ");
Serial.println(first);
Serial.println(second);
Serial.println(third);
Serial.println(forth);
Serial.println(fifth);

```

}

# Answer
> 0 votes
String are the not the recommended way to use with Arduino although try using single parameter instead of two like substring(1) and let me know

```
char data[5];
for(int i=0;i <5 ;i++)
{
 data[i]=Serial.read();
}
char data1=data[0];
char data2=data[1];

```

so on and so forth ..

# Answer
> 0 votes
I think it would be easier if you used a char array. Here's some sample code.

```
char recievedData[100]
int numChars = 0
//Now we are in the receiving loop
recievedData[numChars] = BLTEserial.read()
numChars++

```

Now that you have a character array with all of the members, you can simply use the numChars variable to figure out how much you got from the serial buffer (for example, using it as the upper limit for a for loop).

---
Tags: c++
---


title: Swapping 5V and GND for a 2 wire motor

text:
# Question
Title: Swapping 5V and GND for a 2 wire motor
I have a 2-wire brushed DC motor in a servo housing which either pushes left or right (and "center" when unplugged).

To push to one side I connect a wire to 5V and the other to GND, to push to the other side I just need to swap the wires.

How can I achieve this with the arduino without any physical rewiring?

# Answer
> 3 votes
I think you need arduino motor shield.

Click Here

Just click on above link, you find a good tutorial about arduino motor shield. I hope it might be helpful.

# Answer
> 0 votes
What you want is called a H-bridge, and it is what a standard Arduino motor shield does.

---
Tags: motor
---


# Question
Title: State change in Arduino Using Adafruit display
```
if(menustate == 1310){menustate ++;Serial.println("Execution:");Serial.println(menustate);}
             if(menustate == 1311){menustate ++;if (hr==0) menustate ++;else{aCount++;gpArray[aCount]=hr;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1312){menustate ++;if (minu==0) menustate ++;else{aCount++;gpArray[aCount]=minu;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1313){menustate ++;if (seco==0) menustate ++;else{aCount++;gpArray[aCount]=seco;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1314){menustate ++;if (dates==0) menustate ++;else{aCount++;gpArray[aCount]=dates;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1315){menustate ++;if (months==0) menustate ++;else{aCount++;gpArray[aCount]=years;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1316){menustate ++;if (years==0) menustate ++;else{aCount++;gpArray[aCount]=years;}}
             if(menustate == 1320){menustate ++;}

```

I am trying to get different time inputs from users by using the menustate value , but here in this code the menustate starts from 1311 and without pressing anything the state goes directly to 1320 .and i cant get to the inbetween states

# Answer
> 1 votes
You should use a switch statement ... than after the switch statement you get the in between states:

```
// conditional loop
{

    // prepare for switch (if something is needed)

    switch (menustate)
    {
        case 1310:
            menustate ++;
            Serial.println("Execution:");Serial.println(menustate);
            break;
        case 1311:
            menustate ++;
            if (hr==0)
                 menustate ++;
            else
            {
                aCount++;
                gpArray[aCount]=hr;
            }
            Serial.println("Execution GP:");Serial.println(menustate);
        break;

        case 1312:
            // ...

        default:
            // You can do here things with all other values
    }

    // Here you have the in between states available
}

```

You should put this switch statement in some conditional loop (like until an end state is reached.

---
Tags: programming
---