message:
How to design and debug a custom I2C master-slave system?

How to proceed, when in need of a custom I2C master-slave system?

What are the design criteria to apply?

What are the debugging tools one can use to troubleshoot problems?

body:
This tutorial I gave at the Embedded Linux Conference tries to answer the questions, providing links to more detailed description of the topics addressed and using the practical example of driving a 4WD drone, where an Arduino Mini Pro acts as slave and controls the 4 independent wheels.
The original document can be found [here][1].

Note: This answer is currently work in progress, as I adapt the highlights from the link.

----------

Typical Applications of the I2C bus
===================================

 - Interfacing with relatively slow peripherals. Ex: sensors, mechanical actuators.
 - Controlling “fast” peripherals, that use other channels for exchanging data. Ex: codecs.

    In a PC, the Operating System usually interacts over I2C with:

    - temperature and battery voltage meters;
    - fan speed controllers;
    - audio codecs.

In case multiple bus controllers are available, peripherals are grouped by speed, so that fast ones are not penalized by slower ones.

----------

A quick introduction to the I2C bus - key features
==================================================
 - Serial bus.
 - Only 2 lines: Serial CLock and Serial DAta (plus ground).
 - 4 speeds: 100kHz, 400kHz, 1MHz, 3.2MHz.
 - Typically, 1 master device and 1 or more slaves.
 - Communications are always initiated by a master device.
 - Multiple masters can co-exist on the same bus (multi-master).
 - Open-Drain: both SDA and SCL need pull-up resistors.
 - “Clock Stretching”
     - The master controls SCL, but a slave can hold it down (because open drain), if it needs to adjust the speed.
     - The master must check for this scenario.
     - A slave can get stuck and jam the bus: need for reset lines from the master to the slave.
 - Typically 7-bit addressing, but also 10 bit is supported.
 - Logical protocol: actual voltage levels are not specified and depend on individual implementations. Ex: 1.8V / 3.3V / 5.0V

Reference URLs:

 - [http://www.i2c-bus.org][2]
 - [http://www.robot-electronics.co.uk/i2c-tutorial][3]

Example of Bus Configuration
============================
[![Example of Bus Configuration][4]][4]

----------
Characteristics of the Protocol (simplified)
============================================
 - 2 message types: *read* and *write*
 - Start / Stop bit - represented as “[“ and “]” in the rest of the answer
 - Address: 7 or 10 bits
 - R/W bit: R = 1 / W = 0 Used to discriminate the type of message sent.
 - Data on the bus: (Address << 1 | R/W)
 - Registers as information handlers, within the selected device.

Example of Bus traffic
======================
[![Example of Bus Traffic][5]][5]
[![Example of Bus Write Cycle][6]][6]
[![Example of Bus Read Cycle Part1][7]][7]
[![Example of Bus Read Cycle Part2][8]][8]

----------
Custom Slaves
=============

*Why create a custom I2C slave?*

 - Desired sensor/actuator unavailable with I2C interface.
 - Less unique addresses available than slaves needed.
 - Desired custom functionality on the slave:
    - Semi-autonomous reactions to stimuli.
    - Filtering/preprocessing input data.
 - Power optimization: custom “sensor hub” does the housekeeping while the main processor is idle.
 - Realtime response to inputs.
 - [your imagination here]

*How to design a custom I2C slave?*

 - Define requirements (see previous slide).
 - Choose microcontroller or microprocessor.
 - Choose Scheduler or Operating System (if any).
 - Define communication sub-protocol:
    - Define parameters and commands to be exchanged.
    - Organize them into “registers” and choose a free address.

----------

Design of the I2C Master
========================

Key design criteria:

 - Weight/Dimensions.
 - Required computational power and average latency.
 - PC-like device
    - Embedded device, typically headless.
    - Preferred programming language: interpreted vs compiled.
 - Availability of busses/gpios for driving the slave(s):
    - GPIOs only: bitbang the protocol
    - I2C: user-space application vs kernel driver.
    - No GPIOs/I2C interfaces available: USB to I2C adapter.

----------
Debugging: Divide and Conquer
=============================

Take direct control of the bus with an ad-hoc device.
Examples:

 - Bus Pirate (useful also for other busses)
 - USB to I2C Master adapter, also based on the FTDI FT232R chip.
 - Custom device (could be a separate project).
 - Snoop the bus with a logic analyzer or a scope/advanced meter.
   Examples:
    - sigrok/pulseview with compatible logic analyzer
    - 2-channels standalone scope/meter
    - Use slave-specific In Circuit Debugger/In Circuit Emulator.

      Example:
      AVR Dragon for AVR chips (Arduino UNO, Nano, Mini, MiniPro)

----------
BUS Pirate
==========
[![Bus Pirate][9]][9]

 - Primarily for development purposes.
 - Can both sniff the bus and drive it.
 - Console interface over serial (ttyACM) port, including macros, or programmatic access for several programming languages.
 - Built-in pullup resistors and voltage sources (5V / 3.3V)
 - Supports many other protocols.
 - References: [Wikipedia][10], [main page][11]

----------
USB to I2C Adapter
==================
[![usbtoi2c][12]][12]

 - Small footprint.
 - Suitable for permanent installations.
 - No need for special connections on the host: it can be used to interface with a typical PC.
 - Variant available that is also SPI-capable.
 - No console interface, only serial binary protocol.
 - Requires [protocol wrapper][13].
 - Reference: [protocol][14]

----------
sigrok and pulseview
====================
sigrok(bakend component) logo

[![sigrok][15]][15]

pulseview (visualizer) example

[![pulseview][16]][16]

Example of low end logic Analyzer

[![saleae][17]][17]

 - De-facto standard for PC-driven measurements on linux (but available on other OSes too).
 - Support for vast range of logic analyzers, scopes and meters.
 - Various protocol decoders, including I2C.
 - Useful for visualizing the logical signals and debugging protocol errors.
 - Even very low end, inexpensive HW can provide a whole new dimension to debugging.
 - References: [sigrok][18], [pulseview][19], [supported hardware][20]

----------
Example: steering a 4WD drone
=============================
Prototype built using 2 Arduino Mini Pro.
[![Drone][21]][21]

----------
What does the slave do in the example?
======================================

The I2C slave:

 - Controls the amount of torque applied to each wheel.
 - Controls the direction each wheel spins.
 - Measures  the rotation speed of each wheel through an optical encoder (Odometer).
 - Exposes the parameters above to the I2C Master.

[![Slave Role][22]][22]

High level block diagram of the I2C Slave.

----------

Selecting the Slave: [Arduino Mini Pro][23]
=====================================

[![MiniPro][24]][24]

 - Enough pins/functions to provide for each wheel:
   - 1 PWM output with independent configuration of the duty-cycle.
   - 1 GPIO for registering odometer input as IRQ.
   - 2 GPIOs for selecting:
     - Forward
     - Reverse
     - Idle
     - Lock
 - I2C HW block for interrupt-driven i2c exchanges.
 - Dedicated pins for SPI-based programming.
 - Small footprint.
 - Low Cost.
 - The board layout of the clone represented in the picture is optimized for mounting on a DIL socket.

----------

Slave-specific ICD: [AVR Dragon][25]
==============================
[![AVR Dragon][26]][26]

 - Supports various programming modes, included SPI programming, through [AVRDude][27].
 - Doesn’t interfere with normal AVR operations, so it can be left plugged into the system.
 - [After enabling debugWire interface, it allows configuring HW/SW breakpoints, by a dedicated backend for gdb/ddd.][28]

----------

Selecting the OS: [ChibiOS][29]
=========================
[![ChibiOS][30]][30]

 - RTOS: preemption, tasks, semaphores, dynamic system tic, etc.
 - Small footprint: link only used code/data.
 - Distinction between RTOS and BSP through HAL.
 - GPLv3 for non-commercial use.
 - Actively developed, but already mature.
 - Supports 8bit AVR.

However it had limited BSP support for AVR, lack of:
 - interrupts driver for AVR GPIOs (added).
 - I2C support for AVR slave mode (custom).
Which had to be developed separately as part of the [Drone SW for the AVR][31].

----------

Defining the Communication Parameters
=====================================

*For each wheel:*

 - **Duty Cycle** of the PWM signal used to drive it - 1 byte.
0xFF = max torque / 0x00 = no torque.

 - **Direction** of rotation - 1 byte.
   - 0x00 = idle
   - 0x01 = reverse
   - 0x02 = forward
   - 0x03 = locked

 - **Average period** in between slots of the optical encoder - 2 bytes.
   - Writing anything resets the measurement.

 - **Parameter Index** - 1 nibble:
   - 0 = Duty Cycle
   - 1 = Direction
   - 2 = Average Period

 - **Wheel indexes** - 1 nibble:
   - 0 = Left Rear
   - 1 = Right Rear
   - 2 = Right Front
   - 3 = Left Front
   - 4 = All

----------
Sub Protocol: Defining the Registers
====================================

**Register format:   0xαβ**
 - α = Parameter Index
 - β = Wheel Index

**Address** (chosen arbitrarily): 0x10

**Bus Pirate format:**
 - [ = start bit
 - ] = end bit
 - r = read byte
 - address times 2 (left shift 1), for R/W bit

----------

Example - in Bus Pirate Format
==============================
**[   i2c_addr   reg_addr=(parm,wheel)   reg_value  ]**

    [0x20 0x20 0x02]  Left Rear Forward
    [0x20 0x21 0x01]  Right Rear Backward
    [0x20 0x22 0x01]  Right Front Backward
    [0x20 0x23 0x02]  Left Front Forward
    [0x20 0x14 0xFF]  Wheels set to max torque

*The car spins clockwise.*

  [1]: http://events.linuxfoundation.org/sites/events/files/slides/ELC 2016 - I2C hacking demystified.pdf
  [2]: http://www.i2c-bus.org
  [3]: http://www.robot-electronics.co.uk/i2c-tutorial
  [4]: https://i.stack.imgur.com/DGm1u.png
  [5]: https://i.stack.imgur.com/X10rA.png
  [6]: https://i.stack.imgur.com/U16Rg.png
  [7]: https://i.stack.imgur.com/90Myv.png
  [8]: https://i.stack.imgur.com/QZiUT.png
  [9]: https://i.stack.imgur.com/lcwyU.jpg
  [10]: https://en.wikipedia.org/wiki/Bus_Pirate
  [11]: http://dangerousprototypes.com/docs/Bus_Pirate
  [12]: https://i.stack.imgur.com/BpCww.jpg
  [13]: https://arduino.stackexchange.com/questions/22069/how-to-operate-under-linux-an-usb-to-i2c-adapter-based-on-the-ftdi-ft232r
  [14]: http://www.robot-electronics.co.uk/htm/usb_i2c_tech.htm
  [15]: https://i.stack.imgur.com/TaJQVm.jpg
  [16]: https://i.stack.imgur.com/LpBQ0m.png
  [17]: https://i.stack.imgur.com/Hged9m.jpg
  [18]: https://sigrok.org
  [19]: https://sigrok.org/wiki/PulseView
  [20]: https://sigrok.org/wiki/Supported_hardware
  [21]: https://i.stack.imgur.com/ptWAZ.jpg
  [22]: https://i.stack.imgur.com/3HfLd.jpg
  [23]: https://www.arduino.cc/en/Main/ArduinoBoardProMini
  [24]: https://i.stack.imgur.com/7bSx8.jpg
  [25]: http://www.atmel.com/webdoc/avrdragon/
  [26]: https://i.stack.imgur.com/WxABh.jpg
  [27]: http://www.nongnu.org/avrdude/
  [28]: http://www.larsen-b.com/Article/315.html
  [29]: http://www.chibios.org/dokuwiki/doku.php
  [30]: https://i.stack.imgur.com/Kzbau.jpg
  [31]: https://github.com/igor-stoppa/ChibiOS/tree/car/


sender: user

message:
Port Manipulation - fastest implementation

I'm working on an Arduino program but am getting bogged down on what is the 'correct' implementation. I understand that multiple versions may work, so for my needs the 'correct' version will be the fastest (i.e. executing in the fewest clock cycles)

I need to set three analog input pins on my Mega 2560 - let's call them PF2-0.

- I could use pinMode() - but that performs some extra checks that I want to leave out.
- I could use _BV() in the process, but that's another function call I wish to avoid.

So, using port manipulation, I can write:

    DDRF = 0x07; //PF2, PF1, PF0 as input
    PORTF = 0x07; // Disable pullups

This should configure my three pins as inputs - and reduce any extraneous function calls. This should even be faster than writing:

    DDRF = (1 << PF2) | (1 << PF1) | (1 << PF0)

Is this the fastest implementation?

*To be honest, I'm not sure how to profile this to know for sure.

sender: assistant

body:
AFAIK the compiler should be smart enough to use bit manipulation instructions when in presence of _BV().

When unsure, you can always add -save-temps to the gcc options, to see what the compiler actually does. It will not give you profiling information, but you can see in detail how your C gets turned into assembly.

Remember to pay attention to what level of optimization you use. You should use the same that will be employed in the final version of your code (probably O2).


body:
The standard Arduino way of doing this is to use `pinMode()`. It's not
fast, but it's easy to understand, especially for beginners. And it's
portable across architectures.

If you want to go fast, then you should skip the Arduino functions and
use port manipulation, and avr-libc. The standard avr-libc way of doing
what you want is:

<!-- language: c++ -->

    DDRF = _BV(PF2)   // set PF2 as output
         | _BV(PF1)   // also PF1
         | _BV(PF0);  // and PF0

This compiles to two assembly instructions: one for loading a CPU
register with the constant, and the other to copy the register to the
DDRF IO port. Notice that you set the bits for the pins you want to set
as _outputs_, and you clear the bits for the inputs. By default, all the
pins start as inputs.

The `_BV()` here is not a function call: it's a macro that expands to
`(1 << (x))`. The way you write the expression to the right of the `=`
sign is irrelevant as long as it is recognised to be a compile-time
constant. If you want to see for yourself, you can disassemble the
generated binary with the command

    avr-objdump -S -C my_prog.elf > my_prog.lst

You get an assembly listing interspersed with your source. Doing this on
the example above yields:

        DDRF = _BV(PF2)   // set PF2 as output
             | _BV(PF1)   // also PF1
             | _BV(PF0);  // and PF0
    100: 87 e0        ldi r24, 0x07 ; 7
    102: 80 bb        out 0x10, r24 ; 16

Here, the `ldi` instruction means “load immediate”, i.e. load a register
(r24) with a constant value (0x07). The “out” instruction copies that
register into port 0x10 (namely DDRF). Both are single cycle
instructions, so the whole sequence takes two CPU cycles.


message:
Sampling Rate of Arduino Uno

It might be a stupid question but, I am currently using Arduino Uno with the 16MHz processor, what is maximum sampling rate of data available to me if I want to read data of a sensors such as accelerometer?

body:
I have a [page about I2C](http://www.gammon.com.au/i2c). The speed of I2C depends on a number of things, such as the I2C clock (which you can change) and also how many data bytes are in a "packet". There is a fixed overhead of the device address in each packet.

A broad rule-of-thumb would be around 4700 bytes per second for a single-byte payload at the default clock rate. You may also need to spend time asking for a reading. I haven't read the datasheet (which you didn't link).

The datasheet for the MPU6050 may give you more information about how fast it can respond.


message:
Arduino Nano - Unknown USB device

I just bought an Arduino Nano v3.0 (compatible? +- 5$) and I cannot connect it to my computer (Windows 8.1 64bit, Arduino IDE 1.6.8 installed).

The Arduino was bought as a clone but shows GRAVITECH.US on the front.
It has a FTDI FT232RL chip (1412-G B8908572) on the back.

When connecting the Arduino the power leds burns the TX and RX led flash a few times (really shortly) and then die. Then the yellow L leds blinks once per second continiously.(power to the Arduino comes from the USB cable, not from external power)

In the system tray I get a message saying

    "The last USB device you connected to this computer malfunctioned,
    and Windows does not recognize it."

In the device manager I get a node under Universal Serial Bus Controllers:

    Unknown USB Device (Device Descriptor Request Failed).

When examining the properties of the device, the device-status is:

    Windows has stopped this device because it has reported problems. (Code 43)
    A request for the USB device descriptor failed.

- I tried to reset the device
- I tried different USB cables
- I used another Windows 8.1 PC without Arduino IDE installed
- I used an old XP computer

All give same error.

I read about the bricking of clones by the recent FTDI drivers...
I downloaded the FT_Prog tool V3.0.60 to check the PID, but the tool simply does not find the Arduino...

I'm out of ideas... does anyone have some left?

Thanks in advance!

Michiel

body:
I found the issue!
There is a bug in the Arduino hardware:
https://ketturi.kapsi.fi/2014/04/how-to-fix-moody-arduino-nano/

You need to bridge pins 25 and 26 of the FTDI chip (located at the back of the Arduino) to ground the pin 26 TEST signal.
If I connect these pins then it works just fine!


body: I've had this issue before. You can try reuploading the bootloader. If that doesn't work, maybe try re-installing the drivers.


message:
What is the best way to attach TMP36 sensor to the copper coil?

I am very new to this site and this question may not be strictly related to Arduino, but I do small Arduino project which needs to measure the temperature of the copper coil using TMP36GZ sensor.

What is the best way to glue it to the coil for best measurements?
Shoul I use silikone or epoxy?
Should I take extra steps to ensure proper readings from the coil surface (f.ex.: using thermal paste)?

body:
If you don't have to worry about conductivity from the electrical standpoint, you could use a thermal epoxy such as [Arctic Silver][1] which uses "microfine" particles of silver to conduct heat. It's a two part (redundant when using the term epoxy, I think) adhesive that is engineered to transfer heat, but may also short conductors. I've used the stuff and unless subject to intentional separating force, it holds well.

  [1]: http://www.arcticsilver.com/arctic_silver_thermal_adhesive.htm


body:
The datasheet devotes a whole page to mounting and thermal conductivity (though not to specific adhesives), particularly with respect to the plastic, through-hole devices, as the leads provide more a direct conductivity path to the sensing junction than the plastic bead does. If the surrounding air is at a different temperature from the coil surface you'll either need to insulate the leads from the air, or better, epoxy them to the coil with a thermally conductive but electrically insulating epoxy.

Here's an excerpt:

> Caution should be exercised, especially with T-3 packages, because the > leads and any wiring to the device can act as heat pipes, introducing errors if the surrounding air-surface interface is not isothermal. Avoiding this condition is easily achieved by dabbing the leads of the temper-ature sensor and the hookup wires with a bead of thermally conductive epoxy. This ensures that the TMP35/TMP36/ TMP37 die temperature is not affected by the surrounding air temperature. Because plastic IC packaging technology is used, excessive mechanical stress should be avoided when fastening the device with a clamp or a screw-on heat tab. Thermally conductive epoxy or glue, which must be electrically nonconductive, is recommended under typical mounting conditions.

Update:
I also noticed they didn't specify an epoxy, which I take to mean the feel it isn't critical. You'll need one compatible with "most" plastics and with copper. I'd probably use a big "wad" (that's a technical term :) of any off-the-shelf non-electrically conductive epoxy over the whole sensor and its leads, getting the sensor face as close to the copper as possible. I might even wrap some thermal insulation around the connecting wires for a foot or so, or even wrap that much of them around the coil and tape them to it, just to keep the sensor and the wires at as close to the coil temperature as possible. My guess is that will be more than sufficient to get temperature readings of the coil to within the sensor's limits of accuracy.


message:
Maximum potentiometer resistance

I want to hook up a potentiometer to my arduino (Leonardo) as a voltage divider with the middle pin to an analog pin. I want to use the highest resistance to save power. I looked on the datasheet and it said the maximum output impedance is 10kOhm (§24.7.1 on Atmega32u4 datasheet). I also found another question that said I should use a 10kOhm potentiometer. What doesn't make sense is if the knob was turned towards the middle so that there is 5k on both sides, it's not the maximum capable resistance. So should I use a 20kOhm potentiometer?

body:
There is a lengthy discussion about this on [the Arduino Forum](http://forum.arduino.cc/index.php?topic=169000.10). As I understand it, the input impedance is only important if you are sampling a rapidly varying signal, as it takes a finite time to charge the sample/hold capacitor. However your potentiometer would not vary rapidly (certainly not in the order of thousands of herz). Thus I don't think the potentiometer resistance will be particularly important, particularly if you are not changing the analog inputs (eg. from one channel to another). The continuous current through the 10k pot would be 0.5 mA.

If you are worried about power, then rather than connecting the +5V side directly to 5V, connect it to an output pin, which you can bring high when you want to take a measurement, and make low at other times. That reduces the power through the pot, since there won't be a voltage potential. You might allow a few microseconds for the reading to stabilize when you need to take one.

---

> So the lower the pot resistance, the faster response time? Also I will constantly always be taking a measurement

No, I don't think this is an issue. The "response time" is really the time taken to do the ADC calculation (nominally 104 µs if you don't fiddle with the registers).

See [ADC conversion on the Arduino (analogRead)](http://www.gammon.com.au/adc). As mentioned on that page you can speed up the measurement by changing the ADC prescaler. However even with a prescaler of 128 you get 9615 conversions per second. I doubt you can turn the pot fast enough for this to be a meaningful issue.

Regardless of the response time, the issue here is *accuracy*. Will a lower pot value give more accurate results? Well, I doubt it. The ADC effectively copies the analog input into a 14 pF capacitor (the "sample and hold" capacitor) which it then tests against the reference voltage divided up in various ways.

The input impedance would be relevant if you were sampling a *high-frequency input*. On the page I linked I sampled a 4 kHz sine wave and got good results. You just won't be turning the pot that fast (4000 times a second).

---

> I'm still unsure with how potentiometer resistance affects the data ...

If you keep sampling the same ADC input (eg. A0) then I think the sample and hold capacitor can be charging in the background (while your code is doing other things).

But even if that were not the case, the datasheet says the sample and hold operation takes place 1.5 ADC cycles after the conversion starts. So at 16 MHz clock rate, and a prescaler of 128 for the ADC clock, this means we have:

    128 * 62.5 ns * 1.5 = 12 µs

Now since the datasheet says the sample-and-hold capacitor is 14 pF, and the time taken to (almost fully) charge a capacitor is reckoned to be:

    5 * R * C

Given R = 110k and C = 14e-12 (14 pF) then it will take:

    5 * 110000 * 14e-12 = 7.7 µs

I quoted 110k because the datasheet mentions a resistance of 1 to 100k in series with the capacitor, plus the 10k impedance they recommend.

This means the capacitor will charge within the 12 µs it has available. Bump R up to 1e6 (1 megohm) and the calculation now gives:

    5 * (100e3 + 1e6) * 14e-12 = 77 µs

This exceeds the 12 µs quoted for the sample-and-hold.

This is why, I suggest, that for fast-changing signals they recommend a lower input impedance.

However if I am correct that the sample-and-hold capacitor is normally connected to the ADC input, then that 77 µs can be spread over the time you deal with the calculation. Still, that is quite a few clock cycles. :)

---

My recommendation is to stick with 10k or so potentiometer (as recommended by the datasheet) and use my earlier suggestion of connecting the 5V side of the pot to an output pin instead of continually having it connected to the +5V signal. That way you only need to "power" the pot when you actually need to take a reading. However you can see that a 20k pot (or even 50k) will probably still be in an acceptable range for an accurate conversion.

For example, a 50k pot could charge the capacitor in:

    5 * 150000 * 14e-12 = 10.5 µs

---

I would also be cautious about a 1 megohm pot because then slight variances in other things (eg. heat on the wire, nearby noise) could swamp the reading from it.

---

> Wait, sorry do I need to half my potentiometers' resistance if I'm using two analog inputs?

No, because the multiplexer chooses one input at a time (the others are effectively out of circuit).

However if you are choosing between two pots (to measure two) then the resistance becomes more relevant. As I showed, with a high value pot it takes longer to charge the capacitor, so if you read A0 and then immediately afterwards A1, you don't want a lengthy charging time for the capacitor, because that would give erroneous readings.


message:
nrf24l01 (8pin) + adapter board (10pin) oops?

I just got my first arduino boards and have been learning the basics (so I know very little). I got the 2.4GHz NRF24L01+ (this one: [NRF24L01+][1]) and along with it a breakout board (this one: [NRF24L01+ board][2]) which I didn't realize was 10pin (nor that there is an 8pin version) vs the wireless board's 8pin. So my question is, is it safe to connect the module to this adapter board in some way? From the pinout of both I would assume not, since for example the bottom two pins on the board are ground (and therefore connected together) and the ground pin on the NRF24L01+ is next to the VCC ([NRF24L01+ pinout][3]) and the top two on the board are both VCC 3.3 and from what I can tell by looking at the etched lines, it seems it leads to the resistors (not sure if they are resistors or what, like I said, I know very little still). There seems to be an LED on this board as well, connected to the AMS1117 chip (that's a voltage regulator, correct?).

So, I am guessing I cannot just connect the NRF24L01+ to the adapter board straight in, right? But, can it with some wires? Would that even make sense? Also, is this board even necessary for anything? I bought it having read something somewhere (been reading too much to keep track of where exactly) that recommended it, but a tutorial I saw today didn't make use of it, instead just soldering a capacitor to two of the pins saying some other place recommended it to reduce noise.

  [1]: http://www.ebay.ca/itm/2pcs-2-4GHz-NRF24L01-Antenna-Wireless-Transceiver-Module-For-Microcontrol-/181847271521?hash=item2a56f12861:g:yn4AAMXQUmFSoxhZ
  [2]: http://www.ebay.ca/itm/191674251825?_trksid=p2057872.m2749.l2649&ssPageName=STRK:MEBIDX:IT
  [3]: http://yourduino.com/docs/nRF24L01-Modules-connection-diagram.pdf

body:
To be honest, I don't see much added value for this breakout board.

First, as you mentioned, you won't be able to plug your NRF24 directly into it because the pinout is not compatible; hence, **you will have to use wires for that**. But you could as well use wires directly from your Arduino to the NRF24 module.

Second, regarding power (you are right, AMS1117 is a voltage regulator), the **Arduino 3.3V pin is enough** (**50mA** for UNO) to power your NRF24 as its current consumption is low (max **13.5mA** as per the [datasheet][1]):

[![enter image description here][2]][2]

Please note these are specifications for the chip itself not for the board, which may need a bit more current, but not much more according to my own experiments.

As a side note, I have created my own very simple breakout for the NRF24 board, with just a tiny piece of stripboard, that's something you can easily do by yourself if you have the right tools (saw, cutter, soldering iron), a few pin headers and some stripboard scrap:

[![enter image description here][3]][3]

Last, the only utility I see with your breakout board is to be used as 3.3V supply for higher currents in future experiments.

**EDIT:**

as commented by @Hans-Neve, a capacitor would be useful between 3.3V and GND pins, as near the NRF24L01 board as possible, so that short consumption peaks do not impact correct function of the board. The breakout board has one (or more exactly 2: 100nF and 10uF) It is advised you add those two (at least the large 10uF cap) in your circuit. I saw some people directly soldering one cap on the pins of the NRF24 board, but if you use short enough wires to connect it, you can perfectly put this cap on a breadboard during your experiments.

  [1]: http://www.nordicsemi.com/eng/content/download/2726/34069/file/nRF24L01P_Product_Specification_1_0.pdf
  [2]: https://i.stack.imgur.com/qg7Mn.png
  [3]: https://i.stack.imgur.com/9QxLM.jpg


message:
Keyboard input arduino speed

I have an Arduino clone of a Leonardo and I was just wondering how many keyboard commands I can send to the computer per second via USB. I'm not talking about the delay between send and receive (because that could vary between computer), I'm talking about the minimum possible time between something like stimulating a key press down and key press up as fast as possible.

body: From my tests, it has been at least 1 millisecond, however, it can depend on what is running simultaneously on the Arduino.


message:
Funduino Uno with 5V 1A power supply?

Can I use a "Funduino Uno" arduino with power from a power bank with DC 5V 1A output?

body: Yes. As long as it connects the the arduino clone via USB and can maintain a stable power output then it's suitable.


message:
Is it possible to make 4hz readings with the DS18S20 temperature sensor?

My current code that doesn't convince me:

    #include <OneWire.h>

    int DS18S20_Pin = 3; //DS18S20 Signal pin on digital 3
    unsigned long startTime = 0;
    #define MEASURE_PERIOD 250
    //Temperature chip i/o
    OneWire ds(DS18S20_Pin);  // on digital pin 3

    void setup(void) {
      Serial.begin(115200);
    }

    void loop(void) {
      if((millis() - startTime) >= MEASURE_PERIOD)
        {
            startTime += MEASURE_PERIOD;
            float temperature = getTemp();
            Serial.println(temperature);
        } //just here to slow down the output so it is easier to read

    }

    float getTemp(){
      //returns the temperature from one DS18S20 in DEG Celsius

      byte data[12];
      byte addr[8];

      if ( !ds.search(addr)) {
          //no more sensors on chain, reset search
          ds.reset_search();
          return -1000;
      }

      if ( OneWire::crc8( addr, 7) != addr[7]) {
          Serial.println("CRC is not valid!");
          return -1000;
      }

      if ( addr[0] != 0x10 && addr[0] != 0x28) {
          Serial.print("Device is not recognized");
          return -1000;
      }

      ds.reset();
      ds.select(addr);
      ds.write(0x44,1); // start conversion, with parasite power on at the end

      byte present = ds.reset();
      ds.select(addr);
      ds.write(0xBE); // Read Scratchpad

      for (int i = 0; i < 9; i++) { // we need 9 bytes
        data[i] = ds.read();
      }

      ds.reset_search();

      byte MSB = data[1];
      byte LSB = data[0];

      float tempRead = ((MSB << 8) | LSB); //using two's compliment
      float TemperatureSum = tempRead / 16;

      return TemperatureSum;

    }

the outcome of few seconds of recording:

    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31
    22.31

EDIT: I inserted the suggestion of @frarugi87 and I inserted the sensor in my pants to test it:

    22.50
    22.50
    22.50
    23.69
    23.69
    23.69
    23.75
    23.75
    23.75
    23.75
    23.75
    23.75
    23.81
    23.81
    23.81
    23.81
    23.81
    23.81
    23.81
    23.81
    23.81
    23.87
    23.87
    23.87
    23.87
    23.87
    23.87
    23.87
    23.87
    23.87
    23.87
    23.87
    23.87
    23.94
    23.94
    23.94
    23.94
    23.94
    23.94
    23.94
    23.94
    23.94
    23.94
    23.94
    23.94
    24.00
    24.00
    24.00
    24.06
    24.06
    24.06
    24.19
    24.19
    24.19
    24.25
    24.25
    24.25
    24.31
    24.31
    24.31
    24.44
    24.44
    24.44
    24.50
    24.50
    24.50
    24.56
    24.56
    24.56
    24.56
    24.56
    24.56
    24.62
    24.62
    24.62
    24.69
    24.69
    24.69
    24.75
    24.75
    24.75
    24.81
    24.81
    24.81
    24.87
    24.87
    24.87
    24.87
    24.87
    24.87
    24.94
    24.94
    24.94
    25.00
    25.00
    25.00
    25.00
    25.00
    25.00
    25.06
    25.06
    25.06
    25.12
    25.12
    25.12
    25.12
    25.12
    25.12
    25.19
    25.19
    25.19
    25.25
    25.25
    25.25
    25.25
    25.25
    25.25
    25.31
    25.31
    25.31
    25.37
    25.37
    25.37
    25.44
    25.44
    25.44
    25.44
    25.44
    25.44
    25.50
    25.50
    25.50
    25.50
    25.50
    25.50
    25.56
    25.56

I still find the change of temperature slow

body:
I would expect some variations in temperature, but I would not say that is a problem caused by the 4Hz readings. You can test my assumption by reading every 3 seconds, does the temperature value change or is it still the same?

I see two potential problems:

1. your DS1820 is defect.

2. from your code I assume that you use parasitic power. In that case the chip consumes power from the data wire ( one wire ;-) ) through a pull up resitor (~4.7 kOhms). If you do not provide a special handling, to drive more current while the DS1820 is converting or copying data to EE or from EE memory to the scratchpad, then there will be (most likely) voltage drops.
Then the Temperature conversion will not happen and you read the old value from the scratchpad in your read cycle.

You can test point 2 by adding VCC to the DS1820, and do not use parasitic power.
If that is your problem, you can fix it with a switching FET Transistor, that provide more current (see DS1820 Datasheet from Maxim) or by using an additional VCC wire.


body:
Not sure if this is the only problem, but when shifting bytes you will lose the msb. This can be solved by casting the variable to an int.

And moreover you don't need the two variables `MSB` and `LSB`.

Try to correct it with this:

    float tempRead = ((((int)data[1]) << 8) | data[0]); //using two's compliment


body:
> Is it possible to make 4hz readings with the DS18S20 temperature sensor?

Yes, but only at 9-10 bits resolution. See [Table 2. Thermometer Resolution Configuration][1]. At full resolution, 12 bits, the conversion time is 750 ms. With the commands, reset, etc, this gives just over 1hz.

I guess this also gives you a hint on what to fix in your sketch.

Cheers!

  [1]: https://datasheets.maximintegrated.com/en/ds/DS18B20.pdf


body: The rate of change of the temperature reading depends on the thermal properties of the sensor package, not on the rate at which you read it. The less expensive, plastic packaged sensors that most of us use will be the slowest to respond to change just because that is the thermal nature of the plastic. Do note that the ground pin of that package has more influence than the package itself, so do your best to ensure the ground pin is exposed to the temperature you're trying to measure, or is at least thermally insulated from the surrounding air, unless the air temperature is what you are trying to measure. If you need faster response to temperature change, you'll need to pay attention to keeping the entire device at or close to the temperature of interest and insulated from surrounding temperatures.


message:
Can you use both 3.3v and 5v

Can you use an Arduino EtherMega's 3.3v and 5v pins with two sensors, one requiring 3.3v and the other 5v and a sketch that combines both?

body: Yes. As long as you take into account that the outputs of the Arduino will be 5V so you may need to reduce that to 3.3V for the 3.3V sensor (if it has any connection to an output).


message:
RTC interrupts and coin batteries

# Summary

I'm having problems with my RTC draining its coin cells quickly - fresh batteries are drained in a few months. The RTC is set to signal an interrupt every 5 minutes, and I wonder - if there is no other power attached to the circuit, is that enough to drain the coin cell?

# Details and my troubleshooting:

Problems with my RTC - if I leave the circuit unpowered for a few days (so that the only power to the RTC is from the coin cell backup), the time resets to 00:00 January 1, 2000. This doesn't happen immediately when I unplug it. If I disconnect it from the computer, plug it back in the next day, the time is ok. If I leave it unplugged for a few days, then plug it in, the date is reset.

This suggests the battery is bad. So I tested it with my meter (and an 100 ohm load, as described here: https://www.youtube.com/watch?v=HcikzMG7mMU). And sure enough, the batter has dropped quite a bit from its 3V start value.

That's all good, except that this battery is only a few months old, and it should last for years in an RTC. I've got two batteries purchased in the last year and used in RTC modules, and both are now drained.

My current hypothesis is that, after I unplug my circuit from the computer, the RTC continues to run on the coin cell, firing interrupts every 5 minutes, and it is these interrupts that are causing the drain. Does this make sense? If not, what else could I check?

# Setup

Breadboard arduino, DS3231 RTC on a breakout, connected

- RTC SDA -> Arduino A4
- RTC SCL -> Arduino A5
- RTC GND -> Common GND
- RTC VCC -> Common 5V (from ftdi/USB cable, when plugged in)
- RTC SQW -> Arduino D2

The RTC is 'active-low', and the SQW pin is held at 5V between interrupts. With my multimeter, the brief drop to 'LOW' is undetectable. I also can't detect any current flow from the SQW pin with my multimeter.

# Sketch

Including only the code related to the RTC (SD card and temperature bits removed).

    /*-(Import required libraries)-*/
    #include <Time.h>
    #include <DS3232RTC.h> //source: https://github.com/JChristensen/DS3232RTC

    /*-( Declare Constants )-*/
    const int wakeUpPin = 2;
    #define resolution 5 // frequency in minutes to wake from sleep

    /*-(Declare Variables)-*/
    time_t t;
    int nextLoop;

    /****** SETUP: RUNS ONCE ******/
    void setup()
    {
      Serial.begin(9600);

      Serial.println();
      pinMode(wakeUpPin, INPUT);

      t = RTC.get();

      nextLoop = ((minute(RTC.get()) / resolution) + 1) * resolution;
      if (nextLoop >= 60) {
        nextLoop -= 60;
      }
      Serial.print(RTC.temperature());
      Serial.print(",");
      Serial.print(RTC.oscStopped());
      Serial.print(",");
      Serial.println(nextLoop); // the minutes when the next reading will be taken

    }

    /****** LOOP: RUNS CONSTANTLY ******/
    void loop()
    {
      t = RTC.get();

      Serial.print(year(t), DEC);
      Serial.print("/");
      Serial.print(month(t), DEC);
      Serial.print("/");
      Serial.print(day(t), DEC);
      Serial.print(",");
      Serial.print(hour(t), DEC);
      Serial.print(",");
      Serial.print(minute(t), DEC);
      Serial.print(",");
      Serial.print(second(t), DEC);
      Serial.print(",");

      goToSleep();
    }

    void goToSleep(void) {
        Serial.print("Sleeping until: ");
        Serial.println(nextLoop);
        Serial.flush();
        RTC.setAlarm(ALM2_MATCH_MINUTES, nextLoop, 1, 1);
        RTC.alarmInterrupt(ALARM_2, true);
        attachInterrupt(0, wakeUp, LOW);

        LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
        detachInterrupt(0);
        RTC.alarm(ALARM_2);
        nextLoop += resolution;
        if (nextLoop >= 60) {
             nextLoop -= 60;
        }
    }

    void wakeUp(){
      // Handler for the pin interrupt.
    }

body: Check your battery, it is behaving like a rechargeable one without a charger.  Mine have the letter "R" at the end of the part number.  There are a lot of RTC modules that charge the battery. Conversely they are some that do not charge the battery. Are you powering it with something other then the coin cell.


message:
Pro Mini Fuse Repair

It looks like I broke my Arduino (Compatible) Pro Mini board using AtmelStudio to change the fuses. I was having trouble with speed and using some basic sketches. For example, the LED blink was on for 2 seconds and off for 2 seconds instead of 1 second. I tried to change the fuses to Ext Clock + 65 ms, and now I can't use the thing at all. Cannot enter programming mode. Any ideas?

body:
Sounds like you broke your fuses.

You may be able to enter programming mode by applying an external clock signal to the clock in pin (use another Arduino to generate it).  If that doesn't work then the only way to fix it is with a "High Voltage Programmer".

Nick Gammon has a very good tutorial here: http://www.gammon.com.au/forum/?id=12898


message:
Arduino on breadboard, and then soldered using a board made on Eagle but won't work

So I'm looking to create an arduino clone to mount on one of my robots. I started off making the arduino on a breadboard, using the instructions found on Arduino's own website and I succeeded. It works as well, I've checked it with the "blink" project.

I then drew the schematic in Eagle:
![schematic][1]

Next, I created a board and routed it, giving the following result:
![][2]

Finally, I transferred it onto a copper clad, soldered it, but it doesn't work. Tried pretty much everything I could think of but there seems to be something wrong and I cant work out what it is.

Can someone please help?

Hassan

[1]: https://i.stack.imgur.com/wdnvm.png
[2]: https://i.stack.imgur.com/aU1Xy.png

body:
I haven't worked out why it's "not working", but some comments on your PCB:

1. Your crystal is too far from the clock pins
2. Your crystal capacitors are most definitely too far from the crystal
3. There are no decoupling capacitors on your Vcc / AVcc pins

Your crystal should be right next to the pins on the chip that it is connected to, and the capacitors for it should be immediately next to that. The layout you have at the moment, if it actually works, will be radiating huge amounts of EMI and would immediately fail any emissions test you'd care to perform.

Without decoupling capacitors on the power pins the chip may not function properly.

**Edit: I have just found your main mistake**

You haven't linked the output of your regulator sub-circuit to Vcc. Power gets regulated but goes nowhere.

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

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


message:
I²C between 2 Arduinos sends additional receive event

I hooked up two Arduino Nanos with I²C, using 3 wires between GND <-> GND, A4 <-> A4, A5 <-> A5Ω and 1kΩ pull-up resistors on A4 & A5.

When I use the following code to communicate between them I get a weird empty receive event.

### master.cpp

<!-- language: c++ -->

 #include <Arduino.h>
 #include <Wire.h>

 #define SERIAL_BAUD 9600

 #define I2C_SLAVE_ADDRESS 8

 void setup () {
  Wire.begin();
  Serial.begin(SERIAL_BAUD);
 }

 void getFromState (unsigned char state) {
  Wire.beginTransmission(I2C_SLAVE_ADDRESS);
  Serial.print("s");
  Serial.print(Wire.write(state));
  Serial.print("e");
  Serial.print(Wire.endTransmission());
  delay(5000);
  Wire.requestFrom(I2C_SLAVE_ADDRESS, 2);
  int c = (unsigned char) Wire.read();
  Wire.flush();
  Serial.print("r");
  Serial.println(c);
  Wire.endTransmission();
 }

 void loop () {
  Serial.println("loop");
  getFromState(0);
  delay(10000);
  getFromState(1);
  delay(10000);
 }

### slave.cpp

<!-- language: c++ -->

 #include <Arduino.h>
 #include <Wire.h>

 #define SERIAL_BAUD 9600

 #define I2C_ADDRESS 8

 unsigned char state = 0;

 void requestEvent () {
  Serial.print("Request ");
  Serial.println(state);
  Wire.write(state);
 }

 void receiveEvent (int amount) {
  Serial.print("a");
  Serial.print(amount);
  Serial.print("r");
  state = (unsigned char) Wire.read();
  Serial.println(state);
 }

 void setup() {
  Serial.begin(SERIAL_BAUD);
  Wire.begin(I2C_ADDRESS);
  Wire.onRequest(requestEvent);
  Wire.onReceive(receiveEvent);
 }

 void loop() {
  delay(10);
 }

### Serial Output Master After 1.5 Loops

 loop
 s1e0r0
 s1e0r1
 loop
 s1e0r0
 s1e0

### Serial Output Slave After 1.5 Loops

 a1r0
 Request 0
 a0r255
 a1r1
 Request 0
 a0r255
 a1r0
 Request 0
 a0r255
 a1r1

### Question

Why is there an empty receive event `a0r255` after every request? Is that normal? Am I doing something wrong? Is this some sort of hardware issue?

EDIT: I opensourced this project [here](https://github.com/dodekeract/arduino-examples/tree/master/custom-i2c-device), take a look if you want to!

body:
Your code has several issues:

For the master:

 - Your I2C transactions should be quick and not delayed with `Serial.print()`s like in `getFromState()`
 - You requested 2 bytes from the slave but you are reading only one from the buffer. `Wire.flush()` flushes the *outgoing* buffer, not the receive buffer. Use `while (Wire.read() != -1);` instead.
 - Its also advised that you use `Wire.available()` to iterate through the receive buffer when `read()`ing; its how you check if anything was received at all and how many bytes were received.
 - After using `requestFrom()`, you shouldn't call `endTransmission()`. Its self-contained.

For the slave:

 - You should never call `Serial.print()` or `delay()` in `requestEvent()` or `receiveEvent()`; both functions are called from within ISRs and ISRs are meant to execute quickly and return.
 - You are requesting 2 bytes from the slave in your master code, whereas your slave's `requestEvent()` writes only one byte.
 - In `receiveEvent()`, again its best to use either `Wire.available()` to iterate through the RX buffer or you use the variable `amount`. This way, you read everything in the buffer; you can also flush the RX buffer like I showed you before.

Finally those delays are rather long; 10ms would do, if they are even needed at all.


body:
The main culprit that is causing your problem is the second

    Wire.endTransmission();

after your `requestFrom`.  That causes the previous `startTransmission()` to be repeated with no data in it - thus giving you a second `receiveEvent` call with no data.


message:
Troubleshooting duplicate libaries (Arduino motor shield and stepper motor)

I have tried a software. It work flawless on the first laptop in a fresh install arduino IDE environment with the libraries I imported.

However when I copy the exact same program over. I get lot of errors and tried to clean up some of the old libraries from earlier programs. Then rerun the compiler; got even more errors and I am not sure what to do except completely clean everything including older libraries that I may need to keep around for older programs.

My includes are as following:

<!-- language: c# -->

    #include <AccelStepper.h>
    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_MS_PWMServoDriver.h"

Error from the Arduino IDE from the second laptop is as following:

<!-- language: lang-none -->

    Arduino: 1.6.7 (Windows 10), Board: "Arduino/Genuino Uno"

    Invalid library found in C:\Users\B Family\Documents\Arduino\libraries\examples: C:\Users\B Family\Documents\Arduino\libraries\examples

    libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)'

    libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\libraries\Adafruit_Motor_Shield_V2_Library-master\utility/Adafruit_MS_PWMServoDriver.cpp:28: first defined here

    libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)'

    libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

    libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::setPWM(unsigned char, unsigned int, unsigned int)'

    libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

    libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::write8(unsigned char, unsigned char)'

    libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

    libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::reset()'

    libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

    libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::begin()'

    libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

    libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::read8(unsigned char)'

    libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

    libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::setPWMFreq(float)'

    libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Error compiling.

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

body:
The diagnostics tell you *exactly* what is wrong! You have multiple copies of the same library, probably because you installed it at different times from different places. The diagnostics even tell you which libraries are duplicates. Remove them and everything will work fine!

While we are at it: another source of duplicate definitions is badly written .h files that *define* (as opposed to only *declaring*) external symbols. Those you have to deal with as they happen, there is no global solution.


message:
Arduino Uno Constantly Resets with WiFi and 4 Relay Module

I am using an Arduino Uno with a 4 relay module (found here: http://www.amazon.com/JBtek-Channel-Module-Arduino-Raspberry/dp/B00KTEN3TM?ie=UTF8&psc=1&redirect=true&ref_=oh_aui_detailpage_o04_s00) and an Adafruit CC3000 WiFi breakout board.  However, once I connect the power source, the board just constantly cycles on and off, e.g. about 1 second per cycle.  Could this have to do with too much current being drawn? Or that the current output of the digital pins isn't enough for all of the relay inputs? I'm new with this, but I am sure all of the pins are appropriately connected.

EDIT: If I use the USB connector (5V 1A) instead of the external power supply, I can connect 1 or 2 of the relays without problem, but must do so AFTER the wifi has already connected to the network, otherwise the wifi chip will never connect.  Also, if I toggle the relays a few times, the wifi becomes unresponsive.  I suspect a current issue maybe?. Any ideas? Thanks!

body: It Will be a power issue you need to supply power direct to the relay modules VCC independent of the arduino, ensure the earths are connected and just use the digital outputs from the arduino to control the relays. Digital low normally switches the corresponding relay on.


message:
Resistor on SPI Chip Select Pin

I'm working on a modular CANBUS system for offroad racing. The idea right now is that the main Arduino (1284p at the moment) will be the only one connected to CANBUS, and other modules will have their own atmega's that will communicate with the master over I2C. They will not be physically on the same PCB, but will be physically within inches of each other. One module will have 8 [MAX31865][1] IC's for interfacing with RTD's. The 31865 is not compatible with 5V microcontrollers, which right now we planned on running the Atmega's at 5V. Since the IC's are SPI, they can all share a MOSI, MISO, and CLK bus, so only two channels of a hex converter. For the Chip Select pin, would it be acceptable to use a resistor to decrease the voltage instead of using an additional 8 channels of hex converting?

What would the upsides/downsides be of using an atmega running at 3.3v for the module with the MAX31865's and just using a hex converter on SDA/SCL for the I2C communication to the master? What atmega I use for this is flexible.

  [1]: https://datasheets.maximintegrated.com/en/ds/MAX31865.pdf

body:
> would it be acceptable to use a resistor to decrease the voltage

I don't see any big problem with using a voltage divider for chip select.

> What would the upsides/downsides be of using an atmega running at 3.3v for the module with the MAX31865's

At 3.3V you can only run at 13 MHz or less (so in practice, 8 MHz, unless you want to do a lot of fiddling around). This may or may not matter to you. At a lower voltage it uses less power which can be a plus, and you don't need to worry about level converters.

> and just using a hex converter on SDA/SCL for the I2C communication to the master?

Do you mean a level converter?


body:
> using a hex converter on SDA/SCL for the I2C communication to the master

I2C is not straight forward for level shifting.  The I/O pins operate in *open drain* mode. That is, they don't send out any voltage of their own, they just pull down (like a button) the signals pulled up by resistors.

To level shift you have to read the state of those lines and then replicate that open drain connection to the signals of a different voltage.

But that is not all of course. I2C is a bidirectional protocol on a single data line. That means that data goes in both directions on the data line, so your level shifter has to be able to work in both ways.

There are special I2C level shifter chips available that do that exact thing. Some people sell them on breakout boards if you google around.

But with all that said, if you run your I2C bus purely at 3.3V it should work quite happily with both 3.3V and 5V devices.  To do so you need to:

1. Use external pullup resistors (~3.3KΩ) to 3.3V
2. Disable the Arduino's idiotic use of the internal pullup resistors on the I2C pins (will need modification of the Wire library)

In short: It is possible to mix 3.3V and 5V I2C devices on a 3.3V I2C bus, but not on a 5V I2C bus.


message:
Two or More Arduinos Handshaking

research would show that there are numerous ways for two arduinos to talk to one another. But i was looking for a 'basic robust protocol' (..it doesn't sound basic ....I know!), to allow for two arduinos to talk to one another. The idea is , Arduino One(slave), is linked to a sensor and it reads data from the sensor and sends the data  to Arduino Two on 'request' of the data by Arduino Two(master). Arduino Two would have to 'request' for the data from Arduino One, before it can read the data, if its available. A popular method on most sites (e.g https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing/shaking-hands-part-1) is the use of the method below. I added a comment in search of clarity.

                  void establishContact()
                         {  //This while loop does baffle me as it suggests that
                            //while there is nothing in serial, send A???
                            while (Serial.available() <= 0)
                           {
                             Serial.println("A");   // send a capital A
                             delay(300);
                           }
                         }
 Now this method was used in handshaking between Arduino and processing. This method was called on the Arduino sketch. On the processing sketch, a method there just checks to see if 'A' was received. If it is, it reads in the data from serial, clears the serial buffer and  writes 'A' back to Serial. I tried using this method on both of my arduinos as i felt it was 'basic' enough, but it didn't work at all. Does anyone has a better idea on how my arduinos could handshake?.

body:
That while loop makes perfect sense.  It' basically nudging the other end repeatedly until it replies with something - anything.

It's like sitting next to someone and poking them in the ribs every 300ms until they respond to you. Once they have responded you can then react to that response - be that to run very fast or tell them your important news.

The idea of handshaking like that is all to do with synchronisation. It ensures that both ends are ready for communication at the same time.  Once synchronised you know, to a high probability, that what you are sending will be interpreted properly, and any replies you get back will be correct.

For basic communication between two Arduinos it's really not necessary.

The simplest call-and-response protocol involves Arduino A sending a single byte as a request and Arduino B replying with a single byte. It is up to you what those bytes represent, but ASCII letters for requests are ideal since they are understandable by a human, and numbers between 0 and 255 or -128 and +127 fit in to one byte (unsigned or signed respectively). Should you want bigger numbers being sent back then the reply will have to be delimited in some way. The simplest way of doing that is to format the response as ASCII data and send it with a CR and/or LF.

Something like:

    if (Serial.available()) {
        char command = Serial.read();
        switch (command) {
            case 'T':
                Serial.println(temperature);
                break;
            case 'P':
                Serial.println(pressure);
                break;
        }
    }

The master end then sends either 'T' or 'P' to request temperature or pressure. It then reads characters up to a line feed and stores them in a string which it can then convert into the desired numeric data type depending on what temperature and pressure are (integer or floating point).


message:
Why is my LED blinking?

I have this simple push button schematic:
[![enter image description here][1]][1]

The idea is that the LED is on as long as the button stays pushed, with the switch closed.

The code is below:

    int ledPin=10;
    int switchPin=5;

    void setup()

    {
      Serial.begin(9600);
      pinMode(switchPin, INPUT);
      pinMode(ledPin,OUTPUT);

    }
    void loop()

    {
      digitalWrite(ledPin,LOW);//DBG
      if (digitalRead(switchPin)==HIGH)
    {
     digitalWrite(ledPin,HIGH);//DBG
     delay(500);
    }
     if (digitalRead(switchPin)==LOW);
    {
    digitalWrite(ledPin,LOW);//DBG
    delay(200);
    }
    }
As I keep the button pressed, **the LED blinks regularly**, instead of **staying on**. Why?
I have tried using a capacitor between the switch and switchPin, with no change.

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

body:
The beginning of your code in the loop:

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

    void loop()  {
      digitalWrite(ledPin,LOW); //remove this line here
      if (digitalRead(switchPin)==HIGH)
    {
         digitalWrite(ledPin,HIGH);//DBG
         delay(500);
    }
     if (digitalRead(switchPin)==LOW);
     {
          digitalWrite(ledPin,LOW);//DBG
           delay(200);
         }
    }

Before your first `if(digital read(switch pin) == HIGH)`  you turn the LED off, and then you have a delay, which gives the blinking effect, remove that and it will not blink.


message:
Do arduino librarys require the arduino to be connected to a computer?

The title pretty much explains my question. If I'm using a library for example one for an accelerometer does the arduino need to be connected to my computer because it's using a library? Or is the library uploaded to the arduino and there for can run with out a computer connected?

body:
No.  Arduino libraries (strictly speaking only the utilized parts) are permanently built-in parts of your compiled sketch.  Effectively they are "statically linked" unlike the situation with modern RAM-based computer operating systems where compiled dynamic link library code may be separately loaded into memory for a program to call at runtime.

(This isn't even really a design choice, as the basic AVR Arduino's cannot load new program code into executable memory at runtime anyway - except by reflashing themselves like the bootloader does, which would be a bit slow compared to normal dynamic linking)

Of course if you have a library which is intended to perform *communication* with a computer, then that connection would probably be required for it to fully operate.


message:
Integer goes garbage after iteration. struct pointer manipulation messed up other variables in memory

I'm writing a [library][1] for Charlieplexed LED display (trying to write a common one actually). The library is working quite fine. In my arduino sketch, I'm using an integer to keep track of the LED, currently on. The integer value increases with time and the LED(s) glow one by one. The problem is, after couple of iterations, this integer value just goes out of chart (in Serial monitor, it has garbage values).

    MatrixCharlieplex mch(Pins, 5, MXCHARLIE_CA); // instance of Class
    int i = 0, j = 0;
    boolean busy = false;
    unsigned long time;
    void setup() {
      //Serial.begin(9600);
      time=millis();
    }
    void loop() {
      if(millis() - time > 100){ // runs every 100 ms interval // corrected from (millis() > (time + 100))
        time=millis();
        blink();
      }
    }
    void blink(){
      if(!busy){
        busy = true;
        //Serial.print("i:\t");
        //Serial.println(i);
        //Serial.print("Node:\t");
        //Serial.println(i+1);
        mch.TurnOn(i+1);
        increase();
        busy = false;
      }
    }
    void increase(){
      i = (++i % 20); // resets after every 20 intervals
    }

Output:

    i: 16
    Node: 17
    i: 17
    Node: 18
    i: 18
    Node: 19
    i: 19
    Node: 20
    i:16 <-- Stopped working here. it should be "i:    0" & "Node:    1"
     16
    Node: 17
     17
    Node: 18
     18
    Node: 19
     19
    Node: 20
    16
     16
    Node: 17
     17
    Node: 18
     18
    Node: 19
     19
    Node: 20

The sketch can also be found [here][2]

***Update:***
There were no hardware-fault. The problem lies in the struct variable declaration as pointers.updated the question & posted answer. The files in the github links have also been updated.

  [1]: https://github.com/turn-a-round/Arduino-Charlieplexing
  [2]: https://github.com/turn-a-round/Arduino-Charlieplexing/tree/master/libraries/Arduino-Charlieplexing/examples/ArduinoMatrixCharlieplex

body:
If you have a Charliplexing board like mine (or even if you made your own) the problem could be electrical. If you turn on a lot of LEDs you may exceed the current consumption allowed and then the processor hangs or resets.

I suggest current-limiting resistors like this:

[![Charliplexing][1]][1]

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


body:
First thing to do is find out whether your problem is electrical or not.
This can be done by removing the electrical parts not crucial to run the code.
If the problem is code related try using another board to eliminate some hardware malfunction on your board.
Doing these steps will give you some insight on the root cause of the problem.


body:
After much trial and error effort, I've found the solution.

There was no problem in the hardware side (I ran the sketch with serial monitor after detaching the LED-matrix and all non-crutial hardwares. Thanks @jantje and @NickGammon fot the tips).

Apparently Arduino is not capable of handling **pointers** in advanced ***Oops*** fashion. The library itself used it heavily, specially **"struct pointers"** as function parameters and as return types (Arduino messed up these pointer values with other variable declarations in memory). After removing those pointers from the code and replace them with normal variables, the code runs well.

    // correct definition
    typedef struct {
        uint8_t vcc;
        uint8_t gnd;
    } DiodeNode;

    // wrong implementation
    DiodeNode* node = new DiodeNode();
    node->vcc = x;
    node->gnd = y;

    // correct implementation
    DiodeNode node = (DiodeNode){x, y};
    // or
    DiodeNode node;
    node.vcc = x;
    node.gnd = y;
    return node; // from functions etc.


message:
MQ4 gas sensor is not working with Arduino UNO

I am trying to detect LPG leakage by using MQ4 gas sensor.
I have made this circuit

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

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

My Arduino code is

    int sensorValue;

    void setup()
    {
      Serial.begin(9600);      // sets the serial port to 9600
    }

    void loop()
    {
      sensorValue = analogRead(0);
      Serial.println(sensorValue, DEC);
      delay(100);
    }

On my serial monitor, I am getting values like

    307
    277
    289
    282
    283
    283
    260
    248
    265
    285
    308
    278
    278
    315
    321
    316
    327
These values are not getting change even after putting sensor near gas lighter. Did I made any mistake in circuit or this sensor could be faulty ? Any help is appriciated.

body:
That is what I would expect to see with one of these sensors.

I'm not sure on the wiring, I think you _may_ be wrong.  Have a read of http://playground.arduino.cc/Main/MQGasSensors#readdatasheet and see if you agree.

Did you leave the sensor to warm up?  It takes a few minutes (from memory) and until its warm it won't give you a proper reading.

An MQ4 should be able to detect Methane, butane and propane, so was your lighter using on of these gasses?  When it does detect the target gas, the number will go up, and stay up for a while.

Another thing you can try is blowing on the sensor, the results will vary depending on what you have been eating, but it should shift one way or another.

If it still doesn't work then buzz out your connections, just to triple check, and re-read the manual.


message:
OLED with arduino?

I recently bought a 0.96" Serial OLED Screen. I am not very experienced with this. I'm trying to display some text with the Arduino Uno. I installed the adafruit SSD1306 and GFX libraries but no luck. I've looked for tutorials for similar screens, but my screen has extra pins that others don't.

Mine has:
`CS` `DC` `RST` `D1` `D0` `VCC` `GND`,
others only have 4.

I don't know what each pin should be connected to. Does any one know how to get this to work? Is there a different library that I could use with this screen?

body:
Yes, certain OLED screens do have different pinouts. For yours, the following would be your OLED's pinouts.

    OLED ---- Arduino

    D0-----------10

    D1-----------9

    RST----------13

    DC-----------11

    VCC----------5V

    GND----------GND

The `CS` pin does not need to be plugged in.

As for the code, you can use [this include][1] from Smart Prototyping as an extra file, then have some simple code in your `loop` portion:

    void loop()
    {

    LED_P8x16Str(23,0,"here is");

    LED_P8x16Str(40,2,"example");

    LED_P8x16Str(20,4,"text");

    }

  [1]: http://smart-prototyping.com/image/data/2_components/Arduino/100952 OLED 0.96inch 12864 display module blue/OELD.txt


message:
Using an Arduino Weight Sensor, it fails to satisfy a while loop and I can't firgure out why

/*

     This example code uses bogde's excellent library: https://github.com/bogde/HX711
     bogde's library is released under a GNU GENERAL PUBLIC LICENSE

     The HX711 does one thing well: read load cells. The breakout board is compatible with any wheat-stone bridge
     based load cell which should allow a user to measure everything from a few grams to tens of tons.
     Arduino pin 2 -> HX711 CLK
     3 -> DAT
     5V -> VCC
     GND -> GND

     The HX711 board can be powered from 2.7V to 5V so the Arduino 5V power should be fine.

    */

    #include "HX711.h"
    #include <Servo.h>

    float calibration_factor = -4050.0;

    #define DOUT  3
    #define CLK  2
    Servo myServo;

    HX711 scale(DOUT, CLK);

    void setup() {
     Serial.begin(9600);
     Serial.println("Food Test");
     scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0
     Serial.println("Readings:");
     myServo.attach(9);
     long zero_factor = scale.read_average(); //Get a baseline reading
     Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
     Serial.println(zero_factor);
    }

    void loop() {
     scale.set_scale(calibration_factor); //Adjust to this calibration factor

     if ((scale.get_units(), 1) <= 5) {
      Serial.print("whoa that is light, more food needed");
      myServo.write(90); // Open food hatch
      delay(2000);
      myServo.write(0);

      do {
       // Do nothing
       Serial.println("It is working somewhat");
       Serial.println(scale.get_units(), 1);
       delay(1000);
       // When weight exceeds 5 it should break out of this loop and go below
      } while ((scale.get_units(), 1) < 10);

      Serial.print("Closing the Hatch");
      myServo.write(0); // close food hatch
     } else {
      Serial.print("Something Went Wrong");
     }
    }

Output:

    It is working somewhat
    10.6
    It is working somewhat
    10.9
    It is working somewhat
    10.5
    It is working somewhat
    6.9
    It is working somewhat
    -0.8

I will try to explain the problem as best as I can. I am using a scale library and the `scale.get_units()`,x returns a value as a float. The whole point is that a servo will open and stay open until a specified weight of 10lbs is reached. As seen in the do, while loop that's what I specify. It jumps into the if loop and then into the do while loop, and it continually prints out values of readings which is what I want. BUT, even when I reach over 10lbs it will not break out of the Do/while loop, essentially it never satisfies the while condition and I have no clue why. It prints out values over 10 but keeps reading values. I know the format isn't the best but any help would be greatly appreciated!!

body:
It looks to me like you have an extra bracket in there that you don't want.

At the moment your structure is:

    if {
        do {
        }
    } while...

As it stands your sketch won't compile. The unbalanced brackets prevent it.  Remove the excess one so that the `while` is associated with the `do` not the `if` and report back.

----
# Part II

The main cause of your problem is the strange bit of code you have in your `if`s and `while`s.

    if ((scale.get_units(), 1) <= 5) {

    ....

    } while ((scale.get_units(), 1) < 10);

In both of those you have the bit `(scale.get_units(), 1)` which is completely meaningless.  The comma operator in C calls (or evaluates) both sides, and then returns the right hand side.  So that calls `scale.get_units()` and then returns 1.  1 has always been, and will always be, less than 10, so the `while` never ends.

I don't know what you were hoping to achieve by having the `, 1` in there, but you should delete it from every place you have it.


message:
Why is the result shorter than expected when I do longString.toCharArray(bigCharArr, longLength)?

I'm running this on a Particle Photon, but I think the issue is just me failing at C++. I'm trying to retrieve some JSON data from a HTTP API, convert it to JSON, and then extract a few values for display on the screen. I convert the String to a char array for the JSON parser, but it seems to only grab the first 10 characters of the String (unless I manually set length to a number shorter than 10), and then of course, the JSON parser fails.

Here's the relevant bit of code:

    int str_len = response.body.length() + 1;
    tft.print("Length: "); tft.println(str_len);
    char char_array[str_len];
    response.body.toCharArray(char_array, str_len);

`response.body` is a big JSON string, but `char_array` is always just the first 10 characters of it: `{"metadata`

Another thing I noticed just now that might be related, `str_len` is usually reported to be ~500 characters, but when I hit the same URL in a browser it ends up more like ~1500 characters. Neither are pretty-printed, so I'm not sure what the discrepancy is.

Here's my complete code, except I removed the base64'd username and password from the Authorization header:

    #include "HttpClient/HttpClient.h"
    #include "SparkJson/SparkJson.h"
    #include "Adafruit_mfGFX/Adafruit_mfGFX.h"
    #include "Adafruit_SSD1351_Photon/Adafruit_SSD1351_Photon.h"

    // OLED - You can use any (4 or) 5 pins
    #define sclk A3
    #define mosi A5
    #define dc   D7
    #define cs   A2
    #define rst  D5

    // Color definitions
    #define BLACK           0x0000
    #define BLUE            0x001F
    #define RED             0xF800
    #define GREEN           0x07E0
    #define CYAN            0x07FF
    #define MAGENTA         0xF81F
    #define YELLOW          0xFFE0
    #define WHITE           0xFFFF

    // Option 1: Hardware SPI - uses some analog pins, but much faster
    Adafruit_SSD1351 tft = Adafruit_SSD1351(cs, dc, rst);

    // Option 2: Software SPI - use any pins but a little slower
    //Adafruit_SSD1351 tft = Adafruit_SSD1351(cs, dc, mosi, sclk, rst);

    HttpClient http;

    // Headers currently need to be set at init, useful for API keys etc.
    http_header_t headers[] = {
        //  { "Content-Type", "application/json" },
        { "Authorization", "Basic <snip>" }, // base64encode(username:password)
        { "Accept" , "application/json" },
        { NULL, NULL } // NOTE: Always terminate headers will NULL
    };

    http_request_t request;
    http_response_t response;

    void setup(void) {

        tft.begin();

        tft.fillScreen(BLACK);
        tft.setCursor(0,0);
        tft.setTextSize(0);
        tft.setTextColor(WHITE);

        // http://twcservice.mybluemix.net/api/weather/v2/observations/current?units=e&geocode=40.0388067,-84.3428471&language=en-US
        request.hostname = "twcservice.mybluemix.net";
        request.port = 80;
        request.path = "/api/weather/v2/observations/current?units=e&geocode=40.0388067,-84.3428471&language=en-US";
        //request.body = "{\"key\":\"value\"}";
        http.get(request, response, headers);

        tft.print("Status: ");
        tft.println(response.status);

        //tft.println("Response Body: ");
        //tft.println(response.body);

        int str_len = response.body.length() + 1;
        tft.print("Length: "); tft.println(str_len);
        char char_array[str_len];
        response.body.toCharArray(char_array, str_len);

        DynamicJsonBuffer jsonBuffer;
        JsonObject& root = jsonBuffer.parseObject(char_array);

        if (root.success()) {
            tft.print("Current Temperature: ");
            const char* temp = root["observation"]["imperial"]["temp"];
            tft.println(temp);
        } else {
            tft.setTextColor(RED);
            tft.println("parseObject() failed");

            tft.setTextColor(GREEN);
            uint32_t freemem = System.freeMemory();
            tft.print("Free memory: ");
            tft.print(freemem/1024);
            tft.println("k");

            tft.setTextColor(WHITE);
            tft.println(char_array);

            tft.setTextColor(CYAN);
            tft.println(response.body);
        }
    }

    void loop() {

    }

The actual printout on the screen is smething like

    Status: 200
    Length: 501
    parseObject() failed
    Free memory: 59k
    {"metadata
    {"metadata":{"language":"en-US","transaction_id":"1460309558940:-660053703","version":"1","latitude":40.04,"longitude":-84.34,"units":"e","expire_time_gmt":1460310025,"status_code":200},"observation":{"class":"observation","expire_

Finally, here's an example of the JSON response I'm trying to parse:

    {"metadata":{"language":"en-US","transaction_id":"1460309558940:-660053703","version":"1","latitude":40.04,"longitude":-84.34,"units":"e","expire_time_gmt":1460310025,"status_code":200},"observation":{"class":"observation","expire_time_gmt":1460310025,"obs_time":1460307900,"obs_time_local":"2016-04-10T13:05:00-0400","wdir":160,"icon_code":26,"icon_extd":2690,"sunrise":"2016-04-10T07:06:23-0400","sunset":"2016-04-10T20:11:13-0400","day_ind":"D","uv_index":3,"uv_warning":0,"wxman":"wx4400","obs_qualifier_code":null,"ptend_code":2,"dow":"Sunday","wdir_cardinal":"SSE","uv_desc":"Moderate","phrase_12char":"Cloudy/Wind","phrase_22char":"Cloudy/Wind","phrase_32char":"Cloudy/Wind","ptend_desc":"Falling","sky_cover":"Cloudy","clds":"OVC","obs_qualifier_severity":null,"vocal_key":"OT48:OX2690","imperial":{"wspd":20,"gust":24,"vis":10.000,"mslp":1018.7,"altimeter":30.09,"temp":48,"dewpt":27,"rh":43,"wc":41,"hi":48,"temp_change_24hour":11,"temp_max_24hour":44,"temp_min_24hour":27,"pchange":-0.10,"feels_like":41,"snow_1hour":0.0,"snow_6hour":0.0,"snow_24hour":0.0,"snow_mtd":1.2,"snow_season":21.3,"snow_ytd":21.3,"snow_2day":0.7,"snow_3day":0.8,"snow_7day":0.9,"ceiling":7400,"precip_1hour":0.00,"precip_6hour":0.00,"precip_24hour":0.00,"precip_mtd":1.10,"precip_ytd":11.76,"precip_2day":0.29,"precip_3day":0.30,"precip_7day":0.96,"obs_qualifier_100char":null,"obs_qualifier_50char":null,"obs_qualifier_32char":null}}}

Any idea what's going on?

body:
It turns out that the HttpClient library has a fixed response length limit of 1024 bytes and whatever it was doing after it hit that limit is what caused all of the trouble.

Forking the library and increasing the limit as recommended at https://community.particle.io/t/issues-with-string-char-array-length-json-parsing/21980 solved the issue.


message:
voltage output at digital pins vs. load

I am trying to convert the signal from digital pin 2 on my Uno to 3.3V.  I set up a voltage divider with 3 x 1000 ohm resistors.  When connected to ground and 5V the divider circuit generates 3.3V correctly, with a calculated input current of 1.7mA.  However I connect it to a digital pin, the digital pin voltage drops from 4.8V to .37V.  I thought the digital pins were to support 40mA, I was assuming 40mA at the 5V supply voltage.  Is my Uno malfunctioning?

Thanks

body: Just figured out I didn't have the pin mode set, it works fine now, thanks.


message:
Arduino OOP and [this] keyword

Lets say I have a sketch called **mysketch.ino** with these contents:

    String globalString = "ThisisGlobal";
    void setup(){}
    void loop(){}

How can I pass **THIS** sketch `mysketch.ino` as an object or its reference to a `.h` file named
`StringChanger.h` with the following contents, so that `StringChanger.h` can change somevariables belonging to `mysketch.ino`.

    class StringChanger{
       template <typename T> // or type of mySketch.ino i don't know what i'm doing
       void changeString(T t) {  //a Reference Or Object Or Whatever
          t.globalString = "GotYouAndChangedYou";
       }
    }

I wan't to have simple usage in the `mySketch.ino`.
For instance:

    #include "StringChanger.h"

    StringChanger change(**this**);  // perhaps default empty constructor here

    String globalString = "ThisisGlobal";

    void setup(){
        change.changeString(); // perhaps pass reference to **this** here
    }
    void loop(){}

How can I accomplish this (give a class an object so that it can change some value of that object) in general and not neccesarily in this context.
Errors I currently get:

    invalid use of 'this' in non-member function
    invalid use of 'this' at top level.

body:
A sketch isn't an object. It is merely a collection of variables, functions and, of course, classes.

Your example seems to be trying to make things incredibly complex when they don't need to be.

There are a number of ways of referencing things in one file from another - whether or not they are in a class.  The simplest is to use the `extern` keyword.  This is used in a file where you want to reference a variable or function that is defined in the global scope of another file. It says "This variable is global, but it's defined somewhere else."

    // Sketch
    String myString = "foo";

    // Library
    extern String myString;
    // ... later on ...
    myString = "bar";

Of course, that means that the name of the variable is fixed and cannot change.  So you can pass the variable to whatever it is you want to use that variable in.  That could be as simple as passing it to your "changer" function:

    // Sketch
    String myString = "foo";
    StringChanger change;
    // ... later ...
    change.changeString(myString);

    // Library
    class StringChanger {
        public:
            void changeString(String &stringToChange) {
                stringToChange = "bar";
            }
    };

If you want to "tie" the variable to the class so you don't have to pass it each time you could pass it to the constructor and have the class remember it:

    // Sketch
    String myString = "foo";
    StringChanger change(myString);
    // ... later ...
    change.changeString();

    // Library
    class StringChanger {
        private:
            String *_string;
        public:
            StringChanger(String &string) {
                _string = &string;
            }
            void changeString() {
                *_string = "bar";
            }
    }

And there's a myriad of other ways of doing it.


message:
Managing 80 ~ 90 accelerometers with Arduino

If one were to want to keep track of data from 80 - 90 accelerometers using arduino, what would be the best way to go about this challenge?

body:
1) Use the I2C address select inputs as an "enable".  If you run out of I/Os before running out of bus time, drive the enables from an I/O expandander. If your accelerometers are SPI, drive or use the expander to drive the chip selects.

2) Use a tree of slave MCUs (Arduino or otherwise) reading a number of accelerometers, extracting and batching the useful data, and reporting only that upstream to a master.  Probably use whichever of I2C or SPI your accelerometers are not using (SPI can be much faster, so hopefully that).

Some accelerometer / gyro parts have an on-board processor which you may be able to program to do some of the data extraction for you.

You could also consider using an FPGA to collect the data.  A commonly available one with enough I/O pins to have a dedicated connection to each accelerometer (and so read them all in parallel) would probably also have the internal resources to implement an Arduino-class soft core processor, if not better.


message:
Controlling HC-05 from a sketch

Hi I am making a sketch and circuit with a HC-05 BT receiver to upload sketches via Bluetooth to my Uno.  This requires giving AT commands from the sketch.  I would like to see the response from the HC-05 but so far I haven't got it to work.  I want to view the response via the standard serial connection and serial monitor.  The commands from the sketch are not being recognized by the HC-05 and I would like to see the HC-05 response to troubleshoot it.

If you have a minute would you mind giving me a tip?  I would greatly appreciate it.  See the ArdProgramModeOn() and Off functions at the end.

Thanks

int ATModePin = 2;  // pin for HC-05 AT comand mode
int HC05powerPin = 3;  // pin for powering HC-05 when high
char btserialrx;  // data through from bt connection
char myChar; // data through serial port connection
#define rxPin 8 // HC-05 bt serial pin
#define txPin 9 // HC-05 bt serial pin

#include <SoftwareSerial.h>
SoftwareSerial btSerial(rxPin, txPin); // RX, TX

void setup() {
  pinMode(ATModePin, OUTPUT);
  pinMode(HC05powerPin, OUTPUT);
  pinMode(5, OUTPUT);
  Serial.begin(9600);
  btSerial.begin(115200);

  digitalWrite(HC05powerPin, HIGH);
  delay(2000);
  }

void loop() {

  while (btSerial.available()) {
    btserialrx = btSerial.read();
  }

  if(btserialrx == '1'){  // change to upload / reset mode
    Serial.println("switching to upload mode");
    ATModeOn();
    ArdProgramModeOn();
    ATModeOff();
    btserialrx = '0';
  }
  else if (btserialrx == '2'){  // change to normal mode
    Serial.println("switching to normal mode");
    ATModeOn();
    ArdProgramModeOn();
    ATModeOff();
    btserialrx = '0';
  }
}

void ATModeOn(){  // reset HC-05 and change HC-05 to AT Command Mode
  digitalWrite(5, HIGH);
  digitalWrite(ATModePin, HIGH); // AT command mode on upon reset
  delay(2000);
  digitalWrite(HC05powerPin, LOW); // hc-05 off
  delay(2000);
  digitalWrite(HC05powerPin, HIGH); // hc-05 on
  delay(2000);
}

void ATModeOff(){  // reset HC-05 and return HC-05 to std. operation
  digitalWrite(5, LOW);
  digitalWrite(ATModePin, LOW); // AT command mode off upon reset
  delay(2000);
  digitalWrite(HC05powerPin, LOW); // hc-05 off
  delay(2000);
  digitalWrite(HC05powerPin, HIGH); // hc-05 on
  delay(2000);
}

void ArdProgramModeOn(){
  btSerial.println("AT");
  delay(1000);
  btSerial.println("AT+POLAR=1,0");  // Arduino reset mode upon HC-05 connection for programming
  delay(1000);
  btSerial.println("AT+POLAR?");  // Arduino reset mode upon HC-05 connection for programming
  delay(2000);
  while (btSerial.available()) {  // Show responses from HC-05
    myChar = btSerial.read();
    Serial.print(myChar);
  }
  delay(4000);
}

void ArdProgramModeOff(){
  btSerial.println("AT");
  delay(1000);
  btSerial.println("AT+POLAR=1,1");  // Arduino normal mode no reset upon HC-05 conection
  delay(1000);
  btSerial.println("AT+POLAR?");  // Arduino reset mode upon HC-05 connection for programming
  delay(2000);
  while (btSerial.available()) {  // Show responses from HC-05
    myChar = btSerial.read();
    Serial.print(myChar);
  }
  delay(4000);
}

body:
Unless you've manually set the btSerial speed, you need to be at the default for AT commands which is 38400 -> btSerial.begin(38400);

If you want to read regular Serial communication, you'll need to monitor 9600 -> btSerial.begin(9600);

If you are unable to to send commands, I feel as if you wouldn't have changed the default speeds.

I used this link as a reference with my project: [Modify The HC-05 Bluetooth Module Defaults Using AT Commands][1]

Lastly, you didn't mention whether or not you soldered a jumper wire to PIN 32 for your ArdProgramOff/On. Another reference for you as well: [DIY Arduino Bluetooth Programming Shield][2]

Hope my answer helps! Good luck!

  [1]: http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/?ALLSTEPS
  [2]: http://makezine.com/projects/diy-arduino-bluetooth-programming-shield/


message:
Where can I find a hardware manual (or documentation) for Arduino Uno & ATMega328P?

Where can I find a hardware manual (documentation or a book) for Arduino board?

As far as I know, all hardware details are dispersed (or scatter) in different tutorials.

body:
The Arduino Uno is little more than an ATmega328P microcontroller. In
most cases you will be interested by the documentation of the
microcontroller itself. Anyway, here are both:

* The [Arduino Uno product page](http://www.arduino.cc/en/Main/ArduinoBoardUno) contains the most basic specs, as well as links to
    * the [board schematic](http://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf)
    * the [pin mapping](http://www.arduino.cc/en/Hacking/PinMapping168), but see below for a nicer alternative
* the [ATmega328P product page](https://www.microchip.com/en-us/product/ATmega328P) links to
    * the [ATmega328P family datasheet](https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf), a 650 page authoritative document
    * the [ATmega328P Automotive - Complete Datasheet](https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf), specific to the Uno's chip.
    * the [AVR instruction set manual](https://ww1.microchip.com/downloads/en/DeviceDoc/AVR-InstructionSet-Manual-DS40002198.pdf), for those who want to play with assembly
    * many application notes discussing specific uses of some peripherals

Alberto (aka PighiXXX) has published nicer versions of the [Arduino Uno
pinout](https://upload.wikimedia.org/wikipedia/commons/c/c9/Pinout_of_ARDUINO_Board_and_ATMega328PU.svg):

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

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


body:
For the hardware part, you can refer to the schematic. It shows all the components so you can find their datasheets for detailed study.

[UNO schematic][1]

But to me, if you're just using the board but not designing your own board or writing libraries for the board, I don't think this is necessary. Stick to application level or IO-level and only really dig into the hardware when you're blocked when doing things like using all timers, low-power mode, interrupt with Serial...

  [1]: http://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf


message:
Are there any advantages to Wifi shields as opposed to a Yun?

I have an Arduino Uno and I have a remote sensing project for which I need Wifi connectivity. After doing research, I've found that I have 2 options:

 1. Buy a WiFi shield for my existing Uno
 2. Buy an Arduino Yun with built-in WiFi

Looking at costs, I found that a WiFi shield costs more than double what it costs to buy a Yun, so it would seem to me that the best option is the Yun as I'd save some cash and get a more capable board. However, I can't help but think I'm missing something.

What are the advantages of an Uno plus Wifi shield as opposed to a Yun?

body:
There's a number of things to consider that could sway your choice one way or another:

# Power consumption

The Uno is a small low-power chip to which you add WiFi. The Yun is an Arduino Leonardo with a WiFi router (like you have on your desk) strapped to the back of it.  The Yun will therefore consume considerably more power than the Uno.

# Boot time

The Uno takes about 1 second to boot up - faster (instant) if you remove the bootloader and program it direct with a programmer.  The Yun takes minutes to boot.

# Stability

The Uno is a solid state single item. The Yun has an entire operating system with filesystems and things.  It's far more likely that the Yun will corrupt itself through power loss than an Uno will get struck by a stray neutrino.

# Cost

Yes, the Yun is cheaper. But is cheap always good?

# Remote-ability

The Yun can be completely reprogrammed remotely. A new sketch can be uploaded to the Leonardo portion of it without you even having to be in the same country. The same can't be said for the Uno.

# Power

The Linux portion of the Yun is considerably more powerful than any normal Arduino.


body:
First of all yun is not the same as uno + wifi shield. yun is more like a linux pcc with wifi and a lenoardo.
If you are asking for your options there are more options. For what you want I would go for a ESP8266. Again there are 2 options here:

 - uno + ESP8266 (as a wifi shield)
 - ESP8266 (as a dev board)

I think it is pretty obvious that the ESP8266 (as a dev board) is the most cost effective.
You can program the ESP8266 just like a uno in the arduino IDE.
So I would advice to take that board.


body:
There aren't just two options.

There are also [Dragino](http://www.dragino.com/products/yunshield/item/105-yun-shield-v2-4.html) and [Iduino](http://www.geeetech.com/wiki/index.php/Iduino_Yun_Shield) Yun shields, which are (usually) slightly cheaper than an Arduino Yun. These can be plugged into Leonardo/Uno base boards.

Whereas an Uno or Leonardo requires about 6-7v from the power supply, a Yun shield requires 9-12v (due to the Atheros chip drawing a bit extra).

There is also the [Tian](http://www.arduino.org/products/boards/arduino-tian), which is the Yun's successor (but at higher cost).

If you're willing to look further afield than Arduino only, you might want to consider a BeagleBone Black (which works out slightly cheaper in terms of cost/feature).


message:
Resetting millis() and micros()

I want to know how much time has elapsed since a certain event, and I do not want to use any external timers. It seems logical to reset an internal timer whenever the event occurs (using an interrupt). Unfortunately, as far as I can tell, `millis()` and `micros()` cannot be manually reset. Obviously, I could save a time stamp whenever the event occurs; however, I want to avoid overflow problems (`micros()` will overflow every ~71 minutes, and `millis()` will overflow every ~50 days).

Is there a way to manually reset these built-in counters? If not, how can I manage the overflow?

body:
`millis()` and `micros()` overflow periodically. However, this is not a
problem: as long as you [compare durations instead of
timestamps](https://arduino.stackexchange.com/questions/12587) you can
forget about the overflows.

The liked answer also gives the trick for resetting `millis()`. Can be
handy for testing purposes, but _you do not need this_ to handle the
millis() rollover problem. Notice that there is no clean way to reset
`micros()`: it relies on a `static` variable, i.e. a variable private to
the file defining it.


body:
Overflow is never really an issue if you always calculate time difference. (Unless the time difference is more that 50 days.)

    unsigned long previousTime = millis();
    ... wait for some event to happen ...
    unsigned long elapsedTime =  millis() - previousTime;

Even if `previousTime` was before the overflow, and `millis()` is after the overflow (so essentially `millis()`<`previousTime`), `elapsedTime` will still be the correct value.

This is because the calculation itself will also overflow. Since `millis()`<`previousTime`, the result would be negative, but the type of the variable is `unsigned`, so it wraps around. I hope that makes sense.

Just don't ever do something like `if( millis() > (previousTime+1000) )`

If you still want to reset millis, you can use the following:

    extern volatile unsigned long timer0_millis;
    unsigned long new_value = 0;

    void setup(){
      //Setup stuff
    }

    void loop(){
      //Do stuff
      //--------

      //Change Millis
      setMillis(new_value);
    }

    void setMillis(unsigned long new_millis){
      uint8_t oldSREG = SREG;
      cli();
      timer0_millis = new_millis;
      SREG = oldSREG;
    }


body:
> It seems logical to reset an internal timer whenever the event occurs (using an interrupt).

No it doesn't. You don't reset your clock to 00:00 when you put a cake in the oven do you?

What you do is note the time. Then periodically you subtract the start time from the current time, giving you the elapsed time. When time is up, you remove the cake from the oven.

---

Think about it for a minute. What if you wanted to time **two** events? Setting millis back to zero would hardly work then, would it? Setting it to zero for the second event would corrupt your timing for the first event.

However *noting the time* each one starts, and comparing the time *now* to the start time, will work for any number of events.

---

For more details see my post about [millis() overflow ... a bad thing?](http://www.gammon.com.au/forum/?id=12127)


message:
Problem controlling a Stepper motor with AccelStepper

I have an Arduino connected to a stepper motor with an Easy Driver as follows:
[![enter image description here][1]][1]

I am controlling the position of the stepper motor using the Serial. This is my code:

    #include <AccelStepper.h>
    AccelStepper stepper(1, 9, 8);

    void setup()
    {
      Serial.begin(9600);
      stepper.setMaxSpeed(10000);
      stepper.setAcceleration(5000);
    }

    void loop()
    {
      char c;
      if(Serial.available())
      {
       int steps = Serial.parseInt();
       Serial.print(steps);
       stepper.moveTo(steps);

      }
      stepper.run();
    }

The code works well but I'm facing a problem, when I set a high position value, it starts turning in the opposite direction, like if there was a limit on the steps. Does anyone know why it starts turning to the opposite direction?

I have tried to solve this problem by using:

    if (stepper1.distanceToGo() == 0)
             {
                stepper1.setCurrentPosition(0);
             }

so I can set lower values to the serial. But the problem goes back again when the value goes up to the power of 6 (like 1000000).

Any idea?

Thanks!

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

body: Ints on vanilla Arduinos are 16 bits, and signed, which means they hold values from -2^15 to +2^15-1, so of course you cannot assign 10^6 to one of them. Use unsigned long (4 bytes), or, better yet, specify the length explicitly by using uint32_t.