# Question
Title: Controlling EL wire or panels with arduino
I understand that el wire and paper needs a special power source known as an inverter to light it up.

If I wanted to control it from an arduino, what point would I connect the arduino to the light or inverter?

# Answer
> 3 votes
## upstream slow blinking

The simplest approach: Use a relay to turn the lights on and off. Control that relay with an Arduino. ("How to turn a relay on and off with an Arduino?" is a separate question).

Cut either one of the wires feeding power into the EL inverter ("upstream of the inverter"), and connect the 2 cut ends of the (formerly) one wire to the contacts of the relay.

```
power source ---- (relay contacts) ---- EL inverter ---- (EL wire)
           +--------------------------------+    +---------+

```

## downstream slow blinking

Alternative approach: Use at least 2 pieces of EL wire. Wire one always-on; use a relay to connect or disconnect the other wire ("downstream of the inverter"). (The relay and controlled wire can be either directly connected to the inverter, or end-to-end connected to the always-on wire -- it doesn't matter for this application).

```
                                   always on
power source ---- EL inverter ---- (EL wire) ---- (relay contacts) ---- (EL wire)
           +----------+    +---------+   +-------------------------------+

```

Control that relay to control the EL wire with an Arduino, same as before.

## dimming and PWM

Many low-cost relays are rated for only about 10,000 operations, so if you use them to blink for a long or short part of each second, they're only guaranteed to last for about 3 hours. If you want to blink faster than that (and most people dim EL lights by blinking them *much* faster than that), you'll have to use something other than a relay.

Also, most people seem to want to do the switching "downstream" of the inverter, so they can "share" a single EL inverter and use it to power lots of independently controlled pieces of EL wire.

Perhaps the simplest approach is to use an off-the-shelf zero-crossing solid-state relay (SSR). ("How to wire a SSR to an Arduino?" is a separate question).

```
power source ---- EL inverter
          +-----------+   | |
                          +----- EL wire (always on)
                          | +-----+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          ... etc.

```

Because most SSRs are overkill for this application -- most of them have heatsinks bonded to high-power triacs designed to handle far more current than we need to light up a EL wire -- some people save a few dollars by assembling their own SSRs out of zero-crossing optocouplers, triacs, etc. (A lower-cost, low-power triac is more than adequate for controlling EL wire, even without a heatsink).

The SparkFun EL Escudo Dos Arduino shield for controlling electroluminescent wire(c)(d); Diana's SparkFun EL Sequencer(e)(f)(g); the seeedstudio EL Shield(h)(i)(j)(k); Tully Gehan's Cool Neon Arduino Shield(m) etc. uses such zero-crossing optocouplers, triacs, etc. (requires a separate EL inverter).

According to some people on the Arduino forums talking about EL wire(n)(p), some people save a few pennies by using normal optocouplers rather than zero-crossing optocouplers. Non-zero-crossing optocouplers seem to work fine for short pieces of EL wire but seems to destroy the triacs (failing "always on") with a few dozen feet of EL wire.

Some people save a few more pennies by skipping the optocoupler, wiring the Arduino directly to the control gate of the triac, and the VCC pin of the Arduino directly to the MT1 pin of the triac. (q) (r) (s) (t) If there were some way to only turn the triac on near the zero-crossing, this could work great; but without zero-crossing control, this has the same problems as the above normal non-zero-crossing optocouplers.

## always-on

The "extra" always-on bit of EL wire is because some people say "never run the inverter without at least 1 foot of EL attached"(a) because running some EL inverters with no load "can damage the inverter"(b).

# Answer
> 0 votes
You could connect the Arduino to the light using a relay or any electronic switches (transistors and etc) that can take around 10 to 15mA per meter (so its distance dependent). You could use this link https://learn.adafruit.com/el-wire/soldering-to-el-wire to find out where to solder the switch connections to

# Answer
> 0 votes
For a simpler option, there are Arduino shields for controlling El Wire. Sparkfun makes a couple and they have some sample code and projects.

https://www.sparkfun.com/products/10878

---
Tags: arduino-uno
---


title: Wiring Issues with Sparkfun Oled

text:
# Question
Title: Wiring Issues with Sparkfun Oled
I'm attempting to hook up an arduino uno with a Sparkfun Oled. I downloaded the example program and made these changes:

```
#define PIN_RESET 3  // Connect RST to pin 3
#define PIN_DC    4  // Connect DC to pin 4
#define PIN_CS    10 // Connect CS to pin 10
#define DC_JUMPER 0

```

I connected everything according to Sparfun's walkthrough. I also wired accordingly. However, I cannot seem to get the Oled to do, well, much of anything. I have tried switching the MOSI and MISO to see if that makes a difference, but it doesn't seem to have any effect.

I'm using: pin 13 - clock (in the picture I was trying pin 8 for the clock but I have tried both)

pin 12 - MISO

pin 11 - MOSI

pin 10 - CS

pin 4 - DC

pin 3 - RESET

Can anyone tell me what's going wrong? I've tried to figure it out for a good long while now and I can't make the display do anything productive.

Thanks

# Answer
Have you connected the `GND` pin from the `UNO` to the breadboard? I can't hardly tell. But it looks like you are also using 5V to power it?

How are you powering the `UNO`? Is it just 3.3V? I'm powering mine with a 5V but have level converters connected.

Mine:
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Compile problem when using keyword 'new' on Raspberry Pi
I have the following line of code in my Arduino sketch:

```
static double *temps = new double[arraySize];  //Declare array to hold tempratures, place the array on the heap where it will not be deleted and keep the pointer as a static
//double temps[arraySize];

```

When I compile with the Arduino IDE on Ubuntu it compiles just fine. However, when I compile on the Raspberry Pi, it throws up the following error:

```
xxx.cpp.o: In function `last Function in file()':
xxx.cpp:[last line in file]: undefined referance to `operator new[] (unsigned int)'
collect2: error: ld returned 1 exit status

```

Is this a bug? If so, how do I report it? If not, why is it throwing this error or how else can I declare a static array of doubles (needs to be static, I calculate an average of some incoming data over several function calls)?

# Answer
The Arduino uses AVR libc which does not provide a complete C++ environment.

Among other things AVR libc does not support `new` and `delete`. See the FAQ for more information.

Some versions of the Arduino libraries may provide new and delete but they are just wrappers around `malloc` and `free`. I suggest not using new and delete on arduino because they do not have the same behavior as C++. For example destructors will not be called on the arduino when delete is called.
> 3 votes

# Answer
> how else can I declare a static array of doubles (needs to be static, I calculate an average of some incoming data over several function calls)

When you find a bug in the Arduino software, please do report it to the appropriate place -- http://arduino.cc/en/Main/ContactUs has the contact details.

One way to declare a static array of doubles is like this:

```
double boxcar_average(double new_sample) {
  const int arraySize = 3;
  static double old_sample[ arraySize ] = {0};
  double sum = new_sample;
  for(int i=0; i<arraySize; i++){
    sum += old_sample[i];
  }
  old_sample[0] = old_sample[1];
  old_sample[1] = old_sample[2];
  old_sample[2] = new_sample;
  return( sum / 4 );
}

```
> 0 votes

---
Tags: c++, linux
---


title: Understanding Digital IMU 6DOF sketch

text:
# Question
Title: Understanding Digital IMU 6DOF sketch
I am looking at the following code and getting confused by a few elements in it:

1) Why is there a writeto function being performed to the memory locations x053,0x31,x09 for accelerometer and 0x68,0x16 and 0x1A for gyro? We are only reading incoming values so what is the purpose of these functions?

2) the bitwise operation being performed in the getGyrscopeReadings and getAccelerometerReadings... are these operations to define how many bits data we will be reading?

```
    #include <Wire.h> //The I2C library

int gyroResult[3], accelResult[3];

//Function for writing a byte to an address on an I2C device
void writeTo(byte device, byte toAddress, byte val) {
  Wire.beginTransmission(device);
  Wire.write(toAddress);
  Wire.write(val);
  Wire.endTransmission();
}

//Function for reading num bytes from addresses on an I2C device
void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

//Function for reading the gyros.
void getGyroscopeReadings(int gyroResult[]) {
  byte buffer[6];
  readFrom(0x68,0x1D,6,buffer);
  gyroResult[0] = (((int)buffer[0]) << 8 ) | buffer[1]; //Combine two bytes into one int
  gyroResult[1] = (((int)buffer[2]) << 8 ) | buffer[3];
  gyroResult[2] = (((int)buffer[4]) << 8 ) | buffer[5];
}

//Function for reading the accelerometers
void getAccelerometerReadings(int accelResult[]) {
  byte buffer[6];
  readFrom(0x53,0x32,6,buffer);
  accelResult[0] = (((int)buffer[1]) << 8 ) | buffer[0]; //Yes, byte order different from gyros'
  accelResult[1] = (((int)buffer[3]) << 8 ) | buffer[2];
  accelResult[2] = (((int)buffer[5]) << 8 ) | buffer[4];
}

void setup() {
  Wire.begin();            //Open I2C communications as master
  Serial.begin(9600);    //Open serial communications to the PC to see what's happening

  writeTo(0x53,0x31,0x09); //Set accelerometer to 11bit, +/-4g
  writeTo(0x53,0x2D,0x08); //Set accelerometer to measure mode
  writeTo(0x68,0x16,0x1A); //Set gyro to +/-2000deg/sec and 98Hz low pass filter
  writeTo(0x68,0x15,0x09); //Set gyro to 100Hz sample rate
}

void loop() {
  getGyroscopeReadings(gyroResult);
  getAccelerometerReadings(accelResult);

  Serial.print(gyroResult[0]);
  Serial.print("\t");
  Serial.print(gyroResult[1]);
  Serial.print("\t");
  Serial.print(gyroResult[2]);
  Serial.print("\t\t");
  Serial.print(accelResult[0]);
  Serial.print("\t");
  Serial.print(accelResult[1]);
  Serial.print("\t");
  Serial.print(accelResult[2]);
  Serial.print("\n");

  delay(50);
}

```

any help would be greatly appreciated!

# Answer
**The `writeTo` functions**

The accelerometer and gyro both have some memory inside that is used to store the configuration. The specific locations and values can be read from the datasheet, but for now I'll trust the comments. These writeTo functions seem to set the device modes and configure the scale used for the sensors.

Notice that they only happen once, right when the program starts. Maybe the devices have a way of storing persistent settings onboard, but setting them once at each startup is safe and easy.

**The Bitwise ops**

These don't set the number of bits we are reading *per se*, They reconstruct larger than 8-bit values. The I2C serial protocol is set up to use 8-bit data segments, so to send any value larger than 8-bits they must be broken down, sent, and then "stitched" back together in chucks.

`(((int)buffer[0]) << 8 ) | buffer[1];`

Whats happening here is that `buffer[0]` is converted to int (a 16 bit value), then shifted over by 8 bits. This means the 8 bits in the original `buffer[0]` are now located in the top 8-bits of the integer, and the lower 8 bits are zeros. Finally the lower 8 bits are set by the bitwise-or operator `|`, which will turn on any bits that were set in `buffer[1]` in the result. Since the bottom 8-bits were 0's from the shift, this just copies `buffer[1]` in exactly.

The net effect is a 16 bit value that contains the bits of both 8-bit buffer values and can be interpreted as a single number.
> 2 votes

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


# Question
Title: Adafruit motorshield disconnected but getting current from Arduino
my Adafruit motorshield is getting current from Arduino board even after disconnected from battery. I was planning to give separate dc power from 6 AA cells to motor shield but not sure if extra current will enter into Arduino and damage it. I have Ultrasonic sensor connected to motorshield which is getting +5v from board (may be Arduino).

Please suggest how to solve this problem.

Thanks

# Answer
If all else fails, read **The Manual**

**The manual indicates that it is intended that the MS electronics may be operated by the Arduino power supply while using a separate external supply for the motor.**

Pages 37 to 39 explain about powering options.
The Arduino and the shield interconnect all of : 3V, 5V, Vin.
3V may not be used by the shield.

Arduino Vin to MS V+ is broken by jumper "PWRJMP" - purple rectangle in diagram below.
Arduino 5V to MS Vcc is not interrupted by a jumper - See labels in red squares below.

---

You did not say what version shield you had or which Arduino or what you mean by "disconnected from battery" or supply any links to relevant documents. ALL of these things will help people to help you better.

Assuming latest MS version,

adafruit motor shield v1.2 \- discontinued.

github v1.2 schematic this appears to be pre V2 BUT is linked to from a ference in the V2 manual so is probably "more or less correct".

**adafruit motor shield v2 manual** \- **probably what you have**

adafruit current MS page

This probably tells you what you need to know. Manual page 37-38

* How to set up the Arduino + Shield for powering motors

Servos are powered off of the same regulated 5V that the Arduino uses. This is OK for the small hobby servos suggested. If you want something beefier, cut the trace going to + on the servo connectors and wire up your own 5-6V supply!

**The DC motors are powered off of a 'high voltage supply' and NOT the regulated 5V.**
Don't connect the motor power supply to the 5V line. This is a very very very bad idea unless you are sure you know what you're doing!

There are two places you can get your motor 'high voltage supply' from. One is the DC jack on the Arduino board and the other is the 2-terminal block on the shield that is labeled EXT\_PWR. The DC Jack on the Arduino has a protection diode so you won't be able to mess things up too bad if you plug in the wrong kind of power. However the EXT\_PWR terminals on the shield do not have a protection diode (for a fairly good reason). Be utterly careful not to plug it in backwards or you will destroy the motor shield and/or your Arduino!
> 2 votes

---
Tags: arduino-motor-shield, adafruit
---


# Question
Title: Simulink with arduino : data acquisition
I'm working on data acquisition from a sensor attached to the Arduino : MPU6050 using a model in Ssimulink. I have installed the hardware support in Simulink but I don't know how to start building the model. The model must read the data from the Arduino by deploying it into the Arduino.

My connection Arduino \<=\> MPU6050 is :

```
Arduino    MPU 9150
3.3V       VCC
GND        GND
A5         SCL
A4         SDA
DIGITAL 2  INT
GND        AD0

```

update : i have use a s-function but I get the following error: \_The call to realtime\_make\_rtw\_hook, during the after\_make hook generated the following error: Could not download the model to the target hardware. Verify the connection between the computer and target hardware.

The build process will terminate as a result.

Caused by: Could not download the model to the target hardware. Verify the connection between the computer and target hardware.\_

But the target is definitely connected, and downloading others module (like led blinking ) with simulink is working fine. I've also tested this on a different PC with Windows 8 (64bits) with the same result. Can anyone give me a hint please?

# Answer
I just made my GY-521(MPU6050) work with Simulink using s-function. I wish this would be helpful for you.

I am using an Arduino MEGA 2650 board. The sensor data is read in in real time. Note that currently only Arduino MEGA 2650, Arduino MEGA 2650 ADK, and Arduino DUE support the real time windows target. If you are using other types of board, this answer may not applied.

Your hardware connection looks correct. But if you have some troubles you can refer to mine for checking:

```
5v VCC
GND GND
SCL SCL(check the register map of your board)
SDA SDA(check the register map of your board)

```

Above four connections are adequate if you just read raw sensor data. INT is needed if you are going to read fused data. But I did not try that.

Next you may write a small program in Arduino IDE to ensure everything works. You can refer to the Arduino MPU6050 examples. The code written here will be used to construct your Simulink s-function later.

Now you can start to build your Simulink block using s-function builder. If you did not do this before, here is a good tutorial:

https://m.youtube.com/watch?v=\_OLctOFjjYQ

In our case, you need to copy Wire.h, twi.h and their .c counterparts in your current working directory where your s-function resides.

And do not forget to rename generated .c file to .cpp, and add external "C" declaration. All of these are illustrated in above video tutorial.

After all of above are done, you turn your simulation mode to external, and run. You can view your sensor data in scope if everything goes right.

---

Source code and configuration used in my function: I include all headers in the `Libraries` panel of S-Function Builder,

```
#ifndef MATLAB_MEX_FILE
#define ARDUINO 100
#include <Arduino.h>
#include <Wire.h>
#include <Wire.cpp>
#include <twi.h>
#include <twi.c>
#define MPU 0x68
#endif

```

Wire.\* and twi.\* files are copied from Arduino IDE's directory. I put these files along with my S-Function block file.

The address of I2C is 0x68 here.

Next, the code for sensor outputs are placed in `Outputs` panel. And do not forget to add ports in `Data Properties` panel.

```
#ifndef MATLAB_MEX_FILE
Wire.beginTransmission(MPU);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU, 14, true);

int raw = Wire.read() << 8;
raw = raw | Wire.read();
ax[0] = (float)raw / 8192.0f;

raw = Wire.read() << 8;
raw = raw | Wire.read();
ay[0] = (float)raw / 8192.0f;

raw = Wire.read() << 8;
raw = raw | Wire.read();
az[0] = (float)raw / 8192.0f;

raw = Wire.read() << 8;
raw = raw | Wire.read();
temp[0] = (float)raw / 340.0f + 36.53f;

raw = Wire.read() << 8;
raw = raw | Wire.read();
gx[0] = (float)raw / 131.0f;

raw = Wire.read() << 8;
raw = raw | Wire.read();
gy[0] = (float)raw / 131.0f;

raw = Wire.read() << 8;
raw = raw | Wire.read();
gz[0] = (float)raw / 131.0f;
#endif

```

Finally, initialization and configuration are done in `Discrete Update` panel.

```
#ifndef MATLAB_MEX_FILE
if (xD[0] != 1) {
    Wire.begin();

    /* Do not sleep */
    Wire.beginTransmission(MPU);
    Wire.write(0x6B);
    Wire.write(0);
    Wire.endTransmission(true);

    /* Gyroscope full scale range: 250 degs/s */
    Wire.beginTransmission(MPU);
    Wire.write(0x1B);
    Wire.write(0);
    Wire.endTransmission(true);

    /* Accelerometer full scale range: 4g */
    Wire.beginTransmission(MPU);
    Wire.write(0x1C);
    Wire.write(8);
    Wire.endTransmission(true);

    xD[0] = 1;
}
#endif

```

Please refer to your board's datasheet for specific address and LSB scales. I am using GY-521 here.
> 3 votes

---
Tags: serial, mpu6050, simulator
---


# Question
Title: Why doesn't the Micro OLED library compile on my DUE?
I have an Arduino `DUE` and just got a `Micro OLED` display from SparkFun.

Using their library, when I try to compile I get the error below. Other example code works just fine and I've programmed this thing a million times with my code. So it's clearly in the SparkFun code.

Here is the SparkFun tutorial page with a description of the product:

https://learn.sparkfun.com/tutorials/micro-oled-breakout-hookup-guide?\_ga=1.19136059.2055231411.1404437767

Here is the library I am using:

https://github.com/sparkfun/Micro\_OLED\_Breakout/tree/master/Firmware/Arduino/libraries/SFE\_MicroOLED

Here is the error I get:

```
Build options changed, rebuilding all

/Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp: In member function 'void MicroOLED::spiSetup()':

/Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:46:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
    ssport  = portOutputRegister(digitalPinToPort(csPin));
            ^
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:48:51: error: 'portModeRegister' was not declared in this scope
    ssreg  = portModeRegister(digitalPinToPort(csPin));
                                                     ^
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp: In member function 'void MicroOLED::i2cSetup()':
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:84:2: error: 'TWBR' was not declared in this scope
    TWBR = ((F_CPU / I2C_FREQ) - 16) / 2;
    ^
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp: In member function 'void MicroOLED::parallelSetup()':
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:109:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
    ssport  = portOutputRegister(digitalPinToPort(csPin));
            ^
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:111:51: error: 'portModeRegister' was not declared in this scope
    ssreg  = portModeRegister(digitalPinToPort(csPin));
                                                     ^
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:114:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
    wrport  = portOutputRegister(digitalPinToPort(wrPin));
            ^

/Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:119:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
    rdport  = portOutputRegister(digitalPinToPort(rdPin));
            ^
  Error compiling.

```

# Answer
> 1 votes
That library is uses some AVR specific methods, that aren't implemented for the ARM processor in the Due.

I don't see a real easy way to port those methods.

---
Tags: arduino-due, library, compile
---


# Question
Title: How to check whether my Arduino is working? And how to fix this?
I tried my first project with Arduino Uno. But I can't upload any code. Power green LED is working and orange LED is always on, not blinking, and IC also getting hot. What can I do to fix this problem?

# Answer
My suggestion is to find someone else with an arduino, and get them to test (with their computer, known to be working) uploading to your Arduino. That way, you can tell if the problem is with your computer or the Arduino.

You haven't mentioned what your first project was. The most common mistake #1 is to light up an LED without a resistor. If you do that for a split second, you might (OR MIGHT NOT!) get away with it. If you leave it running for a few seconds, you are almost certainly going to burn out your AtMega (the IC on the board). This might very well result in the symptoms you describe. If this has happened, and your chip (IC) is removable (some are, some aren't), you should be able to buy a new chip of the same kind. An Arduino Uno has an AtMega 328, you will want a DIP package (they are the removable ones), and you will want one with an Arduino Bootloader pre-programmed. Replacing the chip may OR MAY NOT fix the problem. Make sure you note down the orientation of the broken chip before you pull it out - it will fit in, but won't work (and could burn out!) if you put it in the wrong way. There should be a little dimple at one end of the chip, right on the end. It should look like this (possibly without the pin labeling sticker): http://www.jaycar.co.nz/productView.asp?ID=ZZ8726&w=atmega328&form=KEYWORD

If your chip is not removable, or replacing the chip doesn't help, then you will need to get a new Arduino.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: fast memory buffer and setting output state
I'm intending to set up a digital delay using a circular buffer (in SRAM) with an Arduino Due (@84MHz). The lenth of the buffer determines the delay. I need about 1us resolution and the delay needs to be dynamically settable between 0 - 500us. I'll probably use most of the memory just for the buffer.

I've got a very basic setup going (with a fixed delay, no buffer), that just updates a temporary variable with the current state of the input signal and then writes the whole word to another port in order to set the state.

Next up is designing the buffer so I can add some delay to the output of the signal.

Filling the buffer using interrupts watching signals on the same port shouldn't be too difficult but I am wondering:

a) taking speed in consideration, which buffer method will have the least processing overhead? Memory stack or an array\[\], or someting else?

b) is there a way to read a port and set an output port in one clock cycle? I am now using `REG_PIOD_ODSR=outbyte;` but ideally it needs to point to a memory address directly.

# Answer
I would use an array, they're about as simple as it gets. 84 clock cycles per sample is very tight, but definitely possible. I'm guessing that's too close to the line to do any sort time testing - you will probably have to set up your loop to take exactly 84 instructions. This means you will probably need to hand-code in assembler. Be very mindful of branching instructions - both branches will need to take the same number of clock cycles.

The Uno (AtMega328) runs most (all?) instructions in one clock cycle, I don't know if the same applies to the Due. You would need to hand-code the assembler, check out how many cycles each instruction takes, and pad it out (there is a do nothing "NOP" instruction, which typically takes one cycle.

HOWEVER -

You can get all this work done for you by using a chip made for this purpose. This is called a Digital Delay Line, http://en.wikipedia.org/wiki/Digital\_delay\_line (or Analog Delay Line if you want analog values, e.g. for sound playback).
> 1 votes

---
Tags: arduino-due
---


title: Should I use an Arduino or not?

text:
# Question
Title: Should I use an Arduino or not?
I am building an electronic gadget eventually to sell.

I think the Atmega IC is used in the arduino and could this be programmed as easily as the arduino?

I'm wondering if I can use the chip and buy just what I need for my circuit, which would be cheaper as there would be no licensing obligations to the Arduino company

Cheers Eamonn

# Answer
Short answer: Yes. After all, Arduinos are made by starting with an ATMega (or other AVR) IC.

Longer answer: People - including myself - routinely build with a bare ATMega328p (or other MCU), programming them off-board on another system, or providing connections to allow programming them in place. Beyond that you only need the soldering skills for the chip you choose (if you're building the boards yourself). I use DIP ICs and off the shelf through-hole PCBs and hand-build one or a couple at a time. Quad Flat-Package or Surface-Mount chips are another step up in complexity for the hand-builder.
> 6 votes

# Answer
I'd like to second the other posts - if you are familiar with Arduino, going to a stand-alone chip is very easy.

You miss out on the following things: programming via USB, 7-12volts through the power jack, and/or power through USB, reset button, led on pin 13, and the clock. Depending on where you get your Atmel chip, you may also need to set the fuses.

The code is exactly the same, even if you go down to a smaller chip (or larger - whatever suits your project best!).

Programming: I use a FreeTronics ICSP (ISP) to program the chips, and have the 6-pin ICSP header on all my projects for easy reprogramming. This particular programmer has a "slow clock" jumper, because when you get the chip from the Atmel factory, their internal clock runs at 1mhz, too slow to program with the Arduino IDE default settings. You can leave it at 1mhz, if your project doesn't need any more, or change the fuses. You will need an ICSP to set the fuses (see further down). By using an ISP rather than usb, you also save a little memory - you don't need a bootloader (which is pre-programmed on Arduinos, but not when you buy the chips from the factory).

You will need to sort out your own power - this depends on what you need, and what you have. You can use a 5-volt AC-DC power supply ("Wall wart") and plug it into mains. Or, you can power it off USB - if you only use USB for power, you can solder the socket directly on your board. You can use a regulator (which is what the Arduino uses for the 7-12v power socket), or, if running it off a 12v power supply, it might be easier/cheaper to buy a car phone charger from the dollar store, and a lot of the work will be done for you. Also, the power supply doesn't have to be 5v - depending on your application, you might run it from 5.5v to as little as 1.8v, depending on your clock speed. Find the data sheet for the chip you use.

A reset button is very easy to add, if you need it - all it takes is a resistor and a pushbutton. Weather you need it or not, depends on your project.

The same applies to the led on pin 13 - it depends on your project.

Finally, the clock. The Arduino has a 16mhz quartz clock. You can do the same, it only takes 3 components (you will have to set the fuses, see further down). You can use a clock up to 20mhz, giving you a 25% speed boost if you need it (you may need to change some settings, because timing functions like delay depend on the clock speed - your delays will be 25% shorter). Or, you can use the internal 8mhz clock (either at full speed, or as from factory, at 1/8 speed, so you get 1mhz). At 4mhz or less, you can run the Atmega at 1.8 volt, or 0.7 volt for the "pico power" chips.

As I have mentioned, you may need to set the fuses to the correct value. The best idea is to go to http://www.engbedded.com/fusecalc/ to work out what fuse settings you want. Specific things to look for: the clock source (internal or external? what speed?), divide clock by 8 internally, and brown-out detection (Arduino chips turn themselves off when the power goes below 4.3v). Warning: setting wrong fuses may set your chip so it is very difficult to fix. You can set the fuses using an ISP; if the clock speed is very slow (I think \< 4mhz? which it is when it comes from the factory), then you will have to "slow program" - some ISPs have a "slow program" jumper, but you can use an option to avrdude to do the same - I think it's -B e.g. -B10).
> 2 votes

# Answer
That's what I do all the time. You might want to buy an ISP programmer to program the chips (e.g. USBASP or usbtinyisp). If you just want to try things out first, you can use your arduino board as an programmer by uploading the ArduinoISP sketch.

The Arduino Uno uses an ATMega328, but you could use other AVR chips too. E.g. the ATMega8, which is slightly cheaper. Or an ATTiny85, which only has a few pins, and is therefor a lot smaller (also cheaper). So you can choose a chip that best fits your needs.
> 1 votes

# Answer
Arduino of course started as a prototyping platform. Build this first, get it working, then move to a circuit board of your own design with the same chip and go from there. However, as the cost of all the components and really the boards themselves drops, I frequently find my self thinking, why not just use the board. Obviously if you are going to market something, having a full arduino in there might be a bit much, but if its just for your own application, I don't see any reason why you wouldn't just buy boards and use them as necessary.
> 0 votes

# Answer
Thanks for all the replys. I have a lot to learn as I only heard of arduino a month ago. Didn't have a reason before. My arduino hasn't arrived yet so I made my basic circuit with components on a breadboard. I think I will need the arduino as I need some monitoring in the circuit.

Thanks again much appreciated. Eamonn
> 0 votes

# Answer
Since you are already using Arduino, I think you not should use atmega, but must! To prevent future headaches, since you look new to electronics, I HIGHLY recommend to check for app notes by Atmel. Just type it "Atmel app notes" at google and you will find a lot of useful tips. Some of them are start to routing by crystal resonator, them GND and Vcc. Use, if possible, on each IC a 100nF ceramic SMT capacitor nearest as possible and another one of 10uF (can be electrolytic) on most robust ones (like microcontroler). Always route opposite signals (like Vcc and GND) tied together with the same size to low its impedance... If you are doing with high inductance loads you should use another sorce (and maybe also a diode as rectifier or an optocoupler).

There's a lot of good practices and if you want to sell your work, you really have to study them.

Good luck! Also look for the electronics SE
> 0 votes

---
Tags: atmega328
---


# Question
Title: Controlling bigger motors with an arduino board
i am german and my english is not the best, anyway i hope you will understand my problem. At the moment i construct a little car with some friends. We have still completed the frame and now we think about controlling it in a electronic way. For example with a controller of a playstation or with our smartphones, however, it should be electronic, so i think about to do this with an arduino board.

We have two motors. One for the direction and the other one for the movement. The first has about 8 ampere and about 12 volt, the other has 800 watt, so around 40 ampere and 24 volt.

My question is, whether it is possible and if so how to control them (or one them) with an arduino board and what do i need in addition?

It would be great if you could help us :)

# Answer
DC motors are typically driven with some sort of BJT/MOSFET solution that will be able to sink enough current to drive the motor because a microcontroller pin can only usually provide a few mA of power. See this link for info on basic microcontroller DC motor control. If slow response is acceptable and only one level of power is required (i.e. no PWM) even power relays could be used to turn on off the motor. Some applications could use this. However, for your application, it sounds like you will want more responsive control over the motor and need a particularly high power MOSFET to properly drive your application as your motor is very high power. Such FETS such as these could be used to properly control such a motor using the microcontroller. Do note additional protection circuitry will be necessary and is probably the topic of another feed, but this would be a place to start if you wanted to build it from scratch. Otherwise go with an over the shelf driver board which will probably have something like the link above used on it.
> 2 votes

# Answer
One of the best ways to controll a motor is to look in to the motor shields from the arduino. You can buy seperate motor controllers with different throughput, some advanced with breaking and some without.

But motorshield is about the best way to get started.
> 0 votes

---
Tags: motor, android
---


# Question
Title: Stabilizing output values of conductive sheet(Velostat) connected to analog pin A0 of Arduino
I am trying to do some experiments with conductive sheet (velostat). When I apply a force on the sheet it should change the value of resistance(output). I taking the output of the sheet by connecting to analog input Ao of Arduino. But I am not getting constant readings from arduino, even if no pressure is applied. Do I need to build any extra circuitry to stabilize the output value? Can anyone please tell how to stabilize the output value of Arduino?

# Answer
You need to use a matching resistance to create a voltage divider.
> 1 votes

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


title: How can I obtain the .hex of a file

text:
# Question
Title: How can I obtain the .hex of a file
I have an Arduino Yún running Openwrt-Yún 1.5.3 (which is the latest version, as I upgraded yesterday), and I am trying to obtain a .hex (compiled sketch), so that I can upload a sketch directly into the Yún. I know about compiled sketches, but there are no build directories in "C:\Documents and Settings\MY\_USERNAME\Local Settings\Temp".

Where can I obtain the .hex of any file I have compiled, and how?

# Answer
As noted in comments, enable verbose compilation and look at the output to find the temporary-directory location. (Click File, Preferences, verbose compilation.)

Note, after you click File, Preferences and the preferences window appears with its half-dozen items, you should also see a note about directly editing preferences in the preferences.txt file. Edit that file (using a plain-text editor, not a word processor) when the arduino IDE is not running. Change the line

```
preproc.save_build_files=false

```

to

```
preproc.save_build_files=true

```

so the .hex files in the temporary directory have a better chance of sticking around.

(I'm not able to test this suggestion on an MS-Windows system. On my Linux system most build files stick around anyway in /tmp/)
> 1 votes

---
Tags: arduino-yun, compile
---


# Question
Title: What pins should I use when blinking AtTiny13 with arduino IDE?
I'm trying to program AtTiny13 using Arduino IDE. I have connected the atTiny to my PC using USBasp programer.

I want to write a simple blink application to test whether it works or not. Which pins should I blink?

# Answer
> 1 votes
You'll need an Arduino library that supports that chip, to make it appear in the Tools \> Board list. The library docs will tell you which pins then correspond to which Arduino digital I/Os. From that you can decide which pin to attach an LED to (with resistor) and how to edit the blink sketch.

Example: http://www.instructables.com/id/Pimp-Your-Chocolates-with-Arduino-IDE-and-ATtiny13/step2/Program-the-ATtiny13/

# Answer
> 1 votes
Because pins 0 and 1 (physical 5,6) are PWM's you should keep them for later ... and you still have A3 and A2 for analogWrite so, you should use Pin 2 (Physical 7, next to +5V) like this :

add this in the setup function

```
pinMode(2, OUTPUT);

```

And add this in your loop function:

```
digitalWrite(2,HIGH);

```

For reference : SparkFun's Help guide

Remember : Physical pin "1", reset, has a dot marked on it.

---
Tags: arduino-ide, attiny
---


title: Fancy Arduino IDE

text:
# Question
Title: Fancy Arduino IDE
Do you know an IDE that is Arduino compatible, with:

* Black background; white hurts my eyes.
* Some auto completion features maybe?
* And also one that lets you minimise brackets. Xcode like.
* A better console...
* Something to clear the serial console.
* A **breadboard view**.

Something fancy!

# Answer
Have a look at Fritzing. I don't know how much you can customize there, but it has a whole suite where you can design hardware, write code, and even order PCB if you want to.
> 3 votes

# Answer
I believe Eclipse can do everything you mentioned except for showing hardware layouts. The appearance of editor windows is customizable. If, by minimizing brackets, you mean collapsing them ("just indicate that something is here; I don't want to see the content"), Eclipse does that too. You can clear the console, but I don't know what "better" features you mean so I can't answer that part. It can take some setting up to get it working for you but it's far and away more powerful and feature-filled than the basic Arduino IDE. It is probably the most used IDE by people who look to upgrade from the basic one.

Update: While it doesn't directly show hardware layouts, it does know about opening files with their default applications. If you put a Fritzing file in your project folder, when you click on it, Eclipse will launch Fritzing. If you put an image file such as a screenshot of the board layout, it will even open that within the IDE.
> 2 votes

---
Tags: programming, ide
---


# Question
Title: How do I connect two slaves of same type in I2C?
I am not experienced about I2C communications, but I do happen to have two HMC5883L magnetometer modules that I wish to connect to a single arduino. It uses I2C protocol, and hence the slave device will have a fixed address. Now Can I change the address of one of my sensors so that the Arduino can differentiate between the two? (I seem to find no way out by reading the datasheet) Thanks in Advance Siddharth Jha

P.S. Can an MPU 6050 module be used to find angle of rotation in X-Y plane (Parallel to the ground)?

# Answer
The problem is with the magnetometer: "The HMC5883L has a fixed I2C address, you can only connect one sensor per microcontroller!" Wiring and Test

Also, it says it in the specs on page 2: I2C Address 8-bit read address 0x3D 8-bit write address 0x3C 3-Axis Digital Compass IC HMC5883L

Low cost magnetometers appear to have fixed I2C addresses. One solution would be to get a different one in addition to yours. For example, the MAG3110 has I2C address 0x0E and the FXMS3110CDR1 has I2C address 0x0F. Xtrinsic MAG3110 Three-Axis, Digital Magnetometer

More information on this page:

How to connect multiple of the same device to an Arduino using I2C?

P.S. You are more likely to get an answer to your second question by posting it separately (and help others in the process).
> 1 votes

# Answer
You can't change the address. You could connect it to some other pins, and bit-bang the I2C protocol.

Or connect the vcc of the unit to an arduino pin, so you can turn it on and off.
> 0 votes

---
Tags: arduino-mega, i2c, accelerometer
---


# Question
Title: What are some steps to attach an Arduino to an electric heater?
I have the below portable electric heater, but I would love to control it's start AND stop time using an Arduino. As-is, it does not come with a stop feature. SO, I have a burning question. How can I get an Arduino to start and stop this heater at specific times of the day?

As you can see, it does have a start time, but it does not have a stop time. The power button is a simple push button. I suspect I would need to 'interject' into that and the board by using a switch? Apologies if the terminology is off, but I'm very green. Where would a noob begin?

-EDIT- The unit is always off when it's plugged back in. That likely means I cannot put a timer on the power cord.

# Answer
Would or should begin? Don't fiddle with the internals of the heater.

Set its switch to the always on position and control switching on and off with an external relay. Make a box that has plenty of room (you can reduce size at a later moment), a power cord, a mains adapter for your Arduino and a mains outlet in which you can plug your heater.

Use:

* an RTC (real time clock) breakout to keep accurate time
* optionally a 7 segment display to display date/time. Just make sure it has a driver chip on it so you don't need your Arduino to multiplex the individual LEDs
* couple push buttons to configure the device
* a relay rated for the maximum power of the heater to turn it on/off, that can be driven from 5V. Possibly needs a transistor and flyback diode to be controlled from an Arduino GPIO line.

And be **very** careful when experimenting with mains power, it can be leathal.
> 2 votes

# Answer
**I don't know if that heater will work for sure with this approach because the buttons are weird.** However, I am 99% sure this will work.

>

*(From http://keshavsaharia.com/2012/12/01/coffeeduino/)*

Basically here's what you do:

1. Disassemble the control panel to find the PCB where the buttons are mounted. Find which button you want to simulate a press of.
2. Find the solder joint where the button meets the PCB.
3. Solder a wire to the two terminals that are connected. Some buttons have three or four terminals: look at the traces on the PCB to see which buttons are connected.
4. Wire the relay with the two wires connected so the relay acts as a switch.
5. Make the proper connections to the Arduino board to control the relay.

In code, you can just turn the relay on for a quarter of a second or so. Then, the IC on the heater will react like you pushed the button.

Make sure to seal all of this up and make sure you don't accidentally short out any of the wires. I would say to also isolate the Arduino and relay to make sure that you don't electrocute yourself at all if something goes wrong.
> 1 votes

# Answer
Use the Arduino to set the start and stop time. Always leave the heater switched on and use something like the 'Mains Switch widget' from SF innovations to control the mains. This unit has a mains relay, is fused to protect against fire and is enclosed in a plastic case. http://www.sf-innovations.co.uk/mains-switch-widget.html
> 0 votes

# Answer
To be safe use a device like the power tail from spark fun(basically a sealed relay unit, ready for you to connect to the arduino)

Much easier and safer if you don't have any experience working with 120V/240V

uses a 3-12 input to switch 120v up to 15A https://www.sparkfun.com/products/10747
> 0 votes

# Answer
The following will work and meets the requirement that the heater does not auto turn on when powered up. You need to turn the heater on manually, so no different from existing, and this then allow you to either

* Power it down at a preselected time of day, provided the Arduino is able to keep track of time, or
* The Arduino will turn it off a set period after it has started to heat.

The latter is easier to do and meets the need well enough.
The only technical requirements are

* Able to sense current drawn by heater.
* Able to turn a heater control relay on/off
* Able to set or select a time delay on Arduino.

Of these, the current detection is hardest and even then, not very hard. Possible means include:

* Current transformer connected to heater lead.
* Opto isolator with LED in series with lead with suitable parallel resistor across opto LED to drop enough voltage to trigger opto on voltage peaks when heater is on, and backwards diode across opto LED for reverse mains cycles. This provides a series of pulses to Arduino when heater is on.

**Equipment:**

Arduino controlled external relay or solid state relay.

Some means of detecting that heater is drawing current - timer mode only.

Arduino.

---

**Arduino cct can:**

* Detect current draw.
* Turn relay off/on
* Be programmed to either stop time or run time.
* Drives external relay or solid state relay.
* Optional: Relay defaults on.

**Then:**

Set external Arduino timer to desired time.
Arduino sets relay ON.
Set heater to desired start time.
When heater start Arduino sees current and starts timing, or in time of day mode just turns off power at correct time.

This keeps all circuitry external.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How do I listen for a sound that matches a pre-recorded sound?
I'm working on a project that uses an Arduino Uno to listen for a bell ring and then uploads to a web server the exact time the bell was rung using a WiFi Shield.

I want to know how I can listen for the bell ring (a three second long high pitch tone) and be able to detect that that's what the Arduino heard. I think the best way may be to pre-record the sound and then the Arduino will constantly try to match the incoming sounds to the prerecorded sound. I'm wondering how I could go about doing this (or are there better methods).

The bell sounds kind of like this: bell sound

# Answer
About the simplest starting point is to use an FFT (fast Fourier transform) library (like ArduinoFFT at openmusiclabs.com) to characterize the spectrum of an audio stream.

\[*Edit:* An alternative method (digital bandpass filter) is mentioned below.\]

Audio typically is made up of many frequencies of many amplitudes and phases, mixed together. FFT sorts some of that out; it estimates the amplitudes of the various frequencies that make up a bit of audio.

The general idea is to use an Arduino ADC to take readings of an audio voltage for a fraction of a second, then use FFT to convert the large set of readings to a small set of numbers, in eg a set of 32 or 64 frequency-bins, to represent amplitudes in given frequency ranges. For example, if the sound during a sample is a mix of five sine waves at five frequencies, the bins those five frequencies are in should have large numbers assigned, while other bins should have small numbers.

The approach would amount to sampling at 10KHz for 0.1 second or so, computing an FFT with 32, 64, etc. bins in the next 0.1 second, and comparing bin counts to a training pattern. Whenever bin count patterns match reasonably well, start a three-second timer; if several seconds of matching samples occur, declare a match.

If the bell is electronically generated and mostly a mix of pure sine waves, then its sound will have an easily recognized spectrum. But if the sound source is buzzy and there is background noise, it may be difficult to compare spectra. See eg
Comparing an audio signal with a previous 'taught/profiled' signal
How do I compare chords played on a guitar with a known sample?
How do I compare 2 audio files, returning a percentage of difference
What does the phase of a FFT bin of an audio signal represent?
Sound pattern matching using Fast Fourier Transform in Windows Phone
How do I go about detecting whistles, pops and other sounds in live audio input?
The Frequency Domain Section 3.4: The DFT, FFT, and IFFT

**An alternative: digital bandpass filter**

Digital bandpass filters are based on processing a signal in a way that detects the amplitude of the signal's frequency component within designated limits.

For theoretical background see wikipedia's *Digital filter* article. Also see Vaseghi, Chapter 5, Digital Filters, (eg section 4.6.6, Design of Band-Pass FIR Filters) pdf file and ECE438 digital filter design lecture notes pdf file.

You can use MatLab or Octave to do most of the work of designing a filter. For example, if you have the Signal package installed and loaded into Octave, commands like

```
v=cl2bp(30, 0.48*pi, 0.52*pi, [0.02, 1.02, 0.02], [-0.02, 0.98, -0.02], 2^11);
freqz(v);
v

```

will compute coefficients for a Constrained L2 bandpass FIR filter, plot the freqency response (as below), and display the 60 coefficients. To use the filter, copy the 30 non-zero coefficients into a program, set up a rolling array of readings, and at each sample compute a new filtered value. If at some point high filtered values occur, and if they recur for about three seconds at the bell's frequency or twice its frequency, then the bell is ringing. Note, there are other kinds of bandpass filters; the Constrained L2 bandpass FIR filter is shown for convenience, but other kinds may be better.

If you are unfamiliar with signal processing, you might need to try the following approach:
1, On your development system, obtain a few seconds of audio to use for tests. (Eg, allocate two buffers of several dozen bytes each; fill one buffer while using the other buffer to send data from the Uno to your development system. Use (eg) Serial.write(buf, len) and a high data rate, eg 115200 bps, to send binary data, with three ADC readings packed per four bytes.)
2, Use Octave or similar software to try out several different FFT or filter approaches. You would use FFT to determine the bell's fundamental frequency and then could try out digital bandpass filters while developing a recognizer. You can also use mkfilter to design filters to try out in C programs on your system, and should be able to iterate more quickly while developing your approach than if you were developing it using the Uno. When you get satisfactory results on your development system, you then can code a sketch to test the technique on your Uno.

Note, for a given filter order, filters implemented using fixed-point integer arithmetic on an Uno can handle more samples per second than those implemented using floating arithmetic. An Uno might support 50000 to 100000 floating multiplies and adds per second (,,,), vs. two to four times as many fixed-point operations per second. If your filter uses a dozen floating point ops per sample, your sample rate probably would have to be under 5000 samples per second. If it uses half as many floating ops or uses fixed point instead of floating point, your sample rate could be twice as much.
> 3 votes

---
Tags: sensors
---


title: Arduino Ethernet Shield vendor is null

text:
# Question
Title: Arduino Ethernet Shield vendor is null
I bought Ethernet Shield for Arduino Uno! from AliExpress. It is good work but I scanned my network with Fing and device Vendor name is null.

Can I change/set device Vendor?

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 10, 0, 0, 106 };

void setup()
{
  Ethernet.begin(mac, ip);
}

```

# Answer
The vendor name is not stored on the device, rather it is indicated only by the first three octets or OUI part of the MAC address which is either stored on the device, or in your case set up by software. Turning this back into a name on another computer which sees its traffic is done by the help of a local or network-sourced OUI lookup table.

Apparently the table your computer is consulting doesn't have an entry for the OUI 0xDE, 0xAD, 0xBE.

And that's not surprising as this is clearly a dummy value put in as a placeholder - read all 6 octets as if they were a word and you'll see it says "dead beef feed" - a variation on a classic magic "illegal" value.

Technically, this is actually a legal value for use on a local network as the 2's bit of the leading octet is turned on, indicating that it is a "locally administered" address, rather than one guaranteed to be unique in all the world as you would expect a proper piece of network hardware to have.

If you find the table your computer is doing OUI lookups in, you could add a DE:AD:BE entry to it.
> 3 votes

---
Tags: arduino-uno, ethernet
---


# Question
Title: What kind of Arduino should I pick for a calculator?
I am planning to build a calculator using Arduino as the base. I already know C and I love low-level stuff, so I guess the software part won't be a problem.

However, I've been stuck with Arduino. What I need is something capable of doing math (as I'm not even sure if Arduino has a FPU), and it to have enough inputs for more than the basic 0-9 `+ - / *` keys.

I am a *real newbie* when it comes to hardware. I don't even have the slightest clue where to start. I barely understand Arduino's specifications, which is why I'm asking here.

I want to do something *more* than the classic calculator, because the software part is not a problem. I just need help on which hardware should I choose; both on the 'which Arduino' and 'which accesories for the Arduino' parts.

P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

# Answer
Start with the biggest (AVR) Arduino you can afford, and worry about miniaturizing it once you have the basics in place. You may find that you don't actually want an Arduino in the end, but something like the ATmega169PA instead so that you have native LCD support (instead of having to use a discrete LCD module).

> P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

Doesn't matter. Most of your x86 assembly experience will easily transfer to AVR (but not all, since the AVR core is simpler than x86).
> 5 votes

# Answer
For the most part, none of the AVR based arduinos are any better at number crunching than any others. They all have a single AVR core running at 16Mhz. None have an FPU, but the software floating point code is very efficient and at the time scales you care about for a calculator, it really doesn't make much of a difference.

The biggest differences between models are memory and available IO, so the decision between AVR models should probably come from what kind of peripherals you want to plug in, not what you want to calculate.

That said, if you want to do a lot of high precision, numerical calculations (like numerical integration or something), you will probably want something with more memory, and floating point types larger than 32-bits. I don't have much experience with those models, but I'm pretty sure that a Yun or a Zero would be better suited for those kinds of calculations. They don't use AVR based main CPUs.

For IO there are too many options to enumerate here. Take a look at the usual suspect's pages (sparkfun, adafruit, etc...) for displays and buttons. These sites have good descriptions and example code for everything.

When picking devices, remember that you can have multiple I2C devices plugged in at once, but only one UART serial per port (uno/leonardo 1 port, mega 4). Software serial can give you more UARTs for low speed comms if need be.

If you want a lot of different individual buttons, there are ways to get more than 1 button per pin, but it would be a bit easier electrically to pick an arduino with as many pins as buttons. Some of the keypads available already have a special wiring scheme to get higher than 1-to-1 pin ratios and descriptions of how to use them, so they might be a good pick to get yourself started.
> 5 votes

# Answer
Any Arduino (I would start with the UNO) will be sufficient to make a calculator similar to the regular HP or TI calculator product line.

For the keypad, you will need to buy an I2C compatible keypad and connect it to the I2C lines. For the screen there is an LCD shield.

You will not need to code anything in assembly. You can write cpp code using the libraries provided with the Arduino.
> 2 votes

---
Tags: build
---


# Question
Title: Programing other Atmel ARM chips using Arduino
Ok, i know professionals generally hate Arduinos, but I would like to know if it would be possible to program Atmel ARM chips using the Arduino IDE. By which I mean, not needing to modify the source code, just add another entry into the "hardware" folder and that's it.

We already know the Atmel ATSAM3X8EA (Arduino DUE) is compattible, but how about a similar chip, like the Atmel ATSAM3X8CA. Or maybe a Cortex-M4 one, like the Atmel ATSAM4E16EA or the Atmel ATSAM4S8CA.

The Atmel ATSAM3X8CA is the closest one to the Atmel ATSAM3X8EA the Arduino Due uses, a bit smaller and with less I/O.

If it isn't possible without much source code modding, I would like to know what would it take to make it work.

Thanks for your answers.

# Answer
Yes it is possible. IDE 1.5.+ support different platforms, as they call it. Where the AVR and sam are provided by stock. Others are possible.

It is fairly involved setup. In short; within each platform there are the following files:

* boards.txt, defines the individual boards using the similar processor.
* platform.txt, defines the compiler arguments
* programmers.txt, defines how to program it.

With corresponding sub directories to match, under the variants/ folder. I have not found an complete tutorial on the matter. However, their

Arduino IDE 1.5 3rd party Hardware specification

An overview of the platform architecture proposed for Arduino 1.5

are a great place to start.

I have not done much with SAM. I do notice that programmers.txt is empty. So it must be done another way.
> 3 votes

---
Tags: ide
---


title: Am I Running Out of RAM Or Not?

text:
# Question
Title: Am I Running Out of RAM Or Not?
I'm attempting to drive 300 TM1803 RGB LEDs from an Arduino Uno using the FastLED library. My code works fine for 100 LEDs, but when I go to 150, the arrays that store LED values and my sensor data get corrupted, causing the LEDs to flash colors randomly every few seconds. From what I've read these are exactly the symptoms of running out of RAM, leading to something overwriting the RAM that contains my arrays.

However, with 150 LEDs, the MemoryFree library says I'm only using 920 bytes of RAM, no matter where in my code I measure, and the IDE says 880. Does anybody know what's going on? Is there something using 1100 bytes of RAM for a very short amount of time, so that I can't measure it?

My code:

```
#include "FastLED.h"
#include <MemoryFree.h>

const byte ledsPin = 3;
const byte sensorPin = A1;

const int numLeds = 300;
const int ledTime = 1000;

const int sensorMin = 0;
const int sensorMax = 512;

const CRGB correction = CRGB(80,255,70); // Cool white
//const CRGB correction = CRGB(160,255,20); // Warm white
const byte hOffset = 170; // baseline hue value
const int8_t hDirection = -1; // 1 or -1, direction of rainbow
const byte s = 255; // saturation (colorfulness)
const byte v = 255; // value (brightness)

const unsigned int arrayLength = numLeds+1;
byte hues[arrayLength];

CRGB leds[numLeds];
byte h = 0; // hue (color)

unsigned long sensorSum;
unsigned int loopCounter;
unsigned int arrayCounterLed;
unsigned int updatesPerLed;
char sp = ' ';
int arrayCounter;

unsigned long time;
unsigned long timeNextLed;
unsigned long timeLeft;
unsigned long time1;
byte route;

void setup() {
  FastLED.addLeds<TM1803, ledsPin, RBG>(leds, numLeds).setCorrection(correction);
  FastLED.setDither(0);
  pinMode(ledsPin, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  delay(10);
  time=millis();
  sensorSum += analogRead(sensorPin);
  loopCounter++;
  if(time >= timeNextLed) {
    timeNextLed = (time/ledTime+1)*ledTime;
    arrayCounter = (arrayCounter +1) % (arrayLength);
    hues[arrayCounter] = (constrain(map(hDirection*sensorSum/loopCounter, sensorMin, sensorMax, 0, 239), 0, 239)+hOffset)%256;
    updatesPerLed = loopCounter;
    loopCounter=0;
    sensorSum = 0;
  }
  for(int led = 0; led < numLeds; led++) {
    time1=micros();
    arrayCounterLed = pseudoMod(arrayCounter - led -1, arrayLength);
    timeLeft = timeNextLed-time;
    byte dist = abs(hues[arrayCounterLed]-hues[(arrayCounterLed+1)%(arrayLength)]);
    if(abs(hues[arrayCounterLed]-hues[(arrayCounterLed+1)%(arrayLength)])<=128) { // if it doesn't cross through 0
      h = (hues[arrayCounterLed]*timeLeft + hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft))/ledTime;
    }
    else if(hues[arrayCounterLed] > hues[(arrayCounterLed+1)%(arrayLength)]) { // if it crosses through 0 forwards
      h = ((hues[arrayCounterLed]*timeLeft + (hues[(arrayCounterLed+1)%(arrayLength)]+256)*(ledTime-timeLeft))/ledTime)%256; // Causing flashing on red pixels?
    }
    else { // if it crosses through 0 backwards
      h = (((hues[arrayCounterLed]+256)*timeLeft + hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft))/ledTime)%256;
    }
    time1 = micros() - time1;
    if(led == 0) {
      Serial.print(dist);
      Serial.print(sp);
      Serial.print(route);
      Serial.print(sp);
      Serial.print(timeLeft);
      Serial.print(sp);
      Serial.print(hues[arrayCounterLed]);
      Serial.print(sp);
      Serial.print(hues[(arrayCounterLed+1)%(arrayLength)]);
      Serial.print(sp);
      Serial.print(hues[arrayCounterLed]*timeLeft);
      Serial.print(sp);
      Serial.print(hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft));
      Serial.print(sp);
      Serial.println(h);
    }
    leds[led] = CHSV(h, s, v);
  }
  FastLED.show();
  Serial.print(updatesPerLed);
  Serial.print(time1);
  Serial.println();
}

int pseudoMod(int a, int b) {
  if(a<0) {
    return a+b;
  }
  else {
    return a;
  }
}

```

# Answer
I found it! I was returning an int8\_t variable from my mod function, causing me to not be able to iterate over more than 126 LEDs. Now this little Arduino Uno is maxing out it's RAM at 409 LEDs!
> 4 votes

---
Tags: arduino-uno, debugging, memory-usage, sram
---


# Question
Title: How to save the SHA256 with HMAC into a variable instead of serial print?
```
#include "sha256.h"

uint8_t hmacKey1[]={
0x65,0x63,0x73,0x74,0x61,0x63,0x79
};

void printHash(uint8_t* hash) {
int i;
 for (i=0; i<32; i++) {
   Serial.print("0123456789abcdef"[hash[i]>>4]);
   Serial.print("0123456789abcdef"[hash[i]&0xf]);
  }
 Serial.println();
}

void setup() {
   uint8_t* hash;
   uint32_t a;

 Serial.begin(9600);

 // HMAC tests
  Serial.println("Test: RFC4231 4.2");

Serial.print("Result:");
Sha256.initHmac(hmacKey1,20);
Sha256.print("Hi There");
 //My TRIAL ATTEMPT
 int i;
 for (i=0; i<32; i++) {
 hash[i] =Sha256.resultHmac();
 Serial.println(hash[i]);
 }
}

```

How do I save the hashed result into a variable? I disregarded the Printhash function above and tried it with my own code but it displays

```
 sketch_feb14a:32: error: invalid conversion from 'uint8_t*' to 'unsigned char'

```

I don't understand the printhash function above and found little to no documentation on the web. I'm thinking of using AES library but I guess it's more complicated over here. The above code is based on Spaniako's CryptoSuite here

# Heading

# Answer
My solution was making a new function that returns a String with the hash

```
String GetHash256(uint8_t* hash) {
    char tmp[16];
    String sHash256 = "";

    int i;
    for (i=0; i<32; i++) {
        sprintf(tmp, "%.2X",hash[i]);
        sHash256.concat(tmp);
    }

    return sHash256 ;
}

```
> 1 votes

# Answer
The hash is a series of binary digits. They are usually represented in hexadecimal form for readibility. You are just printing out the raw bytes, which will give a series of random ASCII characters. Some of these may be control characters which interfere with serial port communication.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Hooking up 12v Push button to arduino uno/nano
I want to use one an push button with an led in middle, similar to this one on eBay. The push button has a 12v input I want to hook it up to an Aduino Uno or Nano.

Is there a way to hook it up and receive the signal?

Specifications from the eBay page:

> * Latching type, push it—on, push it again — off
> * Switch Rating: 3A/250VAC
> * LED voltage: 12V only
> * Contact Configuration: 1NO1NC
> * Pin Number: 5

# Answer
> 2 votes
Most likely, there will be a push button, and on separate wires, there is a light. If this is the case, you can hook the push button part up to the arduino. You can test this - find two random wires, test the resistance with a multimeter, then press the button and see if the resistance changes. Keep trying until you find two wires that change when you press the button.

Once you find the pair, you can hook one of those two to a digil pin on the Arduino, and via a resister (large, anything 10kilo-ohm or larger is fine) to ground (GND). Then, connect the other side of your pushbutton to 5V. See http://arduino.cc/en/tutorial/button for photos and a circuit diagram - their wiring is more complicated than it needs to be, and their button has 4 pins in two pairs (left pair, and right pair in the picture with the breadboard; the left-top and left-bottom are permanently connected, and the right-top and right-bottom are permanently connected). Have a look at the circuit diagram - that's a lot simpler. The zig-zag at the top is the resistor, and the disconnected looking thing is the switch (open). There is sample code there too.

Note that push buttons typically "bounce" - that is, when you push them, they will go (starting off) on-off-on-off-on-off-on, so if you're counting the number of pushes you will get a result which is way too high. If you delay long enough in between (10ms?) then you won't get these. The code I linked to already has debounce built in.

The other part is the light. This is a little more tricky. The light will probably use too much current for the arduino to supply directly. You will need a transistor and a resistor (again, at least 10 kiloOhm is good).

The transistor should be an NPN transistor, and should look like the top one in http://www.reprise.com/host/circuits/transistor\_pinouts.asp. The easiest one is the base - this is the middle one. Connect this via your resistor to another digital pin on your arduino (pin 13 is great for testing this, because it will also light up the led on the Arduino). Next, connect your emitter to ground (GND). Then, IF YOUR POWER SUPPLY IS NO MORE THAN 12 VOLT! you can connect VIN to the + side of the light, and the - side of the light to the collector.

Next, load a sketch - the "blink" sketch is good to test this. Adjust the pin as necessary.

Note that, these switches have a resistor already built in to the light; if you want to do the same with an ordinary led, you will have to add one yourself. Check out http://ledcalc.com/ to tell you which resistor you need.

---
Tags: button
---


# Question
Title: AT command XBee from atmega to disable DIO5 (associated led)
I community! I need put ATcommand to my XBee from my atmega using a "xbee library" and a function that I have found in internet. I think the ATComand is "ATD50" to change the DIO5 to value "0" (disabled). My intention is to turn off a led connected into DIO5 (digital input/output 5 (associated led)) after X second/minutes of turning on the device (so that it doesn't turn one again after initial check).

This is a part of my code:

```
#include <XBee.h>
XBee xbee = XBee();
uint8_t atdCmd[] = {'A','T','D','5','0'}; //<---command to put DIO5 to "0" (disabled)
AtCommandRequest atRequest = AtCommandRequest();
AtCommandResponse atResponse = AtCommandResponse();
void setup()
{
delay(30000);
atRequest.setCommand(atdCmd);
xbee.send(atRequest);
}
void loop()
{}

```

...but it doesn't work! Thanks guys!

# Answer
finally I solved the problem with this code:

```
uint8_t atdCmd[]={'D','5'};
uint8_t value[]={4};///pongo DIO5 a output LOW
uint8_t length=1;
AtCommandRequest atRequest = AtCommandRequest(atdCmd, value, length);
xbee.send(atRequest);

```

The problem was that I tried to put command with 5 caracters,... and only accepts 2 caracters for "AT command"
> 1 votes

---
Tags: arduino-uno, xbee, atmega328
---


# Question
Title: How to wait outside the loop without delay()?
Is it possible to delay a task inside a function that is called only once (meaning, it's not inside the loop) without using delay()?

This library I'm using, for reading sensor measurements via serial has a delay() in it. I want to get rid of it, but I don't how to do it, because the library's function is not looped.

I guess the simple solution would be to move the library functions inside the loop, so I can do a simple check with millis() and run the delayed part as soon as 250 ms have passed. I would like to improve this library though and do a simple, single call for sensor data that doesn't not hold up the entire program.

This is the function with the delay:

```
uint16_t COZIR::Request(char* s)
{
  Command(s);
  // empty buffer
  buffer[0] = '\0';
  // read answer; there may be a 100ms delay!
  // TODO: PROPER TIMEOUT CODE.
  delay(250);
  int idx = 0;
  while(CZR_Serial.available())
  {
    buffer[idx++] = CZR_Serial.read();
  }
  buffer[idx] = '\0';
  uint16_t rv = 0;

  switch(buffer[1])
  {
    case 'T' :
            rv = atoi(&buffer[5]);
            if (buffer[4] == 1) rv += 1000;
            break;
    default :
            rv = atoi(&buffer[2]);
            break;
  }
  return rv;
}

```

I've had a look at the SoftTimer library, but it requires sketches to be written very differently (without a loop). I'm also not sure if I can even pass arguments to delayed tasks with that library.

# Answer
> 3 votes
You could split `Request()` into two separate functions: You call `sendRequest()`, then go do other stuff, then, some time later, you call `getResponse()`. If you get `RESPONSE_NOT_READY`, then you know you have to call it later:

```
#define REQ_WAIT_DELAY     250  // Wait for 250 ms
#define RESPONSE_NOT_READY ((uint16_t) -1)

uint32_t time_request_sent;

void COZIR::sendRequest(char* s)
{
  Command(s);
  time_request_sent = millis();
}

uint16_t COZIR::getResponse()
{
  if (millis() - time_request_sent < REQ_WAIT_DELAY)
      return RESPONSE_NOT_READY;
  buffer[0] = '\0';  // empty buffer
  int idx = 0;
  // From here, same as original COZIR::Request()
}

```

This assumes that `RESPONSE_NOT_READY` (`0xffff`) is not an otherwise valid response. If all 2^16 values of an `uint16_t` may be valid, then you need another way for the library to signal that the response is not ready. Also, make sure you never compare timestamps, because of the `millis()` rollover problem. Taking the difference between two timestamps and comparing this with a specified delay (as in the example above) is rollover-safe.

**Update**: Here is an example of how this could be used:

```
COZIR cozir(some_serial_connection);

void loop()
{
    static bool waiting_for_a_cozir_response = false;

    if (time_to_get_another_cozir_reading()) {
        if (waiting_for_a_cozir_response) {
            report_something_is_wrong("This COZIR is too slow!");
        }
        else {
            cozir.sendRequest("Hi Cozir! Pliz send me another reading.");
            waiting_for_a_cozir_response = true;
            /* We won't get the response on this iteration. *
             * We will ask next time.                       */
        }
    }
    else if (waiting_for_a_cozir_response) {
        uint16_t response = cozir.getResponse();
        if (response == RESPONSE_NOT_READY) {
            /* Nothing to do now, really. We will just try again *
             * at the next loop() iteration.                     */
        }
        else {
            waiting_for_a_cozir_response = false;
            do_something_with_the_cozir_response(response);
        }
    }
    do_whatever_else_has_to_be_done_in_the_loop();
}

```

# Answer
> 0 votes
You can look at the BlinkWithoutDelay example sketch (under Digital). Basically you store the current millis as a variable, then have an if statement to check that it has been more than x milliseconds.

---
Tags: serial, timing
---


# Question
Title: Arduino Uno - What can I make with just the base board
So I just bought my first Arduino (an Uno r3), and dove right in.

All I have currently is the base board (I didn't want to invest too heavily and then realize arduinos weren't for me), so I made a quick script that translates input letters to morse via the LED on the top.

Now that I'm done with that, I figured I'd come here to ask: do you guys have any random ideas for things I can make with JUST the uno? I understand that I should probably just start buying kits and shields, but I'm just curious as to what I can make with the most minimal of items. I consider it a test :)

Thanks in advance guys!

# Answer
> 0 votes
Well,

Your question is very broad. But the Arduino essentially needs controlling gadgteers to make things easy ( and funny ).

However if you know a bit of electronics, then you may be able to use the IN/OUT analog ports and build other interfaces to control, for example the lights of your home, or even better. You can measure and control priate things should be linked. Increasing the power of your home.

If you have interest in cars, then you can perform to connect the on-board computer of your car to the Arduino, like this.

Well, there are numerous ideas, none of these I'm saying is new and there are even libraries ready to be used in these segments mentioned above.

Regards, Andrew Paes

---
Tags: arduino-uno, c++
---


title: Arduino Grounding Issue

text:
# Question
Title: Arduino Grounding Issue
I have a project that turns a LED strip on and off using capacitive touch. The project uses an Arduino Micro as the brain and a 12v wall wart to power everything. I have the Arduino ground and negative from the power supply running to a common ground.

Everything works as expected during testing and the Arduino is connected via USB to my computer; however, when I unplug the USB and connect the circuit to the light installation, the lights just flicker on and off. When I touch my finger to the negative/ground (and presumably provide common ground), everything works as expected.

It seems obvious to me that I have a grounding issue, but really do not know how to proceed. Is there a specific technique for grounding from a wall wart? Do I need to somehow pull the ground/negative down? I feel like there is something obvious that I am missing.

Thank you in advance for any and all help.

# Answer
> 1 votes
Seems like there is a problem in your wall wart, actually some people are having problems using wall wart with arduino. The problem is with the circuit of thre arduino regulator and with sime ripple variances with de wall wart, i sugest you to setup in your project a regulator (7805) and see if the problem is gone. This is by far problem not just with grounding, but with the power suply in general. I was used to make PIC projects and once it was happening exatly the same that happaned to you but the microcontroller started to work when i put my hand or finger close without even touching it :x. Crazy thing. If the power supply isn't well suited, the arduino enter in continous reset looping because of supply noise. So just put an external regulator, an maybe an extra capacitor (generally 10 nF) in arduino micro power supply rais (VCC-GND). Here's my tip. Good look man, tell me if it worked :)

---
Tags: arduino-micro
---


# Question
Title: Arduino PWM output cannot drive MOSFET 0-12V
On an Arduino Uno, the PWM pin 3 is connected to the `gate` pin of an N-channel MOSFET STP16NF06L. The source pin is connected to ground of a 12 V power supply and drain pin connected to a multimeter. The other end of the multimeter is connected to the positive terminal of the power supply.

**Question:** When Arduino varies its PWM output from 0 to 255, the multimeter reading goes from 11.50 V to 12.10 V. Why isn't it 0 to 12 V?

When the FET gate is connected to the Arduino pin that outputs either 0 V or 5 V, the multimeter reading is as expected at 0 V and 12 V respectively.

# Answer
> 1 votes
Assuming you have a suitable FET You should have a circuit in line the following. http://elinux.org/RPi\_GPIO\_Interface\_Circuits#Using\_a\_FET

You should have some kind of load (a multimeter will have too high an impedance). Use a resistor 4.7k or smaller. You should also have a resistor on the gate

# Answer
> 0 votes
When the FET is saturated (pin 3 is high), I would expect the instantaneous voltage to be the full 12 v. When pin 3 is at 0v, there should be no connection across the FET; I would expect the voltage to fluctuate randomly. you might see the same if you measure voltage with nothing touching the probes, especially if the probes move relative to each other.

I'm fairly new to FETs, so I may be on completely the wrong track.

# Answer
> 0 votes
Also put a LED with a resistor connected trough drain, then you read the voltage across the resistor and also have visual feedback with the LED. Resistor should be with 0V when your pin is LOW. It's easier to work with transistor knowing if there is current or not.

---
Tags: arduino-uno, pwm, mosfet
---


# Question
Title: how does serial port communication work under the hood?
im just looking for how to send/ write date to pc over serial port from arduino..vice versa.

I have few Question to ask after taking so much time and couldn't figure it out myself. I hope you guys can guid me please.

First, i found i can use Serial.println() function to send some data then, on the pc side, it just checks and reads the port (/dev/tty..). But, how does this process actually work under the hood? So, if you use serial.println() it knows about where to write?

Second i also found it's something to do with UART communication.. But, inside Hardware.cpp file, i couldn't find any function call to the one for UART.

Third there is the code like extern HardwareSerial Serial; Then where is the definition of this Serial?

Fourth There seem to have ring buffer for serial buffer. So, when data is being sent then, what and who fill the data into this buffer inside Hardware.cpp?

please, forgive my silly question.. i'm just so curious about this..

# Answer
Serial.println knows where to write because Serial is an object. On boards with more than one port there will also be a Serial1,Serial2,etc. Each object corresponds to a port.

The ring buffers are filled from interrupts. When a new byte comes in, it triggers an interrupt that puts the byte in the buffer. When a byte is finished sending it triggers another interrupt that reads the next byte from the buffer and sends it.

Somewhere there is a source file that sets up the UART. It's full of writing special values to registers and low level things like that. I'm not sure what files things are defined in, but if you use the search feature on github there is tons of interesting stuff.
> 2 votes

# Answer
The first question already got a perfectly good answer. I am answering the other ones.

> i couldn't find any function call to the one for UART.

There are no "UART functions" in the MCU. The UART is controlled by reading and writing into special registers. These come by names like `UCSR0A`, `UCSR0B`, `UCSR0C` (USART 0 Control and Status Registers A, B and C), `UBRR0L`, `UBRR0H` (Low and High bytes of the USART 0 Baud Rate Register) and `UDR0` (USART 0 Data Register). These registers are all referenced in HardwareSerial.cpp. You can check the datasheet for their meaning.

> where is the definition of this Serial?

In HardwareSerial.cpp, by the end of the file, right after the comment "Preinstantiate Objects".

> There seem to have ring buffer for serial buffer. So, when data is being sent then, what and who fill the data into this buffer inside Hardware.cpp?

There are actually *two* ring buffers: the receive buffer (`_rx_buffer`) is filled by an interrupt service routine and is emptied by you calling `Serial.read()`. The transmit buffer (`_tx_buffer`) is filled by you calling `Serial.write()`, `Serial.print()` or `Serial.println()` (the line `_tx_buffer->buffer[_tx_buffer->head] = c;` in `HardwareSerial::write()`), and is emptied by an interrupt service routine.

These interrupt service routines are defined in HardwareSerial.cpp. They start with lines like `ISR(SOMETHING_vect)`. They are triggered by the hardware UART. The transmit ISR is triggered when the UART is ready to accept a new byte to transmit (when it is done transmitting byte *n*, it starts transmitting byte *n*+1 and is ready to accept byte *n*+2 in its TX buffer). The receive ISR is triggered when a new byte has been received.

> when does it get initialised?

When you call `Serial.begin()`.
> 2 votes

---
Tags: arduino-uno, programming, serial, c++
---


# Question
Title: datalogging sampling frequency bottleneck
My datalogging system which consits of the Flora, RTC, SD card breakout board, LSM9DS0 sensor is shown in the picture below;

https://www.dropbox.com/s/d8pwcn59nq11lzs/2014-11-25%2012.26.56.jpg?dl=0

The sampling rate/s is capped at 30 when writing into the sd card. If I disable the sensor and only save the time it goes up to 65. Writing into the serial interface rather than the sd card makes the rate goes up even higher at 127. for my application I need at least 100 samples/s. I am thinking the sd card is the problem after making the tests mentioned. The flora clock at 16Mhz is surely able to provide a higher sampling frequency. After checking the sensor datasheet and library I haven't found any limitation either. any input on this issue?

# Answer
First, based on my experience with similar hardware, something about the sd card I/O stinks: it should be plenty fast enough. Using a class 4 (cheapo) sd card I've seen a 16mhz AVR do a FAT filesystem open for appending, write a new record of maybe 70 characters and close the file, all a few hundred times per second. This was with the Arduino "SD" library apparently written by Sparkfun in 2010 and improved by Adafruit sometime later.

Maybe the I/O library you're using is dog slow? Another possibility is that your SD card has a lot of files on it and something about directory (folder) traversal during an open is the bottleneck? (my experience is with just a few files on a given sd card)

But you could try buffering N samples so each sd card write records N samples.

If you do this, don't forget to "flush" any remaining samples when you go from "sampling" to "not sampling" modes, if that's possible. That is, if something is telling the thing 'start', then 'stop', part of the response to 'stop' is to get the N-m buffered samples written out to the sd card.
> 1 votes

# Answer
I have used Sparkfun's OpenLog as I have also found the SD library slow when writing many small samples. It lets you log directly from the Serial connection, so you should be able to get at least the 127 samples per second. You may also try increasing the baud rate, especially if you are using outputting to Serial.
> 0 votes

---
Tags: sd-card, datalogging, rtc
---


# Question
Title: Converting Random Binary Data to PWM Signal
I am using a Arduino Due. I am doing a project on Visible Light Communication. I need to convert a binary data into a PWM Signal. Can anyone suggest me a method of generating that PWM Signal based on the binary data given?

Thank You.

# Answer
So, if you simplu has to convert the binary data to PWM signal there are few things you need to cover:

1. If the binary data that you are receiving from the sensor is linear or non linear.
2. What is the size of binary byte. Ex: int(16 bits),char(8 bits),long (32 bits).
3. If it is linear, then if the data is multiplied by some number it will output a value betwen 0-255.
4. If the data is not linear than you just need to create an giant array with the pwm intensite value direct without any particular mathematical function. Ex: array\[1024\] = {0,1,1,2,3,4,5,5,6,6,10,9,...}; (1024 values because if you are using analog input. Then you can direct output the values from array:

```
analogWrite(3,array[x]); //x being your data

```

Here's the linear Example:

```
   //map(value, fromLow, fromHigh, toLow, toHigh);
    y = map(x, 0, 1023, 0, 255);

```

Doing this, y will receive a value from 0 to 255. You just need to first do a simple serial program that prints you through arduino serial window the binary data and see if the data increases or decreases conform your light project.

* I don't know about your programming levels or if you are using a digital sensor or analog sensor, but if you are using a digital sensor, so you are probaly using SPI communication or i2c. Then you just need to read that binary data and take where the values bits are with bit wize manipulation.

```
y=(x & (0xfff<<3))>>3;

```

Tell me more about the source of data, how this data is and how is the behavior of the data so i can help you a lot more. Thanks
> 2 votes

# Answer
Count the amount of time a signal is high over a certain period, and use the ratio of on time to period as the duty cycle for the PWM signal.
> 1 votes

# Answer
Rather than completely build everything from scratch, perhaps you can use some already tested and debugged Arduino library designed for free-space optical communication, such as

Practically all of these systems convert expand arbitrary binary data to structured "frames" or "packets" of information including some sort of checksum. Each packet is repeated several times; hopefully the receiver catches at least one of them. Each bit of the packet is expanded to either the "pattern representing a 0 bit" (typically turning the LED off for the full bit time) or the "pattern representing a 1 bit" (typically blinking the LED at 38 KHz for the full bit time, typically using a PWM).

To make the hardware and the software simpler and cheaper, most of these systems transmit only a few dozen bits per second. A few free-space optical communication systems are designed to run much faster, such as RONJA.
> 1 votes

---
Tags: arduino-due, pwm, communication
---


title: Arduino uno AVR assembly with LEDs

text:
# Question
Title: Arduino uno AVR assembly with LEDs
I am currently in an introductory assembly language class. My assignment is to use a sparkfun joystick shield kit to do something with an arduino uno. I figure turning on LEDs is the easiest. We must program it in AVR assembly(note: we have only used nasm assembly all semester).

I don't really know how this needs to be done, but I would like the lights to turn on when a button is pressed (one LED per button). I also want to use the analog pins to have the joystick LEDs fade in and out.

below is the code I have right now, and don't have the equipment to test it.

Am I on the right track, or is it a horrible mess? The professor was referring to the arduino pins with hex, but I couldn't find a mapping of the pins and their hex values.

Thanks in advance.

```
.include "/usr/local/include/atmega32u4.def"

        .global  main

        .section .text

main:

        cbi     PortD, 2            ; joystick button
        cbi     PortD, 3            ; right button
        cbi     PortD, 4            ; up button
        cbi     PortD, 5            ; down button
        cbi     PortD, 6            ; left button

        cbi     PortC, 0            ; joystick vertical output
        cbi     PortC, 1            ; joystick horizontal output

        ldi     r16, 0x7c           ; select pins 2-6 for button input mask
        in      ddrd, r16           ; set digital button pins as input
        ldi     r17, 0x03           ; select pins 0 & 1 for joystick input
        in      ddrc, r17           ; set analog joystick pins as input

        ldi     r18, 0x1f           ; select pins 8-12 for button LED output
        out     ddrb, r18           ; set digital button LED pins as output
        ldi     r18, 0x0c           ; select pins 2 & 3 for joystick LED ouput
        out     ddrc, r18           ; set analog joystick LED pins as output

loop:

        ldi     r20, PortD          ; read in from digital pins 0-7
        and     r20, r16            ; apply button input mask
        mov     r20, r20 >> 2       ; shift left twice
        sts     PortB, r20          ; turn on LEDs of pushed buttons

        ldi     r20, PortC          ; read in from analog pins
        and     r20, r17            ; apply joystick input mask
        mov     r20, r20 >> 2       ; shift left twice
        sts     PortC, r20          ; turn on LEDs of joystick movement
        rjmp    loop

```

# Answer
> 2 votes
Did you know that the Arduino Uno uses the Atmel ATmega328P processor?

## using the ADC for analog input in assembly language

You may want to skim through Chapter "24. Analog-to-Digital Converter" of the ATmega328P datasheet.

You may want to read application note "AVR126: ADC of megaAVR in Single Ended Mode" and browse through the corresponding AVR126 example software. (It's in the C language, but it mentions all the registers you'll need to read the ADC in your assembly language program). (As you can tell from the ATmega328 datasheet, the ATmega88 has exactly the same ADC as the ATmega328).

"Assembler source code for the conversion of an analogue voltage to an 8-bit-number", "AVR ASM Introduction: A moron's guide to ADC" and "ATmega8 ADC Example" have a pure assembly language program for reading the ADC on a Atmel AVR chip -- alas, on a slightly different chip that may have slightly different registers than the ATmega328P.

Good luck!

---
Tags: arduino-uno, led, shields, assembly
---


# Question
Title: How to choose between Lithium-ion vs NiMH batteries to power Arduino on the go.
For my next project I'd like to use a battery pack to power my Arduino. I would also like to get a small solar panel and charging module to charge these batteries when possible (during the day).

1. What is the right type of battery for this kind of application?
2. What are the differences given this context?
3. What are the factors I need to consider when choosing a rechargeable battery for this application?

# Answer
> 3 votes
Look at **Battery University** for many good ideas.

Both NimH and LiIon are viable for your application.

LiIon are easier to manage well **if** managed well.
ie do it right and they are easy to manage, but cut corners and they are easier to destroy.

NimH can be abused more with a slow degradation in capacity - although complete destruction is possible.

As a LiIOn cell has a ~= 3.0V to 4.2V range you'd probably probably need a step up inverter with 1 cell, or a buck regulator with 2 cells, which is 'annoying'. If you are prepared to use the cell over say a 3.4V to 4.2V range with an LDO regulator for a 3.3V system then you lose a significant amount of available capacity but increase battery cycle life substantially.

Nimh give 1.0 - 1.2 V/cell so eg

* 6 cells give 6 - 7.2V for a 5V system,
* 5 cells give say 5.25V - 7V if run down to 1.05V for a 5V system with a suitable LDO regulator, and
* 4 cells give 4 - 4.8V for a 3V3 system.

NimH are easier overall to build half well and get half good results.

LiIon are slightly harder to get going with in most cases, work very well if treated well, and are VERY unforgiving of bad treatment past a certain point.

---
Tags: power, voltage-level, battery, current, solar
---


# Question
Title: Communication between python script and Arduino sketch
I'm trying to transfer data beetween the two scripts. I'm already using the YunMesseger library (https://github.com/plotly/YunMessenger). But it only make the

Arduino -\> Python

communication. I would like to know how to make the reverse way.

I would like to point that I'm search for a solution that doesn't involve the use of the Bridge, because I don't want to have concurrency problems.

# Answer
One option is to use spacebrew. This is a cloud-based service, however you can run your own server which is based on node.js, so it should work on the Yun.

Your Arduino can then send or receive data using yunSpacebrew, and you can connect it to python using pySpacebrew. This is a pure python library, so it ought to run fine on the Yun.
> 1 votes

---
Tags: arduino-yun
---


title: Issue with usbserial for arduino clone

text:
# Question
Title: Issue with usbserial for arduino clone
I have attached photo of the clone Uno board recently acquired, and I am working on a Mac OS X 10.7.5

I have sourced the solution from http://javacolors.blogspot.com/2014/08/dccduino-usb-drivers-ch340-ch341-chipset.html

Which suggests to install 340/341CH drivers and run a sudo code. When I plug in the Uno board, the Arduino IDE still does not show under port selection, the "dev.tty.usbserial"

and as such I cannot contact or upload any command to the Uno board. Been trying for a whole day.. please help if you know a possible solution

This is the board:

I bought the board from this site:

http://www.aliexpress.com/item/UNO-KIT-Upgraded-version-of-the-For-Starter-Kit-the-RFID-learn-Suite-Stepper-Motor-ULN2003/1207142899.html

screenshot from the IDE does now show any usbserial

# Answer
> 2 votes
You will need to allow the use of unverified drivers for this version of the Arduino. Unlike the genuine Arduino this board needs the ch340 and ch341 drivers and because they are not verified you will need to run the following command in order for them to work:

sudo nvram boot-args="kext-dev-mode=1"

I just got a handful of these clones (so cheap) and once I installed the drivers and then set the nvram kernel extensions to dev mode all was OK.

# Answer
> 0 votes
This may be better asked on http://apple.stackexchange.com

At the terminal run `ioreg -p IOUSB` then plug in the Arduino and see what changed.

On my Mac the setting is serial.port=/dev/tty.usbmodemfa131

---
Tags: serial, usb, mac-os
---


# Question
Title: What happens if I connect an external power supply, plus to GND and minus to VIN?
So far, I have connected plus to VIN and minus to GND, but I am curious what would happen if I do it the other way around. And I am not going to try in case I break someting.

So, what will happen?

# Answer
> 1 votes
Some systems have protection against people connecting things in reverse.
Some don't.

On unprotected systems you MAY destroy the powered system and/or you MAY destroy the power supply - both these depend on happenstance, system design and luck.

Possibly worse - you may damage the target system in an inobvious way so that it subsequently behaves incorrectly or damages other equipment.

Systems which are designed to be protected may not be protected in all cases. eg if you have a "shield" connected that accesses the Vin pin outside the protection diode the reverse polarity voltage may damage the shield AND current may travel via the shield circuitry back into the Arduino via other connections.

---

Advice on You tube may just sometimes very very occasionally be wrong. Or more often.

If **this "Reference Schematic"** is correct (as you'd hope it was) then Vin is connected to the "inside" of protection diode D1 - so D1 does not protect against reversed polarity. See lines and boxes in red.
Larger version of diagram **here**

D1 does protect against reversed polarity on "PWRIN".
How PWRIN relates to shield feeding I know not.

---
Tags: power
---


# Question
Title: Decide on baud rate for a project using Arduino Uno R3
I am using an Arduino Uno R3 with the MPU 6050 to get motion data. Different example codes use different baud rates, without any proper explanation as to why.

So how do I know which baud rate is perfect for my project?

# Answer
> 5 votes
I most cases it doesn't matter!

In some cases the highest possible is preferred, as it prevents delays. That is when the buffer is full (when sending large amounts of data through the serial connection). As `Serial.write` will block until there is room in the buffer. In most cases this won't be an issue.

When running your arduino at slower speeds, you have to select a lower baudrate, or the micro-controller can't keep up.

When connection to other devices (e.g. GSM shield) using serial, that device may require a specific baudrate.

---
Tags: arduino-uno
---