message:
Where can I get a high-quality ADC (audio digitizer) for Arduino?

Is there a high-quality (32 bit/96,000 kbps) digitizer for Arduino?

Does anybody know where I can find the best options for this?

body:
You are going to need a bigger board.

(96000000 samples/second) * (32 bits / sample) ~= [3 Gigabits/second][1]

A poor little Arduino Uno only runs at 20MHz and can process 8 bits bytes at a time, so even if it could somehow read and store a byte every cycle, it would still be orders of magnitude too slow for your purposes.

While I guess is might be possible to build a shield with an ultra high speed ADC and on board memory to directly store the captures samples to, you probably would bother making it since the Arduino would struggle to do anything useful with the captured data even after the fact.

The highest quality audio recording shield for Arduino I've seen is a modified [Wav Shield][2] that can record 8-bit mono files at 44,100 samples per second using the [waverp library][3].

  [1]: http://www.wolframalpha.com/input/?i=(96000000 sample/second) * (32 bits / sample)
  [2]: http://www.adafruit.com/products/94?&main_page=product_info&cPath=17_21&products_id=94
  [3]: https://blog.adafruit.com/2009/07/07/waverp-an-arduino-library-for-recording-and-playing-wave-files-on-the-adafruit-wave-shield/


sender: user

sender: assistant

body:
 think 96000kps was most likely a typo. 96ksps or 96000sps is more likely since the title specifies audio. Still a little too much for an Arduino though. You need a chip with I2S and a CODEC chip.

I am working on a project at the moment interfacing a PIC32 to a CODEC for CD quality audio reproduction. The codec I am using (PCM1774) is DAC only, but you can get CODECs in many combinations of ADC and DAC with different numbers of channels in each.

I2S is very similar to SPI but needs some extra facilities that not all chips can provide. Things like:

* High speed flexible base clock at (for example) 256x the sample frequency
* Left/Right framing clock derived from base clock
* DMA for smooth transfer of data

I don't know what offerings Atmel have, but for PIC32 you need one of the more modern chips, such as the PIC32MX1xx/2xx family, PIC32MX470, or for high end work the 200MHz PIC32MZ chips.

The MX1xx/2xx and MZ chips are available in a Arduino-like system called chipKIT which might suit your needs better than small Atmel chips.

The Arduino Due might also be able to do I2C but I won't be able to help you with that since I have relegated my Due to the bittom of my junk pile.


message:
2 way RF with Virtual Wire / 315 / 433 MHz

I am trying to figure out how to get 2 Arduinos to talk back and forth from one another using cheap simple RF modules. I have a total of 4 RF modules (2 receiver and 2 transmitter) and 2 Arduinos. I need Arduino A to send about 3 variables to Arduino B, and I need Arduino B to send 1 variable back to Arduino A.

When I attempted 2 way communication, I programmed Arduino A to broadcast constantly, while having Arduino B trade off between receiving once, then sending once on every other loop. This resulted in Arduino B also only broadcasting, and was not receiving any signal from Arduino A.

My other attempt was to have Arduino B send for about 250 ms, then receive for 250 ms, and repeat. This worked as long as Arduino A was only broadcasting, but as soon as I had Arduino A doing the same thing, the clock on each seemed to be slightly off and there would be periods where both Arduinos were sending, or where both were trying to receive, so it was also very unreliable.

Is there a reliable way to do two way communication with this kind of hardware, or would I need transceivers to do this kind of project?

body:
If the RF Modules you are mentioning are the ones I am thinking of they do seem to be very special bits of kit.  I have tried Bluetooth you can get cheap HM05 modules (Might be the wrong number you want the one that can be the master or slave).  These were a bit better but don't have the range.
My personal fav at the moment would be a ESP8266, no I have never hooked one up to an Arduino, but it can be done fairly easily.  You should get 100m range (in ideal circumstances) and you can get aerials to boost that.  You can also set one up as a repeater between two wifi segments.

Whatever you decide you might want to change your code slightly so that one Arduino sends a time signal and the other doesn't send its data until its turn.  Or give them GPS receivers and pull the time from there.


body:
With VirtualWire, an Arduino can only send, or only receive. It can't do both at once. It is basically like software serial, but with Manchester encoding of the message.

Write your code for the sender to send once, and then listen for a response.
If no response after some interval, try sending again, and then go back to listening.
Perhaps try one more time.

Write your code for the receiver to always be listening, and not reply until a message is received.
Add some code to indicate when a good message is received as an aid to debugging.

You should be able to connect Tx to Rx and Rx to Tx (and Gnds) between the two Arduinos and get the sequence to work back and forth, and then connect the RF modules and have them work as well.

I think the encoding done by Virtual wire adds 37 bytes to the message, which the library takes care of, so the end result is only the data that was sent.

You might also try the RadioHead library, of which VirtualWire is one part now.


message:
Supply arduino through Vin pin with a battery

1. is it dangerous for arduino the below circuit because GND pin is common with -12V battery pole?
 1. is it dangerous for lots of 5v circuit to be grounded on -12v battery pole?
 1. in case i don't connect GND arduino pin with -12v , does arduino works?
 1. in case that 1,2 question is dangerous for arduino,does it safe if a connect a diode at P1 mark?

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

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

body:
Voltages, being a *potential difference* are always measured relative to another voltage.  Normally that reference voltage is referred to as *ground*, though may not always be.

The + and - on the battery refers to the *polarity of the battery* not the *polarity of the voltage*.

For instance, *relative to the - terminal* the positive terminal is 12 volts higher, or +12V.  *Relative to the + terminal* the negative terminal is 12V lower, so -12V.

When one of your battery terminals is connected to a point in your circuit nominated as ground (the - terminal of your battery in this case) then your battery voltage at the + terminal is measured relative to ground, which we say is 0V.  So the + terminal is 12V higher than the - terminal, and the - terminal is 0V, so therefore the + terminal must be 12V *with respect to ground*.  The - terminal, since it is connected to ground is at the same voltage as ground, so it is 0V *with respect to ground*.

If you were to connect the + terminal of a battery to ground instead, then the - terminal would be 12V *lower* than ground, so would be -12V *with respect to ground*.  The + terminal would be 0V *with respect to ground*.


message:
I'd like to make RC car and remote controller via bluetooth (HC06)

At first, I tried to make whole code for an RC car and remote controller, but I realized that it's difficult for me since I have few ideas about C++. So, I changed a few things like turning on the LEDs with switches and servomotors with potentiometer. Here are my code.

**Remote controller**

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(2,3);
    int sw1=13;
    int sw2=12;

    void setup() {
      BTSerial.begin(9600);
      Serial.begin(9600);
      pinMode(sw1, INPUT_PULLUP);
      pinMode(sw2, INPUT_PULLUP);
    }

    void loop() {
      int a = analogRead(A0);
      int map_a=map(a,0,1023,0,255);
      int state1=digitalRead(sw1);
      int state2=digitalRead(sw2);

      BTSerial.print('S');
      BTSerial.print(map_a);
      BTSerial.print(',');
      BTSerial.print(state1);
      BTSerial.print(',');
      BTSerial.print(state2);
      BTSerial.print('E');
      delay(100);
    }

< RC CAR >

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(2,3);

    byte buffer[255];
    int bufferPosition;

    void setup() {
     BTSerial.begin(9600);
     Serial.begin(9600);
     bufferPosition=0;

    }

    void loop() {
      {
        if(BTSerial.available()>0){
        unsigned char data = (unsigned char)BTSerial.read();
        buffer[bufferPosition++]=data;
        Serial.println(data);
        delay(100);
        }
    }
    }

When I checked the result from `Serial.println(data)` from RC car code,
it was trash...

Can you instruct me what's wrong with this code?

body:
There are some fundamental problems in the code - `bufferPosition` never stops increasing (until it reaches 32768) and so `buffer` will overflow. However, neither of these two problems are causing the 'trash', as you are outputting the result of reading the serial, not anything from the buffer.

The problem lies in the casting of the result from `BTSerial.read()` to `unsigned char`.

`Serial.print()` does not like this. Actually it doesn't care, but it won't give you what you expect. It just prints out the value stored - so 'a', which is 97, will come out as '97' on the serial monitor. `Serial.print()` only outputs ASCII characters when you give it a `char` or `char[]`.


message:
What does the 'arduino' avrdude programmer do?

The command line that my toolchain ([CLion][1] + [PlatformIO][2]) uses to program my Arduino (Uno) includes includes

    avrdude ... -c arduino ...

but [the documentation][3] for this programmer simply reads

> -c programmer-id
>          ...
>         arduino           Arduino
>          ...

What does the `arduino` programmer do. Does it just correspond to using the bootloader?

  [1]: https://www.jetbrains.com/clion/
  [2]: http://platformio.org/#!/
  [3]: http://www.nongnu.org/avrdude/user-manual/avrdude_4.html

body:
Yes, the -c option specifies the methods of interacting with the device's loader.

The source code of the arduino programmer is http://svn.savannah.nongnu.org/viewvc/trunk/avrdude/arduino.c?root=avrdude&view=markup

Specifically, '-c arduino' chooses the client side code tailored to the bootloader in the Arduino Uno.  Looking at the code in the above link, it tweaks the DTR and RTS lines to get the Ardunino into an stk500 compatible mode, and then invokes the stk500 protocol.


message:
I would like to retrieve data from a MySQL database using PHP using HTTP requests, on my Arduino

Please help me find a way to do it.

I have looked at the following for sending data [Arduino to MySql][1]

  [1]: http://www.instructables.com/id/PART-1-Send-Arduino-data-to-the-Web-PHP-MySQL-D3js/

But can't seem to find visa-versa.

body:
There are two things you have to set up for this:
1. Retrieving/parsing websites from your Arduino.
2. Making a dynamic website using PHP (and MySql).

- Try to set up your Arduino as a [WebClient][1], check if you can retrieve a website like google.com or [a minimalistic website][2].
- Try to get your arduino to interpret a string or retrieve values from that website. (I.E: retrieve the day/time from the HTTP message)

IF your arduino can retrieve webpages, you're halfway there (somewhat). And your project is running out of the scope of this arduino.stackexchange.

Now you're going to have to [create a dynamic website][3]. You can let PHP reach for values from your MySql database (you should just use a text file first) and display them on your site (in HTML).
Your Arduino can now poll your website, to get the HTML content and parse it to the values.

  [1]: https://www.arduino.cc/en/Tutorial/WebClient
  [2]: http://www.minimalsites.com/
  [3]: https://www.google.nl/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8#q=dynamic website php mysql&es_th=1


body:
You could develop a REST based service, to make Arduino consume web service using the [aRest][1] library.

Following is a tutorial of how to use the aRest API with Arduino: [A REST API for Arduino & the CC3000 WiFi Chip][2].

  [1]: https://github.com/marcoschwartz/aREST
  [2]: https://learn.adafruit.com/a-rest-api-for-arduino-and-the-cc3000-wifi-chip?view=all


message:
IR sensor readings at different voltages

I am currently working on a photo-transistor like this:
http://www.ebay.com/itm/10pcs-ITR8307-S18-TR8-Optical-Switches-Reflective-Phototransistor-Output-/381374566327?hash=item58cbb20fb7:g:lgoAAOSwr81UQ7KG

It very nicely allows me to identify colors white, green and black. The problem I am having is that the Arduino is powered with batteries so the readings for those colors change as voltage in the batteries reduces.

I tried to make the reading proportional to the voltage in the system, but this still gives different values, I guess the readings change non-linearly as voltage changes.

I wonder what will be the solution to this problem: Specifically, how to make the reading of an IR sensor the same for the same color at different voltages?

This is the code I am using so far:

    void setup() {
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
    }

    void loop() {
    // read the input from the IR sensor on pin A0:
    float sensorValue = analogRead(A0);
    // read the voltage in the system by connecting pin A1 to Vcc, with the same resistor value used in the IR sensor:
    float Vref = analogRead(A1);

    // adjust reading value to voltage in system:
    float AdjustedReading = sensorValue/Vref;

    Serial.println(AdjustedReading);
    delay(100);
    }

body:
It sounds to me like your system works, but you have trouble if your voltage drops.

First of all here's 2 tips that might solve your problem.

1. instead of just making 1 reading do 10 and take an average - this reduces noise.

2. the voltage reference is allready based on the voltage that powers the system so with your adjusted reading you try to accomplish something which has already happened an therefore has the opposite effect and actually increase the error.

see http://tronixstuff.com/2013/12/12/arduino-tutorials-chapter-22-aref-pin/ for a very good explanation.

3. Add a RC filter to removes random fluctuations in the signal from you photoresistor

see https://electronics.stackexchange.com/questions/17754/where-to-place-a-capacitor-to-smoothen-ir-sensor-reading for a short description and the calculated example.

If however it is correct, and your readings of colors don't follow a linear scale, you would have to deduce that actual curve and apply it in the code - but that might not be easy.

So it would be much more easy to remove that variable by ensuring that the voltage is constant. Most Arduino boards have an 5V onboard voltage regulator that will keep the voltage exactly at 5 Volt when connected to battery via the **power Jack!**

*(USB bypasses this regulator and have a little voltage drop so it is sligthly lower than 5V, and more very prone to fluctations if coming from a AC source affecting your analog read considerably)*

The battery connected onboard voltage regulator however requires a higher input to do the regulation so the battery needs to supply atleast 6.2V or higher, in your case you would have to use a voltage source of less than 6.2V if this is the source of your problems.

*(the voltage regulator on original arduino boards needs voltage of 1.2V higher than the needed output - clones might differ and require upto 2v more than the needed output)*

hope this can help solve the issue

Mikael


message:
connecting RTC DS1307 to ethernet shield

What is the easiest way to mount DS1307 to ethernet shield?

I tried to do this:
https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/wiring-it-up

but my program just freezes when I try to read data from RTC. Is there any other ways to do it?

Code looks like this:

    const int RTCpin2 = 2;
    const int RTCpin3 = 3;

    void setup() {
        pinMode(RTCpin2, OUTPUT);
        pinMode(RTCpin3, OUTPUT);

        analogWrite(RTCpin2, LOW);
        analogWrite(RTCpin3, HIGH);
    }

    void loop() {
         // process RTC time
    }

body:
I assume that snippet of code is supposed to provide the +5Vand GND for powering the RTC module.  Well, there's two fundamental flaws with it:

1. Pins 2 and 3 are the DIGITAL pins, not the analog pins. Instead you want to be using pins A2 and A3.
2. analogWrite controls the PWM output on pins that support PWM. HIGH is 1, so analogWrite will be providing a 1/255 duty cycle PWM signal on that pin.

So to fix it:

1. Use pins A2 and A3 instead of 2 and 3
2. Use digitalWrite() instead of analogWrite().


message:
Multithreading with Arduino

Well I've just started learning the concept of multithreading with C++ and immediately a bunch of questions came to mind about the possibility of using multithreading with microcontrollers in general and Arduino specifically.

So, is it possible to use multithreading on any type of Arduino boards?

body:
The really quick answer is "maybe" – it depends on what you mean by "Arduino" and what you mean by "thread." The answer is likely to be different for the AVR based Arduinos (Uno et al.) vs. the ARM based Arduinos (Due et al.) – I would expect there to be much better hardware support for "real" threads on the ARM processors. Another question you'd want to answer is "why threads?" Do you want the abstraction to help you organize your code? Or do you actually need "real" threads?

Before there was hardware thread support (e.g., the mid-80s) there are user thread implementations, it seems possible that they might be adaptable to run even on an AVR. I would expect it to be something of a project.

There is a threads package called [Protothreads][3] which may be interesting. The description says "Protothreads are extremely lightweight stalkless threads designed for severely memory constrained systems." I found [another question asking about simple usage][4] of Protothreads, so it seems that you may find some other users of the package.

You may also find some useful information in this Stack Exchange [question on threads][1], a quick search for "C user threads" found [this implementation][2] on the first page – and I'm sure there are many more.

A search on "Arduino threads" found several more interesting looking links:

* https://arduino.stackexchange.com/questions/286/how-can-i-create-multiple-running-threads
* [Arduino Thread package on GitHub](https://github.com/ivanseidel/ArduinoThread)
* http://www.kwartzlab.ca/2010/09/arduino-multi-threading-librar/
* http://forums.trossenrobotics.com/showthread.php?5923-Multithreading-(Parallel-loops)-on-an-Arduino

If you just want threads, a small and inexpensive board, and I/O pins it might be worth considering a Raspberry Pi – Linux has thread support.

[1]: https://stackoverflow.com/questions/9145321/implementing-a-user-level-threads-package
[2]: http://homepage.cs.uiowa.edu/~jones/opsys/threads
[3]: http://dunkels.com/adam/pt
[4]: https://arduino.stackexchange.com/questions/12411/arduino-protothreads-by-example


body:
In [Cosa][1] you can find the following support for concurrent programming:

 1. [Events][2], interface interrupt service routines
 2. [Jobs][3], delayed, [periodic][4] or [alarm][5] functions with us, ms and seconds level timers (Watchdog, RTT or RTC).
 3. [FSM][6], object-state function
 4. [ProtoThreads][7], object-state pointer
 5. [Threads][8], Semaphores, etc, multiple stacks
 6. [UML][9] Capsules and Connectors, dependency driven programming

There are plenty examples on how to use these. A good starting point is the [Blink][10] sketches. There is even a [multi-threading Blink][11] example with a thread that does the LED on/off and a controller thread that periodically changes the blink period. The thread stack size is only 64 bytes and it runs even on an ATtiny.

With all the AVR internal hardware modules (such as SPI, TWI, UART, etc) there is plenty of opportunities for concurrency.

A [Scheduler][12] library for the Arduino core is also available. This is a port of the Cosa Threads. Please see github for further details.

Cheers!

  [1]: https://github.com/mikaelpatel/Cosa
  [2]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Event.hh
  [3]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Job.hh
  [4]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Periodic.hh
  [5]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Alarm.hh
  [6]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/FSM.hh
  [7]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/ProtoThread/ProtoThread.hh
  [8]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/Nucleo/Thread.hh
  [9]: https://github.com/mikaelpatel/Cosa-UML
  [10]: https://github.com/mikaelpatel/Cosa/tree/master/examples/Blink
  [11]: https://github.com/mikaelpatel/Cosa/blob/master/examples/Blink/CosaBlinkThread/CosaBlinkThread.ino
  [12]: https://github.com/mikaelpatel/Arduino-Scheduler


body:
There's one Arduino-like product that certainly could enable multi-threading, as it is multi-core: the [Shield Buddy TC275][1].

[![Core setup and loop functions][2]][2]

So basically you have three `setup()` functions, and three `loop()` functions. True multi-threading.

  [1]: https://www.rs-online.com/designspark/bringing-multicore-to-the-arduino-world-with-shieldbuddy-tc275
  [2]: https://i.stack.imgur.com/RUu3B.jpg


body:
I use [Atomthreads][1] on Atmega128, it is very lightweight with minimum overhead. Have task scheduler, mutex, semaphores and queue. Code is portable but might require some configuration to use with Arduino IDE (I use Atmel Studio). I primarily use task scheduler, never had problems. Just checked, the development is still active.

  [1]: https://www.google.mn/url?sa=t&source=web&rct=j&url=http://atomthreads.com/&ved=0ahUKEwizhomMgsrRAhXMHZQKHV74DcAQFggYMAA&usg=AFQjCNGsxGMmrzZ5XhSCrSidilYeNhcdwg&sig2=EUhC4i0J711ypa5OhK2o7g


message:
What is the minimum wattage of resistors for breadboarding with Arduino Uno?

I'd like to buy new resistors for breadboarding with my Arduino Uno. There are 0.25W, 0.4W, 0.6W, 1W, 2W, 3W, 5W, 10W resistors in the shop. What is the most suitable for this operation?

body: The smaller the better for the most part. On 1/4 or 1/8 W resistors the leads size is small enough to work well in bread boards. Rarely do you need to dissipate large amounts of power so 1/8 is a good size for logic, maybe 1/4-1/2 for power supply areas.  See Majenko's answer for the heavy math, mostly applicable in power supply areas as he points out.


body:
The answer is: It depends what you want to use them for.

You need a wattage that is higher than the power it will dissipate. What that power is depends on what you are doing with them.  There are standard formulae that tell you the power in any given situation.

For instance, if you know the current and the resistance you can use:  P=I²×R. If you know the voltage across the resistor it's P=V²÷R.

Take as an example the common resistor for an LED.  Assume a 2V LED and a 220 ohm resistor. With a 5V total voltage the voltage across the resistor would be 5-2=3V. So the power would be (3²)/220 = 9/220 = 0.041W so you could quite happily use a 0.125w (⅛w) resistor for that job.

To be honest though most common Arduino jobs can be accommodated by ⅛W or ¼W resistors.  ¼W is better for breadboarding since the leads are fatter than ⅛W, but ⅛W can take two leads at once direct into an Arduino's headers. Also if you fold the leads in half and squash them with pliers they fit better.


body:
Go with 1/4 Watt resistors but be prepared to use 1/2 Watts if the leads don't press down cleanly into the breadboard which is what I think you are asking about. If you need anything in the higher wattage range and you are working with an Arduino, then you are doing it wrong. An Arduino could not smoke a 1/4 watt if it tried.

I have fought for years with our purchasing agent over this at the college I work for. He buys 1/8th watt resistor in bulk, but fails to heed the advice that you cannot use these on standard classroom breadboard without bending the leads at best and failing to even make a good connection at worst. You need reliable connections and 1/8th and smaller are useless on breadboards. Just my two cents from years and years of experience.


message:
Taking off the chip from Arduino

I just uploaded a sketch of a song to my Arduino and it works well.  Could I just take the chip out and hook up speakers to it and a power source to play the song? and just get another chip and put it in the Arduino.

body:
Yes and no.

To elaborate, the sketch you downloaded to the chip has been flashed to internal non-volatile memory. So if you were to move it to *another* Arduino board or other device with the appropriate support hardware, then it should work just fine.

However, if you're intending to directly hook-up speakers to it and a power source, then I highly doubt it's going to work. You really need some support hardware for the chip (such as an external clock - though I think the Atmega328 has an internal clock, decoupling capacitors, amplifiers for the spearkers, etc.).


body:
Easy part first: You CAN put another chip on arduino PROVIDED that chip already has a bootloader on it. If it's a raw chip, burn the bootloader on it first. [This guide will help](http://www.arduino.cc/en/Tutorial/ArduinoToBreadboard).

You CAN connect the programmed chip to speaker PROVIDED you add the minimal circuit components required for an arduino to run. These include - a 16 MHz crystal, two 22 pf capacitors and a 10K resistor. Use the schematic in the bootloader guide. That will work.

Besides this, you will require a 5V power source. You can alternatively use 3xAA cells (4.5V will work perfectly). Alternatively use a wall adapter of 7V or higher and use a linear regulator (7805) to generate a perfect 5V supply for your arduino. You will need this pin mapping diagram to connect the speaker to arduino once you take it out from the board:

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

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


message:
Why won't processing not communicate with Arduino uno?

I downloaded the Processing language and ran the "Hello World" program to test it. The message appears in the Serial console but not on the Processing console. It prints "null" only. I am using the code supplied by Sparkfun. Other people have had this problem. I am looking for clear explanation and solution.

body:
I apologize for presenting a vague question. I was unable to successfully run the simple code to learn "serial communication" presented by Sparkfun on: https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing.

Step 1. Run Arduino to produce "Hello, World" on the Serial Port.
Step 2. Run Progressing 3.0.1 to produce "Hello, World" on its console.

The code from the website are copied and pasted onto my iMac running El Capitan. I received an error message for Step 2 stating the "port is busy."

Once I closed the Arduino (Step 1) and compiled and ran Step 2, it worked!

Several other people found different solutions. My solution is simple. Run one program at a time.


message:
Is a HC-SR04 fast enough to make decisions on moving robot (4 Johnson motors 300 rpm)?

I am working on a project in which I have made a robot powered by 4 Johnson DC motors (300 rpm) and controlled by Arduino UNO R3. Now in my project I'd used ultrasonic sensor (HC-SR04) for detecting obstacles.

What I want is that as soon as my an obstacle is detected robot should turn by 180° but what actually happening is that sometimes robot takes turn very late (though I'd kept range of sensor approximately 50cm) and sometimes it just collides with obstacles.

As I'm new to Arduino I just want to know if an ultrasonic sensor is fast enough to sense obstacles and signal the Arduino about it, before it gets close enough?

Here's my code

    int sense()
    {
         analogWrite(trigPin, 0);
     // instead of digitalWrite(trigPin,LOW);
         delayMicroseconds(2);

    /* as I'd used my digital pins for  motors and all i have to use pwm pin for  trigger pin of sensors i guess it doesn't make any difference*/

         analogWrite(trigPin, 255);
      // instead of digitalWrite(trigPin, HIGH);
         delayMicroseconds(10);

         analogWrite(trigPin, 0);
         duration = pulseIn(echoPin, HIGH);

         distance = duration/58.2;

          if (distance > maximumRange)
              return 0;
          else
              return 1;
    }

body:
Try using [NewPing][1] library. Ping sensors consistently and reliably at up to 30 times per second.

  [1]: http://playground.arduino.cc/Code/NewPing


body:
On it's max speed, how far is it's braking distance?
Then you should start braking atleast from before that distance of the object.

Let's say your braking distance is 25cm, you should start braking >25cm.
But this is only when you would *instantly* brake at the moment you're within 25cm reach.

So we have to know how many distance we will travel during the calculation, before we start braking.
You could just try it out, set the distance a little higher everytime you crash into it (Assuming it doesn't fail and is always at the same time).

We have to know the top speed of your motor, RPM doesn't say a lot in this story, we'll need to know how big your wheels are to be able to determine how many cm's you'll travel per revolution, and doing that times the RPM, you know your top speed. (Or you can also measure this, but it can change depending on how full your battery is)

Also, your code should be **real-time** you'll likely want to use **timers** to trigger the `trigPin` and use an interrupt on the `echoPin` to be sure none of your code will delay your sensor. This will improve execution speed aswell as reliability/deterministic timing. Also, it will make it possible to run it aside from your regular code.

So if you know, your top speed = 10cm/second.

And you know that 1 calculation+reaction-time is 200ms.

You can safely assume that you need >2cm extra.

To be honest, you should add a little for when it's slippery/another surface or just so you won't touch the object.

So. The ping sensor is almost always fast enough, only if the calculated range is outside your max range, it will not work.
You could however, use an [IR proximity sensor][1] which will trigger at a set distance. This way you don't have to do any calculations and just brake whenever you receive the interrupt. But it won't tell you the distance to the object.

The cool thing on the distance sensor is that you can also scale the brake distance on your driving speed, so that it will brake later when you're driving on half your speed. That way you can come very close to an object, but still be 100% sure that you won't crash into it.

  [1]: http://www.hobbyist.co.nz/?q=infrared_proximity_sensor


message:
Where is the Aref pin for Attitny88

I would like to use the external analog refence voltage in an Attiny88 project I am working on that will be powered with batteries.

However, the datasheet for this processor does not show an Aref pin like other versions of the attiny, like attiny85 and attiny84, where it is usually the pin PA0 or PB0. Does anyone know where is the pin for the external voltage reference in attiny88 (e.i. Aref pin)? Does this chip has the functionality for an external analog reference voltage?

body: As shown in the detailed information for the ADMUX register in the ADC section of the datasheet, the ATtiny88 has no external voltage reference. Consider using a ATmega8 or ATmega88PB instead.


message:
What is the correct way to wire a piezzo buzzer with a potentiometer and a button?

I'm working on a morse transmitter (kind-a), this how it looks like now:
[![Arduino-button-potentiometer-piezobuzzer][1]][1]

  [1]: https://i.stack.imgur.com/RYiYq.png
It's working, but is it correct? My piezo buzzer is 3-24V. I use the potentiometer as a volume control. The button is for transmitting morse code.

I've seen a way of wiring like this, not using any resistors, it feels wrong, is it correct?
https://cdn.sparkfun.com/assets/learn_tutorials/3/1/0/Arduino_circuit_11_01.png

body:
You are using the Arduino basically as a power supply (in your wiring). The linked wiring is for PWM (analogWrite). This allows pulse output to generate tone (and volume). Here is a good [reference][1].

  [1]: http://www.varesano.net/blog/fabio/pwm-and-arduino-fading-led-and-playing-melodies-piezo-speaker


message:
Sending IR (NEC)-Signals with Arduino

I have an **Arduino Micro** where I want to control a display with IR commands. So the Arduino should send the IR commands to the display.

I have found a library "[Arduino-IRremote][1]", which I am using to transmit Commands to the display. The display works perfectly with its remote control, however I can't get it accept signals from my Arduino.

Now the special part about my setup is, that I do not use a "classic" IR transmitter. Instead i uset an IR cable, which is connected to "IR-In" of the display. So no LED - only a wired connection. The IR-cable consists of 3 wires. 2 for power supply (VIN and GND) and one is for the data connection. The wire with the data connection is connected with the Arduino PWM pin 3 (like it is said on the example in the linked library), but I tried all other pins anyway.

    #include <IRremote.h>
    IRsend irsend;

    void loop() {

      for (int i = 0; i < 2; i++) {
        digitalWrite(RXLED, HIGH);
        irsend.sendNEC(0x004eff71, 32);
        Serial.println( "sendNEC 00 4E FF 71" );
        digitalWrite(RXLED, LOW);
        delay(40);

      }
      delay(1000);
    }

`004eff71` is a NEC-Command from the original remote control

  [1]: https://github.com/z3t0/Arduino-IRremote

Now can somebody tell me, what I'm doing wrong? The program compiles and the LED lights up, everytime it should send the NEC-command. But still the display receives nothing.
What is wrong?

body:
It isn't working probably because the output of the Arduino isn't simply an on/off signal.

That library uses a pulse width modulated output on the Arduino to drive an LED.  **When the LED is "on" the signal driving it is actually pulsing at a very high rate.**

I don't know what all you'd have to change to make that work with a direct wired connection.

Another thing that might becausing problems is that without checking, you can't be sure that the signal level you are sending matches the levels that the IR receiver would normally produce.


body:
It would help to know the specifications of the IR input on the device you're trying to control but after a bit of googling it looks like most of them are just expecting a connection to an IR receiver. I found a link to what appears to be a common one, TSOP22.., TSOP24.., TSOP48.., TSOP44.. and here's a link to the data sheet (http://www.vishay.com/docs/82459/tsop48.pdf). If you check the Vo on page 2 it shows 0-5V. You didn't mention if you're using a 5V or 3V Arduino so that could be an issue.

The PWM outputs do in fact generate square wave signals so at first glance this does not look like a hardware issue (assuming it is wired correctly for the IR input on your equipment).

I'd start taking a look at the data you're trying to send. I haven't looked into the library you mentioned and hopefully it contains a sample to show how to properly initialize the library and send data. Maybe instead of first byte first it needs to be sent first byte last or requires a fixed number of bytes to send...

Providing more details about your project you might get a better answer.


message:
FastLED fade WS2812B

Learning how to program with Arduino, but the learning curve is out of my league.

I have this

        #include <FastLED.h>
        #define NUM_LEDS 4
        #define DATA_PIN 3

            CRGB leds[NUM_LEDS];

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

           void loop() {
          // Turn the first led red for 1 second
          leds[0] = CRGB::Green;
          leds[1] = CRGB::Red;
          leds[2] = CRGB::Green;
          leds[3] = CRGB::Red;
          FastLED.show( 99 );
          delay(1000);

          // Set the first led back to black for 1 second
          leds[0] = CRGB::Red;
          leds[1] = CRGB::Green;
          leds[2] = CRGB::Red;
          leds[3] = CRGB::Green;
          FastLED.show( 99 );
          delay(1000);
        }

So, I want them to fade from green to red.
led 1 is green, and led 2 is red
I should probably program this in a different way, but I don't know how.
Any ideas are welcome!

body:
At the moment you have become used to working with pre-defined named colours, like CRGB::Red and CRGB::Green.  Those are just symbolic names for combinations of numeric values for red, green and blue.

So by using numeric values and varying them slightly over time you can create fade effects.  I am not personally familiar with that library or class, so I cannot tell you how to do it, but reading the documentation should show you how you can use variables to specify each of the colour components as a single colour.

As for how to fade from red to green - since they are two completely separate colours (they use separate colour channels in the LEDs) there are two main ways of doing it:

1. Start with red on full and green off. Slowly increase green to get yellow. Then slowly decrease red to get green.
2. Start with red on full and green off. Slowly increase green while slowly decrease red. At 50% they will cross over.


body:
    //start with full red
    leds[0].red = 255;

    //slowly add green
    for( int i=0; i<256; i++ )
    {
      leds[0].green = i;
      delay(10);
    }

    // slowly subtract red
    for( int i=255; i>=0; i-- )
    {
      leds[0].red = i;
      delay(10);
    }


message:
Send AT commands to ESP8266 from Arduino Uno via a SoftwareSerial port

**GOAL**

From Arduino UNO, send AT commands to ESP8266 via a SoftwareSerial port and receive results.

**CURRENT STATUS**

I either send AT commands and get nothing back (*wiring scheme 1*) or I send AT commands and get garbage back (*wiring scheme 2*).

Using the Arduino as a pass through (as explained in the tutorial listed in the resources section), I can send AT commands. I have found that I can communicate with the ESP8266 at 115200 baud.

This is the results of running `AT+GMR`:

    AT version:0.40.0.0(Aug  8 2015 14:45:58)
    SDK version:1.3.0
    Ai-Thinker Technology Co.,Ltd.
    Build:1.3.0.2 Sep 11 2015 11:48:04

**WIRING SCHEME 1**

*!! I have the green wire attached to pin 3 on the Arduino Uno and the yellow wire attached to pin 2; not 1 and 0 as the picture suggests !!*

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

**WIRING SCHEME 2**

Same wiring as above, but I have RX and TX reversed. The green wire is attached to pin 2 and the yellow wire is attached to pin 3.

**CODE**

*This is running on Arduino Uno*

<!-- language: cpp -->

    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(2, 3);

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

      Serial.println("Started");

      // set the data rate for the SoftwareSerial port
      esp8266.begin(115200);
      esp8266.write("AT\r\n");
    }

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

**RESULTS FROM RUNNING SKETCH**

*Wiring Scheme 1*

    Started

*Wiring Scheme 2*

    Started
    �����

I have tested the ESP8266 via the instructions listed in the tutorial in the *Resources I've Used* section below. The ESP8266 works just fine when sending it instructions via the Serial Prompt.

**RESOURCES I'VE USED**
http://rancidbacon.com/files/kiwicon8/ESP8266_WiFi_Module_Quick_Start_Guide_v_1.0.4.pdf

**QUESTION**

Does anyone know if what I am trying to do is possible? And if it is, what am I doing wrong?

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

body:
**Does anyone know if what I am trying to do is possible?**
It is possible, i've done it with 2 arduinos where one was simulating ESP8266 (waiting for ebay order).

**And if it is, what am I doing wrong?**

What you are doing is wrong on most levels, but i think you got most sorted out.

An idea is to implement this little fella: [Logic level shifter][1] it will save you many troubles later.

On your "WIRING SCHEME 1" you are using the arduino's Hardware serial port to talk directly to the device as if it was connected through a TTL cable or FTDI cable.

This means that the arduino device would in theory read from the hardware when talking too the ESP8266, if you have another arduino or a TTL cable, try and connect it to gate 2 and 3 on the "main" arduino and you should get a similar result as for your example result 2. Since you would that way proxy through the arduino. If not that would be a place to start debugging.

Beside that i could only recommend you in investing in either a TTL 3,3v or a logic level converter. When i got my cable everything worked out of the box.

  [1]: http://www.banggood.com/3_3V-5V-TTL-Bi-directional-Logic-Level-Converter-For-Arduino-p-949438.html


body:
Well you may try this:

Start by uploading blink sketch to your Arduino then connect it to your ESP8266 like this: TX-TX and RX-RX.

Now open Serial Monitor and send AT command and see if it responds. If so then you can control it using your Arduino by wiring it back to TX-RX and RX-TX.

PS: Don't forget to set the line ending in the Serial Monitor to Newline or Carriage Return.

Use this code to connect to ESP8266:

    #include <SoftwareSerial.h>

    const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
    const byte txPin = 3; // Wire this to Rx Pin of ESP8266

    // We'll use a software serial interface to connect to ESP8266
    SoftwareSerial ESP8266 (rxPin, txPin);

    void setup() {
      Serial.begin(115200);
      ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
      delay(1000); // Let the module self-initialize
    }

    void loop() {
      Serial.println("Sending an AT command...");
      ESP8266.println("AT");
      delay(30);
      while (ESP8266.available()){
         String inData = ESP8266.readStringUntil('\n');
         Serial.println("Got reponse from ESP8266: " + inData);
      }
    }

Since the Hardware Serial interface will be busy when connected to Computer, then you have to use another Serial interface to communicate with your ESP8266. In this case, Software Serial comes handy.


body:
I had lot of problems as well. In my case problems are almost solved by switching from SoftwareSerial to [AltSoftSerial]( https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html ). It seemed that on the Uno the standard software serial library was not working for me. After switching I started to get results back for the first time. (I also used level shifting and external power supply for 3.3V)

****

And by almost solved I mean - I still get, from time to time, gibberish on the terminal. So even AltSoftSerial isn't a perfect solution.
I was using the ESP-07 with a 115200 bps data rate.


body:
> Does anyone know if what I am trying to do is possible?

Absolutely possible :)

> And if it is, what am I doing wrong?

SoftwareSerial isn't capable of 115200 baud rate (despite "allowing" this as a setting).  Some reports suggest as high as 57600 is workable, though in my experience 9600 is best for reliability.  How to change the baud rate on the ESP8266 will depend on the firmware version.  I've had success with `AT+IPR=9600`.  You only need to run this command once (it's a persistent setting).  I'd suggest, based on your description, that this is the most likely culprit that's causing the "garbage" output you describe.

A couple of other notes:

 - The ESP8266 runs on 3v3, not 5v, so you shouldn't have it directly connected to the digital pins—you need to run through a logic level converter.  Running 5v can fry your ESP8266.
 - The Arduino's 3v3 output has insufficient current to support the ESP8266 reliably (50mA Arduino vs up to 300mA for the ESP8266 by some accounts)—try running the ESP8266 off a separate supply.  It probably won't affect simple commands like `AT` but when you try to connect to a network etc. it may cause unexpected device resets.
 - As noted by others, you need to send \r\n — so make sure your Serial window is set to send both (this is a drop-down in the serial window)


body:
We found that many of the problems with the ESP - Arduino Uno serial software integration had to do with incompatible baudrate. We created this short tutorial (including a Github library) which you are welcome to test and see if it solves these issues. [http://www.instructables.com/id/Simple-ESP8266-Arduino-Uno-Software-Serial-Integra/][1]

  [1]: http://www.instructables.com/id/Simple-ESP8266-Arduino-Uno-Software-Serial-Integra/


body:
Here are a few tips when using ESP8266 Module.

1. Don't use software serial as it's unreliable especially at higher baud rates.

2. Always [connect ESP module to computer][1] and test all AT commands before interacing with Arduino to ensure that you are working in right direction

3. [Make a power adaptor board][2] to make ESP module compatible with Arduino 5v supply

Also check out [this link][3] for more details

  [1]: http://absaransari.com/2018/01/26/connecting-esp8266-wifi-mobile-with-computer-using-pl2303/
  [2]: http://absaransari.com/2018/01/25/how-to-power-esp8266-from-5v-supply/
  [3]: http://absaransari.com/category/esp8266/


message:
Wire over 1ft does not work with sensors SRF02

Im using an SRf02 ultrasonic sensor, and I need to make the wires long to elevate the sensor. They turn on and blink and are able to transmit a signal, yet they are not able to receive a signal. What is the error?

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

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

body:
Using the internal pullup resistors for I2C is not recommended.  Arduino are very wrong in providing those as the default option and basically "hiding" the fact that I2C needs decent pullup resistors from you.

The internal pullup resistors, because they are so weak (i.e., a high resistance, typically > 50KΩ), do not pull the clock and data lines up adequately, and as such are only suitable for very short connections (in the order of a few inches).  Anything longer and the induced noise and inductance and capacitance of the wires will corrupt the I2C waveform.

I2C requires pullup resistors in the range of 2.2KΩ to 4.7KΩ.  As you can see that is more than 10x the pullup strength of the internal resistors.

For off-board connections (i.e., wires) you want the lower end of that range.  So add a 2.2KΩ resistor between SCL and +5V and another between SDA and +5V and you should find it works much better.


message:
MPPT using preassembled 'adjustable' buck/boost IC

This is more of a thought experiment, as I don't know if I'll have the time to work on it.

Items:

- Arduino
- [Homebrew MPPT controller from Instructables][1]
- [LM2596 Adjustable Buck Regulator][2]

Idea:

Looking at the Instructable, that seems like a fairly interesting and robust circuit, originally developed by one Tim Nolan whose website no longer seems to exist.

I'm somewhat lazy/fearful of messing things up when building from scratch, so I like to get preassembled modules and tinker instead. So, my thought is simple (ish). Looking at the LM2596 module, the output voltage is determined by the setting of the multiturn pot. I'd like to replace that pot with, say, a PWM controlled voltage from an Arduino, which I can then adjust using Tim Nolan's code to achieve MPPT.

So to be very specific, the question is: can I safely remove that pot and use a PWM'd voltage in its place, in order to control the output for MPPT?

  [1]: http://www.instructables.com/id/ARDUINO-SOLAR-CHARGE-CONTROLLER-Version-30/?ALLSTEPS
  [2]: https://i.stack.imgur.com/9iE2z.jpg

body:
No.

The switching frequency of the LM2596 is 150kHz, but the sampling frequency of the Arduino is only 10kHz (on a good day).  You won't be able to adjust the PWM quickly enough to fine-tune the LM2596 output voltage.  The LM2596 uses the 1.23V feedback voltage to change what it's doing.  But the feedback voltage will only change as fast as the Arduino can change the PWM feeding it (and that the RC smoother will allow).

It will be like pushing a shopping cart backwards, blindfolded.  By the time you feel the directional change in the cart, it will have steered off course by quite a bit.  Then you have to compensate wildly to bring it back on course.

The same would probably happen here: the LM2596 would begin adjusting the output voltage to make the feedback voltage come back towards 1.23V.  But the Arduino doesn't respond in time.  The Arduino has to do an ADC conversion, do some calculations, change the PWM, which eventually changes the RC output voltage, which is the feedback voltage.  So the LM2596 changes some more... and even more.  Eventually the feedback voltage does change, but by this time the output voltage has changed significantly.

Another way to look at is that the LM2596 is like another "processor", trying to optimize its own function, output voltage instead of MPPT.  It's running much faster than the Arduino, so there's no way the Arduino can trick the LM2596 into doing what it *really* wants, MPPT.


body:
The pot is actually part of the feedback mechanism, so you can just feed it a fixed voltage (based on PWM duty cycle). See the [second diagram on page 9 of the datasheet](http://www.ti.com/lit/ds/symlink/lm2596.pdf)

You could however replace it with a [digital pot](https://www.sparkfun.com/products/10613) (not necessarily 10k).


message:
How to send unmodulated IR-Signal via cable?

I need to generate en (extended) NEC signal. I have connected an Arduino with a display-device via an IR cable.

`Arduino --> IR-cable --> IR-input of display device`

**IR-cable:**
[![IR Cable datasheet][1]][1]

One plug is cutted and the 3 wires are connected with the arduino.

The arduino should generate NEC Signals, and the display shall react to it. Basically the arduino acts like a wired remote control.

The problem is: There are many tutorials around, that show how to do this with a sensor (e.g by using this [library][2]). But none of the tutorials says how to do it with a cable.

I found out, my previous attempts all failed, because I tried to generate a modulated NEC-signal to the display. The display however does not understand it, because there is no device that demodulates the signal. The IR sensor normally does this, which is missing in this case.

e.g.
This is, what an modulated NEC signal looks like:

`00 4e ff 61`

The library generates the moduled signal (pulse bursts) and this is how it works for IR sensors.

But how do I have to send my IR-command, that the display understands it? How do I send a not-modulated IR signal?

**The following graphic demonstrates the issue:**

[![IR][3]][3]

I do not have IR-LED Transmitter, Amplifier, Limiter, Band Pass Filter, Demodulator, Integrator, Comparator....
I just want to create the green Output-signal directly from my Arduino

  [1]: https://i.stack.imgur.com/rAIhP.jpg
  [2]: https://github.com/z3t0/Arduino-IRremote
  [3]: https://files.cablewholesale.com/mailimages/ir-transmission.gif

body:
There are two major components to an infra-red signal.  One is the high frequency carrier wave signal that pulses the LED on and off.  This frequency has to match that of the receiver and is used with either a high-pass or band-pass filter to filter out ambient IR light and allow it to only react to a real signal.

The second component, and it sounds like this is the one you are interested in, is the on-off pulsing of that carrier wave in different combinations and with different timings to denote binary 0 and 1.

**Without knowing what your cable actually is, and we'd need to see a datasheet to get all the proper information, all this is just surmising.**

I would imagine that you provide power and ground to the emitter cable, and the third pin is a logical "on/off" signal that enables and disables the carrier frequency to the LED.  That would allow you to send any codes you like as long as you know the timing of the signal.

In the library you link to is all the timing you need in the ir_NEC.cpp file.  The times are defined as:

    #define NEC_BITS          32
    #define NEC_HDR_MARK    9000
    #define NEC_HDR_SPACE   4500
    #define NEC_BIT_MARK     560
    #define NEC_ONE_SPACE   1690
    #define NEC_ZERO_SPACE   560
    #define NEC_RPT_SPACE   2250

The actual data format is defined in the `sendNEC` function:

    void  IRsend::sendNEC (unsigned long data,  int nbits)
    {
     // Set IR carrier frequency
     enableIROut(38);

     // Header
     mark(NEC_HDR_MARK);
     space(NEC_HDR_SPACE);

     // Data
     for (unsigned long  mask = 1UL << (nbits - 1);  mask;  mask >>= 1) {
      if (data & mask) {
       mark(NEC_BIT_MARK);
       space(NEC_ONE_SPACE);
      } else {
       mark(NEC_BIT_MARK);
       space(NEC_ZERO_SPACE);
      }
     }

     // Footer
     mark(NEC_BIT_MARK);
     space(0);  // Always end with the LED off
    }

The `mark` and `space` functions take a number of microseconds to perform either an ON or OFF of the PWM signal.  That is somewhat simpler for you, since it is just an ON or OFF of a digital IO pin to control the output of the emitter cable.  So where you have a MARK you turn on the output, then delay for the specified time. For a space you turn off the output and again delay for the specified time.

So you can just replicate the operation of that sendNEC function but with your own output control and timing in it instead of using the functions in that library.

----

**Edit:** It seems the cable doesn't need power - just provide the ground connection and the signal connection.  Of course, this is assuming that it isn't just an LED on a wire.  If it is just an LED on a wire then you would need to just use the library you link to as it is.


message:
Olimexino 32u4: Wire.endTransmission() hangs

I'm trying to get a TAE5767 (FM radio) to work. According to [this instructable][1] I'm trying it on a 5V-Olimexino 32u4 (Leonardo-compatible) with following code (Arduino 1.6.3):

<!-- language: c -->

    #include <Wire.h>

    void setFrequency(float frequency) {
      unsigned int frequencyB = 4 * (frequency * 1000000 + 225000) / 32768;
      byte frequencyH = frequencyB >> 8;
      byte frequencyL = frequencyB & 0xFF;
      Wire.beginTransmission(0x60);

      Wire.write(frequencyH);
      Wire.write(frequencyL);
      Wire.write(0xB0);
      Wire.write(0x10);
      Wire.write(0x00);
      Serial.println("sending");
      Wire.endTransmission();
      Serial.println("sent");
    }

    void setup() {
      Serial.begin(9600);
      while (!Serial) {
      }

      Wire.begin();
      setFrequency(89);
    }

    void loop() {
    }

Unfortunately, it only prints

    sending

First, I thought I'd damaged my chip, but I'm now using the second with the same result. I've also tried the I2C-Scanner from [Nick Gammon][2], but it prints nothing. I've tried adding 2.2k resistors from SCL and SDA to 5V without success. Does someone has a clue what I can try?

  [1]: http://www.instructables.com/id/TEA5767-FM-Radio-Breakout-Board-for-Arduino/?ALLSTEPS
  [2]: http://www.gammon.com.au/i2c

body:
I've did not got it working with `Wire`. Hence I've implemented a I2C protocol myself using bit-banging and then it works.

**Update from 2017-September-16**

The problem was not `Wire.h` but a specialty of the Olimexino 32u4 board. I've only found out by using a Real Time Clock connected to the UEXT port's I2C bus, that I have to switch on the power for the UEXT port by setting D8 to LOW. Otherwise SDA or SCL seem to be pulled down preventing any I2C communication.


message:
Read serial data from XV11 sensor

I am trying to read data from an XV-11 sensor using the description of the format found here https://xv11hacking.wikispaces.com/LIDAR+Sensor.  This is the code I am currently using to communicate with the computer by USB and the sensor with software serial on an arduino uno.

<!-- language: c -->

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX

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

      mySerial.begin(115200);
    }

    int count = 0;

    void loop()
    {
        if(mySerial.available())
        {
          byte in = mySerial.read();
          Serial.println(in, HEX);
        }
    }
However, the data I am receiving on the computer is inconsistent with what I expect.  For example, I am expecting a 0xFA byte every 22 bytes, however this only sometimes happens.  Many times extra or fewer bytes appear in the middle of the data.  I am using the 5 volt arduino serial communication, however I have heard that it is still compatible with 3.3 V sensor communication, so I doubt it is the problem.  I don't thinkthe sensor is broken, as it is new from a working unit.

body: The 'Serial' baud rate is too low compared to the baud rate of 'mySerial'. It could be causing you to lose bytes as the Serial buffer overflows, especially if the sensor transmits a lot of values in a relatively short interval. Increase the Serial baud rate to 115200 and see how it goes.


body: Soft Serial is totally unreliable. You may have a better error rate at other baud rates, but you will never achieve the same as a hardware based serial connection.  I'd switch my debugging connection to the software serial, nd use the hardware serial for the XV-11.


message:
Printing Serial Readings for 2+ Parallax Ping Sensors

trying print values for two sensors, one works the other is 0, any tips on how i can use more than one?

    const int pingPin = 10;
    const int pingPinz = 11;
    unsigned int duration1, duration2, inches1, inches2;

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

    void loop() {
      pinMode(pingPin, OUTPUT);          // Set pin to OUTPUT
      pinMode(pingPinz, OUTPUT);          // Set pin to OUTPUT
      digitalWrite(pingPin, LOW);        // Ensure pin is low
      digitalWrite(pingPinz, LOW);        // Ensure pin is low
      delayMicroseconds(2);
      digitalWrite(pingPin, HIGH);       // Start ranging
      digitalWrite(pingPinz, HIGH);       // Start ranging
      delayMicroseconds(5);              //   with 5 microsecond burst
      digitalWrite(pingPin, LOW);        // End ranging
      digitalWrite(pingPinz, LOW);        // End ranging
      pinMode(pingPin, INPUT);           // Set pin to INPUT
      pinMode(pingPinz, INPUT);           // Set pin to INPUT
      duration1 = pulseIn(pingPin, HIGH); // Read echo pulse
      duration2 = pulseIn(pingPinz, HIGH); // Read echo pulse
      inches1 = duration1 / 74 ;        // Convert to inches
      inches2 = duration2 / 74 ;        // Convert to inches
      Serial.println(inches1);            // Display result
      Serial.println(inches2);            // Display result
      delay(200);                 // Short delay
    }

body:
Your problem is in how you are working with the two sensors. At the moment you are triggering both sensors together then waiting for the first one to echo back. Only when that has responded do you then wait for the second one to echo back, and that echo has been and gone already.

Imagine you have two tennis balls. You throw them both at different walls at the same time, then attempt to catch them both. While you are catching the first ball the second one bounces off the back of your head and rolls under the table. That's what's happening with your echos.

So instead you need to treat both sensors completely separately. Trigger the first, then get the response. Then trigger the second and get the response.


message:
Reading Analog values of bluetooth module HC 05

I am working on a project which requires signal strength of a bluetooth TX and RX. what i assume is that in bluetooth module like hc05, there is an antenna receiver which reads the analog signal and then passes it to its ADC to get data in terms of 0's and 1's. But is there any way i can read the analog signal strength of the reveiver antenna directly? Please help

body: Try looking up the datasheet to see if there is a command for signal strength. It's impossible to **directly** read the the analog value since the signal strength is way too low in amplitude.


message:
Sublime Text Compilation Issue

I've tried searching for this issue but came up empty. Due to the desire to use a better IDE, I installed Sublime Text 3 and Stino. I have installed the Stino package and now have the Arduino menu inside the Sublime Text editor. I have selected the Arduino application folder appropriately. However, when I compile the simple Blink example, I'm presented with the following error. This error comes up when I attempt to compile any Arduino project. Have I forgotten to configure a setting? All videos and tutorials I've seen just follow the same steps as I have and don't seem to include any additional configuration (besides selecting the Arduino application folder).

    [Stino - Start building "Blink"...]
    [  3%] Creating C:\Users\cketc_000\Documents\Arduino\Blink\Blink.ino.cpp.o...
    "C:\Program Files (x86)\Arduino/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD  -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=161 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\examples\01.Basics\Blink" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\cketc_000\Documents\Arduino\Blink\Blink.ino.cpp" -o "C:\Users\cketc_000\Documents\Arduino\Blink\Blink.ino.cpp.o"
    The filename, directory name, or volume label syntax is incorrect.

    [Stino - Exit with error code 1.]

body:
As a quick update for anyone who runs into a similar issue (granted, a week later)...

I upgraded to 1.6.5 of the Arduino IDE, making sure to set my Arduino application folder appropriately, and the compilation issue has disappeared. I am able to compile and upload projects successfully.


message:
Send stepper to position and back AccelStepper

At the moment I am working on a code that should send a plateau to a certain position and back. The plateau is being moved by the stepper, in my case a Nema 17 with a [Polulu DRV8825](https://www.pololu.com/product/2133) driver. Everything is hooked up correctly.
My goal is to press '4' on the keyboard and that then the stepper moves to a certain position. However, I am not succeeding in this. I am using AccelStepper and at the moment I have the following code:

<!-- language: c -->

    #include <AccelStepper.h>

    AccelStepper stepper(1, 5, 4);

    int spd = 1000;    // The current speed in steps/second
    int sign = 1;      // Either 1, 0 or -1
    int buttonState = 0;

    void setup()
    {
      Serial.begin(9600);
      stepper.setMaxSpeed(1000);
      stepper.setSpeed(1000);
    }

    void loop()
    {
      char c;
      if (Serial.available()) {
        c = Serial.read();
        if (c == 'f') {  // forward
          sign = 1;
        }
        if (c == 'r') {  // reverse
          sign = -1;
        }
        if (c == 's') {  // stop
          sign = 0;
        }
        if (c == '1') {  // super slow
          spd = 100;
        }
        if (c == '2') {  // medium
          spd = 900;
        }
        if (c == '3') {  // fast
          spd = 1000;
        }
        if (c == '4') {
          //not working, does anyone know how to do this?
          stepper.moveTo(500);
        }
        stepper.setSpeed(sign * spd);
      }
      stepper.runSpeed();
    }

Does anyone have tips or know how to achieve this?

Thanks is advance!

body:
[Gerben's comment](https://arduino.stackexchange.com/questions/18604/send-stepper-to-position-and-back-accelstepper#comment34648_18604):
>You need to call stepper.run() instead of runSpeed, for moveTo to work.

provides the answer. The updated code is:

    #include <AccelStepper.h>

    AccelStepper stepper(1, 5, 4);

    int spd = 1000;    // The current speed in steps/second
    int sign = 1;      // Either 1, 0 or -1

    int buttonState = 0;

    void setup()
    {
      Serial.begin(9600);
      stepper.setMaxSpeed(1000);
      stepper.setSpeed(1000);
    }

    void loop()
    {
      char c;
      if (Serial.available()) {
        c = Serial.read();
        if (c == 'f') {  // forward
          sign = 1;
        }
        if (c == 'r') {  // reverse
          sign = -1;
        }
        if (c == 's') {  // stop
          sign = 0;
        }
        if (c == '1') {  // super slow
          spd = 100;
        }
        if (c == '2') {  // medium
          spd = 900;
        }
        if (c == '3') {  // fast
          spd = 1000;
        }
        if (c == '4') {
          //not working, does anyone know how to do this?
          stepper.moveTo(500);
        }
        stepper.setSpeed(sign * spd);
      }
      stepper.run(); //You need to call stepper.run() instead of runSpeed, for moveTo to work. – Gerben
    }


message:
The 3.3 volts of the USB To TTL

I'm using ESP with USB to serial converter (D-SUN) is it possible to use the 3.3 volts of the USB instead of the Arduino Uno?

body:
I don't know what that adapter is (a link would be nice, or at least the chip number it uses) but in general the 3.3v on a USB TTL adapter can only provide a small current. For instance the FT232RL can only provide up to 50mA at 3.3v. That may not be enough current to drive the RF circuitry of the ESP. The early Arduinos used the FT232RL chip for the USB interface and it was the 3.3v from that which was used for the 3.3v header on the Arduino. This was somewhat of a failing with those Arduinos since the 50mA limit was a real problem when people started using more 3.3v devices. That was one of the driving forces (as well as cost) in the decision to switch to an MCU for the USB interface.

So to be on the safe side I wouldn't use the 3.3v from the USB adapter to power the ESP. You are better using a 5v to 3.3v regulator circuit driven from the 5v of the USB. And yes, that could be a whole Arduino, or build your own on some stripboard.


body: From my experience using the USB to TTL adapter will not work very well. I got some code on my ESP somehow, but could not get it working reliable. So I ended up powering it from an additional source.


message:
How to convert frequency into db

I have made an Arduino circuit which outputs in terms of frequency(hz) and I need output in terms of db as well

So is there any formula which can I apply to convert frequency hertz to db or is there any reference link to understand the conversion process.

Any help will be highly appreciated

body: dB is volume (sound pressure), frequency is pitch. The two are entirely different concepts and can't be converted. A bit like you can't convert the roundness of a doughnut into blue. Roundness and blueness (it has blueberries in it by the way) are two different properties of the doughnut.


body:
Decibels (Db) are calculated using amplitudes and by definition decibels are the measurement of sound intensity or power level of electrical signal by comparing it with a given level on a logarithmic scale, which is **independent of frequency**.

You can measure the decibels though if you know the amplitude of your source which i'm guessing is ~5v .


body:
dB it self just express in a logarithmic scale a ratio between two values and it self is unit independent (because is a ratio). Just because the most common uses of dB scales are linked to intensity or power doesn't necessarily mean that can't be used to represent other ratios of different types of quantities. Or at least I couldn't find any definition that restricts the use of dB in such cases. The formulas to express such ratio are present [here](https://en.wikipedia.org/wiki/Decibel) you just have to figured it out what is really your ratio.

So, for example, if you have some kind of sensor that somehow the output is a frequency, let's say something like

    f(x) = ax + f0  [Hz]

There is no reason why you can't express this function in a logarithmic ratio scale using dB something like, related to f0 or f(x=0)

    L(x) = 10*Log10*(f(x)/f0) [dB]

which would give you the represented dB output of your equation with respect to x.

**But** since we are in arduino stackexchange and talking about sensor, the common use of dB in electronics is the representation of power ratio or (the more common) a frequency response of a circuit(or system) that is represented by a [Bode Plot](https://en.wikipedia.org/wiki/Bode_plot), so I advise you to really take a good look at both links and try to figure what you really are asked to represent.


message:
What does the bootloader do?

As far as I understand it checks for a valid serial connection (new program incoming) and then either writes it to flash or starts executing the existing program.

Can't the 32u4 or EDBG fill the role of an ISP and program the MCU instead of the MCU self-programming? I know the EDBG is accessed via OpenOCD to write the bootloader to the SAMD21 on Arduino Zero boards so why is the bootloader even required?

body:
The bootloader is there for convenience.

Yes, you understand what the bootloader does and how it operates.  However, you have missed out one benefit, and that is evident when you're *not* using the bootloader.  That is, when you're not using the bootloader the *same* connection can be used for a serial connection to the PC.  If the 32U4 were directly programming the main MCU then it would be talking to the SPI pins not the UART pins, so you would need a second connection, or both a connection to the UART *and* the SPI pins, and much more complex firmware on the 32U4, in order to get a serial connection to the PC.

So the simplest option is just to have a dumb pass-through interface from the USB to the UART pins and have the main MCU self program with a bootloader.

It also means that you don't need any special programming hardware when making your own board - just something (another arduino maybe) to get the bootloader on there in the first place (or buy the MCU pre-programmed) and then use any TTL serial interface to program it with your main program.


message:
Message received with 1 character less

I have the following situation:

One Arduino Uno with a 433mhz transmitter wired to the laptop to have serial communication. Another Arduino Uno with a 9V battery wired with a 433mhz receiver and an LCD screen (16x2, I2C).

I have the following code to transmit:

    #include <VirtualWire.h>

    void setup() {
      //Force low when enabled
      vw_set_ptt_inverted(true);
      //Set pin 12 for transmitter
      vw_set_tx_pin(12);
      //Setup with speed of the data transfer.
      vw_setup(4000);
      //Set serial communication at 9600 baud
      Serial.begin(9600);//set Serial
      //Set pin 13 to light up when transmitting
      pinMode(13,OUTPUT);
    }

    void loop() {
      //If message send via serial monitor
      if (Serial.available()) {
        //wait a bit for the entire message to arrive
        delay(100);

        while (Serial.available() > 0) {
          //Read serial into string
          String message = Serial.readString();
          //Initialize char array
          char msg[message.length()];
          //Write string to char array
          message.toCharArray(msg, message.length());
          //send char array as unsigned int (bits)
          vw_send((uint8_t *)msg, strlen(msg));
          //Wait until the complete message has been send
          vw_wait_tx();
          //Turn on light when finished
          digitalWrite(13,HIGH);
          delay(200);
        }
      }else{
        //Turn off light
        digitalWrite(13, LOW);
      }
    }

And the following code to receive a message and print on a LCD screen:

    #include <LiquidCrystal_I2C.h>
    #include <VirtualWire.h>

    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

    void setup() {
      //start up LCD with 16 chars with 2 lines
      lcd.begin(16,2);
      //Turn on backlight
      lcd.backlight();
      //Write initialising message
      lcd.setCursor(0,0);
      lcd.print("Initialisation..");
      //Force low when enabled
      vw_set_ptt_inverted(true);
      //Set pin 12 to receive
      vw_set_rx_pin(12);
      //Setup with speed of the data transfer.
      vw_setup(4000);
      //set pin 13 for light
      pinMode(13, OUTPUT);
      //Start receiver
      vw_rx_start();

      //Set message on LCD that setup has completed
      lcd.setCursor(0,1);
      lcd.print("Completed!");
    }

    void loop() {
      //initialize array for message
      uint8_t msg[VW_MAX_MESSAGE_LEN];
      uint8_t msgLength = VW_MAX_MESSAGE_LEN;

      //If message received
      if (vw_get_message(msg, &msgLength)){
        //Turn on light
        digitalWrite(13, HIGH);

        //Print on lcd
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.write(msg, msgLength);
      }else{
        //Else turn of light
        digitalWrite(13, LOW);
      }
    }

My problem is that the message that is being transmitted and received by the other arduino always is short 1 character. For example if I send "test", it receives and displays "tes". What am I missing?

(My short solution was to just add a space to the message, then the space got cut off. But I want to understand what is going wrong.)

body:
I haven't found the source of the problem by reading through the code, and will limit my comments to advice about debugging the problem.

With the code as it stands, there are half a dozen points where the missing character might have dropped out.  With just a final result, the problem location is difficult to narrow down.  Modify your code to display intermediate data.

For example, in the sending code, print the read-in string and its length to Serial.  Eg, if you `#include <Streaming.h>` you can say:

`Serial << message << ' ' << message.length() << endl;`
`Serial << msg << ' ' << strlen(msg) << endl;`

and so forth.

[Note, `msg` actually occupies strlen(msg)+1 bytes, the last byte being a null-byte terminator, which your code doesn't send or receive.]

In the receiving code, besides the `lcd.write` of `msg`, do an `lcd.print` with `msgLength`.

You can also do some code clean-up in the sender.  Remove the line

`while (Serial.available() > 0) {`,
and its corresponding `}`, because  `Serial.readString()` already contains a character-wait loop with timeout.


message:
From Arduino to a miniaturized circuit

I have a project made with Arduino, and I want to replace it by a miniaturized circuit with just a microcontroller. Is there any tutorial that can guide me in doing this? Any reference is wellcome. Thank you!

body:
You can use an [Arduino on a breadboard][1] to get you going. From the breadboard, you can then develop a circuit on a pre-made PCB like this:

[![PCB][2]][2]

Then to a custom PCB, if you so desire.

  [1]: https://www.arduino.cc/en/Main/Standalone
  [2]: https://i.stack.imgur.com/gl4zM.jpg


body:
The main question is: Which features do you want to have on your board?

You can start off with the design files of the Arduino board you are using: update what you need (and don't need).

Then, for the manufacturing itself, several approaches will work:

- veroboard & through hole components. Not very practical, not small, but easy;
- DIY manufacturing: toner transfer method, or if you have a CNC, isolation milling;
- Boardhouse (e.g. PCB manufacturer) to whom you send your finished design to have it manufactured.

An alternative would be to use a smaller board, like an Arduino nano: it all depends on what your constraints/goals are.


message:
Are INTx pins the only ones eligible for Software Serial?

As opposed to PCINT (Atmel's Pin Change INTerrupt, INTx is arduino-compatible interupt)  In other words, does Software Serial use atmel's pin change or arduino falling interrupt?

body: `SoftwareSerial` uses PCINT.  `AltSoftSerial` uses INT0 or INT1, which has FALLING, RISING, CHANGE or LOW LEVEL options.  See Section 12.2, p. 71 of the Atmel [ATmega328 spec](http://www.atmel.com/images/doc8161.pdf), for example.


message:
Converting three axis magnetometer to Degrees

I do not know if here is the best place to post this question.
I have a 9-DOF sensor (MPU 9150) and I want to use its magnetometer to retrieve the rotation angle, from 0 to 359. However, its library returns three values: x, y and z.

I do not know how to transform this into a single value. There's any way to do this?

body:
This is a basic math problem.

    az=90-atan(y/x)*180/pi

"atan()" is arctangent and converts from coordinate variables to angle in radians, *180/pi converts from radians to degrees, and 90- converts from degrees math angles (degrees CCW from the x axis) to azimuth (degrees CW from north).

Calibrating the sensor is a trickier problem.


body:
You first need calibration (either using the device calibration method, or, by rotating it in a complete circle to ascertain the full field strengths).

You can then use the X, Y, and Z readings to compute the location of "north" relative to whichever way you're pointing (keeping in mind that "north" changes as much as 30 degrees depending where on earth you are (called declination - see http://www.magnetic-declination.com/), and that it's not horizontal to the ground either (confusingly, called "inclination" - see https://physics.stackexchange.com/questions/283761/if-you-hold-a-compass-needle-vertical-does-it-point-down-or-up-differently-on-wh/283782 )

If you picture the X, Y, and Z readings as meaning "where on an imaginary circle is the direction of magnetism - where those 3 circles are on 3 different planes, you can compute the logical position of a vector pointing towards magnetic north in 3 dimensions.

The bad news - there's no simple way to do what you want accurately, and definitely not one that's going to work without trig math on all 3 readings (you can't just use X and/or Y alone).

The good news - you probably don't really need to know an actual "heading" - most applications just need some local relative direction as compared with something you already know.

Beware that strong magnets (such as ones in all modern motors) seriously mess with readings from a long way away (10 or more foot even) - grab an app from your phone store that shows your phone magnetometer readings, and wave a magnet around to see this easily!


body:
The answer given by Dave X, namely

    az=90-atan(y/x)*180/pi

is on the right track. However, it cannot work as is for two reasons:

1. The formula fails badly whenever x = 0,

2. It gives the same azimuth for x = y = 1 and for x = y = −1. In other
   words, it cannot differentiate between north-east and south-west.

The formula could be fixed by replacing `atan(y/x)` by a function that
returns:

* atan(y/x) if x > 0
* π/2 if x = 0 and y > 0
* −π/2 if x = 0 and y < 0
* atan(y/x) + π if x < 0 and y ≥ 0
* atan(y/x) − π if x < 0 and y < 0

That would be essentially a two-argument, “quadrant-aware” version of
the arctangent, yielding results in (-π, π] instead of
(−π/2, π/2).

Fortunately, such function already exists. It is a very standard
function of the C library and is called `atan2()`. Thus, the correct
formula is

    az = 90 - atan2(y, x) * 180 / M_PI;

Now, since atan(y/x) = π/2 − atan(x/y), the formula above can be
simplified into

    az = atan2(x, y) * 180 / M_PI;

This formula gives the direction of the (x, y) vector counted clockwise
from the y axis. It is likely that the OP wants instead to know the
heading of some kind of vehicle. The correct formula depends then on how
the magnetometer has been mounted relative to the vehicle. If we assume
that the x axis of the magnetometer points forward and the y axis points
to the left, then:

* the vehicle is heading north (0° magnetic heading) when the horizontal
  component of the magnetic field is along +x
* the vehicle is heading east (90° magnetic heading) when the horizontal
  component of the magnetic field is along +y

From here, it follows that the vehicle heading is

    heading = atan2(y, x) * 180 / M_PI;

Obviously, the [magnetic declination][] has to be added if one is
interested in the _true_ (rather than _magnetic_) heading.

------------------------------------------------------------------------

**Edit**: All this assumes the XY plane is horizontal. If it is not
(due to the vehicle's pitch and roll), see [Tails86's answer][ans] for a
way to cope with that.

[magnetic declination]: https://en.wikipedia.org/wiki/Magnetic_declination
[ans]: https://arduino.stackexchange.com/a/88707/7508


body:
I wanted to expand upon what Anon is getting at and provide some math as I've just gone through this process for a similar 9-axis device.

First, it's good to know what the magnetic field vector means. I like [this source][1] because it provides [an image][2] showing where magnetic vectors point as you move up and down earth. It points downward on the northern hemisphere and upward in the southern hemisphere. The text is otherwise not relevant as it more or less just explains how you can approximate laitudinal position from that data - the angle of the horizontal component is all that we need to be concerned with in order to obtain a heading.

The problem with Edgar's answer is that it assumes that your reference plane is flat against earth. As soon as you add any pitch or roll, that answer won't be right. To correct, you need to project the magnetic field vector onto your horizontal plane. Luckily, that sensor also provides you with an accelerometer which provides a way to tell you which way is down due to the force of gravity as long as you're not moving around too quickly.

What I did was [project the magnetic field vector onto the acceleration vector][3] then subtracted that from the magnetic field vector to get the horizontal component vector. Then I could retrieve the vector angle on the X/Y plane just as described by others.

First, a partial definition of a vector so I'm not depending on external libraries:
```cpp
    class Vector3D
    {
    public:
        Vector3D() : mArr{} {}

        Vector3D(double x, double y, double z)
        {
            mArr[0] = x;
            mArr[1] = y;
            mArr[2] = z;
        }

        double dot(const Vector3D& rhs) const
        {
            double out = 0;
            for (int i = 0; i < NUM_DIMENSIONS; ++i)
            {
                out = out + mArr[i] * rhs.mArr[i];
            }
            return out;
        }

        Vector3D operator* (double x) const
        {
            Vector3D out;
            for (int i = 0; i < NUM_DIMENSIONS; ++i)
            {
                out.mArr[i] = mArr[i] * x;
            }
            return out;
        }

        Vector3D operator- (const Vector3D& x) const
        {
            Vector3D out;
            for (int i = 0; i < NUM_DIMENSIONS; ++i)
            {
                out.mArr[i] = mArr[i] - x.mArr[i];
            }
            return out;
        }

     double getX() const {return mArr[0];}
     double getY() const {return mArr[1];}
     double getZ() const {return mArr[2];}

    private:
        static const int NUM_DIMENSIONS = 3;
        double mArr[NUM_DIMENSIONS];
    };

    Vector3D operator* (double x, const Vector3D& y)
    {
        return (y * x);
    }
```

Here is how the compass angle can be computed:
```cpp
    // mag: magnetic vector
    // accel: acceleration vector (due to gravity)
    double computeYaw(double mag_x, double mag_y, double mag_z, double accel_x, double accel_y, double accel_z)
    {
        const Vector3D vector_mag(mag_x, mag_y, mag_z);
        const Vector3D vector_down(accel_x, accel_y, accel_z);
        const Vector3D vector_north = vector_mag - ((vector_mag.dot(vector_down) / vector_down.dot(vector_down)) * vector_down);
        return atan2(vector_north.getX(), vector_north.getY()) * 180 / M_PI;
    }
```

EDIT: I changed the code so needed elements of a Vector are defined here so there is no confusion.

EDIT2: [Here][4] is a good resource on this subject if you need a more accurate solution. As stated in this resource, the above is only really useful if you're not moving around too much and your magnetic environment is clean.

  [1]: https://lohmannlab.web.unc.edu/geomagnetic-imprinting/
  [2]: https://lohmannlab.web.unc.edu/wp-content/uploads/sites/8154/2014/10/geomagnetic-field-low-res-624x385.jpg
  [3]: https://en.wikipedia.org/wiki/Vector_projection
  [4]: https://www.mdpi.com/1424-8220/11/10/9182/pdf


message:
Arduino Uno and Raspberry Pi USB Serial Communication

I am trying to get Arduino Uno with Raspberry Pi to communicate with each other. I want the python script to write a message and for my Arduino to read it. This was working before, but I came back a week later and it stopped. Essentially, I want the Raspberry Pi to write '3' and for my Arduino to recognize this 3 and light up some LEDs. Where do you think I am going wrong? The Arduino works when testing it through the IDE and Serial Monitor. There are no errors when running the python script, the LEDS just don't light up, so I assume there is some miscommunication.

Python Code

    import serial
    ser = serial.Serial('/dev/ttyACM0', 9600)
    ser.write('3')

Arduino Code

    String serialRead;
    int val;
    void setup() {
      Serial.begin(9600);
      strip.begin();
      strip.setBrightness(25);
      strip.show(); // Initialize all pixels to 'off'
    }

    void loop() {
      serialRead = Serial.read();
      if (Serial.available() > 0) {
        val = Serial.read();

        if (val > '0' && val <= '9') {
          Serial.println(val);
          val = val - '0';
          Serial.println(val);

          if (val == 3)
          {
            //strip.setBrightness(100);
            colorWipe(strip.Color(127, 127, 127), 50);
            colorWipe(strip.Color(0, 0, 0), 50);
          }
        }
      }
    }

body:
Just at a glance:

Your loop consumes the byte and stores it in `serialRead`, so there is probably no available data at the outer `if`, so it is never entered.

Try deleting this line:

    serialRead = Serial.read();


message:
Blink question with breadboard & LED

I tried a basic Blink example and I found a strange case where :

Works
[![Working example][1]][1]

Does not work
[![NOT working example][2]][2]

Can someone explain me what is happening ?

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

  [2]: https://i.stack.imgur.com/rpYOF.jpg

body:
It is because the rail in the middle breaks the vertical connections.
So the positive leg in the first example is not connected to the negative leg of the LED.

In your second example both the negative leg and the positive leg are connected on the same rail, because of the that the power is not flowing through the LED but directly back to the GND pin of your arduino.

Same for the resistor. Since both legs are connected to the same rail, the resistor has no effect.


message:
MQ135 output on Arduino Uno

I bought an FC-22 (MQ135) gas sensor module which I plugged into my Arduino Uno. I connected it to the A0 analog port. Then created a code that reads the raw data from A0 (code below).

When I run the code on my Arduino Uno in my house I get values of about 30. If I blow over the sensor I get values until about 160. My question is now how I have to read / interpret these values.

According to the MQ135 specifications the sensor has a sesitivity for air quality, measuring benzene, alcohol and smoke.

How can I interpret the values I get? What is a good value and what isn't? Do I have to calculate something out of these values?

My code looks like this:

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

    void loop() {
      int sensorValue = analogRead(0);
      Serial.print(sensorValue, DEC);
      delay(100);
      if (sensorValue > 50) {
        digitalWrite(13, HIGH);
      }
      else {
        digitalWrite(13, LOW);
      }
    }

body: According to the [datasheet](https://www.olimex.com/Products/Components/Sensors/SNS-MQ135/resources/SNS-MQ135.pdf) you have to calibrate it.


message:
Extra characters remain in Serial

I have spent the whole day trying to deal with this problem connecting Arduinos together using UART (Serial). But the problem is that it always behaves weirdly. For now the problem is that if previous number (I am sending numbers over serial) stays in the serial port.

Let me describe the problem. I want to send the following sequence of numbers 16 4 100. Numbers are sent with a terminator char after each number, but on the receiver side I get the following result 16 46 100.

As you can see if the previous number is longer (length, has more digits) than the current one, like 16 and 4, 132 and 34, the difference (number of digits) remains in the next result: for 16 and 4 it will be 16 and 46, for 132 and 34 it will be 132 and 342.

I have tried different ways to solve this problem, but unfortunately I cannot find the solution.

Here are my functions used for communication:

<!-- language: c -->

    void sendCommandToSerial(int command) {
      Serial3.print(command);
      Serial3.print(TERMINATOR_CHAR);
      Serial3.flush();
    }

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

    int readRawBytes(char *inputBuffer,const int bufferSize) {
      return Serial3.readBytesUntil(TERMINATOR_CHAR, inputBuffer, bufferSize);
    }
    int readIntFromSerial() {
      if(readRawBytes(inputBuffer,DEFAULT_BUFFER_SIZE) > 0) {
        return atoi(inputBuffer);
      }
      return -1;
    }
    int readFloatFromSerial() {
      if(readRawBytes(inputBuffer,DEFAULT_BUFFER_SIZE) > 0) {
        return atof(inputBuffer);
      }
      return -1;
    }

I have tried both software and hardware serials, still the same.
Please help to find and solve the problem.

body:
The Stream member function readBytesUntil() does not null terminate the string. It returns the number of characters read. You must terminate the string with null(0) before calling atoi() and atof() or fill the string will null(0) before calling readBytesUntil().

For more details see Arduino [Stream.cpp][1].

Cheers!

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L219


message:
Arduino IDE fails without sudo

I use Arduino IDE 1.6.6 on Ubuntu 15.10.

Starting the Arduino IDE without using `sudo` fails for both:

 - uploading the code to the Arduino Uno
 - starting the serial monitor

The group I need to add my user to is called `dialout`:

    myuser@mycomputer:~$ ls -l /dev/ttyACM*
    crw-rw---- 1 root dialout 166, 0 Dez 12 17:57 /dev/ttyACM0

So I added `myuser` to `dialout`:

    sudo usermod -a -G dialout myuser

Somewhere I read that I have to add `myuser` to `tty` as well, so I did it:

    sudo usermod -a -G tty myuser

Though I still fail with the above mentioned when trying to use the IDE with `myuser`.

What do I have to do to get the IDE working with `myuser`?

body:
There should be a command like 'id' or something similar that will show the groups you are a member of. Run that to check that the new groups have taken effect – you may need to log out and then log back in.

The other thing to check is the group owner of the device itself (in /dev). that will also need to match the group you assigned to yourself. Also make sure that the device permissions allow group access.


message:
Displaying binary to LEDs

I've written a program for Arduino UNO and 3 LED lights. The program is supposed to turn an inputted number into binary and then display it on the LEDs, on being 1 and off being 0 I have looked it over quite a few times and don't understand why it is not working as it should. I'm a beginner at working with Arduino so I probably just need a more experienced eye to show me where I have messed up. I have a link to a picture of the Arduino setup below. Thanks!
https://drive.google.com/file/d/0B8k_WNZ3eFOkZHkwNUllTEp4WGM/view?usp=sharing

    //setting up lights
    const int lightOne = 13;
    const int lightTwo = 12;
    const int lightThree = 11;

    //array of the lights for when printing the binary
    int lights[] = {lightOne, lightTwo, lightThree};

    void setup() {
      //setting pin modes and starting up the serial monitor
      pinMode(lightOne, OUTPUT);
      pinMode(lightTwo, OUTPUT);
      pinMode(lightThree, OUTPUT);
      Serial.begin(9600);
    }

    //converts a given number into binary
    String binary(int number) {
      String r;
      while(number!=0) {
        r = (number % 2 == 0 ? "0" : "1")+r;
        number /= 2;
      }
      return r;
    }

    //outputs the binary string to the lights (not expecting numbers larger than     9)
    void printBinary(String binaryNumber) {
      for (int i = 0; i < sizeof(binaryNumber); i++) {
        digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH));
        delay(2000);
      }
    }

    void loop() {
      int input = Serial.read();                //get the number
      String binaryNumber = binary(input);      //convert number to binary
      Serial.println(binaryNumber);             //print binary to serial monitor
      printBinary(binaryNumber);                //display number in binary on     LEDs

    }

body:
You need to check that there are characters available before reading. Please see documentation of [Serial.read][1]() (and [Serial.available()][2]).

Cheers!

  [1]: https://www.arduino.cc/en/Serial/Read
  [2]: https://www.arduino.cc/en/Serial/Available


body:
#Welcome to SE Arduino!

##Long Version

You have a couple of things to look at:

1. Don't use `String` class it has too much overhead for Arduino.
1. Your conversion function is not really necessary because you can convert it on your `Serial.println()` by specifying `binary` as output. eg: [`Serial.println(number, BIN)`][1];
1. The `Serial.read` returns an integer, but that `int` only contains a [`byte`][2] (unsigned) value anyway (unless there's nothing to be read, in which case it returns `-1`). Because you're taking a number (not really relevant) and you want it to be a number on the return, just use `int` or `byte` (unsigned: `0 <-> 255`) or [`char`][3] (signed: `-127 <-> +128`).
1. You could/should/doesn't matter if you use `Serial.available()` or not, it is a matter for yourself, I usually do, but it's non blocking anyway and if there's nothing there to be read, it'll just continue on anyway. Although if you're not going to use it, you should test for that `-1` as what you're doing at the moment is taking that and converting it to binary (which is `0xFF` which is everything on). **This is one of your major problems in the code** (the other is in the **Short Version** section.
1. You're using `"0"` and `"1"` which are `ASCII` values, and you haven't indicated how you're getting the number. So it may be `ASCII` (`byte`) or actually a `byte` value. ie, `"0"` is `48 (dec)` or `30 (hex)`. Whereas a `0` is just `zero`. Funnily enough, because you're using modulo (`%`) it doesn't really matter because you're only interested in the lowest nibble, which for the sake of your code, doesn't matter what's encoded at the higher end. ie: `1` (`0b00000001`) is the same as `"1" = 49 (dec) = 0x31 = 0b00110001` when used with `%2`.
1. Ditch your `delay(2000)`. Delays are evil* :) You could write the values to the pins all day, you're not going to cause any problems, if you want to output less to your serial port (which you should do), you could do timed outputs back to Serial. ie, do your `Serial.println()` once a second, or record the values into backup/old variables and compare them, and only print the output if the value changes
1. The big one is in the next section

##Short Version
This is your *main* problem, on this line:

    digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH));

I think you need:

    digitalWrite(lights[i], (binaryNumber[i] == '0' ? LOW : HIGH));

You already have the pin value encoded in the array, you don't want to add 11 to the index, that's going to throw you above your three light values :)

*** Delays are evil**: It's a matter of opinion, and that's just how I feel, I actually googled it and this is just a random response. But it contains the crux of what I'd say anyway: http://www.makeuseof.com/tag/arduino-delay-function-shouldnt-use/

  [1]: https://www.arduino.cc/en/Serial/Println
  [2]: https://www.arduino.cc/en/Reference/Byte
  [3]: https://www.arduino.cc/en/Reference/Char


message:
Rotating a motor with L293D

I'm following this [tutorial][1] to control a DC motor with an Arduino.

I have the same problem as this stackexchange post arduino.stackexchange.com/questions/10049/problems-with-l293d where the motor is not rotating.

 - The chip is heading to the right. (5v pins are on the right)
 - Connecting directly the motor to the battery works.
 - Current (5V on the bottom & 2*1.5V) is flowing everywhere expected EXCEPT on the yellow & green wires of the motor (the red wire of the battery pack is connected to the second line of the breadboard).
 - Connecting directly the motor to the battery works.
 - I copied the code of the above tutorial which is basically : "digitalWrite(4,HIGH);", there is current on the cable.

Am I wrong into thinking that a L293D chip can output sufficient current ? Is the chip malfunctioning ?

[![My montage][4]][4]

  [1]: http://communityofrobots.com/tutorial/kawal/how-drive-dc-motor-using-l293d-arduino
  [2]: https://i.stack.imgur.com/fZ6Ym.jpg
  [4]: https://i.stack.imgur.com/FE9o4.jpg

body:
Your picture shows a holder for two AA cells, yielding something in the neighbourhood of 3v.  That is far too little for an L293D.  (This isn't really your fault, as it appears you got this erroneous idea from following a bad tutorial, but it does demonstrate that not everything you read on the Internet is sensible.  Using a 9v "transistor" battery is also a bad idea).    3 cells would be about the minimum, but even there it would not work well, as that chip has two bipolar transistors in the path yielding a voltage drop of over a volt.

To use a an L293D you really want at least a 5 or 6 volt system, and a motor wound for low to moderate current at that voltage.

If you want to use a lower voltage, look at a more modern MOS-based H bridge chip - the TB6612FNG is an often used example.  You will however still want to choose motors wound for moderate current at a 3- or 4- cell voltage - those intended for 2-cell usage typically draw more current than is ideal for an IC driver chip.

It is entirely possible that there are additional issues with your attempt as well.  Normally, a question such as this would require a complete and accurate schematic diagram, which you have not provided.