# Question
Title: Arduino eeprom_put sketch writes data in two locations?
Using precisely this code - the ***eeprom\_put*** example in the Arduino IDE, and am seeing some strange results...

The sketch does write correctly to eeAddress = 0, and the corresponding ***eeprom\_get*** sketch does return the data.

Please note that I've initialized the entire EEPROM with 'FF's before any test...

The weird part is this sketch writes exactly the same data starting at Address = 2048. The loop is not running; I see no jump to offset 2048... I gotta be missing something!

I'm dumping EEPROM using avrdude, and viewing results in an external hex editor.

How is this stuff stored? Apart from not being able to directly view a float - OK, I get it - should the other data be simply *viewable* in hex?

My own experiments in writing hex bytes directly also work, but also write in two locations.

Small update to this: Precisely the same behavior seen with a RobotDyn Mega. Both the 'clone' Mega and the RobotDyn report: Device signature = 0x1e9801 (probably m2560)

```
#include <EEPROM.h>

struct MyObject {
  float field1;
  byte field2;
  char name[10];
};

void setup() {

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  float f = 123.456f;  //Variable to store in EEPROM.
  int eeAddress = 0;   //Location we want the data to be put.

  //One simple call, with the address first and the object second.
  EEPROM.put(eeAddress, f);

  Serial.println("Written float data type!");

  /** Put is designed for use with custom structures also. **/

  //Data to store.
  MyObject customVar = {
    3.14f,
    65,
    "Working!"
  };

  eeAddress += sizeof(float); //Move address to the next byte after float 'f'.

  EEPROM.put(eeAddress, customVar);
  Serial.print("Written custom data type! \n\nView the example sketch eeprom_get to see how you can retrieve the values!");
}

void loop() {
  /* Empty loop */
}

```

# Answer
What is probably happening is aliasing. Let's say your processor has a 16 bit address bus. 16 bits can count up to 2^16 = 65536 = 64k memory addresses. Each address is a byte (B) so your processor has 64k-Bytes of address space. It can physically address 64kB of memory.

What happens if you only have one memory chip with 4KBytes of memory, with only 12 address lines? Well, if the designer was lazy (or cost-conscious), the first 12 address lines on the processor will be connected to the 12 lines on the memory chip. The other 4 lines on the processor will be ignored.

So it doesn't matter what the processor does with address lines 13-16 -- they're not connected to the memory chip. Therefore the contents of the memory chip appears where you expect, starting at address `0`, but also again at address 4096, and again at address 8192 and so on.
> 2 votes

---
Tags: sketch, eeprom, memory
---


title: code optimazation 6x6 Matrix

text:
# Question
Title: code optimazation 6x6 Matrix
I planed a 6x6 matrix with a Arduino Nano as controller. Its only possible to let one LED in the matrix lighten up. Any idea how I get the Code smaller? (Im a C Noobie ^^)

*~Nico*

Circuit diagram:

Code:

> ```
> void setup() {
>   pinMode(1, OUTPUT);
>   pinMode(2, OUTPUT);
>   pinMode(3, OUTPUT);
>   pinMode(4, OUTPUT);
>   pinMode(5, OUTPUT);
>   pinMode(6, OUTPUT);
>   pinMode(7, OUTPUT);
>   pinMode(8, OUTPUT);
>   pinMode(9, OUTPUT);
>   pinMode(10, OUTPUT);
>   pinMode(11, OUTPUT);
>   pinMode(12, OUTPUT);
>   pinMode(13, OUTPUT);
>   pinMode(14, INPUT);
>   pinMode(15, INPUT);
>   pinMode(16, INPUT);
>   pinMode(17, INPUT);
> }
>
> void loop() {
>   int value1 = digitalRead(14);
>   int value2 = digitalRead(15);
>   int value3 = digitalRead(16);
>   int test = digitalRead(17);
>   int x1 = 2;
>   int x2 = 3;
>   int x3 = 4;
>   int x4 = 5;
>   int x5 = 6;
>   int x6 = 7;
>   int y1 = 8;
>   int y2 = 9;
>   int y3 = 10;
>   int y4 = 11;
>   int y5 = 12;
>   int y6 = 13;
>
>
>   // put your main code here, to run repeatedly:
>
>
>   if (test == HIGH) {
>     digitalWrite(x1, HIGH);
>     digitalWrite(y1, HIGH);
>     delay(15);
>     digitalWrite(y1, LOW);
>     digitalWrite(y2, HIGH);
>     delay(15);
>     digitalWrite(y2, LOW);
>     digitalWrite(y3, HIGH);
>     delay(15);
>     digitalWrite(y3, LOW);
>     digitalWrite(y4, HIGH);
>     delay(15);
>     digitalWrite(y4, LOW);
>     digitalWrite(y5, HIGH);
>     delay(15);
>     digitalWrite(y5, LOW);
>     digitalWrite(y6, HIGH);
>     delay(15);
>     digitalWrite(y6, LOW);
>     digitalWrite(x1, LOW);
>     digitalWrite(x2, HIGH);
>     digitalWrite(y1, HIGH);
>     delay(15);
>     digitalWrite(y1, LOW);
>     digitalWrite(y2, HIGH);
>     delay(15);
>     digitalWrite(y2, LOW);
>     digitalWrite(y3, HIGH);
>     delay(15);
>     digitalWrite(y3, LOW);
>     digitalWrite(y4, HIGH);
>     delay(15);
>     digitalWrite(y4, LOW);
>     digitalWrite(y5, HIGH);
>     delay(15);
>     digitalWrite(y5, LOW);
>     digitalWrite(y6, HIGH);
>     delay(15);
>     digitalWrite(y6, LOW);
>     digitalWrite(x2, LOW);
>     digitalWrite(x3, HIGH);
>     digitalWrite(y1, HIGH);
>     delay(15);
>     digitalWrite(y1, LOW);
>     digitalWrite(y2, HIGH);
>     delay(15);
>     digitalWrite(y2, LOW);
>     digitalWrite(y3, HIGH);
>     delay(15);
>     digitalWrite(y3, LOW);
>     digitalWrite(y4, HIGH);
>     delay(15);
>     digitalWrite(y4, LOW);
>     digitalWrite(y5, HIGH);
>     delay(15);
>     digitalWrite(y5, LOW);
>     digitalWrite(y6, HIGH);
>     delay(15);
>     digitalWrite(y6, LOW);
>     digitalWrite(x3, LOW);
>     digitalWrite(x4, HIGH);
>     digitalWrite(y1, HIGH);
>     delay(15);
>     digitalWrite(y1, LOW);
>     digitalWrite(y2, HIGH);
>     delay(15);
>     digitalWrite(y2, LOW);
>     digitalWrite(y3, HIGH);
>     delay(15);
>     digitalWrite(y3, LOW);
>     digitalWrite(y4, HIGH);
>     delay(15);
>     digitalWrite(y4, LOW);
>     digitalWrite(y5, HIGH);
>     delay(15);
>     digitalWrite(y5, LOW);
>     digitalWrite(y6, HIGH);
>     delay(15);
>     digitalWrite(y6, LOW);
>     digitalWrite(x4, LOW);
>     digitalWrite(x5, HIGH);
>     digitalWrite(y1, HIGH);
>     delay(15);
>     digitalWrite(y1, LOW);
>     digitalWrite(y2, HIGH);
>     delay(15);
>     digitalWrite(y2, LOW);
>     digitalWrite(y3, HIGH);
>     delay(15);
>     digitalWrite(y3, LOW);
>     digitalWrite(y4, HIGH);
>     delay(15);
>     digitalWrite(y4, LOW);
>     digitalWrite(y5, HIGH);
>     delay(15);
>     digitalWrite(y5, LOW);
>     digitalWrite(y6, HIGH);
>     delay(15);
>     digitalWrite(y6, LOW);
>     digitalWrite(x5, LOW);
>     digitalWrite(x6, HIGH);
>     digitalWrite(y1, HIGH);
>     delay(15);
>     digitalWrite(y1, LOW);
>     digitalWrite(y2, HIGH);
>     delay(15);
>     digitalWrite(y2, LOW);
>     digitalWrite(y3, HIGH);
>     delay(15);
>     digitalWrite(y3, LOW);
>     digitalWrite(y4, HIGH);
>     delay(15);
>     digitalWrite(y4, LOW);
>     digitalWrite(y5, HIGH);
>     delay(15);
>     digitalWrite(y5, LOW);
>     digitalWrite(y6, HIGH);
>     delay(15);
>     digitalWrite(y6, LOW);
>     digitalWrite(x6, LOW);
>
>
>
>   }
> }
>
> ```

# Answer
> Any idea how I get the Code smaller?

don't try to get the code smaller -\> try to get it working.

for things like this, you should think about

1) how to structure the display data: typically it is done in a matrix format. I would structure it as an array of 6 chars / columns, with the rows in the lowest 6 bits;

2) how to track the column being displayed and updated: using a static variable typically;

3) how to update the display periodically: via a timer interrupt usually.

Each update would go something like this:

```
  turn off all columns;
  present row information;
  update the column index and turn it on;

```

what's left is to implement that in a way that the code is flexible and portable to a different application.

once that's done, all your application needs to do is to stuff the right information into the display buffer and the display routine, invoked via a timer isr, will take care of the updating all by itself, without user involvement.

if you still need help, let us know.

edit: i put this together quickly to demonstrate the concept.

it is a display routine, led\_display(), being invoked via a timer2 interrupt, displaying data in an 8-char buffer, 0x11, 0x22, ..., 0x88.

the scanning is done by colomn (active high), and the rows are connected to D0..D7, and the cols D8..D13, A0, A1, all user configurable.

```
//global variables
uint8_t lRAM[COL_NUM]={         //display buffer
    0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88
};

const uint8_t row_pins[ROW_NUM]={   //pins tied to matrix' rows
    0, 1, 2, 3, 4, 5, 6, 7,
};

const uint8_t col_pins[COL_NUM]={   //pins tied to columns
    8, 9, 10, 11, 12, 13, A0, A1,
};

```

once the initialial set-up is done, there is nothing the user needs to do, other than filling the display buffer with information s/he wishes to be displayed.

```
void setup() {
    // put your setup code here, to run once:
    //pinMode(led, OUTPUT);
    led_init();                         //reset the led module

    //set up timer2
    tmr2_init(TMR2PS_32x);              //timer2 with 32:1 prescaler -> 16Mhz / 256 / 32 = 2Khz per col.
    tmr2_act(led_display);              //install user handler to update the display periodically
}

void loop() {
    // put your main code here, to run repeatedly:
    //digitalWrite(led, HIGH);  // turn the LED on (HIGH is the voltage level)
    //delay(100);               // wait for a second
    //digitalWrite(led, LOW);   // turn the LED off by making the voltage LOW
    //delay(100);               // wait for a second
}

```

and here is the execution.

ps: the code was originally written to drive 8x7-segment displays but it works with 8x8 matrix as well -\> they are essentially the same thing.

the display routine, led\_display(), follows the general sketch laid out earlier.

```
//update the display
void led_display(void) {
    static uint8_t col_index=0;         //current col
    //turn off current col -> the only active col now
    COL_OFF(col_pins[col_index]);

    //update the column index
    col_index=(col_index==COL_NUM-1)?0:(col_index+1);

    //present row data
    if (lRAM[col_index] & (1<<0)) ROW_ON(row_pins[0]); else ROW_OFF(row_pins[0]);
    if (lRAM[col_index] & (1<<1)) ROW_ON(row_pins[1]); else ROW_OFF(row_pins[1]);
    if (lRAM[col_index] & (1<<2)) ROW_ON(row_pins[2]); else ROW_OFF(row_pins[2]);
    if (lRAM[col_index] & (1<<3)) ROW_ON(row_pins[3]); else ROW_OFF(row_pins[3]);
    if (lRAM[col_index] & (1<<4)) ROW_ON(row_pins[4]); else ROW_OFF(row_pins[4]);
    if (lRAM[col_index] & (1<<5)) ROW_ON(row_pins[5]); else ROW_OFF(row_pins[5]);
    if (lRAM[col_index] & (1<<6)) ROW_ON(row_pins[6]); else ROW_OFF(row_pins[6]);
    if (lRAM[col_index] & (1<<7)) ROW_ON(row_pins[7]); else ROW_OFF(row_pins[7]);

    //turn on the display
    COL_ON(col_pins[col_index]);
}

```
> 2 votes

# Answer
You can use arrays to hold sets of row pin numbers or column pin numbers, which then allows use of `for` loops for `pinMode()` settings and for testing LEDs one after another, as shown in code below.

Note, using `enum { ... };` for integer-constant declarations is slightly more compact than a series of `const int` statements. When a constant name in an `enum` does not have an `=` and value after it, it is given a value one larger than the previous constant. So, for example, the first `enum` in the following code sets `x2` to 3, `x3` to 4, etc.

```
enum { x1=2, x2, x3, x4, x5, x6};
enum { y1=8, y2, y3, y4, y5, y6};
const byte rowPins[] = { x1, x2, x3, x4, x5, x6};
const byte colPins[] = { y1, y2, y3, y4, y5, y6};
enum { nRow = sizeof rowPins / sizeof rowPins[0] };
enum { nCol = sizeof colPins / sizeof colPins[0] };

void setup() {
  for (byte i=0; i<nRow; ++i) pinMode(rowPins[i], OUTPUT);
  for (byte i=0; i<nCol; ++i) pinMode(colPins[i], OUTPUT);
  for (byte i=14; i<18; ++i)  pinMode(i, INPUT);
}

void loop() {
  byte test = digitalRead(17);
  if (test) {
    for (byte x=0; x<nRow; ++x) {
      digitalWrite(rowPins[x], HIGH);
      for (byte y=0; y<nCol; ++y) {
        digitalWrite(colPins[y], HIGH);
        delay(15);
        digitalWrite(colPins[y], LOW);
      }
      digitalWrite(rowPins[x], LOW);
    }
  }
}

```

Note, subroutines and functions can be used to modularize code and (typically) reduce its volume. See code sample below. In the code as is, the subroutine doesn't particularly reduce volume, but definitely adds modularity. You may find it useful to look up *refactoring*.

```
enum { x1=2, x2, x3, x4, x5, x6};
enum { y1=8, y2, y3, y4, y5, y6};
const byte rowPins[] = { x1, x2, x3, x4, x5, x6};
const byte colPins[] = { y1, y2, y3, y4, y5, y6};
enum { nRow = sizeof rowPins / sizeof rowPins[0] };
enum { nCol = sizeof colPins / sizeof colPins[0] };

void setup() {
  for (byte i=0; i<nRow; ++i) pinMode(rowPins[i], OUTPUT);
  for (byte i=0; i<nCol; ++i) pinMode(colPins[i], OUTPUT);
  for (byte i=14; i<18; ++i)  pinMode(i, INPUT);
}

void lightup(byte x, byte y, unsigned int howLong) {
  digitalWrite(rowPins[x], HIGH);
  digitalWrite(colPins[y], HIGH);
  delay(howLong);
  digitalWrite(colPins[y], LOW);
  digitalWrite(rowPins[x], LOW);
}

void loop() {
  byte test = digitalRead(17);
  if (test) {
    for (byte x=0; x<nRow; ++x)
      for (byte y=0; y<nCol; ++y)
        lightup(x, y, 15);
  }
}

```
> 3 votes

---
Tags: arduino-nano, code-optimization, code-review
---


title: Picking an Arduino

text:
# Question
Title: Picking an Arduino
I'm looking to develop my own personal SmartWatch, hardware, software, and all. My problem is starting off on the hardware portion of it; more specifically what platform I should build it on. I already have an Arduino Uno (R3), nut I was hoping to find something a bit smaller. Any recommendations on what parts I should use?

# Answer
> 7 votes
What you start with is not too critical as you can develop basic concepts on any Arduino hardware and use it to drive a display of your choice for testing. This can be migrated to whatever is found suitable as the project progresses.

Important to consider are the number of I/O lines of various sorts that you need. Most AVR ICs that you are liable top use will have "some" analog input and PWM output lines. If you were going to drive a "bare" LCD you may need to use a processor with LCD drivers, but in most designs use of an existing module with eg SPI interface is probable preferable.

Most Arduinos in the UNO, Nano, Pro Mini, ... range are in reality not a lot more functionally that a processor IC, USB bridge (if needed) and voltage regulator(s). For a tidily small watch you may ultimately wish to use a bare SMD AVR IC with an Arduino boot loader code installed. You can move away from AVR ICs to other Arduino compatible systems - with some extra knowledge needed in most cases.

.\____________________________________________________

**Examples only:**

Here is an **Internet of things hardware roundup** which includes some small controllers as examples.

**Panstamps** offer MSP430 and ATMega328p (Arduino compatible versions).

. \_______________________________________________

**RFDuino - from here** offer some fingertip sized products with RF capability. Note that this use an ARM Cortex M0 processor, not an ATMega controller. While it is "Arduino compatible" it will not run all code that the typical UNO, Nano, ... boards run.
Manual here

Their Kickstarter page

# Answer
> 2 votes
Why not start with your Arduino Uno, it's got lots of I/O pins, and it's a great little device to start prototyping your watch.

You could add a number of sensors/peripherals such as

* a Bluetooth module, - connect your phone
* an IMU, - detect different excercises from your wrist movement
* a tiny motor - to make the watch vibrate
* a speaker for audible notifications
* tactile buttons for switch between modes and functions of the watch
* a LCD screen, - to see the time and other data
* maybe a few LEDs as a torch function.

Once you develop your code and your happy with it, you could shrink your board accordingly, because you will then know how much I/O pins you'll need, and what voltage these sensors need to operate, and their inputs (analog vs. digital). You could even design your own PCB board with all these sensors.

You could use the Uno as a stepping stone.

# Answer
> 1 votes
One Possibility is that you could just use an avr chip without the arduino breakout, but still include the arduino bootloader, and this way it would be easier for you to isolate your preferred features, however with this method you would be sacrificing some safety without short circuit protection, and it would be a bit more work to upload, but this is also the cheapest.

# Answer
> 1 votes
Have a look at the LilyPad (Main Board, USB, Simple) and Gemma. The Gemma may have too few I/O pins for your needs, but it really does look small.

# Answer
> 0 votes
I have quite a few nanos / mini pros that I got as plain avr boards. they are great little things.

I also got a few minimus avr - if you want to venture outside of arduino. like the at90 usb stick / key, they are little boards that are 100% self-contained. they are ideal to play with on long flights.

---
Tags: arduino-uno, shields, hardware
---


# Question
Title: What would be the best way to sense the tank level of a 1000L water tank?
I want to read in the values to an arduino analog input.

The approaches I have been looking at are:

1.) A ultrasonic distance sensor; my concerns are that tehse are not usually waterproof.

2.) A pressure transducer; these tend to be very pricy.

3.) Some kind of level switch which provides digital input (Is water level here: yes/no?)

Would anyone happen to have some advice on what sort of sensor would be good for the application of reading in the tank level and using the information in a sketch?

# Answer
There are some ultrasonic sensors that are specifically designed for this very application. I have used something simlar as a water level sensor, and they seem to be reliable. The sensor that I used was from MaxBotix, and had a range of up to 5m, resolution of 1mm, and both analog and serial data output. Interfacing it with an Arduino was very easy.

Have a look at This article for details
> 1 votes

# Answer
> 1.) A ultrasonic distance sensor; my concerns are that tehse are not usually waterproof.

Ultrasonic rays will ping through water till it transfer back from the bottom of tank. So it can not provide you the level of water.

> 2.) A pressure transducer; these tend to be very pricy.

Yes it will be very pricy.

> 3.) Some kind of level switch which provides digital input (Is water level here: yes/no?)

This option will be best and more reliable. You can use some water level indicator probes or magnetic float switch.

**Probes/Electrode**

When electrode is in contact with water it will pass current through it and give indication to system or controller.

**Magnetic Float Switch**

Magnetic float switch having magnet under water proof enclosure. When water level reach upto Float switch then circuit will be close and will give level signal to system.

In above to switches magnetic float switch will be best option. Because if water having High TDS then there will be erosion of electrode or element of TDS will gether around electrode and result in conductivity loss of rode.

And this is not possible in case of Magnetic Float switch as it is under water proof enclosure. It is also cheap solution.
> 0 votes

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


# Question
Title: Local variable usage in SRAM not counted
I use the following code to print the currently used SRAM space:

```
// this function will return the number of bytes currently free in RAM
// written by David A. Mellis
// based on code by Rob Faludi http://www.faludi.com

#include "TypeDefs.h"

int availableMemory()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

int printAvailableMemory(uint32 location)
{
  Serial.print(F("Available Memory at "));
  Serial.print(location);
  Serial.print(F(": "));
  Serial.println(availableMemory());
}

```

My main application (stripped) looks like:

```
...
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  printAvailableMemory(1);

  printAvailableMemory(2);

  test();
  printAvailableMemory(3);
}

void test()
{
  Preferences _prefs2;
  _prefs2.Set();
  printAvailableMemory(4);
}

```

While preference (.h) looks like:

```
#include "TypeDefs.h"

class Preferences
{
   private:
      uint8 _startChannel;
      uint8 _endChannel;
      uint8 _startNote;
      uint8 _endNote;
      uint8 _startCc;
      uint8 _endCc;
   ...
};

```

The output is:

```
Available memory at 1: 1065
Available memory at 2: 1065
Available memory at 4: 1065
Available memory at 3: 1065

```

I would expect the numbers (1065) would change, since a local variable (\_prefs2) is made so at location 4 I would expect more space to be used.

Also, if I remove the \_prefs2 code like below, the numbers stay the same.

```
void test()
{
    printAvailableMemory(4);
}

```

Why is the local variable not counted?

# Answer
> 3 votes
> Why is the local variable not counted?

Let us start with the function `availableMemory()`, what does it do?

```
int availableMemory()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

```

It returns the amount of memory between the top of stack (address of local variable v) and the heap end.

The answer lays in how the compiler works. One strategy that is used is function *in-lining*. This forces the functions `test(), printAvailableMemory(), availableMemory()`, etc. to be unfolded into `loop()` (which actually also gets unfolded into `main()`).

A common frame with the local variables is created and the variable for the top of the stack becomes one of them. You need a tougher test case to see how the stack top changes, e.g. tell the compiler not to in-line a function.

```
int availableMemory() __attribute__ ((noinline));

```

To check this generate the assembly listing for your sketch.

Cheers!

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


# Question
Title: Deep sleep mode for the Uno without complicated circuits?
so I'm building something using an Uno that will run on batteries - so, I've watched a couple of these low power tutorials to lessen the energy consumption so the batteries can last longer, but they're not exactly what I want - they all require some sort of circuit. I've found this tutorial (http://www.engblaze.com/hush-little-microprocessor-avr-and-arduino-sleep-mode-basics/) which only needs an LED, and it's ideal, but I would like to know if you know of any other methods which would reduce consumption to less than 5mA without using any complicated circuits (other than unplugging the Uno)

Thank you!

# Answer
> 1 votes
> Deep sleep mode for the Uno without complicated circuits?

Forget using an Arduino Uno if you want to do low power (less than 10 mA standby). There is too much extra circuits (LEDs, Voltage Regulators, etc) to allow that.

See for instance, https://www.gammon.com.au/forum/?id=11497

With an Arduino Pro Mini it is possible to achieve low power after removing the Power LED and cutting the Voltage Regulator.

The hardware/software support for low power cannot really be used before the board is design for that.

Cheers!

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


title: SPI.H library to control APA102

text:
# Question
Title: SPI.H library to control APA102
I am trying to run a strip of APA102 addressable LED's using a Mini pro.

The same strip I can run using a raspberry pi using SPI so I know the Strip works and what data I need to send to get it running.

My current code is as follows and I have striped it back to the bare minimum as I see it.

It all compiles and runs but nothing on the LED strip. The stip only has data and clock that should be connected to the CLK and Data in to connect to the MOSI.

All i want is to be able to send a 32bit value,

I had also tried

```
uint32_t value = 0xE0ffffff

```

but again no luck

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

  Serial.begin(9600);

  SPI.begin();

  byte start = 0x00;
  SPI.transfer(start);
  SPI.transfer(start);
  SPI.transfer(start);
  SPI.transfer(start);

  SPI.transfer(0xEF);
  SPI.transfer(255);
  SPI.transfer(0);
  SPI.transfer(10);
}

```

# Answer
> -1 votes
take a look at the datasheet, compare it vs. your code for any incompliance.

based on my quick reading, your code isn't consistent with the datasheet.

put the communications in a routine would help maintain uniformity.

---
Tags: spi, arduino-pro-mini
---


title: wiring a arduino led project

text:
# Question
Title: wiring a arduino led project
I am moving a project from breadboard and jumper cables. It light a bunch of LEDs with different sets running of many almost every pin. I need a few meters of cables. I will a resistor on each led. I have no idea what kinda cable/wire to use and googling cable gets me nowhere. What kinda wire do people use?

# Answer
> 2 votes
When choosing wire for your project the main consideration is the amount of current. Second would be the distance.

For LEDs the current is generally low (milliamps) so something like a 20 or 22 gauge wire would be fine. You should be able to get it at a local hobby electronics shop or Amazon of course.

FYI, Wire gauge numbering is such that the lower the number the thicker wire. Thus 20 is thicker than 22.

You may find this AWG (American Wire Gauge) table helpful: http://www.powerstream.com/Wire\_Size.htm

---
Tags: wires
---


title: Arduino Nano TX LED is on

text:
# Question
Title: Arduino Nano TX LED is on
My Arduino nano make weired thing... The TX LED is on when i define a Variable and a digital Pin as output. Do you now if it is a error in the code? If I upload a clear new sketch the LED is off.

*~Nico*

Code:

> ```
> int ok = 1;
> int err = 0;
> int x1 = 2;
> int x2 = 3;
> int x3 = 4;
> int x4 = 5;
> int x5 = 6;
> int x6 = 7;
> int y1 = 8;
> int y2 = 9;
> int y3 = 10;
> int y4 = 11;
> int y5 = 12;
> int y6 = 13;
> int value1 = digitalRead(14);
> int value2 = digitalRead(15);
> int value3 = digitalRead(16);
> int test = digitalRead(17);
>
> void setup() {
>   pinMode(0, OUTPUT);
>   pinMode(1, OUTPUT);
>   pinMode(2, OUTPUT);
>   pinMode(3, OUTPUT);
>   pinMode(4, OUTPUT);
>   pinMode(5, OUTPUT);
>   pinMode(6, OUTPUT);
>   pinMode(7, OUTPUT);
>   pinMode(8, OUTPUT);
>   pinMode(9, OUTPUT);
>   pinMode(10, OUTPUT);
>   pinMode(11, OUTPUT);
>   pinMode(12, OUTPUT);
>   pinMode(13, OUTPUT);
>   pinMode(14, INPUT);
>   pinMode(15, INPUT);
>   pinMode(16, INPUT);
>   pinMode(17, INPUT);
> }
>
> void loop() {
>   // put your main code here, to run repeatedly:
>
> }
>
> ```

# Answer
> 3 votes
You configure serial pins as output, this may be your issue.

also, you're calling some digitalRead() before setup call, you would have to do that in the loop.

---
Tags: programming, led, arduino-nano
---


title: Arduino analog pins

text:
# Question
Title: Arduino analog pins
How many sensors can be used by a arduino uno and mega separately.? Does each sensor can use the ADC of arduino simultaneously? If not how to use all the sensors simultaneously if possible?

# Answer
> 4 votes
> How many sensors can be used by a arduino uno and mega separately?

Assuming you mean analog signals. As many as the number of analog pins on those boards. This can be extended by using an analog multiplexer and additional digital pins. The total number of channels is number of analog pins minus one plus log2 of the number of digital pins used to select the input channel, e.g. 8 additional analog channels through a multiplexer will require 3 digital pins for channel selection.

> Does each sensor can use the ADC of arduino simultaneously?

There is a single ADC module which takes approx. 112 us to convert an analog signal to 10-bit digital number. There is no simultaneous conversion of multiple channels.

> If not how to use all the sensors simultaneously if possible?

All sensor can be connected but only one at a time is sampled and conversion to digital number.

Cheers!

# Answer
> 2 votes
All AVR- and ARM-based Arduinos have a single ADC, connected to multiple input channels. If you *require* simultaneous sampling of multiple sources then you will need to use one or more external ADCs.

# Answer
> 0 votes
> If not how to use all the sensors simultaneously if possible?

a few ways:

1) use external adc;

2) use a sample-and-hold circuitry on the sensors;

3) find a mcu that has more than one adc modules; some pic24/dspics have that. some atxmegas have that. and some arm chips have that as well, to list a few.

4) use multiple avrs, each for a sensor;

...

---
Tags: arduino-uno, arduino-mega
---


# Question
Title: Why is there no smooth value from ADXL335?
I have written this code to read x-acceleration from ADXL335.

1. Why is the value toggling between 342, 343, 344 even at rest? Is there anything I need to do to get a smooth curve?
2. How to increase resolution? (I'm using a Mega 2560)

---

```
int Xcurr,Ycurr,Zcurr;
int Xpre=0,Ypre=0,Zpre=0;
int res=0;
// these constants describe the pins. They won't change:
const int groundpin = A1;
// analog input pin 4 -- ground
const int powerpin = A0;
// analog input pin 5 -- voltage
const int xpin = A3;
// x-axis of the accelerometer
const int ypin = A2;
// y-axis
const int zpin = A4;
// z-axis (only on 3-axis models)
const int stpin = A5;

void setup() {
  Serial.begin(9600);
  pinMode(groundpin, OUTPUT);
  pinMode(powerpin, OUTPUT);
  digitalWrite(groundpin, LOW);
  digitalWrite(powerpin, HIGH);
  pinMode(stpin, OUTPUT);
  digitalWrite(stpin, LOW);
}

void loop() {
  Xcurr=analogRead(xpin);
  Serial.print(Xcurr);Serial.print("\n");
  delay(100);
}

```

# Answer
> 1 votes
It is called moving average, the calculations you can use to prevent such problems can be found at wikipedia

In principle, what you do is take the average over the last x measurements to take away the peaks.

---
Tags: sensors, accelerometer
---


# Question
Title: Problem connecting 10W led + Led driver Directly Arduino Uno
can anyone give me an advice on connecting an 10W led + 12 volt drive to an Arduino Uno? it works without the board but when i tried to connect to Uno it doesn't work anymore. Thankyou

# Answer
> 3 votes
To operate LED using Arduino you will need a switch that can be operated using electronic switch like transistor, Mosfet or Relay board. More easy and reliable option would be using Relay Board.

You can visit this link and can get more idea....

http://www.electroschematics.com/8975/arduino-control-relay/

# Answer
> 1 votes
You'll need a switch such as a transistor, and capable of handling 10W, to be driven by the Arduino and connect/disconnect the LED to an external 12v supply. There are many examples on the web. Remember to connect the 12v and 5v grounds together.

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


# Question
Title: Arduino IDE COM Port error on Windows 10
I have an Arduino micro, uno, and mega and none of them will connect to the com port on the Arduino IDE. I went to the device manager aand it is recognized but when I try to update the driver I get this:

Any help of how to fix this problem?

# Answer
> 2 votes
An easy thing to try but might not help: Use another USB port of your computer and see if the driver is reinstalled.

Otherwise, go to control panel and find the drivers (Device Manager), search for the Ports (COM & LPT) drivers and remove the driver for the Arduino manually, reconnect the Arduino and check if it is installed correctly. Possibly a wrong version of an Arduino driver is installed. If another driver is installed at COM3 (where is my Arduino), remove that driver and try again.

# Answer
> 1 votes
Option 1: Try to update or reinstall com port driver in control panel/device manager...

Option 2: There might be problem while installing Arduino IDE or problem occur during Arduino gets board and library updates over air itself. Try to reinstall IDE.

---
Tags: arduino-uno, arduino-mega, arduino-micro
---


title: Store a variable?

text:
# Question
Title: Store a variable?
I want to have a switch, that when on, will grab an analog number and essentially "freeze" it. Similarly to how STO\> works on a TI83. What should I be using? Excuse my lack of technical terms, I'm not sure what to search and therefore do not know what to use. Thank you :)

# Answer
My recommendation:

1. Configure an external interrupt on the raising edges of the input where the button/switch is wired. Note that only pins 2 and 3 of Uno are capable of external interrupts.
2. Write a very simple ISR that just sets to `True` a global `volatile` variable (a flag to signal that the button/switch has been actuated) and does nothing else.
3. In the `loop()` check if the flag variable has been changed by the interrupt. If that's the case, then:

* Debounce/deglitch the button/switch (optional, but highly recommended).
    * Read the analog input of your choice and store its value or do whatever you want to do with it.
    * Reset the flag variable to `False` so it can be changed the next time the interrupt is fired.
> 1 votes

# Answer
You could use EEPROM on the Arduino. For example:

```
#include <EEPROM.h>

int valAddr = 0;

#define analogPin 0
#define buttPin 3
void setup() {
  pinMode(buttPin,INPUT);
}

void loop() {
  /***
    Need to divide by 4 because analog inputs range from
    0 to 1023 and each byte of the EEPROM can only hold a
    value from 0 to 255.
  ***/
  if(digitalRead(buttPin)){
     int val = analogRead(analogPin) / 4;
     EEPROM.write(valAddr, val);
     //access this value again by using int newvalue = EEPROM.read(valAddr)*4;

  }
}

```

By using EEPROM your value will be stored in non-volatile memory, meaning it will stay in memory even after a power cycle which is similar to how `STO>` works.
> 0 votes

# Answer
Only read the analogue pin if the button is pressed.

```
#define analogPin 0
#define buttPin 3

int analogVal = 0;

void setup() {
  pinMode(buttPin,INPUT);
}

void loop() {
    // You can do stuff here

    // If the button is pressed...
    if (digitalRead(buttPin)
    {
        // ..read the analogue pin
        analogVal = analogRead(analogPin) / 4;
    }

    // You can do stuff here
}

```
> 0 votes

# Answer
Here's a simple way of tracking the switch and managing the bit of state you need to manage:

```
int analogPin = 0;
int switchPin = 3;
int switched = 0; // the last-known state of the switch
int lastRead = 0; // the last-desired analog sample

void setup() {
  pinMode(switchPin, INPUT_PULLUP); // connect switch to switchPin+GND w/o resistors
}

void loop() {

  if(digitalRead(switchPin)){ // switch on:
    if(!switched){ // switch on, but was unknown
      lastRead = analogRead(analogPin); // the wanted leading-edge value
      switched = 1; // seen it on
    }//end if switch changed?
  }else{ // switch off:
    if(switched) switched = 0;      //  remember that switch is off
    lastRead = analogRead(analogPin); // the latest value
  }

  Serial.println("Value is " + String(lastRead));
  delay(500);
}

```
> 0 votes

# Answer
Read the analog input and store it, continuously. If the switch is off, also write the value to the "freeze" value:

```
void loop(){
   int value, freeze;

   value = analogRead(ANALOGPIN);
   if( !digitalRead(SWITCHPIN) ){
      freeze = value;   // sw is off, upd freeze value
   }
}

```

This doesn't take into account possible bouncing of the switch. That may or may not matter depending on the actual rate of sampling the analog input and what you intend to do with the frozen output, as the switch bouncing will be shorter than human perception but long enough (10s of msec, perhaps) for the MCU to notice and react to changes.
> 0 votes

# Answer
> it will continuously read my analog input.

easy:

1. have the adc in free running mode and in the isr writes the adc value to a buffer.
2. watch the state of the button in an isr. if it changes, save the buffer value to something else.

there are simpler ways of doing it but less real time than that. need to watch out for atomicity if a multi-byte value is involved.
> 0 votes

---
Tags: arduino-uno, variables
---


title: Linking Arduino and Matlab

text:
# Question
Title: Linking Arduino and Matlab
My project is based on controlling a moving fan using different hand gestures. I am using image processing toolbox from matlab to detect and identify various hand movements.I want to link my matlab codes to arduino for hardware implementation. How to link these two?

# Answer
> 3 votes
This block of code can give you some idea...

```
% create an arduino object

a = arduino('com3', 'uno');

% start the loop to blink led for 10 seconds

for i = 1:10

    writeDigitalPin(a, 'D11', 1);

    pause(0.5);

    writeDigitalPin(a, 'D11', 0);

    pause(0.5);

end

% end communication with arduino

clear a

```

For more details on this code and working of it you can visit.... Here

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


# Question
Title: Problem sending data from arduino with ESP8266 to a local mysql database
i'm currently trying to send a randomly generated number from Arduino via ESP8266 wifi module to a local mysql database estabilished with xampp, but having a problem with it. Here is my arduino and php receiving code. I should mention that i'm extremely unfamiliar with mysql, php, and the whole server & database things, so any help would be greatly appreciated.

Arduino Code:

```
#include <ESP8266WiFi.h>

const char* server = "192.168.1.106";
const char* ssid = "DARUSALAM C8";
const char* password = "asro4520";
const char* SensorID = "ESP001";

WiFiClient client;

void setup() {
  Serial.begin(115200);
  delay(10);

  pinMode(BUILTIN_LED, OUTPUT);
  digitalWrite(BUILTIN_LED, HIGH);

  WiFi.begin(ssid, password);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.print(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi Connected");
}

void loop() {
float n = random(300);

Serial.print("Random Number: ");
Serial.println(n);

  if (client.connect(server,80)) {
    Serial.print("Posting data...");
    digitalWrite(BUILTIN_LED, LOW);
    Serial.println("Random Number: " + String(n));
    client.println("GET /log.php?n=" + String(n));
    client.println("HOST: ");
    client.println(server);
    client.println("Connection: close");
    client.println();

    client.stop();
    Serial.println();

    digitalWrite(BUILTIN_LED, HIGH);
  }

  delay(5000);
}

```

PHP code:

```
<?php

$db_amb = mysqli_connect("127.0.0.1", "root", "", "wemos");
if (!$db_amb) die("Gagal terkoneksi ke DB Utama. Error : " . mysqli_connect_error());

$n = $_REQUEST['n'];
if (!empty($n) &&)
{
  $s = "insert into data_random set value1='$n'";
  $r = mysqli_query($db_amb, $s);
  echo "OK";
}
else echo "ERR";
?>;

```

The database is named 'wemos', and the table where i intend to store the data is named 'data\_random' with 4 columns named value1-value4. My intentions is to store the random number to the 'value1' field.

**EDIT** the problem i encountered is whenever i checked `http://localhost/log.php` this appears:

```
Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\log.php on line 7

```

i have tried modifying the syntax in numerous ways but the problem presist. I suspect my code may have some underlying fundamental problem that is not syntax related, but i can't tell due to my lack of experience. Again, any help/clue is greatly appreciated. Thank you very much

# Answer
The `HOST` should not have a newline after it, so you should have

```
client.print("HOST: ");
client.println(server);

```

In addition your PHP looks dodgy to me. I'm not very familiar with PHP at all, but I think the `&`s here are left over from something you have removed, and causing syntax errors - just remove them

```
if (!empty($n) &&)

```

I believe your `n` parameter is going to be in `_GET` (not `_REQUEST`). Also, you should check whether it's there, not just assume it is, so:

```
if isset ( $_GET["n"] )
{
    $n = $_GET["n"];
    // Do your database stuff here
}

```

(You should find the PHP log (where depends on what OS your server is running on) and I think it would point you straight to this problem. No point trying to debug it blind.)
> 1 votes

# Answer
Change this:

```
client.println("GET /log.php?n=" + String(n));
client.println("HOST: ");
client.println(server);

```

To this:

```
client.print("GET /log.php?n=" + String(n));
client.println( " HTTP/1.0" );
client.print("Host: ");
client.println(server);

```

This means you're sending the `Host:` header + value on one line, and you're correctly appending the `HTTP/1.0\n` after your URL-request.
> 0 votes

---
Tags: esp8266, http
---


title: Arduino Shield on Breadboard

text:
# Question
Title: Arduino Shield on Breadboard
I would like to ask if I can stack directly Adafruit PN532 RFID Shield onto my breadboard. Or do I need something for that? Thank you.

# Answer
> 3 votes
Chances are the offset headers won't allow the shield to directly plug into a breadboard.

As @Majenko noted, shields have a header that is offset by 0.16" from the other headers. Since a breadboard is a strict 0.1" grid that header won't fit into the holes.

# Answer
> 1 votes
@Mazaryk is right.

Shields have a header that is offset by 0.16" from the other headers. Since a breadboard is a strict 0.1" grid that header won't fit into the holes.

# Answer
> 1 votes
There was a Kickstarter project a few years ago to make just such an adapter. You might get in touch with the developer to find out whether he's made (or is planning) another run.

---
Tags: adafruit, rfid
---


# Question
Title: RTL8170 Web Server - client unable to connect
RTL8170 is a new module, which is in many ways better than the old ESP8266 module. We are able to flash this module with Arduino using an Ameba Writer, and it should be able to support any code that is supported by the ESP (with some adjustments). It has been officially supported by Realtek's environment but it does not use all the GPIO (only 2). Luckily, pvvx developed an environment for Arduino IDE, which we can install and use through this tutorial: https://hackaday.io/project/19163/logs

I have uploaded a modified SimpleWebServerWiFi sketch from Ameba RTL8170 examples by both trying the official Realtek and pvvx's environments, and using LEDs to troubleshoot (I don't have an SPI/I2C LCD or a Serial-to-USB) I found the module being able to connect to my Samsung's hotspot but unable to communicate with the module because server.available() never turns true. When my module connects to my Samsung Note 4's hotspot, I see its IP (192.168.43.123) and fail to connect to it via a browser (on the phone or with a Windows laptop). Android port scanning apps indicate that the target IP address of the module has no open ports. Code below.

Update2: I've made adjustments to the code according to suggestions, but it still didn't respond. Updated code below:

```
   /*-----------------------------------------------------------------|
  |  Build using pvvx's enviroment: https://github.com/pvvx/RtlDuino  |
  |  Tutorial: https://hackaday.io/project/19163/logs                 |
  |=================================================================*/

#include <WiFi.h>

char ssid[] = "WiFi_SSID";      //  your network SSID (name)
char pass[] = "password";   // your network password
int keyIndex = 0;   // your network key Index number (needed only for WEP)
String currentLine = "";   // make a String to hold incoming data from the client

int status = WL_IDLE_STATUS;
WiFiServer server(80);

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

  //Serial.begin(38400);      // initialize serial communication
  pinMode(LED_BUILTIN, OUTPUT);      // set the LED pin mode
  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    //Serial.println("WiFi shield not present");
    while (true); // don't continue
  }
  String fv = WiFi.firmwareVersion();
  if (fv != "1.1.0") {
    //Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    //Serial.print("Attempting to connect to Network named: ");
    //Serial.println(ssid);         // print the network name (SSID);

    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);
    // wait 0.2 seconds for connection:
    delay(200);
  }

  server.begin();                   // start the web server on port 80

}

void loop() {

  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,

    //Serial.println("new client");           // print a message out the serial port
    while (client.connected()) {            // loop while the client's connected

      if (client.available()) {             // if there's bytes to read from the client,

        char c = client.read();             // read a byte, then
        //Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {

            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Length: 88");
            client.println("Content-Type: text/html");
            client.println("Connection: Closed");
            client.println();

            // the content of the HTTP response follows the header:
            client.print("Click <a href=\"/H\">here</a> turn the BUILTIN_LED on<br>");
            client.print("Click <a href=\"/L\">here</a> turn the BUILTIN_LED off<br>");

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            //break;
          } else {    // if you got a newline, then clear currentLine:
            //digitalWrite(1,HIGH); // Doesn't turn ON
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          //digitalWrite(1,HIGH); // Turns ON
          currentLine += c;      // add it to the end of the currentLine
        }
        //digitalWrite(1,HIGH); // Turns ON
        // Check to see if the client request was "GET /H" or "GET /L":
        if (currentLine.endsWith("GET /H")) {
          digitalWrite(LED_BUILTIN, HIGH);               // GET /H turns the LED on
        }
        if (currentLine.endsWith("GET /L")) {
          digitalWrite(LED_BUILTIN, LOW);                // GET /L turns the LED off
        }
      }
    }
    //digitalWrite(1,HIGH); // Turns ON
    // close the connection:
    client.stop();
  }
}

```

**Update 1:**

I am still unable to fix the code. If no one can fix this code, please feel free to provide a totally new code.

P.S.: If this question keeps stagnating, I'll remove it and recreate it.

Any help is appreciated. Thank you!

# Answer
Inside the while loop, where you give the link to click you have a break that prevents the handling of the answer from the client.

I would reconsider the use of that break and structure the code to not use it at all.
> 1 votes

# Answer
If you must use `String`, get its declaration out of `loop()`. You're only fragmenting your heap and reducing available RAM. Instead, declare it in the file scope and reserve sufficient space for a request line with the `reserve()` method in your `setup()`.

Though response headers are supposed to be case-insensitive, it's still a good idea to follow the 'standard', spaces and all, like this for instance:

```
HTTP/1.1 200 OK
Content-Length: 88
Content-Type: text/html
Connection: Closed

```

Try sending all the fields above, especially the content length. And get rid of the `break` like mico said. There's no way your builtin LED will turn on or off if you keep breaking right after you respond to the client.
> 0 votes

---
Tags: esp8266
---


# Question
Title: Reading values from SQL Arduino ethernet
I'm about to do this project where I will make some lights flash up depending on some values that are in an SQL database on a server. I have already bought my Arduino and waiting for it to arrive. But I've been stuck at how to read the SQL data from the Arduino, connected to ethernet only.

Is there a library where I can select from the database directly or do I have to make a web service, in which I can make a http request to when needed?

If it's a web service, can I be directed to some examples of this being used with Arduino? I've been looking around the past few days but haven't been able to find a decent example.

Best regards and thanks a lot in advance for your time! :-)

# Answer
> 1 votes
I would make a small http REST API on your SQL server. The Arduino could use the API to get the data. The API can easily be done in php, ruby or whatever.

# Answer
> 0 votes
Connecting to an SQL database from the Arduino would be the hard way. Creating a simple web page that can read data from your database and display said data would be the easier way. You could then access this data on the Arduino via an http request.

Here's an example of how to write such a web page in PHP: https://www.w3schools.com/php/php\_mysql\_select.asp

And here's the Arduino example for an HTTP request with an ethernet shield: https://www.arduino.cc/en/Tutorial/WebClient

---
Tags: arduino-uno, programming, ethernet, web-service
---


# Question
Title: How to change the baud rate of ESP8266 (12E) using an Arduino Uno?
I have with me an Arduino UNO and an ESP8266 (12E) WiFi Module. I need to make a webserver using the two. I read that the default baud rate for ESP8266 is 115200, and that the software serial pins can't handle such high speeds. I dont have an USB-UART converter at hand. Is there a way to use my Arduino as one to change the baud rate, so that I can interface with the chip using the software serial pins of the Arduino later.

# Answer
> 1 votes
You can use this block of code in Arduino to set baud rate...

```
void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {}

```

Change value in serial.begin() as per your value.

# Answer
> 1 votes
Use SoftwareSerial library for your module and define your own tx and rx pins like this and then you can define baud rate for your specified serial pins.

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9); // RX, TX for your module
void setup(){
   mySerial.begin(115200);
}

```

for more details visit https://www.arduino.cc/en/Reference/SoftwareSerialBegin

# Answer
> 0 votes
You can use the SoftwareSerial library and define your own tx and rx pin and set baud rate according to your requirement.

```
#include <SoftwareSerial.h>   // SoftwareSerial library
SoftwareSerial mySerial(2,3); // RX, TX for your module

void setup()
{
   mySerial.begin(9600);      // Set your buad rate
}

```

And you can also do without this library.

```
void setup()
{
  Serial.begin(9600);        // Set your baud rate
}

```

---
Tags: arduino-uno, esp8266, softwareserial
---


# Question
Title: Working or functionality of pinMode(), digitalWrite() and digitalRead()
I'm a newbie in Arduino. I find out a couple of examples.

Here, below arduino simple code I just uploaded.

Here, what is functionality or working of `pinMode`, `digitalWrite` and `digitalRead` ?

```
const int kPinLed = 7;
const int kPinBtn = 8;

void setup()
{
  pinMode(kPinLed, OUTPUT);
  pinMode(kPinBtn, INPUT_PULLUP);
}

void loop()
{
  if(digitalRead(kPinBtn) == LOW)
  {
    digitalWrite(kPinLed, HIGH);
  }
  else digitalWrite(kPinLed, LOW);
}

```

# Answer
> 5 votes
```
{
  pinMode(kPinLed, OUTPUT);
  pinMode(kPinBtn, INPUT_PULLUP);
}

```

This block of code used to define mode of Pin i.e. making pin as Output pin or Input pin.

```
if(digitalRead(kPinBtn) == LOW)
{

}

```

This block of code is used to read value from defined digital pin either High or Low. And in return will give pin state High or Low. For example if we want to make LED ON which is connected to one of digital pin of Arduino at certain condition, we will define that pin under above block of code and can read state of that pin as High or Low.

```
 {
   digitalWrite(kPinLed, HIGH);
 }
 else digitalWrite(kPinLed, LOW);

```

This block of code is used to make Pin state High or Low i.e. Under certain condition this function will make pin state either High or Low.

To learn more, visit......

**PinMode** Click here

**DigitalRead** Click here

**Digital Write** Click here

# Answer
> 5 votes
Welcome to the world of Arduino!

To start off, the Arduino website has excellent descriptions of its various API functions, in your case - https://www.arduino.cc/en/Reference/pinMode

https://www.arduino.cc/en/Reference/DigitalWrite

https://www.arduino.cc/en/Reference/DigitalWrite

Now to answer your question:

**pinMode** determines whether a specified pin behaves as input or output - does it read a signal to the Arduino (read from a a sensor, for example) or does it output to another component (a led to light it, a motor to move it). It achieves this by changing the impedance on the pin- high impedance for input, low for output.

**IINPUT\_PULLUP** means both setting the pin to input mode, while 'pulling up' the input to be high when it is not explicitly low by an external component (whatever is connected to the pin)

```
  //configure the pin somePin to behave as output
  pinMode(somePin, OUTPUT);
  //configured the pin to behave as input, and 'pullup' the input to HIGH
  pinMode(somePin, INPUT_PULLUP);

```

Once you have set a pins mode to be input/output, you can read or write from it, depending on its mode.

If you configured a pin to be in input mode, you can use **digitalRead**

```
//read the value from someInputPin and store it in the variable 'num'
int num = digitalRead(someInputPin);

```

If you configured a pin to be in output mode , you can use **digialWrite**

```
//write the value from 'num' to someOutputPin, and by extension whatever connected to it
int num = HIGH;
digitalWrite(someOutputPin,num);

```

# Answer
> 3 votes
Very good question for every beginner. Let me explain.

**pinMode()** : This function set the functionality of pin. Means either INPUT or OUTPUT or INPUT\_PULLUP.

INPUT use when you connect your arduino to the sensor.

OUTPUT use when you connect your arduino to LED, motor etc.

INPUT\_PULLUP use when we require internal pull-up. For example, if we connect a pushbutton to our arduino then we require some pull-up resistor. Then this thing can be done by this INPUT\_PULLUP. So we don't require any resistor in circuitry.

Now depend upon your circuit requirement you have to use proper pinMode.

**Syntax:** pinMode(pin, mode)

Where,

pin: the number of the pin whose mode you wish to set

mode: INPUT, OUTPUT, or INPUT\_PULLUP.

You can see this thing in your code.

```
void setup()
{
  pinMode(kPinLed, OUTPUT);       // LED as OUTPUT
  pinMode(kPinBtn, INPUT_PULLUP); // Push Button as INPUT with pull-up.
}

```

**digitalWrite():** This function set pin states either HIGH or LOW. Here, 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.

**Syntax:** digitalWrite(pin, value)

Where,

pin: the pin number

value: HIGH or LOW

Now, again in your code.

```
digitalWrite(kPinLed, HIGH); // Pin set as HIGH

digitalWrite(kPinLed, LOW);  // Pin set as LOW

```

**digitalRead():** This function use to read the value from a specified digital pin, either HIGH or LOW.

**Syntax:** digitalRead(pin)

Where,

pin: the number of the digital pin you want to read (int)

And this thing in your code looks like.

```
if(digitalRead(kPinBtn) == LOW) // Check pin states : LOW or HIGH
{
  //Your code...
}

```

# Answer
> 2 votes
PinMode sets the mode or function of the pin, like input (when you connect it to a sensor), or output (when you connect it to a LED for example). There are also some variances (like pullup/pulldown for special cases).

In practice, when you set the value to LOW, 0 V will be put on the signal, and 5 V will be put when it is HIGH (at least on an Uno).

PinModes are normally set during setup (once), and DigitalRead/Writes in the loop since you want to change it dynamically.

Btw, the last pat of the example can be better written as:

```
digitalWrite(kPinLed, digitalRead(kPinBtn) == LOW ? HIGH : LOW);

```

The ? operator (called ternary operator) checksk if the condition (digitalRead(kPinBtwn) == LOW is true, if so it will use the value behind ? otherwise the vvalue after : is used).

---
Tags: arduino-uno, programming
---


# Question
Title: Passing variable value in structure object
in this code i want to pass value of variable char array 'pass' in object "MyObject". But i am getting this error.

```
    Arduino: 1.6.11 (Windows 8.1), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

C:\Users\XXX\Desktop\EEPROM_put\EEPROM_put.ino: In function 'void setup()':

EEPROM_put:17: error: array must be initialized with a brace-enclosed initializer

};

^

exit status 1
array must be initialized with a brace-enclosed initializer

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

when i change pass to \*pass, result of EEPROM.get() is 1 and 6, instead of 1, 62345, 7539514682.

```
#include <EEPROM.h>
struct MyObject {
boolean stat;
char password[6];
char mobile[11];
};

char pass[6]="62345";
void setup() {
Serial.begin(9600);
while (!Serial);
MyObject customVar = {
  1,
  pass,
  "7539514682"
 };
EEPROM.put(1, customVar);
Serial.print("Written custom data type!");
}

void loop() {

}

```

# Answer
> 2 votes
Use `class` and `constructor`

```
#include <EEPROM.h>
class MyObject {
    boolean stat;
    char password[6];
    char mobile[11];
  public:
    MyObject(bool tempStat, char tempPassword[], char tempMobile[])
    {
      stat = tempStat;
      strcpy(password, tempPassword);//As suggested by mikael
      strcpy(mobile, tempMobile);
    }
};

char pass[6] = "62345";
void setup() {
  Serial.begin(9600);
  while (!Serial);
  MyObject customVar(true, pass, "7539514682");
  EEPROM.put(1, customVar);
  Serial.print("Written custom data type!");
}

```

# Answer
> 0 votes
While the method from Sniper's answer works, it involves copying the data, which is something you often want to avoid on an Arduino. The simplest fix to your problem is probably to initialize your `password` field with a literal string, just like you did with the `mobile` field:

```
MyObject customVar = {
    1,
    "62345",
    "7539514682"
};

```

or maybe, if you want the password to be written near the top of the program,

```
#define PASS "62345"

MyObject customVar = {
    1,
    PASS,
    "7539514682"
};

```

Another option is to not store the strings in the object. Instead, store them elsewhere and have the object only hold *pointers* to them:

```
struct MyObject {
    boolean stat;
    const char *password;
    const char *mobile;
};

char pass[6] = "62345";

[...]

MyObject customVar = {
    1,
    pass,
    "7539514682"
};

```

Note that, in this case, the mobile number is stored by the compiler as an unnamed string constant. Because it is constant, the `mobile` field has been typed as `const char *`. I typed the `password` field identically for symmetry, but in this use case it need not be `const`.

---
Tags: arduino-mega, eeprom
---


title: Arduino Standalone construction

text:
# Question
Title: Arduino Standalone construction
In tutorial - https://www.arduino.cc/en/Main/Standalone , they have used voltage regulator. Can we able to do without Voltage regulator ?(to compact the circuit), If so what should the voltage & current value in Atmega328?

# Answer
> 3 votes
That's actually quite an involved question to answer. The short answer is "Yes, you can do without the regulator as long as you get the voltage right".

And that is where it gets tricky.

The datasheet states:

> * Operating Voltage:
>     + 1.8 - 5.5V

So you can power it from two or three AA batteries, for instance (3V - 4.5V). However, that is not the whole story.

The voltage you provide it with dictates what frequency the chip can reliably run at. Later in the datasheet is this nice little graph:

Since the normal Uno-like arrangement runs at 16MHz you're looking at a minimum voltage of around 3.8V - 4V (it's actually quite hard to work out from that graph).

But if you are willing to reduce your clock speed to 8MHz (which is what the 3.3V Arduino "Pro" boards run at) then you can drop right down to about 2.5V.

At a 2.5V lower limit with 3 AA batteries it would equate to a minimum voltage of 0.83V per cell, which is below the normal minimum accepted "flat" voltage of 0.9V per cell.

So powering from 3 AA batteries with a clock speed of no more than 8MHz would give you probably the best run-time. Note, also, that a decrease in clock frequency decreases the current consumption as well - the slower you run the chip the less current it needs. You can see that in this graph in the datasheet:

And yes, as you can see, the lower the supply voltage the lower the current as well. So as the batteries run down and the voltage drops so does the current, reducing the speed at which the batteries will run down.

As you can see, if you don't mind the supply voltage changing (which of course will affect everything else in the circuit, so you need to check those out first), running directly from batteries without a regulator can actually have advantages. But as I say, you need to check what else you are running in the circuit to make sure it doesn't mind if the power supply voltage drifts.

And don't forget, also, that the supply voltage affects the ADC readings, since they are referenced to that voltage as well.

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


title: Arduino Mega and LP621024D70LL

text:
# Question
Title: Arduino Mega and LP621024D70LL
I'm intending to try a LP621024D70LL (128 KB SRAM memory, 32 pins) on an Arduino Mega.

However, I now see there is no library for it ... I wonder how hard it is to access it? I can miss 32 digital pins (the Mega has enough), however, I'm a bit worried about having to write a library, especially since I do not have any gear like an oscilloscope.

Would it be easy to use the library of the more knwn 32K256 or 23LC1024 as basis? (where I also have no experience with btw).

# Answer
> 1 votes
That's so old I can't find a datasheet for it. If you know the pinout then you know more than me at the moment. Chances are it's a standard 8-bit CPU interface.

* Writing:

Set the address on the address pins, set the data to write on the data pins, enable the chip, and pulse WR.

* Reading:

Set the address on the address pins, enable the chip, and while pulsing the OE pin read the data pins.

And no, you can't really use a serial SRAM chip library as a basis - the operation is completely different.

---
Tags: arduino-mega, sram
---


title: Hex to binary, LED blinking

text:
# Question
Title: Hex to binary, LED blinking
I need to write a program that takes a user inputted HEX value and converts it to binary, then an LED blinks according to the number of 1's in the binary. For instance, if the value is 0xABC then there are number of 1's are 7 so LED will blink 7 times.

I only just started Arduino so not sure how to let user input a value nor do I know how to convert HEX to BIN but I'm assuming that once I convert the HEX to BIN I can just use a loop to count the number of 1's yet I'm unsure as to actually how to do that. This is what I've written so far.

```
  byte val=0xABC;
int ledPin=13;

int countSetBits(unsigned int n)
{
    unsigned int c;
    for (c=0;n>0;n=n&(n-1))
        c++;
    return c;
}

void blink(int n)
{
    for (int i = 0; i < n; i++)
    {
        digitalWrite(ledPin,HIGH);
        delay(500);
        digitalWrite(ledPin, LOW);
        delay(500);
    }
}

void setup()
{
    Serial.begin(9600);
    pinMode(ledPin,OUTPUT);
    blink(countSetBits(val));
}

void loop()
{   }

```

Any help would be appreciated. EDIT: If I want to take a number from a user and then make the LED blink according to the number of 1's in its binary form, how would I implement that?

# Answer
> 2 votes
You are almost there. Now you just have to read and parse the hex numbers supplied by the user.

The simplest way to accept numeric user input is with `Serial.parseInt()`. This is not always ideal since it involves blocking the program until it either receives an invalid character or the reading times out. It is also not applicable to your situation because it only works with decimal numbers.

The better standard way to get the input is to put the incoming bytes into a buffer until you catch a specific character designated as an end of message marker. This is typically a CR (`'\r'` in C++) or an LF (`'\n'`). This technique is more involved than just calling `parseInt()` but it is often preferred because it can be done in a non-blocking way. See for example this simple command line interpreter.

In your case, however, you do not need to buffer the incoming bytes. You can instead parse the hex number while you read it, like this:

```
void loop()
{
    if (Serial.available()) {
        static unsigned int val;
        int c = Serial.read();
        if (c >= '0' && c <= '9') {
            val = 16 * val + (c - '0');
        } else if (c >= 'a' && c <= 'f') {
            val = 16 * val + (c - 'a' + 10);
        } else if (c >= 'A' && c <= 'F') {
            val = 16 * val + (c - 'A' + 10);
        } else {  // End of number.
            blink(countSetBits(val));
            val = 0;  // reset for next round
        }
    }
}

```

# Answer
> 1 votes
You might do it much simpler... Create a fixed array that for each hex character possible (0..F) has the number of 1's counted.

Than iterate through the string, sum up the values of 1's from the array and make a LED blink that many times.

Something in pseudo code:

```
// Number of 1's: 0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
boolean ones[] = {0, 1, 1, 2, 1, 2, 2, 3, 1, ...                };
string str = "ABC";
int total = 0;
for (index = 0; index < str.length; index++)
{
   if string[index] <= '9'
       total += ones[string[index] - '0'];
   else
       total += ones[string[index] - 'A' + 10];
}

```

# Answer
> 1 votes
You could use *BIT SHIFTING* looks flash, but is actually really useful.

```
const unsigned char value = 0x55;  // Input
int blinks = 0;                    // Times to blink.

for (int i = 0; i < 8; ++i)
{
    blinks += ((value >> i) & 0x01); // Could just blink the light if its true.
}

```

`(value >> i)` takes value and moves the number right `i` places. So if value is Hex 55 (0x55) that is 01010101 in binary. On the first time around the loop when `i` is 0 `(value >> 0)` will be 0x55 (unchanged). `0x55 & 0x01` is a logical and between the two numbers, so any bits that are set in both will be set in the result. Since 0x01 only has the least significant bit set (LSB) then we only need to look at the LSB of 0x55, which we know is set. therefore blinks is incremented by one. On the second time around the loop `value >> i` is 0x2A (00101010) because value has been shifted right one place. So `0x2A & 0x01` = 0, so blink isn't altered.

etc.

The answer at the end of the loop is `blinks == 4`.

# Answer
> 0 votes
> Any help would be appreciated.

your code is in pretty good shape - there are some minor issues that need to be taken care of. the countSetBits() is a fairly standard implementation and in this case returns the right value:

I sped up the blinky rate for convenience.

a good starting out place.

---
Tags: led
---


# Question
Title: How does avrdude burn a bootloader much quicker than the Arduino IDE?
To burn a bootloader to the Arduino Micro (ATMega32u4), I'm using an Arduino Uno with the ArduinoISP program uploaded to it.

### 1st case: Arduino IDE

Very straightforward, using the ArduinoISP sketch included in the IDE.

From clicking on "Burn Bootloader" to the output window displaying "Done burning bootloader", it takes **61 seconds**.

### 2nd case: avrdude

I'm running `avrdude` directly from the Arduino IDE's folder like so (line breaks added for your reading pleasure):

```
D:\Programme\Arduino\hardware\tools\avr\bin>avrdude.exe -v -v -c arduino
-p atmega32u4 -P com4 -b 19200
-U flash:w:"..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex"

```

From pressing Enter to `avrdude.exe done. Thank you.` displaying on stdout, it only takes **11 seconds**. Full output is posted below.

```
 D:\Programme\Arduino\hardware\tools\avr\bin>avrdude.exe -v -v -c arduino -p atmega32u4 -P com4 -b 19200 -U flash:w:"..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex"

avrdude.exe: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "D:\Programme\MHV AVR Tools\bin\avrdude.conf"

         Using Port                    : com4
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude.exe: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude.exe: Device signature = 0x1e9587 (probably m32u4)
avrdude.exe: safemode: hfuse reads as D8
avrdude.exe: safemode: efuse reads as CB
avrdude.exe: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude.exe: erasing chip
avrdude.exe: reading input file "..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex"
avrdude.exe: input file ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex auto detected as Intel Hex
avrdude.exe: writing flash (32730 bytes):

Writing | ################################################## | 100% 0.25s

avrdude.exe: 32730 bytes of flash written
avrdude.exe: verifying flash memory against ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex:
avrdude.exe: load data flash data from input file ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex:
avrdude.exe: input file ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex auto detected as Intel Hex
avrdude.exe: input file ..\..\..\arduino\avr\bootloaders\caterina\Caterina-Genuino-Micro.hex contains 32730 bytes
avrdude.exe: reading on-chip flash data:

Reading | ################################################## | 100% 0.35s

avrdude.exe: verifying ...
avrdude.exe: 32730 bytes of flash verified

avrdude.exe: safemode: hfuse reads as D8
avrdude.exe: safemode: efuse reads as CB
avrdude.exe: safemode: Fuses OK (E:CB, H:D8, L:FF)

avrdude.exe done.  Thank you.

```

## Question:

Where does this discrepancy come from? The baud rate is hard coded to be 19200 in the ArduinoISP sketch, so that can't be it.

# Answer
> 4 votes
In the Arduino IDE do this:

* File \> Preferences \> Show verbose output during: \> upload (check) \> OK
* Tools \> Burn Bootloader

After it finishes examine the output in the black console window at the bottom of the Arduino IDE window. If you look carefully you'll see that the Arduino IDE actually runs two separate AVRDUDE commands when you **Burn Bootloader**. The first sets the fuses according to the settings in boards.txt for the selected board, the second actually burns the bootloader. So your comparison is not really fair unless you run both commands in your test of using AVRDUDE directly.

## Edit by OP:

Full output in the Arduino IDE:

```
D:\Programme\Arduino\hardware\tools\avr/bin/avrdude -CD:\Programme\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cstk500v1 -PCOM4 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xcb:m -Uhfuse:w:0xd8:m -Ulfuse:w:0xff:m

avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "D:\Programme\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM4
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: erasing chip
avrdude: reading input file "0x3F"
avrdude: writing lock (1 bytes):

D:\Programme\Arduino\hardware\tools\avr/bin/avrdude -CD:\Programme\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cstk500v1 -PCOM4 -b19200 -Uflash:w:D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex:i -Ulock:w:0x2F:m
Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x3F:
avrdude: load data lock data from input file 0x3F:
avrdude: input file 0x3F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lock verified
avrdude: reading input file "0xcb"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0xcb:
avrdude: load data efuse data from input file 0xcb:
avrdude: input file 0xcb contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "0xd8"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xd8:
avrdude: load data hfuse data from input file 0xd8:
avrdude: input file 0xd8 contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xff"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xff:
avrdude: load data lfuse data from input file 0xff:
avrdude: input file 0xff contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified

avrdude done.  Thank you.

avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "D:\Programme\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex"
avrdude: writing flash (32730 bytes):

Writing | ################################################## | 100% 35.65s

avrdude: 32730 bytes of flash written
avrdude: verifying flash memory against D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex:
avrdude: load data flash data from input file D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex:
avrdude: input file D:\Programme\Arduino\hardware\arduino\avr/bootloaders/caterina/Caterina-Micro.hex contains 32730 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 19.92s

avrdude: verifying ...
avrdude: 32730 bytes of flash verified
avrdude: reading input file "0x2F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x2F:
avrdude: load data lock data from input file 0x2F:
avrdude: input file 0x2F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lock verified

avrdude done.  Thank you.

```

---
Tags: avr, programmer, bootloader, avrdude
---


title: Arduino voltmeter maximum amp input

text:
# Question
Title: Arduino voltmeter maximum amp input
I made a programmable Arduino that measures an input voltage. The Arduino will close or open an inverter using a relay to prevent the set of batteries from dropping below 50% to keep the batteries healthy. I currently have a set of 8 6V batteries configured to supply a total of 12V to one inverter. I used a set of 10k ohm and 100k ohm to safely measure the 12 volt input from the batteries. In the current configuration the total Amperage provided by the set of batteries is 400 amps. Is it safe to measure the voltage from a 12V/400A input or do I need some kind of protection?

# Answer
It is perfectly safe.

The Arduino will see the voltage reduced by the divider you have. It will see whatever current it needs to see in order to sense the voltage - which is a tiny amount.

Remember: Current is drawn on demand by the load. It is never pushed by a supply.
> 1 votes

---
Tags: arduino-uno
---


title: String to char array conversion

text:
# Question
Title: String to char array conversion
In my project I need to convert a string to a char array. From various examples I concluded that `toCharArray()` will convert a string to a char array. But I failed to do so. The error is:

> 'a' does not name a type

The code I am using is:

```
String a = "45317";
char b[6];
a.toCharArray(b,6);

```

Resources are https://www.arduino.cc/en/Reference/StringToCharArray and http://forum.arduino.cc/index.php?topic=199362.0

# Answer
> 4 votes
If you're trying to use a method of `a` in the global scope, that's doomed to failure. You can only call methods within functions.

If all you want is a char array with "45317" in it then just use:

```
char *b = "45317";

```

If you want to convert a string that is built at runtime into a char array, then your current method is correct - you just have to do it in the right place.

# Answer
> 4 votes
There's a built in conversion which will return the underlying string-contents as a NULL terminated character array:

```
 String foo = "Steve was here"
 char *text = foo.c_str();

```

That is probably all you need, unless you do want to copy into a buffer. In that case you can use the standard C library to do that:

```
 // Declare a buffer
 char buf[100];

 // Copy this string into it
 String foo = "This is my string"
 snprintf( buf, sizeof(buf)-1, "%s", foo.c_str() );

 // Ensure we're terminated
 buf[sizeof(buf)] = '\0';

```

(You might prefer `strcpy`, `memcpy`, etc to `snprintf`.)

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


# Question
Title: Does sharing code on Arduino Create automatically grant any license rights?
I have code I am happy to share under a GNU GPL License and which is marked accordingly. Before I upload it to Arduino Create Web Editor I want to check whether in doing so I inadvertently grant additional license rights. I have searched for any terms and conditions which may inform me but not found any as yet.

# Answer
Arduino Create doesn't assume any licensing of any form. Sharing isn't a public thing. You have to specifically provide someone with a link to your sketch. If you choose to post that link publicly then that is your concern.

Any licensing should be included with your sketch.
> 1 votes

# Answer
You should read the GPL License terms with respect to any rights you are concerned about, but in general, GPL licensed software is available to anyone to do anything with, as long as they keep it public and perpetuate the GPL License. Note: IANALawyer. If you wish to protect any specific rights, you should probably consult one.
> -2 votes

---
Tags: arduino-ide
---


# Question
Title: Is there some kind of timer function that returns the amount of time passed?
I'm doing a project and I want to get the amount of time between two sensor inputs. i.e. the sensor detects something, and it triggers a timer, and when the sensor picks up something else, it stops the timer and stores the amount of time the passed in a variable. Is there a library or a specific function that exists?

# Answer
> 1 votes
Just adding a few notes to the perfectly valid answers you already got:

On your typical AVR-based Arduino, `micros()` has a resolution of 4 µs and `millis()` is updated every 1024 µs. This last point implies that `millis()` increments most times by 1 ms, but occasionally by 2 ms. Keep this in mind if time resolution is an issue.

Both `millis()` and `micros()` return 32-bit unsigned numbers. This implies that `millis()` overflows (it rolls-over to zero) roughly every 49.7 days and `micros()` every 71.6 min. This limits the maximum interval length you can measure with each of those functions. It does **not** limit the maximum run time of your program, since subtracting two timestamps does work fine across a rollover event.

# Answer
> 1 votes
It's simple enough to make a "helper" function to give you the number of milliseconds between each call of the function:

```
uint32_t millisSince() {
    static uint32_t lastMillis = millis();
    uint32_t now = millis();
    uint32_t diff = now - lastMillis;
    lastMillis = now;
    return diff;
}

```

Every time you call that it will return the amount of time that has passed since you last called it. The first time it will return 0 since it has never been called before.

# Answer
> 0 votes
Yes, you can use millis() or micros() which give the milliseconds resp microseconds since the board started up.

However by substracting two values taken close within time you can measure a time period (for example for your sensors). With this functionality you can program the timer yourself.

See https://www.arduino.cc/en/Reference/HomePage and search for micros/millis.

# Answer
> 0 votes
Yes, read and store the value from millis() at the first event. Then read millis() again at the second event. Subtract the stored value and you'll have the time, in milliseconds, between the events. millis() returns a long unsigned int and your memory variables for storing its value need to be of the same type.

---
Tags: programming, c++
---


title: Two solenoid valves, both independent

text:
# Question
Title: Two solenoid valves, both independent
I am currently working an automatic home gardening system. There are two moisture sensors and two solenoid valves to allow water to plant two different zones. Preferably, I want to water the plants for x amount of time. I started programming this and I noticed that with my code below, if one solenoid valve goes off, the entire program will delay **until one** of the solenoid valves **closes** and thus the **other** solenoid valve **will not open until the other one is closed**.

However, I want to prevent this from happening and I want the program to continue reading the moisture readings while one of the solenoid valves is open so that the other solenoid valve can open whenever the zone needs water as well.

```
int solenoidPin1 = 1; //connected to Digital 1
int solenoidPin2 = 2; //connected to Digital 2
void setup(){
  pinMode(solenoidPin1, OUTPUT);
  pinMode(solenoidPin2, OUTPUT);
}
void loop(){
  int moisture1 = analogRead(moisturePin1);
  int moisture2 = analogRead(moisturePin2);
  if (moisture1 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
  delay(300000); //water for five minutes
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }

  if (moisture2 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin2, HIGH); //switch solenoid ON
  delay(300000); //water for five minutes
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }
}

```

I was thinking that I should do the following for the conditioning part. Will this work instead for what I'm trying to do?

```
  if (moisture1 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
  }
  else if (moisture1 >= 550){
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }

  if (moisture2 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin2, HIGH); //switch solenoid ON
  }
  else if (moisture2 >= 550){
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }

```

***Note:*** I'm using a capacitive moisture sensor, so the output voltage/reading is **higher** the drier the dirt is.

# Answer
The essence of your problem is that the `delay()` function *blocks* your program until the delay is over. This is only acceptable if the program is doing one single things at a time. If you need to do multiple things in parallel, like monitoring two moisture sensors, this approach does not work.

Then, the first thing is to get read of `delay()` and instead use `millis()` for managing time in a *non blocking* fashion. The essence of this approach is to never wait. Instead, if it is time to do something *right now*, you do it. If not, you just don't do it this time, but you don't wait. This is nicely covered in the Blink without delay Arduino tutorial. You should get familiar with this technique, as it is essential for many Arduino projects.

Your problem is slightly more complex than blinking an LED though, as the valve can be in two different states, and the action to perform depends on that state. This is managed by a software construct called a finite state machine. Essentially you have to remember the current state and, depending on it, you decide what to do and what the next state should be. Here is how you could do the timed watering with this approach:

```
static enum { OFF, ON } stateValve1, stateValve2;
static uint32_t startedValve1, startedValve2;  // time when started

if (stateValve1 == OFF && analogRead(moisturePin1) <= 250) {
    digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
    startedValve1 = millis();
    stateValve1 = ON;
} else if (stateValve1 == ON
        && millis() - startedValve1 >= WATERING_TIME) {
    digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
    stateValve1 = OFF;
}

// and the same for valve 2.

```

For more in-depth coverage of the subject, I recommend you read the Majenko's tutorial on finite state machines

At this point, the next step would be to throw in some modularization in order to make the code less repetitive. I suggest making a class for representing a “timed valve”. The valve has a `turnOn()` method that turns it on, but does nothing if the valve is actually already on. The class takes care of turning the valve off when the time has elapsed. But since it cannot do that all by itself, you have to call an `update()` method periodically to give it a chance to check whether it's time to go off. Here is my implementation of that class:

```
const uint32_t WATERING_TIME = 100000;  // for example

class TimedValve
{
public:
    TimedValve(uint8_t pin) : valvePin(pin), state(OFF) {}
    void turnOn() {
        if (state == ON) return;  // do nothing if already ON
        digitalWrite(valvePin, HIGH);
        state = ON;
        timeStarted = millis();
    }
    void update() {
        if (state == ON && millis() - timeStarted >= WATERING_TIME) {
            digitalWrite(valvePin, LOW);
            state = OFF;
        }
    }
private:
    uint8_t valvePin;
    enum { OFF, ON } state;
    uint32_t timeStarted;
};

```

And you would use it like this:

```
const int solenoidPin1 = 1;
const int solenoidPin2 = 2;
const int moisturePin1 = A1;
const int moisturePin2 = A2;

void setup(){
    pinMode(solenoidPin1, OUTPUT);
    pinMode(solenoidPin2, OUTPUT);
}

void loop()
{
    static TimedValve valve1(solenoidPin1), valve2(solenoidPin2);

    // Turn the valves ON if needed.
    if (analogRead(moisturePin1) <= 250)
        valve1.turnOn();
    if (analogRead(moisturePin2) <= 250)
        valve2.turnOn();

    // Let them turn OFF if it's time.
    valve1.update();
    valve2.update();
}

```
> 1 votes

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


title: How do I power an arduino without USB?

text:
# Question
Title: How do I power an arduino without USB?
I'm working on a project where my arduino talks to another device that uses serial communication. I've connected my USB cable to a USB-to-serial adapter, so it can communicate with the device.

The problem I'm running into is powering the device: if I'm using the USB for serial, I can't use it for power. I have made sure that the device isn't turning on by putting

```
pinMode(13, OUTPUT);
for (int i = 0; i < 10; i ++) {
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);
}

```

at the start of the `setup` function: if it works, it should start by blinking LED 13.

I tried powering it with a 5V power supply through the power jack, next to the USB connector, but that didn't work. Is there something I'm missing? Do I need a different type of power supply?

# Answer
> 1 votes
> my arduino talks to another device that uses serial communication

What other device? You haven't said which Arduino, but Arduinos are generally "devices" which talk to a "controller" (host) which is generally a PC / Mac.

The host has the job of supplying power (via the USB cable) to the device. Thus your Arduino will be powered by the device it is plugged into.

Disregarding this issue for the moment, you can supply *regulated* 5V power directly to the 5V pin on the Arduino. On the Uno (and many others) this is labelled "5V".

The power jack is to supply 7V to 12V (eg. from a wall-wart) which then goes through the voltage regulator on the Arduino (depending on the model in question).

There is quite a discussion about this on https://www.arduino.cc/en/main/arduinoBoardUno. On that it mentions:

> Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

This is true. Directly supplying 5V to the 5V pin bypasses the regulator and also bypasses the reverse-voltage protection diode. However it is *possible* to do it.

---

> What about the Vin pin?

For a Uno you can see from the reference schematic what happens:

The power jack (on the left) goes into the reverse-voltage protection diode (D1). The other side of that becomes Vin. Then it goes into the 5V voltage regulator (U1). The other side of that becomes the 5V line.

Thus to supply 5V you can provide 5V power to the pin marked 5V. It is probably not ideal, because the voltage regulator may not be designed to have power applied on its "output" side.

There is more circuitry to decide whether to use the USB power or the Vin power (not shown above).

# Answer
> 1 votes
The kind of voltage regulator on the Arduino board will need about 7v to give 5v out to the board. If you trust that your 5v supply is well regulated - at least that it won't exceed 5v, no spikes, etc. - you can connect it directly to the 5v pin on the board edge. Just be aware that you'll be bypassing the protection of the voltage regulator so it will be on you to make sure you're providing the proper polarity, well regulated 5v. Exceed that value and you'll stand a good chance of damaging the board.

---
Tags: serial, power, usb
---