# Question
Title: Sense checking Arduino Uno barebones schematic
I have had some difficulties finding a barebones Arduino board and have had the following made. I just wanted to see if anyone could spot any issues? I think it has everything. I'm really trying to get it as minimalistic as possible, but at the same time able to use a power source like a 12v/24 battery. Any help would be greatly appreciated. Many thanks

# Answer
> 1 votes
1. You shouldn't put a capacitor under the chip like that. In fact I don't much like the layout of the whole crystal circuit at all.
2. You need capacitors on the 7805 regulator - around 10µF on both the input and output.
3. The RESET pin needs a pullup resistor otherwise the chip won't function at all.
4. You need decoupling capacitors on all VCC pins on your main chip.
5. Instead of meandering ground traces you should use a ground pour.
6. Running from the kind of voltages you propose the 7805 is going to melt. You will need a BigAss™ heat-sink on it. For those kind of voltages you would be better using a switching (aka *buck*) regulator. Maybe as an off-board module to keep your board simple.

# Answer
> 0 votes
C4 is under the IC, which may (or may not) do problems, regardless which side of PCB you place it actually. The reset is better to connect via resistor to defined level than to leave floating. Usually there is also capacitor there to delay start until power is stabilized. I would put big capacitor near the stabiliser (also I think, it is recomended by manufacturer of the stabiliser for a reason), but maybe if you have good batery and short wires, it could work too. Also small capacitors between GND and VCC as near the IC as possible are common to reduce noise. And reset button is usefull add-on, but not necessary. Anyway I think, it could work as it is (with the reset defined).

If you have some particular application in mind, then you may use also different layout and/or get more connectors for some pins (some of my "arduinos" does not look like Arduino at all, having all periferials on the same PCB instead on some shields.

also http://download.gilhad.cz/arduinobb\_12.jpg this is fully working arduino, which I used many times - so you do not miss anything critical (those LEDS are not necessary)

---
Tags: arduino-uno
---


# Question
Title: Using Arduino libraries for adding more functionalities to a bootloader
I have a short question to ask before putting time for research.

I have an Arduino Leonardo with the LUFA mass storage bootloader flashed. Now what I need to do is to add more functionalities to the bootloader. Because in the final product, the Leonardo board will be connected to a fitness machine (permanently connected) and the machine has Windows OS. Then the Leonardo should be able to read an RFID card (I need to add an RFID reader to the board, each user has his own RFID card) and then mount a remote server directory to the local USB Host based on the selected user.

I will have to use a wifi shield too. My question is this: is it theoretically possible to add all these functionalities to the LUFA mass storage bootloader? Because it's not possible to use the Arduino IDE for this purpose, since I'm not uploading any sketch on top of the bootloader, rather than editing the existing mass storage bootloader with the required functionalities and re-flash the chip. Am I correct? (This is what I understood after some research. And I'm a noob :D).

Could you please elaborate what would be the first step for solving this issue?

# Answer
@Majenko: I think, that the task IS possible, but it is really hard (and Leonardo may need more memory for that eventually and some shields too and so ...) but if I understand the problem, than the Leonardo should pretends to be mass storage device for that application, and pretend it have some folders and files on it, depending which RFID is used to activate it.

The application probabelly is NOT going to format the MSD because it would lose all the user data on it.

So Leonardo can do following:

* pretend it is already formatted and have some known filesystem on it (vfat is easy enought and probabelly usable as many USB flash sticks came with it)
* when the machine detects inserted USB, it ask for type - so it get MSD
* then it will read partition table - Leonardo can emulate it easily, having "just one partition of given size and type" the partition can even be stored as a file on that fileserver to save Leonardo's memory.
* next goes reading FAT table and root directory
* + knowing the user from RFID it is possible to select the right directory on file server,
    + then enumerate lengths of all files inside (and directories)
    + make table with the names and "offset"
    + send back the FAT as if those files were ordered on the "disk" so each entry points to the following sector, until the last marks EOF
    + root directory begins after FAT and contains names of the files, their lenghts, dates and starting sectors (and some very basic right like read-only, system and such)
    + then follows files and directories
* each time the machine asks for a "sector", it is possible to compute, in which file the sector is placed, read the portion of a file (potentially fill it with zeroes to "sector lenght" and return it as requested "sector"
* if the sector is in directory instead, return the part of directory (that means filenames and such)
* if the sector is outside it all (should not happen), return just zeroes.

On the other direction:

* if you get something outside structure, put it to temp. file along with address of such stray "sector"
* if you get something in a file, just replace the file content on given offset
* if you get something in directory, you need to compare it with previous version and "rename file", "create file" or "delete file" acordingly.
* it would probabely need two directories on the server for each user - one for actual files, other for "lost sectors" and "deleted files" which could be "reconected", "undeleted" or "attached later" to the files/directories. The second directory can be emptied after "removing USB MSD" when user with given RFID logouts.

It is lot of work, but basically it could be done. It also needs a lot of accounting on the Leonardo and lot of communication with the fileserver, but it is possible to do.

It suppose, that the files on fileserver would not be modified by somebody else while "mounted" and that the Windows machine would not "format" the USB to some kind of filesystem, the Leonardo does not understand (how to translate to the real files on server).

But for the supposed use I think those two conditions could be reasonable. The MSD probabelly just holds the "user profile" so the machine can put in records of hir/her activiti, some stats and so on, probabely it would be just a few growing files maybe even just in root directory.

Anyway I would not like to write such system, as it is terrifying lot of work and a lot of things could go wrong, if there is a bug (or bad connection).

Also the size of required memory for Leonardo is large - probabelly larger, than the Leonardo actually have, but it could be offloaded to the filesystem too (in "hidden directory" not shown to the machine) - which would be slow and hard to manage - or expanded by HW RAM, which would be a lot faster, but needs nontrivial settings.

(Remebers me, how I wrote resident program for DOS, which had just 130 bytes, which swaped in two 16KB widows of EMS where the rest of program (actually interpret of some pseudocode) was placed (it was like 4 or 6 such 16KB pages, but was able to swap itself acordingly) while the remaining two EMS pages was reserverd for data (like 300-400KB total of pseudocode and data) which was also swapped as needed to access everything. From DOS point of view it was just the 130B resident API, from the view of program, which was using it, it was 400KB engine running FORTH-like program and containing database. The result was like 3x faster processing of 2.000+ employes wages.)

Here are the memory restrictions even more tight, but I thing, that it is possible to do such thing, only it is extremely hard to make it work reliably.
> 1 votes

# Answer
From your brief description of what you want to do I think you want to:

1. Mount a Windows share on your Leonardo
2. Make said share available through USB MSD

Well, sorry to break it to you, but that is not possible. No, it's not because the Leonardo isn't up to the task, but you are trying to mix two completely different concepts.

A Windows share (*CIFS*) is a file-centric system. That is, you access files within the share and request bytes at offsets within the files. The client has no concept of the underlying filesystem, it just works on files.

A USB MSD device, in contrast, has no concept of files, directories, etc. Instead all it knows about is blocks. Raw fixed size blocks of data. The computer that it is attached to is what knows what a filesystem is. It requests blocks of data from the MSD and interprets them as a filesystem, allowing you to access the files within it.

You can see the problem you would now face? MSD responding to requests for raw blocks of data from a computer which then wants to get the contents of files from a server - how do they fit together? Simply: they don't.

So you are going to have to re-think your basic idea.

One possible idea would be to use some client-server block based system, such as iSCSI, which gives you block devices on a network (a single file which is an image of a virtual disk), though only the device which is attached to that block device through the network can see the content of it.
> 0 votes

---
Tags: arduino-leonardo, bootloader, avr, atmega32u4
---


title: Connecting to Nano via USB3

text:
# Question
Title: Connecting to Nano via USB3
I have a Uno (third party) that I connect to my Dell laptop with no problems at all. But I've just received a Nano (also third party) that I just can't get to upload. After lots of interneting, I hit Windows normally-useless troubleshooting tool. That tells me that the USB device (the Nano) doesn't understand USB3 and I should plug it into a USB2 port. Unfortunately, being a new machine there IS no USB2 port.

Is Windows Troubleshooting lying? Is there a problem interfacing with a Nano via USB3?

Edit: Error message is:

```
stk500_recv(): programmer is not responding

```

# Answer
> 1 votes
I have run in to similar symptoms while using USB based Arduino clones connected to USB3 ports. Connecting them to a USB2 port on the same PC worked (where this was an option).

For computers that only have USB3 ports, I found that connecting the device via a cheap USB 2.0 hub (not USB3 hub) solved the issue.

I'm not sure why these devices behave like this, but there seems to be something about USB3 ports that these boards don't like.

# Answer
> 0 votes
Windows troubleshooter is just trying to tell you that you've plugged a USB2 device into a USB3 port, thus wasting its USB3 capabilities which could be useful for another device. Of course, if you only have USB3, you can't do otherwise.

USB3 is fully backward-compatible with USB2, so whatever your problem is, it is not related to the fact that you plug the Nano into a USB3 port. Perhaps your problem comes from the fact that your Nano is "third party" - I suppose that means it's not the original device and thus it may not be fully compatible. If my guess is right, try to find out what programmer your Nano clone supports: chances are you just need to select a different programmer type in Arduino settings, or buy a separate programmer supported by your device.

# Answer
> 0 votes
1- Check your COM ports, make sure it is correct

2- Arduino Nano will somethime require a driver, download it

3- Reboot your system and see what happens

---
Tags: uploading
---


# Question
Title: Problem with uploading LUFA MassStorage .hex file to Leonardo
I have been trying to make my Leonardo board to work as a USB device. So I started with compiling the open source LUFA USB library demo "MassStorage" for the Leonardo board settings. Since I'm using Mac OS, I downloaded the "AVR Tools" software to upload the hex file to the board(I didn't want to use the ISP protocol to flash. Because it is not possible to remove the chip from the board to make the correct ISP circuit connection). Anyway I was managed to flash the board. But afterwards it is not detectable by the computer. The serial port is not detectable. This proves it flashed something. Afterwards I flashed it again with the original bootloader file and it was identified as before. I'm a beginner to Arduino programming and forgive me if I'm asking elementary question. What am I doing wrong?

# Answer
Cannot say for sure, but if you was able to flash something, then loose functionality, but was still able to flash it back, then there is possibility, that you flashed the application part (with would-be-bootloder code), not the bootloader part (and the old bootloder in bootloader part then enabled you to flash back something sensibe).

bootloader is resposible for saving application in memory in process of flashing and running the application after that, or in case you just connect the board and do not start flashing it just after (maybe software/transmit) reset.

if you save bootloader to application part of memory, it is highly possible, that it would not do anything good, as the original bootloader would still run first and setup your board and the application (with new bootloader code) would try something futile (and maybe have bad addresses already, as it is suppose to be runned in bootloader place, not in application).

There are two parts of flash memory in arduino - one for application, other for bootloader and they have different use, even if they are just different parts of one big flash area. So make sure, what you actually updated and how was the hex compiled (for which address)
> 1 votes

---
Tags: serial, arduino-leonardo, bootloader, avr
---


# Question
Title: Output specific value using port manipulation
How can I output a specific value on a pin using port manipulation?

Example: I want to use this code but without any arduino functions, just with port manipulation:

```
for (int i = 0; i < 255; i++){
analogWrite(11, i); //write the i value to pin 11
}

```

I want to replace the `analogWrite` function with register manipulation. Is that possible?

# Answer
The `analogWrite` function is just an interface to setting up the hardware timers to do PWM (pulse-width modulation). I have a page about timers which you may find helpful.

Depending on which pin you want to output the PWM to, the registers will be slightly different. Here is one example from my page:

```
const byte OUTPUT_PIN = 3;  // Timer 2 "B" output: OC2B

const byte n = 224;  // for example, 1.111 kHz

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

  TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2B1); // fast PWM, clear OC2A on compare
  TCCR2B = bit (WGM22) | bit (CS22);         // fast PWM, prescaler of 64
  OCR2A =  n;                                // from table
  OCR2B = ((n + 1) / 2) - 1;                 // 50% duty cycle
  }  // end of setup

void loop() { }

```

---

> How can I output a specific value on a pin ?

I should point out that the only values you can output are +5V or 0V. There is no provision for outputting (say) 3.7V. The only way you can sort-of do this is by using PWM and then running the result through an RC filter. There is an example on my page about op amps.

An example circuit could be:

This uses a resistor and capacitor to filter out the "ripple" in the PWM, giving you a reasonably smooth output voltage, proportional to the PWM duty cycle.

For a larger range of output values a rail-to-rail op-amp would be preferable.
> 1 votes

---
Tags: arduino-uno, port-mapping
---


# Question
Title: Best way to power an Arduino using the Vin pin
I have a powerbank rated 5v. The battery is actually 3.6v, powering the built-in SMPS to give out 5v. I have stripped one end of the USB cable coming from the power bank, powering a motor driver and the Arduino in parallel. The positive end of the power bank, which is 5v, is going into the Arduino and the motor driver IC's Vcc.

I heard that 5v is not enough to drive the Arduino from the Vin pin. And there is only one power out from the powerbank, so directly connecting the Arduino through the USB would leave nothing to drive the motor driver IC.

A USB splitter would be the obvious solution, but is there anything else I can do? The power source has to be mobile. Can I power the Arduino through the Vin with those 9v batteries commonly used in electronics hobby projects?

# Answer
> 6 votes
You have a powerbank which has a USB output, right? Why not just plug a cable from that into the Arduino USB port? That will connect the 5V directly into the 5V pin of the Arduino (probably via a switching MOSFET). Then you can connect to your motor driver from the 5V pin on the Arduino (and Gnd of course). There may be some limitations on how large a motor you can drive (based on the capacity of the power bank, and to an extent also the thickness of the traces on the Arduino board).

As others have commented, Vin is not intended for that purpose (ie. to supply 5V). You should supply 7V or more to Vin to force the switching MOSFET to disconnect the USB input. In your case you don't have 7V from the powerbank.

---

Here is how the Uno Rev3 power system works:

The input jack (circled in blue) goes through a diode (D1) to the Vin line.

Vin then goes through the 5V voltage regulator (U1) to provide +5V.

However on the top left you see 2 x 10K resistors (RN1A and RN1B) which make a voltage divider from Vin to Gnd. This is compared to the output of the 3.3V voltage regulator by U5A op-amp (circled in red). If higher, then T1 (circled in green) will turn off, disconnecting USBVCC from the +5V line. If lower, then USBVCC is connected to +5V. The nett effect is that if Vin in greater than 6.6V (because of the voltage divider) then the circuit chooses to use Vin, otherwises it uses USBVCC (USB power).

That's why they recommend to use 7V or more into Vin.

Note that you lose around 0.7V through the diode, which is why you need something like 7.3V at the input jack to allow for the loss of the 0.7V before the op-amp compares it to 6.6V.

# Answer
> 1 votes
I had this problem last year when I needed to power a prototype using a LiPo battery which supplies only 3,2 up to 3,7V (and up to 4,2V when charging).

My way of solving the problem was to use a voltage boost module. Boost circuits are a kind of circuit where you the inertial properties of passive components to elevate (or attenuate) DC voltage levels.

But you don't need to worry about the math behind use, there is modules like the MT3608 which will supply your circuit up to 28V starting from as little 2V, check the datasheet.

# Answer
> 0 votes
That is true, you can't power the Arduino with 5V ***from VIn***.

If you have a constant 5V and you are confident that no major spikes are going to happen, then you might as well connect it to the Arduino's 5V pin.

Other wise, you need at least 7V power the Arduino from the VIn pin. Some say you can put in 6V, but that is just from test. The 7V is more reliable. Thus, you can power the Arduino with a 9V battery is you wish.

---
Tags: power
---


title: Servo/Motor for barrier gate

text:
# Question
Title: Servo/Motor for barrier gate
I am working on a small project that will need to check for proper UPC's then if validated, lift a barrier gate to move along cardboard boxes. The Arduino comes in with the gate lifting. I have this barrier gate working with a very small servo that came included with the Arduino Starter Kit, but this could not hold the weight that might be pushing up against it with a longer arm. Has anyone had any experience with something like this or could someone direct of a power supply/servo combo that would be up to the task? These boxes could weigh up to 20 pounds.

Thanks!

# Answer
> 1 votes
You may **purchase a servo motor with greater torque**.

You may find both DC as well as AC servo's. If you are using it in a real industrial scenario I would suggest you to use the AC, as you may not have to convert the ac power to DC and these motors will need real high current. So it would be better if it works on the main voltage. I did find **PANASONICs ac servo** as google search result.

If you have problems with integrating the greater torque motor to your current system let me know i can help you out.

# Answer
> 0 votes
You could look at larger DC gearmotors such as automotive power window or power door motors and use limit switches for position sensing. To power this you would need a 12V power supply capable of at least 5 amps.

---
Tags: arduino-uno, power, motor, servo, robotics
---


title: Arduino keeps crashing

text:
# Question
Title: Arduino keeps crashing
I've got an Arduino with a WS2812 hooked up to it, powered by the USB on my computer and I am trying to run the following code:

```
#include <FastLED.h>

#define NUM_LEDS 144
#define DATA_PIN 6
#define LED_TYPE WS2812B
#define COLOR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
  FastLED.show();
}

void loop() {
  for(int dot = 0; dot < NUM_LEDS; dot++) {
    fill_solid(leds, NUM_LEDS, CRGB::Red);
    leds[dot] = CRGB::Black;
    leds[dot] = CRGB::Blue;
    FastLED.show();
    leds[dot] = CRGB::Red;
    delay(30);
  }
}

void setAll() {

  FastLED.show();
}

```

What this does is sets all the LEDs to red, then goes through each one turning it off, then to blue and then back to red.

For some reason, it gets X number of LEDs along and then crashes. By crashes I mean the Arduino disconnects itself from the computer, but the Arduino stays on with the LED strip still powered up.

Any ideas? This is a genuine Uno and I can run any of the FastLED or NeoPixel examples for hours on end without an issue

# Answer
> 2 votes
It is inferred from your question that the Arduino is getting powered through the USB port. As you say the Arduino appears "gone" from the computer when you light up too many LEDs.

All USB ports are only obliged to supply 500mA with out the USB Device (the Arduino) negotiating for more power from the USB Host. If the load goes beyond 500mA, the USB Host (the computer) can limit the power my reducing the voltage. At some point the Atmel processor on the Arduino will stop working.

There are many tutorial on how to use LED strips on the web. Most will indicate power from a larger than normal power supply is necessary. Also, that the LED strip power should be connected directly to an appropriately chosen power supply.

The following image from this web page illustrates this:

(Note: In this picture PIN 6 was chosen to communicate with the LED strip. Your specific application (program or sketch) may use a different pin. Also, realize that the power supply in the picture is wired to only power the LED strip. The Arduino still needs to be powered.)

# Answer
> 2 votes
See Powering NeoPixels.

> Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue).

OK, so you have 144 LEDs.

```
#define NUM_LEDS 144

```

That means you need to allow for 8.64 amps to power them!

```
144 * 0.060 = 8.64

```

(This is a worst-case scenario, but you should probably allow for 2 amps at least).

As st2000 points out, the USB interface will provide 500 mA (0.5 amps). So you are possibly 8 amps short. You need to power the NeoPixels independently, not through the Arduino.

By powering them through the Arduino they are draining the current from the USB port so much that the over-current protection kicks in.

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


# Question
Title: clear Arduino as a global variable in Matlab
I'm trying to use `Arduino` in `Matlab`. cause I used Arduino in some function I had to define `Arduino` as a global variable.

```
clc,clear,close all;
global a
a = arduino();
.
some functions
.
clear a

```

at the end of my code I `clear` the variable but as I run the code again this error appear:

```
Failed to open serial port (user COM) to communicate with board Uno. ...
 Make sure there is no other MATLAB arduino object for this board.

```

I guess the global function can't be clear by `clear` command so I tried `clear all` instead `clear` in the last line. It works perfect as I run it again and again but as you know this is `Matlab` tips for `clear all` command

```
Using clear all causes MATLAB® to recompile previously cached code,
and can decrease performance.

```

I've tried `delete(a)` so the result was:

```
Error using arduino/delete
Cannot access method 'delete' in class 'arduino'.

```

any help would be appreciated.

# Answer
In the MatLab Help Center they had nice description of how to clear a variable from memory. Check it here: https://www.mathworks.com/help/matlab/ref/clearvars.html

In your case should be: `clearvars -global a;`
> 1 votes

---
Tags: matlab
---


# Question
Title: I am making an easy game but something in my code is wrong
I am making a game where you need to push the button when the LED lights up but it is not registering the push at the right time. I need to push the button when LED is about to go off.

My code:

```
randNumber = random(2);

if(randNumber == 0){
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
}

if (btnAddFirst.pressed() && randNumber == 0){
  Serial.println("You did it");
}
else {
  Serial.println("u failed");
}

```

# Answer
> 4 votes
Don't use `delay()`, since nothing can happen (not even reading a button) while that delay is running.

Instead use `millis()` as in the `BlinkWithoutDelay` example sketch.

---
Tags: arduino-uno
---


title: Arduino Leonardo model differences

text:
# Question
Title: Arduino Leonardo model differences
I was thinking of buying another Arduino, and the Leonardo looks appropriate.

However I am confused! The Comparative Tables seems to show 2 different Leonardos. (This table is very difficult to read with tiny black text on a grey background, and no key to the column headings.)

There appear to be different models "R3" and "R4" from different retailers and Element14 seems to have a "U4". Can anyone clarify the differences?

I assume I can use the Uno Prototyping shield on the Leonardo.

# Answer
At the end of the day the Leonardo is just a chip (ATMega32U4) on a board with a voltage regulator, a couple of LEDs and USB socket / shield headers. There's not much else to it.

Different revisions may change some of the support components - maybe a component went EOL and they needed to change it, or a better / cheaper one came along that they switched to - but the basic design of it - a chip on a board with minor support components - can't really change.

The reason it's hard to find the differences between the different revisions is because those differences are so inconsequential to the end user that knowing them is irrelevant. The only real way you'd find the differences would be to compare the schematics of each revision to find the components that have changed. In some cases it may even just be a change to the silk screening in re-branding from Arduino to Genuino, or just a slightly more modern logo, etc.

It's still the same chip, and still connected up in the same way.
> 0 votes

---
Tags: arduino-leonardo
---


# Question
Title: How to convert Arduino example sketch to a complete c++ project?
I'm experimenting something new with my Arduino Leonardo. I removed its original bootloader and flashed it with LUFA mass storage example with added functionalities(now its a firmware). I'm trying to now add RFID reader(read/write) example to my firmware. For that I have to convert the sketch to a c++ code. So I copied relevant header file and cpp file from the library folder(libraries-\>rfid-master-\>bla.h,bla.cpp). But I'm confused what to do with the .ino file under examples(libraries-\>rfid-master-\>examples-\>ReadAndWrite-\>blabla.ino). I guess this code should be copied to the main class of my firmware. Any ideas?

# Answer
> 5 votes
Basically \*.ino is \*.cpp without headers. So you can

* rename it to \*.cpp,
* If you have any functions which are used before they have been defined, provide declarations for each function before its first use
* `#include <Arduino.h>` on the top
* `#include <Wire.h>` if you are using Wire and so on

and you have "normal" CPP file.

If you are making library this way, than you create also \*.h file, where you declare all exported functions and objects and #include that file in your \*.cpp as first line (than you do not need/have to forward declare any of that exported functions)

You may like to take a look at https://github.com/arduino/Arduino.git https://github.com/sudar/Arduino-Makefile and https://github.com/ladislas/bare-arduino-project

the Bare Arduino have 2 projects each using 2 libraries, so you can get inspiration there

---
Tags: c++, arduino-leonardo, avr, ino
---


# Question
Title: Arduino Mega web server always returning JSON data even if JSON is not passed in URL
I am trying to return JSON data if JSON is found in the HTTP header, and if not I am trying to display a normal page. But instead it always displays the JSON text, even if I do not pass the JSON in the URL! Full code is here.

```
if (client) {
  // an http request ends with a blank line
  boolean currentLineIsBlank = true;
  boolean sentHeader = false;
  while (client.connected()) {
    if (client.available()) {
      // client data available to read
      char c = client.read(); // read 1 byte (character) from client
      // buffer first part of HTTP request in HTTP_req array (string)
      // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
      if (req_index < (REQ_BUF_SZ - 1)) {
        HTTP_req[req_index] = c; // save HTTP request character
        req_index++;
      }
      // last line of client request is blank and ends with \n
      // respond to client only after last line received
      if (c == '\n' && currentLineIsBlank) {
        if (!sentHeader) {
          // send a standard http response header
          client.println(F("HTTP/1.1 200 OK"));
        }
        // Ajax request - send JSON output
        if (util::StrContains(HTTP_req, "json")) {
          // Spit out JSON data
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: ArduinoMega");
          client.println("Connnection: close");
          client.println();
          client.print("{\"arduino\":[{\"location\":\"outdoor\",\"celsius\":\"");
          client.print(tempInC);
          client.print("\"}]}");
          client.println();
          break;
        } else {
          client.println(F("Content-Type: text/html"));
          client.println(F("Connection: close")); // the connection will be closed after completion of the response
          client.println(F("Refresh: 1000")); // refresh the page automatically every 60 sec
          client.println();
          sentHeader = true;
          client.println(F("<!DOCTYPE HTML>"));
          client.println(F("<html><head><title>"));
          client.println(F("Welcome to Arduino WebServer</title>"));
          util::printProgStr(client, htmlStyleMultiline );
          client.println(F("</head><body style='background-color:grey'>"));
          client.println(c);
          client.print(F("<p style='color:red';style='font-family: Arial'> LIVE: </p>"));

```

Please help.

# Answer
So figured out the problem, the issue was I was closing the connection instead when it was json fetched, I had to keep alive the connection.

so replaced `client.println("Connnection: close");` with `client.println("Connection: keep-alive");`

which fixed the problem.
> 0 votes

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


title: CC3000 Wifi: Enable Debug

text:
# Question
Title: CC3000 Wifi: Enable Debug
How do I enable debugging using Adafruit CC3000?

I am using the Adafruit\_CC3000\_Library. I've followed the WebClient.ino example sketch. I'm able to make 300 to 400 HTTP requests, but eventually the connection will hang.

I have looked at the CC3000 source and utilities and found that the `Adafruit_CC3000_Library` has a `&Printer` reference in a local variable called `CC3KPrinter`. I can't figure out how to enable or activate `CC3KPrinter`, as it is in a code block contingent on `CHECK_PRINTER`. I thought that `#define`-ing some variables in my sketch would help:

```
// None of these flags seem to enable debug within the CC3000 code.
#define _CC3000_DEBUG  1
#define DEBUG_MODE     1
#define ENABLE_CC3K_PRINTER 1

```

An example code snippet within the CC3000 library that I'm trying to enable is at line 916:

```
  CHECK_PRINTER {
    CC3KPrinter->println(F("Timed out waiting to connect"));
  }

```

# Answer
To enable debugging, you need to

* uncomment `ENABLE_CC3K_PRINTER` in `Adafruit_CC3000.h`
* If you want to pass in some debug stream other than the default `Serial`, you should pass a pointer to the object (which should inherit from `Print`, such as `SD` or `Client`) as the last argument to the constructor in your sketch:

```
Adafruit_CC3000(uint8_t csPin, uint8_t irqPin, uint8_t vbatPin, uint8_t spispeed = SPI_CLOCK_DIVIDER, Print* cc3kPrinter = CC3K_DEFAULT_PRINTER);

```
* In `utility/debug.h`, change the value of `DEBUG_MODE` to 1 (or any non-zero value)

I don't know what caused your issue but you shouldn't put this in your code:

```
#define _CC3000_DEBUG  1

```

Because most of `utility/debug.h` is wrapped in the usual:

```
#ifndef _CC3000_DEBUG
.
.
.
#endif

```

Your `#define`, depending on where it's placed, could cause most of the file to be skipped by the compiler and result in compilation errors. To be on the safe side, get rid of it and simply include `utility/debug.h` as needed.
> 1 votes

# Answer
Poor workaround: since I was trying to solve a connection hang, I opted to use a watchdog timer solution, leveraging the lightly documented `<avr/wdt.h>` library.
> 0 votes

---
Tags: arduino-uno, serial, c++, wifi, library
---


title: Arduino uno shift register

text:
# Question
Title: Arduino uno shift register
I have shift register 74HC595. I added 7 push buttons from Q1-7 and the 8th to ground. On the other side which pin of the register will go to Arduino pin 2? And wich one to the 5v pin?

How can I read one button at a time in the code because on the Arduino it is just 1 pin?

# Answer
> 0 votes
You cannot. The 74HC595 does not have parallel inputs, such as you would need to read from 7 switches.

You need a parallel-in, serial-out shift register, such as a CD4021B. You can find details on how to use it with an Arduino here

> How can I read one button at a time in the code because on the Arduino it is just 1 pin?

Basically you "clock in" the data by toggling a clock line - each toggle presents the next bit, which you read in using your one digital input.

# Answer
> 0 votes
A shift register is an output device. You won't be able to "Read" 7 push buttons in this way.

A shift register like that is for taking a "series" of bits on one wire and parallelizing them onto 8 wires.

It does not work in reverse. The reverse is called a multiplexer.

# Answer
> 0 votes
Shift registers are available in several flavors:

Serial-in, Serial-out (SISO) units like 7491 have serial input and output.

Serial-in, parallel-out (SIPO) units like 74164 have serial input, parallel output.

Parallel-in, Serial-out (PISO) units like 74165 or 74166 (etc. – just search for shift register in a list of 7400 series integrated circuits or other series) have parallel input, serial output.

Other variations: The 7494, 7495, and 7499 have serial and parallel input, parallel output. The 7499 also has serial output. The 7494 and 7499 can shift right or left. (Most of the models listed earlier only shift one direction.)

Anyhow, by using an appropriate shift register, along with a bunch of resistors and diodes, it is possible to read lots of switches. As suggested in another answer, you might want to ask about how to do that.

---
Tags: shift-register
---


title: Millis...alternate flash

text:
# Question
Title: Millis...alternate flash
I thought I had the Millis() command sorted but i'm stumped on the one. Aim is to get 2 led's alternately dimming, they work great with delay(); of course....but i can't figure where i'm going wrong with Millis(). Please have a look and point out what i've got wrong. Thanks Doug

```
int LED3 = 5;
int LED4 = 6;

// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED3=0;
unsigned long previousMillisLED4=0;

int intervalLED3 = 500;
int intervalLED4 = 500;

void setup() {
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);

      digitalWrite(LED3,LOW);
      digitalWrite(LED4,LOW);

}

void loop() {
  //unsigned long currentMillis = millis();
      for(int P=0;P<6;P++){
        //if ((unsigned long)(currentMillis - previousMillisLED3) >= intervalLED3) {
            analogWrite(LED3, 127);
            analogWrite(LED4, 254);
        delay(500);
              //previousMillisLED3 = currentMillis;

      //if ((unsigned long)(currentMillis - previousMillisLED4) >= intervalLED4) {
            analogWrite(LED3, 254);
            analogWrite(LED4, 127);
       delay(500);
             //previousMillisLED4 = currentMillis;
      }
}

```

Sorry, problems inputting code, but its all there.
I realize that there are some closing brackets missing in the LOOP() section for millis but it is set for delay() to show that it works.

# Answer
Well, the for loop is useless. Then you need to plan your time cycle. For instance what you want is

```
time(ms)  LED3  LED4
   0       127   254
 500       254   127
1000 -> back to 0

```

So implement this. One way can be the one suggested by st2000:

```
int LED3 = 5;
int LED4 = 6;

// just one tracking, since there is only one sequence
unsigned long previousMillis=0;

int endOfPhase1 = 500;
int endOfPhase2 = 1000;

void setup() {
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);
    digitalWrite(LED3,LOW);
    digitalWrite(LED4,LOW);
}

void loop() {
    unsigned long currentMillis = millis();

    if ((currentMillis - previousMillis) < endOfPhase1) {
        analogWrite(LED3, 127);
        analogWrite(LED4, 254);
    }
    else if ((currentMillis - previousMillis) < endOfPhase2) {
        analogWrite(LED3, 254);
        analogWrite(LED4, 127);
    }
    else
        previousMillis += endOfPhase2;
}

```

Just a small note about this: I tend to prefer summing the period instead of setting previousMillis to millis because this way small errors do not accumulate.

This way is the simplest, but the state machine oriented is the one I suggest you, since it is more powerful and you will reuse this a lot of times. Moreover it will detect the "change" of state, thus avoiding the continuous analogWrite (in the previous code the analogWrite instructions are executed a lot of times).

Just define a state machine as two states (state 1, where LED3 is 127 and LED4 is 254, and state 2, where LED3 is 254 and LED5 is 127). The transitions will be after 500ms in each state, but I'll make two separate constants so you can trim them later. Usually each state has a function to be performed when you enter the state, a function to run continuously, a function when you exit and one or more transitions. The way to perform this is

1. calculate if there is a state change
2. if there is, perform the exit functions of the previous state and the enter functions of the next state
3. advance to the new state
4. perform the actions to be done continuously in the new state

In our case just state transition, enter and advance should be implemented. Usually you use a switch case on a variable holding an index for the state. In this case, for instance,

```
int LED3 = 5;
int LED4 = 6;

// just one tracking, since there is only one sequence
unsigned long previousMillis=0;

int state1duration = 500;
int state2duration = 500;

uint8_t state;

void setup() {
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);
    digitalWrite(LED3,LOW);
    digitalWrite(LED4,LOW);

    state = -1; // Invalid state, used to force a transition at startup
}

void loop() {
    unsigned long currentMillis = millis();

    // Check the transition
    uint8_t nextState = state;
    switch (state)
    {
    case 1: // Transition for state 1
        if ((currentMillis - previousMillis) >= state1duration)
        {
            nextState = 2;
            previousMillis += state1duration;
        }
        break;
    case 1: // Transition for state 2
        if ((currentMillis - previousMillis) >= state2duration)
        {
            nextState = 1;
            previousMillis += state2duration;
        }
        break;
    default: // When unknown state, go to state 1
        nextState = 1;
        break;
    }

    // If there is a change, perform the enter functions
    if (nextState != state)
    {
        switch (nextState) // enter functions of the next state
        {
        case 1: // Entering state 1
            analogWrite(LED3, 127);
            analogWrite(LED4, 254);
            break;
        case 2: // Entering state 2
            analogWrite(LED3, 254);
            analogWrite(LED4, 127);
            break;
        }
    }

    // Advance to the new state
    state = nextState;
}

```

This can be more complicated, but believe me, it is not. Once you get what this means you will be able to solve a lot of problems this way.

According to my experience, never try to simplify this to your particular problem, since it will make things more complicated. Just add, when needed, the exit functions (before switch(nextState) put another switch on state) and the execution (after the advancing, put another switch on state) if needed.
> 1 votes

# Answer
You are trying to use millis() exactly like delay(). The method delay() stops the program from progressing forward. It blocks the program. This is frowned upon as the processor could be doing something useful during this time.

The method millis() does not stop the program. Instead it is like telling you what time it is. It is your code that then need to know at what time you want to do something.

But in your code, you are doing something odd. You are switching the brightness of the LEDs then IMMEDIATELY switching them back. You are using the same time for the two things you want to do. Instead try to initialize previousMillisLED4 to 500, intervalLED3 to 1000 & intervalLED4 to 1000.
> 1 votes

# Answer
The final sub routine...I did move the counter to get a better result. The variable "ditchFlag" is set in an IF statement further up in the sketch. The duration of the subroutine is a combination of the timers and the number in "count".

```
void ditchDim() {
while (ditchFlag == 1) {            //set to 1 when conditions are met

unsigned long currentMillis = millis();

if ((currentMillis - previousMillis) < endOfPhase1) {
    analogWrite(LED3, 127);
    analogWrite(LED4, 254);
}
else if ((currentMillis - previousMillis) < endOfPhase2) {
    analogWrite(LED3, 254);
    analogWrite(LED4, 127);
}else{
  count = (count+1);
    previousMillis += endOfPhase2;
    }
      if (count == 5) {
        count = 0;
        ditchFlag = 0;
        return;
    }
  }
}

```

thanks Doug
> 0 votes

---
Tags: millis
---


# Question
Title: Why is the nRF24L01 not working with Arduino Esplora?
I am working on a remote control car from an Arduino Esplora board and the Mega 2650 Board. My problem lies with the Esplora board as the nRF does not transmit like it is supposed to or does not even transmit at all.

I am using the `pingpair_test.ino` from the RF24 library to make sure the transceiver is working, and when I try to transmit on the serial monitor, I get the following output:

```
Configuration = t

STATUS = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0

RX_ADDR_P0-1 = 0x0000000000 0x0000000000

RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00

TX_ADDR = 0x0000000000

RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00

EN_AA = 0x00

EN_RXADDR = 0x00

RF_CH = 0x00

RF_SETUP = 0x00

CONFIG = 0x00

DYNPD/FEATURE = 0x00 0x00

Data Rate = 1MBPS

Model = nRF24L01

CRC Length = Disabled

PA Power = PA_MIN

Now sending length 4...No responses received. Are interrupts connected?

```

I have no idea what any of this means besides the interrupts part.

Even using `interrupts();` the Arduino Esplora still refuses to send data. I am sure my wiring is correct because the status light on the nRF is on and I triple checked all of the SPI pins.

On the Esplora:

* CE = 0
* CSN = 1

On the Mega:

* CE = 51
* CSN = 50

I have a fritzing sketch here for those who want to see my wiring.

# Answer
Funny you should ask, I have been playing with nRF24 for a while, and was thinking of trying out my Esplora. There are however a few problems, which have postponed this (read: can't be arsed).

1. Pins. You need access to the SPI pins + 2 other pins. On the code you linked to, it's 8 and 9. Which won't work on an Esplora: D9 is not broken out, and D8 is CARD\_CS. Better leave that alone. Your best bet would be to use the ICSP header and the two orange TinkerKit pins, D11 & D3.

**\[UPDATE\]** Also, the RF24 library uses `D2` for IRQ, which is going to be slightly inconvenient on an Esplora, as this pin isn't broken out either. TMRh20 doesn't use an IRQ pin. Neither does Mirf.

2. As you can see, the Esplora is on 5V, which could give the nRF24 module a headache. You'll have to step that down to 3.3. Way too much work for me, but then again I'm lazy.
3. If you're planning on using the screen, the ICSP header is kind of in an awkward place. I've tried fitting regular cables under the screen, and all I've got for my pains was a big dose of what the heck.
4. Stand-alone power. If you're planning to use the Esplora as a standalone, you'll need a battery and a voltage stepper. So in the end, you could use the voltage of the battery for the nRF24 module, and the 5V output from the stepper for the Esplora. More work, grrr.
> 0 votes

# Answer
Looking at your output either you have a wrong wiring or, more probably, you need a capacitor between the nRF24 positive and negative pins: anything between 10uF and 100uF will do.
> 0 votes

---
Tags: spi, nrf24l01+, rf, arduino-esplora
---


# Question
Title: Win10 64bit, IDE 1.8.0 back to IDE 1.6.13 won't compile anything including Blink. 1.6.12 does compile
Arduino: 1.8.0 (Windows 10), Board: "Arduino/Genuino Uno"

c:\program files (x86)\arduino\hardware\tools\avr\bin../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied

exit status 1 Error compiling for board Arduino/Genuino Uno.

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

# Answer
Try locating the code file in explorer.exe, go to its properties and check if the system has full access to the file. Just to be sure, run the Arduino IDe as an administrator.
> 1 votes

---
Tags: compile, ide
---


# Question
Title: System voltages: Can I use a 5V touchscreen shield on a 3.3V arduino?
The system voltage on my arduino 101 is published at 3.3V, even though it also has a 5V output pin.

My Seeedstudio touchscreen is supposedly a 5V device. http://wiki.seeed.cc/2.8inch\_TFT\_Touch\_Shield\_v2.0/

I believe I've successfully ported the library for this touchscreen to the 101 because it now runs and compiles on both the 101 and the Mega, although it gives erroneous values on the 101. Could it be because of this voltage difference? is there any way to fix it?

Edit- I should add that the 101 is labeled as "5V tolerant".

Edit II: I've found a pretty informative review that explains a little bit about how the 101 is supposed to work with 5V peripherals. I'm not sure though how it could work in cases where a shield does not recognize 3.3V as logic high. Usually 3.3V is right around the cutoff voltage for many circuits. http://www.tweaktown.com/reviews/7706/intel-curie-based-arduino-101-programmable-microcontroller-review/index2.html

# Answer
> 1 votes
You'll probably need a fairly common device known as a logic level converter. One such example, in breakout board form, can be found here: https://www.sparkfun.com/products/12009

There are tons of other options depending on what exactly you need.

---
Tags: voltage-level, 101
---


title: ESP-01 won't start correctly

text:
# Question
Title: ESP-01 won't start correctly
I'm trying to connect my Arduino Uno to an ESP-01 module, but I can't get it to start correctly. All I can get out from the ESP-01 is an "invalid" message when it is enabled. Can anyone please help? Additional information can be found below.

Here's my configuration:

* Arduino connected to a computer via USB cable (serial connection working)
* ESP-01 connected to the same UART connection, TX from Arduino is lowered to 3,3V with resistors
* ESP-01 powered with external battery + capacitor to ensure sufficient current
* I've tried all different configurations with GPIO0 and GPIO2 connecting them to ground and 3,3V, with and without resistors.
* I've tried 3 different ESP modules

Here's how things work:

* Arduino sends back every received UART transmission so that I can monitor the whole thing.
* I can send messages to Arduino from a terminal on the PC and Arduino responds.
* I can send messages from Arduino by pressing a button and the messages can be seen on the terminal.
* When I send AT\r\n from Arduino I can read it on the terminal but nothing happens on the ESP-01.
* When I send exactly the same message from the terminal, the blue light on ESP flashes but there is no response from the ESP. Arduino sends that message back to terminal of course.
* When I connect CH\_PD to 3,3V the ESP gives a message: Ai-Thinker Technology Co. Ltd. invalid
* The baud rate is correct (115200) since I can only read that invalid message on this rate

# Answer
> 2 votes
Sharing the hardware UART between the terminal and the ESP generally does not work well. You'll be much better off to add a SoftwareSerial port on another pair of pins to talk the the ESP.

---
Tags: arduino-uno, esp8266, wifi
---


# Question
Title: Show images on a monitor using Arduino via Wifi
Consider a computer monitor hanging on a wall. Next to it is an Arduino Uno with a wifi. Is it possible to create something like this? Using wifi it should be possible to send data (images) to Arduino. This will be output to a monitor, like an image gallery. Images can be any type (videos included).

Is it possible? Where does one start?

Thank you.

# Answer
> 4 votes
I have somewhere in my stash a shield that enables an Arduino to overlay graphics on the screen. But it is kinda crude and low-res. What you're trying to achieve is definitely not for Arduino, it is way underpowered.

You'd better look into doing this with something like a Raspberry Pi.

# Answer
> 1 votes
What you want is the GameDuino shield which gives you a full VGA experience on your Arduino. Also good for making games with.

# Answer
> 1 votes
For the novice/intermediate, this is going to take way too much time and effort to meet the requirements you have asked with an Arduino Uno (if it is even possible).

May I suggest a Raspberry Pi instead.

The Raspberry Pi (depending on the model) has multiple video outputs:

* HDMI
* Composite video
* LCD display

Each of these video outputs require very little effort to get going.

Adding WiFi capability requires just a USB WiFi dongle (and possibly downloading a driver) a bit of set-up and that about it. The RPi 3 (Model B) has on-board WiFi so you won't need the dongle.

What you want is very similar to a digital photo frame, so I would search for people who have already done that using google. I imagine that there would be plenty of free code/software out there on the internet.

All of this is a lot easier on the Raspberry Pi compared to using the Arduino.

---

pcDuino is another hardware platform much like the Raspberry Pi that would meet your requirements. The pcDuino is less popular than the Raspberry Pi and so there may be less open source code out there in cyberspace - but it would still be worth a try.

---
Tags: arduino-uno, wifi, display
---


title: RS232-TTL Data Transmission

text:
# Question
Title: RS232-TTL Data Transmission
I'm developing an computacional module to create risk maps in agriculture, I am using one arduino mega as "GreenSeeker", generating "fake" data to transmit via RS232 connection to one Raspberry PI, where she is process the data and generate the maps with GPS coordinates.

But, I have this cable.

I need to transmit data throught Arduino mega, and catch this data in the Raspberry PI.

I\`ve have doubt about where connect the Serials pins on Arduino, the USB go on connect on the Raspberry PI USB, and the Serial go on Arduino, i need the right pins and where to connect them, and some code example.

# Answer
> 1 votes
I think you just want a normal USB A-B cable, exactly like you'd use on a PC.

You probably could use the cable you picture, but you'd need a female DB-9 connector. If you really want to do that for some reason, you need to connect the Tx pin on the DB-9 (pin 2) to the Rx pin on the Mega, and the Rx pin on the DB-9 (pin 3) to the Tx pin on the Mega.

---
Tags: serial, arduino-mega, usb, communication, rs232
---


# Question
Title: Need help with the basics on serial control
I am struggling to get my head around why this just won't work. In my simple mind this simple sketch should do as it's told. But I am obviously missing something fundamental.

If anyone could shed some light on what I am doing wrong that would be very good!

The sketch is just to control a relay by typing on or off into the serial monitor. However although it uploads, all I get is the `Serial.println` repeating and no action on the physical relay.

I can manage to control things over serial by using the switch, case statements but I wanted to try it using full words rather than single chars and also using IF statements etc.

Thanks in advance!

***EDIT*** I just changed the string inputs to a char input and `serial.readstring` to just `serial.read` and it works with just entering a 1 or a 2 for example. So to re-ask my question - how can I get it to respond the same but using words? Thanks!

```
int relay=8;
String serialInput;

void setup() {
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
}

void loop() {
  Serial.println("To toggle relay enter on or off");
  while (Serial.available()==0) {}
  serialInput = Serial.readString();
  if(serialInput=="on") {
    digitalWrite(relay, HIGH);
  }
  if(serialInput=="off") {
    digitalWrite(relay, LOW);
  }
}

```

# Answer
> 3 votes
You are assuming that `Serial.readString()` will magically know how long a string you meant to send, and wait until it's all there. It doesn't guarantee that.

If your PC uses Linux or Mac, you can use `Serial.readStringUntil('\n')`, which will read until a line end, and send `on<ENTER>` as your command.

If you use Windows, the line endings are `\r\n` so it's a bit more awkward. Build up your string piece by piece, perhaps

```
int relay=8;
String serialInput;

void setup() {
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    char c = Serial.read();   // get one byte from serial buffer
    if ('\r'==c || '\n'==c) {
      // End of line - process the string
      if(serialInput=="on") {
        digitalWrite(relay, HIGH);
      } else if (serialInput=="off") {
        digitalWrite(relay, LOW);
      }
      serialInput = "";
    } else {
      serialInput += c;     // add it to readString
    }
  }
}

```

Brief description of how it works:

The string `SerialInput` starts empty. We do the following repeatedly:

* If there is a character available on the serial port, read it.
* If it is not an end-of-line character, add it to the end of our string
* If it IS an end-of-line character, we know we've got to the end of the line, so...
    + check whether it matches one of our "target" strings, and act on it if so
    + clear it back to an empty string

---
Tags: arduino-uno, serial, relay
---


# Question
Title: Equivalent for PORTB in Arduino Mega 2560
Like I said in the subject, I would like to know the equivalent for the instruction:

```
PORTB |= 0x01;
PORTB &= ~0x01;

```

More precisely I was using it to trigger a fast pulse conversion on my shield-ADC on an Arduino Uno. Now I am using an Arduino Mega 2560.

Can you write the exact same instruction for ATMega2560?

# Answer
This code sends a pulse on pin PB0, which on the Uno is equivalent to digital 8. On the Mega, digital 8 is PH5, thus you would write

```
PORTH |= _BV(PH5);
PORTH &= ~_BV(PH5);

```

The equivalence between the Arduino pins and the AVR pins is provided in the official documentation, but there are nicer versions at pighixxx.com:
> 4 votes

# Answer
The other answer has provided correct information and useful documentation on the question as asked. This answer uses a slightly more portable method of producing a brief pulse on a given digital pin.

This more-portable method uses some standard (although not well-documented at arduino.cc) functions to get port numbers, port pointers, and bit masks from a pin number. These functions – `digitalPinToPort()`, `portInputRegister()`, and `digitalPinToBitMask()`– can be used at run time to compute physical ports and pins from Arduino pin numbers. In some cases the computation could occur at compile time if compiler is smart enough or is allowed to optimize. But avr-gcc as configured for the Arduino IDE is not so allowed, which is a reasonable default for embedded programming.

This method also uses the fact that an AVR pin – as on most Atmel-based Arduinos – will toggle when you write a 1 to its bit in its input register. For example, see §14.1 in Atmel doc8271, the ATmega48A/PA/88A/PA/168A/PA/328/P datasheet, which states:

> Three I/O memory address locations are allocated for each port, one each for the Data Register – PORTx, Data Direction Register – DDRx, and the Port Input Pins – PINx. The Port Input Pins I/O location is read only, while the Data Register and the Data Direction Register are read/write. However, **writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register**. ...

---

# Example program

```
/*  jiw - Jan 2017 - toggle Arduino digital pin 8 several ways
Re: http://arduino.stackexchange.com/questions/33033/equivalent-for-portb-in-arduino-mega-2560 */
volatile uint8_t *portofpin;
uint8_t bitofpin;
void setup() {
  pinMode(8, OUTPUT);       // Set pin as output
  portofpin = portInputRegister(digitalPinToPort(8));
  bitofpin = digitalPinToBitMask(8);
}
void udelay() {
  delayMicroseconds(5);
}
void loop() {
  PORTB |= 0x01;        // Set Uno pin 8
  PORTB &= ~0x01;       // Clear Uno pin 8
  udelay();
  PINB = 1;         // Toggle Uno pin 8
  PINB = 1;         // Toggle Uno pin 8
  udelay();
  PINB = bitofpin;      // Toggle Uno pin 8
  PINB = bitofpin;      // Toggle Uno pin 8
  udelay();
  *portofpin = bitofpin;    // Toggle Arduino pin 8
  *portofpin = bitofpin;    // Toggle Arduino pin 8
  udelay();
}

```

---

# Compilation on Uno

`loop()`, from compilation of the example program for an Uno board:

```
void loop() {
  PORTB |= 0x01;                // Set Uno pin 8
 10e:   28 9a           sbi     0x05, 0 ; 5
  PORTB &= ~0x01;               // Clear Uno pin 8
 110:   28 98           cbi     0x05, 0 ; 5
  udelay();
 112:   0e 94 83 00     call    0x106   ; 0x106 <_Z6udelayv>
  PINB = 1;                     // Toggle Uno pin 8
 116:   81 e0           ldi     r24, 0x01       ; 1
 118:   83 b9           out     0x03, r24       ; 3
  PINB = 1;                     // Toggle Uno pin 8
 11a:   83 b9           out     0x03, r24       ; 3
  udelay();
 11c:   0e 94 83 00     call    0x106   ; 0x106 <_Z6udelayv>
  PINB = bitofpin;              // Toggle Uno pin 8
 120:   80 91 00 01     lds     r24, 0x0100
 124:   83 b9           out     0x03, r24       ; 3
  PINB = bitofpin;              // Toggle Uno pin 8
 126:   80 91 00 01     lds     r24, 0x0100
 12a:   83 b9           out     0x03, r24       ; 3
  udelay();
 12c:   0e 94 83 00     call    0x106   ; 0x106 <_Z6udelayv>
  *portofpin = bitofpin;        // Toggle Arduino pin 8
 130:   e0 91 01 01     lds     r30, 0x0101
 134:   f0 91 02 01     lds     r31, 0x0102
 138:   80 91 00 01     lds     r24, 0x0100
 13c:   80 83           st      Z, r24
  *portofpin = bitofpin;        // Toggle Arduino pin 8
 13e:   e0 91 01 01     lds     r30, 0x0101
 142:   f0 91 02 01     lds     r31, 0x0102
 146:   80 91 00 01     lds     r24, 0x0100
 14a:   80 83           st      Z, r24
  udelay();
 14c:   0c 94 83 00     jmp     0x106   ; 0x106 <_Z6udelayv>

```

As you can see in the above, instead of using read/modify/write sequences to implement `PORTB |= 0x01; PORTB &= ~0x01;`, the compiler produced `sbi 0x05,0; cbi 0x05,0;`, to directly set and then clear bit 0 of register 5, PORTB. This uses 4 clock cycles total, producing a pulse that's high for 2 cycles.

avr-gcc implemented `PINB = 1; PINB = 1;` via `ldi r24, 1; out 3,r24; out 3,r24`, which takes 3 cycles total and produces a pulse that's high for 1 cycle.

It implemented `PINB = bitofpin; PINB = bitofpin;` via `lds r24, 0x0100; out 3,r24; lds r24, 0x0100; out 3,r24`, which takes 6 cycles total and produces a pulse that's high for 3 cycles. (In `setup()`, the value of `bitofpin` was stored in RAM location 0x100, and the value of `portofpin` was stored in 0x101, 0x102.)

Finally, it implemented `*portofpin = bitofpin; *portofpin = bitofpin;` via a six-instruction sequence that takes 14 cycles and produces a pulse that's high for 7 cycles. Obviously, the compiler could have produced a 4-instruction sequence (by not reloading r30, r31, and r24) that takes 8 cycles and a pulse that's high for 1 cycle, but it didn't.

---

# Compilation on Mega

`loop()`, from compilation of the example program for a Mega or Mega 2560 board:

```
void loop() {
  PORTB |= 0x01;                // Set Uno pin 8
 218:   28 9a           sbi     0x05, 0 ; 5
  PORTB &= ~0x01;               // Clear Uno pin 8
 21a:   28 98           cbi     0x05, 0 ; 5
  udelay();
 21c:   fa df           rcall   .-12            ; 0x212 <_Z6udelayv>
 21e:   81 e0           ldi     r24, 0x01       ; 1
  PINB = 1;                     // Toggle Uno pin 8
 220:   83 b9           out     0x03, r24       ; 3
 222:   83 b9           out     0x03, r24       ; 3
  PINB = 1;                     // Toggle Uno pin 8
 224:   f6 df           rcall   .-20            ; 0x212 <_Z6udelayv>
  udelay();
 226:   80 91 00 02     lds     r24, 0x0200
  PINB = bitofpin;              // Toggle Uno pin 8
 22a:   83 b9           out     0x03, r24       ; 3
 22c:   80 91 00 02     lds     r24, 0x0200
  PINB = bitofpin;              // Toggle Uno pin 8
 230:   83 b9           out     0x03, r24       ; 3
 232:   ef df           rcall   .-34            ; 0x212 <_Z6udelayv>
 234:   e0 91 01 02     lds     r30, 0x0201
  udelay();
 238:   f0 91 02 02     lds     r31, 0x0202
  *portofpin = bitofpin;        // Toggle Arduino pin 8
 23c:   80 91 00 02     lds     r24, 0x0200
 240:   80 83           st      Z, r24
 242:   e0 91 01 02     lds     r30, 0x0201
 246:   f0 91 02 02     lds     r31, 0x0202
  *portofpin = bitofpin;        // Toggle Arduino pin 8
 24a:   80 91 00 02     lds     r24, 0x0200
 24e:   80 83           st      Z, r24
 250:   e0 cf           rjmp    .-64            ; 0x212 <_Z6udelayv>

```

The assembly code for Mega is much the same as that for the Uno, except that `bitofpin` and `portofpin` values were stored in RAM 0x200–0x202 instead of 0x100–0x102, and `rcall` or `rjmp` was used to call `udelay();`, instead of `call` or `jmp`.

---

# Making assembly listings

To make assembly listing files for a program, use a command like

```
avr-objdump -CSI$PWD $TMPPATH/togglepin8.cpp.elf > togglepin8.ino.mega.asm

```

where `$PWD` represents the current working directory that contains a sketch like `togglepin8.ino`, and `$TMPPATH` represents whatever temporary directory the IDE stuck the source in to compile and link it. The C switch (not used for above listings) tells avr-objdump to demangle symbols. Switch S says to display source code intermixed with disassembly if possible. Switch I tells location of source code.

---

# Conditional compilation

Conditional compilation is another way to make the source code portable to several Arduinos. For example, near the beginning of the sketch one could include the following `#ifdef` and `#define` statements to set up `BITOFPIN` and `PORTOFPIN` values for later use:

```
#ifdef ARDUINO_AVR_UNO
#define BITOFPIN  1
#define PORTOFPIN PINB
#endif
#ifdef ARDUINO_AVR_MEGA2560
#define BITOFPIN  _BV(PH5)
#define PORTOFPIN PINH
#endif

```

To find out what board-dependent symbols are defined at compile time, turn on verbose output during compilation and look for flags of the form `-Dsym=val`.
> 4 votes

---
Tags: arduino-mega, port-mapping
---


title: Multiple tones with one piezo buzzer

text:
# Question
Title: Multiple tones with one piezo buzzer
I have figured out how to make a piezo buzzer play two tones at once with `analogWrite()` and `tone()` but how would I make an actual song by playing both bass and treble, such as this one. Here is the circuit I had to do it:

and here is the code I had to do it:

```
int buzzer1 = 9;
int buzzer2 = 10;

void setup() {
  pinMode(buzzer1, OUTPUT);
  pinMode(buzzer2, OUTPUT);
}

void loop() {
  analogWrite(buzzer1, 100);
  tone(buzzer2, 262);
}

```

# Answer
First of all - You can drain max 20mA via pin, when one of the pins is HIGH and the other LOW, there is 5V between them, so there should be at least 250 Ohm resistor placed there, if you do not want damage your Arduino. I sugest add, to each of the red wires, at least a 200 Ohm resistor (to be safe).

For playing melody you have to save it somewhere, probabely easiest way is in arrays, and then play it note by note at regular intervals.

something like this (but insert your notes and set the length correctly):

```
int num_tones=6;
int tones1[] = {100,200,400,200,100,50};
int tones2[] = {262,131,131,262,131,524};

void loop() {
  for (int i=0;i<num_tones;i++){
    analogWrite(buzzer1, tones1[i]);
    tone(buzzer2,tones2[i]);
    delay(250);
  }
}

```
> 2 votes

# Answer
I completed the following project https://github.com/linhartr22/count

Plays PWM files on Arduino through piezo speaker.

Most of the results came from the following page:

http://highlowtech.org/?p=1963

I'm using the https://github.com/damellis/PCM/zipball/master library mentioned there. count.ino is my sample sketch. As the web site mentions the audio comes out on Digital I/O pin 11. I've tested with both a piezo buzzer and a 4 ohm speaker. I'm really impressed. It does mess with some of the PWM timers so this may not be suitable for all applications.

I used Audacity to convert the sample wave files I was provided into PWM. The .h files are included in this repo.

The number of notes you can hold on the Arduino will depend on the size of the wave samples. If you need more notes, it might be possible to extend this with an SD card reader or other form of memory. It wasn't required for my project.
> 0 votes

---
Tags: arduino-uno, pwm, piezo
---


# Question
Title: Arduino Nano 3.0 and Arduino Uno Benchmarks
What are the benchmarks (MIPS) of an Arduino Uno (ATmega32P) and Arduino Nano 3.0 (Atmega328) @ 1.6MHz?

# Answer
> 2 votes
ATmega16U4/ATmega32U4, ATmega48A/PA/88A/PA/168A/PA/328/P, ATmega2560, and numerous other Atmel AVR 8-Bit microcontrollers have an instruction set typically with “135 Powerful Instructions – Most Single Clock Cycle Execution” per datasheets.

That is, many of the AVR instructions, including almost all of the logic and arithmetic instructions, execute in 1 cycle. A fair number of memory access instructions take 2 cycles. A few instructions (eg JMP) take 3 cycles, and some (RCALL, CALL, RET, RETI, et al) take 4 or 5 cycles. Others (eg SBRC) take 1, 2, or 3 cycles, depending on operand values and whether a branch occurs that disrupts the pipeline, which is shallow. For an overview, see the instruction set summary in any AVR-part datasheet. For details, see Atmel's AVR Instruction Set Manual, doc0856 at atmel.com.

Overall, the average instructions per second in a typical compiled C program probably is between 1.5 and 2, so a 16 MHz system might do 8 to 11 MIPS on average, while carefully tailored do-nothing code can easily achieve 16 MIPS.

# Answer
> 0 votes
Do you mean 16MzHz?

Benchmarks are here.

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


# Question
Title: ATtiny85 AC Phase Control for dimming a light bulb
I'm trying to dim a light bulb via an ATtiny85, which accepts commands sent over I2C. My problem is that the bulb is barely dimming and is flickering quite a bit.

My circuit can be seen here:

The opto-isolator (and thus the triac) is controlled via pin 2 (AKA PB3, AKA PCINT3) and AC zero cross detection is done on pin 3 (AKA PB4, AKA PCINT4) on the ATtiny85.

The code uses Pin Change Interrupt Enable rather than the single External Interrupt Enable, because the External Interrupt pin is pin 7 (aka PB2), which is used as the SCL for the I2C communication.

The 8MHz internal clock is used and the timer/counter prescaler is 1024, which means that I have an effective input range (see `level` variable in the code) of roughly 0-65. My AC source is USA (60Hz).

```
#include <avr/interrupt.h>
#include <avr/io.h>
#include <TinyWireS.h>

#define PULSE 4       //trigger pulse width (counts)
#define I2C_SLAVE_ADDR 0x4 // the 7-bit address (remember to change this when adapting this example)

byte trigger = 3;
byte detector = 4;
byte level = 50;
byte maxLevel = 65;
byte minLevel = 0;

void setup() {
    TinyWireS.begin(I2C_SLAVE_ADDR); // join i2c network
    TinyWireS.onRequest(requestEvent); //setup i2c requester
    digitalWrite(detector, HIGH);  //enable pull-up resistor
    pinMode(trigger, OUTPUT);// Set AC Load pin as output
    TCCR1 = 0;     //stop timer
    OCR1A = level;    //initialize the comparator
    TIMSK = _BV(OCIE1A) | _BV(TOIE1); //interrupt on Compare Match A and  enable timer overflow interrupt
    GIMSK = 0b00100000; //Enable pin change interrupt
    PCMSK = 0b00010000; //PB4, physical pin 3 PCINT4
    TCCR1 = B00001011; //Prescale the timer
    sei();  // Turn on interrupts
}

ISR(PCINT0_vect) {
    //interrupt looking for zero crossing
    TCNT1 = 0;   //reset timer - count from zero
    OCR1A = level;
    TCCR1 = B00001011;// prescaler on 1024, see table 12-5 of the tiny85 datasheet
}
ISR(TIMER1_COMPA_vect) {
    //comparator match
    digitalWrite(trigger,HIGH); //set triac gate to high
    TCNT1 = 255-PULSE;
    //trigger pulse width for a few cycles for triac to latch on. 255 bc the counter can only count up to 255
}

ISR(TIMER1_OVF_vect) {
    //timer1 overflow
    digitalWrite(trigger, LOW); //turn off triac gate
    TCCR1 = 0;  //disable timer stop unintended triggers
}

void loop() {}

void requestEvent() {
    if (TinyWireS.available()) {
        level = TinyWireS.receive();
        if (level > maxLevel) {
            level = maxLevel;
         else if (level < minLevel){
            level = minLevel;
        }
    }
    TinyWireS.send(OCR1A);
}

```

I have tried a variety of bulbs (incandescent and dimmable LED), with none working any better than another.

Here is a video showing the zero cross detection (yellow) and the ATtiny85 trigger (blue) on an oscilloscope as I send it different dimming levels Bad phone video

I've thought about the snubber, I just don't have the parts on hand right now. I think it will help but I don't think it will correct whatever my larger issue is.

I'd appreciate all and any help. Thanks.

(Note: I also posted this here. Apologies if crossposting is frowned upon).

# Answer
So I think there were (was?) two issues.

1) Pin change interrupts on the Attiny85 are triggered on rising and falling edges which I think was causing the flickering.

I changed the code to rising edge only triggering:

```
ISR(PCINT0_vect){ //interrupt looking for zero crossing
        if (digitalRead(4) == HIGH){
                TCNT1 = 0;   //reset timer - count from zero
                OCR1A = level;
                TCCR1 = B00001011;// prescaler on 1024, see table 12-5 of the tiny85 datasheet
       }
}

```

2) Attiny85 #reset pin. Pulled that guy high with a resistor.

Anyways, here's the oscilloscope and dimming led blub video: youtube
> 0 votes

---
Tags: sensors, interrupt, timers, attiny, electronics
---


# Question
Title: Can I use the nRF8001 Bluefruit LE Breakout on 3.3V instead of 5V on my Arduino Uno?
I have an nRF8001 Bluefruit LE Breakout module and when I check images on how to wire it, the schematic looks like this with the 5V connection:

I was wondering whether it was possible to use the 3.3V instead. I looked at the documentation, it says this:

> By connecting 5.0V on the VIN pin, all of the signals will be level shifted between 5V for the Arduino and 3.3V for the nRF8001, meaning you don't need to worry about damaging the IC by providing logic levels that it can't safely handle.

And this, which confirms that it works, right?

> If you are using 3.3V logic, simply connect 3.3V from your development board to the VIN pin on the nRF8001 breakout.

I am pretty new, so I want to make sure, so I do not destroy any modules.

https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/hooking-everything-up

# Answer
> 1 votes
Yes. That nRF8001 board runs on 3.3V. And do make sure that using it with a 5V-Arduino, they put a regulator that steps down 5V to 3.3V. Which is why if you have 3.3V already, you connect it to Vin, and you're good to go.

---
Tags: arduino-uno
---


title: Creating Arduino library file

text:
# Question
Title: Creating Arduino library file
I need to create a library file for Arduino. While surfing the Internet, it shows me to use C, C++. Is a C++/C compiler mandatory to create library files in Arduino? Or we can use the Arduino IDE to create library files?

# Answer
Libraries are just text files. Use your favourite text editor (such as Sublime Text, Notepad++, etc. NOT a word processor like Word) to create and edit them. It is up to the IDE to compile them for you. You don't need anything else.
> 0 votes

# Answer
The Arduino IDE has a compiler, and will in the end compile the library with whatever `.ino` script you'll write. But you don't need any compiler to write a library. All you need is a text editor, and produce `.cpp` and `.h` files.

However when you test the library, you'll have to use the Arduino IDE to compile it.
> 0 votes

---
Tags: library
---


# Question
Title: How many modules can an Arduino Nano v3 support (in code)?
I'm planning to use an Arduino Nano v3 for a simple project plus some devices like capacitive touch buttons, an LCD display and a Bluetooth module on an I²C. Will these devices require (like classes or function in programming) that might take up the entirety of the 30KB space?

Devices:
HC-SR04 Distance Sensor
TTP229 Capacitive touch sensor
LCD1602+HD44780 LCD Display
HC-06 Bluetooth module

# Answer
The number of modules isn't really relevant; your PC deals with that during compilation and linking. The unbreakable requirement is that the total size of all the modules not exceed the size of available Flash memory.

The Bluetooth module won't need a library module unless you use SoftwareSerial to make another port for it. The two sensors' library footprints won't be too big. The LCD probably has at least one character table and maybe several sizes of each of several fonts. That's likely to be your largest one.

I always find microcontrollers' RAM size to impose much more stringent requirements than their Flash sizes.
> 0 votes

# Answer
The devices will require some code to make them work and there is a chance, depending on how you write the code, that this may consume all the available RAM on the chip. However I doubt you will go to more than 60% if you use the standard libraries for those devices, but there is only one way to find out...

Get the libraries for the devices and look at the examples for each device. You should be able to hack an "example" of your own that calls all 4 examples in the main loop(). This should give you an idea of how much memory you are going to use.

If you use too much it might be possible to snip pieces away from the libraries, the LCD will probably have font tables that you don't need for instance. Or you could use an alternative Arduino.
> 0 votes

---
Tags: arduino-nano
---


# Question
Title: How to flash an ATmega directly without a dedicated flashing device?
An ATmega microcontroller can be flashed by a C compiler and a USB dedicated device (ISP).

I tried to flash the program into the microcontroller by saving the machine code to a MicroSD card that I then attached to the microcontroller. I figure we can use the USB SPI reader to test the program without dedicated device like USBtiny.

But I suspect that the compiler is just producing the hex file and then the USB will translate it to machine code.

Was I thinking wrong?

If the compiler loads the machine code through the USB programmer to microcontroller so don't we just need a MicroSD USB to program it?

# Answer
Your initial assumption "An ATmega microcontroller can be flashed by a C compiler and a USB dedicated device (ISP)." is wrong.

The C compiler converts the source code into assembly language. It is then passed to an assembler which converts it to object code. The linker then creates an ELF file from it all. That is then converted into a HEX file using `objdump`.

That HEX file is then loaded by another program, `avrdude`, which knows how to control the USB-connected programming device. That device then issues special instructions to the chip through the ISP port to copy the data loaded from the HEX file into the memory of the chip in the right way.

It's quite a complex procedure and you require some active component in the mix to do the job. Just connecting an SD card and hoping it will work is, I am sorry to say, a laughable concept. You require something that a) understands how to read data from an SD card and can interpret it, and b) knows how to program an ATMega through ISP.

It is possible to create something that does that, using another chip, such as another ATMega, and writing the software to do it. If you feel adventurous, of course. You would basically have created a stand-alone programmer, which has advantages when you want to do field upgrades, but is pointless when you are sat at your desk developing software.
> 1 votes

# Answer
The compiler doesn't do that, a separate program does that. For most ATMegas and most people, the program that does this is called avrdude. It interfaces with your ISP and transfers the code when you give it appropriate settings. See here:

http://www.ladyada.net/learn/avr/avrdude.html

So you get the hex from your compiler, and send that through avrdude to the chip using your ISP. At no point is the MicroSD necessary. FWIW, the ATMega must have its code loaded into its flash memory. It cannot run code from the Micro SD.
> 0 votes

---
Tags: atmega328, spi, usbasp
---


title: What does map() do?

text:
# Question
Title: What does map() do?
Regarding the following code:

```
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
ax = map(ax, -17000, 17000, -1500, 1500);

```

I know the reason for taking 17000 as value - that's 1g. But I am not getting how and why 1500 value is taken.

# Answer
The `map()` function is well explained here.

In short, it maps one range of numbers to another. In this case it will map `ax` from the range (-17000:17000) into the range (-1500:1500).

Imagine a ruler with both inches and cm on. If you have a measurement in inches, you can represent that same measurement (point on the ruler) in cm. Your "ruler" here has one scale ranging from -17000 to 17000, and another scale ranging from -1500 to 1500. You're finding the reading on the second side at the point `ax` on the first.

If you mean specifically why are those numbers used -- then I have no idea since you give no context.
> 3 votes

---
Tags: arduino-uno
---


title: Defining Serial UART

text:
# Question
Title: Defining Serial UART
I'm new to Arduino..

I'm currently trying to create a GPRS connection through SIM card. For that, I need to connect a serial UART port.

I don't know how to define the Serial UART. Could you please help me with that?

# Answer
In the setup function you will need to call the `Serial.begin()` function.

To receive a serial character you should call the `Serial.available()` function inside an if statement.

To send a character you can either use the `Serial.write()` or `Serial.print()` functions.

Below is a simple example program that will echo the characters back to the PC.

```
//-------------------------
// Simple serial loopback
//-------------------------

void setup()
{
  // initialize the serial communication:
  Serial.begin(9600);
}

void loop()
{
  byte inChar;

  // check if data has been sent from the computer:
  if (Serial.available())
  {
    // read the most recent byte
    inChar = Serial.read();
    // send back the charater
    Serial.write(inChar);
  }
}

```

There are plenty of "built-in" examples in the Arduino IDE that use the various serial functions. These can be viewed without any hardware attached. In the IDE go to `File` \> `Examples` and from there a lot of the examples for the serial UART are in the `Communications` section. Details of these examples can be found on the Arduino Tutorial site.
> 2 votes

# Answer
The Arduino has only one UART which is used for program upload and for the serial terminal output to your computer. While you can connect it to another serial device that will make debugging cumbersome as 1) you won't be able to send any debug output; and 2) you will need to change it back and forth between your computer and the GPRS as you re-build and upload your code. You pretty much *need* a second UART to do this any kind of conveniently.

Look up the library module called SoftwareSerial which can simulate a UART on a second pair of pins, with some limitations: It is limited to communicating at 9600 baud; it can not transmit and receive at the same time; at most, one SoftwareSerial port can be receiving (or even listening) at any one time; and it can interfere with some other internal hardware, notably the interrupt system and at least one of the timers. (The link points to the Arduino website whose documentation isn't always the very latest, but what's there will give you the idea).

In many cases, and yours is likely one of them, these are not show-stoppers, just something to be aware of as your code becomes more complex. As long as you can operate your device by occasionally sending it a string and receiving another in reply, and your system doesn't include other high-speed devices that must be serviced quickly when they request it, you probably won't notice the limitations.
> 1 votes

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


# Question
Title: Accessing Values From Array Within a Library
There are many great examples of how to access information from an array on the net. I ran into a specific case that has me confused. I am using a library for attiny 85 TinyPpmReader.h. This is a simple library that will take PPM signals in from a RC receiver running in pulse position mode and allows you to attach to a pin to process input. Easy enough.

In the code below, I ran into some confusion when trying to access the data in the array. I am trying to filter out a single channel in the ppm stream and print the contents of only 1 channel (Original example prints 8 channels) and eventually map that value to a servo. (I pasted the serial monitor ouput at the end of the code)

I tried accessing the variable stored in the array like this:

```
void loop()
{
for(uint8_t Idx = 1; Idx <= TinyPpmReader.detectedChannelNb(); Idx++) /* From Channel 1 to Max detected */

if(TinyPpmReader.detectedChannelNb == [5]) //Is this channel 6 in index 0-7?
{
Serial.println(TinyPpmReader.width_us[5); // if so, print only index 5 containing channel 6 values
}
delay(500);
}

```

Example unedited sketch from library

```
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

#define PPM_INPUT_PIN  2

void setup()
{
  Serial.begin(38400)
  TinyPpmReader.attach(PPM_INPUT_PIN);
}

void loop()
{

  Serial.print(F("* Period="));Serial.print((int)TinyPpmReader.ppmPeriod_us());Serial.println(F(" us *"));
  Serial.print(F("ChNb="));Serial.println((int)TinyPpmReader.detectedChannelNb());
  for(uint8_t Idx = 1; Idx <= TinyPpmReader.detectedChannelNb(); Idx++) /* From Channel 1 to Max detected */
  {
    Serial.print(F("Ch"));Serial.print(Idx);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(Idx));Serial.println(F(" us"));
  }
  delay(500);
}

```

The serial monitor prints this:

```
* Period=17928 us *
ChNb=8
Ch=1496 us
Ch=1744 us
Ch=896 us
Ch=1560 us
Ch=1640 us
Ch=1496 us
Ch=1536 us
Ch=1688 us

```

Any suggestions? It is probably something simple but I dont think I am googling the correct question to get the correct answer.

EDIT: That worked Mark!

New Code Mapping attempt (Compiles,does not work)

```
#include <TinyServo.h>
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

int PPM_INPUT_PIN = TinyPpmReader.width_us(3); //<------- Doesn't work

//int potpin0 = 3;    <---------          // This worked
int val0;                     // integer to store value

const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                       // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

#define PANSERVO 0
#define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

void setup()
{
  setupServos();
}

void loop()
{
  val0 = analogRead(PPM_INPUT_PIN);  <---------          // reads the value of the       potentiometer (value between 0 and 1023)            // reads the value of the 2nd potentiometer (value between 0 and 1023)
  val0= map(val0, 1000, 2000, 0, 180);
    // scale it to use it with the servo (value between 0 and 180)
       // scale it to use it with the servo (value between 0 and 180)

moveServo(PANSERVO, val0);

  delay(5);                           // waits for the servo to get there
}

```

# Answer
> 0 votes
This code (from the example) is what prints a single index - index `Idx`:

```
Serial.print(F("Ch"));Serial.print(Idx);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(Idx));Serial.println(F(" us")); }

```

To print, say, index 3 you'd use

```
Serial.print(F("Ch"));Serial.print(3);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(3));Serial.println(F(" us")); }

```

To simply *get* the value from index 3, without printing it:

```
int a = TinyPpmReader.width_us(3);

```

(assuming it's an `int`)

---
Tags: arduino-uno, c++, array
---


title: creating table in 24LC256

text:
# Question
Title: creating table in 24LC256
here i am doing some project with the help of Arduino UNO with External EEPROM (24LC256), All i want to create table and wants to store all data into 24LC256 External EEPROM,there are many library for internal EEPROM to create table with limited data as per size of arduino EEPROM but i have huge data to store so have to use External eeprom to do, so i can't find any proper library for doing that.!

can anyone tell me how to do that...

any suggestion..Please help me..

thanking you..

# Answer
> 0 votes
Simplest way to create a table is to view it as a vector of struct's. For performance it is good to make the struct size a multiple of the EEPROM page size.

```
struct row_t {
  ... column fields ...
};

uint32_t row_addr = TABLE_START_ADDR;
row_t data;
data.column = value;
...

eeprom.write(row_addr, &data, sizeof(data));
row_addr += sizeof(row_t);
...

```

Basically you need to map a two/multiple dimensional table onto a one dimensional address space (of the EEPROM). The programming language can help with some of the calculations (and hide them).

Cheers!

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


# Question
Title: How to print (or store) gps lat, lng value (TinyGPS++) with Bluetooth BLE nRF8001?
I have a u-blox gps module and I use TinyGPS (http://arduiniana.org/libraries/tinygpsplus/) to get out the lat + lng.

If i write...

```
Serial.println(gps.location.lat(), 6);

```

...out in the log I get the correct latvalue. Right now I however work with a BLE (https://www.adafruit.com/product/1697) and when I try to print it like this:

```
BTLEserial.print (gps.location.lat()`, 6);

```

I get a error: `no matching function for call to 'Adafruit_BLE_UART::print(double, int)'`

If I do this instead, the code runs...

```
BTLEserial.print ((gps.location.lat(),6));

```

But I do not get the correct lat, instead I get this value `6.00000000`

I have tried to store the lat like this:

```
double myLat;

myLat = (gps.location.lat(), 6);
BTLEserial.print (myLat);

```

But with that myLat also has a value of `6.00000000` which is not correct.

I tried this as well:

```
char sValueOne[16], sValueTwo[16];
char sBuffer[33];

strcpy(sBuffer,dtostrf(((gps.location.lat(),6)), 15, 8, sValueOne));
strcat(sBuffer,",");
strcat(sBuffer,dtostrf(((gps.location.lng(),6)), 15, 8, sValueTwo));

BTLEserial.write((uint8_t *)sBuffer, strlen(sBuffer));

```

But with that I still get `6.00000000`. I am starting to run out of ideas now to make this work. I have tried to send it both directly and store it but nothing works successfully.

So how can I adjust the code to be able to print (or store) gps lat, lng value (TinyGPS++) with Bluetooth BLE nRF8001?

Appreciate every help and tips!

# Answer
> 1 votes
The Arduino Stream/Print classes may sometime need some extra attention.

```
BTLEserial.println(gps.location.lat()`, 6);

```

The member function is available in the class Print but gets "hidden". You can help the compiler to find it with a prefix:

```
BTLEserial.Print::println(gps.location.lat()`, 6);

```

Cheers!

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


title: pulseIn() function not working

text:
# Question
Title: pulseIn() function not working
I want to find the length of upper one signal (purple one). So for that, i used pulseIn() function for that. But i just get 0 as a result in serial monitor.

```
int pulsepin = 8;
int value = 0;

void setup()
{
  pinMode(pulsepin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  value = pulseIn(pulsepin, HIGH);
  Serial.println(value);
  delay(1000);
}

```

Here, above is my arduino code which i used. I don't know why I don't get any reading except 0.

# Answer
`pulseIn()` returns an `unsigned long` (32 bits) not an `int` (16 bits), so you may have some truncation occurring in your program leading to a `0` value.

Hence you should modify your program as follows:

```
int pulsepin = 8;
unsigned long value = 0;

void setup()
{
  pinMode(pulsepin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  value = pulseIn(pulsepin, HIGH);
  Serial.println(value);
  delay(1000);
}

```

Also beware that `pulseIn()` has a timeout (it will not wait forever). This timeout is used for the whole completion of the pulse, i.e. first waiting for the signal to get `HIGH`, then waiting for it to get back `LOW`. If no pulse is detected and complete (**LOW -\> HIGH -\> LOW**) within this time, then `pulseIn()` will return 0.

Default timeout value is 1 second, but you can set any value (in microseconds) you want that can hold in an `unsigned long`:

e.g. if you need 10 seconds, then:

```
  value = pulseIn(pulsepin, HIGH, 10000000UL);

```

I am not sure why you use `delay(1000)` in your `loop()`, I would remove it as a pulse may occur during that time and it would not be seen by your program.

Here is a suggested update (I also used `const` where it made sense but that won't change program behavior):

```
const unsigned long PULSEIN_TIMEOUT = 10000000UL;
const int pulsepin = 8;
unsigned long value = 0;

void setup()
{
  pinMode(pulsepin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  value = pulseIn(pulsepin, HIGH, PULSEIN_TIMEOUT);
  Serial.println(value);
}

```

You may also want to avoid printing 0 values since they mean no pulse was detected:

```
void loop()
{
  value = pulseIn(pulsepin, HIGH, PULSEIN_TIMEOUT);
  if (value > 0)
    Serial.println(value);
}

```
> 5 votes

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


# Question
Title: How do I order the gcc compiler to generate -S flag in Arduino IDE
How can I set the Arduido IDE to generate the `-S` flag to gcc to see the machine code in Arduino? (the sketches)

# Answer
> 2 votes
Compiler flags are defined in the platform.txt of the board you have selected in the **Tools \> Board** menu. You can also add compiler flags via a `build.extra_flags` property in the boards.txt entry for the selected board.

---
Tags: arduino-ide, gcc
---


title: Controlling Arduino from Raspberry Pi

text:
# Question
Title: Controlling Arduino from Raspberry Pi
I am trying to control an Arduino Leonardo R3 to run some code when "triggered" from a Raspberry Pi. This would be in a loop so that it can be run multiple times. I have set up the Raspberry Pi and tested it with an LED and the output is working fine.

I then connected this to the Arduino and checked for a HIGH input from the RPi using an if statement.

```
void setup() {
  pinMode(7,INPUT);
  if(digitalRead(7)==HIGH) {
    // CODE IN HERE
  }
}

```

I found that this did not work as the if statement was always true because of pullup resistors not being used. I would greatly appreciate some guidance on this.

# Answer
You have to verify, at least:

A. if the 3.3V of the RPi can be read as high on the Atmega, if so you can connect them without any resistor.

B. if not, you have to use a voltage adapter (yes, other components and many possible solutions), otherwise you RPi GPIO will be ruined if using a pullup on the 5V.

The pullup and pulldown, in this case, should be used when you are in A and the peripheral support the higher voltage. This is not the case.
> 2 votes

# Answer
I don't have much experience about Arduino boards connected to the Pi, never tried anything other than Arduino Due, but I do have some experiences with ATmega328P directly attached to the Pi. The ATmega is clocked at 12MHz instead of 16 to guarantee a stable state at 3.3V supply voltage.

Physical connection takes 5 signal wires besides the 3.3V power rail, with the ATmega talking with the Pi over SPI as a slave device, using both slave select lines, one at the SS pin and the other at RESET pin. This allows communication over proper hardware interfaces while eliminates the need of a programmer or preprogrammed chips as the ATmega use its SPI interface as ICSP, this setup essentially keep ICSP properly wired to the Pi at all times. An additional pin can be used as a IRQ pin from the ATmega to the Pi.

About the protocol that part is up to yourself. There are endless possibilities and you can implement anything that fits your need and easy to use.
> 1 votes

# Answer
I have done this in a different manner.

I have used the UART TX pin of RPi connected to the RX pin of the arduino and sent serial messages from Arduino to RPi.

That worked fine.

But the thing is, what you have done is correct and has to work.

Please make sure that you have connected Arduino's ground and RPi ground together.

---

If you not do that and try the same code it has to work. Because the RPi and Arduino are in two different circuits, so in order to work, make them one make GROUND common.
> 1 votes

---
Tags: programming, pins, arduino-leonardo
---