# Question
Title: ard-reset-arduino resetting Leonardo/Micro via USB works on OSX, fails on Ubuntu
I'm trying to program a Leonardo (actually a Micro ATmega32U4) via the command line using USB. Schematically, I'm doing `ard-reset-arduino` followed by a `sleep 1` and an `avrdude` command.

This works reliably on my Mac (OSX 10.12.1, avrdude v6.3), but bombs out on Ubuntu (Ubuntu 5.2.1-22ubuntu2, avrdude v6.1) with the message:

```
.avrdude: butterfly_recv(): programmer is not responding

```

Update: I believe this is actually due to a failure to get the atmega32u4 into the bootloader. See `update` at the bottom of this post...

Has anyone seen this? Any suggestions for debugging strategies or things to try?

### Details on the Mac:

Here is the command line with results under OS X:

```
$ ./ard-reset-arduino --verbose --caterina /dev/cu.usbmodem1411 && sleep 1 && /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -V -D -p atmega32u4 -C /Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -c avr109 -b 9600 -P /dev/cu.usbmodem1411 -U flash:w:./leds_test.ino.leonardo.hex:i
Forcing reset using 1200bps open/close on port /dev/cu.usbmodem1411
/dev/cu.usbmodem1411 has come back after reset

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.
Programmer supports the following devices:
    Device code: 0x44

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: reading input file "./leds_test.ino.leonardo.hex"
avrdude: writing flash (9146 bytes):

Writing | ################################################## | 100% 0.70s

avrdude: 9146 bytes of flash written
avrdude: safemode: Fuses OK (E:CB, H:D8, L:FF)
avrdude done.  Thank you.

```

### Details on Ubuntu:

Here is the command line with results under Ubuntu. Except for the pathnames, all of the options are the same as under OSX:

```
$ /boot/ard-reset-arduino --verbose --caterina /dev/ttyACM0 && sleep 1 && /usr/share/arduino/hardware/tools/avr/../avrdude -V -D -p atmega32u4 -C /usr/share/arduino/hardware/tools/avr/../avrdude.conf -c avr109 -b 9600 -P /dev/ttyACM0 -U flash:w:/boot/leds_test.ino.leonardo.hex:i
Forcing reset using 1200bps open/close on port /dev/ttyACM0
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
/dev/ttyACM0 has come back after reset

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

```

### Postscript

Just to make sure I hadn't borked the bootloader somehow, I moved the Leonardo/Micro back to the OSX and re-ran the reset / programming sequence under OSX. It worked without error, so I conclude that the resident bootloader is intact.

### Update

I believe the real problem is that under Ubuntu, `ard-reset-arduino` fails to put the Leonardo into the bootloader.

Here's why I believe this is the problem: the resident sketch makes the onboard LEDs blink. On the Mac, running `ard-reset-arduino` makes the blinking stop for about 8 seconds. On Ubuntu, the LEDs continue to blink without interruption after the `ard-reset-arduino` command returns.

### Update 2

Here's an even simpler Python program that resets the Leonardo under OSX but not under Ubuntu.

```
#! /usr/bin/python
import sys
import serial

ser = serial.Serial(sys.argv[1], 1200)
ser.close()

```

# Answer
> 0 votes
I'm somewhat embarrassed as to the source of the problem. It wasn't an OSX vs Ubuntu issue.

Rather, on the Ubuntu system, there was an another application that was holding the USB port open, so attempts to reset the Leonardo were failing.

Rather than delete this post out of shame, I'm leaving it here in case someone else stumbles across the same problem.

---
Tags: usb, arduino-leonardo, bootloader, avrdude, reset
---


title: DigitalRead() floating pin problem

text:
# Question
Title: DigitalRead() floating pin problem
I am having a problem implementing a the digitalRead() function in arduino uno.I want digitalRead to return 0 when nothing is connected and return 1 when it is connected to +5 volt.But seems like digitalRead returns random values when it is not connected to anything. I have kind of solved the problem by a small piece of code to stabilize the value i'll attach the code here but if any other solution is avalable..Please help.

The function is as follows:-

```
bool getValue()

{

String k="";

if(digitalRead(3)==HIGH)

k="HIGH";

else

k="LOW";

bool f=true;

for(int i=0;i<1000;i++)

{
String z;

  if(digitalRead(3)==HIGH)

  z="HIGH";

  else

  z="LOW";

  if(k!=z)

  {

    f=false;

    break;

  }

}

if(f==true)

return true;

else

return false;

}

```

# Answer
> 3 votes
The solution is called a *pull down resistor* and it's exactly the same as when you are using a button - the button is what connects the pin to +5V. The pull down resistor (usually around 10kΩ) connected to ground is what makes the pin read LOW at other times.

---
Tags: arduino-uno
---


# Question
Title: Remote temperature sensor system without slave board
I want to build a temperature control network over my house reading data from each room and sending it to the main board for further processing. I need about 6 sensor nodes sending the data over the air to the main node. There are tons of tutorials of making master-slave temperature/pressure etc control systems of 2 Arduino boards communicating via wireless channel. I find it a bit expensive to have a board per sensor node. **Is that possible to build a sensor device without a controller using just a sensor, a battery and a wireless transmitter plus required radio components?** It's ok to send raw data to the main node. Assuming it knows the protocol it will be able to decode the data there from all the incoming channels.

# Answer
As @Majenko said on comment, its possible. One of the choice is ESP8266. Your project has been successfully accomplished, you can check here, here, or here. NSP8266 only needs 3-3.6V (low current) supply voltage.
> 1 votes

# Answer
@Sergey if its cost what's bothering you , there are numerous low-cost options for MCUs. For eg you can club a MSP 430 ( probably \<1$) chip with a cheap RF transmitter which wont burn a hole in your pocket and is absolutely reliable. Wifi modules can be a little expensive and need constant connectivity. So, you have a choice on this.
> 1 votes

---
Tags: wireless
---


# Question
Title: How do I measure watts without a CT clamp?
I'm trying to build an "IoT" project for home that will in effect create a smartplug. I'd like to add the capability to measure the watt usage of the plug (and whatever's connected to it). I'd like to not use a CT clamp for this purpose, and I was hoping someone here can help.

I have a 220 V mains connection and I'd like to measure the watts used by a connected appliance to the smart plug is a small as possible form. CT sensors are too big for this purpose.

Thanks.

# Answer
> 3 votes
You can't use a CT sensor to measure power. CT sensors measure current. Measuring Watts is the correct unit if you want to know the rate of energy consumption (power) from an outlet.

*Response to a Comment: There are consumer devices that cost only $12.95 that might be ideal, if the only usage scenario is to compare various devices for steady state power draw and you are fine with 3% (1.5 digit) accuracy. For the 220 VAC (whether split phase or single phase) you would need to gang two of them together appropriately. These plug-outlet designs are nicely miniature, but will not support checking past values, providing feedback to a control system, or Wattage plotting against date, time of day, or tay of week.*

Measuring of Wattage accurately (to two or three significant digits) is not trivial if the 220 Volt source is an AC power grid, thus the length of this answer.

The basic EE formula for power is P=IV for DC, meaning power is the product of current and voltage. But you can't just go with **Watts = 220 X current** and expect any more than one significant digit of accuracy. Grid Voltage may not be a clean sine wave and may vary five or ten Volts under normal conditions.

If you want more than one digit of accuracy, you'll need to calculate RMS (root mean square) power in Watts by sampling both Voltage and current and using the AC principles that extend the simple P=IV relation. I don't know if you have knowledge of what electrical engineers call RMS. In case you don't, the articles in the result set of **This Search** \[1\] may be helpful.

Let's hypothetically say you are considering doing the **work necessary to get the two or three significant digits of accuracy in determining power** consumption. To get a sense of what that would entail, here's some information on doing that properly. You will want to consider line voltage fluctuation, reduce your noise levels, protect your Arduino board from over-voltage, and follow electrical code reasonably well.

The below measurement fixture design is not small, but it could be miniaturized. Unfortunately the design of a miniaturized version is large project FAR outside of the scope of an answer in this forum. You may be one of those that likes the challenge, so I'll share a design for a larger version and leave it to you or other answering parties to think of a miniaturization that meets all these other reasonable goals.

Off the shelf parts to fabricate a full sized power measurement fixture to interface with an embedded board like the Arduino Due, for example:

1. Two electrical boxes
2. A length of electrical conduit at least 50 cm long
3. Electrical hardware to connect the two boxes and secure the AC cord leading to the plog and to the devices being powered.
4. Two lengths of 2-conductor 18 AWG shielded twisted pair cable with at least 500V rating
5. Code compliant AC cabling
6. Wire nuts
7. Box for the buffering circuit
8. A good quality digital Voltmeter with RMS AC as one of the options

Fabricate this way, but using proper code-compliant electrical practices in addition to these basic instructions for the main circuits:

1. Connect the plug to one of the boxes with properly rated AC cord.
2. Connect the two boxes with the conduit and properly rated power and return wires (white and black).
3. Connect the second box to the device
4. In each box, connect the 2 conductors of the shielded twisted pair in parallel to the AC circuit passing through the box with the wire nuts. You must leave the shields of the two twisted pair lengths isolated (not connected to the box or the ground wire in the AC circuit.
5. Bring both twisted shielded pairs into the buffering circuit box.

The buffering circuit would condition each of the two AC voltage in three stages.

1. Surge protector
2. Resistor divider (see other Arduino articles for this)
3. Zener diode to further protect the A-to-D converter on the board

The Zener diode and the resistor divider would drop the voltage from 400 V down to below the max voltage of the Arduino board, which any of the voltages might be relative to the ground potential on the Arduino board under certain conditions. The Arduino Due might be a good choice, because of multiple built in true A-to-D channels and the higher accuracy (digits resolution) than most other Arduino options.

The output of the box for each of the FOUR voltages would be connected to FOUR analog inputs.

* Vph = the hot (black) coming from the plug
* Vpr = the return (white) coming from the plug
* Vlh = the hot (black) going to the load (devices to be powered)
* Vlr = the return (white) going to the load

In the software you would probably want to measure the above four voltages in immediate succession (no delay between the four analogRead calls) every millisecond for a second, which will capture 60 cycles of data in 1,000 samples, enough to get three significant digits of accuracy in your power measurement. The 60 samples of 4 channels can be thought of as 1,000 vectors of 5-dimensional data. The fifth dimension is the time offset in milliseconds.

The software goal would be to calibrate the conversion of the 4 by 1,000 element array of analogRead integers to a 2 by 1,000 element array of doubles that represent instantaneous Voltage and current. Then power in Watts can be calculated from the Voltage-current data set.

When dealing with the 1,000 sample vectors, your loops will start with "for (int index = 0; index \< 1000; ++ index) { ...".

You will need to convert your digital values representing the Voltages coming from your resistor divider to physical units. These are the operations you would do on each sample.

1. V = Cv * (Vph - Vpr)
2. I = (Cih * (Vph - Vlh) - Cir * (Vlr - Vpr)) / R

V and I are the doubles that represent instantaneous Voltage and current respectively.

Cv, Cih, Cir, and R are also doubles. They are the calibration constants to convert the analogRead values to line voltages and currents. A typical way to calibrate their values is to measure the RMS voltages across the three node pairs represented by each subtracted voltage pair in the inner parentheses above and the current, using some constant load. A good load option would be some non-digital device that is fully warmed up and in some steady state.

From the voltages and currents and the digital values acquired from the four analog channels in the Arduino, with some algebra skill, one can determine the scaling factor C for each of the three cases, by dividing: (V1 - V2) / V, where V1 and V2 are the RMS values measured with the digital Voltmeter and V is the calculated RMS voltage from the samples.

R can be calculated by dividing the Voltage and current values V/I in accordance with the principles discussed in the articles referenced above.

Once you have calibrated your measurements for V and I in your block of 60 samples, the articles above give you some direction as to how to calculate your power in Watts RMS in a loop.

\[1\]: Search for "calculating rms watts from samples of voltage and current" via Google.

---
Tags: sensors
---


# Question
Title: How to load page from SD card and still show live data from sensors?
I am just wondering, how can we display page from SD card and still show live data from sensors?

I have web server running on Arduino mega using ethernet shield, in my sketch I am doing client.print to build content of a page being displayed, and refreshing it display live data.

But I can't think of a way how can I load page from SD card and display data from sensors.

# Answer
Based upon this W3C example you can have `w3-include-HTML.js` file with the following contents:

```
function w3IncludeHTML() {
  var z, i, a, file, xhttp;
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    if (z[i].getAttribute("w3-include-html")) {
      a = z[i].cloneNode(false);
      file = z[i].getAttribute("w3-include-html");
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          a.removeAttribute("w3-include-html");
          a.innerHTML = this.responseText;
          z[i].parentNode.replaceChild(a, z[i]);
          w3IncludeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      return;
    }
  }

```

Now you can put this in your `.html` file:

```
<div w3-include-html="generated_data.html"></div>
<script src="w3-include-HTML.js"></script>

```

and then you can use something as:

```
server.on("/generated_data.html", live_data);

```

If you want to be able to use `server.on()` you must include `<ESP8266WebServer.h>` but you can serve the content the way you like. You can examine the `ESP8266WebServer::on()` method source code and adapt it according to your needs or you can just use that method as is.

Everything until now will result with calling the `live_data()` function and inserting it's response into the `div` which has the attribute `w3-include-html="generated_data.html"`.

Now you only need to generate the live data inside the `live_data()` and to send the response:

```
void live_data() {
  String data_from_sensor;

  // read here the data from some sensor and store it in data_from_sensor
  String response = "<h1>Live data</h1><p>The data is: " + data_from_sensor + "some unit</p>";
  server.send(200, "text/html", response);
}

```

And that's it. The live data generated inside `live_data()` will show where was the empty `div` with `w3-include-html` attribute.

Of course, you can have more `div`s with different `w3-include-html` attributes and belonging `server.on()` statements.

There are many ways, this is just an example so you can get an idea from where to start. This code will not update the live data on and on but now that you know the mechanism, you can modify the code to do whatever you like.
> 1 votes

# Answer
This is a variation on Chupo\_cro’s answer... His suggestion to use `XMLHttpRequest()` is definitely the way to go. But unlike his answer, I suggest here to *not* send HTML-formatted data. Just send the raw data as JSON, which is the simplest data format suitable for this job. Since your client computer is likely to be orders of magnitude more powerful than your server, you can offload all the job of presenting the data to the client JavaScript code. Keep your Arduino server minimalist and have it only serve:

* static content (HTML, JavaScript and CSS) from the SD card
* *raw* live data as JSON.

And then let the client handle the presentation of the data in whatever form you like.

Your static Web page would then contain no data and have instead placeholders of the form `<span id="XXX">---</span>`. For example:

```
<p>Rain sensor reading: <span id="rainValue">---</span>,
<span id="rainQuality">---</span> rain<br>
Temperature: <span id="tempCelsius">---</span> °C
/ <span id="tempFahrenheit">---</span> °F<br>
Humidity: <span id="humidity">---</span>%<br>
Dew point: <span id="dewPoint">---</span> °C</p>

```

Your client JavaScript code starts by collecting references to those placeholders:

```
// HTML elements with replaceable content.
var elements = null;

window.onload = function() {
    var getElt = document.getElementById.bind(document);
    elements = {
        rainValue: getElt("rainValue"),
        rainQuality: getElt("rainQuality"),
        tempCelsius: getElt("tempCelsius"),
        tempFahrenheit: getElt("tempFahrenheit"),
        humidity: getElt("humidity"),
        dewPoint: getElt("dewPoint")
    };
    setInterval(requestLiveData, 5000);
};

```

Then the page can be updated from live data simply by filling the `innerHTML` attributes of the elements:

```
function dewPoint(temperature, humidity) {
    return ...;
}

// Update page from live data.
function updatePage(data) {
    elements.rainValue.innerHTML = data.rain;
    elements.rainQuality.innerHTML =
        data.rain < 300 ? "heavy" :
        data.rain < 500 ? "moderate" : "no";
    elements.tempCelsius.innerHTML = data.temperature;
    elements.tempFahrenheit.innerHTML = data.temperature * 9 / 5 + 32;
    elements.humidity.innerHTML = data.humidity;
    elements.dewPoint.innerHTML = dewPoint(data.temperature, data.humidity);
}

```

Notice that the data processing (Celsius → Fahrenheit conversion, dew point calculation, converting the rain reading to words) is now done by the client. The live data is retrieved from the server using Ajax, aka `XMLHttpRequest()`:

```
function requestLiveData() {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState != 4) return;
        if (request.status != 200) {
            alert("Ajax request failed: "
                + "status = " + request.status);
            return;
        }
        var data = JSON.parse(request.responseText);
        updatePage(data);
    };
    request.open("GET", "/live_data");
    request.send(null);
}

```

You may have noticed the last line of the `window.onload` function is

```
setInterval(requestLiveData, 5000);

```

which means the `requestLiveData` function above will be automatically called every 5000 ms.

Now, the only thing your server has to do is answer a request for `GET /live_data` by sending the raw data as "application/json". It should look like this:

```
{"temperature":15,"humidity":48.3,"rain":500,"soilMoisture":22}

```
> 0 votes

---
Tags: programming, library
---


# Question
Title: I want to change my "serial monitor" command to push button command for IR cloning project
```
void loop() {
  char data[6];
  int index = 0;

  delay(1000);  //Serial input seems to need some kind of short delay or the data gets screwed up.

  while (Serial.available() > 0) {            //Loop if there data on the serial line
    if (index < 5) {                          //Make sure we don't overflow
      data[index] = Serial.read();            //Load a character into the string
      index++;                                //Increment the index to get the next character
    }
  }

  data[5]='\0';  //Null terminate the string

  if (strcmp(data, "POWER") == 0){                //If the Arduino receives the POWER signal...
    Serial.println("SENDING SIGNAL!");
    for (int i = 0; i < NumIRsignals; i+=2) {         //Loop through all of the IR timings
      pulseIR(IRsignal[i]*10);              //Flash IR LED at 38khz for the right amount of time
      delayMicroseconds(IRsignal[i+1]*10);  //Then turn it off for the right amount of time
    }
  }                                         //Otherwise do nothing!
}

// This function allows us to PWM the IR LED at about 38khz for the sensor
// Borrowed from Adafruit!
void pulseIR(long microsecs) {
  // we'll count down from the number of microseconds we are told to wait

  cli();  // this turns off any background interrupts

  while (microsecs > 0) {
    // 38 kHz is about 13 microseconds high and 13 microseconds low
   digitalWrite(IRledPin, HIGH);  // this takes about 3 microseconds to happen
   delayMicroseconds(10);         // hang out for 10 microseconds, you can also change this to 9 if its not working
   digitalWrite(IRledPin, LOW);   // this also takes about 3 microseconds
   delayMicroseconds(10);         // hang out for 10 microseconds, you can also change this to 9 if its not working

   // so 26 microseconds altogether
   microsecs -= 26;
  }

  sei();  // this turns them back on

```

# Answer
> 2 votes
1. Identify the code which collects the characters from the serial port. Then remove it.
2. Also remove the line of code which check to see if the correct character sequence was received.
3. Replace the above check with code that tests if a button has been press.

Note:

* Mechanical buttons bounce!
* And software is fast enough to see this as multiple button presses.

Avoid problems by going here and learning how to connect buttons to an Arduino and de-bounce buttons in software.

---
Tags: arduino-uno, ir
---


# Question
Title: How to wire a small quadcopter drone with resistor and breadboard (If possible)?
http://www.instructables.com/id/SpeechVoice-Controlled-Arduino-Drone/?ALLSTEPS

Hi guys!

I am following this project but I do however not have all the items currently at home so I was thinking if there is an optional solution.

I do not have any resistors or a breadboard currently at home so I was wondering if there is an optional solution.

What I have is, arduino uno + arduino mini and hc-05 bluetooth and of course 4 small drone motors. On top of this I have TIP-122 transistors and a l293d motor driver.

Could I somehow make it work with that considering i do not have resistors or a breadboard at home?

I know how to solder of course so if I need to solder wires that is not a problem. I appreciate any help very much!!

# Answer
You need resistors where that article puts them, otherwise you could brownout the whole thing. You may be able to get away without a PCB, at the cost of reduced stability. Find or borrow the three resistors needed for the project, and then I recommend that you order both a large pack of 1% resistors as well as a variety of PCBs when you are able to.
> 1 votes

# Answer
As already pointed out, you won't be able to finish that project without using resistors because your Arduino mini pins at most support 40 mA (as far as I recall - please check the datasheet). Those resistors are there to limit your pin current. (However in that case, 100 ohms is too low, please use 220 ohms for your sake!)

What you can do is:

Other than that, in my opinion, you can get away with not having a breadboard or PCB. Just make sure that the wires in no case touch each other (this thing will be flying and dropping for sure!) or you'll end up burning one of those chips.

Also, keep in mind that if you short that lipo battery, there is a significant risk of fire/toxic gas hazard. So I would try this outside, away from people.
> 1 votes

---
Tags: drone
---


title: How to get the ID of an Arduino?

text:
# Question
Title: How to get the ID of an Arduino?
I use Arduino Pro Mini. As I know, every MCU has a number. Different MCU has different number. How to get it ?

# Answer
Arduino Pro mini is based on Atmega328 which does not have a unique ID. It has only `device signature` which you can read if you turn on `Show verbose output during upload` in Arduino IDE's **File** \> **Preferences**.
> 3 votes

# Answer
Could you be confusing the term micro-chip (often applied to any tiny, programmable electronic device) with the manufacturer named "Microchip" (who make the PIC series of micro-controllers, among many other products)? Microchip (the company) does make a line of products that have individually unique IDs. Most manufacturers do not provide unique IDs in their micro-controller devices, and AVR's Atmega 328 series devices do not have unique ID's.
> 1 votes

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


title: Power issues with RFDuino

text:
# Question
Title: Power issues with RFDuino
I am new to hardware, I have always used plug and play shields to accomplish simple projects. A while back I purchased RGB LED Shutter Shades from Macetech. I got the hacker version thinking I would add a RFDuino and use that to power the glasses and receive commands from my iPhone. I found out that the glasses needed 5v and the RFDuino could only do 3V. So i used a Sainsmart Nano v3 to control the LED's and I added a RFDunio to receive commands from my iPhone, the RFDuino is powered by the Nano.

The issue I am having is that when Im using an external battery pack, the kind you use to charge your phone, I'm guessing the power is not consistent enough and the RFDuino drops its connection to my phone. When I run the glasses using my computers USB port I do not have that problem.

My question: Is there something I can add to my circuit to make this inconsistency with my power stop happening?

# Answer
I am the designer of the RGB Shades and co-own macetech LLC. The RFDuino specifications claim only 18mA on transmit and receive, so there should not be a current draw issue from that module.

Known power issues with the RGB Shades include high current draw on startup. They can pulse about 1.3 amps (the blue flash) before your software sets them to a more reasonable level. Most USB power packs made today can handle 1.0 amps, some can supply more, but it's still common to find packs limited to 500mA...that would be one thing to check.

Since you are using your own code, please also note that our default code on the controller-included RGB Shades sets the maximum brightness to about one-quarter the actual maximum brightness of the LEDs. This is done to conserve power as well as reduce brightness to non-blinding levels. If your code is attempting to operate at normal brightness, please be aware the RGB Shades could draw up to 4 amps.

The best way to detect the problem would be to get a multimeter and compare the supply voltage when connected to your computer and when connected to the USB power pack.
> 2 votes

# Answer
Wireless modules usually draw bursts of big currents in small amounts of time. For example ~1000mA for 1 uS (microseconds). Their overall power consumption can be low, however.

Perhaps, your external battery pack has a low current output which can not supply the burst current that RF module needs, but your PC is sufficient enough.

I would suggest adding capacitors (their size and amount depends, but put some big ones like 10000 uF in parallel and observe) so the burst current is compensated from the capacitors.

Make sure that those battery packs have enough current (hence, power) to power your RF module.

You can always use high rated battery packs such as LiPo's used in RC planes/copters, but be aware, they react badly when shorted so it may not be a good idea to use those batteries on your glasses...
> 0 votes

---
Tags: arduino-nano
---


title: SPFD5408 for TFT in Arduino Due

text:
# Question
Title: SPFD5408 for TFT in Arduino Due
I have interfaced HC024071 TFT Display with Arduino Due using SPFD5408 Adafruit library. It works perfect.

But using the same library with Arduino Due (with pin connections modified as follows):

```
// For the Arduino Uno, Duemilanove, Diecimila, etc.:
//   D0 connects to digital pin 8  (Notice these are
//   D1 connects to digital pin 9   NOT in order!)
//   D2 connects to digital pin 2
//   D3 connects to digital pin 3
//   D4 connects to digital pin 4
//   D5 connects to digital pin 5
//   D6 connects to digital pin 6
//   D7 connects to digital pin 7

```

But unfortunately, errors occur (which made me guess Due is incompatible with the same)

```
Build options changed, rebuilding all
In file included from C:\Users\Arun Baby\Desktop\test\sketch_dec16c\sketch_dec16c.ino:2:0:

sketch\TFTLIB.H: In function 'void Draw_Welcome_Screen()':

sketch\TFTLIB.H:154:36: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Z.A.R.S",55,150,BLUE,3);

                                    ^

sketch\TFTLIB.H:155:59: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Zone Adaptive Response System",25,180,BLACK,1);

                                                           ^

sketch\TFTLIB.H:157:57: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Touch anywhere to continue!",30,280,BLACK,1);

                                                         ^

sketch\TFTLIB.H: In function 'void Draw_Menu()':

sketch\TFTLIB.H:166:48: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Z.A.R.S Main Menu",120,300,WHITE,1);

                                                ^

sketch\TFTLIB.H:168:42: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Driving Mode",20,45,0x1220,2);

                                          ^

sketch\TFTLIB.H:169:46: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Zones Supported",20,135,0x1220,2);

                                              ^

sketch\TFTLIB.H:170:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Settings",20,225,0x1220,2);

                                       ^

sketch\TFTLIB.H: In function 'void Draw_Settings()':

sketch\TFTLIB.H:179:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Settings",160,300,WHITE,1);

                                       ^

sketch\TFTLIB.H:181:43: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Re-Caliberate",20,45,0x1220,2);

                                           ^

sketch\TFTLIB.H:182:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("GPS Lock",20,135,0x1220,2);

                                       ^

sketch\TFTLIB.H:183:34: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("BACK",20,225,WHITE,2);

                                  ^

sketch\TFTLIB.H: In function 'void Manual_Recaliberation()':

sketch\TFTLIB.H:189:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Touchscreen \n   Recaliberation",60,100,WHITE,2);

                                                               ^

sketch\TFTLIB.H:191:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("STEP 1",100,200,WHITE,2);

                                       ^

sketch\TFTLIB.H:192:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Please touch the BLUE dot...",40,250,WHITE,1);

                                                            ^

sketch\TFTLIB.H:198:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Touchscreen \n   Recaliberation",60,100,WHITE,2);

                                                               ^

sketch\TFTLIB.H:200:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("STEP 2",100,200,WHITE,2);

                                       ^

sketch\TFTLIB.H:201:59: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Please touch the RED dot...",40,250,WHITE,1);

                                                           ^

sketch\TFTLIB.H:209:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Touchscreen \n   Recaliberation",60,100,WHITE,2);

                                                               ^

sketch\TFTLIB.H:211:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("STEP 3",100,200,WHITE,2);

                                       ^

sketch\TFTLIB.H:212:62: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Please touch the YELLOW dot...",40,250,WHITE,1);

                                                              ^

sketch\TFTLIB.H:224:61: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Recaliberation \n    Complete",30,100,WHITE,2);

                                                             ^

sketch\TFTLIB.H:227:36: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("BACK",20,225,WHITE,2);

                                    ^

In file included from C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_Adafruit_TFTLCD.cpp:30:0:

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\pin_magic.h:306:33: warning: backslash and newline separated by space [enabled by default]

   #define read8inline(result) { \

 ^

In file included from C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/pins_arduino.h:20:0,

                 from C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:6:

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp: In member function 'TSPoint TouchScreen::getPoint()':

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                 ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:61:21: note: in expansion of macro 'digitalPinToPort'

   uint8_t xp_port = digitalPinToPort(_xp);

                     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                 ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:62:21: note: in expansion of macro 'digitalPinToPort'

   uint8_t yp_port = digitalPinToPort(_yp);

                     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                 ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:63:21: note: in expansion of macro 'digitalPinToPort'

   uint8_t xm_port = digitalPinToPort(_xm);

                     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                 ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:64:21: note: in expansion of macro 'digitalPinToPort'

   uint8_t ym_port = digitalPinToPort(_ym);

                     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:77:4: note: in expansion of macro 'portOutputRegister'

   *portOutputRegister(yp_port) &= ~yp_pin;

    ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:78:4: note: in expansion of macro 'portOutputRegister'

   *portOutputRegister(ym_port) &= ~ym_pin;

    ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:86:4: note: in expansion of macro 'portOutputRegister'

   *portOutputRegister(xp_port) |= xp_pin;

    ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:87:4: note: in expansion of macro 'portOutputRegister'

   *portOutputRegister(xm_port) &= ~xm_pin;

    ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:102:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(xp_port) &= ~xp_pin;

     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:106:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(yp_port) |= yp_pin;

     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:125:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(xp_port) &= ~xp_pin;

     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:129:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(ym_port) |= ym_pin;

     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:133:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(yp_port) &= ~yp_pin;

     ^

```

Is it actually true? Is SPFD5408 completely incompatible with Due? Trying out UTFT Library with Due gave errors and with Uno, Blank white screen.

Is there any library that is compatible with Due then?

# Answer
Yes, that is true. It looks like it tries to do some low-level port manipulation for speed, but it doesn't know how to do that on a Due since it's a completely different beast.

You could always read the datasheet and look at the initialisation code (the hardest part to work out yourself) and roll your own code to control the TFT - it's not actually that hard usually.
> 0 votes

---
Tags: arduino-uno, arduino-due, tft
---


# Question
Title: Detecting a 2.8ms pulse using a Arduino Uno
I am working on a project for knowing the position of a DC motor which has a hall sensor built into it. I am a newbie into programming using the Arduino Uno R3. After some forum search and self checks, I cannot pass this hurdle. I hope I can frame the questions properly here.

My Problem: The DC motor hall sensor sends out 2 high pulse of 11.3V - 13V with a duration of 2.8ms for each revolution. My Arduino interrupt pin doesn't read the high pulse as it gives me "0" count after motor spin (I run 50 loops and results remain the same).

On my breadboard, I use a voltage divider to reduce hall-effect ouput from max 13V to 5V so that the Arduino pin 2 can read rising voltage when it jumps to 5V (low should be 2.5V).

Couple of things I noted during the motor spin -

a) The `millis()` function returns 79-81ms per sketch run

b) The same hall sensor output if connected to analog pin reads 580,590,590,1001, 1012, 580, 580.. etc. I cannot gauge position of the motor by using these values as they are inconsistent on the way up Vs. way down.

I have attached analog readings while going up and down in snap shot below:  2 questions I have:

1. Why is the pin 2 not detecting a high pulse? will it not be able to read 2.8ms durations because of motor speed (9.5 rev/s or 570rpm)?
2. Is it possible to gauge anything from Analog read function? Am I missing something?

Thanks in advance for all responses.. Any questions regarding the circuit, I will be more than happy to post them.

# Answer
> 4 votes
First, better to see whole source and schematics.

"Why is the pin 2 not detecting"

Check: 1. Hall sensor connected to Pin 2

2. pulses variable declared as volatile.
3. Check if internal pull up resistor setup consistent with hall sensor connection.
4. Check that Hall sensor's lowest signal voltage is below 0.3 VCC (you said 5V, so it should drop below 1.5V), BTW 580 - the lowest analog value you showed means 2.83V
5. Check you are not using nointerrupt();

"Is it possible to gauge anything from Analog read function? Am "

Yes. Analog read takes about 0.1 ms in default setup, so should make at least 1000 reads per second to catch peak.

So, Easiest way is to choose some value like 600, when analog read is above mark it as Rising when it drops below mark is Falling. More complicated ways will include some training and hysteresis to improve detection.

Also I suggest to use voltage limiter instead of voltage divider. This gives better detection.

# Answer
> 0 votes
All,

Here is the code:

```
int flag = 1;
int speedo = 255;
          int counter =0; //counts the number of revolutions
          int timeu=0;
          int timed=0;
          int Voltmeasure=0;
          int times=0;
          volatile unsigned int pulses=0; //pulse counter
          bool upcount=false;
          bool downcount=false;
          unsigned int timeold=0;
          int difference=0;

          void count()
          {
            if(upcount==true)
              pulses++;
              else if (downcount==true)
               pulses--;
          }

          void setup()
          {
            // initialize serial communication:
            Serial.begin(9600);
            pinMode(11,OUTPUT);
            pinMode(12,OUTPUT);
            pinMode(13,OUTPUT);
            pinMode(2, INPUT);
            pinMode(3, INPUT);
            attachInterrupt(digitalPinToInterrupt(2),count, RISING);
          }
          void stopmotor()
          {
            digitalWrite(12,HIGH);
            digitalWrite(13,HIGH);
          }
          void motorCCW()
          {
            analogWrite(11,speedo);
            digitalWrite(12,HIGH);
            digitalWrite(13,LOW);
          }
          void motorCW()
          {
            analogWrite(11,speedo);
            digitalWrite(12,LOW);
            digitalWrite(13,HIGH);
          }

          void loop()
          {
              if(flag==1)
              {
                delay(2000); //wait for 2 seconds to start motor
                flag=2;
              }

            //first run motor moves down
                if (counter<16 && flag==2)
                {
                  motorCW(); //moving up

                  //Reading Hall-sensor pulses- using analog signal
                  Voltmeasure = analogRead(A3);
                  Serial.print("CW Voltmeasure = ");
                  Serial.print(Voltmeasure);
                  Serial.println();

                  //Reading Hall-sensor pulses - using interuppt signal
                  upcount=true;

                  //counting the number of high pulse
                  if (Voltmeasure>700 && times==0)
                  {
                    counter++; times=1;
                  }
                  else if (Voltmeasure<610)
                    times=0;

                  //timer for number of loops
                  timeu++;
                  Voltmeasure=0;

                  if (timeu==70||counter==16) //move by 70 cycles or until counter is 16
                  {
                    stopmotor();
                    upcount=false;
                    timeu=0;
                    times=0;
                    Serial.print("High-point is reached - Travel complete");
                    Serial.println();
                    delay(2000); //delay by 2 seconds
                    flag=3;
                  }
                }

                if (counter>0 && flag==3)
                {
                  delay(2000); //pause before next run
                  motorCCW();

                  //Reading Hall-sensor pulses - using analog signal
                  Voltmeasure = analogRead(A3);
                  Serial.print("CCW Voltmeasure = ");
                  Serial.print(Voltmeasure);
                  Serial.println();

                  //Reading Hall-sensor pulses - using interuppt signal
                  downcount=true;

                 //counting the number of high pulse
                  if (Voltmeasure>700)
                  {
                    counter--; times=1;
                  }
                  else if (Voltmeasure<610)
                    times=0;
                  timed++;
                  Voltmeasure=0;

                  if (timed==70||counter==0) //move by 70 cycles or until counter is 0
                  {
                    stopmotor();
                    downcount=false;
                    timed=0;
                    times=0;
                    Serial.print("Lowest point is reached - Travel complete");
                    Serial.println();
                    flag=3;//stop motor
                  }
                 }

          //  difference=millis()-timeold;
          //  timeold = millis();
          //
          //  //Printing information after line complete
          //  Serial.print("time for one sketch = ");
          //  Serial.print(difference);
          //  Serial.println();

            Serial.print("Counter = ");
            Serial.print(counter);
            Serial.println();

            Serial.print("pulses = ");
            Serial.print(pulses);
            Serial.println();

          }

```

General block diagram

Motor with Hall sensor, Ve is 13V, Ue is 13.5V:

I print the counter (Analog pin) and pulses (interrupt pin) with running this program code.

The Analog pin reads:

CW Voltmeasure = 574

CW Voltmeasure = 588

CW Voltmeasure = 1000

CW Voltmeasure = 999

CW Voltmeasure = 998

CW Voltmeasure = 1002

CW Voltmeasure = 1002

CW Voltmeasure = 589

CW Voltmeasure = 588

CW Voltmeasure = 590

CW Voltmeasure = 588

CW Voltmeasure = 1000......by this time motor spins 6.5 rev (based on time elapsed) but counter is only @ 3 (3 highs)

Pulses read 0.......

This is where i am at. Not able to understand Analog readings dont match the number of revs with the highs & why interupt pin reads 0......

# Answer
> 0 votes
I tried modifying the voltages to interrupt pins

Now interrupt pin voltages read: High:1.456V Low: 1.07V

Note: The arduino is running at 12V external source.

My "pulses" counter still reads 0 for interrupts. Any idea why?

# Answer
> 0 votes
All,

My Arduino is not reading interrupts across the interrupt pin:

I am getting a high of 1.456V and a low 1.07V through the interrupt pin 2... But the pulses counter still remain 0....

Any idea why?

```
  volatile unsigned int pulses=0; //pulse counter
  volatile int8_t steps=0;
  int timeu=0;
  int flag=2;

  void count()
  {
    pulses++;
  }

  void setup()
  {
    // initialize serial communication:
    Serial.begin(9600);
    pinMode(11,OUTPUT);
    pinMode(12,OUTPUT);
    pinMode(13,OUTPUT);
    pinMode(2,INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(2),count,RISING);

  }

  void stopmotor()
  {
    digitalWrite(12,LOW);
    digitalWrite(13,LOW);
    steps=0;
  }
  void motorCCW()
  {
    analogWrite(11,255);
    digitalWrite(12,HIGH);
    digitalWrite(13,LOW);
    steps=-1;
  }
  void motorCW()
  {
    analogWrite(11,255);
    digitalWrite(12,LOW);
    digitalWrite(13,HIGH);
    steps=1;
  }

  void loop()
  {

    if (timeu<=1000)//First time - Going up
    {
        sei();
        motorCW(); //moving up
        flag=8;
        timeu++;
      }
    else if (timeu==1000)
      {
          flag=10;
          stopmotor();
          cli();
          //Serial.print("Completed time cycle of 50");

      }

  if (flag==10)
  {
    Serial.print("pulses = ");
    Serial.print(pulses);
    Serial.println();

  }

  }

```

# Answer
> 0 votes
All,

I didnt need the voltage comparator in the end, the code was running slower and wasnt picking up all the hall sensor signals that the motor was giving due to loop time. i changed the ifs to else ifs and then i was able to get a faster loop time.

Thanks all for the help.

The device is working as intended..

---
Tags: arduino-uno
---


title: Cannot run arduino as web client

text:
# Question
Title: Cannot run arduino as web client
I have ethernet shield mounted on arduino mega, I am able to run it as server but when i try to run it as client it doesnt work , most of the time it assigns itself `255.255.255.255` ip address which i get to know as i am printing from my sketch using `Ethernet.localIP()` it sometimes randomly works but then it does nt establish connection with server, I have double checked there is no firewall on my router that can block arduino ethernet web client.

```
#include "Ethernet.h"
#include <SPI.h>
#include<dht.h>
dht DHT;

#define DHT11_PIN 8

double tempInC;
int humidity;

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
//IPAddress ip(192, 168, 1, 177);

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,1,177);

byte subnet[] = { 255, 255, 255, 0 }; //assigning subnet mask
byte gateway[] = { 192, 168, 1, 1 }; //assigning gateway

EthernetClient client;
char server[] = "192.168.1.3"; // IP Adres (or name) of server to dump data to

String data;

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

  while (!Serial) {
    ; //wait for serial port to connect. Needed for native USB port only
  }
  Ethernet.begin(mac, ip, gateway, subnet);

  Serial.print(F("connected. My IP is "));
  Serial.println(Ethernet.localIP());
  // give the Ethernet shield a second to initialize:
  delay(1000);
  data = "";
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  delay(200);
  tempInC = DHT.temperature;
  humidity = DHT.humidity;
  Serial.print("Temp: ");
  Serial.print(tempInC);
  Serial.print(" Humidity: ");
  Serial.println(humidity);
  if (client.connect(server, 80)) {

    // Make a HTTP request:
    client.print(F("GET /arduino/add.php?temp1="));
    client.print(tempInC);
    client.print(F("&hum1="));
    client.print(humidity);
    client.println(F(" HTTP/1.1"));
    client.print(F("Host: "));
    client.println(server);
    client.println(F("Connection: close"));
    client.println();

  }
  else {
    Serial.println(F("connection failed"));
  }

  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  else {
    Serial.println("Client not available");
  }
  if (client.connected()) {
    client.stop();  // DISCONNECT FROM THE SERVER
  }
  //  delay(60000); // WAIT FOR A MINUTE BEFORE SENDING AGAIN
  delay(10000);
}

```

Here is the output of what I get from above sketch

```
connected. My IP is 255.255.255.255
Temp: 26.00 Humidity: 63
connection failed
Client not available

```

Even when it gets correct IP assigned which I am setting up in the sketch the connection to server fails. I am very upset not being able to run client. Please help.

# Answer
> 2 votes
This could be an SD card SPI bus issue.

Note that because the W5100 and SD card share the SPI bus, only one can be active at a time. If you are using both peripherals in your program, this should be taken care of by the corresponding libraries. If you're not using one of the peripherals in your program, however, you'll need to explicitly deselect it. To do this with the SD card, set pin 4 as an output and write a high to it. For the W5100, set digital pin 10 as a high output.

> Check the Arduino shield datasheet.

Changing pin mode:

```
pinMode(4, OUTPUT);
digitalWrite(4, HIGH);

```

# Answer
> 0 votes
I don't *know* what the problem is, but I can see some issues with your code. Perhaps fixing them will make it work, or at least get you closer.

Reading between the lines in your code, it looks like you are expecting an IP address from DHCP. You won't get that, according to the documentation because you are specifying one. Just so that you know.

You're calling the four-parameter version of `Ethernet.begin()` but using an invalid set of parameters. You're probably meaning to use one of these:

```
Ethernet.begin(mac, ip, dns, gateway);
Ethernet.begin(mac, ip, dns, gateway, subnet);

```

or if you want to use DHCP (which I'd recommend, if you can, because managing them yourself is a pain), just use

```
int success == Ethernet.begin(mac);
if (success) { /* it worked */ }

```

Lastly -- and this is a guess -- I wonder if adding a `delay(1000)` after `Ethernet.begin()` would change the behaviour. It's not really a solution, but it might help you debug.

---
Tags: arduino-mega, ethernet, web
---


# Question
Title: How to merge HCSR04 code with DF Player mini mp3
As the title says, I have a problem to merging the HCSR04 code with DF Player mini mp3 codebases so that they are working together in the one sketch.

The idea is when the ultrasonic sensor reads a certain range, it will trigger a specific mp3 files via the DF player.

I'm using 5 Ultrasonic sensors, and I wanted each sensors to trigger different mp3 files.

***Ultrasonic code:***

```
int trigPin1=2;
int echoPin1=3;

int trigPin2=4;
int echoPin2=5;

int trigPin3=6;
int echoPin3=7;

int trigPin4=8;
int echoPin4=9;

int trigPin5=10;
int echoPin5=11;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(trigPin3, OUTPUT);
  pinMode(echoPin3, INPUT);
  pinMode(trigPin4, OUTPUT);
  pinMode(echoPin4, INPUT);
  pinMode(trigPin5, OUTPUT);
  pinMode(echoPin5, INPUT);

}

void loop() {
  long duration1, distance1;
  digitalWrite(trigPin1, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = duration1/58;

long duration2, distance2;
  digitalWrite(trigPin2, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin2, LOW);
  duration2 = pulseIn(echoPin2, HIGH);
  distance2= duration2/58;

long duration3, distance3;
  digitalWrite(trigPin3, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin3, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin3, LOW);
  duration3 = pulseIn(echoPin3, HIGH);
  distance3= duration3/58;

  long duration4, distance4;
  digitalWrite(trigPin4, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin4, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin4, LOW);
  duration4 = pulseIn(echoPin4, HIGH);
  distance4= duration4/58;

  long duration5, distance5;
  digitalWrite(trigPin5, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin5, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin5, LOW);
  duration5 = pulseIn(echoPin5, HIGH);
  distance5= duration5/58;

  Serial.print (distance1);
  Serial.print (",");
  Serial.print(distance2);
  Serial.print(",");
  Serial.print(distance3);
  Serial.print(",");
  Serial.print(distance4);
  Serial.print(",");
  Serial.print(distance5);
  Serial.println(",");
  delay(100);

}

```

***DF Player code:***

```
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

SoftwareSerial mySoftwareSerial(12, 13); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

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

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(10);  //Set volume value. From 0 to 30
}

void loop()
{
  static unsigned long timer = millis();

  if (millis() - timer > 2000) {
    timer = millis();
    myDFPlayer.next();  //Play next mp3 every 3 second.
  }

  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }
}

void printDetail(uint8_t type, int value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }

}

```

# Answer
I've refactored it a bit, to remove the need to repeat the same code, 5 times, for 5 sensors.

```
#include "Arduino.h"
#include "SoftwareSerial.h"

#include "DFRobotDFPlayerMini.h"

const byte SENSOR_COUNT = 5;
byte triggerPins[SENSOR_COUNT] = {2,4,6,8,10};
byte echoPins[SENSOR_COUNT]    = {3,5,7,9,11};

SoftwareSerial mySoftwareSerial(12, 13); // RX, TX

DFRobotDFPlayerMini myDFPlayer;

void printDetail(uint8_t type, int value);

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

  for( byte i=0; i<SENSOR_COUNT; i++ )
  {
    pinMode(triggerPins[i], OUTPUT);
    pinMode(echoPins[i], INPUT);
  }

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(10);  //Set volume value. From 0 to 30

}

int currentSound = -1;
void loop()
{

  for( byte i=0; i<SENSOR_COUNT; i++ ) // loop through all distance sensors
  {
    if( detectPresence(i) ) // check if there is an object near it
    {
      if(currentSound!=i) // check that it's a different sensor than the one that was last triggered
      {
        Serial.print("play song number ");
        Serial.println(i);
        myDFPlayer.play(i+1); // play song nr `i+1`
      }
      currentSound = i;
    }
  }

  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }

}

// detectPresence will return TRUE if there is an object close to it.
bool detectPresence(byte sensorNr)
{
  if( sensorNr>=SENSOR_COUNT )
    return false;
  long duration, distance;
  //digitalWrite(triggerPins[sensorNr], LOW);  // Added this line
  //delayMicroseconds(10); // Added this line
  digitalWrite(triggerPins[sensorNr], HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(triggerPins[sensorNr], LOW);
  duration = pulseIn(echoPins[sensorNr], HIGH);
  distance = duration/58;

  return distance<30;// choose your own value here, from which distance it should trigger a sound
}

void printDetail(uint8_t type, int value){

  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }

}

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Why do I get access denied when I do have mysql root user added to grant all privileges?
I am using the below mysql example sketch to upload data directly to mysql db.

```
#include "SPI.h"
#include "Ethernet.h"
#include "sha1.h"
#include "mysql.h"

/* Setup for Ethernet Library */
byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 1, 177);
IPAddress server_addr(192, 168, 1, 3);
//char server_addr[] = "192.168.1.3";

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference

char user[] = "root";
char password[] = "secret";
char INSERT_SQL[] =
 "INSERT INTO test_arduino.hello VALUES ('Hello, MySQL!', NULL)";

void setup() {
  Ethernet.begin(mac_addr, ip);
  Serial.begin(9600);
  delay(1000);
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password))
  {
    delay(500);
    Serial.println("Connection Successfull,inserting to database.");
     /* Write Hello, World to MySQL table test_arduino.hello */
     my_conn.cmd_query(INSERT_SQL);
     Serial.println("Query Success!");
  }
  else
    Serial.println("Connection failed.");
}

void loop() {
}

```

I am getting the error in serial Monitor:

> Connecting...
>
> Error: 76 = Access denied for user 'root'@'192.168.1.177' (using password: YES).
>
> Connection failed.

even when I have all prvialages on `root` user for the ip of client !

```
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.177';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT host FROM mysql.user WHERE User = 'root';
+---------------+
| host          |
+---------------+
| 127.0.0.1     |
| 192.168.1.177 |
| ::1           |
| localhost     |
| raspberrypi   |
+---------------+
5 rows in set (0.00 sec)

```

I ran the following query :

```
mysql> SELECT SUBSTRING_INDEX(USER(), '@', -1) AS ip,  @@hostname as hostname, @@port as port, DATABASE() as current_database;

```

and got the below result !

```
+-----------+----------+------+------------------+
| ip        | hostname | port | current_database |
+-----------+----------+------+------------------+
| localhost | ceres    | 3306 | test_arduino     |
+-----------+----------+------+------------------+
1 row in set (0.00 sec)

```

however I am trying to access the test\_arduino database from a different IP other than the one mentioned above, does that mean where it says localhost, it is supposed to have `192.168.1.177` as well ? if so How do I insert ip to database `test_arduino` ?

then what am I missing ? please help.

# Answer
I finally figured out

By default it may proabbly have an IP address `127.0.0.1` bind to the `3306` port . This won't let your Arduino Ethernet shield connect to mysql server running on a different machine. In my case, I have mysql server running on raspberry pi 3, and it has IP `192.168.1.145`. So for arduino to push directly to databse on remote mysql server, you should have mysql server IP `192.168.145` bind to `3306` port of mysql server running on it. So that MySQL server is visible to remote client on local network on which your arduino Ethernet shield is connected to via LAN. Then you login to mysql server , and create a user :

```
CREATE USER 'myuser'@'192.168.156' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

```

then you grant privileges as shown below.

```
GRANT ALL ON *.* TO 'myuser'@'192.168.156';
GRANT ALL ON *.* TO 'myuser'@'%';

```

Important Note: the ip address shown in above mysql queries `192.168.156` is the ip address of my ethernet client establishing connection with database on mysql remote server.

Thats it.
> 1 votes

---
Tags: arduino-mega, ethernet
---


title: Random analog input

text:
# Question
Title: Random analog input
I'm trying to build a midi controller that takes the input from a photoresistor and a reed switch anemometer and outputs midi signal.

I've constructed the circuit as in the diagram below but when I test the inputs I receive only random numbers from analog input 3. I get a clear signal on A5.

I'm confused as to what's going on. I've seen other solutions to this problem mention the circuit not being grounded properly but as far as I can see I have the correct grounding.

# Answer
> 1 votes
Random numbers usually mean that the pin is floating (i.e. not touching anything)

You need to check your connections to A3.

Try this:

* Remove the LDR and R6. Check their resistance using multimeter. (To see if they are not burnt etc.)
* Connect R6 to its place. You should get 0 V (0) because R6 is connected to GND.
* Remove R6 and put it in place of LDR. Now, you should be seeing 5V (1024) on A3.
* After you complete this for R6, try it with using LDR only. You should see same results (Make sure LDR has some light on it to lower its resistance)
* Put everything back in place. You should not be seeing random values because now everything is properly connected.

If you are still seeing random values, then that LDR may be disfunctional. Get another one.

Oh and one more thing, make sure LDR illumination does not change while you're getting readings.

---
Tags: arduino-uno, electronics
---


# Question
Title: Arduino using Ethernet shield WebClient example code is not working
I'm using an Arduino Uno and Ethernet shield with the WIZnet chip W5100. The WebServer code example is working. DHCP is working, the Ethernet shield is receiving an IP address from the Linksys modem "router" and everything is fine.

But I cannot connect to a web site using the WebClient code. I found out that `client.connect(server, 80);` is returning -1 "Time\_OUT" and it is supposed to return 1 according to the Arduino Ethernet library.

I tried connecting to different websites. I tried assigning an IP address manually, not using DHCP. I tried making pin 4 of the SD memory card SPI to output `pinMode(4, OUTPUT); digitalWrite(4, HIGH);` But it doesn't work. I get on my Serial line connection failed or it returns "connected" then "Disconnecting..." immediately after because `client.connect` has returned -1.

The example code I'm using:

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x28, 0xAD, 0xBE, 0xEF, 0xB9, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 1, 177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

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

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:

  Serial.println("connecting...");
  delay(2000);
  Serial.println(Ethernet.localIP());

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.print(client.connect(server,80));
    Serial.println();
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

```

This is my output:

Using a local server IP address like my router's IP address, the connection works. But the issue is mainly in the WAN. Any help would be appreciated.

# Answer
This doesn't look right:

```
if (client.connect(server, 80)) {
    Serial.print(client.connect(server,80));
    ...

```

If the first call to `client.connect()` succeeds, you call it again immediately, and the error message you're seeing comes from that second call. This really is not surprising — I can't imagine a scenario in which that would actually work.

What you really want is something more like:

```
if (result = client.connect(server, 80)) {
    Serial.print(result);
    ...

```
> 1 votes

# Answer
I resolved my problem:

The problem was in the mac address itself. When i used the mac address given by the example itself the connection didn't fail and `client.connect()` returned 1.

I used this mac address instead of the one in the code above:

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

```
> 0 votes

---
Tags: ethernet
---


title: I can't receive a letter using UART

text:
# Question
Title: I can't receive a letter using UART
I wrote a simple program where I transmit and receive a letter via UART. The transmit function works 100% but the receive interrupt function doesn't work at all... Can someone adjust the receive interrupt function so I can receive a string instead of a char?

```
#define FOSC 16000000 // Clock Speed
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1

void setup() {
  USART_Init(MYUBRR);
  interrupts();
}

void loop() {
}

void USART_Init(unsigned int ubrr) {
  /*Set baud rate */
  UBRR0H = (unsigned char)(ubrr>>8);
  UBRR0L = (unsigned char)ubrr;
  UCSR0B = (1<<RXEN0)|(1<<TXEN0);
  //Enable receiver and transmitter */
  UCSR0C = (1<<USBS0)|(3<<UCSZ00);
  /* Set frame format: 8data, 2stop bit */
  UCSR0A |= (1 << RXCIE0);
  UCSR0C=0;
}
void USART_Transmit(unsigned char data) {
  /* Wait for empty transmit buffer */
  while(!( UCSR0A & (1<<UDRE0)));
  /* Put data into buffer, sends the data */
  UDR0 = data;
}

ISR(USART__RXC_vect) {
  char ReceivedByte;
  ReceivedByte = UDR0;
  // Fetch the received byte value into the variable "ByteReceived"
}

```

# Answer
> 1 votes
> ```
> ISR(USART__RXC_vect)
> {
>   char ReceivedByte;
>   ReceivedByte = UDR0;
> // Fetch the received byte value into the variable "ByteReceived"
> }
>
> ```

`USART__RXC_vect` is not the name of the interrupt vector, `USART_RX_vect` is.

If you don't get the name right there is no compiler warning, however the interrupt routine is not called.

---

> ```
> UCSR0A |= (1 << RXCIE0);
>
> ```

That line is wrong. `RXCIE0` is in `UCSR0B` not `UCSR0A`. If you set the bit in the correct register you will get an interrupt.

---
Tags: arduino-uno, interrupt, uart
---


title: I2C and SPI at the same time?

text:
# Question
Title: I2C and SPI at the same time?
I would like to ask a question relating to the following communication setup:

STM32 -- Arduino Pro Mini -- ADNS3080 sensor

The interface between STM32 -- Arduino is I2C and the interface between Arduino Pro Mini--ADNS3080 is SPI.

I have tested the communication between the STM32 and the Arduino Pro Mini, and between the Arduino Pro Mini and the ADNS3080 sensor. Both of them work fine; I can successfully send and receive data in both cases.

Now, I want to read the register of the ADNS3080 sensor using the STM32. First, I start an I2C communication between the STM32 and the Arduino Pro Mini, then I send the register address of the ADNS3080 to the Arduino Pro Mini. The Arduino Pro Mini reads the register address and in the same function starts a communication, using SPI, with the ADNS3080 sensor.

But I receive I2C errors in the STM32. Is it possible to use I2C and SPI at the same time? Do I have to introduce delays between the I2C and SPI commands?

Regards, Ali

# Answer
> is it possible to use I2C and SPI at the same time?

Yes it is. Both are implemented in hardware in the chip. They can operate "in the background" and raise an interrupt when there is something to do.

> Do I have to introduce delays between the I2C and SPI commands?

No you don't.
> 6 votes

# Answer
Your Arduino code probably needs to implement clock stretching as an i2c slave. This tells the master to chill for a little while as the slave does some work to get an answer.
> 2 votes

---
Tags: i2c, spi
---


# Question
Title: How do I control arduino uno multiplexed digital pin (using HC74595)
**Edit:**

***I moved the whole initial post to avoid misunderstanding and confusing everyone, sorry***

after all the reading i came up with this:

this is my code for ultrasonic sensor that going into digital pins in my arduino:

```
int trigPin1=2;
int echoPin1=3;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
}

void loop() {
  long duration1, distance1;
  digitalWrite(trigPin1, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = duration1/58;

  Serial.print (distance1);
  Serial.print (",");
  delay(100);
}

```

and this is the idea i wrote to set the "extra digital outputs" on the 595 chip:

```
int DS_pin = 8;
int STCP_pin = 9;
int SHCP_pin = 10;

void setup()
{ // put your setup code here, to run once:
  pinMode(DS_pin, OUTPUT);
  pinMode(STCP_pin, OUTPUT);
  pinMode(SHCP_pin, OUTPUT);
  writereg();
}

bool registers[8];

void writereg()
{
  digitalWrite(SHCP_pin, LOW);

  for (int i = 0; i<=7; i++)
  {
    digitalWrite(STCP_pin, LOW);
    digitalWrite(DS_pin,registers[1]);
    digitalWrite(STCP_pin, HIGH);
  }
    digitalWrite(SHCP_pin, HIGH);
}

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

}

```

now if you guys have a little time to check it, and tell me what should i wrote so the ultrasonic sensor will be working with the 595 chip's outputs?

Let say im going to put the Trigger pin into Q0 and Echo pin into Q1

thanks in advance

# Answer
> 0 votes
It is good that you are thinking of abstraction in order to simplify programming. Simplifying programming by using familiar names makes it easier to understand the code.

In your example:

```
int triggerPin=2
pinMode(triggerPin, OUTPUT)

```

..you are abstracting the actual pin used to trigger the ultrasound by calling it by a familiar name "triggerPin". You could have just as easily wrote the same code as:

```
pinMode(2, OUTPUT)

```

Now you are asking how to abstract the pins when connecting the Arduino to the 74HC595. The truth is, you don't have to. But to make it easier to write & read the code you can use what ever names make sense to you. In this example of connecting an Arduino to a 74HC595 there are 3 Arduino pins connected to the 74HC595. They called them "dataPin", "latchPin" and "clockPin". If these make sense to you use these names.

> Add: can i address the output like this?
>
> ```
>  #define LED_PIN     Q1
>
> ```

No, nothing knows what "Q1" is. Remember, you are adding this hardware to the Arduino. So nothing, not the compiler nor a library, knows about the hardware you added let alone a pin called Q1 on the added hardware.

First you need to understand how to set Q1 through Q8. Refer to the 74HC595 Arduino tutorial linked to above. Inspect the example programs. Once you understand how to set / un-set Q1 through Q8, you can decide if you what to simply shift out a number or if you want to use abstraction giving names to the shift register output pins.

If I were only writing patterns, for example lighting up 8 LEDs, I would stick to numbers. However, if I were controlling different things, for example a light, a motor & a buzzer, I would assign each a unique name and build my program around the names.

---
Tags: arduino-uno, multiplexer
---


# Question
Title: Can I use a HC-05 and a GPS without a breadboard on a Arduino Uno?
I was wondering if I can use a GPS (in my case a U-BLOX) and a hc-05 at the same time connected to a arduino uno without a breadboard? I have tried my GPS on the arduino uno alone and it works very good. Now my question is, can I add a hc-05 on the board directly and put the VCC on the empty 5v?

I put together a schematic of what I had in mind below:

Would this schematic work or would I need a breadboard?

# Answer
I don't see why not. The breadboard is just something to help you prototype yuproect, in the end, your project should always be on a perfboard or a custom PCB.

Note that some male-female header might get handy.

I'm not sure that the HC05 can handle 5V though. You migh want to check.
> 1 votes

---
Tags: gps, hc-05
---


title: Arduino Uno Bluetooth connection

text:
# Question
Title: Arduino Uno Bluetooth connection
I'm trying to connect two Arduino Unos with Bluetooth modules (HC-06 and HC-05). Does anyone know the steps required to do that?

I still haven't figured out:

* How to pair the two Bluetooth devices, and;
* How to pair each Bluetooth with each Arduino.

If you have any useful tutorials, please let me know.

# Answer
> 2 votes
There is a nice example for Arduino here.

Connecting 2 Arduinos by Bluetooth using a HC-05 and a HC-06: Pair, Bind, and Link

The Uno works the same way as the board in the example.

Arduino 1

Arduino 2

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


# Question
Title: Minimum circuitry required to program an AVR
Where is the information what is the minimum-required circuitry to program any AVR via ICSP?

Sometimes I see schematics that show just the chip and the six wires for the ICSP header (RESET, VCC, GND, MISO, MOSI, and SCK).

Other times, I see some passive components connected to some of the pins.

So why is it different some times? How do people know when to use extra components when wiring up the chip for programming? Do the datasheet for these MPU's provide the details?

# Answer
> 2 votes
I have a page about a minimal board. The minimal circuit is the chip itself, and a couple of decoupling capacitors. A pull-up on /RESET is advisable (however the processor has a weak pull-up on it).

The six wires you mention are required for ICSP programming. An example from my page is:

That is using an Arduino as an ICSP programmer.

I think most designers would mandate the decoupling capacitors. You may get away without the pull-up on /RESET but probably at the expense of reliability.

The wires changed colour between the two photos because my earlier board (shown second) had the capacitors further away from the chip pins than they should have been. They really should be next to the chip for maximum effectiveness.

---

Note that, depending on the fuses, you may need to supply an external clock. In my case I did it like this:

The default chip fuses (from the manufacturer) does not require a crystal.

---
Tags: programming, icsp
---


# Question
Title: Options for measuring position of garage door
I'd like to be able to measure the position of my garage door. Determining if the garage door is fully open or fully closed should be fairly simple with some magnetic reed switches but I'd like to know the position of the door when it's partially open/closed.

# Answer
A couple of possibilities occur to me. One would be to mount a rotary encoder on a rotating part of the door. Another would be to attach a reed switch to the track and a series of magnets to the door. I suppose you could do something with a proximity sensor as well.

How much precision do you need in the position of the door? What do you know that is deterministic? For example is the door transit time predictable? Is it a positive drive? Do you get to know when the door starts moving? That might be enough right there.

If you can say more about what you're trying to do it would make it easier to provide suggestions and insight.
> 2 votes

# Answer
I would suggest an Ultrasonic Range Finder. There is an example in the Arduino Tutorials and they are available cheaply on ebay.
> 2 votes

# Answer
A linear encoder (usually comprising an LED, a photodetector, and an encoder strip with black lines on it) would work, but a long encoder strip is expensive and probably not reliable a garage environment. You could use a radial encoder attached to the motor, but that is probably too expensive too and overkill for your application.

Ranging devices are often difficult to use with something narrow and dirty like the bottom edge of a garage door. Placing devices on the door itself is probably not the most reliable and inexpensive way to do this either.

**A Solution for Any Large Spring Loaded Position Sensing**

One way that can be very reliable and is inexpensive is to use two strain gauges. In spite of the low cost, this approach is used in many industrial and laboratory arrangements. You could use an IN114 or a similar 8-pin dip instrument amplifier to convert the differential strain gauge resistance to a Voltage within the range of the Arduino analog input.

I'd guess a cost around $100 with shipping for the IN114, the rest of the circuit, strain gauges, emery cloth, bonding cement, temperature sensor (optional), power supply, jacks, solder, circuit housing, PCB breadboard, and cabling.

You will need to use a Wheatstone bridge at the + and - input of the instrument amp. There are plenty of example circuits. Search for, "instrument amp wheatstone bridge strain gauges," to get some schematic diagrams.

An adjacent two of the four legs of the Wheatstone bridge are the two strain gauges. One of the other two legs would be a potentiometer in series with a fixed resistor to give you offset adjustment. Another potentiometer adjusts gain. The IN114 spec sheet shows how to set the gain and how to power the chip.

Mechanically, the strain gauges would go on opposite sides of the exact same point on the spring, near where it attaches to the stationary frame to which the tracks are mounted. One strain gauge must be bonded to the inside of the spring. The other to the outside, directly opposite the inside one through the thickness of the spring wire. This will allow the Voltage you measure to indicate the strain on the spring which is related to the position of the door.

(The image at http://recordtek.com/sites/default/files/Gauge-spring.png shows a strain gauge bonded to the outside of the spring. The inside complement would go directly underneath it on the inside.)

I'd recommend an Arduino Due to read the output voltage of the IN114, setting the gain and offset to stay within the 1.55 to 2.75 V range of the analog inputs of the Due for all garage door positions. That will take some trial and error with a Voltmeter before you connect the Due.

To calibrate the system, the analogRead() values for ten somewhat equally spaced garage door positions are placed in an array of integers. Another same size array of doubles receives the corresponding door positions in whatever units you want. These can be static arrays that are initialized in your Arduino code.

You would get the position from the analogRead() at any point in time by interpolating the data in the table represented by the two corresponding arrays. That is easier than it sounds. There are articles explaining how and libraries providing linear interpolation in C, some of which may be usable without modification in an Arduino sketch.

**Bonding the Strain Gauges**

There are many articles available on using strain gauges and how to rigorously clean the surface and position and orient the gauges before bonding them to the metal of the spring. That's critical. They have to point in a particular direction, and the bond will come apart if you don't clean the metal well enough, which would not be good.

**Going High End**

If you wanted high accuracy, you could enhance your design to possibly get three or more significant figures as you reach expert level.

* Read and factor in temperature when doing the interpolation
* Take more than 10 calibration samples and use larger arrays to match
* Use a quadratic or cubic interpolation instead of linear
* Write a calibration algorithm to fill the two arrays with new values automatically every time the door goes from one extreme position to the other
> 1 votes

---
Tags: sensors
---


title: Does this code work as a PWM?

text:
# Question
Title: Does this code work as a PWM?
I'm working on an Arduino project and I need to write some code that controls the frequency and duty cycle of a square wave signal (pulse width modulation). I'm not allowed to use the PWM function, I have to write my own code.

I've tried this code on Proteus (virtual Arduino) but there are two problems:

1. The frequency is always high (hundreds of Hz) even if the input voltage is zero. It never reaches 0.5 Hz or 1 Hz.
2. The duty cycle is very high or very low. I never see 50% or 75% duty cycle on an oscilloscope. When I change the position of the potentiometer it becomes 90% or 10% (I think) and there are no other values.

Would you tell me what's wrong with this code please? I can not find my mistake:

```
unsigned long Time = 2000000; unsigned int Volt; float dutyCycle = 0.5;
void setup() {
  pinMode(13, OUTPUT); //set Pin 13 or On-board LED to output
}

// the loop function runs over and over again forever
void loop() {

  Volt = analogRead (1);    // Frequency: input voltage is through potentiometer at analong pin 1
  dutyCycle = analogRead (0) / 1023;    // dutyCycle potentiometer is at analong pin 0
  Time = ( 2000954 / (1 + Volt) )- 954; //This equations is linear. When input voltage is zero, frequency = 0.5Hz. When input voltage is 5v, f=1000Hz.

  digitalWrite(13, HIGH);   // turn the LED on
  delayMicroseconds(Time * dutyCycle );              // wait
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delayMicroseconds(Time * (1-dutyCycle) );          // wait
}

```

# Answer
```
dutyCycle = analogRead (0) / 1023;    // dutyCycle potentiometer is at analong pin 0

```

Dividing a small integer by a bigger integer leaves you with 0. If `analogRead()` returns 1023 you will get a result of 1. Everything else will give you 0. You need to divide by a floating point number - either `1023.0` or `1023f`.

`analogRead()` is slow. Because it is happening between every single cycle of your square wave you can expect to never get to anywhere near 100% duty cycle. There will always be a LOW period where the analog input is being read.

You should:

1. Fix your integer division problem
2. Make the ADC "free running" or interrupt driven so it doesn't interfere with your PWM generation

... Or ...

1. Fix your integer division problem
2. Make your PWM generation timer driven, either using the OC peripheral or manually with interrupts, so it doesn't interfere with the analog reading.

... Or ...

You could even do both. Make everything as asynchronous as possible leaving your loop() free to just do the heavy work of calculating the values.
> 4 votes

---
Tags: pwm, programming
---


title: How to use the eclipse arduino scope?

text:
# Question
Title: How to use the eclipse arduino scope?
I am quite new to the Arduino stuff. I have got the Arduino IDE installed side by side with Eclipse. I am using Eclipse with the Arduino plugin, which is working well for me, including the SerialMonitor.

If you're using Eclipse with the Arduino plugin, it'll also add two new views. One is the serial monitor, the other one is called scope. Scope is a 6 channel Oscilloscope. But I don't know how to get values displayed there.

I am just curious how to use the scope there. I can't find any tutorial for this.

Can somebody explain how to show something inside the scope?

# Answer
The simplot library (referenced below) is an excellent example of how to use the scope which works as advertised. Firstly, readers should note that there are two different Arduino plugins for Eclipse ("Eclipse C++ IDE for Arduino" and "Arduino Eclipse plugin named Sloeber V3"). Only the latter has a scope and a seriel monitor that allows data to be sent. Getting simplot and the scope to work, however, can be a problem depending on the platform. On a Mac, with the latest version of Eclipse (Neon.2 Release Candidate 2) and the Sloeber V3 plugin, the default path to the Private Library is Users/yourname/Arduino/libraries. Unfortunately, this path doesn't (necessarily) exist. One could spend hours trying to figure out how and where to import a library when the critical library folder doesn't exist.

The solution (at least on a Mac):

* Create a folder (arbitraily) named "Users/yourname/Eclipse/libraries".
* Include this folder in Eclipse - Preferences - Arduino - Private Library Path
* Download jantje's entire Github Arduino Library, unpack it and move the "simplot" folder into your Private Library Folder. "simplot" should now show up in the libraries.
* Use: Arduino - Add a Library to the Selected Project
* Or build a project using the simplot.ino example.

It should work beautifully.
> 2 votes

# Answer
Given that two bytes are short, you send:

1. `SCOPE_START_DATA` `short` flag: `0xCDAB`
2. `short` number of following bytes to read (for example, `0x0002` for only one channel)
3. one `short` per channel

P.S. This is shamelessly stolen from it.baeyens.arduino.monitor.views.ScopeListener
> 1 votes

# Answer
The plugin FAQ links to a defunct website. However the internet wayback machine reveals some good info (https://web.archive.org/web/20150321054307/http://www.negtronics.com/simplot). In particular a link to the arduino forums that has some code samples: http://forum.arduino.cc/index.php?topic=58911.0
> 1 votes

# Answer
Try the simplot library.

It is from the author of the plugin and works with both 32 and 8 bit processors. There is an example included that should get you going.

The plotter itself automatically connects to the first serial connection so there is no connect needed for the plotter like there is for the serial connection.
> 0 votes

---
Tags: arduino-uno, eclipse
---