# Question
Title: Serial.print() is slower than it should be
I'm trying to use Arduino as a DAQ but the `Serial.print()` is not working as fast as I expected. How many bits are sent if you are using a int, because if I use a `uint8_t`, it's taking the same amount of time? How I could improve the speed of the `Serial.print()`? I'm already working at 115200 baud.

# Answer
> 5 votes
> I need a sample rate of 6 kHz

OK, so that means you need to sample and send every 1/6000 seconds (167 µs).

I have a lengthy discussion about the ADC hardware. Amongst other things is a table of conversion times for the different ADC prescalers, assuming a 16 MHz clock:

```
Prescaler
    2    * 13 * 1/16E6  = 0.000001625 (  1.625 µs)
    4    * 13 * 1/16E6  = 0.00000325  (  3.25  µs)
    8    * 13 * 1/16E6  = 0.0000065   (  6.5   µs)
   16    * 13 * 1/16E6  = 0.000013    ( 13     µs)
   32    * 13 * 1/16E6  = 0.000026    ( 26     µs)
   64    * 13 * 1/16E6  = 0.000052    ( 52     µs)
  128    * 13 * 1/16E6  = 0.000104    (104     µs)

```

If you go for maximum resolution (10 bits) you need a prescaler of 128, which takes 104 µs. The number of conversions you can do a second (taking the inverse of the above) is:

```
Prescaler  Conversions/sec
  2           615,385
  4           307,692
  8           153,846
 16            76,923
 32            38,462
 64            19,231
128             9,615

```

---

You also need to take into account the transmission time. At 115200 baud you can transmit one byte every 1/11520 seconds (86.8 µs) so therefore two bytes (16 bits) would take 173.6 µs.

If you sample then transmit you will therefore take, per sample:

```
104 + 174 = 278 µs

```

This is too slow if you want to achieve it inside 167 µs.

---

You can sample asynchronously (in the background) so you transmit one sample while taking the next one, but you are still limited by the transmission speed of serial, so it would still take 174 µs per sample.

In fact, fiddling with the prescaler isn't really the issue here because the serial transmission time is the limiting factor.

Forget about the ADC and how it works for the moment. At 115200 baud you can't transmit 2 x 6000 bytes per second. That is simply because the maximum is 11520 bytes per second.

# Answer
> 2 votes
By not using `Serial.print`?

`Serial.print` will format the number as a string of ASCII characters. The number of characters depends on the size of the number. Yes, that is very wasteful.

If you are sending values between 0 and 255 (`uint8_t`) you can just send the raw value as a single ASCII character, since there are 256 of those.

```
Serial.write(myVal);

```

For anything greater than 255, i.e., you want to send an `int` or `uint16_t` then you will have to come up with some better way. You can't send one byte for the full value, so you would have to send it as two bytes:

```
Serial.write((myVal >> 8) & 0xFF);
Serial.write(myVal & 0xFF);

```

HOWEVER... how do you know which byte coming in is which? It's very very easy to get out of sync and not get the right values when you read the data in. So you need some way of "packetizing" the data so that you know "This is a correct set of values". Just how you do that is entirely up to you - do you just wrap each pair of bytes in a special set of other bytes? Nah - that becomes as wasteful as `Serial.print`. Instead it's better to buffer up a batch of values and send them as a block with just a few extra bytes to define the packet.

One example of doing that is my ICSC library. Take a look at it and you can see how you can craft a packet to send lots of data as one stream of data.

# Answer
> 1 votes
`Serial.print` sends the ASCII representation of the data. So:

```
uint8_t data8 = 102;
uint32_t data32 = 102;
char datastring[] = "102";
Serial.print(each_of_the_previous_data);

```

each of these are sent exactly in the same way, i.e. three bytes ('1', '0', '2', so 0x31 0x30 0x32).

This, as you noticed, is highly inefficient. What I suggest you is to send them in binary mode, so

```
uint8_t *convertToByteArrayLittleEndian(uint8_t *buffer, int32_t val)
{
    uint8_t i;
    for (i = 0; i < 4; i++)
    {
        buffer[i] = val & 0xFF;
        val = val >> 8;
    }
    return buffer;
}
uint8_t *convertToByteArrayBigEndian(uint8_t *buffer, int32_t val)
{
    uint8_t i;
    for (i = 0; i < 4; i++)
    {
        buffer[3-i] = val & 0xFF;
        val = val >> 8;
    }
    return buffer;
}

uint8_t supportArray[4];
uint8_t data8 = 102;
uint32_t data32 = 102;
char datastring[] = "102";
Serial.write(data8); // Sends 0x64 = 100
Serial.print(convertToByteArrayLittleEndian(supportArray,data32),4); // Sends 0x64 0x00 0x00 0x00
Serial.print(convertToByteArrayBigEndian(supportArray,data32),4); // Sends 0x00 0x00 0x00 0x64
Serial.print(datastring); // Sends 0x31 0x30 0x32

```

I had to use an helper function to convert from int to byte array, since Serial.write does not support directly an int. You can choose if you want to send the data in big endian or little endian format.

As you can see, in binary mode the amount of data exchanged varies.

Just three more things.

1) you probably can go higher in frequency (maybe 1Mbit/s) with the serial. Just try it out

2) If you decide to use binary mode, maybe you will need some synchronization (i.e. a start byte) to ensure you are not listening a stream from a "middle" point. There are various techniques (prevent use of some bits in the stream, use some forbidden values and escape it)...

3) If you want to go faster, I suggest you to switch peripheral. For instance use SPI (of course you won't be able to use a common USB-UART interface, but you can create a native USB dongle with an SPI interface to get the connection)

EDIT:

According to other info from the OP:

The data is 10 bits. Let's split it into two 5bits data, so we can use the upper 3 bits for sending sync info (to understand which byte comes first). The required rate is 6kHz.

I made some calculations, and it looks like that you can use this code:

```
#include "TimerOne.h"

bool timerHasBeenTriggered = false;

void setup()
{
    Timer1.initialize(167);         // initialize timer1, and set a 6kHz frequency
    Timer1.attachInterrupt(callback);
    Serial.begin(#HIGHER_THAN_115200#);
}

void callback()
{
    timerHasBeenTriggered = true;
}

void loop()
{
    int16_t val = analogRead(ANALOG_PIN); // takes 104us
    Serial.write((val & 0x1F) | 0xA0); // Send lower 5 bits, upper 3 set to 101
    Serial.write((val >> 5) & 0x1F); // Send lower 5 bits, upper 3 set to 000
    while (!timerHasBeenTriggered);
    timerHasBeenTriggered = false;
}

```

Here the loop has an execution time of around 104us (serial calls just store the values in a queue). The vast majority of the time is spent acquiring from a channel.

I used a timer to trigger the next acquisition so it can be more precise (and the millis() function is useless, since you want to trigger it 6 times per millisecond).

From the PC you will receive two bytes. The first one is in the form `0b101XXXXX`, the second `0b000YYYYY`. You will only have to

1. wait for a byte starting with 101
2. save the other 5 bits (XXXXX)
3. get the next byte and check it starts with 000
4. the data will be just the concatenation of the two 5-bits chunks: YYYYYXXXXX

Note that the limiting factor of the timing is the analogRead function. If you want to go faster (or to acquire from multiple channels) you will need to change the ADC clock prescaler. This, however, will make your ADC frequency higher than 200kHz, which is not recommended (you will get less precise data).

# Answer
> 1 votes
If your signal of interest is of short-enough duration, you might get by by collecting the data into memory, then dumping it at whatever speed you can. If you're using an Uno or other AtMega328 based Arduino, the RAM size, and therefore, your buffer, will be quite limited. Storing the first value as int and subsequent values as one-byte differences can help.

An on-board memory device, like an FRAM, could buffer 8K or 32K bytes (or half as many ints).

Or the same differences technique can be used to send one-byte binary differences and improve your sample transmission rate. It's easy to get out of sync, though. This won't be too reliable for continuous or long data streams.

Otherwise, you're just baud-bound. How fast can you drive the serial output and the receiver still be able to keep up? You're pushing the edges of what the device can do. It's an interesting problem and possibly fun to solve, but I'm reminded of the old adage about alligators and needing to drain the swamp! :)

# Answer
> 1 votes
Some benchmarking of Serial.print() and comparing to clib functions (itoa/ltoa) might give some insight. First, printing int and long int with DEC base using Arduino core Print functions (Arduino IDE 1.6.7, Arduino Mega2560).

```
Serial.print(12345, DEC): 240 us
Serial.print(12345678L, DEC): 388 us

```

Second, use HEX base.

```
Serial.print(0x1234, HEX): 204 us
Serial.print(0x12345678L, HEX): 384 us

```

Third, use the AVR clib functions to convert number to a string and then print the string. 10 and 16 base.

```
Serial.print(itoa(12345, buf, 10)): 104 us
Serial.print(ltoa(12345678L, buf, 10)): 240 us

Serial.print(itoa(0x1234, buf, 16)): 80 us
Serial.print(ltoa(0x12345678L, buf, 16)): 240 us

```

Cheers!

---

Below is the test sketch:

```
void setup()
{
  uint32_t start, stop, us;
  char buf[16];
  Serial.begin(9600);

  start = micros();
  Serial.print(12345, DEC);
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(12345, DEC): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(12345678L, DEC);
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(12345678L, DEC): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(0x1234, HEX);
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(0x1234, HEX): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(0x12345678L, HEX);
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(0x12345678L, HEX): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(itoa(12345, buf, 10));
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(itoa(12345, buf, 10)): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(ltoa(12345678L, buf, 10));
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(ltoa(12345678L, buf, 10)): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(itoa(0x1234, buf, 16));
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(itoa(0x1234, buf, 16)): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(ltoa(0x12345678L, buf, 16));
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(ltoa(0x12345678L, buf, 16)): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

}

void loop()
{
}

```

The clib itoa/ltoa are regarded to be relative slow and there are proposals to improve performance. Please see, for instance, this bug report.

---
Tags: serial, data-type
---


title: Atmel AVR languages

text:
# Question
Title: Atmel AVR languages
Hello I recently purchased some atmel AVR chips. You can programme them in Arduino. I was wondering if it is possible to programme them in any other language except for C or Arduino. Also can you use just binary instead of C?

# Answer
> 1 votes
> I was wondering if it is possible to programme them in any other language except for C or Arduino.

I have seen this question before. Here is a great answer with a lot of links:

https://stackoverflow.com/questions/6590161/programming-languages-targeting-arduino-avr

There are also a number of libraries/platforms/frameworks as the Arduino core to help you up from "bare metal".

Cheers!

# Answer
> 1 votes
You can program them in C or C++ through the avr-gcc compiler. Arduino uses C++ (-std=gnu++11) and automatically includes a few libraries, as well as generating forward declarations for anything in the top level .ino file automatically.

You can write AVR assembly and translate it to machine code using avr-as (a portion of avr-gcc)

There is nothing stopping you from just writing whatever bytes you want to program memory if you want to write machine code.

You can look through the avr instruction set if you are interested in those last two options.

---
Tags: atmega328
---


# Question
Title: Not able to upload any code to Arduino Uno
NOTE: Using the Arduino Uno

I am WORKING on a project that I have to submit in a few days. My arduino was all set up and was working fine.

Project:Arduino controls a 9v motor depending on the command given. As the arduino only provides 5v , i added a 9v battery to it through a transistor

I decided to add new code into the arduino but when I tried it failed. I have uploaded code thousands of times before (successfully) all of a sudden the IDE keeps giving the following message

> avrdude: ser\_open(): can't open device "\\.\COM3": Access is denied.

I have looked up for a lot of solutions on this forum and elsewhere. Here are the things I have tried so far:

1. Changing the COM port
2. Disabling all the other devices CONNECTED to COM
3. Tightening the CONNECTIONS
4. Re installing all the drivers and the IDE
5. Rebooting the system
6. Using another laptop to upload code

All the above have given me the same output for some reason. The built in LED light and the power LED switch on when the board is CONNECTED to a power source (my laptop). Could the board have been damaged by any chance ? How can I check if the board is spoilt ? Should I buy a new board ?

# Answer
I have a post Have I bricked my Arduino Uno? Problems with uploading to board \- that describes various tests you can carry out to isolate where the problem is.
> 2 votes

# Answer
Have you tried changing the Microprocessor in the Arduino Uno? An AtMega320P is much cheaper than new Arduino, and usually only the microprocessor gets spoilt, rest of the board remains intact.
> 1 votes

# Answer
Could be the OS not allowing the application to access the COM ports, there is a terminal command to give the Arduino IDE access to the specific COM port.
> 1 votes

# Answer
1. Remove all device connect to uno, and upload code to uno. Because, your device like motor will confuse uno.
2. Check you usb to serial device.
3. Check your uno
> 0 votes

# Answer
Check the device that the IDE says you're connected to.

http://forum.arduino.cc/index.php?topic=51489.0
> 0 votes

---
Tags: arduino-uno, uploading
---


# Question
Title: Quick start on Arduino for experienced embedded programmer?
I'd like catch up the Arduino concepts (programming & IDE). There are excellent online tutorials available for Arduino but all of them which I saw are made for those who didn't have embedded/electronics background. Going through them is heavily time consuming as I'm already familiar with the embedded programming other than Arduino or Raspberry Pi.

Does any one know any quick reference materials for Arduino which excludes electronic/embedded basics which is meant for experienced embedded programmer? That could be a big time saver for me.

Thanks in advance!

# Answer
> 5 votes
As far as I know, there is no tutorials about using Arduino's for, e.g. "multi-tasking, real time response". That is not the focus of the Arduino community.

The Arduino UNO development board is built around Atmel's ATmega328. The Summary datasheet gives an overview of its hardware capabilities on the first page. If you are familiar with MCU development, that should give you a feel for its hardware capabilities. The complete ATmega8/168/328 datasheet is over 600 pages, and describes every feature, with all registers in detail.

The Arduino IDE uses gcc under the covers. So you likely already know how to use that. When you download and install the Arduino IDE, gcc and gnu binutils for AVR will be installed too.

The Arduino IDE has all of the Atmel header files, so much of the code in the datasheet should compile, link and upload.

The IDE is really designed for beginners. It is to easy to use, but has very few features beyond basic editing, compiling and loading. It does support a serial-monitor to see text printed by the uploaded application, but it doesn't support a debugger like GDB out-of-the-packet.

However, it doesn't prevent you writing C++ code and header files, and it will build the whole collection of files.

Because the IDE lets you create and edit C++ directly, you can install the IDE on any of the three main platforms, and get started very quickly.

You will probably want to visit AVRFreaks who tend to focus at a lower level than Arduino.

There is also AVR LibC library which points you at the documentation for the AVR upload tool, avrdude, and debugger.

Summary: Install Arduino IDE, do a couple of quick projects to get a feel for the system. Then start writing C++ as normal. Install AVR LibC library for a more traditional library, and visit AVRFreaks forums for more technical help and information.

# Answer
> 1 votes
> But I suppose to debug an existing Arduino project (which my friend gave to me because the developer left from his small electronic company) developed for GSM based remote motor control product. They haven't used Arduino board but used Arduino IDE/library for coding. Flashed the hex output from Arduino on their custom board with Atmel processor. So I need to go through the existing Arduino code and help them to solve the issue that they are facing.

This is maybe one of the worst type of projects to get involved in. Code that needs debugging on a platform that you have not used before. Code that you might not know the status of and where the requirements are loose.

I would recommend starting by getting all the details on the table. Understand the intended software architecture, estimate memory foot-print, and processing, etc - if the product is feasible. There might be a reason for the developer ditching this project?

AVR is small scale embedded and that implies a very different implementation strategy. There is no operating system and much of the code is bare metal.

The Arduino core is a platform (library) that abstracts a small set of basic hardware functions. It was originally intended for Media/Design Students. To help reduce the threshold when getting started the IDE has build support, i.e. pre-processing, such as an implicit add of the Arduino header file (Arduino.h) and generation of forward declarations for functions in a sketch. The IDE does not use make/makefiles. Source code is C/C++ (AVR GCC) and if necessary AVR assembly.

The quick reference for the Arduino core function can be found here. There is also a list of libraries. Some are packaged with the Arduino IDE/core while others need to be installed. There is a library manager in the IDE to download and install some of the libraries. New libraries are added more or less daily right now.

Depending on the code you will have to read more about the libraries used and/or internal AVR hardware (registers, functions, etc).

Cheers!

---
Tags: documentation
---


# Question
Title: How to Store 2 analogRead values and read using EEPROM for Arduino Uno?
Trying to write 2 values coming from `analogread(A0)` and `analogread(A1)` by `EEPROM.write` and retrieve the values by `EEPROM.read`. I tried the following sketch for each write and read. However, could not get the values. Any help please.

For writing to EEPROM:

```
#include <EEPROMex.h>
int addr = 0;
int array[] = {0, 0};
char a;
void setup() {
}
void loop() {
    array[0] = analogRead(0) / 4;
    array[1] = analogRead(1) / 4;
    EEPROM.write(addr, a);
    addr = addr + 1;

    if (addr == 512) {
        addr = 0;
    }

    delay(100);
}

```

For reading from EEPROM is:

```
#include <EEPROM.h>
int address = 0;
int value[2];
void setup() {
    Serial.begin(9600);

    while (!Serial) {
        ;
    }
}
void loop() {
    value = EEPROM.read(address);
    Serial.print(address);
    Serial.print("\t");
    Serial.print(value[0]);
    Serial.print("\t");
    Serial.print(value[1]);
    Serial.println();
    address = address + 1;

    if (address == 512) {
        address == 0;
    }

    delay(500);
}

```

# Answer
See Reading and Writing Data Structures to EEPROM.

```
EEPROM.write(addr,a);

```

You can't *directly* write arrays. See the link for how to do it.

Example code:

```
#include <EEPROM.h>
#include <EEPROMAnything.h>

int array[2];
int addr=0;

void setup()
{
}

void loop()
{
  array[0] = analogRead(0)/4;
  array[1] = analogRead(1)/4;
  EEPROM_writeAnything(addr, array);
  addr += sizeof (array);

  if(addr >= 512)
    exit (1);

  delay(100);
}

```

Your posted code is a bit flawed anyway. You know EEPROM has a limited life? If you have a sketch that writes to EEPROM indefinitely you will wear it out.

My code above stops once it reaches address 512.
> 1 votes

# Answer
You write the read value directly to `value`, while value is actually and array. Try this instead.

```
void loop() {
    value[0] = EEPROM.read(address);
    value[1] = EEPROM.read(address + 1);
    Serial.print(address);
    Serial.print("\t");
    Serial.print(value[0]);
    Serial.print("\t");
    Serial.print(value[1]);
    Serial.println();
    address = address + 2;

    if (address == 512) {
        address = 0;
    } // not address==0;

    delay(500);
}

```
> 0 votes

# Answer
EEPROM can store one byte at a location. To store value of int, it requires two consecutive location. For double, it requires four memory location. I have written code to store and read, int & double to and from built-in EEPROM. Modify as per your need.

```
/*
  StackExchange Question: "How to Store 2 analogRead values and read using EEPROM for Arduino uno?"
  Question Id: 15910 (http://arduino.stackexchange.com/questions/15910/how-to-store-2-analogread-values-and-read-using-eeprom-for-arduino-uno)
  Author: Anurag S. Vasanwala (AnuragVasanwala@gmail.com)

  Tested on Arduino Version 1.6.7

  Description:  This sketch helps to store and read, Integer & Double to and from built-in EEPROM.
  Objectives:
    + Write Integer @ Specified Address (Fn: EEPROM_Write_Int)
      + Conversion from Integer to Byte Array
      + Store Bytes
    + Read Integer from Specified Address (Fn: EEPROM_Read_Int)
      + Read Bytes
      + Conversion from Byte Array to Integer
    + Write Double @ Specified Address (Fn: EEPROM_Write_Double)
      + Conversion from Double to Byte Array
      + Store Bytes
    + Read Double from Specified Address (Fn: EEPROM_Read_Double)
      + Read Bytes
      + Conversion from Byte Array to Double
 */
#include <EEPROM.h>

// MACRO : Combines FROM_BYTES into TO_OBJECT of datatype "DATATYPE"
#define CombineBytes(FROM_BYTES, DATATYPE, TO_OBJECT) \
  TO_OBJECT = *((DATATYPE *)FROM_BYTES);

// MACRO : Splits FROM_DATA of DATATYPE into equivalent byte array TO_BYTES
#define GetBytes(FROM_DATA, DATATYPE, TO_BYTES) \
  *((DATATYPE *)TO_BYTES) = FROM_DATA;

// Writes Integer's equivalent bytes to Address and Address + 1
void EEPROM_Write_Int(unsigned int Address, int Data)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(int);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  // Call macro to store byte array into Temp_Buffer from Data
  GetBytes(Data, int, Temp_Buffer);

  // Write number of bytes to memory location specified in Address and so on
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    EEPROM.write(Address + Index, Temp_Buffer[Index]);
  }
}

// Reads two bytes from Address and Address + 1 and returns equivalent int
int EEPROM_Read_Int(unsigned int Address)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(int);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  int Result;

  // Read number of bytes from memory location
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    Temp_Buffer[Index] = EEPROM.read(Address + Index);
  }

  // Call macro to combine bytes into equivalent to int
  CombineBytes(Temp_Buffer, int, Result);

  return Result;
}

// Writes Double's equivalent bytes to Address, Address + 1, Address + 2 and Address + 3
void EEPROM_Write_Double(unsigned int Address, double Data)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(double);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  // Call macro to store byte array into Temp_Buffer from Data
  GetBytes(Data, double, Temp_Buffer);

  // Write number of bytes to memory location specified in Address and so on
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    EEPROM.write(Address + Index, Temp_Buffer[Index]);
  }
}

// Reads four bytes from Address, Address + 1, Address + 2 and Address + 3 and returns equivalent double
double EEPROM_Read_Double(unsigned int Address)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(double);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  double Result;

  // Read number of bytes from memory location
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    Temp_Buffer[Index] = EEPROM.read(Address + Index);
  }

  // Call macro to combine bytes into equivalent to double
  CombineBytes(Temp_Buffer, double, Result);

  return Result;
}

void setup()
{
  // Initialize Serial @ 9600 baud
  Serial.begin(9600);

  // Print size of datatype just for reference
  /* Serial.print("Size of byte = ");
  Serial.println(sizeof(byte));
  Serial.print("Size of int = ");
  Serial.println(sizeof(int));
  Serial.print("Size of float = ");
  Serial.println(sizeof(float));
  Serial.print("Size of double = ");
  Serial.println(sizeof(double)); */

  int myInt1 = -290;
  int myInt2;
  double myDbl1 = 23.41;
  double myDbl2;

  // Write myInt1 @ 100 memory location; It requires 2 consequtive memory location to store integer
  EEPROM_Write_Int(100, myInt1);

  // Read integer located @ memory location 100 and assign it to myInt2
  myInt2 = EEPROM_Read_Int(100);
  Serial.println(myInt2);

  // Write myInt1 @ 200 memory location; it requires 4 consequtive memory location to store double
  EEPROM_Write_Double(200, myDbl1);

  // Read double located @ memory location 200 and assign it to myDbl2
  myDbl2 = EEPROM_Read_Double(200);
  Serial.println(myDbl2);
}

void loop()
{

}

```

> This code is successfully tested on Arduino Version "1.6.7".
> 0 votes

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


# Question
Title: Why the 4.7 K Ω resistor in this pitch follower sketch?
I am reading *Arduino for Dummies*, and I am blocked at the pitch follower exercise. It consists in making a piezo vary with a light sensor. I can't see the point of the resistor (and why 4.7?) in this sketch:

Any help for a dummy is appreciated! :-)

# Answer
The resistor couples with the LDR to form a *voltage divider*. The voltage at the point where the resistor and LDR join will vary depending on the ratio of the two resistances - the resistance of the LDR and the 4700 ohm resistor.

The value of 4700 is chosen to allow a reasonable range of voltages when in a ratio with the LDR, and the best value depends on the resistance range of the LDR.
> 7 votes

# Answer
*Arduino measures Voltages on pins A0 to A5; but the LDR is a variable resistor (varying with Light). So we need to convert the varying resistance to a voltage that the Arduino can measure.*

For more details see here.

Cheers!
> 1 votes

---
Tags: arduino-uno
---


title: Nokia32/RCMM IR decoding issues

text:
# Question
Title: Nokia32/RCMM IR decoding issues
I am trying to decode the IR signals from a remote. I'm using an Arduino Pro Micro, and a TSOP38238 IR receiver.

I found out that the remote uses the Nokia32(RCMM) protocol, and I have been able to partially decode it using cyborg5/IRLib (specifically this one: rcmm.ino). I tweaked the values of the example using the LIRC file corresponding to my remote, mainly the absolute error tolerance (Freebox\_V5.lircd.conf).

Compared to other remotes I tried (with different protocols) the RCMM algorithm doesn't manage to decode the signal every time. Around 40% of the time when I press a button I got an "Unknown type received" output from the decoder.

The following is three outputs (for the same button) of the algorithm for a successful decoding and below two other outputs corresponding to two failures. Could anyone tell me what could be done to increase the success of the decoding algorithm?

## **Successful**

```
Decoded RCMM: Value:2400A601 (32 bits)
Raw samples(36): Gap:63264
  Head: m410  s290
0:m160 s290 1:m160 s590      2:m210 s390    3:m210 s240
4:m210 s240 5:m210 s240      6:m210 s240    7:m210 s240
8:m210 s540 9:m210 s590      10:m210 s390   11:m210 s590
12:m160 s290    13:m160 s290         14:m160 s240   15:m210 s440

16:m160
Extent=9810
Mark  min:160    max:210
Space min:240    max:590

```

## **Failure 1**

```
Unknown type received. Ignoring.
Decoded Unknown(0): Value:0 (0 bits)
Raw samples(36): Gap:3148
  Head: m410  s290
0:m160 s240 1:m210 s590      2:m210 s390    3:m210 s240
4:m210 s240 5:m210 s240      6:m160 s290    7:m160 s290
8:m160 s590 9:m210 s590      10:m160 s440   11:m210 s590
12:m160 s240    13:m210 s240         14:m210 s240   15:m210 s390

16:m210
Extent=9810
Mark  min:160    max:210
Space min:240    max:590

```

## **Failure 2**

```
Unknown type received. Ignoring.
Decoded Unknown(0): Value:0 (0 bits)
Raw samples(32): Gap:27904
  Head: m410  s290
0:m160 s290 1:m160 s590      2:m160 s490    3:m160 s240
4:m210 s240 5:m160 s290      6:m160 s290    7:m160 s290
8:m160 s290 9:m160 s590      10:m160 s490   11:m160 s590
12:m160 s1190   13:m160 s440         14:m160
Extent=9460
Mark  min:160    max:210
Space min:240    max:1190

```

# Answer
> 3 votes
I'm unable to provide a complete answer yet but my research so far into a similar quest to use a similar remote can at least answer why you are getting two values for the same button on the remote. This is by design: the Nokia-32 RCMM protocol of this remote uses toggling codes that flip between one value and another on alternating presses of the same button.

My quest and the challenges of decoding this remote are documented in this thread: https://github.com/bengtmartensson/harctoolboxbundle/issues/97 where I discover that my IR remote uses Nokia 32 protocol but with mark and space timings slightly different from what most Arduino libraries are programmed for requiring a tweak to the signal in order to enable other libraries to decode it successfully.

Further information here: http://www.avsforum.com/forum/93-remote-control-area/1517341-theater-master-mx-500-remote-won-t-learn-bell-fibe-remote-any-help.html#post24345872 where we learn:

> it is different from most IR signals, because it has 4 different off durations, denoting zero, one, two , or three, while traditionally IR protocols have used just two off durations signifying zero or one.

---
Tags: ir, arduino-pro-micro
---


# Question
Title: Is Teensy compatible with the Arduino keyboard library?
I am thinking about buying some Teensy micro-controllers, but I want to know if the teensy are compatible with the arduino keyboard library.

# Answer
It looks like the Teensy designer uses the standard Arduino mouse and keyboard library:

https://www.pjrc.com/teensy/td\_keyboard.html

On another note, I'm sure Teensy is a fine product, but I prefer other open hardware solutions like Pro Micro which can be had on AliExpress.com for under $4 ea.
> 1 votes

---
Tags: library, teensy, keyboard
---


# Question
Title: Possible to store variables directly in EEPROM?
Is it possible to store a variable directly in EEPROM and retrieve it *without* needing to use a library?

I'm building a project that can change the colour of an RGB LED and I want to store the colour in a non-volatile memory space, but I was wondering if I could avoid using one of the EEPROM libraries and have a global variable stored in nonvolatile memory, but still accessed directly, without needing to call a function.

# Answer
Writing and reading EEPROM is possible to do without a library. Take a look at the datasheet of the ATmega328P to find an example: On page 25 / 26 there are example codes for reading and writing both in assembler and C. They do wrap it in a function but as I said in a comment if you only have place in your code where you would like to access EEPROM you can put the code there without duplication. These functions write and read one byte at a time, so if you want to store larger datatypes (a 16-bit integer for example) you already need to call the routines more than once.

Note that the EEPROM has a limited life cycle of at least 100,000 write/erase cycles (cells must be erased before they can be written, reads are unlimited) and it is considerably slower than SRAM (typ. 3.3 ms for writing a byte). You also need to make sure no interrupts interfere with the write process.

However, in the sense of the question it seems this is not what you want: You cannot just create a global variable and have it magically being written to EEPROM.
> 3 votes

# Answer
EEPROM can store one byte at a location. To store Integer variable, it requires two consecutive location. For Double, it requires four consecutive memory location. I have written function to store and read, int & double to and from built-in EEPROM. As per your question, you can modify it as per your need.

> Actually this answer was copied from another thread.

```
/*
  StackExchange Question: "How to Store 2 analogRead values and read using EEPROM for Arduino uno?"
  Question Id: 15910 (https://arduino.stackexchange.com/questions/15910/how-to-store-2-analogread-values-and-read-using-eeprom-for-arduino-uno)
  Author: Anurag S. Vasanwala (AnuragVasanwala@gmail.com)

  Tested on Arduino Version 1.6.7

  Description:  This sketch helps to store and read, Integer & Double to and from built-in EEPROM.
  Objectives:
    + Write Integer @ Specified Address (Fn: EEPROM_Write_Int)
      + Conversion from Integer to Byte Array
      + Store Bytes
    + Read Integer from Specified Address (Fn: EEPROM_Read_Int)
      + Read Bytes
      + Conversion from Byte Array to Integer
    + Write Double @ Specified Address (Fn: EEPROM_Write_Double)
      + Conversion from Double to Byte Array
      + Store Bytes
    + Read Double from Specified Address (Fn: EEPROM_Read_Double)
      + Read Bytes
      + Conversion from Byte Array to Double
 */
#include <EEPROM.h>

// MACRO : Combines FROM_BYTES into TO_OBJECT of datatype "DATATYPE"
#define CombineBytes(FROM_BYTES, DATATYPE, TO_OBJECT) \
  TO_OBJECT = *((DATATYPE *)FROM_BYTES);

// MACRO : Splits FROM_DATA of DATATYPE into equivalent byte array TO_BYTES
#define GetBytes(FROM_DATA, DATATYPE, TO_BYTES) \
  *((DATATYPE *)TO_BYTES) = FROM_DATA;

// Writes Integer's equivalent bytes to Address and Address + 1
void EEPROM_Write_Int(unsigned int Address, int Data)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(int);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  // Call macro to store byte array into Temp_Buffer from Data
  GetBytes(Data, int, Temp_Buffer);

  // Write number of bytes to memory location specified in Address and so on
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    EEPROM.write(Address + Index, Temp_Buffer[Index]);
  }
}

// Reads two bytes from Address and Address + 1 and returns equivalent int
int EEPROM_Read_Int(unsigned int Address)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(int);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  int Result;

  // Read number of bytes from memory location
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    Temp_Buffer[Index] = EEPROM.read(Address + Index);
  }

  // Call macro to combine bytes into equivalent to int
  CombineBytes(Temp_Buffer, int, Result);

  return Result;
}

// Writes Double's equivalent bytes to Address, Address + 1, Address + 2 and Address + 3
void EEPROM_Write_Double(unsigned int Address, double Data)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(double);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  // Call macro to store byte array into Temp_Buffer from Data
  GetBytes(Data, double, Temp_Buffer);

  // Write number of bytes to memory location specified in Address and so on
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    EEPROM.write(Address + Index, Temp_Buffer[Index]);
  }
}

// Reads four bytes from Address, Address + 1, Address + 2 and Address + 3 and returns equivalent double
double EEPROM_Read_Double(unsigned int Address)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(double);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  double Result;

  // Read number of bytes from memory location
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    Temp_Buffer[Index] = EEPROM.read(Address + Index);
  }

  // Call macro to combine bytes into equivalent to double
  CombineBytes(Temp_Buffer, double, Result);

  return Result;
}

void setup()
{
  // Initialize Serial @ 9600 baud
  Serial.begin(9600);

  // Print size of datatype just for reference
  /* Serial.print("Size of byte = ");
  Serial.println(sizeof(byte));
  Serial.print("Size of int = ");
  Serial.println(sizeof(int));
  Serial.print("Size of float = ");
  Serial.println(sizeof(float));
  Serial.print("Size of double = ");
  Serial.println(sizeof(double)); */

  int myInt1 = -290;
  int myInt2;
  double myDbl1 = 23.41;
  double myDbl2;

  // Write myInt1 @ 100 memory location; It requires 2 consequtive memory location to store integer
  EEPROM_Write_Int(100, myInt1);

  // Read integer located @ memory location 100 and assign it to myInt2
  myInt2 = EEPROM_Read_Int(100);
  Serial.println(myInt2);

  // Write myInt1 @ 200 memory location; it requires 4 consequtive memory location to store double
  EEPROM_Write_Double(200, myDbl1);

  // Read double located @ memory location 200 and assign it to myDbl2
  myDbl2 = EEPROM_Read_Double(200);
  Serial.println(myDbl2);
}

void loop()
{

}

```

> This code is successfully tested on Arduino Version "1.6.7".
> 2 votes

# Answer
You can have a global variable in EEPROM if the EEPROM is memory mapped. Memory-mapping the EEPROM is possible on ATxmega chips. Notice that writes go to a temporary buffer, not the EEPROM itself, until you explicitly issue a write command.

Most Arduinos, however, use ATmega chips, which do not have this feature. I am not aware of any xmega-based Arduino or clone.
> 2 votes

---
Tags: eeprom
---


# Question
Title: connection issues with 3 arduinos any suggestions?
I have 3 arduinos that I want to program on, all of them with their own cable and I have tried to connect them to my laptop on several different usb ports, my usb ports work with mouses so that's unlikely to be the problem. However I just cannot connect to them they just don't appear under /dev/ttyACM\* and the arduino IDE cannot find them either. I'm running ubuntu 14.04 any suggestions for finding out what is likely to be wrong with my system or the arduinos?

For some odd reason they now all appear to be seen as /dev/ttyACM\* but they now all give me a

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

```

error

Anybody have any idea how to fix? The arduino's do not have any wires in them except usb (nothing in reset or any other pin), I'm on ubuntu so the drivers shouldn't be an issue? And pin 13 flashes when I reset the arduino.

# Answer
> 2 votes
it's been a while but a long time later I found that the cable I was using was broken. A different cable worked.

---
Tags: arduino-uno, usb
---


title: POST request not working

text:
# Question
Title: POST request not working
I'm following a guide on storing sensor data to MySQL:

Guide

My POST request isn't getting any results to my server. For now, I'm only storing temperature.

Here is my code for saving data:

```
void sendData(double input) {
  String data = "sensorid=3000000&temp=" + doubleToString(input, 2) + "&hum=1.2";

  if (client.connect("192.168.1.50", 80)) {
    client.println("POST /arduino/add.php HTTP/1.1");
    client.println("Host: 192.168.1.50");
    // client.println("User-Agent: Arduino/1.0");
    // client.println("Connection: close");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.print(data.length());
    client.println();
    client.print(data);

    Serial.println("Sent data: " + data);
  }

  if (client.connected()) {
    client.stop();
  }

  delay(300000);
}

```

I've commented out two headers since it did not give any other results. My `Serial.println` gives: Sent data: sensorid=3000000&temp=24.00&hum=1.2, which means that the Arduino is connected to the given IP-adress and that my request data is as I want. They are also working perfectly when I'm testing with Requestmaker, so I'm pretty sure my error comes from the way I'm doing the request here.

Do you have any idea how I can solve or debug this?

# Answer
*Answered by Edgar Bonet*

There needs to be an empty line between the headers and the body of the request. Therefore you have to `println()` (not `print()`) the end of the last header.
> 1 votes

---
Tags: ethernet, datalogging
---


title: RGB LED Resistance

text:
# Question
Title: RGB LED Resistance
In tutorials I've seen, people connect every LED of a RGB LED to a resistance. I understand the purpose, but could we simply put the same resitance once, if we connect it to the common cathode or annode?

Example:

# Answer
The problem with one resistor in common anode/cathode is that when you activate more than one colour of the RGB LED, you will have additional current flowing through the one resistor which will cause increased voltage drop across the one resistor due to ohms law which will cause less forward voltage across the LED and likely extinguish it or at least make it much less bright.
> 5 votes

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


# Question
Title: Controlling 3 stepper motors simultaneously
I have three stepper motors connected to the drv8825 drivers to an arduino uno.

I am using the example code below (from here), which works fine for moving multiple stepper motors at the same time BUT they all move for the same number of steps and in the same direction. I would like to tweak the code so that all of them move at the same time but each one for a different number of steps and in different directions. The motor with the least steps would probably have to wait for the motor with the most steps to finish its movement before going again.

```
int dirPin = 8;
int stepperPin = 7;
int bdirPin = 6;
int bstepperPin = 5;

void setup() {
 pinMode(dirPin, OUTPUT);
 pinMode(stepperPin, OUTPUT);
 pinMode(bdirPin, OUTPUT);
 pinMode(bstepperPin, OUTPUT);
}
 void step(boolean dir,int steps){
 digitalWrite(dirPin,dir);
 digitalWrite(bdirPin,dir);
 delay(50);
 for(int i=0;i<steps;i++){
 digitalWrite(stepperPin, HIGH);
 digitalWrite(bstepperPin, HIGH);
 delayMicroseconds(800);
 digitalWrite(stepperPin, LOW);
 digitalWrite(bstepperPin, LOW);
 delayMicroseconds(800);
 }
}
void loop(){
 step(true,1600);
 delay(500);
 step(false,1600*5);
 delay(500);
}

```

Thank you in advance for your help!

# Answer
> 0 votes
You would first have to provide all the necessary information to your `step()` function: direction and number of steps for *each* motor. Then you just have to stop the loop at different points for each motor. You do this by running the loop up to the number of steps of whichever motor needs to run for longer, and making the steps of each motor conditional on the loop index, as follows:

```
void step(boolean dir0, int steps0,
          boolean dir1, int steps1,
          boolean dir2, int steps2) {
    digitalWrite(dir0Pin, dir0);
    digitalWrite(dir1Pin, dir1);
    digitalWrite(dir2Pin, dir2);
    delay(50);
    int max_steps = max(max(steps0, steps1), steps2);
    for (int i = 0; i < max_steps; i++) {
        if (i < steps0) digitalWrite(stepper0Pin, HIGH);
        if (i < steps1) digitalWrite(stepper1Pin, HIGH);
        if (i < steps2) digitalWrite(stepper2Pin, HIGH);
        delayMicroseconds(800);
        if (i < steps0) digitalWrite(stepper0Pin, LOW);
        if (i < steps1) digitalWrite(stepper1Pin, LOW);
        if (i < steps2) digitalWrite(stepper2Pin, LOW);
        delayMicroseconds(800);
    }
}

```

It would be more elegant to put the data for all the motors in an array, and you would probably want to do so if you have more than three motors.

# Answer
> 2 votes
You need a struct for each stepper with a timestamp, a position and rate of change and a loop that updates the postion based on rate which is the change in position over some time:

```
struct stepper {
  unsigned long timestamp;
  int position;
  int rate;
};

// init steppers array

while (keepGoing()) {
  unsigned long now = millis();
  int si;

  delay(10);

  for (si = 0; si < 3; si++) {
    struct stepper *stepper = &steppers[si];

    if (steppers[si].timestamp > now) {
       steppers[si].position += steppers[si].rate;
       steppers[si].timestamp = now + 100;
    }
  }

```

This is a back-of-a-napkin sketch of course. It is only supposed to illustrate how you can update any number of things concurrently.

The important thing is that you only call delay once. And presumably it would be only a very short delay compared to the unit of time for the rate. In the above example it would adjust the stepper position every 100ms. You would need to experiment with the timing to find a good behavior given the speed of the stepper, speed of the code and maximum permitted rate.

Beware that there is a lot to think about beyond this. For example, you should initialize the timstamps with different timestamps so that the motors are not all running at the same instant and thus *try* to minimize the total power consumed by the motors at any particular time.

Note that I have never played around with stepper motors but this type of loop is a common programming idiom for handling things concurrently.

# Answer
> 2 votes
I have two ideas:

* I don't have personal experience working with the AccelStepper Library, but I believe it implements a class that allows you to work with multiple steppers.
* I plan on controlling two steppers for a project of my own (a self-balancing robot implemented with an STM32 processor), and I plan on using hardware timer interrupts to control the speed of my motors. A quick google search shows that a similar approach is possible with Arduino. You can probably use `Timer0`, as 1ms is fairly fast for a single step. This has several benefits...
    + The refresh function will run on set intervals, (allowing you to control the speed very precisely.
    + It will run with the correct timing, even if there is a function in `loop()` that is taking a long time.

**Note: do NOT put any `delay` statements in your interrupt handlers.** If you do this, it will probably prevent other interrupts from occurring and cause some API functions (such as `millis` or `micros`) to misbehave. In addition, the execution of anything in `loop` is halted while the interrupt is being handled, meaning that you would effectively stop everything until the interrupt is done. See the caveat in Arduino reference page for `delay`.

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


# Question
Title: Arduino & ARM - Replacement for avr-libc?
There is very cool avr-libc library that provides direct access for all functions of AVR microcontrollers. I'm writing a project for **Arduino Due** and I want to use timers and ISRs directly. Is there a library like `avr-libc` for ARM Cortex M3?

# Answer
> 1 votes
I found the official library here: http://www.atmel.com/tools/atmel-arm-toolchain.aspx

**UPDATE:**

I have finally understood understand how **exactly** Arduino accesses specific ARM features. It includes `sam.h` file which in turn contains Cortex Microcontroller Software Interface Standard. With this cool interface anyone can use so many cool features:

* Timers
* Advanced interrupts
* Power saving mode
* SIMD instructions
* And many other

# Answer
> 2 votes
I think `newlib` is the one you want. howto

---
Tags: programming, c++, arduino-due, c
---


title: ATTiny84 blink mystery

text:
# Question
Title: ATTiny84 blink mystery
Novice mode, please.

I programmed my ATTiny84 using Arduino Ethernet (Arduino IDE 1.6.7) using https://github.com/damellis/attiny branch \- `1 MHz internal oscillator` mode. I uploaded ISP sketch to Arduino with all cables disconnected (first I did it with all of them connected but Arduino didn't seem to mind), connected the whole setup using 10 uF capacitor and the sketch got sent into ATTiny84 without problems.

Blink sketch is using atttiny84's digital pin 7 (that is physical leg No. 6) set to 1 s blink rate.

But, when I connect an yellow LED, it won't blink. I'm not yet good enough with my oscilloscope (don't know how to hook it up) but my multimeter is showing something weird - voltage is slowly rising on DP7 (I measured against ground) - over approx. 5-6 seconds to 400 mV, then immediately jumps to 1V (not sure about this, could be measurement bug) and then right to 0V.

Blink sketch:

```
int led = 7;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

```

I'm clueless. Please confer. Thank you.

Images of my setup:

# Answer
> 1 votes
I solved my own problem. Wiring was completely OK, so was flashing.

The problem was RESET pin (4th physical pin). As soon as I disconnected it after flashing, LED started blinking. If someone knows why, I'd appreciate some info.

---
Tags: attiny
---


# Question
Title: Cat motion detector that can tell the difference from humans
I'm trying to build a cat motion detector but, to avoid getting false alarms when a person walks by, I was thinking of using RFID. i.e. the cat has a collar and the detector senses the collar when they get within a couple of feet and makes a noise.

The problem there seems to be with RFID is that the range is so short - e.g. 4".

Anyone have a better solution?

# Answer
Place an additional motion sensor such that it can only detect motion from things significantly taller than cats, and use that as an inhibitor/classifier of the cat motion signal.
> 1 votes

# Answer
What about a transmitter on the collar - Bluetooth, or a coded infra red pulse, that could be detected by fixed stations?

Battery life and safety (swallowing batteries!) would be serious considerations though...
> 0 votes

---
Tags: arduino-uno
---


title: PIR sensor issues

text:
# Question
Title: PIR sensor issues
**The code works but there was a problem on the output. When the PIR detect the presence of motion the output (pin 12) would not give an instant HIGH state on the output, it has more than 10 sec delay to provide a HIGH state on PIN 12. HOw can I lessen the time that once the PIR sensors detected motion it would give a HIGH state to the output (pin 12)? please help me regarding this problem! Thanks**

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

void loop()
{
    pinMode(13,OUTPUT);//output 1
    pinMode(12,OUTPUT);//output 2
    int pirOuts=11;pinMode(pirOuts,INPUT); /*PIR sensor 1*/
    int pirOut = 10;pinMode(pirOut,INPUT); /*PIR sensor 2*/

    if (digitalRead(pirOut) || digitalRead(pirOuts) == HIGH){
        digitalWrite(12,HIGH);
        tone(13, 50132); delay(100); noTone(13); delay(10);
        tone(13,54621);  delay(50);  noTone(13); delay(50);
        tone(13,35689);  delay(60);  noTone(13);
    }
    else if (digitalRead(pirOut)||digitalRead(pirOuts)==LOW){
        digitalWrite(12,LOW);
        tone(13,50132); delay(100); noTone(13); delay(10);
        tone(13,54621);  delay(50);  noTone(13); delay(50);
        tone(13,35689);  delay(60);  noTone(13);
    }
    else
    {}
}

```

# Answer
> 1 votes
Check to make sure your PIR sensor reads high when triggered. Most of them will trigger high, but I've seen a few that will trigger low. Also, some PIR sensors have potentiometers to control delay. Some delay the trigger, some delay the reset between triggers.

The delay may not be coming from the Arduino, but from the sensor itself.

Note, the first if statement is formatted incorrectly:

```
if (digitalRead(pirOut) || digitalRead(pirOuts) == HIGH)

```

should probably be:

```
if (digitalRead(pirOut) == HIGH || digitalRead(pirOuts) == HIGH)

```

It works the way you coded it because you're doing a logical OR of the two input values (which will be 0 or 1) then comparing the result to HIGH. As I said it will work, but probably not best practice.

Also, in your code, I don't understand why you're using else if instead of just else.

```
else if (digitalRead(pirOut)||digitalRead(pirOuts)==LOW){

```

Basically, your first if statement has to be false (so both pirOut and pirOuts must both be low) so your if statement as written will always be true.

If your intent was to execute that code when either pirOut or pirOuts goes LOW, then it should be a separate if statement, not an else if.

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


# Question
Title: Override #define statements in libraries
I'm using a library that, by default, wants to use Serial2 as the interface to a display, however, I'm working with an UNO which only has one serial interface, so the compile fails. I'm trying to use a SoftwareSerial instead, but I can't figure out how to override the #define statement in the library without editing the library.

I'm guessing since the software serial port isn't generated at compile time, I can't.

```
#include <SoftwareSerial.h>
#define nexSerial HMI
#include <Nextion.h>

SoftwareSerial HMI(8,9);

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

}

void loop() {
  // put your main code here, to run repeatedly:

}

```

I haven't started writing code yet, can't get past the attempt to redirect the serial interface to a software serial.

# Answer
> 1 votes
You're allowed to modify the header file. The version I looked at says

```
#define USE_SOFTWARE_SERIAL //Comment this line for use  HardwareSerial

```

...but I think he meant "comment this line out to use HardwareSerial". Or conversely, "uncomment this line to use SoftwareSerial."

Then you just pass your `SoftwareSerial` instance into the `Nextion` constructor:

```
SoftwareSerial HMI( 8,9 );
Nextion nextion( HMI );

void setup()
{
   HMI.begin( 9600 ); // or whatever speed...

```

However, because you are using pins 8 & 9, I would **strongly** recommend using AltSoftSerial instead. It is much more reliable and efficient. MUCH.

You would have to modify the Nextion files to either (1) search and replace all occurrences of `SoftwareSerial` with `AltSoftSerial`, or (2) add a third choice to the author's `#ifdef/#endif` sections. For example:

```
#define USE_SOFTWARE_SERIAL // uncomment this line to use SoftwareSerial
#define USE_ALTSOFT_SERIAL  // uncomment this line to use AltSoftSerial
                            // comment both above  to use HardwareSerial

#if defined(USE_SOFTWARE_SERIAL)
#include <SoftwareSerial.h>
#elsif definied(USE_ALT_SOFTSERIAL)
#include <AltSoftSerial.h>
#endif

class Nextion{
 private:
  void flushSerial();
#if defined(USE_SOFTWARE_SERIAL)
  SoftwareSerial *nextion;
#elsif defined(USE_ALTSOFT_SERIAL)
  AltSoftSerial *nextion;
#else
  HardwareSerial *nextion;
#endif

```

Do either one of those things in all files that refer to the `Nextion` serial member; Nextion.CPP certainly needs it.

# Answer
> 0 votes
You can't.

All you are doing in your code is providing a #define to the instance of the header file that is included in your sketch file. You have no way of modifying the instance that is included in the library's source files.

---
Tags: serial, library, softwareserial
---


title: Arduino mega R17 led blink continuously

text:
# Question
Title: Arduino mega R17 led blink continuously
I have bought 10 Arduino Mega 2560 clones and all of them have the same problem. When I connect the to my PC I get a message that windows cannot recognize that device and the LED at the board in R17 blinks non stop. normally this led stops when the arduino is ready. Also in the Arduino IDE I don't see the port option enable.

# Answer
You need CH340G drivers. CH340G is a chip that basically replaces the usual ATMega 8U2/16U2 that is used for USB to serial interface. As CH340 cannot be reprogrammed it means that you can't emulate other USB devices with your arduino for example a keyboard.

---

You can download the drivers here.
> 2 votes

---
Tags: arduino-mega
---


# Question
Title: How should I use an optocoupler to control a 12Vcc load with Arduino?
I am developing a project to operate a load of about 12Vdc. I considered the use of an optocoupler to avoid mechanical wear of a relay. The design I have tried is this:

This configuration seems to work OK, but I am a biologist and this is my first attempt with an opto of any kind!!!! I had a lot of trouble with the transistor until I changed to a PNP. Is this right? Can it be done with an NPN or even without any transistor at all?

# Answer
> 1 votes
If your load draws a small amount of current (less than about 30 mA current), your 4N35 optocoupler could drive the load directly on 12 volts.

Ignore my use of 4N28 (similar to 4N35). It is the symbol that I had.

It appears that your PNP transistor circuit is something like this :

The PNP transistor circuit can work well depending upon your load current. The PNP circuit has some problems with the transistor not turning on fully (and won't be described here). You may not get the full 12 volts to your Load. But, if it works for your load, then be happy with the PNP circuit.

The circuit below is for a NPN transistor circuit :

Using the NPN circuit allows (in this case) for the transistor to turn on fully, leaving almost the full 12 volts for your Load.

Important Note : The NPN transistor circuit produces an output that is the LOGIC opposite of the PNP circuit. Notice that for the PNP circuit, a logic 1 to the input of the optocoupler (LED on) turns on power to your Load.

On the NPN circuit, a logic zero (0) to the optocoupler LED is required to turn on your Load.

Another variation of the circuit is below, and does NOT have the reverse logic situation. In other words, it will behave like the PNP circuit. When LED is on, the Load will be on :

You can experiment with the value of R1 in the NPN circuits. You could experiment with lower value, down to 1K (1000 ohms) if you are using a power transistor to drive high current loads.

---
Tags: relay
---


# Question
Title: Control brightness of 20 watt street LED light using Arduino
I have searched google and I now know that if we change the resistance, we can change the brightness of an LED, but I was wondering how to change resistance by using a micro controller.

# Answer
> 2 votes
Did you do a web search? "arduino pwm high power led driver" gives all the info you may need to answer this.

Here is a nice youtube clip, by Julian Ilett that explains how to do this: 60W High Power LED Driver with PWM #2 - Brightness Control.

---
Tags: arduino-uno, arduino-mega, arduino-ide, arduino-due, arduino-nano
---


title: Data changes when working with classes

text:
# Question
Title: Data changes when working with classes
When I pass an array, and it's len to the constructor of a class. I store the length, and access it later, it's value changes, seemingly at random.

```
#include "Arduino.h"

#define NUMSENSORS 2
const byte dataPins[] = {A5, A4};

class B {
    public:
        B(byte pin) { _pin = pin; }
        byte getPin() { return _pin; }
    private:
        byte _pin;
};

class A {
    public:
        A(const byte sensorPins[], int len) {
            Serial.print("provided len is: ");
            Serial.println(len);
            _len = len;
            Serial.print("Stored len is: ");
            Serial.println(_len);
            for (int i=0; i<len; i++) { myBarray[i] = new B(sensorPins[i]); }
        }
        B* myBarray[];
        int _len;
        void printLen() {
            Serial.print("Length is: ");
            Serial.println(_len);
        }
};

void setup() {
    Serial.begin(115200);
    A test(dataPins, NUMSENSORS);
    for (uint8_t i=0; i<10; i++) {
        test.printLen();
        delay(100);
    }
}

void loop() {
}

```

The value of len is fine in the constructor, but is different when I call it in the function "getLen".

I feel as though it has something to do with pointers. Because if I comment out the for loop in the constructor of A, the value is correct.

Any help would be greatly appreciated, thanks in advance.

# Answer
> 2 votes
Let us do this with a template class and avoid malloc, etc.

```
#define membersof(x) (sizeof(x) / sizeof(x[0]))

const byte dataPins[] = { A5, A4 };

class B {
public:
  byte getPin() { return (_pin); }
  void setPin(byte pin) { _pin = pin; }
private:
  byte _pin;
};

template<unsigned len>
class A {
public:
  A(const byte sensorPins[]) {
    for (unsigned i = 0; i < len; i++)
      _vec[i].setPin(sensorPins[i]);
  }
  unsigned getLen() { return (len); }
  B* getB(unsigned ix) { return (ix < len ? &_vec[ix] : NULL); }

private:
  B _vec[len];
};

void setup() {
  Serial.begin(115200);
  A<membersof(dataPins)> test(dataPins);
  unsigned len = test.getLen();
  Serial.print(F("test.getLen()="));
  Serial.println(len);
  for (unsigned i = 0; i < len; i++) {
    B* bp = test.getB(i);
    Serial.print(F("test::B["));
    Serial.print(i);
    Serial.print(F("].getPin()="));
    Serial.println(bp->getPin());
  }
}

void loop() {
}

```

Cheers!

---
Tags: programming, arduino-mega
---


# Question
Title: How can I pass a char array as the parameter to a function?
I am creating a menu for adjusting system variables.

The menu is made up of pointers like so:

```
char* options4[] = {"hMin1", "hMax1", "refr1", "fSpeed1"};

```

I want to pass the selected string as the parameter for an 'adjust' function for use in some conditional logic and for display on a HCMAX7219 7 segment display. Here's what I've got:

```
int option = 0;
float variable = 82.0;

if(Serial.available() > 0) {
  key = Serial.read();
  if(key == back) {
    return;
  } else if(key == fwd) {
    float newVar = adjust(String(options4[option%4]), variable);
  } else if(key == down) {
    option++;
  } else if(key == up) {
    option--;
  }
}

float adjust(char* str, float var) {
  ...do some stuff...
  display.print7Seg(str, 8);
  EDIT: forgot this call..
  display.print7Seg(var, 1, 4);
  ...do stuff to var...
  return var;
}

```

The library function takes `(char[] TextString, unsigned int Offset)` as it's parameters.

EDIT: the library also has functions `print7Seg(long number, byte decimalPlace, unsigned int Offset)` and `print7Seg(long number, unsigned int Offset)`

Now I'm new to pointers, but I can see that I am passing a pointer to my adjust function, and expecting it to dig out a char array from memory. I can't see any problems with that, though I may be missing something. When I try to compile, the IDE just crashes with exit status 84; so no debug info.

Am I going about this the wrong way?

# Answer
There are one or two things missing in your code. Where is setup() and loop()? Or is it just a snippet?

But answer to the question first. This is not right:

```
newVar = adjust(String(options4[option%4]), variable);

```

Should be:

```
newVar = adjust(options4[option%4], variable);

```

You want to index the vector of strings and pass one of the elements to the function.

Cheers!
> 1 votes

# Answer
Ah .. ok I've just figured it out..

This *is* a legitimate way to pass char arrays to functions.

The original `char* options4[]` array is just an array of pointers to char arrays in memory, so passing one of these pointers to a function works fine.

The culprite was actually my float parameter, I was trying to make a library function call with a float to this function: `print7Seg(long number, byte decimalPlace, unsigned int Offset)`.

This is what was causing the IDE to crash.

I got around it by having an int version of each of the variables I need to set. Then typecasting and dividing by a float to get variables that will be used in the main program. like so:

```
int hMin1Int = 820;
float hMin1 = (float)hMin1Int / 10.0;
int hMax1Int = 880;
float hMax1 = (float)hMax1Int / 10.0;
int refr1 = 30; //minutes
int fSpeed1 = 128;

```

I was then able to change my function to accept an `int`, the library function, so far, seems to be ok treating an int as a long, but if not I can just make all my ints longs:

```
int adjust(char* str, int var) {
  ...do some stuff...
  display.print7Seg(str, 8);
  display.print7Seg(var, 1, 4);
  ...do stuff to var...
  return var;
}

```

I was asking the wrong question!

Still I hope this will be useful to someone, so I will leave it up. Thanks for the response Mikael Patel.

Moral of the story, know your library.
> 0 votes

---
Tags: c++, arduino-ide, string, pointer, array
---


title: Playing music with an Arduino

text:
# Question
Title: Playing music with an Arduino
Good evening!

I am quite new with Arduino but not in programming. Still, I have already done some programs with few leds.

I was just wandering how to create a circuit and a program that would play the "happy birthday" song with the following materials:

I have a breadbord and some wires.

Else, do you have some links where I could start learning how to play music with it?

# Answer
> 0 votes
Thanks to Mikael Patel for suggesting that link (your Google-Fu must be strong!).

I am pasting the code below so that this answer survives any possible future deletion of the read-only part of the Arduino Forum.

```
//ONG LIT YIT 2013-07-20
//This following code plays happy birthday melody on Arduino
//Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
//this project requires a Piezo Buzzer and

// an Arduino board and
//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

const int speakerPin = 9;
const int LENGTH = 28; // the number of notes
const char notes[LENGTH + 1] = "GGAGcB GGAGdc GGxecBA yyecdc";
const int beats[LENGTH] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16 };
const int tempo = 150;

void playTone(int tone, int duration)
  {
  for (long i = 0; i < duration * 1000L; i += tone * 2)
    {
    digitalWrite(speakerPin, HIGH);
    delayMicroseconds(tone);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(tone);
    }
  } // end of playTone

void playNote(const char note, const int duration)
  {
  char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',
                  'c', 'd', 'e', 'f', 'g', 'a', 'b',
                  'x', 'y'
                 };
  const int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,
                  956,  834,  765,  593,  468,  346,  224,
                  655 , 715
                };
  const int SPEE = 5;

  // play the tone corresponding to the note name
  for (int i = 0; i < 17; i++)
    {
    if (names[i] == note) {
      int newduration = duration / SPEE;
      playTone(tones[i], newduration);
    }
  }
} // end of playNote

void setup()
  {
  pinMode(speakerPin, OUTPUT);
  } // end of setup

void loop()
  {
  for (int i = 0; i < LENGTH; i++)
    {
    if (notes[i] == ' ')
      {
      delay(beats[i] * tempo); // rest
      }
    else
    {
      playNote(notes[i], beats[i] * tempo);
    }

    // pause between notes
    delay(tempo);
  }
} // end of loop

```

I also cleaned up the code a bit.

---
Tags: sound
---


# Question
Title: Should millis() be stored in a variable once each loop, or called for every reference?
When comparing the value of millis() numerous times per loop(), are there reasons for/against storing it in a variable once at the top of loop(), v.s. calling millis() each time?

The most basic example code "Blink Without Delay" is written as such:

```
void loop() {
  //...
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // Do stuff
  }
}

```

I don't really she why the example code above bothers storing millis() in a variable "currentMillis" at all. (I realize that in such a simple program, there would be no noticeable difference.)

I imagine that if I use a variable, the longer the duration of loop(), and the further down my use of the "currentMillis" variable, the more deviated the stored value will be.
*I'm wondering the other ramifications of either method as well.*

Does calling millis() directly hog resources of any sort? If not, I imagine it would be better to not use a variable, so as to get a more accurate time value and save a bit of memory.

# Answer
> 4 votes
The primary downside to calling a function each time is that it may take more CPU cycles to complete the overall loop. The difference in CPU cycles, if any, depends on the actual implementation of the function and how the compiler optimises the call. For low-CPU sketches, this difference is probably unnoticeable.

Generally speaking, it is good programming practice to avoid calling a function more times than is necessary. Really the function should be called directly only if you have reasons to believe, based on desired timing and procedure order, that using the same return value in multiple places could create problems. In the example sketch given, there would be almost no functional difference between using a variable or calling the function inline.

Another advantage to using a variable is that you can give it a name that makes the code clearer to understand. In the example given, the relationship between `currentMillis` and `previousMillis` is very clear. In the case where a function returns a more complex object, such as a class or structure instance, using a variable (of the appropriate type) can be really useful since this would allow multiple members of the returned data to be accessed without calling the function multiple times. In fact, even in the given example, the function would have to be called twice since `currentMillis` appears twice in the loop.

As far as memory goes, an unsigned long uses very little.

---
Tags: time, millis, timing
---


# Question
Title: How to stop Arduino from reseting after serial connection lost
If I connect to an Arduino Uno via a serial console to read debugging statements and then disconnect, the Arduino appears to reset. How do I stop this from happening?

I'm trying to program an Arduino to receive a "shutdown" signal from a Raspberry Pi via serial, which will make the Arduino cut the RPi's power. However, this will also cut the serial connection, and if it causes the Arduino to reset, it'll reactivate power.

# Answer
There is a link on the Uno marked RESET-EN which links the Atmega16U2 (or 8U2) which handles incoming serial data to the main chip, the Atmega328P. If you cut that link (eg. with a knife) then it won't reset. However uploading new sketches will be harder because you will have to manually press the Reset button when the IDE starts to upload a new sketch.

---

Board:

---

Schematic:

---

One thing that people do is put a 10 µF capacitor between RESET and GND. That holds enough current to "weather" the reset pulse, and that stops the board resetting. You can always remove the capacitor to reprogram the board.
> 4 votes

# Answer
I found the solution to my problem was this answer, which works for me on both a normal laptop and Raspberry Pi without having to modify any Arduino hardware.
> 0 votes

---
Tags: serial
---


# Question
Title: Detect how long a push button is being pressed?
I would like to detect how long the state on/off is going on for. Is there a way to do that? I would like to do that for two reasons:

1. I would be able to make a very simple toggle button. (I know about the other way with the old value and new value).
2. I can make the button being pressed for a long time be like a return button.

Anyone got any ideas?

# Answer
This needs a combination of patterns.

First, the button pin needs to be debounced. This can be done with the "blink-without-delay"-pattern where the button pin is sampled with a low period (40 ms in the example code below).

Second, a simple state-machine is needed to keep track of the button state but also if the return button action function, doReturnButton(), has already been called.

The button is assumed to be connected from GND to pin4. The button action function, doButton(), is called when the button is pushed (goes LOW).

```
const int buttonPin = 4;
const unsigned long debounceInterval = 40;
const unsigned long returnInverval = 400;
bool buttonState = true;
bool returnButtonState = false;
unsigned long buttonDownMillis = 0L;

void doButton()
{
  Serial.print(buttonDownMillis);
  Serial.println(F(":doButton"));
}

void doReturnButton()
{
  Serial.print(buttonDownMillis);
  Serial.println(F(":doReturnButton"));
}

void setup()
{
  Serial.begin(57600);
  while (!Serial);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
  unsigned long currentMillis = millis();
  static unsigned long previousMillis = 0L;

  // Check if it is time to sample the button pin
  if (currentMillis - previousMillis >= debounceInterval) {
    previousMillis = currentMillis;

    // Did the button change
    if (digitalRead(buttonPin) != buttonState) {
      buttonState = !buttonState;

      // Was the button released
      if (buttonState) {
        returnButtonState = false;
      }

      // Was the button pushed
      else {
        buttonDownMillis = currentMillis;
        returnButtonState = true;
        doButton();
      }
    }

    // Check if button was pushed and time for return action
    else if (returnButtonState) {
      if (currentMillis - buttonDownMillis >= returnInverval) {
        returnButtonState = false;
        doReturnButton();
      }
    }
  }
}

```

What does the code do?

1. It samples the button pin with a debounce interval.
2. If the button state changes: a. High to Low it calls the doButton() function and captures a timestamp. It also allows detect of return time interval. b. Low to High. Return time interval is not allowed any more.
3. It checks if the return time interval has elapsed and if so calls the doReturnButton() function. The detect is then not allowed any more.

The doButton() function is called when the button is pushed (transition high to low), only once. The doReturnButton() function is called if the return time limit exceeds and the button is still low. Both are only called once per push (transition high to low).

To avoid the multiple transitions that occur when a button is pushed a debounce time period is used. The can also be done in hardware with a RC-circuit.

With some abstraction it could be rewritten as:

```
#include <Timemark.h>

Timemark debounce(40);
Timemark buttonHold(400);

const int buttonPin = 4;
bool buttonState;

void doButton()
{
  Serial.println(F("doButton"));
}

void doReturnButton()
{
  Serial.println(F("doReturnButton"));
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);
  Serial.println(F("started"));
  pinMode(buttonPin, INPUT_PULLUP);
  buttonState = digitalRead(buttonPin);
  debounce.start();
}

void loop()
{
  if (debounce.expired()) {
    bool currentState = digitalRead(buttonPin);
    if (currentState != buttonState) {
      buttonState = currentState;
      if (buttonState) {
        if (buttonHold.expired())
          doReturnButton();
        else
          doButton();
        buttonHold.stop();
      }
      else {
        buttonHold.start();
      }
    }
  }
}

```

This also demonstrates the callback on the release of the button. The Timemark class hides all the time intervals, expire calculations, etc.

Cheers!
> 2 votes

# Answer
1. Note the time the switch is pressed (with `millis()`)
2. Note the time the switch was released.
3. When the switch is released calculate the difference. If it is a "long" time do one thing, otherwise do something else.
> 1 votes

---
Tags: programming, button
---


title: 21 Servo on Mega?

text:
# Question
Title: 21 Servo on Mega?
I want to use 21 servo (SG5010) motors using Mega board. Is it possible to do this?

A possibility is all the servos will be operating at the same time, with average load of ~3.5 KG, and each using 1A, so 21 servos will use 21A.

Will be able to supply power? If yes then how do I go about it?

# Answer
> 2 votes
There is a servo/sensor shield for the Arduino Mega that can control up to 54 servos. This shield will only fit the Mega, unlike the usual 14 servo Arduino shield, which is shaped to fit most Arduino boards.

Here is an easier to view diagram:

It is possible, and **advisable**, to supply power via the screw terminals from an external power source, rather than use the Arduino's own power. Even just one servo can have difficulty in working from the Arduino's on board power supply, especially if just using USB to power the Arduino. However, even with the use of an external power source powering the shield, I have my doubts as to whether the shield could support 21A without burning out. Someone may be able to clarify this.

You may find this page, Servo Shield, useful:

> **MEGA Sensor Shield**
>
> The Arduino MEGA has many more I/O pins (54 Digital pins and 16 Analog pins)than a standard Arduino. This shield also has connectors specifically for some external devices like an SD Card, Radio communications (Bluetooth and others). It also has an option to power the "V" pins on all the Digital I/O 3-pin groups from an external power supply instead of the Arduino +5V. This is good for large numbers of servos etc. The "Analog" 3-pin groups still use the Arduino +5V which is better from an electrical noise perspective.
>
> This version has two options of +5V supply to all the "V" pins:
>
> * Jumper on: +5 comes from the Arduino. Should be limited to about 300 ma
> * Jumper off: +5 (or other appropriate voltage) comes from an external supply connected to the blue terminal strip. External power Ground must also be connected to the blue terminal strip.
>
> Using an external supply allows more current than the Arduino or Mega can supply, such as current for control of many servos or relays, and other attached devices. Usually this is +5V because most external devices require it. It is possible to use +6 volts if ALL the attached devices are the same such as Servos with that rating.

# Answer
> 0 votes
The Mega board will not be able to supply that much current, no. If you consult the schematic, you will see that the 5V regulator is rated for a maximum current of 800mA.

A computer PSU would be an appropriate power supply (a typical 350W PSU will happily supply \>30A on the 5V rail). Be aware that some PSUs have a minimum load; you may need to add a power resistor or other load.

Also note that if you want individual control of all the servos, the ATmega1280 only has 16 PWM outputs (IIRC), so you would need software PWM or an external PWM IC.

---
Tags: arduino-mega, power, servo
---


title: Maintaining Arduino on Ubuntu 14.04

text:
# Question
Title: Maintaining Arduino on Ubuntu 14.04
I used to use Arduino on Windows but I changed to Linux last week and I was wondering how to have a maintained version of the Arduino terminal:

Indeed, I'm not sure my version is quite recent:

The icon seems to have lived ages without a little lifting...

Maybe I'm wrong but it seems so when I open the "Tools" option for instance...

Furthermore I tried to copy and paste this code:

```
//ONG LIT YIT 2013-07-20
//This following code plays happy birthday melody on Arduino
//Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
//this project requires a Piezo Buzzer and

// an Arduino board and

//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

//HAVE FUN

//this project requires a Piezo Buzzer and

// an Arduino board and

//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

//HAVE FUN

int speakerPin = 9;

int length = 28; // the number of notes

char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc";

int beats[] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8,8, 16, 1, 2,2,8,8,8,8,16, 1,2,2,8,8,8,16 };

int tempo = 150;

void playTone(int tone, int duration) {

for (long i = 0; i < duration * 1000L; i += tone * 2) {

   digitalWrite(speakerPin, HIGH);

   delayMicroseconds(tone);

   digitalWrite(speakerPin, LOW);

   delayMicroseconds(tone);

}

}

void playNote(char note, int duration) {

char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',

                 'c', 'd', 'e', 'f', 'g', 'a', 'b',

                 'x', 'y' };

int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,

                 956,  834,  765,  593,  468,  346,  224,

                 655 , 715 };

int SPEE = 5;

// play the tone corresponding to the note name

for (int i = 0; i < 17; i++) {

   if (names[i] == note) {
    int newduration = duration/SPEE;
     playTone(tones[i], newduration);

   }

}

}

void setup() {

pinMode(speakerPin, OUTPUT);

}

void loop() {

for (int i = 0; i < length; i++) {

   if (notes[i] == ' ') {

     delay(beats[i] * tempo); // rest

   } else {

     playNote(notes[i], beats[i] * tempo);

   }

   // pause between notes

   delay(tempo);

}

}

```

And not all of it appeared in the Arduino terminal.

# Answer
If you want to get maintained (automatically updated) version of Arduino IDE then you install if from a package repository with its dependencies e.g. using `apt-get`:

```
sudo apt-get update
sudo apt-get install arduino arduino-core

```

However, this way you get a very old version (currently *1.0.5*). Obviously, it is not updated too often if at all.

If you already installed from the package repository via apt-get you can uninstall the package and its dependencies like this:

```
sudo apt-get remove arduino arduino-core
sudo apt-get autoremove

```

**Better way is to download and install Arduino IDE yourself.** This way Arduino software won't automatically be updated, so you should check Arduino website every now and then and download a new version if one is available.

Open a terminal window (e.g. by pressing *CTRL-ALT-T*), and run `uname -m` to check if you are running 32 bit or 64 bit platform:

```
uname -m

```

See output:

```
x86_64 ==> 64-bit kernel
i686   ==> 32-bit kernel

```

Go to Arduino Download page on Download the Arduino Software and download the 32 bit or 64 bit version, depending on the Ubuntu version installed on your computer.

In a terminal window extract the package and move it to your preferred location, e.g. `/opt`. You need sudo rights to move it to `/opt`. Finally, run the install script if you want to start the IDE graphically (adds desktop icon, MIME type, default application for `.ino`). See the example commands below for installing the latest 32 bit version as of the time of writing to `/opt`.

```
cd ~/Downloads
tar xf arduino-1.6.7-linux32.tar.xz
sudo mv arduino-1.6.7 /opt
/opt/arduino-1.6.7/install.sh

```

You can also start the IDE from the terminal:

```
/opt/arduino-1.6.7/arduino

```
> 4 votes

---
Tags: linux, ubuntu
---


title: Power converting - up or down?

text:
# Question
Title: Power converting - up or down?
Sorry if there is an obvious answer to this - I'm pretty new at Arduino and electronics. I've searched a bunch, but I think I'm too vague - and don't know what terms to look for.

I have a pretty simple project using a 3.3v Arduino Pro Mini (https://www.adafruit.com/products/2377) and a 12v button/LED (https://www.adafruit.com/products/1185).

I'd like to give the LED the full 12v so the light is a bright as possible. The system will be battery operated.

**The question is**: Do I *need* a 12v power supply or can I use a 3.7v power supply and upgrade it somehow? I know I can power the LED with 3.7v but then it's really dim. Is there a way to "upgrade" the 3.7v to 12v? I would assume this would draw more power and drain the battery faster, but I think that would be ok.

I'm hoping to get away with a 3.7v power supply because I want to use a lithium ion polymer battery (https://www.adafruit.com/products/328) - since it's small and rechargeable.

Seems like if I go with 12v source then I need a much bigger battery pack, and I'm hoping to keep the project small. Not sure if it would help to know, but I only need the device to run for 4+ hours between charges.

I'm guessing people will say to go with 12v since the Pro Mini can downgrade the 12v supply so there'd be less parts I have to deal with (I can already make this work). But, again, I was hoping to get away with a small rechargeable power supply. Or, are there good, small 12v batteries - I can't seem to find any on Adafruit or SparkFun.

Any recommendations? Thanks!

# Answer
> 3 votes
Since your project is to be battery powered, you want to make your system as efficient as is reasonable.

So I am going to take an approach that ends up improving the efficiency of your project.

The button you describe in your link states :

> This button has a domed red plastic cover with a black retaining ring around it. There's an optional LED included

Further, the LED included has a "built in resistor", so that the LED can operate from 12 volts.

Since you would have to install the "optional LED", why not purchase a Red LED that operates from lower voltage. You will still need a resistor but you won't need to have a voltage converter.

Example : Their LED probably has a 2 volt LED (approximate) that operates at perhaps 20 mA). This would require a 500 ohm resistor (which they incorporate into the LED). The power loss (wasted) in the resistor is 0.2 watts (200 mW).

Improved Example : With LED of about 2 volts operating from 3.3 volt power source. This would require a 68 ohm resistor. The power loss in the resistor would be 0.027 watts (27 mW). A substantial improvement in efficiency.

The manufacturer of the button does not give specifications for the LED (the one with the resistor included). You should connect their LED to a 12 volt power supply and measure the current drawn. It is possible their LED draws more current than I have shown in the examples. This would require a re-calculation of the resistor values.

But in any case, the improvement in efficiency will still exist.

# Answer
> 1 votes
Basically you have two choices. There is a third, but you don't wan to take that route.

The third route is to directly power the system with 12V and rely on the Arduino's regulator to drop it to the right voltage for the Arduino. That is very very inefficient and wasteful, and your battery won't last very long - plus the regulator will get hot. So don't even consider that option.

So the two sensible options - start with 3.7V and step it up to 12V using a *boost regulator*, or start at 12V and step it down using a *buck regulator*.

Which of those will be the easiest and most efficient? Well, there's not much to choose between them.

With either of those solutions you are converting voltage and current. With a buck regulator you are converting voltage into current, and with a boost regulator you are converting current into voltage.

If you start at 12V and step it down yes you need more cells, but each cell can be smaller since each one will have to supply less current. With 3.7V and stepping up you will have just one cell, but it will need to be bigger since it will have to supply more current.

From a charging perspective it is easier to charge a single cell since you don't have to worry about cell balancing.

From a price and availability point of view, buck (step-down) regulators are cheaper and easier to get hold of on places like eBay than boost (step-up) regulators as pre-built circuits.

So really the choice is yours - 12V (well, 11.4V it would really be - 3S LiIon / Li-Poly) and buck regulator, or 3.7V and boost regulator. Both will work, both will be about as efficient as each other.

Incidentally there are boost regulators specifically designed for driving LEDs from battery sources - you might like to look around to see what is available in that way.

---
Tags: power, electricity
---


# Question
Title: SendSMS example sketch hangs at PINMUNBER if statement
I'm using an Arduino shield connected to an Arduino Uno for sending text messages. I'm using one of the in built examples from the Arduino IDE for sending SMS by name - `sendsms` in the GSM examples. However, the code doesnt work at all... it keeps hanging at the line

```
if (gsmAccess.begin(PINNUMBER) == GSM_READY)

```

and never goes beyond it.

I didn't keep any pincode for my SIM card. please help

# Answer
Try this sketch:

```
#include <SoftwareSerial.h>

SoftwareSerial gsm(2,3);
void setup() {
  Serial.begin(9600);
  gsm.begin(9600);
  delay(1000);
}

void loop() {
  // put your main code here, to run repeatedly:
  while (gsm.available() > 0)
    Serial.write(gsm.read());
  while (Serial.available() > 0)
    gsm.write(Serial.read());
}

```

This sketch will help troubleshoot exactly what's wrong with your setup, without the clutter of a library.

Connect the shield's TX pin to Arduino pin 2 and the shield's RX pin to Arduino pin 3. Ensure that all GNDs are connected. Upload the sketch. Set your serial monitor to `BOTH NL & CR` and the baud rate to 9600. Enter `AT` from the serial monitor. If you recieve `OK`, it means comms have been established with the shield. If you receive gibberish, change the SoftwareSerial baud rate to values from 19200, 57600, etc. until you get a legible response.

Then send the command `AT+CREG?` to check the SIM's registration status. If you get something like `+CREG: *, 1` or `+CREG: *, 5` (\* means 'dont care'), then your SIM has been registered on the network. Report your results here.
> 0 votes

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


# Question
Title: Do I use 3,3V or 5V, when device supports both?
I have a general question regarding the power-supply of the electronic components, that are attached to an Arduino.

If I have a device that operates at voltages between 3,3V and 5V (e.g. this RS232 to ttl converter), what is the best way to connect it with the Arduino?

> Connect 3.3V or 5V power supply between VCC and GND

I know, that you can not draw as much current out of the 3,3V Pin like on the 5V Pin. But what if I don't need much current anyways (like in the linked example)?

What ware the advantages / disadvantages of connecting it to 3.3V and 5V?

# Answer
> 7 votes
Using the MAX3232 data sheet , which is what the TTL Converter has on it's board :

The main difference between using 3.3v or 5v is on the receiver data line "R" (or Rout as it is called on the MAX3232).

Simply put, you want to power the TTL converter from the same voltage as your Arduino is using (3.3v or 5v). Meaning the voltage that your I/O pins will put out and accept.

The received data line R will go between 0 volts and Vcc.

You would NOT want to power the TTL converter at 5 volts if you are using the converter for a 3.3v Arduino, as the received data line would go to 5 volts when high. Actually Vcc - 0.1 volts (typ.) (5 - .1 = 4.9) as per this specification :

If you power the TTL converter from 3.3 volts, the received data line (Rout) switches between 0v and 3.3v as shown here :

---
Tags: power, voltage-level
---


# Question
Title: Are there flexible pressure sensors for Arduino that can measure forces of at least 600 lbs?
I'm in need of flexible pressure sensors that can read how much force is exerted on someone's foot while running (these sensors would be placed inside the shoe). Since pressure can often be three times the weight of the person, I need something fairly strong. Are there fairly cheap sensors that are available or hacks that could do the same thing?

Thanks!

# Answer
As you are presumably measuring changing (dynamic) loads, you could consider a piezo electric sensor.

At the simplest, use a piezo element usually sold as a buzzer (make sure you get the plain element with no electronics included, some 'buzzers' also have drive circuitry).

That will give you a voltage pulse proportional to applied pressure, which might give you the precision that you need, and is very small and light to insert in a shoe.

See this question for a similar solution (and the above image!)
> 0 votes

# Answer
Sensors such as you describe are usually called "Load Cell".

At the 600 pound weight, I haven't found any "flexible" load cells. A sensor would have to be quite robust.

Flexible might not be the best answer.

This load cell page has quite a range of load cells, several thousand pounds, also not very inexpensive.

This might be difficult to install in running shoes :
> 1 votes

---
Tags: sensors, project, components
---


title: Cannot disable interrupts

text:
# Question
Title: Cannot disable interrupts
I am new to arduino.

Why does this not work the way it's supposed to?
Shouldn't it block all interrupts for 3secs after it received one from digi pin 2?

How would I accomplish this: Running a method whenever the value on this pin changes, execute it and then listen for more interrupts from that pin?

```
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

int i = 0;

void loop(){}

void test(){
  noInterrupts();
  Serial.println("Interrupt registered - waiting " + i);
  delay(3000);
  Serial.println("done waiting!" + i);
  i++;
  interrupts();
}

```

# Answer
You could achieve that by this simple rewrite:

```
void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

volatile bool changed = false;
int i = 0;

void loop() {
  if (!changed) return;
  Serial.print(F("Interrupt registered - waiting "));
  Serial.println(i);
  delay(3000);
  Serial.print(F("done waiting "));
  Serial.println(i);
  i += 1;
  changed = false;
  clearInterrupt(digitalPinToInterrupt(2));
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

void test() {
  changed = true;
  detachInterrupt(digitalPinToInterrupt(2));
}

```

The interrupt service routine (ISR), test(), is really short and does not call functions that actually need interrupts to work (e.g. delay(), Serial). Please see Nick Gammon's comment below on clearInterrupt(), i.e. EIFR = bit (INTF0);

An alternative rewrite is to use the BlinkWithDelay-pattern and a somewhat more complex state-machine:

```
volatile bool changed = false;
bool waiting = false;

const unsigned long waitIntervalMillis = 3000UL;
unsigned long waitStartMillis = 0L;

int i = 0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

void loop() {

  // Check for change
  if (!changed) return;

  // Check for change before wait interval
  if (!waiting) {
    Serial.print(F("Interrupt registered - waiting "));
    Serial.println(i);
    waiting = true;
    waitStartMillis = millis();
  }

  // Check if wait interval has expired
  else {
    unsigned long currentMillis = millis();
    if ((currentMillis - waitStartMillis) >= waitIntervalMillis) {
      Serial.print(F("done waiting "));
      Serial.println(i);
      i += 1;
      changed = false;
      waiting = false;
    }
  }
}

void test() {
  changed = true;
}

```

A third rewrite is possible. Assuming that the pin is connected to a push button, the interrupt handler can be replaced by simply reading the pin with a low frequency (for debouncing).

Cheers!
> 2 votes

# Answer
Probably your biggest problem is that `delay()` cannot be used inside interrupt service routines (ISR's) and it doesn't work if interrupts are turned off because it uses interrupts to function.

ISR's should be as short as possible, because they stop normal operation of the device while they execute. A good ISR will set a few variables, and then return, while the main program loop checks the state of those variables and actually does stuff. Mikael Patel's answer shows how you can rewrite your sketch to do this.
> 1 votes

---
Tags: arduino-nano, interrupt
---