body: I just started using Arduino and so far I've used both `delay()` and `delayMicroseconds()`. I was wondering what the difference between these two is, because it seems to me that they're the same.

title: delay() vs delayMicroseconds()

Answers: 1

body:
From the documentation:

> #delay()
##Description

>Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are 1000 milliseconds in a second.)

So... milliseconds vs. microseconds.


body:
I have an Arduino `DUE` and just got a `Micro OLED` display from SparkFun.

Using their library, when I try to compile I get the error below.  Other example code works just fine and I've programmed this thing a million times with my code.  So it's clearly in the SparkFun code.

Here is the SparkFun tutorial page with a description of the product:

https://learn.sparkfun.com/tutorials/micro-oled-breakout-hookup-guide?_ga=1.19136059.2055231411.1404437767

Here is the library I am using:

https://github.com/sparkfun/Micro_OLED_Breakout/tree/master/Firmware/Arduino/libraries/SFE_MicroOLED

Here is the error I get:

    Build options changed, rebuilding all

    /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp: In member function 'void MicroOLED::spiSetup()':

    /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:46:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
        ssport  = portOutputRegister(digitalPinToPort(csPin));
                ^
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:48:51: error: 'portModeRegister' was not declared in this scope
        ssreg  = portModeRegister(digitalPinToPort(csPin));
                                                         ^
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp: In member function 'void MicroOLED::i2cSetup()':
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:84:2: error: 'TWBR' was not declared in this scope
        TWBR = ((F_CPU / I2C_FREQ) - 16) / 2;
        ^
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp: In member function 'void MicroOLED::parallelSetup()':
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:109:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
        ssport  = portOutputRegister(digitalPinToPort(csPin));
                ^
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:111:51: error: 'portModeRegister' was not declared in this scope
        ssreg  = portModeRegister(digitalPinToPort(csPin));
                                                         ^
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:114:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
        wrport  = portOutputRegister(digitalPinToPort(wrPin));
                ^

    /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:119:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
        rdport  = portOutputRegister(digitalPinToPort(rdPin));
                ^
      Error compiling.

title: Why doesn't the Micro OLED library compile on my DUE?

Answers: 1

body:
That library is uses some AVR specific methods, that aren't implemented for the ARM processor in the Due.

I don't see a real easy way to port those methods.


body:
I'm new to the world of Arduino and I'm working on a wireless charging project that needs a 5.7MHz sine wave. I've tried using a Due and changing the PWM and DAC, but I can't get a clean sine wave at that frequency using anything I've found online. My signal is either way too low, or too high and horribly distorted.

Any help would be appreciated. I have access to a Mega, Due, Uno, and Mini.

title: High Frequency Sine Wave Generation

Answers: 3

body:
To generate a **square wave**, you only need to update the output at a rate of two points per cycle. (*Technically, when the Arduino's PWM output is configured for 50% duty cycle, that's a square wave at some frequency.*)

But to generate a clean **sine wave** (without a lot of **distortion**), you need to update a lot more frequenclly than two points per cycle. Personally I wouldn't want to go much below 20 points per cycle.

Imagine the sine wave is generated by a wheel that spins at some rate. Viewed from the edge, a point on the edge of the wheel traces out a sine wave. Viewed from the axle, you see the point going around in a circle.

Now instead of spinning the wheel continuously, suppose the wheel moves in steps of 30 degrees, 12 steps for a complete turn. Instead of a continuous sine wave, you get discrete steps of 0, 0.5, 0.866, 1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5, 0, 0.5, ...   Although this sequence approximates an ideal sine wave, it's pretty coarse because the steps are so large.

Now try 15 degrees per step (24 steps per cycle). Now you get 0, 0.259, 0.5, 0.707, 0.866, 0.965, 1, ... Much smoother, although the steps are still fairly noticeable.

So there will be less **phase error**, the more steps there are per cycle of the signal. That's not the only source of distortion however. There is also round-off error due to the limited resolution of the Digital-to-Analog Converter (DAC). For example, the value 0.866 I mentioned above should actually be an irrational value, half the square root of 3. Since it's an irrational number, there's no way for a real DAC to get this value exactly right. DAC output step values are ideally based on powers of two (1/2, 1/4, 3/4, 1/8, 3/8, 5/8, 7/8, etc.). And furthermore a real DAC can have offset error, gain error, non-linearity, as well as uncertainty about precisely when the new programmed value is reached.

There's also **frequency error** when the system's highest-frequency master clock is divided by an integer. If the Arduino UNO's master clock frequency is 16MHz, and the SPI setup function `setClockDivider()` is used to divide the master clock by 2, that's 8MHz. Divide by 3 and you get 5.333MHz. Divide by 4, that's 4MHz. Divide by 5, that's 3.2MHz. There's no way to get a clock frequency that's between these discrete steps. For small divisors, there's a big jump between steps. So if you needed to be able to smoothly adjust the frequency, you'd need a much higher master clock frequency. And, if you needed to configure the 16MHz Arduino UNO to an SPI clock frequency of exactly 5.7MHz, that's just not possible -- setClockDivider(2) is too fast, setClockDivider(3) is too slow, and setClockDivider(2.807017543859649) isn't supported by the hardware.

If your system could write to a DAC at an **update rate** of 12MHz, then 12 points per cycle gives a 1MHz output, and 24 points per cycle gives a 500kHz output. Or taking it the other way round, if you need to generate a 5.7MHz output waveform, then the DAC update rate needs to be somewhere around 100MHz to get a clean, low-distortion waveform. This is probably beyond the limit of what you can directly synthesize in software using something like an Arduino or a Raspberry Pi. A 16MHz Arduino UNO could maybe synthesize a few 100kHz using software synthesis, but at 1MHz there's going to be significant distortion.

Software-controlled`Direct Digital Synthesis` is very sensitive to timing, so the actual DAC update would need to be implemented in an **interrupt service routine**, run by a periodic timer. ( See https://electronics.stackexchange.com/questions/26363/how-do-i-create-a-timer-interrupt-with-arduino )  If you just used a while loop with a delay statement, then whenever the code needs to do something else, the waveform would just freeze up. This is more of a problem if the Arduino is trying to manage several other tasks at the same time as it is synthesizing the waveform.

**Hardware** `Direct Digital Synthesis` (DDS) is possible. Same principles. There needs to be a `phase accumulator`, which is just a counter that keeps track of the phase angle of the "wheel" that's generating the sine wave. *(The phase accumulator needs to be modulus 360 degrees or 2 pi radians, but there's no requirement to count in 1 degree steps. Better to divide the circle into 2^N slices so that 360 degress maps to the natural counter overflow value.)* And there also needs to be a lookup table with the sine value for each of those steps. This lookup table only needs to cover 90 degrees of the sinewave, because the waveform is symmetrical -- the other three quadrants can be found by 2's complementing the values and indexing from the other end of the table. Or, the sine can be approximated by a polynomial calculation. More steps x more DAC resolution requires a deeper, wider lookup table. There are integrated circuits available that perform the timing-critical actions, all the software needs to do is send some initial configuration to set it up. Changing the frequency only requires configuring a new frequency divisor value into the DDS chip, so the Arduino can manage other things without causing distortion.

If the original problem only needs one **fixed frequency under 200MHz**, and doesn't need any adjustment to that frequency, then the hardware gets a whole lot simpler. The crystal oscillator circuits that we use to generate the timing for digital circuits, are in fact analog to begin with. You can contact a crystal vendor and request a custom **AT cut crystal**; google `custom quartz crystal frequency` for quartz crystal vendors. Construction requires a careful printed circuit board layout; the white solderless breadboard commonly used in Arduino projects just doesn't work well above 10MHz. Granted, this fixed-frequency solution doesn't involve Arduino in any way, but if it solves the problem, that's what's important.

body:
I wonder for which purpose you would use a micro controller at all.

If you need a fixed frequency circuit, you could design just that.

If you need a generator with variable frequency, that would justify the Arduino, but in this case I would use the Arduino to control the frequency indirectly.

Ex: create a [VCO][1] and use the Arduino to adjust the voltage, through a [DAC][2]

  [1]: https://en.wikipedia.org/wiki/Voltage-controlled_oscillator
  [2]: https://en.wikipedia.org/wiki/Digital-to-analog_converter

body:
One problem (for me) is to know how much time lines of (C) code take to execute on a (16) MHz Arduino. This and the coding you use would set an upper limit to the sinewave frequency you could synthesise at a given quality.

You probably can't beat assembly language when time is tight.


body:
I want to avoid using the big USB B connector to program my Arduino Mega. Since there are those RX TX Pins I thought, it would be possible, to connect my USB - Wires from my PC directly to those RX TX Pins. `D+ -> TX and D- RX`. [This Post on Arduino Stackexchange][1] says, those wires are just connected, while [this post][2] says the exact opposite.

I'm confused. Is it possible or would I damage my board when connecting USB wireq to RX / TX pins on my Arduino?

  [1]: https://arduino.stackexchange.com/questions/3772/can-tx-and-rx-pins-on-the-uno-be-used-like-regular-digital-pins
  [2]: https://arduino.stackexchange.com/questions/4652/usb-d-d-to-arduino-mega-rx-tx

title: Connect Arduino via TX RX Pins to Computer's USB Port

Answers: 2

body:
Strictly Serial interfaces use ±15V, although this is uncommon these days (but then so are PCs with serial ports). ±12V, ±5V or even 0/+5V also exist. Connecting a ±15V interface to the Pi would destroy it. There are RS232 adapters to ensure safety.

If you are talking about connecting USB data lines to serial forget it. The voltages are the least of your worries, the USB serial encapsulates the data in a protocol.

body:
The first answer that you cite that you say says it is possible is in fact not talking about  what you are referring to  - it is discussing the use of the RX & TX pins directly when they are not being used for USB connection.

The second answer you cite is technically incorrect but "correct enough" in the context.

The answer to your question  is "It can be done but it requires a different boot loader, its slower, its technically inferior, it's less standard, it requires a degree of understanding (on someone's part) to get it going, and **it can be done**

It IS possible to access USB directly from digital I/O pins. As TX & RX are also standard digital I/O pins they could be used for this purpose BUT you need dedicated bootloader code to do this and it has inferior performance if a USB to serial converter is available. The eg ADAFruit Arduino Trinket uses this system.

_______________________________

Here is how the (or a)  [**ADAFRUIT Trinket Bootloader**](http://www.embedded-creations.com/projects/attiny85-usb-bootloader-overview/details) works. (The Trinket is not mentioned here but I'm told that this is what it uses. If not, it works in functionally the same manner).

This is in turn based on the [**USBaspLoader**](http://www.obdev.at/products/vusb/usbasploader.html)

A (very) simple "more or less Arduino compatible" development board which can use this system is [Metaboard](https://metalab.at/wiki/Metaboard). It's circuit diagram is shown below. As can be seen - it uses an ATMega168 and the USB connection is made to two standard digital I/O pins.

![enter image description here][1]

**"Metaboard" using ATMega168**

 - note USB connection to pins PD2 & PD4 - NOT via RXD on PD0 and TXD on PD1 via a serial to USB converter, as is more usual.

__________________

AND another version:  [**AVRUSBBOOT**](http://www.fischl.de/avrusbboot/)

![enter image description here][2]

________________

And **again**

[**BootloadHID**](http://www.obdev.at/products/vusb/bootloadhid.html)   They say  -

- BootloadHID is a USB boot loader for AVR microcontrollers. The uploader tool requires no kernel level driver on Windows and can therefore be run without installing any DLLs.

 BootloadHID is a USB boot loader for AVR microcontrollers. It can be used on all AVRs with at least 2 kB of boot loader section, e.g. the popular ATMega8. The firmware is flashed into the upper 2 kB of the flash memory and takes control immediately after reset. If a certain hardware condition is met (this condition can be configured, e.g. a jumper), the boot loader waits for data on the USB interface and loads it into the remaining part of the flash memory. If the condition is not met, control is passed to the loaded firmware.

 This boot loader is similar to Thomas Fischl’s avrusbboot, except that it is built on top of the HID device class. This implementation is more user friendly on Windows, since no kernel level drivers need to be installed.

  [1]: https://i.stack.imgur.com/ScLWt.jpg
  [2]: https://i.stack.imgur.com/uMRel.png


body:
I'm using this simple code

    #include <Bridge.h>
    #include <YunServer.h>
    #include <YunClient.h>

    YunServer server;

    void setup() {
      Serial.begin(9600);
      Bridge.begin();
      server.listenOnLocalhost();
      server.begin();
    }

    void loop() {
      YunClient client = server.accept();
      if (client) {
        Serial.println("client");
        process(client);
        client.stop();
       } else {
         Serial.println("no client");
       }
       delay(50);
    }

    void process(YunClient client) {
      String command = client.readStringUntil('/');
      Serial.println(command);
      if (command == "turnLeft") {
        Serial.println("Gira a sinistra");
      }
      if (command == "turnRight") {
        Serial.println("Gira a destra");
      }
      if (command == "goTo") {
        String value = client.readStringUntil('/goTo/');
        Serial.println(value);
      }
    }

but it seems to have problem with bridge (or server, or client, i cannot understand) because it only write "no client" on the serial.

I can not understand what is wrong.

title: Arduino Yun - Problem with bridge and client

Answers: 2

body:
Probably too late to answer your question. Your problem is on line

    if (client)

Change it to

    if(client.connected())

which actually returns true when client is connected.

body:
I presume you are wanting the print output to show up on the Serial Monitor but you have connected the Arduino IDE to the Yun via the WiFi port on your network. If this is the case, then change all refs of Serial.print to Console.print
This will direct the ASCII text to the Serial Monitor.


body:
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

title: Connecting to Nano via USB3

Answers: 3

body:
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.

body:
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

body:
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.


body:
I want to interface a GLCD with arduino uno. The GLCD is JHD12864E.   The connections are as shown in this image ![GLCD Connections](https://i.ytimg.com/vi/OmMnzDh4HAg/maxresdefault.jpg)

I downloaded the OpenGLCD library and uploaded HelloWorld program from it.
I got the error:
        stk500_recv() : programmer is not responding

Then I googled it and also tried to upload using ISP using another arduino. The program uploaded successfully, but i did not get any output on GLCD.

I am not getting this error when uploading any other sketches. Can anyone explain to me why do we get this error? And what is the solution to it?

title: Why does avrdude error appear when interfacing GLCD with arduino uno in ubuntu

Answers: 0


body:
My Ethernet shield dont have any MAC address, please tell me how to find the MAC address, I'm stucked! Here is the link from where I bought the Ethernet shield.
http://www.amazon.in/gp/product/B00AXVX5D0?ie=UTF8&at=&force-full-site=1&ref_=aw_bottom_links

title: Didn't have MAC address on Wiznet based ethernet shield (cloned)

Answers: 2

body:
You can set the Mac address to whatever you want.  Many of the example sketches will have one already present, but as long you follow the standard mac format it should be happy (I am using the same shield).  In the Examples menu, you should see Ethernet then Webserver where you can find the following example.  You can change it a bit, but most of the time I just leave it alone.

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

body:
Ethernet will work as long as two different machine in the LAN don't have the same MAC address, as @Nathan wrote in his answer.

The MAC address [is built by two parts][1], a prefix which are given to manufacturers of network devices and is called *OUI*, and a suffix that is the node part that manufacturers can use as they wish.

If you want to build an MAC address yourself, use a *Locally administered* address.  Universally administered and locally administered addresses are distinguished by [setting the second-least-significant bit of the most significant byte of the address][1].
That will make this address to not use any OUI prefix, as that bit is zero on OUI, which minimize the risk of two or more devices have the same MAC address in same LAN.

If you get the same MAC addresses you will get very strange results if they happen to be in the same LAN, I tell you.  Been there, done that, and it wasn't fun to debug.

Here are a [site that looks up MAC addresses][2] (and generate random ones).  But if you want to see which manufacturer have that MAC address, [you read it from IEEE and their list][3].

  [1]: http://en.wikipedia.org/wiki/MAC_address#Address_details
  [2]: http://www.macvendorlookup.com/
  [3]: http://standards.ieee.org/develop/regauth/oui/public.html


body:
My question isn't specific to Arduino but can concern Raspberry Pi and all Internet of Things homemake projects.

As I'm preparing a personal projet with sensors, data storage and visualisation/reporting web page (not yet Android app) I'm looking about Internet of Things platform.

It seems all that I can find are cloud related system. I would prefer a home localized solution but I'm not able to find one (and maybe open source) where datas don't go outside home.

The goal is to be able to :

send datas from my Arduino to a home storage server

store these data into database for later query (may be MySql)

trigger some computation or aggregation job over datas

prepare some graphs

generate some html page from template

option: allow Android client to connect and get datas/graphs

Before starting thinking how to create my own (non standardized) system is anyone can give me some advice ? some name of such existing system ?

Thanks

Thomas

title: Internet of Things at home only

Answers: 2

body:
I recently worked extensively on a Home Automation Project and here's what I would recommend based off of that:

 1. Use Arduino for hardware interfacing.
 2. Use Raspberry Pi for hosting your server.
 3. Write your server using Node.js (or Python if you wish).
 4. Use Express, Socket.io (or Python simple server). Google these.
 5. Use Serial (USB) for communication between Arduino and Raspberry Pi
 6. Use RF/BLE if you want to go wireless.
 7. Use Redis or MySQL for database.
 8. Use a graph JS API for charting.
 9. To build an android app, send http requests (or a Socket.io link), for communication.

This is a simple to implement, but you'll need to put some time. Good luck.
All of the above steps are abstracted from each other. This means that if you want to incorporate additional features, you can change any stage without affecting the whole.

body:
Setting up a basic webserver on the Raspberry Pi is fairly straightforward, and as long as you have a firewall and aren't port-forwarding the data will be restricted to your home network.  You can also setup the firewall on the Pi to allow only local access fairly easily.  I did a similar project, and here was my process.

1. Get the Arduino to output the data in a standard way.  I used CSV format, but as long as it easy to parse you should be fine.
2. Get the Arduino to make the data available.  I ended up using the webserver sketch to generate a page with all of my values, but you could just as easily have it send data instead.
3. Insert the data into a database.  I had a cron job that every x minutes would pull the webpage, parse the data, and insert it into the database.
4. Make the webpage.  There are a ton of open source graphing projects, and I chose a PHP based one as that is the language I am most comfortable with.  Javascript, Python, and CSS can also do it if you prefer.
5. Since I used PHP it was fairly easy to setup a template system.  Basically it had some standard include statements, then worked off of $_GET variables to call a variety of graphs.


body: Are there any *Arduino-like* board designs that are ***NOT*** using an AVR chip, but perhaps a chip like the Z80 or the 6502?

title: Arduino-like boards with other microcontrollers

Answers: 1

body:
You have to define what you mean by "Arduino-like" beyond just not using an AVR.

There's the Arduino Galileo using an Intel chip and supports the Arduino development tools, as well as the Arduino Due which is an Arm-based chip.

There's the Netduino which uses ARM chips (STMicro's) and is pin compatible with Arduino shields, but I don't know what the development framework is (other than it being in .NET), though this doesn't necessarily say much because not even all Arduino boards have the same pin compatibility (Nano boards are much smaller, LilyPad Arduinos which are round and semi-flexible, etc.)

Then there are related boards, but don't support the Arduino environment or any pin compatibility (TI Launchpad springs immediately to mind, but pretty much every manufacturer has some sort of demo board or development board for their MCU's).

There's a huge list of Arduino-like boards [here](http://en.wikipedia.org/wiki/List_of_Arduino_boards_and_compatible_systems) (split into levels of compatibility, includes the official Arduino boards).


body:
are there any USB to TTL with switchable 5v and 3.3v

i need to use it for raspberry pi and arduino

title: USB to TTL with switchable 5v and 3.3v in one

Answers: 1

body:
Many 3.3V FTDI based devices are 5V tolerant and will work with both:

* [Adafruit's FTDI friend](https://www.adafruit.com/product/284)
* [Sparkfun FT231X Breakout](https://www.sparkfun.com/products/11736)

Here is general information about logic levels: https://learn.sparkfun.com/tutorials/logic-levels


body:
my Adafruit motorshield is getting current from Arduino board even after disconnected from battery. I was planning to give separate dc power from 6 AA cells to motor shield but not sure if extra current will enter into Arduino and damage it. I have Ultrasonic sensor connected to motorshield which is getting +5v from board (may be Arduino).

Please suggest how to solve this problem.

Thanks

title: Adafruit motorshield disconnected but getting current from Arduino

Answers: 1

body:
If all else fails, read [**The Manual**](https://learn.adafruit.com/downloads/pdf/adafruit-motor-shield.pdf)

**The manual indicates that it is intended that the MS electronics may be operated by the Arduino power supply while using a separate external supply for the motor.**

Pages 37 to 39 explain about powering options.
The Arduino and the shield interconnect all of : 3V, 5V, Vin.
3V may not be used by the shield.

Arduino Vin to MS V+ is broken by jumper "PWRJMP" - purple rectangle in diagram below.
Arduino 5V to MS Vcc is not interrupted by a jumper - See labels in red squares below.

![enter image description here][1]
_____________________________

You did not say what version shield you had or which Arduino or what you mean by "disconnected from battery" or supply any links to relevant documents. ALL of these things will help people to help you better.

Assuming latest MS version,

[adafruit motor shield v1.2](http://www.adafruit.com/product/81)  - discontinued.

[github v1.2 schematic](https://raw.githubusercontent.com/adafruit/Adafruit-Motor-Shield-for-Arduino/master/mshieldv12schem.png) this appears to be pre V2 BUT is linked to from a ference in the V2 manual so is probably "more or less correct".

[**adafruit motor shield v2 manual**](https://learn.adafruit.com/downloads/pdf/adafruit-motor-shield-v2-for-arduino.pdf) - **probably what you have**

[adafruit current MS page](https://learn.adafruit.com/adafruit-motor-shield/use-it)

This probably tells you what you need to know.  Manual page 37-38

 - How to set up the Arduino + Shield for powering motors

 Servos are powered off of the same regulated 5V that the Arduino uses. This
is OK for the small hobby servos suggested. If you want something beefier, cut the trace
going to + on the servo connectors and wire up your own 5-6V supply!

 **The DC motors are powered off of a 'high voltage supply' and NOT the regulated 5V.**
Don't connect the motor power supply to the 5V line. This is a very very very bad idea unless you are sure you know what you're doing!

 There are two places you can get your motor 'high voltage supply' from. One is the DC jack on the Arduino board and the other is the 2-terminal block on the shield that is
labeled EXT_PWR. The DC Jack on the Arduino has a protection diode so you won't be able
to mess things up too bad if you plug in the wrong kind of power. However the EXT_PWR
terminals on the shield do not have a protection diode (for a fairly good
reason). Be utterly careful not to plug it in backwards or you will destroy the motor
shield and/or your Arduino!

  [1]: https://i.stack.imgur.com/LF9QF.jpg


body:
I'm working on a custom arduino that will run at 3.3 V with no regulators or USB chips (for power consumption).  I've heard that overclocking the chip at 16 MHz/3.3 V is generally fine, but I'd like to stay within spec anyway.

First: to run at 8 MHz, do I just need to replace the crystal?  Or is there anything else I have to do?

Second: Do I need to make any code changes to reflect the new speed?  I'm using serial, SPI, and I2C connections in this project, along with the NilRTOS operating system and millis/delay functions.  Will any of these be broken?  Will the code run noticeably slower?

Third: How can I program the chip?  Is it ok to program it in an Arduino Uno at 16 MHz, then transplant it to the custom arduino?

Fourth: Will power consumption change at 8 MHz?

Thanks!

title: What are the implications of running an ATmega328P at 8 MHz and 3.3 V with the Arduino system?

Answers: 2

body:
The formula seems to be volt*5.9-6.6=mhz (valid between 1.8v and 4.5v), so at 3.3v, this would give 12.8mhz. Be aware that, if you are running at 12.8mhz, ANY drop below 3.3v MAY cause problems (and very hard to diagnose, too!) or you MAY get away with it.

However, Arduino Atmega328p chips have a "brown-out" detection set at 4.3v - any drop below that, the chip shuts down. You can get an ISP (AKA ICSP) to change the fuses - go to http://www.engbedded.com/fusecalc/ to work out what to set fuses to. You can also use the ISP to read the current fuses, or indeed reprogram the chip without an Arduino board - all my projects have a 6-pin header. If you do this, before reprogramming using the Arduino board, you will have to "Burn Bootloader" (in the tools menu). Note that programming can still be done via Arduino IDE.

Alternatively, if you want to go "light" (and have an ISP), you can change the fuses to use the internal 8mhz clock - this frees up 2 extra pins, too! Be aware, however, that the internal clock may drift 1.2 hours per day (=5%), compared to 1.7 seconds per day (=20 parts per million) on a typical quartz crystal. If you don't use it for timekeeping, this probably doesn't matter.

You will need to make changes to the timing, for your code - you need to add a boards.txt with correct settings for your chip/clockspeed etc - you can copy the settings from the entry for the board, change the name, and change the setting "build.f_cpu"; restart (or start) your Arduino IDE, go to "Tools->Board" and select the board you added.

You can move the chip on/off the board, and reprogram it there (note that the board selected in Tools->Board is the FINAL board, not the programming board). Be careful plugging/unplugging it - eventually, you WILL bend the pins! Alternatively, you can use ISP (ICSP), as mentioned above - much recommended. ISP programming will also work if the chip is factory default, so long as it has a working clock.

How much power is used by the chip depends hugely on what you do with it - not just clock speeds, clock source, etc but also sleep modes. If you are sleeping a lot, it may draw less when running faster than running slower - if almost all your time is asleep, then the power consumption should be counted per clock cycle, not per second - if your clock is half the speed, and half current, then you draw the same current per instruction. Since the rest of your time is spent asleep, you get no benefit. See http://www.gammon.com.au/power for a very good breakdown of power usage, tips on how to save power, etc.

If you slow your clock down too much, serial and i2c may become unreliable (unless you slow down the speed), but I would expect to be able to go down to  1mhz before this to be a problem - a 1mhz chip trying to do 9600bps has 104 instructions per bit of data transferred. i2c runs at 100khz, so you get 10 instructions per bit (at 1mhz) - possibly pushing it. 8mhz should be fine. Test, test, test.

UPDATE:
There are 3 possible settings for the brown-out detection - there are 3 possible values for the AtMega328p: disabled, 1.8v, 2.7v, and 4.3v. I was under the impression (above) that Arduinos were normally set to 4.3v; apparently that is not the case (see comment below). I recall seeing somewhere that there was brownout detection. This is something to keep in mind, if your arduino resets, especially when putting larger loads on the battery (running motors, multiple leds etc).

body:
> First: to run at 8 MHz, do I just need to replace the crystal? Or is there anything else I have to do?

No, run on the internal oscillator as suggested by AMADANON Inc.

Alternatively, set the "divide clock by 8" fuse (which would run it at 2 MHz from a 16 MHz crystal) and then in code change the division back up to 2. ie.

    #include <avr/power.h>

    void setup ()
      {
      // slow clock to divide by 2
      clock_prescale_set (clock_div_2);
      } // end of setup

Or for programming in another Uno leave the fuse alone, program at 16 MHz and then drop the clock down in the target chip, hoping it works long enough at 3.3V to execute that first instruction. The safest thing would be to just install an 8 MHz crystal or resonator on the target board. However if timing is not critical run with the internal oscillator.

> Second: Do I need to make any code changes to reflect the new speed? I'm using serial, SPI, and I2C connections in this project, along with the NilRTOS operating system and millis/delay functions.

If you tell the IDE you have an 8 MHz processor (eg. a Lilypad) then it should adjust delays, baud rate calculations etc. appropriately.

> Will any of these be broken?

I2C and SPI are self-clocked. They can run at a variety of rates. I doubt there will be any problems with them. As for serial, providing the calculations are done right a wide range of baud rates should still be available.

>  Will the code run noticeably slower?

Well yes, it will run at half speed compared to 16 MHz.

> Third: How can I program the chip? Is it ok to program it in an Arduino Uno at 16 MHz, then transplant it to the custom arduino?

You can do that. Or you could connect up an ICSP header or an FTDI header and program it in situ.

Examples here: http://www.gammon.com.au/breadboard

> Fourth: Will power consumption change at 8 MHz?

Yes, it is reduced somewhat.

You can reduce it considerably more by using other techniques as described at http://www.gammon.com.au/power, and referred to by AMADANON Inc.


body:
I have installed an [MFRC522 RFID reader][1] in my house. The main use so far is to tell the house I've arrived using an RFID keychain, by leaving it in the key holder.

I would also like for the house to detect when I'm gone, and I was thinking that, if I can detect when a tag is present, I should also be able to detect when it is not.
However, this poses some challenges like the following:

 - Should I be constantly reading the tag until it disappears from range? (when I take it from the key holder).
 - What if I have more than one RFID Keychain/Tag in the range of the reader? (because there could be other keychains in the same key holder). Would I get multiple readings or could one tag interfere with another in some way?

I realize that maybe this is not the typical RFID scenario when the tag is scanned and then moved away from the reader. I've been searching about "RFID tag absence detection" but I've only found what seemed to me like very theoretical papers.

Do you have any advice or experience in implementing something like this?

Thanks!

  [1]: http://playground.arduino.cc/Learning/MFRC522

title: How to detect the absence of an RFID tag?

Answers: 2

body:
I don't think it is particularly practical, unless you make your own RFID scanner. The off-the-shelf ones generally only respond once when a particular card is in range, so you can't even detect if the card is left next the reader, or not.

Also, as the range is usually quite limited (a few cm) I don't see how it could tell the difference between you being out of the house, or taking a bath.

What might work better would be to have an active transmitter (eg. a nrf24l01) in your pocket, which every minute or so sent a "I'm home!" message to a central place. The absence of such a message after 10 minutes could indicate you are out.

The other approach would be to "check out" with your RFID scanner. I did an [RFID event management system](http://gammon.com.au/forum/?id=12869) a little while back. You use a special "admin" card to indicate that a person was leaving an event for a while (a pass-out). You could do that, or have a button by the door, which you press. The "I am leaving" button.

body:
Oh Yes it is possible.
I did a project which allows to transmit data from RFID card to a bluetooth device.
You can use below code to identify presence & gone:

    #include <SPI.h>
    #include <MFRC522.h>
    #include <SoftwareSerial.h>

    #define SS_PIN 10
    #define RST_PIN 9
    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

    SoftwareSerial BTserial(0, 1); // RX | TX
    int sensorPin = A0;
    int sensorValue = 0;
    String lastBlock="";
    void setup() {
        Serial.begin(9600); // Initialize serial communications with the PC
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card
    //mfrc522.setPassiveActivationRetries(0x9A); // for example
    //Serial.println("Scan PICC to see UID and type...");
    BTserial.begin(9600);
    Serial.println("Scan PICC to see UID and type...");
    }
    boolean flag=false;
    int counter=0;
    void loop() {
    // Look for new cards
    BTserial.println("Scan PICC to see UID and type...");
    if ( !mfrc522.PICC_IsNewCardPresent()) {
      if(mfrc522.PICC_IsNewCardPresent()){
        if(!flag){
        byte sector         = 1;
    byte blockAddr      = 4;
    byte dataBlock[]    = {
        0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
        0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
        0x08, 0x09, 0xff, 0x0b, //  9, 10, 255, 12,
        0x0c, 0x0d, 0x0e, 0x0f  // 13, 14,  15, 16
    };

    byte trailerBlock   = 7;
    byte status;
    byte buffer[18];
    byte size = sizeof(buffer);
    status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
    dump_byte_array(buffer, 16);

        flag=true;
        }
      }
      else{
        if(flag){
        flag=false;
        }
      }
          return;
    }
    }

    void dump_byte_array(byte *buffer, byte bufferSize) {
    String a=String((char)buffer[9]);
    String b=String((char)buffer[10]);
    String c=String((char)buffer[11]);
    String d=String((char)buffer[12]);
    String str="";
    str+=a;
    str+=b;
    str+=c;
    str+=d;
    lastBlock=str;
    Serial.println(str);
    BTserial.println(str);
    }


body:
I am looking at the following code and getting confused by a few elements in it:

1) Why is there a writeto function being performed to the memory locations x053,0x31,x09 for accelerometer and 0x68,0x16 and 0x1A for gyro? We are only reading incoming values so what is the purpose of these functions?

2) the bitwise operation being performed in the getGyrscopeReadings and getAccelerometerReadings... are these operations to define how many bits data we will be reading?

        #include <Wire.h> //The I2C library

    int gyroResult[3], accelResult[3];

    //Function for writing a byte to an address on an I2C device
    void writeTo(byte device, byte toAddress, byte val) {
      Wire.beginTransmission(device);
      Wire.write(toAddress);
      Wire.write(val);
      Wire.endTransmission();
    }

    //Function for reading num bytes from addresses on an I2C device
    void readFrom(byte device, byte fromAddress, int num, byte result[]) {
      Wire.beginTransmission(device);
      Wire.write(fromAddress);
      Wire.endTransmission();
      Wire.requestFrom((int)device, num);
      int i = 0;
      while(Wire.available()) {
        result[i] = Wire.read();
        i++;
      }
    }

    //Function for reading the gyros.
    void getGyroscopeReadings(int gyroResult[]) {
      byte buffer[6];
      readFrom(0x68,0x1D,6,buffer);
      gyroResult[0] = (((int)buffer[0]) << 8 ) | buffer[1]; //Combine two bytes into one int
      gyroResult[1] = (((int)buffer[2]) << 8 ) | buffer[3];
      gyroResult[2] = (((int)buffer[4]) << 8 ) | buffer[5];
    }

    //Function for reading the accelerometers
    void getAccelerometerReadings(int accelResult[]) {
      byte buffer[6];
      readFrom(0x53,0x32,6,buffer);
      accelResult[0] = (((int)buffer[1]) << 8 ) | buffer[0]; //Yes, byte order different from gyros'
      accelResult[1] = (((int)buffer[3]) << 8 ) | buffer[2];
      accelResult[2] = (((int)buffer[5]) << 8 ) | buffer[4];
    }

    void setup() {
      Wire.begin();            //Open I2C communications as master
      Serial.begin(9600);    //Open serial communications to the PC to see what's happening

      writeTo(0x53,0x31,0x09); //Set accelerometer to 11bit, +/-4g
      writeTo(0x53,0x2D,0x08); //Set accelerometer to measure mode
      writeTo(0x68,0x16,0x1A); //Set gyro to +/-2000deg/sec and 98Hz low pass filter
      writeTo(0x68,0x15,0x09); //Set gyro to 100Hz sample rate
    }

    void loop() {
      getGyroscopeReadings(gyroResult);
      getAccelerometerReadings(accelResult);

      Serial.print(gyroResult[0]);
      Serial.print("\t");
      Serial.print(gyroResult[1]);
      Serial.print("\t");
      Serial.print(gyroResult[2]);
      Serial.print("\t\t");
      Serial.print(accelResult[0]);
      Serial.print("\t");
      Serial.print(accelResult[1]);
      Serial.print("\t");
      Serial.print(accelResult[2]);
      Serial.print("\n");

      delay(50);
    }

any help would be greatly appreciated!

title: Understanding Digital IMU 6DOF sketch

Answers: 1

body:
**The `writeTo` functions**

The accelerometer and gyro both have some memory inside that is used to store the configuration. The specific locations and values can be read from the datasheet, but for now I'll trust the comments. These writeTo functions seem to set the device modes and configure the scale used for the sensors.

Notice that they only happen once, right when the program starts. Maybe the devices have a way of storing persistent settings onboard, but setting them once at each startup is safe and easy.

**The Bitwise ops**

These don't set the number of bits we are reading *per se*, They reconstruct larger than 8-bit values. The I2C serial protocol is set up to use 8-bit data segments, so to send any value larger than 8-bits they must be broken down, sent, and then "stitched" back together in chucks.

`(((int)buffer[0]) << 8 ) | buffer[1];`

Whats happening here is that `buffer[0]` is converted to int (a 16 bit value), then shifted over by 8 bits. This means the 8 bits in the original `buffer[0]` are now located in the top 8-bits of the integer, and the lower 8 bits are zeros. Finally the lower 8 bits are set by the bitwise-or operator `|`, which will turn on any bits that were set in `buffer[1]` in the result. Since the bottom 8-bits were 0's from the shift, this just copies `buffer[1]` in exactly.

The net effect is a 16 bit value that contains the bits of both 8-bit buffer values and can be interpreted as a single number.


body:
How can I open simultaneously two socket connections with a GSM shield?

It seems that when I try to open the second connection, it is not opened, and additionally the first connection is closed.

Code:

    #include <GSM.h>

    #define PINNUMBER      ""
    #define GPRS_APN       "sm2ms.movilforum.es"
    #define GPRS_LOGIN     ""
    #define GPRS_PASSWORD  ""

    #define SERVER "www.abv.bg"    // some server
    #define PORT   80              // some port

    static GSM gsm;
    static GPRS gprs;
    static GSMClient clientControl;    // first connection
    static GSMClient clientData;       // second connection

    void setup()
    {
        // initialize serial communications
        Serial.begin(9600);

        Serial.println("GSM not initialized");

        while (true)
        {
            if (gsm.begin(PINNUMBER) == GSM_READY)
            {
                Serial.println("GSM initialized");

                while (true)
                {
                    GSM3_NetworkStatus_t eErrorCode;

                    delay(1000);

                    eErrorCode = gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD);
                    if (eErrorCode == GPRS_READY)
                    {
                        Serial.println("GPRS initialized");

                        return;
                    }
                    Serial.print("Not connected to GPRS, error code = ");
                    Serial.println(eErrorCode, 1);
                }
            }

            Serial.println("Not connected to GSM");
            delay(1000);
        }
    }

    void loop()
    {
        delay(1000);

        Serial.println((clientControl.connect(SERVER, PORT))
                       ? ("Connected") : ("Couldn't connect"));

        delay(1000);

        Serial.println((clientData.connect(SERVER, PORT))
                       ? ("Second connection succeeded")
                       : ("Second connection failed"));

        Serial.println("Do something here");

        // close the stuff here!!!
        for (;;);
    }

The serial dumps:

    GSM not initialized
    GSM initialized
    GPRS initialized
    Connected
    Second connection failed
    Do something here

With other clients I don't have problem supporting two simultaneous connections. Here the first connection succeeds, the second fails.

Regards,
Boyan

title: How can I open simultaneously 2 client socket connections with GSM shield?

Answers: 0


body:
I'm wondering where the pin setting is manifested in the library.
I want to use the RC522 with other digital pins than the default 50-53 pins, because I am using a shield for a display on theese ports.

Where can I change the used ports?
why are two ports user-defineable `#define RFID_SS  10 #define RFID_RST 5` while the rest is not?

I am with this [Playground-Guide][1] using this [library from Github][2] on my Arduino Mega

  [1]: http://playground.arduino.cc/Learning/MFRC522
  [2]: https://github.com/miguelbalboa/rfid

title: Use RFID-RC522 with other Pins

Answers: 3

body:
    #define RFID_SS  10
stands for Slave Select on port 10, the SPI is a serial interface, meaning you can connect all kinds of SPI devices to the same wires, as long as slaves have different IO ports.

This is also the reason you don't need to define the other ports because they need to be connected to your SPI.

I suggest you make yourself familiar with this page: http://arduino.cc/en/Reference/SPI

To sum it up. You can change the reset and Slave Select pin out, (those set in the variables) but not the SPI Pins. But you can use the ISCP pins in the middle of the board.

body:
SPI
The RFID_SS pin is the slave select pin.
So you can have another arduino pin for a LCD_SS select.
Having RfID_SS =low - talk to RFID.
Having LCD_SS =low talk to LCD via MISO.
Note: Drive other slave select High otherwise they'll both get the data.
Having only one device in communication at a time.
Cheers
Nik V

body:
Sorry I'm a bit late (5 years late) but hopefully this can help someone who's just now trying to do this!

There's an old obscure Sunfounder library, "rfid1.h" that lets you declare every pin. Like this:

    rfid.begin(IRQ,SCK,MOSI,MISO,NSS,RST);

It's a bit hard to find the library online these days, but at the bottom of this page (http://wiki.sunfounder.cc/index.php?title=Mifare_RC522_Module_RFID_Reader) if you download the "RFID-RC522_test_experiment" zip file it will have the library in there. The secret is that this library includes a software SPI which is sort of like a software serial for SPI communication. Letting other digital pins be used as MISO etc...

This library also makes it much easier to use multiple RFIDs reliably since they don't have to share all the same pins.

You can find some example code here: https://www.sunfounder.com/learn/RFID_kit_V1_for_Arduino/lesson-29-rfid-entrance-guard-system-rfid-kit-v1-0-for-arduino.html


body:
A brief description of what I'm doing here. I wanna make a pet project, basically a device (be it Arduino or raspberry pi) that I can connect to via bluetooth / wifi (both preferably), that will be connected to a stereo system and allow me to play music. I essentially want to make a wireless sound system in my house.

My question is, is raspberry pi more adequate for my needs? Or would arduino get the job done? I know that raspberry pis are essentially mini computers, so I feel that the raspberry pi would be too much, since all I really need to do is design a bluetooth / wifi interface and send the signal to the aux cable connected to the stereo.

Any help would be really useful here. I've never worked with either/or, and this is my first project with Arduino / Raspberry pi (hello world). Thanks in advance.

EDIT: In response to comments below, a greater idea of what I want to do:

I want to design an item that will appear on local wifi as a sound device. i.e. on an imac / macbook I'd be able to right click on the speaker icon in the upper right and select it there). From there, I'm hoping to stream audio to the device, and have it play to a stereo that the arduino / raspberry pi would be connected to. I'd love to make this universal (i.e. possible to connect via your android phone / a windows machine), but I can imagine that part being a lot more difficult. I'd also like to add bluetooth functionality at some point, but that'd be in the future. Hopefully this gives everybody more of an idea of what I'd like to achieve here! I appreciate all the help so far.

title: Arduino or Raspberry Pi for my project

Answers: 2

body:
As mentioned in the comments, a Raspberry Pi would be superior here.

The standard AVR (not Due/Galileo/Yun) Arduino is superior to the Pi in only one area: IO. It has a 5V logic that's more compatible than the Pi's 3.3V (although you can use a *logic level shifter*). The Arduino also features more PWM pins and an ADC, along with interrupts. An Arduino also is a lot simpler to use for basic projects, but it becomes impractical when you need more computing power.

A Pi excels at the data-crunching side of things. It can handle a lot more data than the Arduino could ever dream of, and then some! Just to put things in perspective, the Pi has a clock speed of 700 MHz by default and the Arduino Uno has one of 16 MHz (with a less powerful architecture).

For your purpose, the Pi's audio jack and ethernet port are unmatched on the Arduino. *Sure*, you can get shields that replicate these behaviors, but the Pi's built in functionality doesn't cost extra and it's more powerful.

body: While it might be an interesting project, the overall quality of the sound generated by such do-it-yourself contraption, is likely to be highly disappointing, because of the not-stellar quality of the final analog stage in the audio output.


body: I tried my first project with Arduino Uno. But I can't upload any code. Power green LED is working and orange LED is always on, not blinking, and IC also getting hot. What can I do to fix this problem?

title: How to check whether my Arduino is working? And how to fix this?

Answers: 1

body:
My suggestion is to find someone else with an arduino, and get them to test (with their computer, known to be working) uploading to your Arduino. That way, you can tell if the problem is with your computer or the Arduino.

You haven't mentioned what your first project was. The most common mistake #1 is to light up an LED without a resistor. If you do that for a split second, you might (OR MIGHT NOT!) get away with it. If you leave it running for a few seconds, you are almost certainly going to burn out your AtMega (the IC on the board). This might very well result in the symptoms you describe. If this has happened, and your chip (IC) is removable (some are, some aren't), you should be able to buy a new chip of the same kind. An Arduino Uno has an AtMega 328, you will want a DIP package (they are the removable ones), and you will want one with an Arduino Bootloader pre-programmed. Replacing the chip may OR MAY NOT fix the problem. Make sure you note down the orientation of the broken chip before you pull it out - it will fit in, but won't work (and could burn out!) if you put it in the wrong way. There should be a little dimple at one end of the chip, right on the end. It should look like this (possibly without the pin labeling sticker): http://www.jaycar.co.nz/productView.asp?ID=ZZ8726&w=atmega328&form=KEYWORD

If your chip is not removable, or replacing the chip doesn't help, then you will need to get a new Arduino.


body:
I'm trying to use [Adafruit's LED Backpack library][1] within a custom class. When I use the Adafruit library directly within a sketch, it compiles fine. When I use an example sketch provided with the library, it compiles fine. However when I create an instance of my custom class with the Adafruit object within it, I get the following error:

> In file included from sketch_feb18a.ino:6:
/Users/lawnmowerlatte/Documents/Arduino/libraries/Bargraph/bargraph.h:18: error: 'Adafruit_24bargraph' does not name a type

All the reasons I've seen for this error stem from the library being missing or otherwise incorrectly installed. However, since I can use it directly, I think something else must be wrong.

**Working**

    #include <Adafruit_LEDBackpack.h>
    #include <Adafruit_GFX.h>
    Adafruit_24bargraph bar = Adafruit_24bargraph();

    void setup() { }
    void loop() { }

**Not Working**

    #include <bargraph.h>
    Bargraph bargraph = Bargraph("Test", "api", 0);

    void setup() { }
    void loop() { }

**bargraph.h**

    #ifndef Bargraph_h
    #define Bargraph_h

    #include <Adafruit_GFX.h>
    #include <Adafruit_LEDBackpack.h>

    #if (ARDUINO >= 100)
    #include <Arduino.h>
    #else
    #include <WProgram.h>
    #endif

    class Bargraph {
      public :
        String name;
     String api;
     Adafruit_24bargraph bar;

     Bargraph(String _name, String _api, int _device,
      String _type="Default");

     void set(String _value);
     void setMax(String _max);
     void update();
        void print();

      private :
       int display[24];

     long max;
     long value;
     int device;
     int size;
     String type;

     void format();
     void write();
    };

    #endif

**bargraph.cpp**

    #define OFF 0
    #define RED 1
    #define YELLOW 2
    #define GREEN 3

    #include <bargraph.h>

    #if (ARDUINO >= 100)
    #include <Arduino.h>
    #else
    #include <WProgram.h>
    #endif

    Bargraph::Bargraph(String _name, String _api, int _device, String _type) : bar() {
     name  = _name;
     api   = _api;
     max   = _max.toLong();
     device  = _device;
     type  = _type;
     value  = 0;

     for (int i=0; i<24; i++) {
      display[i] = OFF;
     }

     bar.begin(0x70+device);
    }

    **Methods Omitted for Brevity**

Can anyone explain what's going on here? I'm pretty certain my class syntax is correct as I have other object-in-object relationships working. I can post code to GitHub if anyone would like to see more context.

  [1]: https://github.com/adafruit/Adafruit-LED-Backpack-Library

title: error: 'CLASS' does not name a type only when creating object inside another object

Answers: 2

body:
I think these lines still need to be in your main sketch file (in addition to being in your custom class file):

    #include <Adafruit_LEDBackpack.h>
    #include <Adafruit_GFX.h>

If I remember the Arduino IDE quirks correctly, it uses the `#include` directives in the main sketch file to determine which libraries to actually link. It's one of those annoying features that was intended to be beginner-friendly but sometimes just makes things more confusing.

body:
If you used the serial port, Arduino sometimes causes confusion.
Close Arduino IDE and
delete files in folder C:/users/[your name]/AppData/Local/Temp/
Its working.
Regards


body:
I use the interrupt function to fill an array with values received from `digitalRead()`.

```c++
void setup() {
    Serial.begin(115200);
    attachInterrupt(0, test_func, CHANGE);
}

void test_func() {
    if (digitalRead(pin) == HIGH) {
        test_array[x] = 1;
    } else if(digitalRead(pin) == LOW) {
        test_array[x] = 0;
    }
    x = x + 1;
}
```

That problem is that when I print `test_array` there are values like: `111` or `000`.

As I understand it, if I use the `CHANGE` option in the `attachInterrupt()` function, then the data sequence should always be `0101010101` without repeating.

The data changes quite fast since it comes from a radio module.

title: Arduino interruption (on pin change)

Answers: 2

body:
The interrupt is being set to fire on a change, and your test_func is set as the Interrupt Service Routine (ISR), called to service that interrupt. The ISR then prints the value of the input.

At first glance you would expect the output to be as you have said, and alternating set of high lows, as it only gets to the ISR on a change.

But what we're missing is that there is a certain amount of time that it takes for the CPU to service an interrupt and branch to the ISR.
During this time the voltage on the pin may have changed again. Particularly if the pin is not stabilised by hardware de-bouncing or similar. Because the interrupt is already flagged and hasn't been serviced yet, this extra change (or many of them, because a pins level can change very quickly relative to the clock speed if it has low parasitic capacitance) will be missed.

So in essence without some form of de-bouncing, we have no guarantee that when the input changes, and the interrupt gets marked for servicing, that the input will still be at the same value when we get to reading its value in the ISR.

As a generic example the [ATmega328 Datasheet][1]  used on the Arduino Uno details interrupt times in section 6.7.1 - "Interrupt Response Time". It states for this microcontroller the minimum time to branch to an ISR for servicing is 4 clock cycles, but can be more (extra if executing multi-cycle instruction at interrupt or 8 + sleep wake time if the MCU is in sleep.)

As @EdgarBonet mentioned in comments, the pin could also similarly change during ISR execution. Because the ISR reads from the pin twice, it would not add anything to the test_array if it encountered a LOW on the first read and a HIGH on the second. But x would still increment, leaving that slot in the array unchanged (possibly as uninitialised data depending on what was done to the array earlier).

His one line ISR of `test_array[x++] = digitalRead(pin);` is a perfect solution to this.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf "ATmega328"

body:
<!-- language-all: lang-cpp -->

**As a sort of prologue** to this overly long answer...

This question got me deeply captivated with the problem of interrupt
latency, to the point of losing sleep in counting cycles instead of
sheep. I am writing this response more for sharing my findings
than for just answering the question: most of this material may actually
not be at a level suitable for a proper answer. I hope it will be
useful, however, for readers that land here in search of solutions for
latency problems. The first few sections are expected to be useful to a
wide audience, including the original poster. Then, it gets hairy along
the way.

Clayton Mills already explained in his answer that there is some latency
in responding to interrupts. Here I will focus on quantifying the
latency (which is _huge_ when using the Arduino libraries), and on the
means to minimize it. Most of what follows is specific to the hardware
of the Arduino Uno and similar boards.

# Minimizing the interrupt latency on the Arduino

(or how to get from 99 down to 5 cycles)

I will use the original question as a working example, and restate the
problem in terms of interrupt latency. We have some external event that
triggers an interrupt (here: INT0 on pin change). We need to take some
action when the interrupt is triggered (here: read a digital input). The
problem is: there is some delay between the interrupt being triggered
and our taking the appropriate action. We call this delay "_interrupt
latency_". A long latency is detrimental in many situations. In this
particular example, the input signal may change during the delay, in
which case we get a faulty reading. There is nothing we can do to avoid
the delay: it is intrinsic to the way interrupts work. We can, however,
try to make it as short as possible, which should hopefully minimize the
bad consequences.

The first obvious thing we can do is take the time-critical action,
inside the interrupt handler, as soon as possible. This means calling
`digitalRead()` once (and only once) at the very beginning of the
handler. Here is the zeroth version of the program upon which we will
build:

    #define INT_NUMBER 0
    #define PIN_NUMBER 2    // interrupt 0 is on pin 2
    #define MAX_COUNT  200

    volatile uint8_t count_edges;  // count of signal edges
    volatile uint8_t count_high;   // count of high levels

    /* Interrupt handler. */
    void read_pin()
    {
        int pin_state = digitalRead(PIN_NUMBER);  // do this first!
        if (count_edges >= MAX_COUNT) return;     // we are done
        count_edges++;
        if (pin_state == HIGH) count_high++;
    }

    void setup()
    {
        Serial.begin(9600);
        attachInterrupt(INT_NUMBER, read_pin, CHANGE);
    }

    void loop()
    {
        /* Wait for the interrupt handler to count MAX_COUNT edges. */
        while (count_edges < MAX_COUNT) { /* wait */ }

        /* Report result. */
        Serial.print("Counted ");
        Serial.print(count_high);
        Serial.print(" HIGH levels for ");
        Serial.print(count_edges);
        Serial.println(" edges");

        /* Count again. */
        count_high = 0;
        count_edges = 0;  // do this last to avoid race condition
    }

I tested this program, and the subsequent versions, by sending it trains
of pulses of varying widths. There is enough spacing between the pulses
to ensure that no edge is missed: even if the falling edge is received
before the previous interrupt is done, the second interrupt request will
be put on hold and eventually serviced. If a pulse is shorter than the
interrupt latency, the program reads 0 on both edges. The reported
number of HIGH levels is then the percentage of correctly read pulses.

## What happens when the interrupt is triggered?

Before trying to improve the code above, we will take a look at the
events that unfold right after the interrupt is triggered. The hardware
part of the story is told by the Atmel documentation. The software part,
by disassembling the binary.

Most of the time, the incoming interrupt is serviced right away. It may
happen, however, that the MCU (meaning "microcontroller") is in the
middle of some time-critical task, where interrupt servicing is
disabled. This is typically the case when it is already servicing
another interrupt. When this happens, the incoming interrupt request is
put on hold and serviced only when that time-critical section is done.
This situation is hard to avoid completely, because there are quite a
few of those critical sections in the Arduino core library (which I will
call "_libcore_" in the following). Fortunately, these sections are
short and run only every so often. Thus, most of the time, our interrupt
request will be serviced right away. In the following, I will assume
that we do not care about those few instances when this is not the case.

Then, our request is serviced immediately. This still involves a lot of
stuff that can take quite a while. First, there is a hardwired sequence.
The MCU will finish executing the current instruction. Fortunately, most
instructions are single-cycle, but some can take up to four cycles.
Then, the MCU clears an internal flag that disables further servicing of
interrupts. This is intended to prevent nested interrupts. Then, the PC
is saved into the stack. The stack is an area of RAM reserved for this
kind of temporary storage. The PC (meaning "_Program Counter_") is an
internal register holding the address of the next instruction the MCU is
about to execute. This is what allows the MCU to know what to do next,
and saving it is essential because it will have to be restored in order
for the main program to resume from where it was interrupted. The PC is
then loaded with a hardwired address specific to the request received,
and this is the end of the hardwired sequence, the rest being
software-controlled.

The MCU now executes the instruction from that hardwired address. This
instruction is called an "_interrupt vector_", and is generally a "jump"
instruction that will bring us to a special routine called an ISR
("_Interrupt Service Routine_"). In this case, the ISR is called
"\_\_vector\_1", a.k.a. "INT0\_vect", which is a misnomer because it is
an ISR, not a vector. This particular ISR comes from libcore. Like any
ISR, it starts with a _prologue_ that saves a bunch of internal CPU
registers on the stack. This will allow it to use those registers and,
when it is done, restore them to their previous values in order not to
disturb the main program. Then, it will look for the interrupt handler
that was registered with `attachInterrupt()`, and it will call that
handler, which is our `read_pin()` function above. Our function will
then call `digitalRead()` from libcore. `digitalRead()` will look into
some tables in order to map the Arduino port number to the hardware I/O
port it has to read and the associated bit number to test. It will also
check whether there is a PWM channel on that pin that would need to be
disabled. It will then read the I/O port... and we are done. Well, we
are not really done servicing the interrupt, but the time-critical task
(reading the I/O port) is done, and it is all that matters when we are
looking at latency.

Here is a short summary of all the above, together with the associated
delays in CPU cycles:

1. hardwired sequence: finish current instruction, prevent nested
   interrupts, save PC, load address of vector (≥ 4 cycles)
2. execute interrupt vector: jump to ISR (3 cycles)
3. ISR prologue: save registers (32 cycles)
4. ISR main body: locate and call user-registered function (13 cycles)
5. read\_pin: call digitalRead (5 cycles)
6. digitalRead: find the relevant port and bit to test (41 cycles)
7. digitalRead: read the I/O port (1 cycle)

We will assume the best case scenario, with 4 cycles for the
hardwired sequence. This gives us a total latency of 99 cycles, or
about 6.2 µs with a 16 MHz clock. In the following, I will
explore some tricks that can be used to lower this latency. They come
roughly in increasing order of complexity, but they all need us to
somehow dig into the internals of the MCU.

## Use direct port access

The obvious first target for shortening the latency is `digitalRead()`.
This function provides a nice abstraction to the MCU hardware, but it is
too inefficient for time-critical work. Getting rid of this one is
actually trivial: we just have to replace it with `digitalReadFast()`,
from the [digitalwritefast](https://code.google.com/p/digitalwritefast/)
library. This cuts the latency almost by half at the cost of a small
download!

Well, that was too easy to be any fun, I will rather show you how to do
it the hard way. The purpose is to get us started into low-level stuff.
The method is called "_direct port access_" and is nicely documented on
the Arduino reference at the page on [Port
Registers](http://www.arduino.cc/en/Reference/PortManipulation). At this
point, it is a good idea to download and take a look at the [ATmega328P
datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf).
This 650-page document may seem somewhat daunting at first look. It is,
however, well organised into sections specific to each of the MCU
peripherals and features. And we only need to check the sections
relevant to what we are doing. In this case, it is the section named
_I/O ports_. Here is a summary of what we learn from those readings:

* The Arduino pin 2 is actually called PD2 (i.e. port D, bit 2) on the
  AVR chip.
* We get the whole port D at once by reading a special MCU register called
  "PIND".
* We then check bit number 2 by doing a _bitwise logical and_ (the C ‘&’
  operator) with `1 << 2`.

So, here is our modified interrupt handler:

    #define PIN_REG    PIND  // interrupt 0 is on AVR pin PD2
    #define PIN_BIT    2

    /* Interrupt handler. */
    void read_pin()
    {
        uint8_t sampled_pin = PIN_REG;            // do this first!
        if (count_edges >= MAX_COUNT) return;     // we are done
        count_edges++;
        if (sampled_pin & (1 << PIN_BIT)) count_high++;
    }

Now, our handler will read the I/O register as soon as it is called. The
latency is 53 CPU cycles. This simple trick saved us 46 cycles!

## Write your own ISR

The next target for cycle-trimming is the INT0\_vect ISR. This ISR is
needed for providing the functionality of `attachInterrupt()`: we can
change interrupt handlers at any time during program execution. However,
although nice to have, this is not really useful for our purpose. Thus,
instead of having the libcore's ISR locate and call our interrupt
handler, we will save a few cycles by _replacing_ the ISR by our
handler.

This is not as hard as it sounds. ISRs can be written like normal
functions, we just have to be aware of their specific names, and define
them using a special `ISR()` macro from avr-libc. At this point it would
be good to have a look at the [avr-libc's documentation on
interrupts](http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html),
and at the datasheet section named _External Interrupts_. Here is the
short summary:

* We have to write a bit in a special hardware register called EICRA
  (_External Interrupt Control Register A_) in order to configure the
  interrupt to be triggered on any change of the pin value. This will be
  done in `setup()`.
* We have to write a bit in another hardware register called EIMSK
  (_External Interrupt MaSK register_) in order to enable the INT0
  interrupt. This will also be done in `setup()`.
* We have to define the ISR with the syntax `ISR(INT0_vect) { ... }`.

Here is the code for the ISR and `setup()`, everything else is
unchanged:

    /* Interrupt service routine for INT0. */
    ISR(INT0_vect)
    {
        uint8_t sampled_pin = PIN_REG;            // do this first!
        if (count_edges >= MAX_COUNT) return;     // we are done
        count_edges++;
        if (sampled_pin & (1 << PIN_BIT)) count_high++;
    }

    void setup()
    {
        Serial.begin(9600);
        EICRA = 1 << ISC00;  // sense any change on the INT0 pin
        EIMSK = 1 << INT0;   // enable INT0 interrupt
    }

This comes with a free bonus: since this ISR is simpler than the one it
replaces, it needs less registers to do its job, then the
register-saving prologue is shorter. Now we are down to a latency of 20
cycles. Not bad considering that we started close to 100!

At this point I would say we are done. Mission accomplished. What
follows is only for those who are not afraid of getting their hands
dirty with some AVR assembly. Otherwise you can stop reading here, and
thank-you for getting so far.

## Write a naked ISR

Still here? Good! For proceeding further, it would be helpful to have at
least some very basic idea of how assembly works, and to take a look at
the [Inline Assembler
Cookbook](http://www.nongnu.org/avr-libc/user-manual/inline_asm.html)
from the avr-libc documentation. At this point, our interrupt entry
sequence looks like this:

1. hardwired sequence (4 cycles)
2. interrupt vector: jump to ISR (3 cycles)
3. ISR prologue: save regs (12 cycles)
4. first thing in the ISR body: read the IO port (1 cycle)

If we want to do better, we have to move the reading of the port into
the prologue. The idea is the following: reading the PIND register will
clobber one CPU register, thus we need to save at least one register
before doing that, but the other registers can wait. We then need to
write a custom prologue that reads the I/O port right after saving the
first register. You have already seen in the avr-libc interrupt
documentation (you have read it, right?) that an ISR can be made
_naked_, in which case the compiler will emit no prologue or epilogue,
allowing us to write our own custom version.

The problem with this approach is that we will probably end up writing
the whole ISR in assembly. Not a big deal, but I would rather have the
compiler write those boring prologues and epilogues for me. So, here is
the dirty trick: we will split the ISR in two parts:

* the first part will be a short assembly fragment that will
    * save a single register to the stack
    * read PIND into that register
    * store that value into a global variable
    * restore the register from the stack
    * jump to the second part
* the second part will be regular C code with compiler-generated
  prologue and epilogue

Our previous INT0 ISR is then replaced by this:

    volatile uint8_t sampled_pin;    // this is now a global variable

    /* Interrupt service routine for INT0. */
    ISR(INT0_vect, ISR_NAKED)
    {
        asm volatile(
        "    push r0                \n"  // save register r0
        "    in r0, %[pin]          \n"  // read PIND into r0
        "    sts sampled_pin, r0    \n"  // store r0 in a global
        "    pop r0                 \n"  // restore previous r0
        "    rjmp INT0_vect_part_2  \n"  // go to part 2
        :: [pin] "I" (_SFR_IO_ADDR(PIND)));
    }

    ISR(INT0_vect_part_2)
    {
        if (count_edges >= MAX_COUNT) return;     // we are done
        count_edges++;
        if (sampled_pin & (1 << PIN_BIT)) count_high++;
    }

Here we are using the ISR() macro to have the compiler instrument
`INT0_vect_part_2` with the required prologue and epilogue. The compiler
will complain that "‘INT0\_vect\_part\_2’ appears to be a misspelled
signal handler", but the warning can be safely ignored. Now the ISR has
a single 2-cycle instruction before the actual port read, and the total
latency is only 10 cycles.

## Use the GPIOR0 register

What if we could have a register reserved for this specific job? Then,
we would not need save anything before reading the port. We can actually
ask the compiler to [bind a global variable to a
register](https://gcc.gnu.org/onlinedocs/gcc/Global-Reg-Vars.html).
This, however, would require us to recompile the whole Arduino core and
libc in order to make sure the register is always reserved. Not really
convenient. On the other hand, the ATmega328P happens to have three
registers that are not used by the compiler nor any library, and are
available for storing whatever we want. They are called GPIOR0, GPIOR1
and GPIOR2 (_General Purpose I/O Registers_). Although they are mapped
in the I/O address space of the MCU, these are actually _not_ I/O
registers: they are just plain memory, like three bytes of RAM that
somehow got lost in a bus and ended up in the wrong address space. These
are not as capable as the internal CPU registers, and we cannot copy
PIND into one of these with the `in` instruction. GPIOR0 is interesting,
though, in that it is _bit-addressable_, just like PIND. This will allow
us to transfer the information without clobbering any internal CPU
register.

Here is the trick: we will make sure that GPIOR0 is initially zero (it
is actually cleared by hardware at boot time), then we will use the
`sbic` (Skip next instruction if some Bit in some I/o register is Clear)
and the `sbi` (Set to 1 some Bit in some I/o register) instructions as
follows:

    sbic PIND, 2   ; skip the following if bit 2 of PIND is clear
    sbi GPIOR0, 0  ; set to 1 bit 0 of GPIOR0

This way, GPIOR0 will end up being 0 or 1 depending on the bit we wanted
to read from PIND. The sbic instruction takes 1 or 2 cycles to execute
depending on whether the condition is false or true. Obviously, the PIND
bit is accessed on the first cycle. In this new version of the code, the
global variable `sampled_pin` is not useful anymore, since it is
basically replaced by GPIOR0:

    /* Interrupt service routine for INT0. */
    ISR(INT0_vect, ISR_NAKED)
    {
        asm volatile(
        "    sbic %[pin], %[bit]    \n"
        "    sbi %[gpio], 0         \n"
        "    rjmp INT0_vect_part_2  \n"
        :: [pin]  "I" (_SFR_IO_ADDR(PIND)),
           [bit]  "I" (PIN_BIT),
           [gpio] "I" (_SFR_IO_ADDR(GPIOR0)));
    }

    ISR(INT0_vect_part_2)
    {
        if (count_edges < MAX_COUNT) {
            count_edges++;
            if (GPIOR0) count_high++;
        }
        GPIOR0 = 0;
    }

It should be noted that GPIOR0 has to always be reset in the ISR.

Now, the sampling of the PIND I/O register is the very first thing done
inside the ISR. Total latency is 8 cycles. This is about the best we can
do before getting stained with terribly sinful kludges. This is again a
good opportunity to stop reading...

## Put the time-critical code in the vector table

For those still here, here is our current situation:

1. hardwired sequence (4 cycles)
2. interrupt vector: jump to ISR (3 cycles)
4. ISR body: read the IO port (on 1st cycle)

There is obviously little room for improvement. The only way we could
shorten the latency at this point is by _replacing the interrupt vector
itself_ by our code. Be warned that this should be immensely distasteful
to anyone who values clean software design. But it is possible, and I
will show you how.

The layout of the ATmega328P vector table can be found in the datasheet,
section _Interrupts_, subsection _Interrupt Vectors in ATmega328 and
ATmega328P_. Or by disassembling any program for this chip. Here is how
it looks like. I am using avr-gcc and avr-libc's conventions (\_\_init
is vector 0, addresses are in bytes) which are different from Atmel's.

    address │ instruction     │ comment
    ────────┼─────────────────┼──────────────────────
     0x0000 │ jmp __init      │ reset vector
     0x0004 │ jmp __vector_1  │ a.k.a. INT0_vect
     0x0008 │ jmp __vector_2  │ a.k.a. INT1_vect
     0x000c │ jmp __vector_3  │ a.k.a. PCINT0_vect
      ...
     0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect

Each vector has a 4-byte slot, filled with a single `jmp` instruction.
This is a 32-bit instruction, unlike most AVR instructions which are
16-bit. But a 32-bit slot is too small to hold the first part of our
ISR: we can fit the `sbic` and `sbi` instructions, but not the `rjmp`.
If we do that, the vector table ends up looking like this:

    address │ instruction     │ comment
    ────────┼─────────────────┼──────────────────────
     0x0000 │ jmp __init      │ reset vector
     0x0004 │ sbic PIND, 2    │ the first part...
     0x0006 │ sbi GPIOR0, 0   │ ...of our ISR
     0x0008 │ jmp __vector_2  │ a.k.a. INT1_vect
     0x000c │ jmp __vector_3  │ a.k.a. PCINT0_vect
      ...
     0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect

When INT0 fires, PIND will be read, the relevant bit will be copied into
GPIOR0, and then the execution will fall through to the next vector.
Then, the ISR for INT1 will be called, instead of the ISR for INT0. This
is creepy, but since we are not using INT1 anyway, we will just "hijack"
its vector for servicing INT0.

Now, we just have to write our own custom vector table to override the
default one. It turns out it is not so easy. The default vector table is
provided by the avr-libc distribution, in an object file called
crtm328p.o that is automatically linked with any program we build.
Unlike library code, object-file code is not meant to be overridden:
trying to do that will give a linker error about the table being defined
twice. This means we have to replace the whole crtm328p.o with our
custom version. One option is to [download the full avr-libc source
code](http://download.savannah.gnu.org/releases/avr-libc/), do our
custom modifications in
[gcrt1.S](http://svn.savannah.nongnu.org/viewvc/*checkout*/trunk/avr-libc/crt1/gcrt1.S?root=avr-libc),
then build this as a custom libc.

Here I went for a lighter, alternative approach. I wrote a custom
crt.S, which is a simplified version of the original from avr-libc. It
lacks a few rarely used features, like the ability to define a "catch
all" ISR, or to be able to terminate the program (i.e. freeze the
Arduino) by calling `exit()`. Here is the code. I trimmed the repetitive
part of the vector table in order to minimize scrolling:

    #include <avr/io.h>

    .weak __heap_end
    .set  __heap_end, 0

    .macro vector name
        .weak \name
        .set \name, __vectors
        jmp \name
    .endm

    .section .vectors
    __vectors:
        jmp __init
        sbic _SFR_IO_ADDR(PIND), 2   ; these 2 lines...
        sbi _SFR_IO_ADDR(GPIOR0), 0  ; ...replace vector_1
        vector __vector_2
        vector __vector_3
        [...and so forth until...]
        vector __vector_25

    .section .init2
    __init:
        clr r1
        out _SFR_IO_ADDR(SREG), r1
        ldi r28, lo8(RAMEND)
        ldi r29, hi8(RAMEND)
        out _SFR_IO_ADDR(SPL), r28
        out _SFR_IO_ADDR(SPH), r29

    .section .init9
        jmp main

It can be compiled with the following command line:

    avr-gcc -c -mmcu=atmega328p silly-crt.S

The sketch is identical to the previous one except that there is no
INT0\_vect, and INT0\_vect\_part\_2 is replaced by INT1\_vect:

    /* Interrupt service routine for INT1 hijacked to service INT0. */
    ISR(INT1_vect)
    {
        if (count_edges < MAX_COUNT) {
            count_edges++;
            if (GPIOR0) count_high++;
        }
        GPIOR0 = 0;
    }

To compile the sketch, we need a custom compile command. If you have
followed so far, you probably know how to compile from the command line.
You have to explicitly request silly-crt.o to be linked to your program,
and add the `-nostartfiles` option to avoid linking in the original
crtm328p.o.

Now, the reading of the I/O port is the very first instruction executed
after the interrupt triggers. I tested this version by sending it short
pulses from another Arduino, and it can catch (although not reliably)
the high level of pulses as short as 5 cycles. There is nothing more we
can do to shorten the interrupt latency on this hardware.


body:
I am planning to build a calculator using Arduino as the base. I already know C and I love low-level stuff, so I guess the software part won't be a problem.

However, I've been stuck with Arduino. What I need is something capable of doing math (as I'm not even sure if Arduino has a FPU), and it to have enough inputs for more than the basic 0-9 `+ - / *` keys.

I am a _real newbie_ when it comes to hardware. I don't even have the slightest clue where to start. I barely understand Arduino's specifications, which is why I'm asking here.

I want to do something _more_ than the classic calculator, because the software part is not a problem. I just need help on which hardware should I choose; both on the 'which Arduino' and 'which accesories for the Arduino' parts.

P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

title: What kind of Arduino should I pick for a calculator?

Answers: 3

body:
Start with the biggest (AVR) Arduino you can afford, and worry about miniaturizing it once you have the basics in place. You may find that you don't actually want an Arduino in the end, but something like the ATmega169PA instead so that you have native LCD support (instead of having to use a discrete LCD module).

> P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

Doesn't matter. Most of your x86 assembly experience will easily transfer to AVR (but not all, since the AVR core is simpler than x86).

body:
For the most part, none of the AVR based arduinos are any better at number crunching than any others. They all have a single AVR core running at 16Mhz. None have an FPU, but the software floating point code is very efficient and at the time scales you care about for a calculator, it really doesn't make much of a difference.

The biggest differences between models are memory and available IO, so the decision between AVR models should probably come from what kind of peripherals you want to plug in, not what you want to calculate.

That said, if you want to do a lot of high precision, numerical calculations (like numerical integration or something), you will probably want something with more memory, and floating point types larger than 32-bits. I don't have much experience with those models, but I'm pretty sure that a Yun or a Zero would be better suited for those kinds of calculations. They don't use AVR based main CPUs.

For IO there are too many options to enumerate here. Take a look at the usual suspect's pages (sparkfun, adafruit, etc...) for displays and buttons. These sites have good descriptions and example code for everything.

When picking devices, remember that you can have multiple I2C devices plugged in at once, but only one UART serial per port (uno/leonardo 1 port, mega 4). Software serial can give you more UARTs for low speed comms if need be.

If you want a lot of different individual buttons, there are ways to get more than 1 button per pin, but it would be a bit easier electrically to pick an arduino with as many pins as buttons. Some of the keypads available already have a special wiring scheme to get higher than 1-to-1 pin ratios and descriptions of how to use them, so they might be a good pick to get yourself started.

body:
Any Arduino (I would start with the UNO) will be sufficient to make a calculator similar to the regular HP or TI calculator product line.

For the keypad, you will need to buy an I2C compatible keypad and connect it to the I2C lines. For the screen there is an LCD shield.

You will not need to code anything in assembly. You can write cpp code using the libraries provided with the Arduino.


body:
I have attached photo of the clone Uno board recently acquired, and I am working on a Mac OS X 10.7.5

I have sourced the solution from
http://javacolors.blogspot.com/2014/08/dccduino-usb-drivers-ch340-ch341-chipset.html

Which suggests to install 340/341CH drivers and run a sudo code. When I plug in the Uno board, the Arduino IDE still does not show under port selection, the "dev.tty.usbserial"

and as such I cannot contact or upload any command to the Uno board. Been trying for a whole day.. please help if you know a possible solution

This is the board:
![Uno board][1]

I bought the board from this site:

http://www.aliexpress.com/item/UNO-KIT-Upgraded-version-of-the-For-Starter-Kit-the-RFID-learn-Suite-Stepper-Motor-ULN2003/1207142899.html

screenshot from the IDE does now show any usbserial
![IDE screenshot][2]

  [1]: https://i.stack.imgur.com/AV3ks.jpg
  [2]: https://i.stack.imgur.com/YYyRK.png

title: Issue with usbserial for arduino clone

Answers: 3

body:
This may be better asked on http://apple.stackexchange.com

At the terminal run `ioreg -p IOUSB` then plug in the Arduino and see what changed.

On my Mac the setting is serial.port=/dev/tty.usbmodemfa131

body:
You will need to allow the use of unverified drivers for this version of the Arduino. Unlike the genuine Arduino this board needs the ch340 and ch341 drivers and because they are not verified you will need to run the following command in order for them to work:

sudo nvram boot-args="kext-dev-mode=1"

I just got a handful of these clones (so cheap) and once I installed the drivers and then set the nvram kernel extensions to dev mode all was OK.

body:
I have a Mac running OSX that is one version older than yours, and had the same problem. Once I installed the CH340 drivers, then plugged in my $3 Arduino, there was a kernel panic and I had to reboot the computer. After trying every "fix" I could find on the internet, I ordered 2 of every popular USB to serial converter on ebay.

The problem is the CH340 drivers do not always work well with OSX. Some folks are lucky and they work great, and other have issues.

A permanent solution is to use a PL2303HX USB to RS232 adapter: http://www.ebay.ca/itm/For-Arduino-Module-Converter-PL2303HX-Converter-NEW-TTL-USB-To-RS232-Adapter-/142004090259?hash=item21101a7593:g:D70AAOSwSWJXRWJV. You will have to download a driver and install it first: http://www.prolific.com.tw/US/ShowProduct.aspx?p_id=229&pcid=41 (Mac OS X Universal Binary Driver v1.5.1).

To use this converter, power up the Arduino using the power jack with 7 - 9 VDC. Connect the PL2303HX ground, TX and RX to the Arduino and plug it into your computer. If a dialog box pops up just cancel it. After you click the upload button in the Arduino IDE, you will see "Binary sketch size.." in the Debug window. Press the reset button on the Arduino for 1/2 a second then release it. The sketch should upload.

The PL2303HX is VERY dependable. Plug it in, look at the Arduino > Tools > Serial Port in the IDE and there it is. Unplug the adapter then recheck the serial port and it's gone. It doesn't matter which USB port you plug it into, the port name is the same for either and should look something like this:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/srC4x.png

You can even use the PL2303HX with a "stand alone" ATMega328P-PU. Make sure to connect a 10k ohm resistor from 5 VDC to pin 1 and momentarily ground pin 1 when you see "Binary sketch size.." in the Debug window.


body: I am trying to do some experiments with conductive sheet (velostat). When I apply a force on the sheet it should change the value of resistance(output). I taking the output of the sheet by connecting to analog input Ao of Arduino. But I am not getting constant readings from arduino, even if no pressure is applied. Do I need to build any extra circuitry to stabilize the output value? Can anyone please tell how to stabilize the output value of Arduino?

title: Stabilizing output values of conductive sheet(Velostat) connected to analog pin A0 of Arduino

Answers: 1

body: You need to use a matching resistance to create a voltage divider.


body:
I have an Arduino Yún running Openwrt-Yún 1.5.3 (which is the latest version, as I upgraded yesterday), and I am trying to obtain a .hex (compiled sketch), so that I can upload a sketch directly into the Yún. I know about compiled sketches, but there are no build directories in "C:\Documents and Settings\MY_USERNAME\Local Settings\Temp".

Where can I obtain the .hex of any file I have compiled, and how?

title: How can I obtain the .hex of a file

Answers: 1

body:
As noted in comments, enable verbose compilation and look at the output to find the temporary-directory location. (Click File, Preferences, verbose compilation.)

Note, after you click File, Preferences and the preferences window appears with its half-dozen items, you should also see a note about directly editing preferences in the preferences.txt file.  Edit that file (using a plain-text editor, not a word processor) when the arduino IDE is not running.  Change the line

    preproc.save_build_files=false

to

    preproc.save_build_files=true

so the .hex files in the temporary directory have a better chance of sticking around.

(I'm not able to test this suggestion on an MS-Windows system.  On my Linux system most build files stick around anyway in /tmp/)


body:
Do you know an IDE that is Arduino compatible, with:

 - Black background; white hurts my eyes.
 - Some auto completion features maybe?
 - And also one that lets you minimise brackets. Xcode like.
 - A better console...
 - Something to clear the serial console.
 - A **breadboard view**.

Something fancy!

title: Fancy Arduino IDE

Answers: 2

body: Have a look at Fritzing. I don't know how much you can customize there, but it has a whole suite where you can design hardware, write code, and even order PCB if you want to.

body:
I believe Eclipse can do everything you mentioned except for showing hardware layouts. The appearance of editor windows is customizable. If, by minimizing brackets, you mean collapsing them ("just indicate that something is here; I don't want to see the content"), Eclipse does that too. You can clear the console, but I don't know what "better" features you mean so I can't answer that part. It can take some setting up to get it working for you but it's far and away more powerful and feature-filled than the basic Arduino IDE. It is probably the most used IDE by people who look to upgrade from the basic one.

Update:
While it doesn't directly show hardware layouts, it does know about opening files with their default applications. If you put a Fritzing file in your project folder, when you click on it, Eclipse will launch Fritzing. If you put an image file such as a screenshot of the board layout, it will even open that within the IDE.


body:
I spent the last week working with the CylonJS framework on my edison using a Maxbotix sensor.
Everyting works with a web client on the front end.
However at the last moment I can't get the edison to talk to an existing AIR client which I must use.
Something to do with how socketIO is implemented in Cylon.

The following simple socketIO server works for me. What I need to do is incorporate support for the mraa library and get analogue input from the Maxbotix sensor.

Can anyone please help? I'm up against a deadline!!!

    var express = require('express');
        var app = express();
        var server = require('http').createServer(app);
        var io = require('socket.io').listen(server,{transports:['flashsocket', 'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']});
         var port = Number(8080);
        server.listen(port);
         app.use(express.static(__dirname + '/'));
         var temp;
         var _this = this;
         io.on('connection', function (socket) {
          console.log('connection '+socket)
         socket.on("data",function(d){console.log('data from flash: ',d);});
          socket.emit("message","wtfwtwftwftwf hello from server");
          socket.on('disconnect', function (socket) {
          console.log("disconnect");
      });

      console.log('_this ='+_this);
      _this.socket=socket;

    });

title: getting simple socketIO server to work with MRAA library on Edison

Answers: 0


body:
I bought Ethernet Shield for Arduino Uno! from AliExpress. It is good work but I scanned my network with [Fing][1] and device Vendor name is null.

Can I change/set device Vendor?

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

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

    void setup()
    {
      Ethernet.begin(mac, ip);
    }

  [1]: https://i.stack.imgur.com/K4G8Y.png

title: Arduino Ethernet Shield vendor is null

Answers: 1

body:
The vendor name is not stored on the device, rather it is indicated only by the first three octets or OUI part of the MAC address which is either stored on the device, or in your case set up by software.  Turning this back into a name on another computer which sees its traffic is done by the help of a local or network-sourced OUI lookup table.

Apparently the table your computer is consulting doesn't have an entry for the OUI 0xDE, 0xAD, 0xBE.

And that's not surprising as this is clearly a dummy value put in as a placeholder - read all 6 octets as if they were a word and you'll see it says "dead beef feed" - a variation on a classic magic "illegal" value.

Technically, this is actually a legal value for use on a local network as the 2's bit of the leading octet is turned on, indicating that it is a "locally administered" address, rather than one guaranteed to be unique in all the world as you would expect a proper piece of network hardware to have.

If you find the table your computer is doing OUI lookups in, you could add a DE:AD:BE entry to it.