title: LiPo batteries with L298N controller

text:
# Question
Title: LiPo batteries with L298N controller
I built an avoidance detector robot from this kit.

When I drove the robot, the two motors performed unequally, so I tested replacing the four x 1.5 AA battery pack with a 9 volts battery. It did the trick. I realized, after having read around Stackexchange a bit, that the L298N controller steals a 1.5 V cell just for "heating up".

So... my question is: Can I run the controller off a LiPo battery? If so, which voltage should I choose, when I want to power my Arduino Uno (copy) and the two motors off it?

I don't really understand what voltage the motors can take.

# Answer
> 2 votes
First off, congratulations on entering the world of robotics. I hope you enjoy it as much as I have. You are correct that the L298N has a voltage drop that is between 1.8V and 3.2V (at 1 Amp) or 4.9V (at 2A). This is a problem I sometimes see in older generations of H-bridge designs. After you figure this problem out and move on, I'd recommend switching to something a little newer like the TB6612FNG or maybe the DRV8871, both of which are pretty common, smaller, and more efficient. But that's a future step. First lets get this current project powered.

I'm having to make some assumptions based on the images that you linked to but I'm going to assume that the motor board can take up to 12V and that it ouputs 5V that you are using to power the arduino. I'm also going to assume that those yellow motors are the familiar cheap hobby motors that run at 3-6V. If any of those are not true, please comment and we can see how things change.

Now as to what kind of batteries to use; there are literally thosands of ways to power this. One option is AA batteries as you are doing now. I would use maybe 6-7 AA batteries to account for the voltage drop of the hbridge but remember that they start at 1.5 but can quickly drop voltage. And the more current you pull from them, the faster they will drop. This will be cheaper if you only want to run it a few times since AA batteries are like $0.50 a piece in bulk. But if you want to run it a lot to experiment, it's going to get expensive (and annoying) fast. Another option is to use NiCad or NiMH batteries that are rechargable. The batteries will be a little more expensive initially and you'll have to buy a seperate charger but this will save money in the long run and be able to supply more current to your motors. NiCad and NiMH batteries are 1.2V (nominal) but come packaged in battery packs so I'd recommend probably an 8.4V pack. Finally there is the Lipo battery packs, also called Li-Ion (which is a much better and more accurate name but I won't get started on that). Li-Ion are rechargable like NiCad and NiMH but are much smaller and lighter for the same energy capacity (mAh). Because of this they have become very popular and have become pretty economical. For instance you can get a decent li-ion for under $20 on hobbyking and be very happy for several years. Li-ion do have an inherant risk but as long as you don't do anything stupid, you'll be fine. They also require a special charger but as long as you aren't worried about super fast charging this isn't too expensive. Li-ion come in individual cells of 3.6V nominal (sometimes advertised as 3.7V) but also come in packs of 7.2V, 11.1V, or 14.4V. Remember that these are the nominal values. A 7.2V pack will start at 8.4V and drain to 6V before it is "dead" If you go this route, I'd go with the 7.2V pack.

I would highly recommend you go with one of the three rechargable options since that will be more economical in the long term and will also allow for longer run times and will supply more current to the motors. Hobbyking.com is a great resource for cheap rechargable batteries as is amazon.

I can't explain everything but here are some further quesitons you should google to get started:

-LiPo safety

-Lipo C rating

-Lipo voltage range

-Lipo mAh rating

I just want to fix a couple misconceptions from other answers:

1) Lipos are not expensive as hell if you take into acount how long they last and their other benefits such as size, weight, and ability to supply current.

2) For a given battery capacity, a LiPo will be smaller and ligher than AA batteries and will provide more current and longer battery life than AA batteries. The ammount of current the Arduino draws will be tiny compared to the current of the motors so don't worry much about it.

3) Not only are Lipos recommended by many people for ground (and air and water) robots, they are becoming the standard for RC cars of almost every size. The motors you are using here are 6V max so 7.2V lipo is a good way to go. Later you might use motors that are 12V and will move up to a 11.1V or 14.4V lipo. Some of the nicer lipos can deliver hundreds of amps to motors and are commonly use in battlebots and similar competions. But you aren't there yet so you're going to use smaller lipos with these smaller motors and maybe someday you'll use big lipos with big motors. Every project has different needs.

4) Sometimes a rechargable battery back will get hot if you are pulling a lot of curernt from it. But as long as you respect the "C" rating (google it) you will be absolutely fine.

---
Tags: motor, battery, robotics
---


title: use button to select variable

text:
# Question
Title: use button to select variable
i have a need to use 3 buttons a a simple option/variable selector at sketch start up ...

Pretty much at startup , script must wait for button press ( one of 3 ) , when button is pressed , use that buttons predefined string value as a variable for the loop script further down .. if wanting to change the "variable" then a reboot is required ..

i know how to digital read in the buttons , but not sure how to

1) wait for one of the buttons to be pressed to then jump to main loop 2) Associate a "string" variable to each button

thinking about it i suppose a If/Else loop will be required for the Input 'wait" and then just if the digital input (button) is pushed then continue .. am i correct ?

Ideas or better way to do it ?

Thx Greg

# Answer
> 2 votes
1) One solution is to create a function that loops repeatedly, eg `while(1)`, until one of the buttons is pressed. It then returns the button "number", eg 0,1 or 2.

2) In C you would usually remember the index into a string table. So one solution is to store the button number in a global variable and use it to index a "string array", something like `char * buttonStrings["B1","B2","B3"];` and to get the string for a button use `buttonStrings[buttonNumber];`

# Answer
> 1 votes
When I am searching for something inside a loop, I find that the simplest thing to do is to just `break` out of the loop once I found it. This was frowned upon in the days when structured programming was a hot thing, but as long as it makes things simpler, you should not be ashamed to `break`:

```
const int button_pins[] = {2, 3, 4};
const char * const urls[] = {"foo.com", "bar.org", "baz.net"};
const char * url;  // the selected URL

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

    // Configure input pins.
    for (int i = 0; i < 3; i++)
        pinMode(button_pins[i], INPUT_PULLUP);

    // Find first button pressed.
    int i;  // button index
    for (i = 0; ; i = i==2 ? 0 : i+1) {
        if (digitalRead(button_pins[i]) == LOW)
            break;
    }

    // The button index selects the URL.
    url = urls[i];

    Serial.print("Selected URL: ");
    Serial.println(url);
}

void loop() {}

```

The `for` loop above is written as an endless loop (no end condition). The expression `i = i==2 ? 0 : i+1` means: “if `i` is `2`, make it `0`, otherwise make it `i+1`”. In other words, we are endlessly looping `i` over 0, 1 and 2.

Now, it may well happen that you actually do not care about which button was pressed once you have selected the proper URL. In this case, you can use the URL pointer as a “flag” that tells you when you can end the loop:

```
// First button pressed selects the URL.
for (int i = 0; !url; i = i==2 ? 0 : i+1) {
    if (digitalRead(button_pins[i]) == LOW)
        url = urls[i];
}

```

Where `!url` means “the URL has not been found”. This works because the C runtime initializes `url` to zero, which is interpreted as `false` in boolean context.

**Addendum**: If you are likely to add new button/URL pairs, you can make this easier by structuring the list as an array of structs:

```
const struct {
    int pin;          // pin number
    const char *url;  // associated URL
} buttons[] = {
    {2, "foo.com"},
    {3, "bar.org"},
    {4, "baz.net"}
    // etc. just add to this list as needed.
};
const size_t button_count = sizeof buttons / sizeof buttons[0];

```

Then the search becomes:

```
for (int i = 0; !url; i = i==button_count-1 ? 0 : i+1) {
    if (digitalRead(buttons[i].pin) == LOW)
        url = buttons[i].url;
}

```

# Answer
> -1 votes
You can try this. The comments in the program explain quite well.

```
const int buttons[3] = {2,3,4}; // buttons pins

int butStatus = 0;

void setup() {
  pinMode(buttons[0], INPUT); // declaring pins as inputs
  pinMode(buttons[1], INPUT);
  pinMode(buttons[2], INPUT);

  while(butStatus<=0) //waiting for a button to be pressed
  {
    for(int i=0; i<3; i++) //running trough the 3 buttons
    {
      if(digitalRead(buttons[i]) == HIGH)
      {
        butStatus = i+1; //set variable to the button that has been turned on
      }

      else
      {
        butStatus = 0; //if there is no button press, keep the variable at 0
      }
    }
  }
}

void loop() {
  //variable butStatus is now equal to the button that has been pressed
}

```

---
Tags: esp8266, button, variables
---


# Question
Title: multiple multiplexer (4051) - how to process the inputs?
I have my Arduiono which has only a limited amount of Inputs/Outputs. But in my project I will have to attach a ton of potentiometers/buttons/LEDs, so I will have to use the IC4051-Multiplexer/Demultiplexer.

I have understood how to switch the Inputs/Outputs via the 3-Bits. But I don't get it, how to connect multiple ID4051s and process the signals(?)

Can someone explain that to me?

# Answer
> 2 votes
The 4051s are only useful, for your potentiometers. For leds, I'd use shift-registers. For buttons you could use input-shift-registers. Though there are better options. E.g. chips that can scan a matrix of buttons, or chips that send you an interrupt, if one of the buttons is pressed (so you don't have to constantly poll the button states.

As to the original question. You can connect the S1, S2, S3, and Z pins of multiple chips to the same pins on the Arduino. You need to use a different Arduino pin for each of the chips E pin.

You can then set the E pin of the chip you want to read to LOW. You then set the correct S1-3 pins to select which output/input of that chip you want to connect to. You then read the value from the Z pin.

I hope that makes sense. Otherwise, let me know.

# Answer
> 1 votes
I have no experience of this chip but I would guess that you would need to connect the child level multiplexer to the output of the parent and use the outputs to drive the address lines.

You could look at an MCP23008 or MCP23016, these are 8 and 16 bit GPIO expanders that you control via I2C. You can have 8 of the MCP230008 (64 pins) before you need to look at I2C bus expanders (which you can get). I think its the same for the 16 bit version, but you would need to double check.

---
Tags: multiplexer
---


title: NodeMCU ESP-12e - Timing errors

text:
# Question
Title: NodeMCU ESP-12e - Timing errors
I'm using the **ESP-12e** with **Arduino IDE**. With that I'm trying to build a clock with a **WS2812B LED strip** matrix that I've build. When I try to display the **seconds** on my matrix there are strange timing problems. It shows me the numbers how I should, the LEDs work OK but ..it misses seconds spontaneously. sometime it jumps the numbers like 00 01 03 06, sometimes 00 02 03 05.. sometimes it hangs at one number for a short time.

1. Is the problem in my code?
2. Or is it due to hardware limitations of the ESP-12e?
3. How can I do it better?

Here is my sketch (I removed some number definitions \[...\] for better overview):

```
#include <ESP8266WiFi.h> //WiFi
#include <Adafruit_NeoPixel.h> //LEDs
#include <TimeLib.h> //Time
#include <WiFiUdp.h> //Synchronize Time

const char* ssid = "XXXXX";
const char* password = "XXXXXXX";

WiFiClient wifiClient;

//NTP Servers
  static const char ntpServerName[] = "us.pool.ntp.org";
  const int timeZone = 1; // Central European Time
  WiFiUDP Udp;
  unsigned int localPort = 8888;  // local port to listen for UDP packets
  time_t getNtpTime();
  void digitalClockDisplay();
  void printDigits(int digits);
  void sendNTPpacket(IPAddress &address);

  // Setup Wifi
void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

/*-------- NTP code ----------*/
// ====================================

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
  IPAddress ntpServerIP; // NTP server's ip address

  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  // get a random server from the pool
  WiFi.hostByName(ntpServerName, ntpServerIP);
  Serial.print(ntpServerName);
  Serial.print(": ");
  Serial.println(ntpServerIP);
  sendNTPpacket(ntpServerIP);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12] = 49;
  packetBuffer[13] = 0x4E;
  packetBuffer[14] = 49;
  packetBuffer[15] = 52;
  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}

// NEO PIXELS
// ====================================

// Setup
#define PIN 0
#define NUMPIXELS 224

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int individualPixels[NUMPIXELS];

// Time variables
int hs;
int m;
int s;

// For Loops
int x;

// RGB color variables
int red;
int green;
int blue;

void colorBlue(){
  red = 0;
  green = 0;
  blue = 100;
}

/* IN LOOP Light pixels corresponding to current time */
void neoPixler(){
  for (x=0; x<sizeof(individualPixels); x++){
    if (individualPixels[x]==1){
      pixels.setPixelColor(x, pixels.Color(red,green,blue)); //Set Neopixel color
    }
    else{
      pixels.setPixelColor(x,pixels.Color(0,0,0));
    }
  }
  pixels.show(); //Display Neopixel color
}

// ALL OFF
void turnOff(){
  for(x=0; x<pixels.numPixels(); x++) {
    individualPixels[x]=0;
    pixels.show();
  }
}

//Numbers
void dl_one(){
  individualPixels[160]=1;
  individualPixels[161]=1;
  individualPixels[146]=1;
  individualPixels[147]=1;
  individualPixels[116]=1;
  individualPixels[117]=1;
  individualPixels[102]=1;
  individualPixels[103]=1;
  individualPixels[72]=1;
  individualPixels[73]=1;
  individualPixels[58]=1;
  individualPixels[59]=1;
  individualPixels[28]=1;
  individualPixels[29]=1;
  individualPixels[148]=1;
  individualPixels[149]=1;
  individualPixels[112]=1;
  individualPixels[113]=1;
}
void dr_one(){
  individualPixels[172]=1;
  individualPixels[173]=1;
  individualPixels[134]=1;
  individualPixels[135]=1;
  individualPixels[128]=1;
  individualPixels[129]=1;
  individualPixels[90]=1;
  individualPixels[91]=1;
  individualPixels[84]=1;
  individualPixels[85]=1;
  individualPixels[46]=1;
  individualPixels[47]=1;
  individualPixels[40]=1;
  individualPixels[41]=1;
  individualPixels[136]=1;
  individualPixels[137]=1;
  individualPixels[124]=1;
  individualPixels[125]=1;
}
void dl_two(){
  individualPixels[152]=1;
  individualPixels[153]=1;
  individualPixels[156]=1;
  individualPixels[157]=1;
  individualPixels[158]=1;
  individualPixels[159]=1;
  individualPixels[160]=1;
  individualPixels[161]=1;
  individualPixels[144]=1;
  individualPixels[145]=1;
  individualPixels[118]=1;
  individualPixels[119]=1;
  individualPixels[104]=1;
  individualPixels[105]=1;
  individualPixels[102]=1;
  individualPixels[103]=1;
  individualPixels[68]=1;
  individualPixels[69]=1;
  individualPixels[64]=1;
  individualPixels[65]=1;
  individualPixels[22]=1;
  individualPixels[23]=1;
  individualPixels[24]=1;
  individualPixels[25]=1;
  individualPixels[26]=1;
  individualPixels[27]=1;
  individualPixels[28]=1;
  individualPixels[29]=1;
  individualPixels[30]=1;
  individualPixels[31]=1;
}
void dr_two(){
  individualPixels[34]=1;
  individualPixels[35]=1;
  individualPixels[36]=1;
  individualPixels[37]=1;
  individualPixels[38]=1;
  individualPixels[39]=1;
  individualPixels[40]=1;
  individualPixels[41]=1;
  individualPixels[42]=1;
  individualPixels[43]=1;
  individualPixels[52]=1;
  individualPixels[53]=1;
  individualPixels[80]=1;
  individualPixels[81]=1;
  individualPixels[92]=1;
  individualPixels[93]=1;
  individualPixels[90]=1;
  individualPixels[91]=1;
  individualPixels[132]=1;
  individualPixels[133]=1;
  individualPixels[130]=1;
  individualPixels[131]=1;
  individualPixels[168]=1;
  individualPixels[169]=1;
  individualPixels[170]=1;
  individualPixels[171]=1;
  individualPixels[172]=1;
  individualPixels[173]=1;
  individualPixels[140]=1;
  individualPixels[141]=1;
}

[......]

// Seconds
// ====================================
void print_numbers(byte num){
  byte num10;
  byte num1;
  num1=num%10;
  num10=(num-num1)/10;
  switch (num10){     //10...
  case 0:
    dl_null();
    break;
  case 1:
    dl_one();
    break;
  case 2:
    dl_two();
    break;
  case 3:
    dl_three();
    break;
  case 4:
    dl_four();
    break;
  case 5:
    dl_five();
    break;
  }
  switch (num1){      //1...
  case 0:
    dr_null();
    break;
  case 1:
    dr_one();
    break;
  case 2:
    dr_two();
    break;
  case 3:
    dr_three();
    break;
  case 4:
    dr_four();
    break;
  case 5:
    dr_five();
    break;
  case 6:
    dr_six();
    break;
  case 7:
    dr_seven();
    break;
  case 8:
    dr_eight();
    break;
  case 9:
    dr_nine();
    break;
  }

}
void seconds(){
/* Get current time */
s=second();
turnOff();
print_numbers(s);
neoPixler();      // Lights
}

void setup() {

  // Debug info
  Serial.begin(115200);
  Serial.println(F("Booting"));

  setup_wifi();

  // Setup UDP Time + Sync Time
  Serial.println("Starting UDP");
  Udp.begin(localPort);
  Serial.print("Local port: ");
  Serial.println(Udp.localPort());
  Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);
  setSyncInterval(3000);

/* NEO PIXELS ------------------------------------------------------------------------------------------------------*/
  colorBlue(); //Standard Color
  pixels.begin(); //Begin Neopixel string
  pixels.show(); // Initialize all pixels to 'off'
}

void loop() {
  seconds();
}

```

# Answer
It's likely the problems are in your code somewhere; but not enough information is available to say for sure.

---

Your first step toward debugging the problem probably should be taking any ESP-12e issues out of the mix. At the beginning of `getNtpTime()` temporarily add something like `return 1477897101UL + millis()/1000;` to get a sync-time that advances at the correct rate and is repeatable for testing. If the display suddenly begins updating smoothly, look for problems in your time code, else in the display code.

---

The technique of duplicating a whole bunch of `individualPixels[116]=1;` lines (with different pixel numbers) is crude, tedious, verbose, error-prone, inflexible, etc. You might instead create some arrays and use a loop to set pixel data. For example:

```
const byte L1[] = {160, 161, 146, 147, 116, 117, 102, 103, 72, 73, 58, 59, 28, 29, 148,
  149, 112, 113, 0};
...
const byte R2[] = {34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 52, 53, 80, 81, 92, 93, 90,
  91, 132, 133, 130, 131, 168, 169, 170, 171, 172, 173, 140, 141, 0};

void loadDigit(byte *pixelList) {
  for (byte j=0; pixelList[j]; ++j)
    individualPixels[pixelList[j]] = 1;
}
...
   loadDigit(L1);  // Write a left 1
...
   loadDigit(R2);  // Write a right 2

```

---

You could also create an array of addresses of number-data arrays, to get rid of the crude, tedious (etc.) switch/case statements in `print_numbers()`. For example:

```
const byte *digitsL[] = {L0, L1, L2, L3, L4, L5, L6, L7, L8, L9};
const byte *digitsR[] = {R0, R1, R2, R3, R4, R5, R6, R7, R8, R9};
...
if (num>9)
  loadDigit(digitsL[num/10]);  // Write tens digit
loadDigit(digitsR[num%10]);    // Write units digit

```

---

If your matrix is logically organized, all of the 1's in R0 are at constant offsets from the 1's in L0 (for example, 12 more), and similarly for other digits. If that's the case, you could modify `loadDigit()` to take a second parameter, `offset`, which indicates where to place the digit in the matrix, ie, tells `loadDigit()` how much to add via a statement like `individualPixels[offset+pixelList[j]] = 1;`. Then you could leave out the `R0 ... R9` arrays (and `digitsR[]` as well) and use code like the following:

```
...
if (num>9)
  loadDigit(digitsL[num/10], 0);  // Write tens digit at left
loadDigit(digitsL[num%10], 12);   // Write units digit at right

```

---

A drawback to using `const byte` arrays like `L0 ... L9` and `R0 ... R9` is that when your program starts they get copied from PROGMEM into RAM for access. It would make sense to declare them in PROGMEM, and use them directly from PROGMEM by appropriate changes. \[*Edit:* See example program, below\]

---

Note, a string of 224 WS2812B units takes about 6.7 ms to update: 224 units x 24 bits x 1.25 μs/bit. Each time you update your matrix of lights, the `millis()` counter, `timer0_millis`, will lose 5 or 6 ms because `pixels.show()` runs with interrupts turned off. To compensate, you could add 5 to `timer0_millis` after each update. To make the loss always be 5 ms instead of sometimes 5 and sometimes 6, add the following code just before `pixels.show()`: `unsigned long now=millis(); while (now==millis());`, which will stall until the end of the current millisecond. To see how to change `timer0_millis`, see the “**Better Alternative**” section of my answer to “How to keep accurate millis() while using ADC\_sleep mode?”.

---

I'd remove the `pixels.show()` call from `turnOff()` because you will (I think) always be calling `pixels.show()` shortly after that, after loading number images, to turn on a bunch of other pixels. That is, clear the array, fill the necessary 1's, then show, without a show between clearing and filling.

---

Following is an example program that illustrates storing a constant array of bytes in PROGMEM, and accessing its entries via `pgm_read_byte()` calls.

```
// Sketch that accepts a number k via serial input, and responds with
// the k-th set of numbers from among some sets of numbers stored in
// PROGMEM.  This avoids copying the array data into RAM.  jiw 31 Oct 2016

#include <Streaming.h>  // Ref: http://arduiniana.org/libraries/streaming/

// Set up datatext in PROGMEM
const byte L1[] PROGMEM = { 102, 103, 112, 113, 116, 117, 146, 147, 148,
                149, 160, 161, 28, 29, 58, 59, 72, 73, 0};

const byte R1[] PROGMEM = { 124, 125, 128, 129, 134, 135, 136, 137, 172,
                173, 40, 41, 46, 47, 84, 85, 90, 91, 0};

const byte L2[] PROGMEM = { 152, 153, 156, 157, 158, 159, 160, 161, 144,
                145, 118, 119, 104, 105, 102, 103, 68, 69, 64,
                65, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 0};

const byte R2[] PROGMEM = { 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 52,
                53, 80, 81, 92, 93, 90, 91, 132, 133, 130,
                131, 168, 169, 170, 171, 172, 173, 140, 141, 0};
const  void* Addrs[] = { L1, R1, L2, R2 };
enum { nAddrs = sizeof Addrs / sizeof Addrs[0] };

void prompt() {
  Serial << endl << "Please enter item number from 1 to " << _DEC(nAddrs) << ": ";
}

void setup() {
  Serial.begin(115200);         // init serial port
  prompt();         // Issue initial prompt
}

void loop() {
  char c, d;
  while (Serial.available()) { // Get characters
    c = Serial.read();
    if (c >= '0' && c <= '9') {
      Serial << c << endl;  // Echo the entered digit
      d = c - '0' - 1;
      if (d>=0 && d < nAddrs) {
        byte k=0, t = pgm_read_byte(Addrs[d]);
        Serial << "Set #" << _DEC(d+1) << ": ";
        while (t) {
          Serial << _HEX(t) << ' ';
          t = pgm_read_byte(++k + Addrs[d]);
        }
        Serial << endl;
      }
      prompt();         // Issue prompt after any digit
    }
  }
}

```
> 1 votes

# Answer
NTP is a protocol implemented over UDP which is a connectionless protocol. If packets are lost then neither the client nor the server will be aware of their loss. So on top of everything else that might be wrong your data source may also be injecting additional errors. You should take the time from a timer on the board and update it from NTP when you receive data.
> 0 votes

# Answer
When I'm trying it like this I get the error:

```
invalid conversion from 'const byte* {aka const unsigned char*}' to 'byte* {aka unsigned char*}' [-fpermissive]

```

---

```
    #include <ESP8266WiFi.h> //WiFi
    #include <Adafruit_NeoPixel.h> //LEDs

    // 1
    const byte L1[] = {160, 161, 146, 147, 116, 117, 102, 103, 72, 73, 58, 59, 28, 29, 148,  149, 112, 113, 0};
    const byte R1[] = {172, 173, 134, 135, 128, 129, 90, 91, 84, 85, 46, 47, 40, 41, 136, 137, 124, 125, 0};
...
    const byte *digitsL[] = {L0, L1, L2, L3, L4, L5, L6, L7, L8, L9};
    const byte *digitsR[] = {R0, R1, R2, R3, R4, R5, R6, R7, R8, R9};

    void loadDigit(byte *pixelList) {
      for (byte j=0; pixelList[j]; ++j)
        individualPixels[pixelList[j]] = 1;
    }

    void print_numbers(byte num){
      if (num>9){
        loadDigit(digitsL[num/10]); // Write tens digit
      }
      else {
      loadDigit(digitsR[num%10]);  // Write units digit
      }
    }

    void seconds(){
    turnOff();
    print_numbers(byte second());
    //print_numbers(second());
    neoPixler();
    }

```

**EDIT:** It works when I add "const" to the loadDigit

```
    //0
    const byte L0[] = {156, 157, 158, 159, 160, 161, 152, 153, 110, 111, 108, 109, 66, 67, 64, 65, 144, 145, 118, 119, 100, 101, 74, 75, 56, 57, 24, 25, 26, 27, 28, 29, 0};
    const byte R0[] = {168, 169, 170, 171, 172, 173, 140, 141, 122, 123, 96, 97, 78, 79, 52, 53, 132, 133, 130, 131, 88, 89, 86, 87, 44, 45, 36, 37, 38, 39, 40, 41, 0};
    //1
    const byte L1[] = {160, 161, 146, 147, 116, 117, 102, 103, 72, 73, 58, 59, 28, 29, 148,  149, 112, 113, 0};
    const byte R1[] = {172, 173, 134, 135, 128, 129, 90, 91, 84, 85, 46, 47, 40, 41, 136, 137, 124, 125, 0};

  void loadDigit(const byte *pixelList) {
      for (byte j=0; pixelList[j]; ++j)
        individualPixels[pixelList[j]] = 1;
    }
    void print_numbers(byte num){
      if (num>9){
        loadDigit(digitsL[num/10]);
        loadDigit(digitsR[num%10]);
        }
      else {
        loadDigit(digitsR[num%10]);
      }
    }
    void seconds(){
      s=second();
      turnOff();
      print_numbers(s);
      neoPixler();
    }

```
> 0 votes

---
Tags: esp8266, rgb-led, nodemcu
---


title: int VS uint8_t VS uint16_t

text:
# Question
Title: int VS uint8_t VS uint16_t
This question is quite clear. What are the differences between an `int`, an `uint8_t`, and an `uint16_t`. I know it has to do with bytes and memory but can someone clarify me a bit?

Things I want to know:

1- How much memory does each take.

2- When to use what.

3- In the end of the day, are they that different?

# Answer
You can decipher most of them yourself.

* A `u` prefix means `unsigned`.
* The number is the number of bits used. There's 8 bits to the byte.
* The `_t` means it's a `typedef`.

So a `uint8_t` is an unsigned 8 bit value, so it takes 1 byte. A `uint16_t` is an unsigned 16 bit value, so it takes 2 bytes (16/8 = 2)

The only fuzzy one is `int`. That is "a signed integer value at the native size for the compiler". On an 8-bit system like the ATMega chips that is 16 bits, so 2 bytes. On 32-bit systems, like the ARM based Due, it's 32 bits, so 4 bytes. Of the three it is the only one that changes.

Personally I rarely use `int` and always use `uint8_t` etc., since the variable type is the same no matter what architecture you compile for. When you use `int` you can run into problems if you had a program that worked fine on a 32-bit ARM but then doesn't work right on an 8-bit ATMega, since the `int` can only store a fraction of the range of numbers on the 8-bit system compared to the 32-bit system.
> 13 votes

---
Tags: memory-usage, variables, memory
---


# Question
Title: How to keep track of if data is outdated
I have a large set of data and it is refreshed every 30 seconds or so. However, not all data is refreshed every time. It is possible that no new data for a particular calculation isn't received for even a few hours. For this reason I need to track what data is possibly outdated, but hasn't been updated (maybe due to technical malfunctions or a sensor is down). I was thinking about creating an additional (large) 2d array to do this, and increment some sort of counter. This way if a particular spot is at `1000` this means it is old. When new data is received it can be reset to `0`. However, this seems like a slow, ineffective way to do this. How could I keep track of data more efficiently?

# Answer
> 1 votes
OK, so you have three possible states for your values:

1. No valid data (-1, or 0xFFFF in 16-bit 2's complement)
2. Valid data (0 to 1000, or 0x0000 to 0x03EB in 16-bit)
3. Valid but "old" data.

If you first check for invalid data before thinking about "old" data (invalid data is never considered "old") then you just have two states:

1. Valid data (0 to 1000, or 0x0000 to 0x03EB in 16-bit)
2. Valid but "old" data.

As you can see the highest 6 bits of the stored value aren't used at all except for storing -1 for invalid data (hence checking for that first). So you could utilize those 6 bits to store all sorts of things. In 6 bits you can store the values 0 to 63. That could be the number of seconds since the last time you got some data.

By masking and shifting you can separate out the two values:

```
val = data[x] & 0x3FF;
sec = data[x] >> 10;

```

Every second add one to the seconds count of each and every data entry that is less than (say) 60.

```
val = data[x] & 0x3FF;
sec = data[x] >> 10;
if (sec < 60) sec++;
data[x] = val | (sec << 10);

```

Now each entry in your array knows how old it is (up to 1 minute), and if it's older than a certain threshold (30 seconds? 45 seconds? you choose) then you consider it "old" and display it as such.

You can make it easier to program by using a union/struct combination:

```
typedef union {
    int16_t rawval;
    struct {
        unsigned value:10;
        unsigned seconds:6;
    } __attribute__((packed));
} data_t __attribute__((packed));

```

If your data array is now made up of that type instead of integers:

```
data_t data[500];

```

you can now access:

* data\[x\].rawval as the raw 16 bit signed value (to look for -1).
* data\[x\].value as the unsigned 10 bit value from 0 to 1000.
* data\[x\].seconds as the unsigned 6 bit value from 0 to 63.

Updating the seconds then becomes as simple as:

```
if (data[x].seconds < 60) data[x].seconds++;

```

When you store a new value using

```
data[x].rawval = sensor.getValue();

```

the seconds is automatically overwritten with 0 which resets the count for you.

And both methods give you data ageing without using a single byte more memory.

# Answer
> 0 votes
Rather than frequently updating a time flag for each data item, you can store a “generation number” for each item. Maintain a “current generation number” `currentGen` and at intervals add one to it. If the interval at which you increment `currentGen` is 20 seconds and you store 16-bit generation numbers, rollover will occur about every 15 days. \[20\*2¹⁶/3600/24 = 15.17 days.\]

For example, suppose your data structure has fields for item.value and item.gen. Whenever you store a new value into item.value, copy `currentGen` into item.gen. Later, to tell the age of an item, use `unsigned int` arithmetic to subtract item.gen from `currentGen`. For example, if `currentGen` is 23453, an element with item.gen = 17487 is about 33 hours old.

Note, if item age ever exceeds 15.17 days, it will wrap around to zero. It that's a concern, either use a larger datatype for item.gen, or update `currentGen` less frequently, for example every two minutes for a 90-day wraparound or every 8 minutes for a 364-day wraparound time.

---
Tags: xbee, array
---


# Question
Title: Wake Arduino (Atmega328) from sleep with ADXL345 interrupt
So I'm relatively new to microcontrollers, and I'm having a problem implementing a feature I want for a project.

I've learned about putting an Atmega328P to sleep from this tutorial. I'm using an Arduino Nano, so I only get my current down to ~9mA rather than the µAs the tutor is getting. Nonetheless, it demonstrates the abstraction I want to learn for when I move to just the Atmega328 with no board.

I've learned to wake up my microcontroller from sleep with a falling external interrupt on INT0/D2 from a simple button. My ISR is empty and just boots me back to the loop, which is fine. As an aside, I have heard that it is better to have simple and short ISR's, but I am not completely sure why.

My question is, can I use my ADXL345 to trigger an interrupt that wakes my Arduino? I am semi-familiar with using an ADXL345 over I2C, although I don't understand why my Sparkfun ADXL345 requires different wiring than my unbranded one, but that's for a separate question I suppose.

So my question is, is it possible, and if so, how? Also, is the I2C connection meaningful for an ADXL345 that is primarily being used as a wake-up interrupt on the Z-axis only? (My use case is an item someone picks up, which wakes my embedded circuit out of sleep and begins logging load cell and UWB sensor data, and is put back to sleep after a period of inactivity).

Thanks in advance - I appreciate any and all help!

# Answer
When using an ADXL345 to trigger an interrupt to wake an Arduino, I2C (or SPI) need not be relevant. Instead, you can just connect pin 8 or 9 (INT1, INT2) of the ADXL345 directly to the Arduino pin that wakes the Arduino. Note, INT1 and INT2 in this answer refer to pins 8 and 9 of the ADXL345.

On the ADXL345, map the wake-up event (or events) to whichever of INT1 or INT2 (pin 8 or 9 on the ADXL345) you've connected to the Arduino. By sending commands from the Arduino to the ADXL345, you can map multiple events to INT1 and INT2 on the ADXL345, and might have both of them connected to different pins on the Arduino for different purposes.

As noted on page 20 of the Analog Devices ADXL345.pdf Rev. E datasheet,

> The default configuration of the interrupt pins is active high. This can be changed to active low by setting the INT\_INVERT bit in the DATA\_FORMAT (Address 0x31) register.
>
> How do I toggle bits in an ADXL345?

You can use SPI or I2C to set up registers on the ADXL345. You will need to configure the unit before it does anything, because it powers up into standby mode. See the second paragraph of **POWER SEQUENCING**, page 13 in spec sheet, and see Table 6 on that same page:

> At power-up, the device is in standby mode, awaiting a command to enter measurement mode, and all sensor functions are off. After the device is instructed to enter measurement mode, all sensor functions are available.
> 0 votes

---
Tags: interrupt, atmega328, accelerometer, sleep
---


title: How to automate an electric kettle?

text:
# Question
Title: How to automate an electric kettle?
I have this tea kettle, which requires pressing two buttons one after the other ("on" and "prog") to start.

I'd like to automate that action (tying it to Tasker on my phone), and am wondering what's my simplest/cheapest option. My communication options are either WiFi or Z-Wave/ZigBee.

I'm assuming Arduino Uno Wifi is an option, but that seems like a huge overkill given how simple what I want to do is. Are there any other simpler/cheaper tools that I could use to do this?

# Answer
You could use lots of options to control it from Mbed boards to the Uno with a wifi shield, to a raspberry pi to .... the list goes on. But if it were me I would use the something like the ESP8266 which cost less than $10 usd and can be programmed with the arduino IDE (I'm assuming that is useful given the community this was posted in). There are also lots of tutorials available online for this kind of thing.

To trigger the button you have two options: a non-destructive one and a destructive one. For the non destructive one, use something like a solenoid in a custom mount or a servo and small lever arm to push the button. The benefit to this is that if you change your mind you just have to move the device and you still have a perfect unharmed kettle. Plus, you can still use it if your device breaks or malfunctions.

For the destructive option, open up the kettle to get at the buttons or button pads and solder a wire to each side. If you're lucky you can do this so that it can still be put back together and the original button still work. One option is to use a relay to connect them. You can use a small solid state relay or a larger coil relay; both would be under a couple of dollars and not large enough to be too obtrusive. Using a relay is nice since you don't have to worry about which voltages are being used on which side of the button and it isolates the microcontroller from the kettle better. (Actually some relays are polarized so if it doesn't work, switch the wires and try again). Another option is to use an optoisolator like this one. It is polarized so if it doesn't work switch the wires. Another option is to use a mosfet. I believe it will work if you get an N channel mosfet with a Vgs (gate to source voltage) less than 3.3V. Hook up the Source pin to the more negative of the two button leads and the Drain to the other. Hook up the gate to a pin on the micorcontroller. Also, you should put a resister between the gate and the source pins.
> 2 votes

# Answer
Replace your button with a relay and use a microcontroller to switch it.

It will be cheaper to use an ESP6266, which could be programmed with the Arduino IDE and the same Arduino code works on it. It will be perfect as it has got just 2 GPIO ports and it will just be the size of your thumb.
> 2 votes

# Answer
**This is simply a suggestion. It is not in your list of communication protocol that you listed but this could work great.**

A good and reliable way is to use an GSM shield with and Arduino. The GSM shield could receive a text such as "on" or "off" and could interpret those messages to control your kettle.

To emulate the switches, you can use 2 MOSFET. They act like an electronic in the sense that when you apply 5V (PNP transistor), it lets current pass and will cut the current flow when there is no voltage applied to it.

NOTE: GSM modules are quite cheap if you know where to get them. I recommended getting a chinese version because they usualy work fine for me and there price is way lower.
> 1 votes

---
Tags: arduino-uno
---


title: NRF24L01+ unable to receive data

text:
# Question
Title: NRF24L01+ unable to receive data
I have 2 Arduino UNO R3 nodes communicating using NRF24L01+ transceivers with the TMRh20 library.

**Setup** I have original as well as cheaper but 'compatible' arduinos. One of the nodes uses an original arduino Uno whereas the other uses the cheaper one.

**Observation**

1. The node with the cheaper Uno can transmit data (sucessfully received by the other node) but is unable to receive data. I have a number of Rf modules and UNo boards. The observation is similar across.
2. Using the same configuration (rf module, connection and code) , the original uno board receives data but noot the other types.
3. Another thing that i observed is that the cheaper uno comes with a 12MHz oscillator on the board whereas the original one has a 16 Mhz one.Can it be the source of problem?

This article mentions something that I could not get but am suspicious of it being a possible direction to the solution to the problem, only if someone could help.

> On Arduino UNO boards SPI pins are connected with some digital pins. While using modem you most remember that these digital pins won't be available.

# Answer
> 0 votes
As it turns out, the culprit was the power supply on the board.

The clone came with AMS1117 based regulator for the 3.3V which it did indeed generate (3.27 measured). Using it, the reception of the RF device failed (although it could transmit data). Also had 10uF and a 0.1uF capacitor hooked up in parallel to Vdd and Gnd of the NRF24L01+, as recommended. I therefore suspected something to do with the SPI configuration.

Finally, having powered the 3.3V to the Rf device from another genuine Arduino solved the problem. Not sure if it was the 3.3V rail from the clone possibly having excessive noise which may be causing the issue, as I did not see a reasonable drop in 3.3V output of the clone while in operation.

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


# Question
Title: Print when echo is read by HR-S04 sensor
I'm trying to see when an echo is received by my HR-S04 sensor. I have a Serial.println within my while loop to read the signal and see once a change happens to break the loop.

The issue is my serial just prints out the pin my echo to linked to. How can I set it so that the serial output is LOW and then HIGH once an echo is received?

```
int trig1 = 3; //Trig 1
int echo1 = 4; //echo1
int ECHO1;
double pingTime1;

void setup()
{
  Serial.begin(9600);
   pinMode(trig1, OUTPUT);  //sets the digital pin 3 as output
   pinMode(echo1, INPUT);  //sets the digital pin 5 as input
}

void loop()
{
  ECHO1 = digitalRead(echo1); //assume echo1 is LOW and HIGH once echo is received

  while (ECHO1 == 0) //continuous loop until echo is HIGH
  {
    digitalWrite(trig1,LOW);
    delay(100);
    digitalWrite(trig1,HIGH);
    Serial.println(echo1); //Troubleshooting to see when pulse is read by sensor
   ECHO1 = digitalRead(echo1);
  }
  pingTime1 = pulseIn(echo1, HIGH); //Measure ping travel time in microseconds
  pingTime1 = pingTime1*1000; //convert microseconds to seconds

}

```

# Answer
> 1 votes
To start with, you code isn't suppose to work. Here is a working code to start with (code below). You have a lot of mistakes so I suggest comparing your code to this one. Also, don't try to debug by adding a `Serial.print(/*something*/);` in your code.

For the time the echo is received is way too fast (under 0,001 seconds). I doupt you can use that for something useful. There is a way to calculate that using the `millis()` function, but it is quite complex for your project.

Here is a working code for the HC-SR04:

```
const int trigPin = 2;
const int echoPin = 3;

long duration, distance;

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  Serial.begin(9600);
}

void loop() {

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;

  if (distance < 150) {
    Serial.print(distance);
    Serial.println("  cm");
  }
  if (distance > 150) {
    Serial.println("OUT OF RANGE");
  }
  delay(20);
}

```

# Answer
> 0 votes
A couple things:

1) I believe your code for the trigger pin is wrong. An example I found sets it up as LOW for 2 microseconds, then HIGH for 10 microseconds, then LOW. (Note that the units are MICROseconds so you must use delayMicroseconds()

2) digitalRead(echo1) does nothing. Use the pingTime1 instead. You will always be receiving an 'echo' so it's not a HIGH or LOW but rather a changing variable stored as pingTime1.

3) echo1 is the variable for the pin. That's why Serial.println(echo1) prints the pin number. You could try Serial.println(ECHO1) but I don't think it will work because of what I said above.

4) If you want a HIGH or LOW to print to screen you must set a cutoff value for pingTime1 then use an if statement to print the appropriate value.

I'm not sure what exactly you're trying to do, but given the points above I do not believe a while loop is necessary.

Try this code. You can keep the first Serial.println() to see the duration of the pulse and/or you can keep the if statement if you want a HIGH or LOW to print to screen.

```
// Send a pulse out through trig pin
digitalWrite(trig1,LOW);
delayMicroseconds(2);
digitalWrite(trig1,HIGH);
delayMicroseconds(10);

//Receive pulse through echo pin
pingTime1=pulseIn(echo1, HIGH);
pingTime1=pingTime1*1000;

// Serial print
Serial.println(pingTime1);

//Serial print (for HIGH or LOW)
if (pingTime1 > cutoff) {
    Serial.println('HIGH');
}
else {
    Serial.println('LOW');

```

---
Tags: serial, sensors, code-review
---


# Question
Title: How can the Arduino check if it is connected to a PC and the PC is on?
I have been searching around the Internet to find if there is a way to check whether an Arduino is connected to a PC or not.

For example: if my PC is turned on, the Arduino will listen to any serial commands it receives, BUT if my PC is turned off, the Arduino will receive some random characters.

How can the Arduino check if it is connected to PC and the PC is on?

# Answer
> 2 votes
As suggested by Paul & Gerben, you could check the 5V USB line to see if it has a voltage or not.

I am assuming from your question that the Arduino is not powered from the USB line. I am also assuming that the USB port is not powered when the PC is turned off.

All you have to do is connect VUSB to a digital input through a resistor like so:

---

Alternatively, you could have the computer send a pre-determined message telling the Arduino that its alive.

If the Arduino receives this message then it lights up the LED on pin 13. If the Arduino hasn't received the "I'm alive" message for a while (ie. a timeout) it then turns off the LED.

A simple PC program could be written to automate this task.

# Answer
> -1 votes
jumper reset -\> ground and rx -\> tx (with power disconnected) connect power, open serial monitor in arduino ide and type anything in and input. if the serial monitor echoes what you typed in, then your connection is good and you should look elsewhere for problems.

Found this solution on the arduino.cc community site.

---
Tags: serial, arduino-nano, sketch
---


title: Inconsistent response AT command

text:
# Question
Title: Inconsistent response AT command
I'm building a vehicle tracker with Arduino shield with Waveshare SIM 808. I am communicating with the Arduino via AT commands, and came across the following problem: The method "leserial ()" returns me the result of the command missing characters

Response `+CGNSINF: 1,1,20161101222934.000,-23.285230,-51.20`

Expected response `+CGNSINF: 1,1,20161101223215.000,-23.285222,-51.204778,623.000,0.02,142.3,1,,1.2,2.5,2.2,,8,7,,,38,,`

Code:

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

String inputString = "";
char inChar;

const int powerkey =  5;
const int statuspin = 6;

void setup() {
  Serial.begin(9600);
  mySerial.begin(9600);
  pinMode(powerkey, OUTPUT);
  pinMode(statuspin, INPUT);

  mySerial.println("AT");
  delay(2000);
  leserial();

  //TURN ON GPS
  mySerial.println("AT+ CGNSPWR =1");
  delay(2000);
  leserial();
}

void loop() {
  //GET LOCATION
  mySerial.println("AT+CGNSINF");
  delay(4000);
  leserial();
  delay(5000);
}

void leserial(){
  inputString = "";
  while (mySerial.available()>0){
    inChar = mySerial.read();
    inputString += inChar;
  }
  Serial.println(inputString);
}

```

# Answer
I managed to solve the problem, I edited the file "SoftwareSerial.h" and changed the size stated in constant `_SS_MAX_RX_BUFF.`

```
#define _SS_MAX_RX_BUFF 64 // RX buffer size

to:

#define _SS_MAX_RX_BUFF 128 // RX buffer size

```

I reached the conclusion that when I realized that the number of bytes returned in the function "mySerial.avaliable ()" was no more than 63 bytes. I appreciate the support of all.
> 1 votes

# Answer
Basically you're sending a command that gives a response, then waiting 2 seconds for that response to arrive (which is completely the wrong thing to do to start with).

You have to ask yourself: where does that response go when it does arrive, while it's waiting for you to finally get around to reading it?

The answer is: into a small internal buffer that is considerably smaller than the response.

Thus most of the response just gets thrown away because there isn't room for it.

Instead you should most definitely NOT delay for 2 seconds waiting for the response, and instead keep looking to see if there are any characters to read up until you reach the end of the line.

It's all explained here: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/
> 2 votes

---
Tags: serial, c
---


# Question
Title: How to add toggle button for LCD display text and backlight?
I have set up a BMP180 and a DHT11 to display data on an HD44780 20x4 LCD.

I want to be able to toggle the altitude from meters to feet, the temperature from Celsius to Fahrenheit, and the pressure from absolute to sea level pressure using a tactile push button.

Here is the software code I have:

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

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

#include <SFE_BMP180.h>
#include<dht.h>
dht DHT;

#define DHT11_PIN 8 // Second pin, leave 3rd pin unconnected 4th is ground
#include <SFE_BMP180.h>
#include <Wire.h>

// You will need to create an SFE_BMP180 object, here called "pressure":

SFE_BMP180 pressure;

#define ALTITUDE 237.0 // Altitude of Phillaur in Punjab, India. in meters

void setup() {
  lcd.begin(20, 4);
  lcd.setCursor(0, 0); // Zeroth Row
  lcd.print("hello, world!");
  lcd.clear();
  int chk = DHT.read11(DHT11_PIN);
  // Initialize the sensor (it is important to get calibration values stored on the device).
  if (pressure.begin()) {
    lcd.print("BMP180 init Success");
    delay(300);
  } else {
    lcd.print("BMP180 init fail");
    while (1); // Pause forever.
  }
}

void loop() {
  char status;
  double T, P, p0, a;
  lcd.clear();
  lcd.setCursor(0,0);
  //TODO Display in Feet as well using toggle
  lcd.print("Altitude: ");
  lcd.print(ALTITUDE, 0);
  lcd.print(" mtrs ");
  status = pressure.startTemperature();
  if (status != 0) {
    // Wait for the measurement to complete:
    delay(status);
    status = pressure.getTemperature(T);
    if (status != 0) {
      // Print out the measurement:
      Serial.print("temperature in deg C, From BMP180: ");
      lcd.setCursor(0, 1);
      lcd.print("Tmpratre: ");
      lcd.print(T, 2);
      lcd.print("'C");
      lcd.setCursor(0, 2);
      lcd.print("Humidity: ");
      lcd.print(DHT.humidity, 1);
      lcd.print("%");
      status = pressure.startPressure(3);
      if (status != 0) {
        // Wait for the measurement to complete:
        delay(status);
        status = pressure.getPressure(P, T);
        if (status != 0) {
          lcd.setCursor(0,3);
          // Print out the measurement:
          lcd.print("Pressure: ");
          lcd.print(P * 0.0295333727, 2);
          lcd.print(" mb");
          p0 = pressure.sealevel(P, ALTITUDE);
          // we're at 234 meters (Phillaur, Pb)
          // TODO: toggle to sea level to absolute pressure
          Serial.print("relative (sea-level) pressure: ");
          Serial.print(p0, 2);
          Serial.print(" mb, ");
          Serial.print(p0 * 0.0295333727, 2);
          Serial.println(" inHg");
          a = pressure.altitude(P, p0);
          Serial.print("computed altitude: ");
          Serial.print(a, 0);
          Serial.print(" meters, ");
          Serial.print(a * 3.28084, 0);
          Serial.println(" feet");
        } else Serial.println("error retrieving pressure measurement\n");
      } else Serial.println("error starting pressure measurement\n");
    } else Serial.println("error retrieving temperature measurement\n");
  } else Serial.println("error starting temperature measurement\n");
  delay(5000);  // Pause for 5 seconds.
}

```

# Answer
> 2 votes
You need to connect the button(s) to available digital inputs of the Arduino. I suggest that you use more than one button based on your description in the question.

The following tutorial describes the circuit needed and the associated code to read that input. All you have to do is duplicate it with a few more buttons on separate (available) digital inputs.

Arduino button tutorial

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


# Question
Title: Do I use an Arduino or an ARM based Launchpad board for my commercial project?
I want to use a board for an Industrial Project, which is based on temperature sensing, sharing and data storage.

Which board do I use? Will it be reliable for a long span of time? Will it be foolproof?

# Answer
Adding to Candice the Cyborg's answer above. Which board do I use? Since its a commericial project you are going to sell then -I would say the right answer is the cheapest ARM or Arduino based board (when migrated to breadboard) to make your project. Will it be reliable for a long span of time? For reliability ARM and arduino would be reliable-they are after all both professional engineering products-and both can be used to make commercial products. I am assuming can be sure that your software for the ARM or Arduino is not buggy and professional-thus there is no reliability issues from the software. The span of time that the arduino can retain information reliably is given in the data sheet-I think its about 100 years.
Will it be foolproof? Yes if you can be sure that you get the hardware design correct and the software correct-I would imagine this is where a problem would probably come from for your device.
> 1 votes

# Answer
If you are want to be professional, make a custom PCB. This lets your project be neither and also stronger. This also makes you look like you actually spent more time on the project and make it great for industries.

If you still want to use an Arduino based board, you might as well use an Teensy 3.2. They are small, powerful and are still at a low price. Buy it here.

If you make a good case for your project, it could last quite a long time. It might even last many years of continuous run outside at unregulated temperatures. Just make sure it doesn't get in contact with water or high levels of humidity and you should be good.
> 0 votes

---
Tags: arduino-mega, sensors, arduino-ide, hardware, temperature-sensor
---


# Question
Title: Change Digispark clock speed, run at low voltage?
I have a low voltage (3.2v) application. I was hoping to use the Digispark. I have a solution using a separate Tiny85, but want to use the Digispark USB programming.

To run at lower voltage I think you need the lower clock rate. I have done this using the standalone Tiny85. I could hook up the Digispark to the programmer direct and change the frequency fuses, however...

I assume reducing the clock rate by programming the fuses would break the Digispark boot loader as it would have the wrong timing. Correct?

Can I dynamically switch the clock frequency in my code after the bootloader or is it fuse controlled only?

Is the bootloader available and could I change it to a lower frequency? Would there be a lot of work changing the code to a different freq? Would it be powerful enough to run the USB bootloader?

# Answer
> 3 votes
You can set the clock prescaler at run time. For example:

```
#include <avr/power.h>

void setup()
{
    clock_prescale_set(clock_div_8);
    // etc...
}

```

More details in the documentation from avr-libc.

Note that with this method your Digispark will still be overclocked when booting, so it might not be 100% reliable. But it will be overclocked only for a very short time.

# Answer
> 2 votes
The digispark uses the micronucleus bootloader.

You can flash that directly onto an Tiny85 without needing the digispark module. So your existing Tiny85 solution could acquire the USB bootloader if you can spare the 2k program space for the bootloader.

I realize this is not a direct answer to your question, but you did note that you have a Tiny85 solution and wanted USB bootloader support on it.

# Answer
> 0 votes
Maximum safe frequency at 3.2V is around 12.7Mhz. See figure 20-2 in the datasheet.

This is indeed lower than the 16MHz the digispark is running at.

---
Tags: attiny, frequency, oscillator-clock, fuses, digispark
---


title: Arduino ESP8266 Webserver

text:
# Question
Title: Arduino ESP8266 Webserver
What I would like to do is control my garden lights using the ESP8266. For this I use the Arduino approach from here. This works great, I use bootstrap and jquery even :D all is well!

Switching lights on and off using my code is fine but now I'd like to switch some continues routines, like blinking. I can start the blinking from the webpage but this code is a loop so I cannot get back to turn it off again.

I could make it blink for a set amount of loops, so eventually it will stop blinking and show the control webpage again. Or I can add the blinking to the hardware, maybe use a 555 for the first time?
But there might be a better way of implementing this..

Using Google I found information about Break and Interrupts, not yet what I am looking for.

```
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char *ssid = "mynetwork";
const char *password = "mypassword";

ESP8266WebServer server ( 80 );

const int led = 5;
String webPage =
"<!DOCTYPE html>\
<html lang='en'>\
<head>\
  <title>Funny Bunny Control</title>\
  <meta charset='utf-8'>\
  <meta name='viewport' content='width=device-width, initial-scale=1'>\
  <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>\
  <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>\
  <script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>\
</head>\
<body>\
<div class='container-fluid'>\
  <div class='page-header'>\
    <h1>Funny Bunny v0.1</h1>\
  </div>\
  <p class='bg-info'>Omdat snuffelen er bij hoort.</p>\
  <p class='bg-warning'>Niet voeren aub.</p>\
  <div class='row'>\
    <div class='col-sm-4'><a href='/aan' class='btn btn-info btn-block' role='button'>aan</a></div>\
    <div class='col-sm-4'><a href='/uit' class='btn btn-warning btn-block' role='button'>uit</a></div>\
  </div>\
</div>\
</body>\
</html>";

void handleRoot() {
  server.send(200, "text/html", webPage);
}

void aan() {
  digitalWrite ( led, 1 );
  server.send(200, "text/html", webPage);
}

void uit() {
  digitalWrite ( led, 0 );
  server.send(200, "text/html", webPage);
}

void setup ( void ) {
  pinMode ( led, OUTPUT );
  digitalWrite ( led, 0 );
  Serial.begin ( 115200 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );

  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( "esp8266" ) ) {
    Serial.println ( "MDNS responder started" );
  }

  server.on ( "/", handleRoot );
  server.on ( "/aan", aan );
  server.on ( "/uit", uit );
  server.onNotFound ( handleRoot );
  server.begin();
  Serial.println ( "HTTP server started" );
}

void loop ( void ) {
  server.handleClient();
}

```

# Answer
> 1 votes
Take a look at the SimpleTimer \[http://playground.arduino.cc/Code/SimpleTimer\] library in the Arduino IDE environment.

You can have timers to:

* call a function at a consistent interval,
* call a function once after a set delay,
* call a function a set number of times with a consistent interval between.

---
Tags: arduino-ide, esp8266, wifi
---


# Question
Title: FIFO overflow - reading IMU MPU6090 and GPS uBlox NEO-6M at once
I am trying to read data from uBlox NEO-6m (I need just speed, just part of the code):

```
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

static const int RXPin = 7, TXPin = 4;
static const uint32_t GPSBaud = 9600;

float gps_speed = 0;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup(){
ss.begin(GPSBaud);
}

void loop(){
if (ss.available())
    {
      gps.encode(ss.read());
      gps_speed = gps.speed.kmph();

    }
}

```

And in the same time I read data from MPU6090 using this code (gps code is integrated in it):

http://nevit.blogspot.de/2014/07/arduino-mpu-6050-pitch-roll-with-2.html

When I try to read data separately it works but together it stuck every second (probably reading of gps data) and MPU6050 serial monitor sending FIFO overflow error ..

I tried to lower MPU data rate to 20Hz from 100Hz but it didn't work. I use Arduino UNO.

I am not so much skilled.. Any idea? Is it even possible to do it like this?

# Answer
> When I try to read data separately it works, but together it stuck every second (probably reading of gps data) and MPU6050 serial monitor sending FIFO overflow error .

Yes, you have to be careful about the loop structure and "blocking" to "wait" for a new GPS speed report. SoftwareSerial also blocks everything else during each received character time.

Just check for GPS characters and update the speed if a complete sentence was received, then do "other things" (e.g., use the IMU data). Here is a NeoGPS version of your example:

```
#include "NMEAGPS.h"
#include <NeoSWSerial.h>

static const int RXPin = 7, TXPin = 4;
static const uint32_t GPSBaud = 9600;

float gps_speed = 0;

NMEAGPS gps;

// The serial connection to the GPS device
NeoSWSerial ss(RXPin, TXPin);

void setup(){
  Serial.begin( 9600 );
  ss.begin(GPSBaud);
}

void loop(){

  // Read GPS characters and see if a new fix is available
  if (gps.available( ss )) {
    gps_fix fix = gps.read();

    //  A fix is available once per second, but the GPS may not know
    //  the speed value, perhaps because the satellite reception is
    //  poor or the unit is just starting.  Check the valid flag.

    if (fix.valid.speed) {

      // Update the gps_speed.  Other parts of your
      //   program can use it whenever they want.
      gps_speed = fix.speed_kph();
      Serial.println( gps_speed );
    }
  }

}

```

NeoGPS is smaller and faster than other libraries and can be configured to only parse the fields you really use.

Your original sketch uses 6884 bytes program space and 349 bytes of RAM.
The NeoGPS version can be as small as 4802 bytes program space and 150 bytes of RAM. Significant savings!

For the software serial library, I would suggest using AltSoftSerial on pins 8 & 9, if you can move the GPS. It is much more efficient, and does not disable interrupts for long periods of time: SoftwareSerial will block for ~1ms, and eternity for a 16MHz Arduino. This is probably interfering with the IMU interrupts.

If you can't move the GPS to pins 8 & 9, you might try another library I maintain, NeoSWSerial. It is much more efficient than SoftwareSerial, and it works on any two pins. NeoSWSerial will "play nicer" with the IMU interrupt code, but it can still be affected if the IMU interrupt code takes too long. NeoSWSerial should not affect the IMU interrupt code. I used it in the above sketch, along with a debug print.
> 2 votes

# Answer
A guess; Software serial is known for messing with interrupts, in fact I think the rule of thumb is do not use interrupts and software serial.

The MPU code you are using is classic Jeff Rowberg, and uses interrupts.

To be honest, there are things you can do, where an occasional overflow does not cause problems, but that is way too deep to explain here, sorry.

In my case I think I will end up using the arduino to handle the MPU, and attaching it and a GPS to a raspberry pi, and let it merge the two. You might be able to accomplish something similar with a bigger Arduino if there is one with 2 (or more) uart serial ports, but I do not have experience with that.

If you can speed up the GPS serial rate, give that a try, it actually helps (which is counter intuitive).
> 0 votes

# Answer
Here is answer for you.

GPS keeps on sending data and fill the mcu input buffer . Use listen function and read one software serial at once ..

If you use listen then only one serial port will work at a time and you can swap accordingly .

I was having same problem and It solved my problem

Just open a dummy serial port and when ever you need gps then listen to GPS serial port and do listen to dummy after GPS reading .
> 0 votes

---
Tags: arduino-uno, gps, mpu6050
---


title: Good Arduino motor drivers

text:
# Question
Title: Good Arduino motor drivers
I need some motor drivers that can control a DC motor with 10-15 A and 25 V. I can't find any shield that can do the job. I need to control 4 motors with these.

Can you suggest some models that are good with this?

And one more question: if a driver can control a DC motor in 2 directions, can it control 2 DC motors in one direction each?

# Answer
We don't really answer "shopping questions".
You could contact several suppliers like Adafruit, sparkfun or maybe even Digikey, Farnell etc (ebay?).

If you search for: "15A dual h-bridge" you will find some motor drivers which should work for you.

**If a driver can control a dc motor in 2 directions can it control 2 dc motors in one direction each?**

Where are you going to use them for? If you're only going in one direction, you won't need a motor driver.

An MOSFET (per motor) is good enough if you only drive one direction. If you want both motors to be able to turn each direction, a dual h-bridge will do.
> 1 votes

# Answer
I think that the current you need is high and you are not likely to get a shield that does that. Look at a H-bridge with the desired current and voltage rating, it will probable be largish with a heat sink. If the motors are going one way then you may just need a simple mosfet style driver. You should probably look for a module with the correct rating as it will have the correct heat sink, track sizes, connections for your motor power and will probably have a diode to protect stuff from the induction spikes. The H bridge will probably be fine with the Arduino output and it may have a voltage reg for its logic that you could use to power the Arduino.
> 0 votes

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


title: Using two software serial - two UART

text:
# Question
Title: Using two software serial - two UART
I have ATMega328p chip, and I have HC-06 on pin A5, A4 (RX, TX) and I have another device on pin 10, 9 (RX,TX).

I want to be able to send some command on BT via Bluetooth Terminal and pass raw (exact) command to that device unchanged just to log on my computer (on my serial monitor) incoming command from BT and to log the response from device the same way on serial monitor and pass unmodified to HC-06.

How can I do that?

I tried by using "listen()" method but sometimes I get some weird character while I'm transferring\reading data, so not sure how to do this.

All baud rates are 9600.

# Answer
You can have high-speed debugging by utilizing either I2C or SPI to send to a second Arduino. That second Arduino can be devoted to receiving debugging information and passing it on (via serial to your PC).

I describe the process here.

The general idea is to add some stuff to the DuT (device under test) to output via SPI/I2C.

Example code:

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

#include <SPI.h>

// conditional debugging
#if DEBUG

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

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

  // an instance of the SPIdebug object
  tSPIdebug SPIdebug;

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

long counter;
unsigned long start;

void setup() {
  start = micros ();

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

}  // end of setup

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

void loop()
{

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

}  // end of loop

```

The other Arduino (which receives the debugging information) simply echoes it to Serial:

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

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

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

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

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

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

}  // end of setup

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

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

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

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

}  // end of interrupt routine SPI_STC_vect

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

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

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

}  // end of loop

```

---

SPI is quite fast, so the overhead of doing the debugging should be slight. The receiving end can batch up the debugging information (up to a point which is about 1000 characters) and then send it to your PC via Serial.

---

I made a library out of the relevant code. The library is available from:

http://gammon.com.au/Arduino/SPI\_Debugging.zip

Example using the library:

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

#include <SPI.h>
#include <SPI_Debugging.h>

long counter;
unsigned long start;

void setup() {
  start = micros ();

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

}  // end of setup

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

void loop()
{

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

}  // end of loop

```

---

There is a similar library for I2C debugging:

http://gammon.com.au/Arduino/I2C\_Debugging.zip

Example of doing I2C debugging:

```
// make true to debug, false to not
#define DEBUG true
const byte SLAVE_ADDRESS = 100;  // which address debugging goes to

#include <Wire.h>
#include <I2C_Debugging.h>

long counter;
unsigned long start;

void setup() {
  start = micros ();

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

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

void loop()
{

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

}  // end of loop

```

---

All of the examples illustrate using a `#define` to turn the debugging output on or off, so you can leave the debugging prints there in case things go wrong, but with debugging disabled they won't have any penalty.
> 2 votes

# Answer
> How can I do that?

You can't.

It is impossible to use two SoftwareSerial ports together. Simply because while you are writing to one port everything else stops. Interrupts are disabled, and receiving requires interrupts. So anything that arrives while you are sending will either be lost or corrupted.

The only solution is to use a board with multiple hardware UARTs like the Mega or any of the more powerful alternatives to Arduino such as chipKIT or Teensy.
> 0 votes

---
Tags: arduino-uno, bluetooth, atmega328, softwareserial, uart
---


# Question
Title: Arduino Pro Mini name in CMakeList.txt in CLion
I recently try to get my Arduino Pro Mini (5v 16mhz)running in Clion.

I tried to set up the CMakeList.txt but I get the following error:

> Error:Can not find f\_cpu in boards.txt for Arduino board ID (pro), aborting.

I used the following configuration:

```
set(${CMAKE_PROJECT_NAME}_BOARD pro)

```

In the boards text, located at C:\Program Files (x86)\Arduino\hardware\arduino\avr\boards.txt I found the following lines:

```
pro.name=Arduino Pro or Pro Mini

pro.upload.tool=avrdude
pro.upload.protocol=arduino

pro.bootloader.tool=avrdude
pro.bootloader.unlock_bits=0x3F
pro.bootloader.lock_bits=0x0F

pro.build.board=AVR_PRO
pro.build.core=arduino
pro.build.variant=eightanaloginputs

## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
## -------------------------------------------------
pro.menu.cpu.16MHzatmega328=ATmega328 (5V, 16 MHz)

pro.menu.cpu.16MHzatmega328.upload.maximum_size=30720
pro.menu.cpu.16MHzatmega328.upload.maximum_data_size=2048
pro.menu.cpu.16MHzatmega328.upload.speed=57600

pro.menu.cpu.16MHzatmega328.bootloader.low_fuses=0xFF
pro.menu.cpu.16MHzatmega328.bootloader.high_fuses=0xDA
pro.menu.cpu.16MHzatmega328.bootloader.extended_fuses=0x05
pro.menu.cpu.16MHzatmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

pro.menu.cpu.16MHzatmega328.build.mcu=atmega328p
pro.menu.cpu.16MHzatmega328.build.f_cpu=16000000L

```

So I'm wondering what Boardname to use, to get the Pro Mini working. Thanks in advance!

# Answer
> 1 votes
The problem here is that the Pro Mini comes in a number of variants for different voltages / speeds etc. The different variants are selected using a menu in the IDE.

CLion doesn't know about those menus, nor how to find the f\_cpu from the right one for your board.

So there are two solutions:

1. Create your own board entry for the Pro Mini without the menu entries.
2. Use an earlier version of the IDE that has the Pro Mini boards as separate entries (basically any version before the menu system was created).

If you want the latest API then you will have to go route 1. That could be as simple as modifying the existing `pro.*` entries to remove the menu and replace that section with just the flags that are set by the correct menu (basically remove all the `pro.menu.*` entries except the ones for your board, then remove the `menu.cpu.<whatever>.` from each of the lines, as well as the entire menu entry name line.)

So you would basically change these lines:

```
## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
## -------------------------------------------------
pro.menu.cpu.16MHzatmega328=ATmega328 (5V, 16 MHz)

pro.menu.cpu.16MHzatmega328.upload.maximum_size=30720
pro.menu.cpu.16MHzatmega328.upload.maximum_data_size=2048
pro.menu.cpu.16MHzatmega328.upload.speed=57600

pro.menu.cpu.16MHzatmega328.bootloader.low_fuses=0xFF
pro.menu.cpu.16MHzatmega328.bootloader.high_fuses=0xDA
pro.menu.cpu.16MHzatmega328.bootloader.extended_fuses=0x05
pro.menu.cpu.16MHzatmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

pro.menu.cpu.16MHzatmega328.build.mcu=atmega328p
pro.menu.cpu.16MHzatmega328.build.f_cpu=16000000L

```

to this:

```
## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
## -------------------------------------------------
pro.upload.maximum_size=30720
pro.upload.maximum_data_size=2048
pro.upload.speed=57600

pro.bootloader.low_fuses=0xFF
pro.bootloader.high_fuses=0xDA
pro.bootloader.extended_fuses=0x05
pro.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

pro.build.mcu=atmega328p
pro.build.f_cpu=16000000L

```

and delete all the other `pro.menu` entries.

---
Tags: arduino-pro-mini, ide
---


# Question
Title: Trouble reading LM35 with long (?) Ethernet connection
I have a quick question to ask. I have an Arduino Uno reading 4 temperature sensors (LM35) in 4 different rooms. What happens is that the two nearest rooms give stable values, while the two further ones give very unstable measurements (the temperature keeps floating +-30C around the real values.)

I have connected all the sensors with Ethernet cables with the longest one being about 8-10m.

Is this problem due to noise picked up along the line? There are no strong electromagnetic sources along the way. I have also measured the voltage values on Arduino end with a multimeter: the values are all stable (and correct) and do not reflect the behaviour detected by Arduino.

Also, I have tried to substitute the LM35 in the farthest room with a photoresistor (the one in the starter kit) and this time the values read by Arduino are perfectly stable. I know that the LM35 works because I have tested it on a breadboard.

Can someone give my some help? Any idea is greatly appreciated.

Edit: I am adding a sketch, although it is a very basic setup: The only difference with the real layout is that there is also a Ethernet shield.

# Answer
> 1 votes
The LM35 has trouble driving any kind of capacitive load, so the long runs of cable are generally not a great idea if you are relying on a voltage signal. The datasheet for it (The one I have is from the Texas Instruments website), has a few strategies to reduce this problem somewhat.

The approach that I have used successfully, is to use a current signal, rather than a voltage signal. This has the advantage that you only need a two wire twisted pair cable (I made my own twisted pairs - it is easy for relatively short runs).

The idea is that you connect the LM35 output to the ground pin with a known resistor value (the datasheet example has a 200 Ohm resistor). Since the voltage is 10mv per degree, the current wil be 10/R mA per degree. There will be an additional small current from the LM35 device itself, but this is small, and almost constant. Then connect the supply and ground to one end of your twisted pair.

At the other end, it is necassary to convert the current signal back to a voltage so that your Arduino can read it. Simply put a resistor (again, 200 Ohms is that used in the datasheet example) between the low side of the twisted pair to OV, the high side connected to 5V, and measure the voltage across this resistor.

Figure 17 in the TI datasheet is the one to follow.

Other things that help to get more stable, acurate readings;

Choose a time to take readings when you are not running anything else that might interfere (wireless comms, ultrasonic sensors, motors, solenoids, etc).

Take several readings. Ignore the first two.

Take the median value of the remaining readings (eg take 5 readings, ignore the first two, and sort the others in order. Then take the middle value.).

Hope this helps.

# Answer
> 0 votes
**Short answer**

Add `delay` between each reading, 100ms should be enough.

**Long answer**

The LM35 is an analog device and you are using the internal ATmega328 ADC to read the voltage on the signal pin. The way the Arduino ADC works is a sample-and-hold process:

1. open a circuit to an internal capacitor
2. charge the capacitor
3. disconnect the circuit
4. compare capacitor to the reference voltage

Because there is only one of such circuits shared among all the 6 analog pins you need to let the capacitor charge up, which is much slower on long lines having a non negligible resistance and also a non negligible capacitance.

Also other wires and power lines near to your ethernet cable are going to influence your readings, but in that case the ethernet cable shielding is going to help you, if properly used.

---
Tags: arduino-uno, ethernet, temperature-sensor
---


# Question
Title: SD-Card-Module doesnt work with external power supply
## Problem description

I am trying to build a datalogger with an Arduino UNO. I have connected a SD card module to the Arduino. I have planned to catch the measurement data from the analog input pins. Everything works fine if connected to the usb port. But if I run the Arduino over an external power supply, the `SD.open`-method fails (It simply returns false). The problem occurs even, if I connect the external power supply additional to the USB connection. So the problem can't be a missing serial connection.

Note that the problem only occurs, if `SD.open` is in WRITE-mode. (`File dataFile = SD.open("datalog.txt", FILE_WRITE);`)

## What I've already tried:

* running the SD-card example code, which is included in the SD card library.
* trying different types of file-system formattings (FAT, FAT32, with different cluster-sizes)
* powering the sd-card reader with 3.3V instead of 5V

## Arduino wiring

Look at the pictures to check if there are some mistakes with the wiring:

## Specifications of the power supply

And here are the specifications of the power supply:

* **Manufacturer:** MyVolts
* **Model:** DD282MU
* **Input:** 100-240V (AC) - 50-60 Hz
* **Output:** 9V, 1A (DC)

---

I hope you can help me with my problem. And of course, I hope there is a solution for the problem at all. Thank you.

# Answer
Okay, thank you all for your efforts.

Finally, after changing the PSU and connecting the Arduino to another usb-port without operating system, I found the solution.

The problem was the SD-Card itself: I swapped the SD-card with a newer (maybe more expensive(?)) one and it just works now. No matter if you connect the Arduino with the PSU or over an usb connection. My assumption is, that there could be a different clock speed of the sd-card module on different voltages, which causes the problem. The old sd-card can't handle the fast speed and runs into an error (or just rejects it) on a write attempt...

Anyway, thank you again for your efforts!
> 2 votes

# Answer
I had this problem too, SD card not initiliasing on external power.
Having read this I turned down my external power voltage to 5.1 V (from 7.5V ish) and suddenly my SD card initialises on external power. So a 'solid' 5 V must have the SPI running at a higher speed ( I guess) make sense. The drawback is TFT is not as bright as should be. ... better get a more 'expensive' SD card module LOL.

Ps - After some testing I had found that the SD card would work up to 6.4V on the power jack, above that the card would not initialise. BTW I am not convinced it is a speed issue only because the SPI speed is locked by a divider to the Mega clock, so the Mega clock needs to change first.

Hope this helps
> 0 votes

---
Tags: arduino-uno, power, sd-card
---


# Question
Title: clkI/O 256 & 1024 (From prescaler) not working with driving PWM on Nano board
I've been working with PWM in TIMER0 of my nano board.

So, it's working now and I know how to set OCR0A or OCR0B.

Then, I went to play with Clock Select Bits CS02 CS01 CS00 in TCCR0B.

0, 8 and 64 prescaler configurations worked as I also don't see the effect on the LED fade speed.

But the more problem I get is that 256 and 1024 prescaler don't work at all and the LED goes on all the time.

What is the problem?

The code:

```
void setup() {
    DDRD |= (1<<DDD6);
    TCCR0A |= 0xC1;
    TCCR0B |= 0x00; // this works for 0x01, 0x02, 0x03 only
    }

    void loop() {
    uint8_t i;
    for (i=0;i<256;i++)
    {
      OCR0A = i;
      _delay_ms(1);
    }
    }

```

regards,

# Answer
The main problem is the prescaler on `Timer0` is already configured to divide clock source by `64` `CS01` and `CS00` are set `(0b00000011)`.

And you are using bitwise OR to "change" prescaler: `TCCR0B |= 0x05;` or `TCCR0B |= 0x04;`. But this'll result into the clock source `7` `(0b00000111)` \- clock source is expected on `T0` input counting on rising edge.
> 0 votes

---
Tags: arduino-uno, led, arduino-nano, pwm, rgb-led
---


title: Problem fetching data from MPU6050

text:
# Question
Title: Problem fetching data from MPU6050
I am new to Arduino. I have an arduino mega board, which I need to interface with MPU6050 accelerometer-gyroscope module.

My connections are

Arduino\_SCL-\>MPU6050\_SCL;

Arduino\_SDA-\>MPU6050\_SDA;

Arduino\_GND-\>MPU6050\_GND;

Arduino\_5 V-\>MPU6050\_Vcc;

Arduino\_Pin 2-\>MPU6050\_INT;

I have uploaded the following code to the arduino mega.

```
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"

MPU6050 accelgyro;

int16_t ax, ay, az, gx, gy, gz;
double  time;
int i;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  accelgyro.initialize();
  time = millis();
  i = 1;
}

void loop()
{
  // collect readings
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  // print result
  Serial.print(i);   Serial.print("\n");
  Serial.print(ax);   Serial.print("\t");
  Serial.print(ay);   Serial.print("\t");
  Serial.print(az);   Serial.print("\t\n");
  Serial.print(gx);   Serial.print("\t");
  Serial.print(gy);   Serial.print("\t");
  Serial.print(gz);   Serial.print("\t\n");

  i = i + 1;
  delay(1000);
}

```

My problem is when I observe the reading on serial monitor, it shows every reading as zero. Does this mean my sensor is damaged or there's some problem with my connection? Or is my code for fetching the data incorrect?

Thanks

# Answer
If you are using the MPU6050 library from jrowberg/i2cdevlib, the library does not have any kind of error handling, so it is unfortunately not easy to guess what went wrong, or even *if* something went wrong. If the getMotion6 function fails, it will simply copy corrupt data into your return values and it is not possible after the invocation to tell if the function succeeded and you got a valid reading, or if the function failed and you only got garbage back.

One possible problem is that the MPU6050 can be configured to use one of two I²C addresses (0x68 or 0x69) and you are using the default address, as implemented in the MPU6050 library (0x68). It might be worth to try the other address, in case your module is configured that way:

`MPU6050 accelgyro(0x69);`
> 1 votes

---
Tags: arduino-mega, mpu6050
---


# Question
Title: How to send multiple data from PC to arduino
I have a project in arduino that i interface with java. The arduino is connected to the computer via usb cable , I use the serial communication. I have two variables:

```
//Code in arduino
int ADelay = 1000;
int BDelay = 1000;

```

I want to change the value of each variable based on the input of the user using the java interface. Is there a code that let the arduino identify that this data:

```
2000

```

Is intended to or for:

```
int ADelay

```

and this

```
300

```

is for

```
int BDelay

```

My only idea on how to achieve this is to add A or B before the number before i send to arduino

```
A2000
B300

```

And use Delimeter in arduino to split the data and use if else condition to decide where the data belong , Is there any other way ? Thanks

# Answer
The approach noted in the question – having an identifying character at the front of each number – is a workable approach. Other approaches include:
• always sending numbers in pairs, eg `2000,300` would denote `A2000 B300`.
• encoding the A or B as part of the number; eg, the range 0-4999 could denote A delays of 0 to 4999, while the range 5000-9999 could denote B delays of 0 to 4999.
• sending A delays via decimal digits, and B delays via letter-substitutes for digits; eg DAA could encode a B delay of 300.

One of the easiest-to-parse approaches is to have an identifying character at the end of each number, rather than at the front. This allows your code to pick up digits until a letter appears, and then dispatch based on the letter. Here's some example code:

```
// Sketch that accepts numbers and action code via serial input.
// Silently ignores any numbers not followed by a valid action letter.
// Does not test for number overflow.      - jiw 3 Nov 2016

void setup() {
  Serial.begin(115200);         // init serial port
}

unsigned int val=0;
void loop() {
  char inc;
  while (Serial.available()) { // Get characters
    inc = Serial.read();
    if (inc >= '0' && inc <= '9') {
      val = 10*val + (inc-'0');
    } else {
      switch (toupper(inc)) {
      case 'A':
        Serial.print("Case A got ");
        Serial.println(val);
        break;
      case 'B':
        Serial.print("Case B got ");
        Serial.println(val);
        break;
      default :
        ; // handle blanks, returns, etc
      }
      val = 0;  // Set val to zero after any non-digit
    }
  }
}

```

---

*Edit 2:* This edit incorporates some code suggestions from comments into the answer.

---

If you need to know whether a number for val1 has been specified -- that is, if you handle items like `500B` as well as `300,500B` -- you can set/test/clear a flag:

```
...
case ',':
  val1=val; v1flag=1;
  break;
...
case 'B':
  if (!v1flag) val1=val1default;
  Serial.print("B stuff with val and val1");
  v1flag=0;
  break;
...

```

---

To retain when the power is off, you can write a `recordData()` function, that when called will write selected data to EEPROM if the value has changed. In `setup()`, load data from where you stored it. For data validation, you can store in the cell after a value *v* its complement, *~v*. If when you reload data it fails the validation test, use a default value instead, and write it to EEPROM for future use.

---

The code snippet shown next, from kaisarGreat's 8 May comment, has several problems to be corrected:

```
case a :
  WATEREQFORN1 = val;
  EEPROM.put(0, WATEREQFORN1);
case b :
  WATEREQFORN2 = val;
  EEPROM.put(1, WATEREQFORN2);
case d :
  DELAY = val;
  EEPROM.put(3, DELAY);

```

Logic or syntax problem: Missing `break` statements at ends of cases. This error will allow execution to flow from one case into the next. While there are situations where that's useful, this is not one.

Logic or syntax problem: Unless `a`, `b`, ... are declared constants they won't work as case designators. Perhaps use `'A'`, `'B'`, ... instead.

Style problem: Variable names in all upper case. Conventionally, C and C++ programmers use all-upper-case names to designate defined constants or macros. Contravening that convention can lead to confusion if other people use or maintain the code. Instead of `WATEREQFORN1` consider `waterEq1`.

Allocation problem: Presumably the `WATEREQ...` variables are multiple bytes in length. `EEPROM.get()` and `put()` read and write data types with multiple bytes using several consecutive bytes of EEPROM. For example, if `WATEREQFORN1` is a real and takes 4 bytes, it will occupy cells 0, 1, 2, 3 in EEPROM.

The following code snippet fixes some of those problems.

```
enum { WaterAddr1=0, WaterAddr2=WaterAddr1+sizeof waterEq1, DelayAddr=WaterAddr2+sizeof waterEq2 };
...
case 'A':
  waterEq1 = val;
  EEPROM.put(WaterAddr1, waterEq1);
  break;
case 'B':
  waterEq2 = val;
  EEPROM.put(WaterAddr2, waterEq2);
  break;
case 'D':
  Delay = val;
  EEPROM.put(DelayAddr, Delay);
  break;
  ...

```
> 0 votes

# Answer
If you are just looking to send something as simple as 2 integers, your approach should be fine, you just need to set your own protocol to encode the data from java and decode it on the arduino side.

Another easy way would be to set a starting byte, could be anything like 0x6A etc, (with optional checksum if it's through bluetooth or other noisy communication method):

```
[8 bit starting byte][32 bit integer data A][32 bit integer data B]

```

On the arduino side you want to keep polling for the starting byte, once you receive the special byte then the next 32 bits would be your data A and the following 32 bits would be your data B.

However if you want something more robust or object oriented you could look into this library: https://github.com/bblanchon/ArduinoJson

It allows you to decode and encode JSON objects which is very flexible and widely accepted, so you just need to encode the data into a JSON object on the java side and decode it using that library.
> 0 votes

---
Tags: java
---


title: Amplify Piezo Sensor

text:
# Question
Title: Amplify Piezo Sensor
I am trying to amplify a piezo sensor per the instructions found at the link below. I am not trying to trigger a buzzer only print to the serial monitor whether the vibration was detected or not. I am a NOOB with respect to circuits and unable to understand why my circuit is not working.

The piezo is either giving a positive (sensing) reading or giving a negative (not sensing) reading depending on where the poteniometer is set. There is no state where-if all is quiet-the piezo is quite and if there is a vibration the piezo senses it and reports to the serial monitor. I see from the blog that if the piezo get stuck on a state to lower the feedback resistor of the op-amp from 220k to 160k but again, there is never a case where it is working then get struck in state. It is always stuck in a state!

The blog post mentions a 0.1uf capacitor in the hand-drawn sketch but the Fritzing diagram shows a 10uf capacitor. I am using the 10uf capacitor. Will switching out the 10uf for a 0.1uf capacitor test potentially damage the Arduino? Is this the cause of the +-state of the piezo? Do I just have a wiring flaw? Any advice is appreciated.

Here is a link to the post including the Fritzing diagram. http://davidhoulding.blogspot.com/2014/02/high-sensitivity-vibration-sensor-using.html

Here is a picture of my circuit.

And the Sketch...

```
#define VIBRATION_DIGITAL_IN_PIN 8
int DurationMillis = 1000;

void setup()
{
  Serial.begin(9600);
  pinMode(VIBRATION_DIGITAL_IN_PIN,INPUT);
}
void loop()
{
  if(digitalRead(VIBRATION_DIGITAL_IN_PIN)==HIGH)
  {
    Serial.println("I felt that");
    delay(DurationMillis);
  }
  else
  {
  Serial.println("I don't feel anything...");
  delay(DurationMillis);
  }
}

```

# Answer
> 2 votes
You write,

> The blog post mentions a 0.1uf capacitor in the hand-drawn sketch but the Fritzing diagram shows a 10uf capacitor. I am using the 10uf capacitor.

The Fritzing diagram in the high-sensitivity-vibration-sensor at davidhoulding.blogspot.com shows a 10μf capacitor connected from +5V to ground on the breadboard. This is a reasonable thing to do, to avoid power supply glitching on that board. It is ok to add an 0.1 μf capacitor in parallel (that is, in addition to, and connected to the same busses) to the 10μf if you want to suppress some noise as well.

The last diagram in the blog, an “updated circuit diagram showing the refinements for reducing the gain to avoid op-amp output lockup, and DC decoupler on the input”, also shows an 0.1 μf capacitor connected between the piezo node and the first op amp input. This will block any DC voltage coming out of the piezo from going into the op amp input. It's likely that any capacitor from 0.05 μf up to 0.5 μf will work just as well there. A smaller coupling capacitor is suitable for higher frequency inputs, and a larger one for lower frequencies. The presence or absence of that capacitor probably isn't the problem with your circuit. Looking at your circuit photo, the wiring looks ok\[\*\]. Perhaps try substituting a different piezo element, or a signal generator if you have one, or a low voltage from a pot varied up and down, to generate a signal into your op amp and comparator stages to see if they are working. If they aren't working, substitute for the LM358.

\[\*\] Although I can't see if the 220KΩ resistor goes to +5 or to pin 1. Also is your comparator output connected into digital pin 8 on the Uno? It looks more like 9 or 10 in the photo. Also, as a personal preference I'd attach the Arduino end of the ground wire to a pin next to the +5 instead of to the ground next to Aref.

---
Tags: arduino-uno, piezo, op-amp
---