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

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

Answers: 2

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


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

title: Where is the Aref pin for Attitny88

Answers: 1

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.


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

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

Answers: 1

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


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

title: Sending IR (NEC)-Signals with Arduino

Answers: 2

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.


body:
I am trying to read data from the Serial port in my Arduino, store it in a buffer and when all the data has been read stop reading and then start using the data (the talkMIDI() function). The Arduino succesfully some bytes from Serial but not all of them and then hangs without stopping before the end.

    void loop() {
      if (!stop)
      {
        char in = Serial.read();
        if (in != -1)
        {
          buffer[pos] = in;
          pos++;
          Serial.write("read");
          Serial.print(pos);
          Serial.print("\r\n");
        }
        if (in == 126)
        {
          stop = 1;
          Serial.write("STOP");
        }
      }
      else
      {
        if (cursor < pos)
        {
          talkMIDI (buffer[cursor], buffer[cursor+1], buffer[cursor+2]);
          cursor = cursor+3;
          delay(500);
        }
      }
    }

After manually sending a 126 value (~) character, I get a "STOP" response on the Serial line but Arduino doesn't start executing the code from the else branch (the talkMIDI() part -- the function doesn't even get called once).

title: How to read all avaiable data from a Serial stream and then stop

Answers: 0


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

title: FastLED fade WS2812B

Answers: 2

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);
    }


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

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

Answers: 6

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/


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

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

Answers: 1

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.


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

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

Answers: 2

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).


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

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

Answers: 1

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.


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

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

Answers: 1

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.


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

title: Read serial data from XV11 sensor

Answers: 2

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.


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

title: Printing Serial Readings for 2+ Parallax Ping Sensors

Answers: 1

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.


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

title: Reading Analog values of bluetooth module HC 05

Answers: 1

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.


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

title: Sublime Text Compilation Issue

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


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

title: Send stepper to position and back AccelStepper

Answers: 1

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
    }


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

title: The 3.3 volts of the USB To TTL

Answers: 2

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.


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

title: How to convert frequency into db

Answers: 3

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.


body: I'm using Arduino Uno board as master and AVR32UC3A0512 as slave. I've written code for arduino using SPI.h library, and Atmel Studio 6.2 using spi.h. I'm sending data from arduino to atmel i.e from SPDR register in arduino to RDR register in Atmel, but the data is not getting recieved. Hence, I'm not able to read the data. I've successfully interfaced SPI between two arduino boards and I'm using the same Arduino Master code while interfacing it with slave EVK. I've also set the baud rate same, I'm not sure what the problem might be. Can anyone please help me out?

title: SPI Interface between Arduino UNO and EVK1100

Answers: 0


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

title: What does the bootloader do?

Answers: 1

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.


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

title: Message received with 1 character less

Answers: 1

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.


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

title: From Arduino to a miniaturized circuit

Answers: 2

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.


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

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

Answers: 1

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.


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

title: Converting three axis magnetometer to Degrees

Answers: 4

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


body:
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);
          }
        }
      }
    }

title: Arduino Uno and Raspberry Pi USB Serial Communication

Answers: 1

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();


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

title: Blink question with breadboard & LED

Answers: 1

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.


body:
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);
      }
    }

title: MQ135 output on Arduino Uno

Answers: 1

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


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

title: Extra characters remain in Serial

Answers: 1

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


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

title: Arduino IDE fails without sudo

Answers: 1

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.


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

    }

title: Displaying binary to LEDs

Answers: 2

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


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

title: Rotating a motor with L293D

Answers: 1

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.


body:
I recently started playing around with Arduinos to connect a few sensors up. I used an Arduino Nano to measure temperature, humidity, air pressure and light level.

To store the data in a database, I used another Arduino that I connected to a Raspberry Pi, and let the two Arduinos talk wirelessly to each other via 433 MHz.

That all works pretty well, but the 433 MHz communication is not exactly the most reliable (I often miss a transmission). When I stumbled upon the ESP8266 module, it seemed like the optimal solution for communication. How cool would it be if I could just pull out the information via an HTTP call from the Raspberry Pi?

After toying around for many hours, uploading many different firmwares, getting more and more frustrated because I could not get it to do anything, I finally have it working through an FTDI module connected up like this:

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

I use an MB102 power module to provide the 3.3v required by the ESP8266. I turns out you need to connect the ground from the MB102 to the ground of the FTDI module to get any proper response. After doing that I was able to send AT commands and get the proper responses. I could even connect it to my home Wifi.

The next thing I want to do is connect it to the Arduino. I found a very simple schema for that (http://blog.huntgang.com/2015/01/20/arduino-esp8266-tutorial-web-server-monitor-example/), where you connect RX to TX and TX to RX. Using the MB102 I connected it like this:

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

Apparently I should now be able to upload a blank sketch to the Arduino, and then use the serial monitor again to sens AT command, exactly the same way I did it when using the FTDI module.

The problem is that I get nothing at all this way. I don't even see my own AT commands in the console. I do see the ESP8266 flashing every time I send a command (I even see it it still connected to my router, probably it remembered the info I send through the FTDI...?)

The question is, what am I going wrong? I read some posts about the TX from the Arduino also being 5v and that you need to do something to bring it back to 3.3v, but there are also many tutorials that say it's not required.

  [1]: https://i.stack.imgur.com/9mjhX.png
  [2]: https://i.stack.imgur.com/aLzdG.png

title: Linking Arduino Nano with ESP8266 Wifi module

Answers: 4

body:
There might be an issue with the baudrate from the Nano FTDI chip to the RX/TX and the ESP8266. Did you disconnect when uploading the sketch?

How about trying [this][1] instead?

Cheers!

  [1]: http://blog.huntgang.com/2015/01/20/arduino-esp8266-tutorial-web-server-monitor-example/

body:
Stumbled on good tutorial here, tried and it does the job:
https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/

body:
Yes, if you are using different power sources the grounds always have to be connected, otherwise the boards don't know what zero volts is.

The TX of the Arduino is 5v, you need a level shifter to convert 5v to 3.3v, something like this (https://shop.pimoroni.com/products/adafruit-4-channel-i2c-safe-bi-directional-logic-level-converter?utm_medium=cpc&utm_source=googlepla&variant=302017581&gclid=CPqujsPxlc0CFcYcGwodb8YIoA)

The TX of the ESP8266 is 3.3v and the RX of the Arduino is 5V and you will need a level shifter to handle this.  You can use the same one as listed above, because it can convert 4 high (5v) signals into 4 low (3.3v) signals.

People say you can so it with resistors, but I have also read that they don't perform well enough to handle fast switching digital signals (so 300 Baud on your serial might be OK, but not 115000 :) )

People also say you don't need level convertors.  That's true things _might_ work for a while without them, but sooner or later something will go pop.  Increasing the voltage will speed up the process so you can imagine what will happen if you connected a 230v supply directly to a USB device.

One final point, do you know the ESP8266 is a 80/160MHz processor with 256KB of RAM, when you compare that to you Arduino its like programming you PC via your phone.  What you could try is connecting the ESP8266 via a FTDI module and program it via the Arduino IDE in Arduino C.  Its a lot easier than all this connection stuff.

body:
The easiest way to work with these devuces is to connect them to a spare pair of Arduino pins and use SoftwareSerial for communicating (unless you're using one of the Arduinos with more than one UART). SoftwareSerial work up to 9600 baud on 16MHz devices, 4800 on 8MHz devices, so you'll need to set the ESP8266 to accommodate that. They currently ship at 115200 baud. You can use the hardware UART on pins (0, 1) but then re-programming the Arduino means disconnecting & reconnecting the ESP temporarily each time, and gets old pretty quickly.

Here's what I do with new ESPs (If you've re-flashed your ESP, you'll need to download the AT instruction-set emulator and re-flash it with that, first):

    # To configure a new ESP module:
    # Connect the ESP and the FTDI as in your top diagram, set your
    # terminal-emulator to 115200 baud, and enter the following:

    AT                             # ESP should respond "OK"
    AT+RST                         # Resets the ESP
    AT+UART_DEF=9600,8,1,0,0       # Sets ESP UART: 9600,N,8,1,no flow ctl

    # Now change the terminal emulator baud rate to 9600

    AT+CWMODE=1                    # Set ESP to station mode (client)
    ATE0                           # Set ESP's echo off
    AT+CWLAP                       # List access points - after a short pause
                                   # the ESP returns a list of WiFi access points

For future reference, here is a link to the [ESP8266 AT Instruction Set][1].

Update June 2020: The above link was broken, now fixed. You can also find documentation at [Espressif's github account][2] (online readable, but not pdf, as of this date).

  [1]: https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf
  [2]: https://github.com/espressif/esp-at/tree/master/docs


body:
I want to learn core and mechanics of microcontrollers with Arduino, and I don't really know where to find good source of knowledge.

Every Arduino related tutorial is about very basic stuff like connecting the LCD display without explaining what every pin does. When it comes to programming tutorials only explain what functions are needed and do not explain what happens inside the hardware.

For example i know what delay() function does, and I know that I can find definition in the source files:

    void delay(unsigned long ms)
    {
     uint16_t start = (uint16_t)micros();

     while (ms > 0) {
      yield();
      if (((uint16_t)micros() - start) >= 1000) {
       ms--;
       start += 1000;
      }
     }
    }

But what I really want to know what that code does, and how to write own functions. I would appreciate if you could provide me with any starting point. Should I just follow the source files until I get it or is there any better reference?

I have Arduino Leonardo, and experience in programming in C/C++.

title: How to learn electronics/programming with Arduino?

Answers: 2

body:
There are two main topics there: Digital Electronics, and C++ programming, and the Arduino happens to bridge the gap between the two.

That's why it's hard to find tutorials in the style you want.  So instead of looking for Arduino tutorials that do what you want you need to split the topics apart and deal with them separately.

Search for C++ programming tutorials. That should help you understand the structure and syntax of a program better. Search for digital electronics tutorials. Good keywords are things like *logic gates*, *combinational logic* or *digital interfacing* and just *digital electronics*. That should help you understand things like logic levels, logical functions, inputs and outputs, and such like.

Once you have basic understanding in both fields you can begin to see how the two relate together. One of the most important skills any engineer has is understanding and interpreting datasheets. From datasheets you can find how the hardware operates and what you would need your program to do to make the hardware do what you want.

body:
For information about the “core and mechanics of microcontrollers with Arduino”, there are numerous articles with lots of details on the [arduino.cc](http://forum.arduino.cc/) forum.  However, most of the code posted there sucks, as does most of the code posted here on [Arduino Stackexchange](http://arduino.stackexchange.com).  That's a natural consequence of people posting code that doesn't work and they wonder why.

For a reasonably organized and accurate body of information about Arduino hardware and software, see [Nick Gammon's Arduino pages](http://www.gammon.com.au/forum/index.php?bbtopic_id=123).  Also see [arduino.land](https://arduino.land/FAQ/showcat.html) pages.  For better understanding of Arduino software internals, see [garretlab's “Internal Structure of Arduino Software”](http://garretlab.web.fc2.com/en/arduino/inside/index.html) pages, which are well organized and quite informative about the subjects they cover.

Regarding the specific `delay()` code shown in the question, first consider this slightly simpler version, from Arduino 1.6.3:

    void delay(unsigned long ms) {
        uint16_t start = (uint16_t)micros();
        while (ms > 0) {
            if (((uint16_t)micros() - start) >= 1000) {
                ms--;
                start += 1000;
            }
        }
    }

Ignoring data type constraints, it's evident that the `while` loop counts down `ms` from its original value to zero.  The burden of the `if` executes about once per millisecond, because `start` advances 1000 microseconds each time within the `if`.

The casts of `micros()` – ie, where `uint16_t` appears in parentheses before `micros()` – tell the compiler to throw away the upper two bytes of `micros()` [which is actually an unsigned long, or [`uint32_t`](http://www.cplusplus.com/reference/cstdint/)] and treat it as an unsigned 16-bit integer.  The low two bytes of `micros()` overflow every 65536 microseconds, on which occasions within a millisecond it will come to pass that although `(uint16_t)micros()` is less than `start`, due to use of unsigned arithmetic `((uint16_t)micros() - start) >= 1000`.

The code you included has one more statement in the `while` loop:

        yield();

For most models of Arduino, `yield()` is an empty function, a do-nothing if compiled at all.  On the Due, with [`Scheduler.h`](https://www.arduino.cc/en/Reference/Scheduler) in use to support cooperative (non-preemptive) multitasking using multiple stacks, `yield()` gives the scheduler an opportunity to schedule another task, if one is ready to run.  Note that if a  “cooperative” but malignant task always takes just under 65536 microseconds to do its work, it can happen that `delay()` as shown never returns.


body:
I'm trying to code a simple transmitter - Receiver program with nRF24L01

Very simple code. Compiles. But when I try to test it using serial monitor. But only the first character is printed on the screen just once.

<!-- language: c -->

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    #define CE_PIN 9
    #define CSN_PIN 10

    const uint64_t pipe = 0xE8E8F0F0E1LL;

    RF24 radio(CE_PIN, CSN_PIN);

    int smth[1];  // the transmitter data
    int x=0;  // the copy of the receiver data
    char rec[1]; //the receiver data

    int ledPin = 3; // choose the pin for the LED
    int inPin = 7;   // choose the input pin (for a pushbutton)
    int val = 0;     // variable for reading the pin status

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);  // declare LED as output
      pinMode(inPin, INPUT);    // declare pushbutton as input

      radio.begin();
      radio.openWritingPipe(pipe);  //originally transmitter
    }

    void loop(){
      val = digitalRead(inPin);  // read input value
      if (val==HIGH) {         // check if the input is HIGH (button released)
        digitalWrite(ledPin, HIGH);  // turn LED OFF
        Serial.println('1');
        smth[0] = '1';
        radio.write(smth, sizeof(smth));
      } else {
        digitalWrite(ledPin, LOW);  // turn LED ON
        Serial.println('0');
        smth[0] = '0';
        radio.write(smth, sizeof(smth));
      }
    }

----------

Serial Monitor :

0

----------

Instead of printing a zeros for infinite time till I change the mode of the switch, even though if I change the mode of the switch from low to high, nothing is printed on the screen.

I'm using Library for instance [http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01][1]

Any help?

  [1]: http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01

title: nRF24L01 Problem

Answers: 2

body: A quick look at the library header files shows you should call `radio.stopListening()` before calling `radio.write()` for the module to switch to transmit mode. This could be what is blocking the `radio.write` in the else block. I also recommend you try a `byte` array first, to get things working, just in case `int`s are the issue.

body:
Completing TisteAndii reply I suggest to have a look at init. According to the RF24 classe list, it seems radio.begin(); and radio.openWritingPipe(pipe); are "void" function.
I personnaly use NRFLite from Dave Parson and his lib send a return value for his _radio.init function.
That's interesting because a lot of lib have a "send feature" which don't return until the receiver replied. So if you turn on your nRF and send data while the receiver is OFF, you're blocked. With a test at init, you can check that and loop until the receiver is available.

Note: I let my answer, but that's not the good one. As indicate in the coment, the init function dont tell if the receiver is avaible, but only if the nRF is connected (your nRF, so not the other one).


body: Can the ATTINYx5 use its universal serial interface for a better UART than the Sofware Serial library alone? If so, is there a library or tutorial for this?

title: ATTINYx5 usi for uart?

Answers: 1

body: AVR307 describes implementation of a half duplex UART implementation using the USI. Note that full duplex is not possible due to the synchronous design of the USI.


body:
I'm currently looking for an RF protocol that doesn't use much power (generally much less than wifi) Something similar to simple AM radio, but with an authentication library readily available. ZigBee has about 250kbps bandwidth. I don't need nearly as much, so something with ~5kbps (dial-up speeds) would be acceptable. Using the Arduino Yun; so i'm constrained to the 5V output.
I'm also trying to stay away from the 2.4 GHz band.

Is there anything out there with this in mind? I was thinking maybe [Z-Wave][1]?

As far as the ZWave chips go this is where i'm at: http://pastebin.com/B0Yif3LS

  [1]: https://en.wikipedia.org/wiki/Z-Wave

title: Looking for an existing lightweight RF protocol

Answers: 0


body:
I have tried to get the Ai-Thinker ESP8266 working at all. If you hook it up to an Uno you have garbage returned no matter what the baud rate is. Tried softwareSerial on D3 and D4 (switching pins doesn't help) and over D0 and D1 with no sketch (to send AT commands directly to the device because softwareSerial wasn't working).

I'm using a logic converter from 5v to 3.3v to handle the voltage correctly.

I also know for a fact you can do that. I've done it a bunch with Bluetooth. HC-05.

NOTE: Pins in the wrong order won't return anything, in order to get garbage it needs to be wired correctly.

I also have a FTDI module that functions as another passthrough unit for this. It has a jumper for 3.3v to 5v and will stay on 3.3v as these units are unable to handle 5v.

I used PuTTY in order to view the boot information of this chip. On boot it returns this information.

So here's my issue.

    ets Jan  8 2013,rst cause:4, boot mode:(3,7)

    wdt reset
    load 0x40100000, len 816, room 16
    tail 0
    chksum 0x8d
    load 0x3ffe8000, len 788, room 8
    tail 12
    chksum 0xcf
    ho 0 tail 12 room 4
    load 0x3ffe8314, len 288, room 12
    tail 4
    chksum 0xcf
    csum 0xcf

    2nd boot version : 1.2
      SPI Speed      : 40MHz
      SPI Mode       : QIO
      SPI Flash Size : 4Mbit
    jump to run user1

    sd▒C▒
    Ai-Thinker Technology Co. Ltd.

    invalid

At the end of the day this invalid line means that the wifi information (from what I understand) is corrupted. It also refreshes this information over and over and WILL NOT accept AT commands so I can't seem to chase it down.

I am afraid that by attempting to update it if this kind of issue happens it will be bricked.

Both of these modules are opened today and I have tested another 8266 with similar results.

Any help would be appreciated.

title: ESP8266 Returns 'invalid' - Cause 4

Answers: 2

body:
Alright so I figured it out. Thanks to user Butters for pointing me in the right direction.

The Arduino Uno DOES NOT have enough power to handle the ESP8266 itself. It needs a power source using a 5v to 3v stepdown chip. The 3v3 rail doesn't handle it by itself.

body: I don't know what this "invalid" means I am getting this on every boot but my device is working fine. I have tested downloading webpages and it's working. So maybe just ignore this. use cutecom it works there, didn't work in minicom maybe because of carriage return absent.


body:
How do you save space by preventing the inclusion of unnecessary binaries?

When I compiled the [ROS Blink](http://wiki.ros.org/rosserial_arduino/Tutorials/Blink) example, I received the warning:

    Global variables use 1,951 bytes (76%) of dynamic memory,
    leaving 609 bytes for local variables. Maxiumum is 2,560 bytes.
    Low memory available, stability problems may occur.

Considering the example uses almost no libraries, I was surprised by this, but sure enough, the compiler pulls in a ton of libraries that are never used:

    Scanning dependencies of src
    Scanning dependencies of arduino
    Scanning dependencies of ros_lib
    src/main.cpp
    arduino/wiring.c
    arduino/wiring_shift.c
    arduino/wiring_digital.c
    arduino/wiring_pulse.c
    arduino/WInterrupts.c
    arduino/hooks.c
    arduino/wiring_analog.c
    arduino/USBCore.cpp
    arduino/new.cpp
    arduino/Tone.cpp
    arduino/WString.cpp
    arduino/HardwareSerial1.cpp
    arduino/Stream.cpp
    arduino/HardwareSerial3.cpp
    arduino/HardwareSerial0.cpp
    arduino/CDC.cpp
    arduino/HardwareSerial2.cpp
    arduino/main.cpp
    arduino/HID.cpp
    arduino/HardwareSerial.cpp
    arduino/IPAddress.cpp
    arduino/Print.cpp
    arduino/WMath.cpp
    arduino/abi.cpp
    Linking libarduino.a
    ros_lib/duration.cpp
    ros_lib/time.cpp
    Linking libros_lib.a
    Linking firmware.elf
    Converting to firmware.hex

Why are so many files being included in the compilation, and how do I filter them out?

title: How to prevent inclusion of unnecessary libraries?

Answers: 2

body:
The [Arduino IDE build][1] script will actually copy all core source code file to the tmp directory, compile and generate an archive file. The sketch is compiled and linked with this library. Only the referenced (used) functions and data are [linked in the binary][2].

The size (both program and data) of this blink is somewhat larger than the "standard" blink example but this is due to the publisher-subscriber run-time.

Cheers!

PS: If you google you can find commands to listing what is actually in the generated binary. [Here][3] is a starting point.

  [1]: https://www.arduino.cc/en/Hacking/BuildProcess
  [2]: http://openhardwareplatform.blogspot.se/2011/03/inside-arduino-build-process.html
  [3]: http://forum.arduino.cc/index.php?topic=155142.0

body:
Part of the compilation process is what is known as *garbage collection*, which is controlled by the compilation flag `-Wl,--gc-sections`

This process goes through the compiled program and works out which sections (functions, blocks of read-only data, etc, each in its own *section* controlled by `-ffunction-sections` and `-fdata-sections` IIRC) and works out which are not needed in your compiled program.  It then deletes them.

The problem you have though is not with code or read-only data size, but with static RAM allocation size.  This is global variables and local static variables - things used for stiring data, maybe as serial buffers, etc.  Most of that is probably part of the underlying RTOS that you have elected to use. Which is the problem of using an RTOS to just blink an LED. It could be seen as a task that is beneath the RTOS and is complete overkill. Of course, since you're just testing, that is pretty irrelevant, however, as you add more functionality you will most likely find that the memory footprint doesn't increase much since it's the "background" stuff that of the RTOS that will always be there regardless of what tasks you are performing.


body:
I'm trying to sending and receiving data via RS485 communication. Interfacing Arduino and PC(laptop)
using SN75176 RS485. I wrote a program to send a string "Hello" from arduino via Tx pin. My intention is to receive
the "Hello" string in my PC's hyperterminal. After uploading the program im receiving junk data. The baud rate i've mentioned in
my program and i gave in hyperterminal are same. I've checked the wire connection, it is ok. Then, what is the problem?

Code:

<!-- language: c -->

 #include <SoftwareSerial.h>
 int Txpin = 1;
 int ditpin = 5;  //for 1st rs485
 int ditpin1 = 2; //for 2nd rs485
 void setup()
   {
     // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(Txpin,OUTPUT);
  digitalWrite(ditpin, HIGH); //For transmit data from arduino
  digitalWrite(ditpin1, LOW); //For receive data to hyperterminal
   }

 void loop()
   {
  Serial.println("Hello\r\n");
  delay(1000);
   }

Wire connection:

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

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

title: Problem in RS485 Communication between Arduino and PC

Answers: 1

body:
You cannot connect from Arduino serial input/output with RS485 circuit and then to the PC RS232 port. You need a TTL to RS232 adapter. For instance an adapter based on [MAX3222][1].

[![MAX3232 circuit diagram][2]][2]

Cheers!

  [1]: http://pdfserv.maximintegrated.com/en/ds/MAX3222-MAX3241.pdf
  [2]: https://i.stack.imgur.com/TPUVf.gif


body:
I have found an Arduino function which converts a 2-bytes-`long`-value to a binary value.

e.g. I call `sendCommand(0x05)` And it gives me an output:

`00000101`

    void sendCommand(unsigned long command){
      for (unsigned long  mask = 1UL << (7);  mask;  mask >>= 1) {

        if (command & mask) {

        Serial.print( "1" );
        } else {

        Serial.print( "0" );
        }
      }
    }

my Problem is, that I want to have the Least significant bit first. How do I have to adjust this function to achieve this?

e.g.
`sendCommand(0x05)`
shall give an output:

`10100000`

title: Convert Long to binary - least signifant bit first

Answers: 1

body:
    void sendCommand(unsigned long command){
      for (unsigned long  mask = 1UL; mask<256UL;  mask <<= 1) {

        if (command & mask) {

        Serial.print( "1" );
        } else {

        Serial.print( "0" );
        }
      }
    }

PS a long is actually 4 bytes long. But your code only uses 1 byte of it.


body:
I have been running a simple RF link between 2 arduini uno recently and everything went faily well. I am now trying a new project with an arduino mini pro (5V/16MHz) and the seeeduino RF link (@315MHz), and I see very odd results : when the transmitter is on USB cable, the link runs ok, but when on a 9V battery (as raw voltage input), I get very very limiter range (a few inches).

Because the setup works on USB, I'm assuming that the current limitation on the GPIO that powers the RF transmitter is not the issue here. It therefore has to be the battery itself or the regulator.

Somehow I need to use a GPIO to shut down the radio during power saving phases. My current design is very basic, I should probably add a transistor to enable power on the RF. I was also thinking maybe the RD oscilliator needs to settle down a bit, I may need to add some delays before starting to send data. I can see on the oscilloscope that the data and power PINs seem to behave correctly, although I have noticed a voltage drop on the power pin which is similar in pattern to the data transmitted (but again this is no issue unless using the 9V battery).

title: powering RF on GPIO

Answers: 1

body:
As established in the comments, the issues here are powering the module directly from a GPIO pin, which are limited to 20 mA, and potentially the limited current of a 9V battery.

Personally I avoid using 9V batteries in projects, as they are comparatively expensive for the lifetime they provide. There are various boost/step-up converters that make a steady 5V supply from two AA batteries.