# Question
Title: Bluetooth not transmitting refreshed sensor values
I have a 9 DOF sensor attached to a BLE chip and Arduino Uno. I want to send the position measurements (i.e. x, y and z coordinates) from the sensor to my iPhone app (Bluefruit LE). The code below starts off well and I am able to see the coordinates on the iPhone. But after showing 6 sets of x-y-z coordinates on the phone all it prints are the x-coordinates. The y and z coordinates do not get shown on the phone at all. I have put the code below (likely not the most efficient code). Any suggestions on how to fix it will be very helpful. thanks in advance.

```
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>
#include <SPI.h>
#include "Adafruit_BLE_UART.h"

/* Set the delay between fresh samples */
#define BNO055_SAMPLERATE_DELAY_MS (100)

#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 2
#define ADAFRUITBLE_RST 9

Adafruit_BNO055 bno = Adafruit_BNO055(55);
Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ,     ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

void displaySensorDetails(void)
{
sensor_t sensor;
bno.getSensor(&sensor);
Serial.println("------------------------------------");
Serial.print  ("Sensor:       "); Serial.println(sensor.name);
Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
Serial.print  ("Max Value:    "); Serial.print(sensor.max_value);
Serial.print  ("Min Value:    "); Serial.print(sensor.min_value);
Serial.print  ("Resolution:   "); Serial.print(sensor.resolution);
Serial.println("------------------------------------");
Serial.println("");
delay(500);
}

/*
Arduino setup function (automatically called at startup)
*/

int x = 0;
int row = 0;
void setup(void)
{
Serial.begin(9600);
Serial.println("Orientation Sensor Test"); Serial.println("");
Serial.println("CLEARDATA");
Serial.println("LABEL,x,y,z");

/* Initialise the sensor */
if(!bno.begin())
{
/* There was a problem detecting the BNO055 ... check your connections */
Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
while(1);
}

delay(1000);

/* Display some basic information on this sensor */
displaySensorDetails();
bno.setExtCrystalUse(true);

BTLEserial.begin();

}

aci_evt_opcode_t laststatus = ACI_EVT_DISCONNECTED;

void loop(void)
{

BTLEserial.pollACI();

/* Get a new sensor event */
sensors_event_t event;
bno.getEvent(&event);

/* Display the floating point data */

Serial.print("X: ");
Serial.print(event.orientation.x, 4);
Serial.print("\tY: ");
Serial.print(event.orientation.y, 4);
Serial.print("\tZ: ");
Serial.print(event.orientation.z, 4);
Serial.println("");

/* This is the code that sends x, y and z coordinates to BLE */
  uint8_t sendbuffernew_x[20];
  char buff_x[20] = "";
  String xorient = "";
  dtostrf(event.orientation.x, 4, 1, buff_x);  //4 is mininum width, 6 is precision
  xorient += buff_x;

  xorient.getBytes(sendbuffernew_x, 20);
  char sendbuffersizenew_x = min(20, xorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_x, sendbuffersizenew_x);
  memset(sendbuffernew_x, 0, sizeof(sendbuffernew_x));

  uint8_t sendbuffernew_y[20];
  char buff_y[20]= "";
  String yorient = "";
  dtostrf(event.orientation.y, 4, 1, buff_y);  //4 is mininum width, 6 is precision
  yorient += buff_y;

  yorient.getBytes(sendbuffernew_y, 20);
  char sendbuffersizenew_y = min(20, yorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_y, sendbuffersizenew_y);
  memset(sendbuffernew_y, 0, sizeof(sendbuffernew_y));

  uint8_t sendbuffernew_z[20];
  char buff_z[20]="";
  String zorient = "";
  dtostrf(event.orientation.z, 4, 1, buff_z);  //4 is mininum width, 6 is precision
  zorient += buff_z;

  zorient.getBytes(sendbuffernew_z, 20);
  char sendbuffersizenew_z = min(20, zorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_z, sendbuffersizenew_z);
  memset(sendbuffernew_z, 0, sizeof(sendbuffernew_z));

delay(1000);

delay(BNO055_SAMPLERATE_DELAY_MS);
}

```

# Answer
> 1 votes
That's an incredibly complex way of outputting a floating point number as a string. You may possibly be fragmenting RAM with your use of String, and those String additions. Try replacing:

```
  uint8_t sendbuffernew_x[20];
  char buff_x[20] = "";
  String xorient = "";
  dtostrf(event.orientation.x, 4, 1, buff_x);  //4 is mininum width, 6 is precision
  xorient += buff_x;

  xorient.getBytes(sendbuffernew_x, 20);
  char sendbuffersizenew_x = min(20, xorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_x, sendbuffersizenew_x);
  memset(sendbuffernew_x, 0, sizeof(sendbuffernew_x));

  uint8_t sendbuffernew_y[20];
  char buff_y[20]= "";
  String yorient = "";
  dtostrf(event.orientation.y, 4, 1, buff_y);  //4 is mininum width, 6 is precision
  yorient += buff_y;

  yorient.getBytes(sendbuffernew_y, 20);
  char sendbuffersizenew_y = min(20, yorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_y, sendbuffersizenew_y);
  memset(sendbuffernew_y, 0, sizeof(sendbuffernew_y));

  uint8_t sendbuffernew_z[20];
  char buff_z[20]="";
  String zorient = "";
  dtostrf(event.orientation.z, 4, 1, buff_z);  //4 is mininum width, 6 is precision
  zorient += buff_z;

  zorient.getBytes(sendbuffernew_z, 20);
  char sendbuffersizenew_z = min(20, zorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_z, sendbuffersizenew_z);
  memset(sendbuffernew_z, 0, sizeof(sendbuffernew_z));

```

by:

```
  char buff[10];

  dtostrf(event.orientation.x, 4, 1, buff);
  BTLEserial.write(buff, strlen (buff));
  dtostrf(event.orientation.y, 4, 1, buff);
  BTLEserial.write(buff, strlen (buff));
  dtostrf(event.orientation.z, 4, 1, buff);
  BTLEserial.write(buff, strlen (buff));

```

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


# Question
Title: How do I make/get a odometer for a lunch box sized robot?
Say I have given the robot a map of the place, it needs to navigate it. I need a odometer to keep track of its current position in the map. I need it to be precise up to a cm.

Can I simply use the motor's RPM and the diameter of the wheel to calculate how much distance the robot has travelled, or is there any catch?

I searched Google and could not find any odometer small enough for my robot. Most of them are for bicycles.

# Answer
> 3 votes
I had the idea to use a computer mouse (optical) to do this - cheap, easily available. You would need two, if you want to be able to measure turning rate, one on the left and one on the right.

You don't even need the whole mouse - if you pull it apart you can ditch the case, the buttons, and about half the circuitry. You will need to do some hacking to figure out how it works, but I doubt you'll find a cheaper odometer that is anywhere near as accurate.

Note: I pulled one apart, then got distracted on another project, but I can't think of a reason why it wouldn't work.

# Answer
> 0 votes
I think the catch is that the wheel will slip, particularly when starting up. The slightest slip and you are counting a rotation that didn't move the robot forwards. Also if it skids when stopping that is more movement that you didn't detect.

You are probably best off with a non-powered wheel (stuck out the side perhaps?) which has the task of only detecting movement. Perhaps put a rubber tire on it to get a good grip. You could connect a rotary encoder to the axle which could count the amount it has turned. There are rotary encoders which do not have friction (eg. optical or magnetic).

If the robot has some non-powered wheels (like a rear wheel) then that could be a good place to measure turns, as it wouldn't slip as much because it isn't under power. You might be able to detect the amount it has turned, for example if it had suitable holes that you could shine a light-detector through.

Alternatively if the area is small enough use a distance sensor (like a sonar) but that probably wouldn't be accurate enough.

---
Tags: arduino-uno, robotics
---


title: Operating Sharp memory LCD with Arduino

text:
# Question
Title: Operating Sharp memory LCD with Arduino
I am trying to write to Sharp memory LCD "LS027B7DH01" which isn't going well for me. I didn't find any useful information for beginners. I just want to display any character on the LCD. Here's my code:

```
#include<SPI.h>

int SCS=10;
int SI=11;
int SCLK=13;
int EXTCOMIN=4;

 void setup()
 {
   pinMode(SCS,OUTPUT);
   pinMode(EXTCOMIN,OUTPUT);
   pinMode(SCLK,OUTPUT);
   pinMode(SI,OUTPUT);
   digitalWrite(SCS,HIGH);
   tone(EXTCOMIN,40);
   SPI.setClockDivider(SPI_CLOCK_DIV16);
   SPI.setBitOrder(MSBFIRST);
   SPI.setDataMode(SPI_MODE0);
   SPI.begin();
   SPI.transfer(0×20);
   delay(3000);
}

void loop()
 {
   SPI.transfer(0×80);
   delay(3000);
   for (byte i=0; i<30;i++)
    {
       SPI.transfer(i+1);
       delay(3000);
      for(int j=0; j<50;j++)
       {
         SPI.transfer(0x0F);
         delay(3000);
       }
       delay(3000);
       SPI.transfer(0×00);
    }
    delay(3000);
    SPI.transfer(0×00);
  }

```

# Answer
As the page Sharp Memory LCD Breakout A2 shows, it seems that you need some additional circuitry to drive the display, such as capacitors and resistors. This is why breakout boards are usually employed. Quoting the page:

> This is a simple breakout board for Sharp’s new Memory LCD displays ( LS013B4DN02 and LS013B4DN04). It brings all pins to a 0.1″ header and provides necessary caps and resistors. The new revision A2 also adds an optional boost converter for those wanting to run 5V display from sub 3.3V supply.The footprints are there, but parts are not populated to save cost. I’ve also added silk labels to the header pins on the back. This is an open design under CC BY SA license.

Of course, you can always make your own breakout circuit. For example, you could reproduce the breakout board using a breadboard and some resistors and capacitors. The schematics are provided on that page for A1

and A2

So, in short, either purchase a breakout board, or make one. Once you have done that , you can use the CraftyCoders Arduino Library

Hope that helps.
> 1 votes

# Answer
I looked at this question as I too plan to drive a Sharp Memory LCD manually with my own code at some point. From your question and comments I think you are going about it the wrong way, even if you are already very proficient with the electronics side of the task.

As mentioned, the breakout board is the easiest way to connect the screen and the library is the easiest way to program it. I suggest you use both *initially* and then replace them one by one. I did this when driving a 32x32 LED matrix.

Once you have a little bit of code running that displays what you want on the screen, try removing the breakout board and wiring the display yourself without changing the code at all. If the display is not what you expect, you know the problem is in the wiring so you don't waste time looking into your code.

Once the wiring is sorted, start on the driver code. Leave the wiring and your code that makes the display show what you want untouched so that you know any problems are in your driver code. The other advantage of this is that you have the working library as reference for how the screen works and what signals to send with what sort of timing.

As a pointer to why your code is not doing what you expect, I *think* you may be misunderstanding how the screen works. Your question and code suggest you may be trying to display ASCII characters on the screen which I believe can be done easily with some LCD displays but I'm fairly sure that these LCDs are not character based - you have to manually set or clear each individual dot. I think the minimum number of dots you can set at a time is a full single line of the display.

In your code you have a delay of 3000ms after every byte send. At that rate it would take 2mins 30secs just to transfer the data for a single line of the screen so maybe you are sending the correct data, but are not waiting long enough to see the results. I've also read that you have to do something (sorry, not quite sure what) at least once per second to prevent problems with the screen - this suggests that taking over 2mins to send a line of data could not work as you expect.
> 0 votes

---
Tags: arduino-uno, lcd
---


title: SimpleAudioPlayer + sleep function

text:
# Question
Title: SimpleAudioPlayer + sleep function
I have tested the SimpleAudioPlayer example.

https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer

This works fine, but when I add a `sleep(1000)` at the end of the `loop()` function, the music sounds dismembered (second run).

```
void loop()
{
    // ... source from the example

    myFile.close();
    Serial.println("End of file. Thank you for listening!");

    sleep(1000);
}

```

Does anyone have any idea on how to resolve this?

# Answer
> 1 votes
`sleep()` is something different. You are probably want to use `delay(1000)` instead.

`sleep()` comes from libsam and is not very well documented for use within the Arduino environment. There is probably a conflicting timer or interrupt between `sleep()` and the `Audio.h` library. So sticking with `delay()` is probably your best option.

---
Tags: arduino-due, audio, sleep, sound
---


# Question
Title: How to send keyboard signals to two separate computers (arduino due)
The arduino due has 2 micro-usb ports that you can connect to two separate computers. I need to send different keyboard signals to each computer. How would I do this?

# Answer
While the Arduino Due has two separate USB ports, only one of them is a native port accessible to the processor. The second port is only usable for programming, and is connected to a different and much smaller chip that handles the programming task.

To connect to multiple computers from an Arduino Due, you have two options:

* You can reprogram the second MCU to allow it to connect to the computer as a keyboard. This method is tricky because it requires an external programmer for it to work.
* You can use a software USB implementation such as V-USB to use regular digital pins to connect to the computer. This is also tricky because it requires a little electronic know how a few extra components to make this work.

Both options require a little something else to make it work, so you will have to pick based on what you feel more comfortable doing.
> 1 votes

# Answer
For one of them, use `Keyboard` as you normally would.

For the other, do whatever Can the 2nd MCU on the UNO R3 be used for keyboard emulation? tells you to do to reprogram the ATmega16U2 connected to the other USB connector.
> 1 votes

---
Tags: arduino-due, keyboard
---


# Question
Title: Digital Potentiometer and Motor Speed Controller
I'm trying to get a Chinese 20A DC Motor Speed Controller working with a MCP42100 Digital Potentiometer. The analogue potentiometer supplied was 100kOhm. I have programmed my arduino with the following code:

```
#define DATAOUT     11
#define DATAIN      12       //not used
#define SPICLOCK    13
#define SLAVESELECT 10
#define NOTEON      9
int potValue = 255;
float potInputValue;

void SPIInitialize()
{
  byte clr;
  pinMode(DATAOUT, OUTPUT);
  pinMode(DATAIN, INPUT);
  pinMode(SPICLOCK, OUTPUT);
  pinMode(SLAVESELECT, OUTPUT);

  digitalWrite(SLAVESELECT, HIGH); //disable device

  SPCR = (1 << SPE) | (1 << MSTR);
  clr = SPSR;
  clr = SPDR;
  delay(10);
}

char SPITransfer(volatile char data)
{
  SPDR = data;                    // Start the transmission
  while (!(SPSR & (1 << SPIF)))   // Wait the end of the transmission
  {
  };
  return SPDR;                    // return the received byte
}

//--- MCP42100 code

byte SetPot(int address, int value)
{
  // Slave Select set low to allow commands
  digitalWrite(SLAVESELECT, LOW);

  // 2 byte command
  SPITransfer(0x10 + address);   // 0x10 = 'set pot' command
  SPITransfer(value);            // Value to set pot

  // Release chip, signal end transfer
  digitalWrite(SLAVESELECT, HIGH);
}

//--- Application code

void setup()
{
  SPIInitialize();          // Initialize the SPI interface

  Serial.begin(9600);
  delay(25);
  Serial.println("Type a resistance between 0-100 kOhms above.");
}

void loop()
{
  if (Serial.available() > 0) {
    // read the incoming byte:
    potInputValue = Serial.parseInt();
    float potValue = (potInputValue / 100.0) * 255;
    Serial.print("Value: ");
    Serial.print(potValue);
    Serial.print(", Resistance: ");
    Serial.print(potInputValue);
    Serial.println(" kOhms");
    SetPot(1, potValue);
  }

}

```

Here is a picture of my setup:

Currently at a resistance of 0 kOhms the motor runs at full speed, as it should do and this is how it reacts with the analogue potentiometer. At a resistance of 100 kOhms, the motor (in this case a computer fan) still has enough juice to spin, until I stop it with my finger, but then it doesn't spin without a little push. With the analogue potentiometer, at 100 kOhms the motor received no juice to spin.

Here is a link to the speed controller: http://www.ebay.co.uk/itm/301366805277?\_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

The speed controller appears to use a 555 timer.

What am I doing wrong with the digital potentiometer to make it so it doesn't behave the same way as the analogue potentiometer?

# Answer
> 2 votes
The MCP42100 does not appear to be an appropriate digital pot for this application.

Without a schematic of the motor controller it is hard to tell, but a good guess would be that the digital pot is seeing voltages higher than the supply voltage you are feeding it, and higher than the **maximum supply voltage** of the digital pot (5.5V; 7.0V abs max). I don't see a voltage regulator on the motor controller board, nor would one be necessary for a low-end design. Probably just a PWM using a 555, as you say.

To make this work you probably need a different type of digital pot - one that can accept logic level inputs and has a higher supply voltage (12V + some margin). You also typically actually have to feed it the higher supply voltage (and be careful that nothing shorts and ruins the micro board).

Otherwise the input protection networks on the digital pot conducts more current than you would expect.

# Answer
> 1 votes
If you look at the MCP42100 data sheet http://www.microchip.com/, on page 4 you will see the details for your unit. Notice that the actual resistance will be in the range of 70k to 130k.

So the reason that you are getting different results is (probably) due to your having a digital pot with a resistance somewhat lower than the physical pot you used.

---
Tags: motor, spi, potentiometer
---


# Question
Title: How much numerical precision can the ESP8266 achieve?
Background: I am trying to port this solar tracker code by Gabriel Miller to run on the ESP8266. Now I'm not a particularly great coder, but I'd like to give it an honest try.

As of recently, the ESP8266 can be natively programmed using the Arduino IDE and code base. Which is pretty convenient.

SO. The solar tracker code written by Gabriel works on the Arduino Uno and the Arduino Mega. The Mega version of the code has a high-precision calculation library called 'BigNumber' to calculate the Sun's position in the sky to a pretty precise degree. My question is:

From what I've read, the ESP8266 is supposed to be a 32-bit microprocessor, so (I assume?) it should be able to handle high-precision numbers without using the BigNumber library; so, how do I check what's the highest numerical precision that the ESP8266 can support? That way I could theoretically just copy the equations over to the ported program rather than having to rewrite the BigNumber library.

# Answer
> 3 votes
I ported the BigNumber library to the Arduino in 2012. The BigNumber library is based almost entirely on the GNU "bc" library. What it does is store numbers with arbitrary precision (ie. as large as you like, and with as many decimal places as you like).

For example, on the Uno you can calculate 3160 like this:

```
3^160 = 21847450052839212624230656502990235142567050104912751880812823948662932355201

```

Or, the square root of 2 to 100 decimal places:

```
sqrt(2) = 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727

```

It's up to you how many decimal places you want. However the trade-off is RAM and speed. The more precision, the more RAM and the slower it is.

A normal precision float (like on the Uno/Mega) has around 7 decimal digits of precision. A *double* float has around 16 decimal digits of precision. See Wikipedia - Floating point.

If the ESP8266 has a C++ compiler then you could probably convert the BigNumber library without too many issues. However if it supports double-precision floats you may not need to.

> How do I check what's the highest numerical precision that the ESP8266 can support?

You may want to ask on the ESP8266 Community Forum \- they may be able to give you a more helpful answer.

---

### Reference

# Answer
> 3 votes
There's not really any difference in numerical precision. What you do get with 32-bit though is *faster* operations on larger data types.

For instance, to add two 32-bit numbers together (uint32\_t) would take many operations on an 8-bit CPY, whereas on a 32-bit CPU it would just take a couple (only one to do the actual addition - a couple to load/save the values to memory).

One key difference, though, is that (to save space) the AVR system has *double precision float* values turned off and aliased to *single precision float* values. This is purely a software feature and has nothing really to do with the hardware. On 32-bit systems that is normally not done, so you can use `double` instead of `float` to increase precision.

However: While `double` is more accurate than `float`, it is still not precise. All floating point values, regardless of precision, are only ever an approximation. For that reason it is often preferred to use *integer* mathematics, and that is where libraries like BigNumber come in handy. They allow you to (as the name suggests) work with much bigger numbers, which is good when dealing with integers when you want a high precision.

For instance, you could measure distance in *km*. Say something is 18.329846283746km away. You could store that as a single precision floating point value and it would end up as 18.329845428467. As a double precision it would end up as 18.3298462837, which is closer, but still not right.

So you could represent it as *meters* instead of *km*. So your 18.329846283746km would be 18329.846283746m.

How about if you represented it as *mm* instead? 18329846.283746mm

Say, why don't we go smaller? Micrometers? 18329846283.746µm

I don't like that decimal point still. What's smaller than µm? nanometers of course! That would be 18,329,846,283,746nm.

Oh look, we have an integer value. However that integer value is too big to fit in a 32-bit number even, which has a maximum of 4,294,967,295. You could try using a 64-bit number (uint64\_t) if the compiler you have supports it, which on both 8-bit and 32-bit systems would need multiple operations to work with (though less on the 32-bit), or you could use a library like BigNumber to deal with it all for you.

By using that method you start out by stating "I want to work in this fixed resolution and I want 100% precision within that resolution", rather than saying "I want to work with these values and I hope you'll get it vaguely right", which is far from ideal.

Also working with integer values is generally considerably faster than working with floating point values unless the CPU has a floating point unit available to do the heavy work for you.

So the difference between an 8-bit and a 32-bit system has nothing to do with the precision that is available to you, but everything to do with how fast operations at different precisions take to perform.

---
Tags: arduino-mega, arduino-ide, esp8266, solar
---


title: Arduino Due for camera control?

text:
# Question
Title: Arduino Due for camera control?
Could one use the Arduino Due to control camera module like OV5642 and send the data to spi device? My project is to capture image with OV5642 and then to send the image data(RGB565) to other device via spi. For this STM32 must be enough, but I'd be happy if I can use the arduino IDE. Because it is much easier to program.

Could you please let me know, if you can use the Due for this task?

# Answer
You are still not giving the full picture, pun intended.

I'll give you an example of what sort of info is missing.

For example, what's the frame rate? What's the color depth of the sensor? If you look at the SAM3x TRM, it says that the SPI is clocked at max 65MHz.

So, the (simplified) math would say:

24bit/pixel * 5Mpixel / 65MHz = 1.846 seconds

And that doesn't even account for acquisition time, so if you do not have fully working DMA on both sides, it's probably even worse. And it will be worse, because you cannot stuff in RAM in one go the entire image.

But maybe that's good enough for you, however it's not possible to say because of the missing info.
> 1 votes

---
Tags: arduino-due
---


title: I have an 'error' with my code

text:
# Question
Title: I have an 'error' with my code
The following code gives me an error:

```
// RFIDunio.h is from http://learn.robotgeek.com/getting-started-guides/39-robot-kits/151-rfiduino.html
#include <RFIDuino.h>

byte    keyTag[5] = {0,0,0,0,0};
boolean noise = false;
byte    masterTag[5] = {37,0,0,127,24};
byte    tagData[5];
byte    tagDatas[5];
boolean verifyKey = false;
boolean mastaKey = false;

void setup()
{
  Serial.begin(9600);
  Serial.println("Welcome to my system!");
}

RFIDuino myRFIDuino(1.2);

void loop()
{
  if(myRFIDunio.scanForTag(tagData == true)
  {
    verifyKey = myRFIDunio.compareTagData(tagData, keyTag);
    mastaKey = myRFIDunio.compareTagData(tagData, masterTag);
    if(verifyKey == true)
    {
      digitalWrite(myRFIDunio.led2,HIGH);
      if(noise == true)
      {
        myRFIDunio.successSound();
      }
      Serial.println("Correct Key!" + " UID = " + tagData[5]);
      delay(250);
      digitalWrite(myRFIDunio.led2,LOW);
    }
    else if(mastaKey == true)
    {
      Serial.println("Programming mode activated!");
      delay(500);
      Serial.println("Please scan a card.");
      myRFIDunio.scanForTag(tagDatas == true)
      delay(1000);
      tagDatas[5] = tagData[5];
      Serial.println("Card has been programmed!");
    }
    else
    {
      digitalWrite(myRFIDuno.led1,HIGH);
      if(noise == true)
         {
            myRFIDuino.errorSound();
         }
      Serial.println("Wrong! " + "UID = " + tagData[5]);
      delay(250);
      digitalWrite(myRFIDunio.led1,LOW);
    }
  }

```

The error is:

```
C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 -IC:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino -IC:\Program Files (x86)\Arduino\hardware\arduino\variants\standard -IC:\Users\*****\Documents\Arduino\libraries\RFIDuino C:\Users\*****\AppData\Local\Temp\build6101268048586666869.tmp\sketch_jul24a.cpp -o C:\Users\*****\AppData\Local\Temp\build6101268048586666869.tmp\sketch_jul24a.cpp.o
sketch_jul24a.ino: In function 'void loop()':
sketch_jul24a:20: error: 'myRFIDunio' was not declared in this scope
sketch_jul24a:20: error: ISO C++ forbids comparison between pointer and integer
sketch_jul24a:21: error: expected `)' before '{' token
sketch_jul24a:55: error: expected statement at end of input
sketch_jul24a:55: error: expected `}' at end of input

```

# Answer
C++ is spelling-sensitive; identifiers need to be spelled the same way each time they are used.
> 0 votes

# Answer
```
if(myRFIDunio.scanForTag(tagData == true)

```

I think you have a bracket missing there.

```
if(myRFIDunio.scanForTag(tagData) == true)

```

Also I think you have spelled myRFIDuino wrong. ni \<-\> in

```
if(myRFIDuino.scanForTag(tagData) == true)

```

And you need a } at the end of your program.

As well, you can't add strings together like you are doing in your Serial prints. Break them up into multiple prints:

```
Serial.print("Correct Key!  UID = ");
Serial.println(tagData[5]);

```

You also have other bits that make no sense at all, such as:

```
myRFIDuino.scanForTag(tagDatas == true)

```

One further thing - that library will never work on Linux, or on MAC OS/X where case sensitivity is enabled on the filesystem. The .cpp file is including a badly named .h file.
> 0 votes

---
Tags: rfid
---


title: LiPo battery charger

text:
# Question
Title: LiPo battery charger
Is it possible to build a battery charger with just an arduino UNO board (and perharps some passive components)?. It's a 3.7V 550 mAh LiPo Battery. I understand I need to monitor the charge and the current flowing into the battery to properly (as in *safely*) charge it.

# Answer
I'll assume that you are trying to charge from a 5V "USB" source.

If you only want to use a UNO + passive components then the hardware intensive method of application note AVR146: Lithium-Ion Battery Charging via USB with ATmega16/32U4 which Ignacio suggests does not meet your need. This is a capable charger but the UNO would not be the major part of it.

**"Normal" charger**

The use of any of the available LiIon charger ICs is an easy and low cost way of adding a charger. These ICs and all related components can cost as little as a few dollars. But ...

**UNO + one resistor very low current charger:**

If using a UNO with no external active parts the current drive rating of the UNO pins limits the maximum current able to be provided. If you **really** want to meet your specification you can achieve a few ten's of mA charge using with a UNO and a few resistors (possibly just one.)

**Super simple good capability charger**

But, a good compromise can be achieved using a UNO (or similar) + one transistor plus a few resistors and capacitors. This can achieve all the usual basic capabilities

* Low current "trickle up" for very low voltage cells
* Constant current charge until Vmax is reached
* Constant voltage charge until I\_cutoff is reached.
* Terminate and stay active until recharge needed.

I will only outline the basic system here. More can be said as and if required.
The main point of note s that in its simplest form the charger uses a linear charging mode so a modest amount of heat needs to be dissipated in the control transistor. Max power dissipation for a A max charge rate would be 2 Watts when the battery was at 3V and full charge was wanted from 5V in.
Power dissipation = (Vin - Vbattery) x Icharge
Worst case here = (5V - 3V) x 1A = 2 watts.
A buck converter could be used (UNO controlled) if desired.

A transistor Q1 connects Vin to battery

Q1 can be PWM controlled by the Uno.

Battery current is monitored by a small resistor Rcur from B- to ground (or in B+ lead)

Vbattery is monitored with an ADC channel (ADC1 or ADC\_V)

Current is measured by measuring voltage across Rcur with an ADC (ADC2 or ADC\_I).

If Rcur is from B- to ground then V Rcur = V ADC2. If Rcur is in B+ lead V across Icur = V\_ADC2 - V\_ADC1.

Q1 on state can be varied by PWM from Uno to control battery current. PWM voltage is smoothed by an RC low pass filter to allow smooth DC control.

**Charging:**

The following steps constitute the standard LiIon charging algorithm implemented by most charger ICs. Variations can be made.

* If Vbat \< 3V set Ichg to Itrickle by PWMing Q1 and reading battery current.

While 3V \<= Vbat \<= 4.2V chg at Imax for battery.

When Vbattery = V-max = 4.2V adjust Ichg with PWM to hold Vbat at 4.2V until Ichg falls to desired fraction of Imax.

Turn off chg voltage fully and monitor Vbat to restart charge at Vbat = Vrestart - maybe 4.0V or as desired.
> 2 votes

# Answer
Yes, it is. AVR146 describes how to charge a battery using a ATmega16U4/32U4 (Leonardo), but there is nothing specific to that chip regarding the actual charging, and the serial communication can easily enough be ported to the ATmega328P.
> 0 votes

---
Tags: arduino-uno, power, battery
---


# Question
Title: Arduino Yun - Problem with bridge and client
I'm using this simple code

```
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

YunServer server;

void setup() {
  Serial.begin(9600);
  Bridge.begin();
  server.listenOnLocalhost();
  server.begin();
}

void loop() {
  YunClient client = server.accept();
  if (client) {
    Serial.println("client");
    process(client);
    client.stop();
   } else {
     Serial.println("no client");
   }
   delay(50);
}

void process(YunClient client) {
  String command = client.readStringUntil('/');
  Serial.println(command);
  if (command == "turnLeft") {
    Serial.println("Gira a sinistra");
  }
  if (command == "turnRight") {
    Serial.println("Gira a destra");
  }
  if (command == "goTo") {
    String value = client.readStringUntil('/goTo/');
    Serial.println(value);
  }
}

```

but it seems to have problem with bridge (or server, or client, i cannot understand) because it only write "no client" on the serial.

I can not understand what is wrong.

# Answer
> 1 votes
Probably too late to answer your question. Your problem is on line

```
if (client)

```

Change it to

```
if(client.connected())

```

which actually returns true when client is connected.

# Answer
> 0 votes
I presume you are wanting the print output to show up on the Serial Monitor but you have connected the Arduino IDE to the Yun via the WiFi port on your network. If this is the case, then change all refs of Serial.print to Console.print This will direct the ASCII text to the Serial Monitor.

---
Tags: arduino-yun, web-server
---


# Question
Title: reversing a micro motor by reversing two pins - one Source and one sink?
can I use this configuration of two pins to run a micro motor ,so I be able to change the polarity of the current (by the code itself-one time out pin1-high out pin2 - low , while next time one low two high!) every time I would like ?(and by changing the polarity OF THE CURRENT to the motor it will revers it) !

Thank's !

# Answer
> 1 votes
```
**Required:**

Drive micro-motor directly from two processor pins.

 - Pin 1 high / Pin 2 low for one direction.
 - Pin 1 low / Pin 2 high for other direction.**

```

This is not a very good idea if it can be avoided but yes, you can operate a motor that way, providing that the motor current is low enough to meet the pin current ratings. It would have to be a very small motor to achieve this.

Take careful note of the current versus voltage drive capabilities of the processor concerned. While a pin may be shown as being able to source or sing 5 or 10 or 20 mA, this is accompanied by a voltage rise for a sink and voltage drop for a source, so at higher currents lower voltages will be available.

A danger is that motor noise may affect the processor.
Placing a small capacitor across the motor will help, and driving the motor through a small resistor from each pin will also help keep noise away from the processor. But depending on the motor used this may not be enough.
The series resistors will drop some voltage and so are limited in maximum allowable size.
The parallel capacitor will slow the direction transition - the larger the capacitor the slower the change.

Using drivers or "buffers" which are higher current rated would allow a larger motor to be driven and would help isolate the processor from the motor noise.

Ask further if any idea here sounds useful.

---

Added: Had a discussion with Gerben (below).
I'd avoided mentioning "catch diodes" but this is an add on that can help.
From each pin add a small Schottky diode\* from pin to Vcc and pin to ground so that all 4 diodes are reverse biased.
(ie Cathode goes to Vcc = line on diode on upper diodes.
Anode goes to ground on "lower" diodes. )
These diodes are usually non conducting. If motor operation or switching causes spikes that rise above Vcc or below ground these diodes will conduct (slightly) before the internal protection diodes do. This is not ideal but can help.
As Gerben notes, when reversing the motor, driving BOTH pins to ground until the motor has stopped and then applying reversing polarity can help. Also driving both high will do the same. There are pros and cons with either method.

---
Tags: power, motor
---


# Question
Title: Use LED on pin 13 again after using the SD library
*The question in short:* On an Arduino UNO or Nano using the SD library, is it somehow possible to use the LED on pin 13 (or any other pin that is used by the library) again after finishing all SD operations?

*Detailed explanation:* In my sketch, during setup() I need to read some data from a file on the SD card, which is being closed again before leaving setup().

Now, I wanted to use the LED on pin 13 during loop() as a status indicator for the user, but it seems that after SD.begin(), pin 13 (and its LED) cannot be used as an OUTPUT anymore.

Here is a minimum sketch to show the behavior. It doesn't matter if I try to turn on the LED right after the call to SD.begin() in setup() or in loop():

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

#define SD_CS  4
#define LED    13

void setup() {
  pinMode(LED, OUTPUT);

  // This still works:
  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);

  SD.begin(SD_CS);

  // This does not work anymore:
  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);
}

void loop() {}

```

# Answer
> 10 votes
It is possible to use the LED on pin 13 again by disabling the SPI bus that is used by the SD library to read/write data to/from the SD card. To disable the SPI bus, simply call `SPI.end()` after closing the file on the SD card.

---
Tags: led, pins, sd-card
---


# Question
Title: Why does my Arduino IDE hang/crash so often?
I've traditionally used a text editor with avr-gcc and makefiles for working with Arduino boards. I'm now trying to develop projects for the wider Arduino user-base, so I am trying to use the Arduino libraries and common IDEs for ease of use.

I started using Stino, but then found out that the Arduino IDE has some toolchain "quirks" that mean I will need to test everything in Arduino IDE expressly.

Since starting to use it more, I have found it frequently hangs or crashes. The triggers for this are:

* Creating a new sketch takes about 15s, and shows me the OS X beach ball.
* Saving a sketch takes about 15s.
* Going to File-\>Examples frequently crashes the IDE - I need to force quit.
* Going to File-\>Sketchbook always crashes the IDE.
* It sometimes randomly hangs.

I don't have any other stability issues and other Java based IDEs like Pycharm work flawlessly.

I have installed numerous libraries, including the entire Teensyduino suite (which is a lot of libraries!). Outside of that, no changes have been made.

Is this a common issue? Is there any logging or anyway I can try and work out what is causing this issue?

This is happening with: \- Arduino 1.05 \- Arduino 1.55

I have tried uninstalling and reinstalling.

# Answer
> 1 votes
## Just report it to Arduino.

You don't really have any other option. I've been waiting to answer this question until I was sure that no one here knew the answer. You don't really have any other option.

This seems like a bug. **We're not Arduino developers or a bug tracking site.** We can only do so much here. Even if it was confirmed a bug and we fixed it, there's only so much that can be done without submitting a report.

---

**BEFORE YOU SUBMIT A REPORT:**

* I'd try copying out the libraries from Arduino. So many libraries might make Arduino IDE somewhat heavier. I don't know if it'll really affect the sluggishness but it's worth a shot.
* The only other thing that I can think of, besides RAM (which you already said wasn't an issue) and the libraries, is some sort of cache/temporary file. Try reinstalling Arduino, even if you haven't, and also I'd try using the beta 1.5.6-r2 version. It has to be pretty stable for it to be the only version that supports the YUN and DUE. Both have been out for a considerable amount of time with this software, so I'd imagine that it's pretty stable minus a few issues.

> Many things are said to have been improved compared to the previous 1.0.5-r2 version.

It'd be stupid not to try the newer version.

# Answer
> 1 votes
For debug and logging you can use the Mac Console app, it will show any errors that come up from the App. You might need to filter for Arduino App related messages though.

---
Tags: arduino-ide, avr-gcc
---


# Question
Title: UNO Timer 1 CTC mode not resetting TCNT1
I'm trying to set up timer 1 to run an isr in CTC mode. no matter what i set OCR1A to it always executes at the same frequency and if i print out TCNT1 I get values higher than OCR1A.

here is my Code

```
    void timer1_init()
    {
    // set up timer with prescaler = 8 and CTC mode
    TCCR1B |= (1 << WGM12)|(0 << CS12)|(1 << CS11)|(0 << CS10);

    // initialize counter
    TCNT1 = 0;

    // initialize compare value
    OCR1A = 100;

    // enable compare interrupt
    TIMSK1 |= (1 << OCIE1A);

      // enable global interrupts
        sei();
    }

ISR(TIMER1_COMPA_vect){
    SET(MOTOR_PORT,LEFT_MOTOR_STEP); //set the pin high
    delayMicroseconds(3); //keep high for a bit
    CLR(MOTOR_PORT,LEFT_MOTOR_STEP); //set it low
}

```

I'm using this to drive a stepper motor so using PWM mode wont work.

# Answer
> 2 votes
It sounds as though timer 1 has not in fact been set to wavegen mode 4. You can ensure that it is by also clearing the other bits of WGM1:

```
TCCR1A &= ~(_BV(WGM10) | _BV(WGM11));
TCCR1B &= ~_BV(WGM13);

```

---
Tags: arduino-uno, interrupt, timers, isr
---


title: Can PWM break a DC motor?

text:
# Question
Title: Can PWM break a DC motor?
I want to know if controlling the speed of a DC motor with PWM could break (burn out the DC motor. Sorry my English isn't that good.

# Answer
Provided that the voltage specs of the motor are not violated, no. However, the inductance of the motor stands a very good chance of destroying the *switch* unless an appropriately-rated flyback diode is used.
> 0 votes

# Answer
Providing that you send the appropriate voltage this shouldn't break your motor. The creator of Arduino suggest this way of driving motor on his book. Source: Massimo Banzi's book : "getting started with arduino" : chapter 5 Advanced Input and Output.
> 0 votes

---
Tags: motor, pwm
---


# Question
Title: Servo motors won't work with motor controller
I have a motor controller controlling two motors, which works perfectly fine when I comment out the two servos in the below code. These two servos are not connected to the motor controller but simply being operated using other Arduino Uno pins, as seen in the code.

When the servo `attach()` functions are included in the code the motor controller only works with one of the motors and the other completely stops working.

I don't understand why the servos are interfering with the motor controller. What's going on here?

```
#include <Servo.h>
Servo myServo1;
Servo myServo2;

int m1_ALI = 10;
int m1_BLI = 9;
int m2_ALI = 3;
int m2_BLI = 11;

int m1_AHI = 12;
int m1_BHI = 4;
int m2_AHI = 6;
int m2_BHI = 5;

void setup() {

  //myServo1.attach(7);
  //myServo2.attach(8);

  pinMode(m1_AHI, OUTPUT);
  pinMode(m1_ALI, OUTPUT);
  pinMode(m1_BLI, OUTPUT);
  pinMode(m1_BHI, OUTPUT);
  pinMode(m2_AHI, OUTPUT);
  pinMode(m2_ALI, OUTPUT);
  pinMode(m2_BLI, OUTPUT);
  pinMode(m2_BHI, OUTPUT);
}

void loop() {

moveForward(30);

}//end loop

void moveForward(int x){

    digitalWrite(m1_AHI, LOW);
    digitalWrite(m1_BLI, LOW);
    digitalWrite(m1_BHI, HIGH);

    digitalWrite(m2_AHI, LOW);
    digitalWrite(m2_BLI, LOW);
    digitalWrite(m2_BHI, HIGH);

    analogWrite(m2_ALI, x);
    analogWrite(m1_ALI, x);
}//end moveForward

```

# Answer
See Servo.cpp:

> Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached. Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four.

Also Servo Library reference

> On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

You are using pins 9 and 10 for your motors.

---

analogWrite uses PWM, the servo library uses PWM, you have a conflict of resources here.
> 2 votes

---
Tags: arduino-uno, programming, motor, servo
---


title: What is Arduino?

text:
# Question
Title: What is Arduino?
Actually I don't know about Arduino, but seeing my fellow classmates, I want to start learning it. Could anybody tell what actually Arduino is about?

# Answer
> 1 votes
---

A popular Arduino - The Arduino Uno:

---

In case I get accused of writing a "link-only" answer ...

The Arduino is a hobbyist prototyping platform, where users can develop projects for microprocessors. Typically the boards have one or two processors on them, can connect to a PC/Mac/Linux by a USB interface, be programmed in C++, and operate external devices (eg. motors, lights, MIDI, LCD screens, LEDs) and take readings (eg. temperature, time, location, voltage).

Different boards have different capabilities, such as the number of I/O ports, the amount of memory, and the size of the program that can be uploaded.

You can connect them to the major operating systems:

* Linux
* Macintosh
* Windows

The hardware and software are open-source, making development for them easy.

---

Image attribution: Sparkfun Electronics

---
Tags: arduino-uno
---


title: Using I2C: Master Reader and Writer

text:
# Question
Title: Using I2C: Master Reader and Writer
I'm using I2C and the Arduino Library (Wire) to communicate between two Arduinos, and my code isn't working. It's supposed to read in an int from the slave, write a value to the slave, then read back that value. I'm expecting "0 4", but i keep getting "0 0". Does this mean that the slave isn't registering the write?

Master code:

```
#include <Wire.h>

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

void ffsis()
{
  //request i
  Wire.requestFrom(2, 1);
  int i = Wire.read();
  Serial.print(i);

  //send n seed
  Wire.beginTransmission(2);
  Wire.write(12);
  Wire.endTransmission();

  Serial.print(" ");

  //request n
  Wire.requestFrom(2, 1);
  int n = Wire.read();
  Serial.print(n);
}

void loop()
{
  delay(100);
}

```

Slave code:

```
#include <Wire.h>

void setup()
{
  Wire.begin(2);
  Wire.onRequest(requestEvents);
  Wire.onReceive(receiveEvents);
}

void loop(){}

int n = 0;

void requestEvents()
{
  Wire.write(n);
}

void receiveEvents(int howMany)
{
  int n = wire.read();
}

```

# Answer
> int n = wire.read();

"Wire" should be capitalized.

Amplifying on Ken's reply, you have two variables called "n", **and** the global one should be declared **volatile**. Also, I2C deals in bytes, not ints, so preferably do this:

```
#include <Wire.h>

void setup()
{
  Wire.begin(2);
  Wire.onRequest(requestEvents);
  Wire.onReceive(receiveEvents);
}

void loop(){}

volatile byte n = 0;

void requestEvents()
{
  Wire.write(n);
}

void receiveEvents(int howMany)
{
  n = Wire.read();
}

```

In addition, the address 2 is a *reserved address*.

> Address 0 is reserved as a "broadcast" address, addresses 1 to 7 are reserved for other purposes, and addresses 120 to 127 are reserved for future use.

You should choose an address in the range 8 to 119.

### Reference
> 1 votes

# Answer
Since you have int n in the receiveEvents function, you're making a new local variable, not using the global n variable.
> 0 votes

---
Tags: algorithm, hardware, i2c, arduino-uno
---


title: Teensy: SPI and Pressure Sensor

text:
# Question
Title: Teensy: SPI and Pressure Sensor
I'm first time working with a Teensy 3.1. I have to connect this (MS5803-01BA: http://www.amsys.de/products/ms5803.htm) pressure sensor via SPI to my Teensy.

My problem is, that I don't have any reliable knowledge on SPI. I read the Wikipedia for it and also the Teensy-Manual.

For the pressure sensor I already got a C-Code but it is only working with the ATMEL ATmega644p microcontroller. I tried to get the code to work with my Teensy, but it seems like I don't get either any input nor any output.

I hope that one of you can help me with the following code and tell me what I'm missing out on. Thank you.

Code:

http://pastebin.com/xaWXfRUR

Datasheet of the pressure sensor:

http://www.amsys.de/sheets/amsys.de.ms5803\_01b.pdf

C-Code for the pressure sensor for the ATMEL ATmega644p microcontroller: http://www.amsys.de/sheets/amsys.de.an520\_e.pdf

---

PS: Please excuse my not perfect English for it's not my native language.

# Answer
Details about SPI at SPI - Serial Peripheral Interface - for Arduino

This isn't right:

```
  SPI.transfer(CMD_ADC_READ); // send ADC read command
  SPDR = SPI.transfer(0x00); // send 0 to read 1st byte (MSB)
  ret = SPDR;
  temp = 65536 * ret;
  SPDR = SPI.transfer(0x00); // send 0 to read 2nd byte
  ret = SPDR;
  temp = temp + 256 * ret;
  SPDR = SPI.transfer(0x00); // send 0 to read 3rd byte (LSB)

```

The SPI library handles SPDR for you. Writing to it yourself will corrupt its behaviour.

It should be more like:

```
  SPI.transfer(CMD_ADC_READ); // send ADC read command
  ret = SPI.transfer(0x00); // send 0 to read 1st byte (MSB)
  temp = 65536 * ret;
  ret = SPI.transfer(0x00); // send 0 to read 2nd byte
  temp = temp + 256 * ret;
  ret = SPI.transfer(0x00); // send 0 to read 3rd byte (LSB)

```

Ditto for elsewhere.
> 1 votes

---
Tags: sensors, spi, teensy
---


# Question
Title: Doesn't work radio transmission from Arduino Uno to Arduino Pro Micro
I have Arduino Uno, Arduino Pro Micro, XY-MK-5V and FS1000A. I need transmit data from Pro Micro to Uno.

Transmitter:

```
    #include <VirtualWire.h>

    void setup() {

      Serial.begin(9600);

      vw_setup(2000);
      vw_set_tx_pin(14);
    }

    void loop() {

      send("Test message!");
      delay(2000);
    }

    void send (char *message)
    {
      vw_send((uint8_t *)message, strlen(message));
      vw_wait_tx();
    }

```

Receiver:

```
#include <VirtualWire.h>

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

    vw_set_rx_pin(12);
    vw_setup(2000);

    vw_rx_start();
}

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

    if(vw_get_message(buf, &buflen))
    {
        for(int i = 0; i < buflen; i++)
        {
            Serial.print(buf[i]);
        }

        Serial.println();
    }
}

```

I dont know why it's doesn't works. When I changed Uno with Micro and Micro with Uno, it's worked.

But I need: Micro + transmitter FS1000A & Uno + receiver XY-MK-5V.

Please help me. I'm using this Pro Micro.

# Answer
> 1 votes
Thanks for your answers. I solved this problem, my Chinese copy has problems with power.

---
Tags: arduino-uno, networking
---


# Question
Title: ATTiny85 Interrupt id vs pin when programming with Arduino
I am using an Arduino Uno with the Arduino as ISP sketch to program an ATtiny85.

I followed this tutorial to set up to program the ATtiny, and successfully got it to run Blink and an interrupt-free version of my program.

I then added an interrupt triggered by a button and got it working on the Arduino Uno (with a software debounce in the ISR). Now I want to run that sketch, with appropriate pin changes, on the ATtiny. Which pins correspond to which interrupt IDs for `attachInterrupt()`?

Or can I not use `attachInterrupt()`? If I can't, how do I do set up an interrupt on an ATtiny85?

# Answer
You can setup interrupts on the Attiny with some different code, but it works the same way. It's important to note that PIN Change Interrupts are triggered at BOTH Rising and Falling Edge

Pins:

Using the Arduino-Tiny Cores

Below is a sample code which used a Pin Change Interrupt on PB1 which switches an LED on and off on PB4.

```
//Includes
#include <avr/io.h>
#include <avr/interrupt.h>

#define INTERRUPTPIN PCINT1 //this is PB1 per the schematic
#define PCINT_VECTOR PCINT0_vect  //this step is not necessary
#define DATADIRECTIONPIN DDB1 //Page 64 of data sheet
#define PORTPIN PB1 //Page 64
#define READPIN PINB1 //page 64
#define LEDPIN 4 //PB4

#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) //OR
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) //AND

/*
 * Alias for the ISR: "PCINT_VECTOR" (Note: There is only one PCINT ISR.
 * PCINT0 in the name for the ISR was confusing to me at first,
 * hence the Alias, but it's how the datasheet refers to it)
 */

static volatile byte LEDState; //variable used within ISR must be declared Volatile.

void setup() {
    cli();//disable interrupts during setup
    pinMode(LEDPIN, OUTPUT); //we can use standard arduino style for this as an example
    digitalWrite(LEDPIN, LOW); //set the LED to LOW
    LEDState = 0; //we use 0 for Low state and 1 for High
    PCMSK |= (1 << INTERRUPTPIN); //sbi(PCMSK,INTERRUPTPIN) also works but I think this is more clear // tell pin change mask to listen to pin2 /pb3 //SBI
    GIMSK |= (1 << PCIE);   // enable PCINT interrupt in the general interrupt mask //SBI

    DDRB &= ~(1 << DATADIRECTIONPIN); //cbi(DDRB, DATADIRECTIONPIN);//  set up as input  - pin2 clear bit  - set to zero
    PORTB |= (1<< PORTPIN); //cbi(PORTB, PORTPIN);// disable pull-up. hook up pulldown resistor. - set to zero
    sei(); //last line of setup - enable interrupts after setup

}

void loop() {
  // put your main code here, to run repeatedly:
  //If you connect a debounced pushbutton to PB2 and to VCC you can tap the button and the LED will come on
  //tap the button again and the LED will turn off.

}

//this is the interrupt handler
ISR(PCINT_VECTOR)
{
  //Since the PCINTn triggers on both rising and falling edge let's just looks for rising edge
  //i.e. pin goes to 5v
  byte pinState;
  pinState = (PINB >> READPIN)& 1; //PINB is the register to read the state of the pins
  if (pinState >0) //look at the pin state on the pin PINB register- returns 1 if high
  {
   if (LEDState == 0)
   {
    digitalWrite(LEDPIN,HIGH); //you can use Arduino Code or LowerLevel Code to write to the register
    LEDState = 1;
    }
   else
   {
    digitalWrite(LEDPIN,LOW);
    LEDState = 0;
    }
  }

}

```

If you're going to be using the ATTiny85, I highly suggest you read through the data sheet to understand better how to program these chips at a lower level of code....It took me a while for it to start to make sense.
> 5 votes

---
Tags: attiny
---


# Question
Title: Remote temperature and humidity sensor with long battery life
I want to build a remote sensor which will measure temperature (range 5-30°C) and humidity (range 20-90%) and provide regularly (in the range of one measurement every minute or tenth of minutes) the measurement via wireless. This sensor will be used indoor, mostly in dark areas.

*Note: measurement could be done every minutes and sending them could be done immediately or in batch of 10 measurements or more).*

I was looking to build this solution using an Arduino, DHT22 sensor and a radio transmitter using ZigBee or Z-Wave protocol, and power it via AA rechargeable batteries. But after studying this solution, I found that it would be challenging to even get **a week of battery life**, this would require using the radio sparingly and to try to use as much as possible the power modes of the Arduino ATmel controller.

That's **not enough**, I want a battery life in the range of several months, 1 month would be "acceptable", **6 months would be the target**, breakthrough would be \> 1 year.

*Note: I don't want wifi, this seems to suck even more power than the other mentioned radio protocol*

# Questions

Is there another more power efficient way to wireless-ly transmit the data?

Or shall I reconsider Arduino all together and look for another more power efficient controller?

Or is there another way?

# Answer
I made a Temperature and humidity sensor - battery powered in 2013. It is powered from 3 x AA batteries, and lasted, as I recall, until a couple of months ago before I changed the batteries. That is, almost two years.

It logs to an SD card every 15 minutes. You could change that interval of course, it would probably not last as long logging every minute.

I certainly wouldn't attempt it with a pre-made board, because of the drain by the power LEDs, the USB chip, the voltage regulator, etc.

I measured 6 µA consumption when asleep.

---

### Schematic

*(RH-click and "View Image" to see a larger version)*

The schematic is deliberately presented as "blocks" of parts of the circuit. To understand it from scratch, make up individual parts, test them and get the code working to your satisfaction. For example, the clock or the temperature sensor.

Some of the parts (like the clock) are already available as pre-assembled boards, if you prefer to reduce soldering.

You could manage without the 7-segment LED readout, however I found it useful for confirming it is working "in the field". The readout LEDs can be purchased cheaply from eBay for around $US 3. Search for `MAX7219 8-Digit LED Display Module 7-Segment` or similar.

---

### Example output

Example of measuring temperature and humidity every minute:

You can see from the graph that I left the room at 9:30 pm, and the temperature slowly dropped until 6:30 am the next morning. The zig-zag effect is the central heating turning on and off.

---

### Construction details

See the linked page for construction notes, schematic, and code.

Power saving details at Power saving techniques for microprocessors.

---

### Estimated life at logging once a minute

If my calculations are correct, logging every minute might reduce battery life to 7 months (these things are best tested of course), but that is because the consumption is much higher when you power up the SD card. It would probably be best to take 15 readings, and then write to the card every 15 minutes. The extra time writing would be minimal, and that would keep the need to power up the card low.

---

### The 7-segment LEDs

To clarify, those 8 LEDs are not normally on. The battery wouldn't last long if they were! If you press the switch it gives an immediate reading through the LEDs, and also tells you how many writes to disk it has done, and how many write errors it has had. This confirms all is operating properly.

The "busy" LED is there to warn you to not remove the SD card while it is writing to it.

---

### Radio communication

To transmit information you could use a NRF24L01 transceiver module. You get those for a couple of dollars on eBay. Example:

Underneath:

You would need another one at the other end to receive (you would need two of whatever radio you chose).

I did a solar powered project using a couple of those. The NRF24L01 uses about 0.9 µA in power-down mode, so that is pretty minimal.

It also uses SPI, so the connections would be very similar to the SD card connector.

I suggest if you are going to attempt this to first get confident with a normal Uno, get the code tested, make sure you have the sleeping/waking going OK, then move it to a low-power board. There are places like Evil Mad Scientist that make "bare" boards, with a prototyping area, which you can use to put things like your temperature sensor on.
> 4 votes

# Answer
There is an excellent article on power reduction at http://www.gammon.com.au/power , but it's definitely worth looking at the parts of your project OTHER than the arduino - that is, your sensor, and your radio. These tend to use much more than your Arduino.

There is some persistent storage on the Arduino - EEPROM - write all your data to that as you read it, then send it all in bulk. Most of the time your radio will spend will be start/end communication.

Making your board is not as daunting as it seems. Use a breadboard to develop & test your project, then use stripboard (aka veroboard) to build your project. You can cut the tracks with a sharp utility knife, or with a specialized stripboard cutting tool (accurate & easier than a knife).

If you are still nervous, find your local makerspace or hackerspace - there are people there that would be happy to teach you to solder, and help you work out your ideas.
> 2 votes

# Answer
Sleep mode of a Zigbee is around 5uA. Power-down mode of an arduino is about the same. You can power the DHT22 via one of the digital pins, so it only uses power if you need it (though I thing you need to give it some time to "warm up"). So I don't see much of a problem. You just need to get the software working right.

Also, don't use an Uno, but one of the more bare-bones boards (e.g. Pro Mini) that don't have an usb-to-serial chip on board. Remove the power-led. Maybe remove the voltage regulator, and use 3 AAs for 4.5V.

I use blank ATMega328 chips, and build my own "arduinos" without all the unnecessary parts. I'm currently working on something similar, and plan on using an CR2032 coincell for power. \>1 Year should be possible as far as I can see. If not I'll switch to AAs (11 times more power).
> 1 votes

---
Tags: power, battery, temperature-sensor, wireless
---


title: Fastest wireless communication

text:
# Question
Title: Fastest wireless communication
Hy guys,

I am currently working on a quadcopter stabilization algorithm for an indoor quadcopter. I now need to setup a wireless communication between my onboard Arduino and my controlling Arduino (and/or RasperryPi (not shure yet)).

My question is: What would be the fastest wireless communication possibility?

I am not worrying about distance; they won't get far apart from eachother. I want to keep a lot of resources on the stabilization algorithm and to keep down resources used for the communication and thus get the fastest communication on very few resources.

What are your opinions and experiences, what is going to be fastest?

# Answer
There is a difference between Wifi and Wireless. Wifi requires an already established network and uses the standard internet protocols. If this is what you mean, then the communication speed would only be influenced by the bandwidth of your network and the speed of the arduinos. I have not been able to find what the speeds of the modules are, but if they are 150 mB/s and your network is only 100, then you'll only get a speed of 100mB/s (which is a pretty decent speed).

If you want wireless (they create their own network using the unlicensed 2.4ghz spectrum, then buy these: nRF24L01+ 2.4GHz. They seem pretty reliable at short distances, and have a low power and high power variant. These have a speed of (at tops) 2 mB/s, but you won't have to worry about having a Wifi connection.

I personally do not know much about Bluetooth modules, so I cannot comment there.

Hope this helped.
> 1 votes

---
Tags: bluetooth, wifi, communication
---


# Question
Title: How to write makefile-compatible sketches?
I'd like to write my sketches so that I can either build/upload them using the Arduino IDE, or optionally using GCC and a makefile.

I know about including the function declarations at the top, but is there anything else to do in order for my sketch to be considered valid C++ by my compiler?

### Update 1

Understanding what the Arduino IDE does to .ino and .pde files is fine, but extraneous to my question, so this is not a duplicate. What I want to know is "how do I write a program such that it is considered valid both by the Arduino IDE **and** g++.

The official(?) makefile available here explains what to do if using the makefile *instead* of the IDE:

```
# The Arduino environment does preliminary processing on a sketch before
# compiling it.  If you're using this makefile instead, you'll need to do
# a few things differently:
#
#   - Give your program's file a .cpp extension (e.g. foo.cpp).
#
#   - Put this line at top of your code: #include <WProgram.h>
#
#   - Write prototypes for all your functions (or define them before you
#     call them).  A prototype declares the types of parameters a
#     function will take and what type of value it will return.  This
#     means that you can have a call to a function before the definition
#     of the function.  A function prototype looks like the first line of
#     the function, with a semi-colon at the end.  For example:
#     int digitalRead(int pin);

```

...but this doesn't explain how use *both* the IDE and a makefile.

### Update 2

I recently found PlatformIO which doesn't answer this question directly, but does automate a lot of the process (generates Scons files for you) and so far I prefer the workflow over both the Arduino IDE and the source+makefile approach. Good support from the authors as well.

# Answer
By gcc/g++ I think you're referring specifically to avr-gcc/avr-g++. Your arduino code probably won't be considered valid C/C++ code because gcc will try to compile with your PC as the target system. Many of the Macros in "WProgram.h" will refer to inaccessible memory on your target system.

Providing you include the header file "WProgram.h" and you build your code with the Arduino Makefile above (which uses avr-g++ not g++), your cpp files should compile and link correctly. Likewise, you will be able to open your Arduino code within the IDE and Verify your code there. The IDE puts in the "WProgram.h" file for you, so technically it would be included twice. However, the include guards will prevent any duplicate code from being compiled.
> 1 votes

# Answer
Generally you'll need to state the `setup()` and `loop()` functions, they are just wrappers of the IDE:

```
void setup() {}
void loop() {}

int main() {
  setup();
  while (1)
    loop();

  return 0; // never reached
}

```

This works both in the IDE and on the command line. As you specify the Board and SerialPort in the IDE, you'll need also to specify both in the Makefile. So you'll end up with two configurations.

Many people leave the IDE because they prefer use different editors or have more configuration options by setting the compiler and linker switches.

To make it really easy, you can use Arduino Makefile. Today starred with 347.

Here an example Makefile:

```
# try: make help
#
include /usr/share/arduino/Arduino.mk
ARDUINO_DIR = /usr/share/arduino
# list boards with: make show_boards
BOARD_TAG = promicro16
ARDUINO_LIBS = EEPROM
# MONITOR_CMD = picocom -b 9600
MONITOR_CMD = moni -config ACM0-9600.cfg
ARDUINO_PORT = /dev/serial/by-id/usb-Arduino_LLC_Arduino_Leonardo-if00
# ARDUINO_PORT = /dev/ttyACM0
# ARDUINO_PORT = /dev/ttyUSB0
OPTIMIZATION_FLAGS = -Os -fexpensive-optimizations -fstrength-reduce
#

```

The '\*.ino' files don't need to be changed and the `Makefile` file is to be placed in the same directory.

Meanwhile I prefer the `Makefile` way, but I still use the IDE for small projects.
> 1 votes

# Answer
> What I want to know is "how do I write a program such that it is considered valid both by the Arduino IDE and g++.

See: How to avoid the quirks of the IDE sketch file pre-preprocessing.

Disregarding for the moment what the Makefile will look like, the simple answer to your question, as discussed in the above link, is to put everything into .cpp and .h tabs in the IDE, and leave the main "sketch" (.ino file) blank. That will still compile under the IDE, and will also therefore be normal C++.

Make sure you start your .cpp files with:

```
#include <Arduino.h>

```

If you use libraries (eg, SPI) you must include them in the main sketch file, which triggers the IDE to copy them into the temporary project build file. The Makefile won't care about that, as you will make sure your Makefile includes all the necessary library files.

Also see my answer here: Classes and objects: how many and which file types do I actually need to use them?
> 1 votes

---
Tags: programming, c++, avr-gcc, gcc
---


title: Self-diagnose components in the circuit

text:
# Question
Title: Self-diagnose components in the circuit
How can I tackle self-diagnosis problem within my Arduino project? For example, I have a temperature sensor and humidity sensor. How can I know if they work or not on Arduino start or inside the sketch loop?

# Answer
You could get your program to output messages to the serial pin on your board, Tx. For example:

```
Serial.begin(9600) //baud rate of 9600

Serial.print("Debug Message");

```

You can use this to print out string and integers. Here is the link to further information on the Arduino website - https://www.arduino.cc/en/reference/serial

If you are already using the Serial pins then you could use the SoftwareSerial Library - https://www.arduino.cc/en/Reference/softwareSerial

This library allows you to make two other pins on your board Tx and Rx. For example:

```
SoftwareSerial mySerial(12,13) //Makes pin 12 Rx and pin 13 Tx

mySerial.begin(9600) //baud rate of 9600

mySerial.println("Debug Message");

```

To read the output from any of the pins on your arduino - use a USB to TTL serial cable. Plug it into your computer and use a program like PuTTY to connect to the serial cable and read the messages coming from the Arduino.
> 2 votes

# Answer
If you can define "it works" in code (e.g. the temperature is between X and Y degrees, and changes no faster than 2 degrees per second), and all you need is a "Yes" or a "No", then you can write this into code, then the easiest way is to use an LED. Make sure you blink it, rather than having it on steadily, so you can tell if it's frozen.

Make sure you try unplugging your sensor, to understand what it does when it fails; this is one thing you specifically want to test for.

If you specifically do not want to do this in your main loop, you can do an interrupt-driven version, but that adds a lot of complexity. I suggest you do it in your main loop if you can.

You can use the current time to blink the light regularly:

```
if (everything_is_working()) {
  if (millis()%10000<1000) {
     <turn led on>
  } else {
     <turn led off>
  }
}

```

The two numbers let you control the flashes. I've used 10,000 and 1,000; this means that out of every 10,000 millis (10 seconds), the led is on 1,000 millis (1 second). Depending on your preference, you can adjust these to your liking. You can also add an else clause which blinks a different pattern depending on what is wrong - 9 seconds on out of 10 for a problem with the humidity sensor, and 5 seconds out of 10 for the temperature sensor having issues.

If your sketch isn't running, the led will stay in it's current state - either on, or off, indefinitely. If your project has no power, the light will obviously be off.

If you want more data, you can either make more complex blink codes - short-long-short-long, for example - or add multiple lights, or even a three-colour LED, with different colours indicating different problems.
> 1 votes

# Answer
Another approach can be handy if you want to do detailed debugging (like outputting numbers) but your serial port is already in use for something, like a GPS. You can use a second Arduino as a "debugging interface" using SPI or I2C. For example, using SPI:

Or via I2C:

In these examples the "debugging" Uno also supplies power to the "main" Uno via the 5 V / Gnd pins.

I have a description about this method on Debugging using SPI/I2C and a second processor. Code is available at: http://gammon.com.au/Arduino/SPI\_Debugging.zip and http://gammon.com.au/Arduino/I2C\_Debugging.zip .

To demonstrate the idea, on the "main" Uno this is an example of sending debugging info via SPI:

```
// make true to debug, false to not
#define DEBUG true

#include <SPI.h>

// conditional debugging
#if DEBUG

  #define beginDebug()  do { SPI.begin (); SPI.setClockDivider(SPI_CLOCK_DIV8); } while (0)
  #define Trace(x)      SPIdebug.print   (x)
  #define Trace2(x,y)   SPIdebug.print   (x,y)
  #define Traceln(x)    SPIdebug.println (x)
  #define Traceln2(x,y) SPIdebug.println (x,y)
  #define TraceFunc()   do { SPIdebug.print (F("In function: ")); SPIdebug.println (__PRETTY_FUNCTION__); } while (0)

  class tSPIdebug : public Print
  {
  public:
    virtual size_t write (const byte c)
      {
      digitalWrite(SS, LOW);
      SPI.transfer (c);
      digitalWrite(SS, HIGH);
      return 1;
      }  // end of tSPIdebug::write
  }; // end of tSPIdebug

  // an instance of the SPIdebug object
  tSPIdebug SPIdebug;

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

```

If DEBUG is true then the debugging prints are activated. Otherwise they turn into "no code".

The receiving end looks like this:

```
volatile char buf [1000];
volatile int inpoint, outpoint;

void setup (void)
{
  Serial.begin (115200);   // debugging

  Serial.println ();
  Serial.println (F("Commencing debugging session ..."));
  Serial.println ();

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // now turn on interrupts
  SPCR |= bit (SPIE);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register
int next = inpoint + 1;  // next insert point

  // wrap-around at end of buffer
  if (next >= sizeof buf)
    next = 0;

  if (next == outpoint)  // caught up with removal point?
    return;  // give up

  // insert at insertion point
  buf [inpoint] = c;
  inpoint = next;  // advance to next

}  // end of interrupt routine SPI_STC_vect

void loop (void)
{
  // insertion and removal point the same, nothing there
  noInterrupts ();  // atomic test of a 16-bit variable
  if (outpoint == inpoint)
    {
    interrupts ();
    return;
    }
  interrupts ();

  // display anything found in the circular buffer
  Serial.print (buf [outpoint]);

  noInterrupts ();
  if (++outpoint >= sizeof buf)
    outpoint = 0;  // wrap around
  interrupts ();

}  // end of loop

```

There is a 1000 byte buffer which will cope with bursts of incoming data, which is then sent out the serial port on the debugging Uno (that is, to your serial monitor).

The linked library above includes code for SPI and I2C debugging interfaces.

---

Having said that, the simplest thing is just to do serial debugging prints inside your code on the main device, if that is practical.

Remember to use the `F()` macro, or your debugging code might take up so much RAM it causes a crash.

eg.

```
Serial.println (F("Temperature sensor working."));

```
> 1 votes

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


# Question
Title: nRF2401 communication (extended vs normal)
Communicating to the antenna-less version from an extended range nRF2401 seems to produce some strange results...

At a distance, the receiver seems to receive a number of values instead of one. For example, if I send a 1, I will receive a 1, but 30 times.

Has anyone had experience communicating across the two models, or is it just best practice to stick to communicating across same models? (Short range \<-\> short range, long range \<-\> long range)?

# Answer
> 1 votes
I've run both version fine together

Your symptom of receiving the same value 30 times would be related to a failed ACK, so the sender thinks it hasn't been received and resends it.

I've had potentially similar problems with the power amplified version running at full power causing interference in nearby circuity, try dialling down the power setting on it.

---
Tags: arduino-uno, arduino-mega, nrf24l01+, arduino-pro-micro, wireless
---


title: Conflict between OneWire and I2C?

text:
# Question
Title: Conflict between OneWire and I2C?
I have two Arduino boards and I want to make them communicate via I2C. The first board (slave) should read a temperature value from a DS18B20 sensor (OneWire) and send it to the second board (master) via I2C.

So, I tried to merge some code from the standard examples (Wire/master\_reader, Wire/slave\_sender and dallas/simple).

When I use the two sketches bellow, the serial monitor of the master board is printing the "hello " message, but when I enable the request temperature lines (slave code)

```
sensors.requestTemperatures();
sensors.getTempCByIndex(0);

```

the serial monitor shows nothing.

I wander if there is a conflict between OneWire and I2C, or if I've made some serious mistakes in the code.

Any suggestions would be appreciated.

# Master

```
#include <Wire.h>

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

void loop(){
    Wire.requestFrom(2, 6);
    while(Wire.available()){
        char c = Wire.read();
        Serial.print(c);
        }
    delay(500);
   }

```

# Slave

```
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(){
    sensors.begin();
    Wire.begin(2);
    Wire.onRequest(requestEvent);
 }

void loop(){
}

void requestEvent(){

    //sensors.requestTemperatures();
    //sensors.getTempCByIndex(0);

    Wire.write("hello "); // respond with message of 6 bytes
}

```

# Answer
> 1 votes
The OneWire stuff can be quite slow. I think I timed doing a temperature read at 12.5 mS which is a long time to be in an ISR. I think you will find that the master assumes it is going to get no response and times out, in that time.

1-Wire Peripheral Interface - for Arduino

What I suggest you do, is get the temperature in the slave, as often as you want, and then just return the temperature when requested. eg.

```
volatile float lastTemp;

void loop(){
  sensors.requestTemperatures();
  float t = sensors.getTempCByIndex(0);
  // protect move of 4 bytes
  noInterrupts ();
  lastTemp = t;
  interrupts ();
}

void requestEvent(){
  Wire.write ((char *) lastTemp, sizeof lastTemp);
}

```

Untested, but that is the general idea.

Documentation about interrrupts, and why I am turning off interrupts when moving the temperature to a global variable: http://www.gammon.com.au/interrupts

# Answer
> 1 votes
If there is a conflict, could the slave switch between i2c and one wire?

I don't know how often your device needs to poll, but if you can get away with, say, once per minute, you could poll at regular intervals, and spend the rest of the time (99%) listening for the master. If it is not polled, the number read could be queued. When the master does manage to connect, it could collect the entire queue quickly.

The master, from it's side, could poll more frequently - say once every 53 seconds. About once or twice an hour, it would fail - it would need to handle that gracefully. No matter, it would get the data next time round. Even failing several times in a row wouldn't be a problem; the data would be queued at the slave for later transfer.

---
Tags: i2c, 1-wire
---


# Question
Title: that no matter what the inputs are Motor1 always moves
```
int motor_forward1 = 7;
int motor_reverse1 = 6;
int motor_forward2 = 5;
int motor_reverse2 = 4;
int motor_forward3 = 3;
int motor_reverse3 = 2;
int sensor1 = A0;
int sensor2 = A1;

 void setup()
{

   pinMode(motor_forward1, OUTPUT);
   pinMode(motor_reverse1, OUTPUT);
   pinMode(motor_forward2, OUTPUT);
   pinMode(motor_reverse2, OUTPUT);
   pinMode(motor_forward3, OUTPUT);
   pinMode(motor_reverse3, OUTPUT);
   pinMode(sensor1, INPUT);
   pinMode(sensor2, INPUT);
 }

 void loop()
 {
   if (digitalRead(A0) == HIGH)
   {
     digitalWrite(motor_forward1,1);
     digitalWrite(motor_reverse1,0);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,1);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,0);
     delay(1000);
   }
   else if (digitalRead(A1) == HIGH)
   {
     digitalWrite(motor_forward2,1);
     digitalWrite(motor_reverse2,0);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,1);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,0);
     delay(1000);
   }
   else
   {
     digitalWrite(motor_forward3,1);
     digitalWrite(motor_reverse3,0);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,1);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,0);
     delay(1000);
   }
   delay(5000);
 }

```

Schematic **here**.

# Answer
The code isn't wrong, it's far too simple to be at fault.

The error is from within Proteus. Those 'pushbutton' switches (and the other switch simulations) are not quite as straightforward as one would like. They have an OFF resistance, usually 100 Megaohms, but that's enough to trick the simulation into not behaving like it should do. You MUST pull the inputs to ground with a resistor - any sensible value will do as it's only required for the *simulation*. As they are, they're in some odd floating/magic/unknown state; common sense does not apply here!

An alternative is to swap the pushbutton for a SPDT switch; connect the common to the Arduino and the other contacts to the 7805 output and ground. You won't need the resistor in this case.
> 1 votes

---
Tags: arduino-uno, motor
---


# Question
Title: Disassembling a RC car for a Arduino Robot
I am looking at making an Arduino robot car. I have a RC car( photos below). I was wondering if I could take the chassis of the car and modify it to make it Arduino controlled, if so how could I do that?(I have an Arduino UNO R3). I would like to make it into a wall avoiding robot. I have never soldered a thing in my life, and I don't own a soldering iron.

# Answer
Sometimes modifying something can be harder than starting from scratch. This is probably one of those cases, but it is over all not too difficult if you have the courage.

Start with a good example, like this robot. It will give you an idea of what hardware you must add to your RC car and how to program the Arduino.
> 0 votes

# Answer
Someone has done exactly this, and written detailed instructions at http://www.instructables.com/id/Autonomous-Control-of-RC-Car-Using-Arduino/

Some remote control devices (usually not the really cheap ones, like the one shown here) will have a standard transmitter/receiver. See http://www.alibaba.com/product-detail/3-channel-radio-control-receiver-box\_311659816.html for a picture of the receiver. If you can find this in your remote control device, you should be able to unplug it, and replace it with an Arduino. You will need the "Servo" library - see https://www.arduino.cc/en/reference/servo

You can probably get away without soldering - you will probably need to strip some wires, and you can use crocodile clips, and/or breadboard jumpers to connect everything up. It won't be pretty.

If you want to learn to solder (I know it's intimidating, but it's not so bad) I recommend that you find a local hackspace/makerspace, and find someone there - they will probably be more than happy to teach you. They probably have everything you need, be nice to them, and if you want them to continue, join up & pay regular subs. And take every opportunity to teach the skills you have to anyone else who asks for help.
> 0 votes

---
Tags: arduino-uno, robotics
---


# Question
Title: Why does my servo twitch and turn on its own?
I've been trying to write a very simple program using Arduino to tell a servo to go to a specific angle when a button is pressed, and to another specific angle when it is released. I find that, even though my sketch is but the simplest possible if then else statement without anything added to it, the servo goes to the right angle when the button is pressed, but when it is released, the servo oscillates between the two specified angles at a regular rate (about once every second). What's even stranger is that when i add delay time to the end of the loop in my sketch, the oscillation becomes more like twitching, and the more delay i add the weirder and less predictable the twitching becomes.

**added info**

```
#include <Servo.h>
Servo Servo1;
int const switchPin = 4;
int switchState = 0;
void setup()
{
    Servo1.attach(11);
}

void loop()
{
    switchState = digitalRead(switchPin);
    if (switchState == HIGH) {
        Servo1.write(40);
    } else {
        Servo1.write(70);
        delay(39);
    }
}

```

the power supply is the regular usb connector plugged from the board to my computer. The circuit is virtually similar to the "mood cue" project on the arduino projects book, except there is a button connected to digital pin 4 instead of a potentiometer.

# Answer
> 3 votes
If it does what you expect when the button is pressed, but behaves unpredictably when released, you almost certainly have a floating input.

See Switches tutorial.

In particular, this is a no-no:

Random fluctuations in voltages will make the switch read HIGH and then LOW, and your servo will chase around trying to change positions.

The simplest fix (without changing anything else) is to add a pull-down resistor between the pin and ground, so now the pin reliably reads LOW when not pressed.

Other methods are discussed on that page, including debouncing.

# Answer
> 1 votes
I'm assuming you do not have a potentiometer hanging out of the servo motor its self.

2 things i could see here, without seeing the actual circuit itself.

1- The inputs are left floating therefore the input is thinking it sees a high state when you never push the button due to electrical noise. To fix this add a 10k Resister to ground on pin 4 while the switch is wired to 5v/3.3v on one side and the other side going into pin 4. This will fix noise going into pin 4.

2- Power supply on board is overheating or lack of power since computer usb port has a max power of 500mA. Use an external power supply to the servo and connect power supply ground to the board's ground to have a common ground.

# Answer
> 1 votes
I see two potential issues in your code.

1. There is no button debouncing in your code: this means everytime you push the button down or up, the `digitalRead()` call will return `HIGH` and `LOW` several times until the signal is stabilized; that could make the servo twitch as you observed.
2. For any call to `servo.write()`, you need to give time to the servo to reach the desired position, typically a few dozen milliseconds.

For the first problem, google for arduino button debouncing and you'll find various solutions for it.

For the second issue, you just need to add `delay()` after every call to `servo.write()`; note that in your code you added `delay(39);` but only for one call to `servo.write()` not for both calls.

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


title: LIght bulb to light up

text:
# Question
Title: LIght bulb to light up
I'd like to write a JavaScript function that lights up an led light for X milliseconds depending on the response from the JavaScript function.

```
function HowManySeconds() {
   setTimeout(HowManySeconds,5000)
   return 1000
}

```

The JavaScript function will come from a website, so I suppose I would need an Internet enabled device that connects to my router and can 'browse' to my website.

Q: What do I need to buy? A tessel? An Espruino?

# Answer
> 1 votes
You could try the intel galileo or the intel edison with arduino shield. They can be programmed with a variant of the arduino ide, but it is possible to call also programs from the native linux os. Or you could have a look at the esp826. At least on the edison it is possible to run node.js, while the esp supports lua.

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


# Question
Title: Want to add an LCD display screen for the output motor
I want add an LCD display screen at output motor. When the motor runs the LCD display show like "motor 1 run forward" and "motor 1 run reverse". I want it display for all motor but I don't know how code using arduino using 16x2 LCD display screen.

```
int motor_forward1 = 7;
int motor_reverse1 = 6;
int motor_forward2 = 5;
int motor_reverse2 = 4;
int motor_forward3 = 3;
int motor_reverse3 = 2;
int sensor1 = 13;
int sensor2 = 12;

 void setup()
{

   pinMode(motor_forward1, OUTPUT);
   pinMode(motor_reverse1, OUTPUT);
   pinMode(motor_forward2, OUTPUT);
   pinMode(motor_reverse2, OUTPUT);
   pinMode(motor_forward3, OUTPUT);
   pinMode(motor_reverse3, OUTPUT);
   pinMode(sensor1, INPUT);
   pinMode(sensor2, INPUT);
 }

 void loop()
 {
   if (digitalRead(13) == HIGH)
   {
     print
     digitalWrite(motor_forward1,1);
     digitalWrite(motor_reverse1,0);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,1);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,0);
     delay(1000);
   }
   else if (digitalRead(12) == HIGH)
   {
     digitalWrite(motor_forward2,1);
     digitalWrite(motor_reverse2,0);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,1);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,0);
     delay(1000);
   }
   else
   {
     digitalWrite(motor_forward3,1);
     digitalWrite(motor_reverse3,0);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,1);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,0);
     delay(1000);
   }
   delay(5000);
 }

```

# Answer
> 1 votes
From this instructable:

```
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print(" **Text for line 1 of LCD**");
  lcd.setCursor(0, 1);
  lcd.print(" **Text for line 2 of LCD**");
  // THE REST OF YOUR SETUP
}

void loop() {
    if (digitalRead(13) == HIGH) {
        // I assume this is the motor going forward
        lcd.print("motor 1 run forward");
    }
}

```

---
Tags: arduino-uno
---


# Question
Title: Good tips for how to connect cables into Mux Shield II?
I just got a Mux Shield 2 and got it working as I expected. Now I started to find out how to actually connect the I/O cables to the board. Doesn't seem to be as simple as I thought. I don't want to solder cables into the board for maintenance reasons. So, does anyone have any good tips on how to do this?

# Answer
Solder 100-mil male headers onto the board, then use 100-mil crimp terminals to connect the wires.
> 1 votes

---
Tags: hardware, wires, multiplexer
---


# Question
Title: Powering 30+ LEDs and flickering one at random
I'd like to power 30+ LEDs, while having a single LED (at random) flicker every 10-15 seconds.

Is this possible to do using an Arduino? I totally new to this so please bear with me.

This is the type of flicker effect I'm hoping to achieve: https://www.youtube.com/watch?v=753-lkao8l0

Many thanks

# Answer
Yes, it is possible, but it's harder than making one LED light up, and then doing the other 29 the same.

An LED typically draws 20mA, which is within the limit for an Arduino pin (40mA); however, there is also a 200mA limit for all pins together, so you cannot power more than 10 LEDs off the same arduino. Also, the Arduino only has 13 digital pins, and 5 analog pins, a total of 18 pins. This includes 2 pins used for programming your Arduino.

If you want to run lots of LEDs, the easiest way is running it through an external chip. You can buy a pre-made board e.g. https://www.adafruit.com/products/1429 (24 channel, these can be daisy-chained together for more than 24 LEDs).

Alternatively, you can save yourself some money if you can just buy the chip - a DIP chip, or through-hole, will slot directly into a solderless breadboard, and can be soldered onto veroboard later to make your project more permanent.

There are a number of chips that will do the job, you want an "LED PWM driver" chip - for example, the TLC5940. There is a tutorial for this at http://tronixstuff.com/2013/10/21/tutorial-arduino-tlc5940-led-driver-ic/ \- PWM just means you can control the brightness of each LED (individually).

If you want to make your project more permanent, you can solder a board of your own - find someone who can solder (your local makerspace/hackspace will be glad to help, I'm sure!) to teach you the basics, don't burn yourself. The easiest way is to use stripboard (aka Veroboard), this also means you can solder the resistors on to the same board (the LEDs too, if you like!). It sounds very intimidating, but it's not hard to learn. You can then buy PWM chips (make sure you get through-hole, aka "DIP" chips - https://en.wikipedia.org/wiki/Dual\_in-line\_package ) rather than "surface mount" chips. The chips are sensitive to heat, so to start you might want to solder on sockets (see same wiki page), then you can slot the chips in later.

You should consider very carefully your power supply - find out how many milliamps (or amps) it can provide - every (lit) LED will draw 20 milliAmps, and the Arduino is rated for 200mA, so if you want more than 9 LEDs, you will want an external power source, with an appropriate rating - 500mA = 0.5 amp will drive 24 LEDs. In this case, do NOT use the 2.1mm jack on the Arduino to power it; the transformer will overheat.

P.S. - you will be able to control the exact brightness of each LED independently. Also, if you use RGB leds, and use 3 pins on the IC to drive each LED, then you will be able to control the exact colour of each LED too!

Good luck!
> 1 votes

# Answer
I've successfully set up a flickering test with 32 LEDs, based on Using a 74HC595 output shift register as a port-expander.

Demo of the overall speed (but not the flickering effect): Vimeo - Shift Register Demo with 32 LEDs

That uses 4 x 74HC595, 32 LEDs, and 32 resistors, plus some decoupling capacitors.

Test sketch which *does* flicker one and leave the rest alone:

```
#include <SPI.h>
const byte LATCH = 10;
const byte numberOfChips = 4;
byte LEDdata [numberOfChips];  // initial pattern

void refreshLEDs ()
  {
  digitalWrite (LATCH, LOW);
  for (byte i = 0; i < numberOfChips; i++)
    SPI.transfer (LEDdata [i]);
  digitalWrite (LATCH, HIGH);
  } // end of refreshLEDs

void setup ()
{
  SPI.begin ();
}  // end of setup

void showPattern (unsigned long patt)
  {
  LEDdata [0] = patt & 0xFF;
  LEDdata [1] = (patt >> 8) & 0xFF;
  LEDdata [2] = (patt >> 16) & 0xFF;
  LEDdata [3] = (patt >> 24) & 0xFF;
  refreshLEDs ();
  } // end of showPattern

const int whichFlicker = 12;  // which LED to toggle
unsigned long pattern = 0xFFFFFFFF;  // pattern for other LEDs

void loop ()
{
  pattern ^= 1UL << whichFlicker;
  showPattern (pattern);
  delay (100);
  pattern ^= 1UL << whichFlicker;
  showPattern (pattern);
  delay (20);
}  // end of loop

```

The flickering is quite fast, but it isn't PWM. If you make the delays lower, the flickering just becomes a duller light, so I think by getting the timing right you could get flickering going fine.

The wiring (in part) is:

The rest is similar. Of course, you need current-limiting resistors for the LEDs (one each).

You can get the 595 chips from eBay for around $US 1.70 for 20 of them. LEDs are cheap. Resistors are cheap.
> 1 votes

# Answer
The other answers use other components to achieve more LEDs. Part of an led is its a diode. You can use this property to link 2 LEDs together and use a high or a low signal to light one. This has a limitation that you can't light both at the same time. But with lighting both for 50% of the time with a short time between each cycle will illuminate both of them. ( though obviously not as bright as if they were powered 100% of the time. )

This idea can be extended into a grid to get more LEDs per pin

Though not an ardiuino its the same chip using the technique mentioned here

http://www.nerdkits.com/videos/ledarray2/
> 0 votes

# Answer
Here is an example of a project that simultaneously drives 40 individually controllable LEDs directly connected to an ATTINY...

http://ognite.com

The same technique would also work directly connecting LEDs to the Arduino IO pins.
> 0 votes

---
Tags: led
---