title: Execute Code on power off?

text:
# Question
Title: Execute Code on power off?
Arduino newbie here.

I'm thinking about building an Arduino-based light switch to control the Philips Hue light system in my living room. I have standard wall light switches that power ceiling lamps, and I basically want all Hue lamps that are scattered around the room to be on when the switch is on, and off when the switch is off, so that I don't necessarily need the app or the Hue remote to turn the room's lights on.

My idea is to install an Arduino on the ceiling instead of a normal lamp, so that its power supply is switchable through the light switch.

I would configure it as a Hue remote control, e.g. with ArduinoHue; if all works well, this would control the Hue lamps directly via ZigBee or via WiFi through the bridge - in both cases without having to use additional wiring.

**Whenever it gets power, I would have it `turnOn()` all lamps, and whenever its power supply is turned off, I would have it `turnOff()` all lamps.** The first part seems simple to me, the second part - not so much.

So here's my question: **Can I execute code in the event of the Arduino losing power, i.e. turn off my Hue lights with its last energy before shutting down?** Is there maybe some hardware configuration that would allow me to detect the power off event and retain enough energy through a battery or capacitors to still run the code?

I have never worked with Arduino before, but I do have some colleagues that can help me out when there's trouble.

# Answer
You could do what you want as you describe it, but are making things harder for yourself that you need to. If you can access the circuit from the switch at or near the switch (which should be 'easy' in most cases) then your system does not have to be depowered when the lighting circuit is as you will have access to the mains AC voltage on either side of the switch.

If you do wish to depower the processor when the lights are turned off you can easily add either a backup battery or a capacitor that runs the processor for "long enough". You can also run a processor in "sleep" mode at extremely low power so that it is always running so have no 'wakeup time". And it is possible to power up a processor so that the delay is not noticeable for practical purposes.

However, as **Hue Bulbs** are Zigbee controlled, with provision ofr both iOS and Android control, you should be able to control them via Zigbee directly without any connection to their wiring.

---

Hue control

Hue specifications
> 2 votes

# Answer
For the capacitor part, two one Farad supercapacitors in series (each 2.7 volts max) cost about a dollar, and there is one 10 Farad cap for two dollars each. I guess that one of these options would work. And the supercaps should last a very long time. I'm not an Electrical Engineer -- just a Joule Thief hobbyist, but I thought this would contribute to your design and wouldn't cost much.

As far as balancing the supercaps, since we're close to the 2.7 volt max, I personally would just put three of the supercaps in series with a voltage divider of three 10K resistors in series tied in, but they would probably not really be necessary.

Oh, and the supercaps I spoke about are actually relatively small (10mm dia x 32mm high for each 10F, and 8mm dia. x 13.5 mm high for the 1F supercaps). Found the 1F at $1.03 as 1572-1270-ND on Digikey. The 10F was $1.97 each for 1572-1287-ND also on Digikey.
> 2 votes

---
Tags: power
---


# Question
Title: How do I connect Arduino to RS232 via USB?
I have a device that takes commands in the form of RS232 communication. I've connected the Arduino's USB port, through an adapter, to the device's 9-pin serial port, but no communication has happened.

The full chain of adapters is a printer cable (which would connect the Arduino to a computer), a female-to-female usb adapter, and a Sabrent USB to serial adapter.

I made sure the communication wasn't happening using the code `while (!Serial)` and blinked an LED in a certain pattern.

Is there something I'm missing? How do you get the devices to communicate?

# Answer
> 3 votes
This is effectively not workable. USB is not a peer-to-peer standard, but a host/device one. Both your Arduino and the USB-serial converter are intended to be devices, so they cannot communicate. While it would be *possible* to use another microcontroller acting as a host to bridge to serial that would be pointless, as the actually central problem of RS232 vs. logic level serial would still need to be solved.

Instead, what you want is an inverting serial level shifter - essentially a board with an IC like a MAX232 or one its many successors. You would either connect this to arbitrary digital pins of the Arduino and use a Software Serial instance, or decide that it is okay to block usage of the USB port by a computer while this is being operated, in which case you could connect it to the D0 & D1 pins used by the on-board USB interface (there are typically resistors in between the chips on the board to support this overriding).

Ironically, in a way what you want is one of the *original* Arduino boards that had a serial level shifter and 9-pin connector in place of the USB chip and USB connector of modern boards. But then, you probably want something with an ATMega328p rather than the earlier, more primitive ATmega chips used on the original boards. If you can still find a board of the original design, upgrading the chip may be an option, or it may be that your task is simple enough not to require it.

There have been many other non-Arduino embedded controller boards released with native RS232 ports as well, especially those dating from around a decade ago might give a good combination of fairly modern capability with not yet having abandoned RS232 in favor of USB.

# Answer
> 1 votes
Any network of USB devices involves a single **host** talking to many slave **devices**. The typical connection to program an Arduino board is, on the USB side:

```
PC (USB Host) <-> USB Cable <-> Arduino (USB Device)

```

On the Arduino board you have the serial side of this communication:

```
USB Serial Adapter <-> TTL serial lines <-> Microcontroller (RX/TX on D0/D1 pins)

```

The microcontroller itself has no idea that any USB communication is involved. The USB serial adapter functions as a device only, not a host, so plugging it into another USB device (though a cable with device connectors on both ends, rather than the usual host connector on one end) will not do anything.

(There are some Arduino boards, such as the Leonardo and the Micro, that use an ATmega32U4 microcontroller with a USB device interface built in. These work in substantially the same way as above except with the without the serial adapter and TTL serial link. The built-in USB interface also cannot be used as a USB host.)

### Arduino USB Host Shield

If you really want to use USB communication, SparkFun sells as USB Host Shield that you can add to a standard Arduino Uno or similar device. The library for it apparently supports USB serial, though you'd want to confirm that before buying the shield. This would leave the Arduino's USB/Serial interface used for programming free to remain hooked up when using the USB host shield, making development easier.

### Direct Serial Connection

A better method (IMHO) is to drop the USB stuff altogether and, as Chris Stratton describes in his answer, have the Arduino talk TTL serial directly to a level shifter (e.g., this breakout board or this shield) that is connected to your RS-232 device. I would go with communications on non-programming pins (i.e., not digital pins 0 or 1) using the SoftwareSerial library or the AltSoftSerial library. (You don't mention the speed of the link, but software serial is generally ok up to 57,600 bps and, depending on the device and what else you're doing, even 115,2000 bps.) This will let you use the serial link to the computer for debugging while running your application.

If you need to work at higher speeds or you just prefer to use a UART (hardware serial), you have two options:

1. Use the USART on digital pins 0 and 1, and be unable to talk to the computer while you're using it to communicate with your RS-232 device.
2. Use an Arduino board with more UARTs or USARTs on it, such as the Mega.

---
Tags: serial, usb, rs232
---


# Question
Title: Benchmarking String.toInt() vs Checking individual characters gives unexpected result
I'm trying to check whether the input string contains all digits or not. I achieved this using 2 different algos. One is to convert the string to integer using String.toInt() and then checking if its value lies between the integer of length of the input string.

e.g. If input string is "123". The corresponding integer must lie between 100-999.

Second, I wrote a function that iterates over each character of the string and checks if its ASCII values lies between 48-57. If not, it returns false.

When I bench marked these two algos, I found that when the string contains only digits, the 2nd algo is about 9 times faster than the 1st one. **But when the string contains even a single non-digit character, the 1st algo takes ~1ms, but the 2nd algo always takes ~5ms.** Why is this? I've not been able to figure this out.

The code:

```
unsigned long start;
unsigned long middle;
unsigned long end;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // send an intro:
  Serial.println("String toInt():");
  Serial.println();
}

void loop() {
  // Read serial input:
  if (Serial.available()) {
    String r = Serial.readString();

    start = micros();
    unsigned long rInt = r.toInt();
    int rLen = r.length();

    if ((rInt >= floor(pow(10, rLen))) || (rInt < floor(pow(10, rLen-1)))) {
      Serial.println("Please enter valid integer value!");
    } else {
      Serial.println(rInt+1);
    }

    middle = micros();

    bool isInt = doesContainInteger(r);
    if (isInt) {
      Serial.println(r);
    } else {
      Serial.println("Please enter valid integer value!");
    }

    end = micros();

    Serial.println(middle-start);
    Serial.println(end-middle);
  }
}

bool doesContainInteger(String s)
{
  int sLen = s.length();
  for (int i=0; i<sLen; i++) {
    char sChar = s.charAt(i);
    if (sChar<48 || sChar>57) {
      return false;
    }
  }
  return true;
}

```

# Answer
1 ms means easy calculation.

2 ms means more time spent in calculation.

5 ms means far more time in message printing to Serial buffer.

I calculated the error message passes serial line in 20-30 msec, so that is why I think there has to be a little bit faster buffer in between there.
> -1 votes

# Answer
As pointed out by Majenko in his (slightly annoyed) comment, you need to change your timing code to time only the calculations you want benchmark, not the I/O or other irrelevant code. For checking the conversion using `toInt()`, for example, try:

```
// time our conversion
unsigned long start = micros();
unsigned long rInt = r.toInt();
bool invalid = rInt == 0;
unsigned long end = micros();

// print the result
if (invalid) {
    Serial.print("in");
}
Serial.print("valid conversion took ");
Serial.print(end - start);
Serial.print(" microseconds.");

```

Note that your assumption that a three-character input that's a valid integer will be between 100 and 999 is wrong; `"003"` and `"-17"` are both three-character inputs that should be correctly converted.

According to the `toInt()` documentation, `0` is returned on failure to convert, so I check for that in the code above. But since one can't tell the difference between a successful conversion of `"0"` and unsuccessful conversion of `"abc"` or some other non-integer, you really should be sure *before* you call `toInt()` that you've got a valid integer int the string.
> 1 votes

---
Tags: serial, string
---


# Question
Title: Connect Arduino Uno to video camera's web Server via Ethernet (not working)
I work with cameras in the film and TV industry. A project I have just started tinkering around with is building an Arduino Uno-based box that would automatically collect the metadata (settings, etc.) via the camera's built-in web server (over Ethernet, at least at the moment). Specifically the Arri Alexa camera.

Like I said, this camera already has a web server and the functionality built in for somebody to hook their computer directly up to the camera with an Ethernet cord (it actually uses an RJ45 - Lemo proprietary cable system in order to support some accessories that draw more power than RJ45 is capable of). Then when you navigate to the camera's IP address in a web browser it serves up a web page to you with all the camera settings and other things displayed.

I found that my test computer connected perfectly to the camera without fiddling with any network settings as the manufacturer's documentation seemed to indicate. Here are the basic network settings my computer had when connected directly to the camera over ethernet (no Arduino yet):

Notice the IP Address and subnet mask: 169.254.106.46 and 255.255.0.0 respectively.

Just to note, these are the manufacturer recommended settings I found in some literature:

Since that was working I tested the Arduino using the same settings. I am using an Arduino Uno combined with a Seeed Ethernet Shield (v2.0) which utilizes a Wiznet 5200 processor (not the 5100 normally used). Because of this you have to use the Ethernetv2\_0 library that Seeed provides rather than the normal Ethernet library.

Here is my code, basically an adapted version of the WebClientRepeating example. I got this code working when I was just connecting to say arduino.cc and was going through the hub of my router (auto-assigned IP address). However when I attempt to connect to the camera with the Arduino sans Hub / Switch with a manually assigned IP address and subnet mask and all that I can never make the client (object) to connect. Basically this code is printing out "connection failed" to the serial monitor indicating and connection was never established.

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

// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};

// fill in an available IP address on your network here,
// for manual configuration:
//IPAddress ip(169, 254, 106, 46); //Address that worked on my computer
IPAddress ip(169, 254, 1, 2); //Manufacturer recommended address

// fill in your Domain Name Server address here:
IPAddress myDns(1, 1, 1, 1); //Random, not sure if I need to do anything specific here

// subnet mask that manufacturer recommends and what worked on my computer
IPAddress subnet(255, 255, 0, 0);

// initialize the library instance:
EthernetClient client;

//IPAddress server(64,131,82,241); //arduino.cc IPAddress
IPAddress server(169, 254, 184, 143); //Arri Alexa (Camera) IPAddress

unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

#define W5200_CS  10
#define SDCARD_CS 4

void setup() {
  // start serial port:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  pinMode(SDCARD_CS,OUTPUT);
  digitalWrite(SDCARD_CS,HIGH);//Deselect the SD card
  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns, subnet);
  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  if (client.available()) {
    char c = client.read();
    Serial.write(c);
  }
  // if ten seconds have passed since your last connection,
  // then connect again and send data:
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
  client.stop();
  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP GET request:
    client.println("GET /webremote/index.html HTTP/1.1");
    client.println("Host: 169.254.184.143");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();
    // note the time that the connection was made:
    lastConnectionTime = millis();
  } else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

```

I guess my question is, if I'm using the exact same network settings that worked for my computer connecting to the camera, why aren't they working for the Arduino? I know this is somewhat of an obscure situation but I'll appreciate any ideas you can give me. Thanks!

# Answer
I agree with Mark that your code all looks sensible, apart from the line defining myDNS. I have no experience of the board/library you are using, but recently I saw an industrial board suffer from a similar problem that turned out to be it was trying to resolve an IP address to a name using reverse DNS and because the DNS server wasn't set properly it failed to connect. So it might be that by setting the address in the myDNS line to a valid DNS server (the one your test PC uses?) then the problem will go away.

If that doesn't work then can you read the manual and see if the Client object can be persuaded to give you an error code or message that would give you a hint as to why it isn't working?

I understand that 169.254.1.2 is the manufacturer recommended address, but why did you use 169.254.106.49 for the test PC? It's very unlikely to be anything, but...

Also (I'm sure this was your first check), is the connection between the Arduino and the camera a straight connection, there are no firewall, routers, switches or bridges in the way doing NAT or PAT or blocking certain connections etc?

(DNS = Domain Name Service, converts names like google.com into meaningful addresses like 1.2.3.4)
> 1 votes

# Answer
In the spirit of "Use the Source, Luke," I've had a look at the code on GitHub, which is I hope the same code that you're using or very similar to it.

There the four-parameter version of `Ethernet.begin()` takes the gateway, not the subnet mask, as the fourth parameter. The subnet mask, when passed in explicitly, is the fifth parameter of the five-parameter version.

This shouldn't actually make any difference since the gateway ought not be used for anything on the same subnet, and the default subnet for class B addresses (from `128.0.0.0` through `191.255.255.255`), in which range your address falls, is 16 bits, `255.255.0.0`.

The problem is, the code linked has what I would argue is a bug:

```
void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway)
{
  IPAddress subnet(255, 255, 255, 0);
  begin(mac_address, local_ip, dns_server, gateway, subnet);
}

```

The subnet mask is *always* set to 24 bits (`255.255.255.0`), in this call that you're using.

`169.254.1.2` and `16.254.184.143` don't have the same 24-bit prefix, so the software (I assume, I've not followed it through) will try to contact the gateway you inadvertently supplied, which isn't even on the same network (not to mention nonexistent), and so fail.

Try calling the 5-argument `Ethernet.begin()` (passing in `0.0.0.0` for the gateway should be fine) and see if that fixes your problem.

I checked the WebClientRepeating example in that repo and they use the three-parameter version. Perhaps you switched to the four-parameter version, or perhaps you got your example from another library. (This example hasn't been modified since the start of the repo in April 2014.)
> 1 votes

---
Tags: arduino-uno, arduino-ide, ethernet, web-server, http
---


# Question
Title: Need Help to implement MODBUS TCP Master over Atmega32 MCU
I am doing a project where I have to interface with Fronius Solar Inverter with Atmega32 MCU over **MODBUS TCP**. I want to set the MCU as client and The inverter as Server and I have to implement two MODBUS Function only these are **READ\_HOLDING\_REGISTER** and **WRITE\_SIGLE\_REGISTER** and Function Code are **0x03** and **0x06** respectively. I am newbie in this field and dont know about networking. Please anybody help me How can I develop the Software in C for this purpose??

The Document of Fronius Inverter for MODBUS TCP is Fronius MODBUS TCP Datamanger

# Answer
So if you want to the atmega as client this means it will start the conection and made the request for values, so translating into modbus words your atmega will be a modbus master and the solar will be a modbus slave.

first you need a way to interface the micocontroller to the tcp/ip stack. you can use an ic or arduino shield which has this ic like a w5100 or enc28j60.

then you can write a library over tcp sockets to start the comunication or change some from the arduino.

https://www.google.com.br/url?sa=t&source=web&rct=j&url=http://myarduinoprojects.com/modbus.html&ved=0ahUKEwj9zMvjiYDTAhXJkpAKHfsNBz0QFggpMAE&usg=AFQjCNEfRhDgPGJNK-IUqrUw1FXEnBcxwQ&sig2=Xs0JNEWi\_F\_XiPgkTQdy-w
> 1 votes

---
Tags: modbus
---


# Question
Title: Is setting clock divider worth changing on delay() to save power?
Along all the "advanced" methods described in this article, does simple method as downscaling processor while `delay` makes a difference on power consumption? How much time does the clock alternation takes itself?

Is below example valid?

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

void setup() {}

void loop {

    /*
       here some jobs to do...
    */

    clock_prescale_set(clock_div_256); // downscale clock
    delay(200); // wait
    clock_prescale_set(clock_div_1); // restore clock
}

```

# Answer
> 1 votes
Reducing the CPU frequency should work, but I would expect better savings by sleeping during the busy loop:

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

void sleepy_delay(uint32_t duration)
{
    uint32_t start = millis();
    while (millis() - start < duration) {
        sleep_mode();
    }
}

```

Note that the sleep will be interrupted at least on every Timer 0 overflow interrupt, which happens every 1024 µs (that's what increments the value returned by `millis()`), so there is no risk of oversleeping. You could add some `power_*_disable()` calls for better savings.

---
Tags: power, code-optimization, code-review
---


# Question
Title: I have four servos connected to an arduiono uno and I cannot control them
I am making a simple bipedal robot. I have four 9g servos connected to my uno. Whenever I try to even do the simplest command, like move right foot 45 degrees it does not work properly. I have tried on my second Uno and i have the same result.

My program for testing the servos:

```
#include <Servo.h>

Servo myservo;

void setup(){
myservo.attach(6);
}

void loop(){
 myservo.write(45);
}

```

Each servo wire is attached to a breadboard where they all share power and ground from the arduino. Each servo wire then has another wire going to pins 3,5,6 and 9.

Does anyone know what the problem is and what I can do? Thanks

# Answer
> 0 votes
An Arduino is not capable of powering four servos. Power them externally, but make sure the ground of the Arduino and servos is connected.

# Answer
> 1 votes
As others have said, the Arduino cannot drive 4 servos - my experience is that it can have problems powering one if you try to move it too often due to the voltage drop caused by the high current consumption. When you move a servo the power consumption rises considerably. A large (220uF or more) capacitor near he servo can help, but even so, by far the best option is to supply the servos from a separate supply.

If the Uno resets when you try to move the servos (especially multiple times per second) then the power supply is most likely your culprit.

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


# Question
Title: ESP8266 not sending temperature data to text message
i am trying to use a ESP8266 module to send temperature data using twilio and send it to my phone via text message. However it does not send the sensor data but the text i placed. Is it possible if i can get it to send sensor data instead? If so how can i do this?

```
strcat(data,"From=");
    strcat(data,PHONE_FROM);
    strcat(data,"&");

    strcat(data,"To=");
    strcat(data,PHONE_TO);
    strcat(data,"&");

    strcat(data,"sid=");
    strcat(data,TWILIO_ACCOUNT_SID);
    strcat(data,"&");

    strcat(data,"token=");
    strcat(data,TWILIO_TOKEN);
    strcat(data,"&");

    strcat(data,"Body=");
    const char TEXT_MESSAGE_BODY []  = "temperature", temperature;
    strcat(data,TEXT_MESSAGE_BODY);

    wifi.httpPost("iot-https-relay.appspot.com","/twilio/Messages.json",data);

```

temperature should be getting sensor raw data and paste it after the "temperature" but it is not working.

# Answer
Not 100% sure what you are trying to do with the line:

```
const char TEXT_MESSAGE_BODY []  = "temperature", temperature;

```

This will not assign the value in temperature to TEXT\_MESSAGE\_BODY, it will create a variable of type char called temperature.

You will need to get your temperature value into a string (array of char) using sprintf() or similar to convert from the base type (float, double?).

Replace const TEXT\_MESSAGE\_BODY \[\] ... etc with :

```
strcat(data,"temperature");

char temperature_s[20];
sprintf(temperature_s, "%f", rawTemperature);
strcat(data,temperature_s);

```

Above assumes rawTemperature is a float holding the value read from the sensor, but the same idea applies for other data types.. There is no checking for buffer overflow etc, but you get the idea.
> 1 votes

---
Tags: arduino-uno, arduino-ide, esp8266, c
---


# Question
Title: How to connect receiver in an Arduino with a motor shield?
I have an Adafruit motor shield v1 stacked on an Arduino Uno. I want to add a 433Mhz receiver to the Uno so I can control it wirelessly. However as you know the motor shield completely covers the Arduino board and all its pins, except perhaps the analog ones (it appeared to me).

So can you please suggest a way to connect the receiver if possible. I desperately need it and can't afford to buy a Mega now.

Please help asap.

# Answer
> 0 votes
Adfruit Motor Shield v1 takes digital pins(D12 to D2) left only digital pins (D13,D1,D0) and all Analog pins of Arduino uno. So if you want to hookup RF receiver with Arduino then you have go this way.. connect RF Receiver output to the Digital pin D0 that is RX.

Here the schematic

---
Tags: arduino-uno, arduino-motor-shield, robotics
---


title: Arduino Com port and PHP Bug

text:
# Question
Title: Arduino Com port and PHP Bug
so please read this whole thing.

My Project: I am making a bell system that is based on PHP. The bell is connected to the arduino UNO via a relay and the arduino is connected to the computer via a USB cable. The interface with the database is built with PHP and MySql. Then we have the code which checks every minuit if the bell has to be rung and if it does send a numeric value to the arduino. There is also an option for a longer bell if we send a '0' to the arduino.

My Code: So this is the file that checks if bell has to rung and sends value to arduino

```
<?php
include('database.php');
$usb_comPort = "COM3";
date_default_timezone_set("Asia/Kolkata");
$time = date("H:i");
$time = trim($time);
$sql = "SELECT bell_amount FROM bell_db WHERE DATE_FORMAT(bell_time,'%H:%i') LIKE '$time'";
$result = mysqli_query($conn, $sql);
$numRows = mysqli_num_rows($result);
if ($numRows == 0) {
  echo 'Error: Nothing found!';
} else {
  $row = mysqli_fetch_assoc($result);
  $bellAmount = $row['bell_amount'];
  $runCommand = "ECHO " . $bellAmount . " > $usb_comPort";
  echo $runCommand;
  exec($runCommand);
}
?>
<html>
<meta http-equiv="refresh" content="60">
<body>
</body>
</html>

```

and this is the arduino's code:

```
int b = 0;
void setup() {
Serial.begin(9600);
pinMode(10, OUTPUT); //relay
}

 void loop() {
  b = Serial.read();

    b = b - 48;
    if(b == 0){
      digitalWrite(10,HIGH);

      delay(3000);
      digitalWrite(10,LOW);
      }
    else{
    for (int i=0; i < b; i++){
      digitalWrite(10, HIGH);
      delay(200);
      digitalWrite(10, LOW);
      delay(200);
      }

    }

}

```

The Issue that i am facing: My aim is that the code should run automatically when the computer is turned on. The code works fine but there is random bug. The code is uploaded to the arduino. When the computer is turned on i want that the system should work but when i run the file (the one that checks if there is a bell to be rung or not ) it processes the code but it is not able to send a value to the com port so the bell does not ring(the serial light on the arduino does not flash). But if i go to the arduino ide and send a value through the serial monitor once then run the php file, it works!

I am running this on a windows 10 computer, i have an arduino UNO and i have tried this with 2 arduino's same result on both.

So anyone know what i can do?

# Answer
Sounds like the COM port is not setup. Opening the Arduino IDE probably does this automatically.

Try running the following command, only once, after turning on your pc to initialize the COM port.

```
mode COM3 BAUD=9600 PARITY=n DATA=8

```

Ps. I'm not a windows user, so this is an educated guess - reference.

Pps. I think you're winning the award for the most complicated way to ring a bell. :)
> 0 votes

---
Tags: arduino-uno, serial, arduino-ide, communication, web
---


title: Confusion about String handling

text:
# Question
Title: Confusion about String handling
I am trying to execute some webbased calls, but my string keep "disappearing", and I am highly confused about why.

I can println a string directly, but if I have it in a variable, it will disappear :I

I tried googling around, but could not find a reason for it. Is it because of the curly brackets ? Is it a memory issue ?

I feel I really can't code on and juggle web calls, if I can't even handle regular string commands..

**Code:**

```
Serial.println(" - CONSOLE/STRING WEIRDNESS - ");
String message = "Testing time {0}";
Serial.println(message);
Serial.println(String(message));
Serial.println("Testing time {0}");
Serial.println(message.substring(3,6));

```

**Response:**

```
- CONSOLE/STRING WEIRDNESS -
(nothing)
(nothing)
Testing time {0}
(nothing)

```

**Update**

This seems to happen whenever there is a number inside a string, it even happends with a simple string like this:

**Code:**

```
Serial.println(" - CONSOLE/STRING WEIRDNESS - ");
String message = "Testing time here is a number 0";
Serial.println(message);
Serial.println(String(message));
Serial.println("Testing time here is a number 0");
Serial.println(message.substring(3,6));

```

**Response:**

```
- CONSOLE/STRING WEIRDNESS -
(nothing)
(nothing)
Testing time here is a number 0
(nothing)

```

# Answer
Give this article a read, it highlights how strings are actually stored in the Arduino memory, and explains how strings should be used.

https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/
> 0 votes

# Answer
The {0} denotes an extra parameter (which you want to print), it seems you just want to print the string without any variable 'value' so you can remove the {0}.

I'm not so familiar with using {0} in C++, but in C# {0} means argument number 0 (after the initial string), since this argument is not given, probably an empty string is created ... it would be more intuitive if the compiler give an error or warning (maybe it gives a warning and you can check for it).

Also converting a string to String() does not do anything but I think it was just for debugging/checking purposes.

Also in Arduino to save SRAM space, normally it is wise to add before each string, the F function like:

```
Serial.println(F("Some string to print"));

```

This will create a memory in Flash and will not be copied to SRAM which is normally quite scarce.

To print out arguments you can simply use multiple print commands (which does not add a new line) and the last part of the line with println, like:

```
Serial.print(F("Test time: ");
Serial.println(test_time);

```
> 1 votes

---
Tags: arduino-yun, string
---


# Question
Title: What is the correct way to create large project files?
I am currently working on a 10x10 RGB LED screen (using Neopixels from Adafruit) and my project files are starting to get rather large. I have several different devices used in this project:

* The LED matrix
* A DS3232 RTC
* An MSGEQ7 DSP chip
* 7 push button switches

Currently i'm using separate classes for each of the devices (RTC, DSP & buttons) as well as the Adafruit GFX and Neopixel library.

What would be the best way to organize this project? Should I put the patterns for the screen in the main.ino file or should they have their own class.

Any help would be greatly appreciated, I can upload the source code if its needed.

Cheers

As a side note, I'm using "Sublime Text 3" along with Stino.

# Answer
> 1 votes
Good to hear you are splitting large amount of code, it will benefit you a lot in the long run.

It's very hard to say what is best, it depends on the interaction of those patterns with other classes. Normally it is best to put them in the location where they BEST belong to, i.e. where the least association with other classes exist.

If it has a lot of interactions, maybe you should put the patterns itself in a different class.

Normally what I keep as guidelines: \- Not more than a few hundred lines in a class \- Not more than 7 (class) variables in a class \- Not more than 7 functions/methods in a class

Of course these are guide lines. If you have a lot of simple (constant) pattern definitions the file will become larger without getting more hard to understand.

Also try to think of a class to have only ONE responsibility. If you want to be serious about splitting classes or how to organize them, read about SOLID.

---
Tags: led, ide, class, neopixel, build
---


title: Problem with Micro SD card breakout

text:
# Question
Title: Problem with Micro SD card breakout
I was connecting my arduino uno to a adafruif micro SD card breakout and everything worked just fine, i could read the sd, write to it and see all the info about it. To do it i just followed the tutorial in here.

My problem is that when I arrived home the exact some thing wouldn't work and I couldn't read the SD card anymore.

I was thinking it could be a bad contact problem since sometimes i get:

```
Initializing SD card...initialization failed. Things to check:
* is a card inserted?
* is your wiring correct?
* did you change the chipSelect pin to match your shield or module?

```

And other times (almost never), i would just get:

```
Initializing SD card...Wiring is correct and a card is present.
Card type: SD2
Could not find FAT16/FAT32 partition.
Make sure you've formatted the card

```

I would like to know if I can assume it is the breakout board failling and I would buy a new one, or if it can be any other thing.

Thank you in advance!

# Answer
Did you try:

1. Reading the SD card in your computer ... if you can read (or write) files, that means the SD card is intact
2. Use a SD card that worked before or similar. Some bigger SD cards (like SDHC, SDXC have less good compatibility). Preferably use a 2 GB or smaller card (unless you have used bigger cards successfully and of the same or smaller type, e.g. SD, SDHC, SDXC).
3. Try different formattings, like FAT, FAT16, FAT32. I think FAT is the mostly recognized formatting.
4. Check connections/wires to/from SD breakout, maybe during your leave accidentally you (or someone else) or due to pressure/tension, a contact/wire got loose.
5. Check another SD card in the SD breakout where the SD card you know is good. If this also does not work, it must be the breakout (or Arduino).
6. Replace every piece of hardware (including wires) one by one and recheck if it works (after you are sure the SD card itself is ok).
> 1 votes

---
Tags: arduino-uno
---


title: Arduino UNO USART problems

text:
# Question
Title: Arduino UNO USART problems
I need to send 6 bytes value from Arduino UNO to the actuator using serial port in order to make it extends. I have added a button to send the data. For example, 0 20 1 1 0 0. The communication settings are 9600 baud rate, 8 data bits, no parity and 1 stop bit. I have used MAX 232 to build a TTL to RS232 circuit. The actuator does not move. Are there any problems on my program? I am new to create USART code. I think I have some problems on transmit function. I am using the build in USART with c code. Here is my code:

```
#define BAUD_PRESCALER 0x67
int buttonPin1 = 4;
int buttonState1 = 0;

void setup() {
    // put your setup code here, to run once:
    pinMode(buttonPin1, INPUT_PULLUP);
}

unsigned char data1 = 0x00; // 0
unsigned char data2 = 0x14; // 20
unsigned char data3 = 0x01; // 1
unsigned char data4 = 0x01; // 1
unsigned char data5 = 0x00; // 0
unsigned char data6 = 0x00; // 0

void USART_Init(void) {
    /*Set baud rate */
    UBRR0 = BAUD_PRESCALER;
    UCSR0A = 0x00;
    /*Enable receiver and transmitter */
    UCSR0B = 0x08;
    /* Set frame format: 8data, 1stop bit */
    UCSR0C = 0x06;
}

void USART_Transmit( unsigned char data ) {
    /* Wait for empty transmit buffer */
    while ( !( UCSR0A & (1<<UDRE0)) )
    {
        ;
    }
    /* Put data into buffer, sends the data */
    UDR0 = data;
}

void loop() {
    // put your main code here, to run repeatedly:
    buttonState1 = digitalRead(buttonPin1);
    if (buttonState1 == LOW)
    {
        USART_Init();
        USART_Transmit(data1);
        USART_Transmit(data2);
        USART_Transmit(data3);
        USART_Transmit(data4);
        USART_Transmit(data5);
        USART_Transmit(data6);
    }
}

```

# Answer
The first thing I do when I have a transceiver that doesn't work is a loopback test. This rules out a lot of potential issues like the wrong pin being used or MAX 232 not being connected correctly.

Receiving your transmission on a PC using USB to RS232 adapter (if you have one) would also be a helpful test.
> 2 votes

# Answer
I would recommend you to use the arduino's built in UART library. Try this code:

```
int buttonPin1 = 4;
int buttonState1 = 0;

unsigned char data1 = 0;
unsigned char data2 = 20;
unsigned char data3 = 1;
unsigned char data4 = 1;
unsigned char data5 = 0;
unsigned char data6 = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);           // set up Serial library at 9600 bps
  while (!Serial);              // wait till UART initialized, for arduino UNO

  pinMode(buttonPin1, INPUT_PULLUP);
}

void loop() {
    // put your main code here, to run repeatedly:
    buttonState1 = digitalRead(buttonPin1);
    if (buttonState1 == LOW)
    {
        Serial.write(data1);
        Serial.write(data2);
        Serial.write(data3);
        Serial.write(data4);
        Serial.write(data5);
        Serial.write(data6);
    }
}

```

You should know that as long as the button is pressed data is being sent to the actuator. With that being said, with one button press you may have the commands sent 10 times. Thus, you have to deal with that in your code.
> 1 votes

# Answer
I think that your BAUD rate setting is wrong. The `UBRR0` register is a 16 bit wide one thus should be accessed in two 8 bit part, via `UBRR0H` and `UBRR0L`. You can check it in the datasheet.

If you further check the datasheet there is an example code in addition to the USART description which shows a correct way of initialization.

> ```
> #define FOSC 1843200 // Clock Speed
> #define BAUD 9600
> #define MYUBRR FOSC/16/BAUD-1
> void main( void )
> {
>     ...
>
>     USART_Init(MYUBRR)
>     ...
> }
>
> void USART_Init( unsigned int ubrr)
> {
>     /*Set baud rate */
>     UBRR0H = (unsigned char)(ubrr>>8);
>     UBRR0L = (unsigned char)ubrr;
>     /* Enable receiver and transmitter */
>     UCSR0B = (1<<RXEN0)|(1<<TXEN0);
>     ...
> }
>
> ```

As you can see the UBRR's value is calculated using the system clock speed `FOSC`, with `MYUBRR` macro which is an equation from the datasheet. Later this value is being set in two part upper 8 bit:

```
UBRR0H = (unsigned char)(ubrr>>8);

```

lower 8 bit:

```
UBRR0L = (unsigned char)ubrr;

```

(Your transmit function seems to be correct. And as I commented it is enough to call the USART init once in the `setup()`.)
> 1 votes

---
Tags: avr, uart
---


title: Trying to make a wattmeter

text:
# Question
Title: Trying to make a wattmeter
I've been trying to make a wattmeter using arduino but cannot find the shield I need to buy to put onto my arduino to make it. There are no such parts in the Arduino Store and online the best I could find is this. This measures the arduino's energy consumption, however, not other things. I am really new at this and thoroughly lost. I would be really glad if someone could help me with this problem :)

# Answer
> 4 votes
You will need an Ampere meter and a Voltmeter. Watts is `Volt` * `Ampere`.

There are logic level compatible units out there for ampere meters ranging from a few mA to at least dozens of Amperes.

Also for voltmeters there are several logic level compatible units available, to plug in your project.

The rest is math. (Watts = A * V )

---
Tags: shields
---


# Question
Title: How to get number of available pins in code?
Different boards have different number of pins.

Is there a way to know this number in code (at least digital and analog pins), or do I have to determine board type (like in this thread) and know the number of pins by myself?

---

*Reasoning for this is that I'm creating prototype using Uno and using 2-3 analog pins for temperature readings, but I want to be able to use the same code for different board in the future with eg. 8 analog pins, so I don't have to remember to change pin numbers in code and maybe solder it convenient way etc. Also being able to use for eg. "last available analog pin" for certain job could help keep code/schematics nice and clean.*

# Answer
It is quite easy actually:

```
Serial.print("number of digital pins: ");
Serial.println(NUM_DIGITAL_PINS);
Serial.print("number of analog inputs: ");
Serial.println(NUM_ANALOG_INPUTS);

```

Note that these are compile-time constants defined as macros in a file named `pins_arduino.h`. There is one such file for every board supported by the Arduino environment. Just to take Curt J. Sampson's example, if someone “made a board with an MCU with 100 digital IO pins available, yet if only ten of these are brought out to pins on the board”, then the macros would tell you you have 10 digital pins. Assuming of course that you installed the proper support package for that particular board.
> 10 votes

# Answer
In the ultimate case, a "board" is not something you can determine programmatically in software; it's not possible in general to tell if, e.g., a particular pin on the microcontroller is connected to a corresponding head pin on the board.

That said, as Edgar Bonet point out, the Arduino board definitions used in the IDE will generally do what you want. Just keep in mind, these are just someone saying "the board should be like this"; a cheap clone board, for example, might be different without a new and proper board definition.

With running code on the microcontroller itself, examining what it can see of the board, you can usually tell which microcontroller you're using. But that just tells you about the chip and its pins, and not about where leads from those pins might go. It sounds to me as if you're asking to find a way to see if your particular microcontroller (e.g., an ATmega328P) is on, say, an Arduino Uno or some other board where certain MCU pins may or may not be hooked up to board pins. The MCU can't tell whether any of its particular pins are connected to headers on the board. As a more specific example, someone could build a board with an MCU with 100 digital IO pins available, yet if only ten of these are brought out to pins on the board, the others are not easily usable. uino.cc/en/Main/ArduinoBoardUno) or \[Arduino Nano\]

For your application, you're thinking in a good direction when considering how to make things easier for others using your code. However, I'd suggest that in the long run it's better just to have clear definitions in an obvious place in your sketch (at the top of the file in a single-file sketch, perhaps in a `config.ino` in a multi-file sketch, or passed in to an initialization function for a library) that says explicitly what pins are used and is easy to change for others. Having the default pins used by the sketch move around if I load the sketch on a different board strikes me as rather confusing.

Keep in mind your audience: the people who are going to be using this on a board different from yours are Arduino hobbyists, and so they're already (or will soon become :-P) familiar with the idea of pins, pin definitions in code, and pin conflicts.
> 2 votes

# Answer
You can identify the host processor at run time - each one has its own signature - but not necessarily the board it's running on (consider an Uno and a breadboard-uino for example). So you'd have to make each kind of board you use distinguishable in some way, such as jumpering 3 pins each high or low to make a 3-bit binary code representing one of 8 board types. The next solution is to define that code or some other identifier at compile time with a #define statement, and use the identifier in one or more #ifdef statements to compile board-specific pin definitions.

If you plan on using standard boards the IDE knows about, the IDE pre-defines some useful symbols for you. Here's the compile command the IDE used for an empty sketch for an UNO (I've reformatted it for readability):

```
"/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++"
-c
-g
-Os
-Wall
-Wextra
-std=gnu++11
-fpermissive
-fno-exceptions
-ffunction-sections
-fdata-sections
-fno-threadsafe-statics
-MMD
-flto
-mmcu=atmega328p
-DF_CPU=16000000L
-DARDUINO=10612
-DARDUINO_AVR_UNO
-DARDUINO_ARCH_AVR

```

The last four lines make the equivalent of #defines for the clock-frequency, the IDE version number, the Arduino-board, and the overall MCU architecture, respectively.

So in your code, a block like:

```
#ifdef ARDUINO_AVR_UNO
   // pin definitions for Uno here
#endif

```

will only be compiled if you selected "Arduino/Genuino Uno" as your board type in the IDE. There are similar symbols for other board types. So for a Nano, `ARDUINO_AVR_NANO` would be defined instead.
> 1 votes

---
Tags: pins
---


# Question
Title: Specific noise while using arduino ADC in free running mode
To make an oscilloscope in matlab environment, for data acquisition on arduino side, when inbuilt `analogRead()` is used, it's working fine, but with very low sampling rate, that aliasing is clearly observed. That too, non-uniform sampling. Thus listing out the drawbacks:

1. Very slow data rate, even if, sent with 115200 baudrate,
2. Aliasing
3. Non-uniform sampling

Thus, to overcome above, ADC in free running mode was used, with 16 as prescaling factor, thus 76.9KHz sampling rate (counting each ADC as 13 clock cycles). Thus, data is uniformly sampled now. Also it is quite fast, because of sampling, and is observed. The only problem now exists is, output has a specific noise. The data being sampled is 50Hz sinusoidal current waveform by current sensor ACS712. It overlays instantaneous current waveform over a bias of 2.5V. Thus, when signal is not present, a constant voltage of 2.5V is observed, thus, 512, because of mapping to 255 range.. 127. But in the case of free running mode, along with 127, 191, 63 only are observed. And it can also be seen that nearly 127 = 63\*2, and 191 = 63\*3. And when current waveform exists, it's highly distorted, but perceptible that it's not the previous signal of just 127, 191, 63. In the below plot, current is passed since 33.5sec.

I am unable to understand this, structured noise. What may be the reason ? I have once read, last two MSB bits get noisy at this sampling rate, but then how would 127, jump to 191. Why is 63 getting added, subtracted at each instant ? I understand the reason for non-uniform sampling now is because of `Serial.print()`, whose interrupts are obstructing the ADC interrupts, but don't understand the reason behind the noise observed.

Following is the code uploaded in arduino. Serial data is read from matlab by `fread()` function.

```
long t1=0,ts1=0,ts2=0;
int aval=0, val=0;

void setup() {

 TIMSK0 = 0x00;           // disable timer (causes anoying interrupts)
 DIDR0 = 0x3F;            // digital inputs disabled
 ADMUX = 0x40;            // measuring on ADC0, right adjust, AREF reference
 ADCSRA = 0xAC;           // AD-converter on, interrupt enabled, prescaler = 16
 ADCSRB = 0x00;           // AD channels MUX on, free running mode
 bitWrite(ADCSRA, 6, 1);  // Start the conversion by setting bit 6 (=ADSC) in ADCSRA
 sei();
 Serial.begin(115200);
 t1=millis();
 }

ISR(ADC_vect)
{
 aval = ADCL;
 aval += ADCH << 8;
}

void loop() {
val = map(aval, 0, 1023, 0, 255);
Serial.write(val);
delay(10);
}

```

# Answer
If you use an ISR to retrieve the ADC result, you will need to protect the read of the variable. An interrupt may occur when reading `aval` in the `loop()`, as this is a 16-bit value and the read requires several instructions. This may give corrupt values.

```
void loop() {
  noInterrupts();
    val = aval;
  interrupts();
  val = map(val, 0, 1023, 0, 255);
  Serial.write(val);
  delay(10);
}

```

Cheers!
> 2 votes

# Answer
It is very unclear what you are trying to achieve here. You are clocking the ADC at its maximum frequency, which has it take one reading every 13 µs, and yet you are delaying for 10 ms after sending one reading through the serial port. So basically your Matlab program is getting one reading out of every 769 you take.

If you want fast data acquisition with a consistent sampling frequency, you basically have two options:

* clock the ADC as fast as you dare, buffer the data in RAM and, when the buffer is full, send it to the host computer
* set a high baud rate and take the data as fast as the UART can send it.

The first option allows for faster sampling rates, but only as short bursts, as limited by the available RAM. Given what you have already written I assume you want continuous acquisition, and thus the second option. I also assume you are using an Arduino Uno or similar.

At 115.2 kb/s (actually 117.647 kb/s given the rounding), every bit sent takes 136 CPU cycles, or 8.5 µs. One byte takes 10 bits (start bit + 8 data bits + stop bit), i.e. 85 µs. This means there is no point in clocking your ADC that fast: you can set the prescaler to 64 and each reading will take 52 µs.

What I would do here is configure the ADC to be triggered by Timer 1, and have that timer deliver the trigger signal every 1360 CPU cycles *exactly*. Then,

```
ISR(ADC_vect)
{
    Serial.write(ADCH);
}

```

assuming of course you have set the left-adjust mode (`ADLAR` bit in `ADMUX`).

With the ADC and the UART working at the very same frequency, you keep the UART busy without ever filling the output buffer. If your ADC runs faster than the UART, the buffer will fill out and your timings will get nasty. On the other hand, if you are really confident in your timings, you could skip the `Serial` managing of that buffer and just do `UDR0 = ADCH` in the ADC ISR.
> 1 votes

# Answer
Not sure what "structured noise" you are referring to but some advices.

1. Check the datasheet to see adc timing requirement. When not enough time is given, acc results are highly correlated serially.
2. In the acc isr, make sure that atomicity is preserved.
3. Isr has its overhead so make sure that it is consistent with your acc speed setting.
4. If you are using only the msb. You can configure the acc to be left alighened, saving you lots of time and headache.
> 0 votes

---
Tags: serial, adc, analog-sampling
---


title: What is the phase of tone?

text:
# Question
Title: What is the phase of tone?
Is it garanteed (with some precision) that the phase of a PWM-signal generated by `tone` is the same on each pin? Can it be altered (by internal means of Arduino) so that it's different on different pins?

I'm looking for a way to adjust phases of signals from several pueso-buzzers by either adjusting distances (least preferrable) or programmaticaly (most preferrable) or by external components (if they're not very complicated).

# Answer
> 2 votes
The arduino.cc description of `tone()` says “Only one tone can be generated at a time”, so presumably you are using some other software to generate tones on multiple pins. For example, Brett Hagman's `play()` code, which Arduino `tone()` is derived from, uses multiple timers, one per tone.

When using `play()`, you probably can adjust phase by calling `delayMicroseconds()` between the two `play()` calls that start up the tone generation; for example:

```
play(11, 440);
delayMicroseconds(235); // Move 2nd tone 8 cm closer
play(9, 440);

```

Note, because `tone()` and `play()` use one timer per output (for example, timer 2 for first tone, timer 1 for next tone, timer 0 for third tone) there usually will be some timer prescale mismatches between 8-bit and 16-bit timers, which may result in slightly different frequencies, leading to some constant phase shift rate if you use that method.

With the speed of sound about 340.29 m/s in air at standard pressure, the wavelength of say 440 Hz would be under a meter, so I presume you would move speakers just a few tens of cm for phasing; hence a few hundred to a few thousand microseconds of phase offset. If you want good programmatic control, and also want to have quite a few speakers, external hardware in the form of a delay line or a bucket brigade chip is an obvious approach.

You could simulate a program-controlled delay line fairly easily using a handful of 74HC595 SIPO shift registers, as follows: Connect the DS of the first '595 to your `tone()` output pin. Connect the Q7S output of each '595 except the last to the DS of the following '595.

Now use another timer to repeatedly clock your tone data into the shift register chain. That is, connect all STCP and SHCP inputs in parallel to a timer output pin. (Eg, OC1A, OC1B, OC2A, or OC2B, which might be pins like 9–12 on an Uno or Nano). Run that timer at 10 to 100 KHz, ie, at some rate *f* that gives you the resolution and range of phase changing that you need.

Calling the shift register outputs o₀, o₁, o₂..., we have oⱼ delayed by (j-i)/*f* seconds relative to oᵢ. That is, successive SR outputs represent different taps for different delays.

# Answer
> 2 votes
The main principle behind working with buzzers, in its simplest form, comes down to something along the lines of

```
digitalWrite(buzzerPin,HIGH);
delay(half_tone_frequency);
digitalWrite(buzzerPin,LOW);
delay(half_tone_frequency)

```

that, when repeated is enough to generate some tone on a single buzzer. However - to get desired tones (frequencies) right, you have to be mindful of the exact time that passes between each part of the code (the pin needs to oscillate in some frequency to produce a tone of that frequency)

So technically, its possible to create different sounds on different buzzers connected on different(!) pins at the same time, if you know exactly how much time each pin spends HIGH and LOW. This is naturally simpler when they do not need to be active concurrently.

# Answer
> 2 votes
If you want fine control over the phases, I assume you may also care about having low phase noise. In this case your best bet is to avoid toggling the pins in software and go for a hardware signal generation.

With an Arduino Uno or similar board, this can probably achieved by programming a timer. I would try the following:

Configure Timer 1 in waveform generation mode 12, i.e. CTC mode with TOP = ICR1. Set the compare output mode of both channels to toggle on compare match. Set ICR1 so that the timer has *half* the period of the signal you want. Now you can independently adjust the phases of both outputs by writing to `OCR1A` and `OCR1B`.

Note that those registers are not double buffered in this mode, so you have to be careful about when you write them.

The Arduino core library has no support for such timer configuration: you will have to learn how to program it yourself. If you are not familiar with the subject matter, I recommend you start by reading Nick Gammon's tutorial on timers.

---
Tags: pwm, audio
---


title: Single-channel serial communication

text:
# Question
Title: Single-channel serial communication
I'm trying to communicate with a device which only uses a single wire at 9600 Baud. How can I use my Arduino UNOs RX/TX-Pins to recieve and transmit on that one wire?

# Answer
> 3 votes
Bidirectional Asynchronous Serial schemes are not uncommon. The famous ones, like RS485, utilize special line drivers and differential signalling, but for short distances you can accomplish something similar using the ability of most MCU's, including the Arduino's ATmega, to tristate the serial transmit pin.

Essentially, you would wire the shared line to both the receive and transmit pins, and when it is not the Arduino's "turn" to transmit, you would configure the Transmit pin as an *input* rather than as an output.

It's then up to a software protocol to make each node transmit at only the appropriate time. Often a bus master can transmit essentially at whim, and subservient device(s) are only allowed to transmit in reply to specific queries from the master. Of course the master should not transmit when it has just request a reply.

Also note that you cannot change the pin over to input mode when the last character is *loaded* into the UART, rather it has to stay in output mode until the last sent character has been clocked out onto the wire.

While putting a resistor between the transmit pin and the shared line could provide some theorectical safety against bus contention introduced by software errors, in practice the hardware will typically survive such conflicts during development, and having too large a resistor there may cause problems with signal quality. If you are going to use a resistor, it should be sized for source termination of the line impedance, *not* for electrical protection. You may also want a weaker pulling resistor to give the bus a known state when no one is driving it. If this state matches the last driven one, the resistor won't have to overcome capacitance to "drive" the line, but rather merely "hold" it in the last driven position.

If you are using a device like the Uno which has only one hardware serial interface, you will have to decide if you are going to use the hardware interface at the cost of breaking the ability to use that to debug or upload sketches, or if you are going to use a software UART ("Software Serial" or its variants) on arbitrary digital pins. If you do the later, it would be entirely possible to rework a library to receive and transmit on the *same* pin, rather than requiring two distinct ones.

---
Tags: arduino-uno, serial, uart
---


title: Johnny Five LCD: black boxes only

text:
# Question
Title: Johnny Five LCD: black boxes only
I posted this also at Stack Overflow. I have tested the Johnny Five LED example on my Arduino Uno, and it worked fine. Now I need to test Johnny Five **LCD**. I connected all wires correctly.

The code:

```
var five = require("johnny-five"), board, lcd;

board = new five.Board();
board.on("ready", function() {
  lcd = new five.LCD({
    // LCD pin name  RS  EN  DB4 DB5 DB6 DB7
    // Arduino pin # 7    8   9   10  11  12
    pins: [7, 8, 9, 10, 11, 12],
    backlight: 6,
    rows: 2,
    cols: 20
    // Options:
    // bitMode: 4 or 8, defaults to 4
    // lines: number of lines, defaults to 2
    // dots: matrix dimensions, defaults to "5x8"
  });

  // Tell the LCD you will use these characters:
  lcd.useChar("check");
  lcd.useChar("heart");
  lcd.useChar("duck");

  // Line 1: Hi rmurphey & hgstrp!
  lcd.clear().print("rmurphey, hgstrp");
  lcd.cursor(1, 0);

  // Line 2: I <3 johnny-five
  // lcd.print("I").write(7).print(" johnny-five");
  // can now be written as:
  lcd.print("I :heart: johnny-five");

  this.wait(3000, function() {
    lcd.clear().cursor(0, 0).print("I :check::heart: 2 :duck: :)");
  });

  this.repl.inject({
    lcd: lcd
  });
});

```

But it doesn't output as expected. It is showing one row of black boxes only. what have I missed?

# Answer
> 1 votes
Try changing the resistance in your 10k potentiometer. This might be a reason for the black boxes.

P.S: I.m a beginner too.

---
Tags: arduino-uno, johnny-five
---


# Question
Title: Serial Port configuration with asio C++ library
I've made a small interface using the asio C++ library to open serial ports and do I/O from/to them. It works with my Arduino Uno and other hardware as well (industrial weighing machines), but I only specify the port and baud rate.

The following code is run in the client application, which runs both on my Windows 10 Student Edition x86\_64 machine, and on old 32 bit Win XP machines that communicate with the weighing machines:

```
/*this is inside a constructor*/
/*iosvc gets passed by reference, port_ is a member variable of type asio::serial_port,
 npuerto is the name of the port (e.g. "COM3") */

port_(iosvc_, npuerto),

/*...*/

port_.set_option(asio::serial_port_base::baud_rate(baudios));

```

The Arduino is programmed to do a serial echo of whatever is sent to it, for testing purposes. This is the echo code:

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

void loop()
{
  while(Serial.available())
  {
    Serial.write(Serial.read());
  }
}

```

It works fine with my Arduino until I unplug it and plug it back in. After replugging it all the values returned are garbage, specifically some sort of '?' character inside a black box, don't know the bit value though, but it's constant. The problem gets fixed when I open an arduino IDE Serial Port monitor. If I close it, and once again use my own software to open up the serial port, all the values are fine.

From this I concluded that the Arduino IDE Serial Port monitor is doing something when it opens up the port that I'm not doing.

Any clues? Flow control? Handshake? Thanks

# Answer
Can you include all the other calls you make related to setting up the serial port along with `asio::serial_port_base::baud_rate(baudios)`? Ideally, split that out into a separate function (that takes parameters such as baud rate) that you know is the only thing doing this setup.

As I mentioned in the comment, getting back the right number of chararacters but incorrect characters looks as if the baud rate is correct but something else is wrong. The first thing that comes to mind is the bits/parity/stop bits settings. Typically you want to be using 8 bits, no parity, often referred to as "8N1".
> 1 votes

---
Tags: serial, c++, rs232, boost
---


# Question
Title: RePaper 2.7" eInk Display with Arduino Due
I got a RePaper 2.7' eInk display that unfortunately doesn't support Arduino Mega because of its limited SRAM capacity (8k bytes). I am porting the library to Arduino Due because of its sufficient RAM capacity (96 KB in two banks: 64KB and 32KB).

I am using the thread rePaper - 2.7" Graphic eInk Dev Board Headers and I've done all the modifications.

Has anyone successfully ported the library to Arduino Due? Also, does anyone have a library for Dynamic Printing for this display?

# Answer
You're trying to port the library from the Due to the Mega? If the library is large a "port" just isn't going to happen because relatively minor modifications to the code are very unlikely to shrink the size significantly; you'll need a complete rewrite.

My suggestion is to start by studying the data sheet for the device and the code for the existing Due driver to get an idea of how it works. Then sit down and write some sketches for your Mega that make something happen on the display (perhaps just clearing it, turning on and off a few specific pixels, the like) to verify your understanding. Once you've done that, you can start to consider the design of your driver.

Because of the vastly different memory limitations it's likely that your driver will look and work very differently from the Due driver. For example, a 264 x 176 x 1 bit frame buffer would use almost 6K of RAM (most of the RAM in a Mega 2560 and far more than in an Uno), so you're not going to want to have one. I don't know if the Due driver has a frame buffer (I'm just using this as an example of a typical difference you might encounter), but if it does, and that's used for doing certain kinds of things, you'll need to do them in a different way or not do them at all.

This is not a simple project, but it's a great one and will teach you a lot about microcontroller programming!
> 1 votes

---
Tags: lcd, display
---


title: Modbus RTU slave library

text:
# Question
Title: Modbus RTU slave library
I want to use an Arduino Genuino Zero as a Modbus slave. I tried to search on google, and found a library. When I try using the library, I get a timeout error.

Can anyone tell me how to solve that error? Did anyone manage to get the Arduino Modbus RTU slave library working?

# Answer
so i edited code your as below #define mySerial Serial1

```
byte test_data[8] = {0x01,0x03,0x00,0x64,0x00,0x02,0x85,0xD4};

int data_count = 5;

void setup() {

mySerial.begin(9600);
Serial.begin(9600);
delay(1000);

}
int count = 0;
void loop() {

  if(count%10 == 0) {
    Serial.println();
    send_data();
  }

  count++;

  while(mySerial.available()>0)
  {
    byte b=mySerial.read();
    delay(1);
    Serial.print(b,HEX);
    Serial.print(" ");
  }
  //Serial.println(count);
  while(Serial.available())
  {

    byte a=Serial.read();
    delay(1);
    mySerial.print(a);

  }

  delay(1000);

}

void send_data() {
  Serial.println("send data");

  delay(1);
  for(char i=0;i<8;i++){
    mySerial.write(test_data[i]);
    delay(1);
    Serial.print(test_data[i],HEX);
    Serial.print(" ");
  }

  Serial.println();

  delay(1);

```
> 1 votes

# Answer
I am unable to simulate and see the result right now; I hope if the library functions properly this might be a communication issue. I can add a one step debug for you to check and see what is happening.

Your device is acting as a Modbus RTU slave, So take another Arduino, make it act it like a master device, and see what response is coming from the slave device. Here is a glimpse of code I used to make arduino as a master and see the response coming in Serial terminal.

```
    #include <SoftwareSerial.h>
    #define rxPin 2
    #define txPin 3

    #define RS485_pin 10
    //SoftwareSerial mySerial(rxPin, txPin);
    #define mySerial Serial1

    byte test_data[8] = {0x01,0x03,0x00,0x64,0x00,0x02,0x85,0xD4};

    int data_count = 5;
    byte rcvdata[15];
    int param_value_int[7];

    void setup() {
      // put your setup code here, to run once:
    //mySerial.begin(19200,SERIAL_8E1);
    mySerial.begin(9600);
    Serial.begin(9600);
    delay(1000);
    pinMode(RS485_pin, OUTPUT);
    digitalWrite(RS485_pin,LOW);
    delay(100);
    }
    int count = 0;
    void loop() {

      if(count%10 == 0) {
        Serial.println();
        send_data();
      }

      count++;

      while(mySerial.available()>0)
      {
        byte b=mySerial.read();
        delay(1);
        Serial.print(b,HEX);
        Serial.print(" ");
      }
      //Serial.println(count);
      while(Serial.available())
      {
        digitalWrite(RS485_pin,HIGH);
        byte a=Serial.read();
        delay(1);
        mySerial.print(a);
        digitalWrite(RS485_pin,LOW);
       // Serial.print(a);
      }

      delay(1000);
      //while(1);
    }

    void send_data() {
      Serial.println("send data");

      digitalWrite(RS485_pin,HIGH);
      delay(1);
      for(char i=0;i<8;i++){
        mySerial.write(test_data[i]);
        delay(1);
        Serial.print(test_data[i],HEX);
        Serial.print(" ");
      }

      Serial.println();
      digitalWrite(RS485_pin,LOW);
      delay(1);
    }

```

Here you can use Software Serial or normal Serial1 or Serial2 on devices like Mega. Make sure if it is RS485 based you have to toggle the RS485 read-write pin each time to enable and disable one feature at a time as RS 485 uses half-duplex communication.

In this case test\_data\[\] uses Function code FC03 Read holding register. You can make your custom data. I am assuming you are familiar with all the types available.Still there is a great site \[ link \] to look up to if you don't know the basics. The last two bytes are checksum. And there is an online checksum calculator available if you need also https://www.lammertbies.nl/comm/info/crc-calculation.html

In this way you can at least debug and share the result, so that we can help more.
> 0 votes

---
Tags: modbus
---


# Question
Title: Trying to make arduino heart beat counter but couldn't understand code
I am trying to make an Arduino heart beat counter . I looked for some code online and found this code on arduino.cc forum but I couldn't understand working of the given code .. specifically these few lines of code: The full code is given below:

```
int sensorValue = 0;
int sensorValue = 0;  // variable to store the value coming from the sensor
int count = 0;
unsigned long time1 = 0;  // store the initial time
unsigned long time2;    // store the current time
void setup() {
    // declare the ledPin as an OUTPUT:
    pinMode(sensorPin, INPUT);
    Serial.begin(9600);
}

void loop() {
    // read the value from the sensor:
    if (count == 0)
    {
        time1 = millis();
    }
    time2 = millis();
    sensorValue = analogRead(sensorPin);
    if (sensorValue > 156)
    {
        increment();
    }
    if (time2 >= time1 + 10000)
    {
        counter();
    }

}

void increment()
{
    count++;
    while (sensorValue > 156)
    {
        Serial.print("Sensor value is greater than .75V\n");
    }
}
void counter()
{
    count = count * 6;
    Serial.print("Heart beat is ");
    Serial.print(count);
    Serial.print(" per min\n");
    time1 = 0;
    time2 = 0;
    count = 0;
}

```

Lines of code I'm not able to understand :

```
if (count == 0)
{
    time1 = millis();
}
time2 = millis();
sensorValue = analogRead(sensorPin);
if (sensorValue > 156)
{
    increment();
}
if (time2 >= time1 + 10000)
{
    counter();
}

```

PS: the given code is in void loop(). in the beginning of the loop.

if u are not able to understand the code i'm leaving a link to the page:this is the link

i would be highly obliged if anyone could really help me soon. Thank u in advance :-)

# Answer
I've reformatted you code to make it easier to read.

Looking just at the lines you don't understand.

Line 1 stores the start time of this loop in the variable `time1` and stores the current time in the variable `time2` these are going to be almost identical until the first heart beat is seen (which will increment count).

Line 6 `sensorValue = analogRead(sensorPin);` reads the value from the sensor, it the reading is greater than some predetermined threshold (156) then it `increment()` the counter and waits until the value goes below 156.

Line 11 checks to see if 10 seconds (10,000 mS) have elapsed since the loop started. If they have then you get your reading via the function `counter()`

Does that make sense?

It would be a lot easier to understand if the original author had put comments in, but most people writing examples assume there code is so easy to understand they don't need to, don't fall into that trap when you become a great programmer! :)
> 1 votes

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


# Question
Title: Arduino restarts when a function is called
When I call a function, get\_split(), the Arduino restarts. I have tried to find what is causing this, but I have had no luck. Here is my code:

```
std::vector<std::vector<std::vector<std::vector<float>>>> get_split(std::vector< std::vector< float > >& dataset) {
  std::vector<int> class_values; // declares vector 'class_values'
  for (int i = 0; i < dataset.size(); i++) { // loops through each value in dataset (the dataset contains vectors)  and appends the last value in each vector to class_values
    class_values.push_back(dataset[i][dataset.size()]);
  }
  std::vector<std::vector<std::vector<float>>> b_index;
  b_index.push_back(std::vector<std::vector<float>>(999));
  std::vector<std::vector<std::vector<float>>> b_value;
  b_value.push_back(std::vector<std::vector<float>>(999));
  std::vector<std::vector<std::vector<float>>> b_score;
  b_score.push_back(std::vector<std::vector<float>>(999));
  std::vector<std::vector<std::vector<float>>> b_groups;
  for (int i = 0; i < dataset[0].size(); i++) {
    for (int j = 0; j < dataset.size(); j++) {
      std::vector<std::vector<std::vector<float>>> groups = test_split(i,  dataset[j][i], dataset); // gets the split of the dataset (assigns each vector in the dataset to either 'left' or 'right')
      float gini = gini_index(class_values, groups); // calculates the gini
      if (gini < b_score[0][0][0]) {
        b_index[0][0][0] = i;
        b_value[0][0][0] = dataset[j][i];
        b_score[0][0][0] = gini;
        b_groups = groups;
      }
    }
  }
  std::vector<std::vector<std::vector<std::vector<float>>>> vals;
  vals.push_back(b_index);
  vals.push_back(b_value);
  vals.push_back(b_groups);
  return vals; // returns the values.
}

```

This code is meant to check the gini of splitting a certain function (the gini\_index() function works fine). Then it calls test\_split which assigns the vector values into two sub-vectors in the vector groups, left and right. Then I just choose the split with the lowest gini.

When I delete everything in the function it doesn't restart, but I have deleted the first for loop, and also the part where it returns a vector, but still no luck. Also when deleting the for loop underneath the declaration of b\_groups, it still doesn't work. I don't think it is a memory/storage issue because the Arduino IDE says that I'm only using 3% of that.

PS: I have used the library StandardCplusplus library to include vectors.

# Answer
Your code is very complex and running it in an environment where you have limited debug facilities is making life worse for yourself.

When an Arduino reboots it is usually because it has thrown a memory error. This happens when you try and access memory that is no longer your program's to access (or never was yours). In this case I originally suspected, based on the complexity of your code, that you were accessing a vector element that you could no longer access.

To prove this I 'ran it on a desktop', in my case a Windows 7 box with Visual Studio 2015 (but you could have used Linux, GCC and GDB). This meant I wrote a little wrapper program and stubbed the functions you called. This resulted in the error message shown below.

This is my 'desktop' code:

```
#include <vector>

std::vector<std::vector<std::vector<float>>> test_split(const int& i, const float& f, std::vector< std::vector< float > >& dataset)
{
    std::vector<std::vector<std::vector<float>>> vals;
    return vals;
}

float gini_index(const std::vector<int>& class_values, const std::vector<std::vector<std::vector<float>>>& group)
{
    return 1.0f;
}

std::vector<std::vector<std::vector<std::vector<float>>>> get_split(std::vector< std::vector< float > >& dataset) {
    std::vector<int> class_values; // declares vector 'class_values'
    for (int i = 0; i < dataset.size(); i++) { // loops through each value in dataset (the dataset contains vectors)  and appends the last value in each vector to class_values
        class_values.push_back(dataset[i][dataset.size()]);
    }
    std::vector<std::vector<std::vector<float>>> b_index;
    b_index.push_back(std::vector<std::vector<float>>(999));
    std::vector<std::vector<std::vector<float>>> b_value;
    b_value.push_back(std::vector<std::vector<float>>(999));
    std::vector<std::vector<std::vector<float>>> b_score;
    b_score.push_back(std::vector<std::vector<float>>(999));
    std::vector<std::vector<std::vector<float>>> b_groups;
    for (int i = 0; i < dataset[0].size(); i++) {
        for (int j = 0; j < dataset.size(); j++) {
            std::vector<std::vector<std::vector<float>>> groups = test_split(i, dataset[j][i], dataset); // gets the split of the dataset (assigns each vector in the dataset to either 'left' or 'right')
            float gini = gini_index(class_values, groups); // calculates the gini
            if (gini < b_score[0][0][0]) {
                b_index[0][0][0] = i;
                b_value[0][0][0] = dataset[j][i];
                b_score[0][0][0] = gini;
                b_groups = groups;
            }
        }
    }
    std::vector<std::vector<std::vector<std::vector<float>>>> vals;
    vals.push_back(b_index);
    vals.push_back(b_value);
    vals.push_back(b_groups);
    return vals; // returns the values.
}

int main(void)
{
    std::vector<std::vector<float>> dataset;

    std::vector<std::vector<std::vector<std::vector<float>>>> result = get_split(dataset);

    return fgetc(stdin);
}

```

Now you need to workout where it is crashing, easy in Visual Studio but very difficult on an Arduino. However I would look at simplifying the code too.
> 2 votes

---
Tags: arduino-mega, c++, arduino-ide, vector
---


title: Connect Two Arduino Uno's

text:
# Question
Title: Connect Two Arduino Uno's
Essentially I am looking to build a remote controlled car using dc motors and one arduino uno to be on the car to supply the power logic and i wanted to use another arduino to be the remote. I was curious what the most effective method would be as to pairing these two devices in a way that it would provide the maximum range possible while still maintaining a decently high bandwidth limit. The reason for this is hopefully i can have the arduino mounted to the car connected to a camera where the camera would send a video feed over to the remote control. I was thinking about using a bluetooth module between the two such as a HM-10 but i wouldn't be able to send a video feed this way because bluetooth cannot transmit that much data at once. However if that is the most practical option i can get over the fact of not having a live video feed and send an image ever 5 seconds or so instead of live. Appreciate any insight on what the most effective method would be in terms of efficiency between range and data stream bandwidth.

# Answer
You wouldn't be able process (acquire, store, resize, output) any sensible video signal with the Uno (or any other Atmega-based board). The amount of memory and clock speed is way too low. Peripherals and instruction set are also lacking - no DMA, FPU, DSP instructions. Arduinos barely cope with audio - any kind of video is out of question, except if you want something like a 5fps 32x32 raw feed. Uncompressed, of course.

If you want another hobby-friendly open source solution, I'd look at something with at least an ARM M4 core, with DMA of course. For communication, regular IEEE 802.11 Wifi is your best bet (high throughput) - those 433Mhz RF modules only transmit 4800bps or so.

There may be better solutions, but I've only used stm32f429 for video: they have DMA(2D), display interface (RGB, 8080 memory interface, ...), DCMI (digital camera interface). Wifi could be handled by something like WifiMCU.

You could use the STM32F429DISCOVERY board with LCD for you remote controller, another STM32F4 board with a camera (ex http://hackaday.com/2014/12/04/serial-camera-courtesy-of-the-stm32f4/) and pair them with two WifiMCUs, if You want to do it with off-the-shelf boards.
> 2 votes

# Answer
You can use raspberry pi and computer to send commands and receive video feed
> 0 votes

---
Tags: arduino-uno, motor, bluetooth, wifi
---


# Question
Title: Convert serial value into hex using in Genuino zero
hello there my code is here.

```
/* Simple Serial ECHO script : Written by ScottC 03/07/2012 */

/* Use a variable called byteRead to temporarily store
   the data coming from the computer */
byte byteRead;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(9600);
}

void loop() {
   char a[8];
    int b;
   /*  check if data has been sent from the computer: */
  if (Serial.available())
  {
    /* read the most recent byte */
    byteRead = Serial.read();
    Serial.print(byteRead,HEX);
  }

```

now when i send '12' from terminal, it prints 3132. means it is ASCII value. but i want to print 12. can you help me?? how to do it??

# Answer
> 4 votes
There are several issues with your sketch. The most important is the lack of understanding for the difference between internal and external representation.

The sketch reads a single character from Serial and prints the value as a hexadecimal number. The character is ASCII; a number that represents symbols in our alphabet.

Your goal is to read characters into a string and then convert the string to a number assuming that the string represents a hexadecimal number ('0'..'9' and 'a'..'f' or 'A'..'F').

The sketch should be 1) scan string, 2) parse and convert string to number, 3) print the number.

Scanning the string requires skipping whitespace and then collecting characters until a whitespace.

The sketch could look something like this:

```
void setup() {
  Serial.begin(57600);
  while (!Serial);
  Serial.println(F("Serial started..."));
}

void loop() {
  const size_t BUF_MAX = 16;
  char buf[BUF_MAX];
  char* bp = buf;
  char c;

  // Skip whitespace
  do {
    while (!Serial.available());
    c = Serial.read();
  } while (c <= ' ');

  // Scan token until whitespace
  *bp = c;
  do {
    while (!Serial.available());
    c = Serial.read();
    *++bp = c;
  } while (c > ' ');
  *bp = 0;

  // Print scanned token
  Serial.println(buf);

  // Convert to number and print
  const int BASE = 16;
  long val = strtol(buf, &bp, BASE);
  if (*bp == 0)
    Serial.println(val);
  else
    Serial.println(F("not a number"));
}

```

This allows scan of hexadecimal numbers with possible sign (as defined by `strtol`). By changing the BASE to zero `strtol` will use the notations for base definitions (prefix '0' for octal, '0x' for hexadecimal). Last, please observe the parse error handling provided by `strtol`(\*bp != 0).

Cheers!

# Answer
> 3 votes
To convert Decimal or Integer value to Hexadecimal you can go this way..

```
byteRead = Serial.read();  //Read your value
myValue =  String(byteRead, HEX); //Convert it into Hexadecimal
Serial.println(myValue); //Print in serial Monitor
myValue1 = String(byteRead,DEC); //Convert it ino Decimal
Serial.println(myValue1); //Print in serial Monitor

```

---
Tags: genuino
---


title: Wemos D1 & Relay shield

text:
# Question
Title: Wemos D1 & Relay shield
For one of my hobby projects I would like to use:

to control the `24V` (`19W`) mist maker.

My current wiring is this:

As you can see the both grounds (12V and 5V) are attached to the `com` connector of the power supply.

I wonder whether grounds should be decoupled (for whatever reason) - i.e. to use separate power supplies? If the above wiring is OK I would really like to know in which circumstances (if any) a separate power supplies would be needed.

Thanks for all your answers in advance.

# Answer
That grounding scheme looks right since the Load ground is coupled back to the supply separately from the logic ground.

The only reason you would separate supplies would be to isolate them for safety or other reasons. For example, if the load side was a large or ac voltage.

Isolation requirements vary with application so it is hard to be more specific than that here.
> 3 votes

---
Tags: relay, wires
---


title: Button that increments a counter

text:
# Question
Title: Button that increments a counter
```
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0,0);

}

void loop() {
  uint8_t buttons = lcd.readButtons();
  int a;
  if (buttons) {

    lcd.clear();
    lcd.setCursor(0,0);

    if (buttons & BUTTON_UP) {
      a+= 1;
      lcd.setCursor(0,0);
      lcd.print(a);
    }
  }

```

I am trying to make a counter that increments everytime the button UP is pressed. Currently, all it is doing is printing 1 everytime the button is pressed. Any help would be nice! Thanks!

# Answer
> 4 votes
Your code, simplified, is:

```
void loop()
    int a;
    a += 1;
}

```

The problem here is that, by putting the declaration of your counter variable within the `loop()` function, you've made it local to that function. Every time `loop()` is called, a new variable `a` is created, initialized to zero, and then incremented.

You want to move the declaration outside of `loop()`, creating a global variable that will remain in existence and maintain its value after `loop()` exits, so that the value is still there when `loop()` is called again:

```
int a = 0;
void loop() {
    a += 1;
}

```

(This could also be done with a static variable, but that's probably beyond the scope of this question.)

---
Tags: arduino-uno
---


# Question
Title: Why does this sketch give MPU FIFO overflows?
I'm transmitting this program over an NRF24l01, data from mpu, and I'm getting a FIFO overflow. Im not sure what the problem is but it gives me a lag when I put it on processing so I know the problem is in the code. I posted the code the below. Pleas help find the issue.

```
// Include libraries necessary for the radios
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8);

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif

    MPU6050 mpu;

    #define OUTPUT_TEAPOT

    #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    bool blinkState = false;
    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer
    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
    // packet structure for InvenSense teapot demo
    uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

    // ================================================================
    // ===               INTERRUPT DETECTION ROUTINE                ===
    // ================================================================
    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }
    // ================================================================
    // ===                      INITIAL SETUP                       ===
    // ================================================================
    void setup() {
        // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
          //TWBR = 8; // 400kHz I2C clock (200kHz if CPU is 8MHz). Comment this line if having compilation difficulties with TWBR.

        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        radio.begin();

        radio.setRetries(15, 15);
        radio.openWritingPipe(0xF0F0F0F0A1LL);

        radio.stopListening();
        Serial.begin(115200);

        // load and configure the DMP
        Serial.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        mpu.setXGyroOffset(54);
        mpu.setYGyroOffset(15);
        mpu.setZGyroOffset(33);
        mpu.setZAccelOffset(1613); // 1688 factory default for my test chip
        mpu.setXAccelOffset(-4009);
        mpu.setYAccelOffset(332);

        // make sure it worked (returns 0 if so)
        if (devStatus == 0) {
            // turn on the DMP, now that it's ready
            Serial.println(F("Enabling DMP..."));
            mpu.setDMPEnabled(true);

            Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
            attachInterrupt(0, dmpDataReady, RISING);
            mpuIntStatus = mpu.getIntStatus();

            Serial.println(F("DMP ready! Waiting for first interrupt..."));
            dmpReady = true;
            // get expected DMP packet size for later comparison
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {

            Serial.print(F("DMP Initialization failed (code "));
            Serial.print(devStatus);
            Serial.println(F(")"));
        }
        // configure LED for output
        pinMode(LED_PIN, OUTPUT);
    }
    // ================================================================
    // ===                    MAIN PROGRAM LOOP                     ===
    // ================================================================
    void loop() {
        // if programming failed, don't try to do anything
        if (!dmpReady) return;
        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {

          /*Do some computational stuff here*/

        }

        // reset interrupt flag and get INT_STATUS byte
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();
        // get current FIFO count
        fifoCount = mpu.getFIFOCount();
        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
            // reset so we can continue cleanly
            mpu.resetFIFO();

            Serial.println(F("FIFO overflow!"));
        // otherwise, check for DMP data ready interrupt (this should happen frequently)
        } else if (mpuIntStatus & 0x02) {

            // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
            // read a packet from FIFO
            mpu.getFIFOBytes(fifoBuffer, packetSize);

            fifoCount -= packetSize;

                /*Object to Transmit Yaw, Pitch, and Roll*/
                typedef struct YPR_TX {
                  int y;
                  int p;
                  int r;

                } YPR_TX;

                YPR_TX ypr_tx;

             //   ypr_tx = calcYPR(ypr_tx.y, ypr_tx.p, ypr_tx.r);

                ypr_tx.y = ypr[0] * 180/M_PI;
                ypr_tx.p = ypr[1] * 180/M_PI;
                ypr_tx.r = ypr[2] * 180/M_PI;

            #ifdef OUTPUT_TEAPOT
                // display quaternion values in InvenSense Teapot demo format:
                teapotPacket[2] = fifoBuffer[0];
                teapotPacket[3] = fifoBuffer[1];
                teapotPacket[4] = fifoBuffer[4];
                teapotPacket[5] = fifoBuffer[5];
                teapotPacket[6] = fifoBuffer[8];
                teapotPacket[7] = fifoBuffer[9];
                teapotPacket[8] = fifoBuffer[12];
                teapotPacket[9] = fifoBuffer[13];

                Serial.print("teapotPacket/t");
                Serial.print("\t");
                Serial.print(teapotPacket[2]);
                Serial.print("\t");
                Serial.print(teapotPacket[3]);
                Serial.print("\t");
                Serial.print(teapotPacket[4]);
                Serial.print("\t");
                Serial.print(teapotPacket[5]);
                Serial.print("\t");
                Serial.print(teapotPacket[6]);
                Serial.print("\t");
                Serial.print(teapotPacket[7]);
                Serial.print("\t");
                Serial.print(teapotPacket[8]);
                Serial.print("\t");
                Serial.println(teapotPacket[9]);
               // radio.getDataRate();

                radio.write(&teapotPacket, sizeof(teapotPacket));

            #endif

            // blink LED to indicate activity
            blinkState = !blinkState;
            digitalWrite(LED_PIN, blinkState);
        }

    }

```

# Answer
> 1 votes
I have been playing around with the MPU6050 with DMP library too. I see you have used Jeff's example code (as have I). I was getting a lot of FIFO overflows too, but that was because my "do computational stuff here" was taking too long (code with delay()) and the FIFO on the DMP was filling up. Perhaps your radio.write() is taking too long?

The code as written by Jeff is really quite robust, but perhaps not what is necessary in all cases. I have put an extra mpu.resetFIFO() below the Serial.println's. Kind of a hack, but it works. I found the suggestion here:

How to clear FIFO buffer on MPU6050?

Also check on Jeff's own suggestion of lowering the data rate on the DMP by altering the header file:

https://www.i2cdevlib.com/forums/topic/27-fifo-overflow/#comment-99

Hope this helps.

# Answer
> 0 votes
You are declaring a FIFO overflow every time the mpu sends interrupt 0x10. Is that correct?

You are using the value in fifoCount before you have set it to a value. Now with the Arduino IDE you are OK doing that, but its not a good practice.

You are checking that the fifoCount is exactly 1024. It might be better to check if it is \>1023 because that will handle the case when it is 1025.

Is there a reason why you have chosen 1024? Since the packet size defaults to 42 that's 24.3 packets.

Around

```
while (!mpuInterrupt && fifoCount < packetSize) {

```

You never get the fifoCount again, so `fifoCount < packetSize` is always true, therefore you wait until there is an interrupt. If there first time there is an interrupt is to tell you 0x10 (which I guess is) fifo full from the MPU's perspective) then that will be the reason it is always full.

```
   // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {

      /*Do some computational stuff here*/
      fifoCount = mpu.getFIFOCount(); // Don't forget to get the latest fifo size.
    }

```

---
Tags: arduino-uno, nrf24l01+, mpu6050
---


# Question
Title: Connect Multiple L293D Motor Controllers to Arduino
I would like to connect 3 L293D Motor controllers to an Arduino Uno with the hopes of powering 6 different dc motors. I was just wondering how to wire this being that one motor controller (which allows for 2 dc motors to be controlled) already takes up most of the pins on the Arduino, thanks.

Below is the wiring diagram for how I am hooking up 1 L293D motor controllers to the Arduino.

# Answer
The suggestion of using an Adafruit Motor Shield V2 for Arduino seems fairly good, although that particular shield controls only four DC motors at once. That shield has a dedicated PWM driver chip on it, which removes the overhead of motor and speed control from the MCU. That might allow you to drive four motors via the shield, and two via wires from the Arduino; or, stack two motor shields on the Uno.

If you definitely want to drive six motors from the Arduino, you may need to add a couple of control chips. You could add a 74HCT04 hex inverter and a 74LS595, to create inverted drive signals and enable signals. For example, the first PWM drive would go to L293 pin 1A and to '04 pin 1A; the first '04 output, 1Y, would drive L293 pin 2A. One of the '595 outputs would go to L293 pin 1,2EN.

Alternately, you could use two '595s, with outputs to control L293 pins 2A; 4A; 1,2EN; and 3,4EN on each of three L293's. The six PWM outputs from the Uno would go to 1A and 3A on the several L293's. Using motor shields probably is a better idea, however.
> 2 votes

# Answer
If you want to make your own circuit.. then you need two IC 74HCT595(8-bit serial-in, serial or parallel-out shift register). You have to wiring with your arduino and L293D you can go this way..  . This Circuit diagram is an Idea, don't think its actual circuit you have to modify this schematic accroding to your application.

Data Sheet link 74HCT595 DATASHEET
> 2 votes

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