# Question
Title: Sparkfun ESP8266 Wifi Shield does not receive data
When I make any GET request to my shield, the only thing I get when I read the request is '\r\n'. I am sending query parameters, and when the request has been read in the past, there was the full http request.

EDIT: Could this be due to some memory issue? It seems to be fairly non-deterministic when it fails, and I have 69% of memory taken when the program starts.

```
/************************************************************
ESP8266_Shield_Demo.h
SparkFun ESP8266 AT library - Demo
Jim Lindblom @ SparkFun Electronics
Original Creation Date: July 16, 2015
https://github.com/sparkfun/SparkFun_ESP8266_AT_Arduino_Library

This example demonstrates the basics of the SparkFun ESP8266
AT library. It'll show you how to connect to a WiFi network,
get an IP address, connect over TCP to a server (as a client),
and set up a TCP server of our own.

Development environment specifics:
  IDE: Arduino 1.6.5
  Hardware Platform: Arduino Uno
  ESP8266 WiFi Shield Version: 1.0

This code is released under the MIT license.

Distributed as-is; no warranty is given.
************************************************************/

//////////////////////
// Library Includes //
//////////////////////
// SoftwareSerial is required (even you don't intend on
// using it).
#include <SoftwareSerial.h>
#include <SparkFunESP8266WiFi.h>

//////////////////////////////
// WiFi Network Definitions //
//////////////////////////////
// Replace these two character strings with the name and
// password of your WiFi network.
const char mySSID[] = "ssid";
const char myPSK[] = "pass";

const short out1 = 10;
const short out2 = 11;
const short out3 = 12;
const short out4 = 13;

bool on1 = false;
bool on2 = false;
bool on3 = false;
bool on4 = false;

//////////////////////////////
// ESP8266Server definition //
//////////////////////////////
// server object used towards the end of the demo.
// (This is only global because it's called in both setup()
// and loop()).
ESP8266Server server = ESP8266Server(80);

//////////////////
// HTTP Strings //
//////////////////
const String html = "HTTP/1.1 200 OK\r\n"
                          "Content-Type: text/html\r\n"
                          "Connection: close\r\n\r\n"
                          "<!DOCTYPE HTML>\r\n"
                          "<html>\r\n"
                          "<link rel=\"icon\" href=\"data:,\">\r\n"
                          "<a href=\"/?toggle=1\"><button>Toggle 1</button></a>\r\n"
                          "<a href=\"/?toggle=2\"><button>Toggle 2</button></a>\r\n"
                          "<a href=\"/?toggle=3\"><button>Toggle 3</button></a>\r\n"
                          "<a href=\"/?toggle=4\"><button>Toggle 4</button></a>\r\n"
                          "</html>\r\n";

// All functions called from setup() are defined below the
// loop() function. They modularized to make it easier to
// copy/paste into sketches of your own.
void setup()
{
  // Set pins
  pinMode(out1, OUTPUT);
  pinMode(out2, OUTPUT);
  pinMode(out3, OUTPUT);
  pinMode(out4, OUTPUT);

  digitalWrite(out1, LOW);
  digitalWrite(out2, LOW);
  digitalWrite(out3, LOW);
  digitalWrite(out4, LOW);

  // Serial Monitor is used to control the demo and view
  // debug information.
  Serial.begin(9600);

  // initializeESP8266() verifies communication with the WiFi
  // shield, and sets it up.
  initializeESP8266();

  // connectESP8266() connects to the defined WiFi network.
  connectESP8266();

  // displayConnectInfo prints the Shield's local IP
  // and the network it's connected to.
  displayConnectInfo();

  serverSetup();
}

void loop()
{
  serverDemo();
}

void initializeESP8266()
{
  // esp8266.begin() verifies that the ESP8266 is operational
  // and sets it up for the rest of the sketch.
  // It returns either true or false -- indicating whether
  // communication was successul or not.
  // true
  int test = esp8266.begin();
  if (test != true)
  {
    Serial.println(F("Error talking to ESP8266."));
    errorLoop(test);
  }
  Serial.println(F("ESP8266 Shield Present"));
}

void connectESP8266()
{
  // The ESP8266 can be set to one of three modes:
  //  1 - ESP8266_MODE_STA - Station only
  //  2 - ESP8266_MODE_AP - Access point only
  //  3 - ESP8266_MODE_STAAP - Station/AP combo
  // Use esp8266.getMode() to check which mode it's in:
  int retVal = esp8266.getMode();
  if (retVal != ESP8266_MODE_STA)
  { // If it's not in station mode.
    // Use esp8266.setMode([mode]) to set it to a specified
    // mode.
    retVal = esp8266.setMode(ESP8266_MODE_STA);
    if (retVal < 0)
    {
      Serial.println(F("Error setting mode."));
      errorLoop(retVal);
    }
  }
  Serial.println(F("Mode set to station"));

  // esp8266.status() indicates the ESP8266's WiFi connect
  // status.
  // A return value of 1 indicates the device is already
  // connected. 0 indicates disconnected. (Negative values
  // equate to communication errors.)
  retVal = esp8266.status();
  if (retVal <= 0)
  {
    Serial.print(F("Connecting to "));
    Serial.println(mySSID);
    // esp8266.connect([ssid], [psk]) connects the ESP8266
    // to a network.
    // On success the connect function returns a value >0
    // On fail, the function will either return:
    //  -1: TIMEOUT - The library has a set 30s timeout
    //  -3: FAIL - Couldn't connect to network.
    retVal = esp8266.connect(mySSID, myPSK);
    if (retVal < 0)
    {
      Serial.println(F("Error connecting"));
      errorLoop(retVal);
    }
  }
}

void displayConnectInfo()
{
  char connectedSSID[24];
  memset(connectedSSID, 0, 24);
  // esp8266.getAP() can be used to check which AP the
  // ESP8266 is connected to. It returns an error code.
  // The connected AP is returned by reference as a parameter.
  int retVal = esp8266.getAP(connectedSSID);
  if (retVal > 0)
  {
    Serial.print(F("Connected to: "));
    Serial.println(connectedSSID);
  }

  // esp8266.localIP returns an IPAddress variable with the
  // ESP8266's current local IP address.
  IPAddress myIP = esp8266.localIP();
  Serial.print(F("My IP: ")); Serial.println(myIP);
}

void serverSetup()
{
  // begin initializes a ESP8266Server object. It will
  // start a server on the port specified in the object's
  // constructor (in global area)
  server.begin();
  Serial.print(F("Server started! Go to "));
  Serial.println(esp8266.localIP());
  Serial.println();
}

void serverDemo()
{
  // available() is an ESP8266Server function which will
  // return an ESP8266Client object for printing and reading.
  // available() has one parameter -- a timeout value. This
  // is the number of milliseconds the function waits,
  // checking for a connection.
  ESP8266Client client = server.available(500);

  if (client)
  {
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    String req;
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();
        req += c;
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank)
        {
          Serial.println(req);
          if (req.indexOf("toggle=1") != -1){
            if (on1){
              Serial.println(F("TURN 1 ON"));
              digitalWrite(out1, LOW);
            }
            else {
              Serial.println(F("TURN 1 OFF"));
              digitalWrite(out1, HIGH);
            }
            on1 = !on1;
          }
          else if (req.indexOf("toggle=2") != -1){
            if (on2){
              digitalWrite(out2, LOW);
              Serial.println(F("TURN 2 OFF"));
            }
            else {
              Serial.println(F("TURN 2 ON"));
              digitalWrite(out2, HIGH);
            }
            on2 = !on2;
          }
          else if (req.indexOf("toggle=3") != -1){
            if (on3){
              Serial.println(F("TURN 3 OFF"));
              digitalWrite(out3, LOW);
            }
            else {
              Serial.println(F("TURN 3 ON"));
              digitalWrite(out3, HIGH);
            }
            on3 = !on3;
          }
          else if (req.indexOf("toggle=4") != -1){
            if (on4){
              Serial.println(F("TURN 4 OFF"));
              digitalWrite(out4, LOW);
            }
            else {
              Serial.println(F("TURN 4 ON"));
              digitalWrite(out4, HIGH);
            }
            on4 = !on4;
          }

          // send html
          client.print(html);
          break;
        }
        if (c == '\n')
        {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r')
        {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
  }

}

// errorLoop prints an error code, then loops forever.
void errorLoop(int error)
{
  Serial.print(F("Error: ")); Serial.println(error);
  Serial.println(F("Looping forever."));
  for (;;)
    ;
}

```

# Answer
> 0 votes
It's an issue using String with arduino. I've changed to use char\[\] and now it is working fine.

# Answer
> 0 votes
In `serverDemo()` you are setting `currentLineIsBlank` to `true`. Then you are reading in each char until you get to a `\n` at which point you are assuming the http request has ended.

```
boolean currentLineIsBlank = true;
....

// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank)

```

I think you want to set `currentLineIsBlank` to `false` to begin with ?...

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


title: How to improve wiring a breadboard?

text:
# Question
Title: How to improve wiring a breadboard?
just saw this tweet and was interested what wires are used there:

https://twitter.com/EngineersGarage/status/448014811280842752/photo/1

The wiring Looks cleaner than the setup I currently have with "normal" wires.

Thanks!

# Answer
> 6 votes
I think the wire itself is perfectly normal. It looks like he's simply soldered right-angled header pins onto the ends. That way, the wires can lie flat on the breadboard instead of being bent over for connections, meaning the whole thing is lower-profile and a little easier to route neatly.

It also has the advantage that they will probably survive far more insertions/removals. With that said, it brings the disadvantage that it exposes the contacts more above the surface of the board, which could increase the risk of accidental connections (short circuits and such like).

# Answer
> 1 votes
Using good wires helps to build clean breadboard setups. I also found that it greatly helps to wire vertically only and to use the breadboard for horizontal connections. If you look at my picture, wires are always vertical. This is easy to achieve when you work with buses like I²C. As you can see, I also used horizontal lines from another breadboard as you can use these like Lego bricks, though you need to cut the adhesive tape in the back. For the wires, I used standard Solderless Breadboard Jumper Cable Wire that you can buy almost everywhere online.

You can also check other pictures on my blog: http://ouilogique.com/horloge\_cycles\_ultradiens/

---
Tags: wires
---


# Question
Title: Merging strings and constants causing scope errors
I'm getting a few errors when merging strings with constants.

Here's the pertinent code...

```
#define STATION_ID ABC123
#define STATION_PASS XYZ987

void loop(){
    String path = "/weatherstation/updateweatherstation.php?ID="+STATION_ID+"&PASSWORD="+STATION_PASS+"&dateutc=now&tempf="+celsiusToFahrenheit(temperature)+"&humidity="+String(humidity)+"&action=updateraw";
}

```

And then the errors...

```
weather.cpp:15:20: error: 'ABC123' was not declared in this scope
weather.cpp:64:66: note: in expansion of macro 'STATION_ID'

weather.cpp:16:22: error: 'XYZ987' was not declared in this scope
weather.cpp:64:90: note: in expansion of macro 'STATION_PASS'

```

Not sure where I'm going wrong on this.

# Answer
Maybe? Not sure, but give this a try.

```
#define STATION_ID "ABC123"
#define STATION_PASS "XYZ987"

```
> 1 votes

# Answer
Further optimization is:

```
#define STATION_ID "ABC123"
#define STATION_PASS "XYZ987"

void loop(){
    String path = "/weatherstation/updateweatherstation.php?ID=" STATION_ID "&PASSWORD=" STATION_PASS "&dateutc=now&tempf="+celsiusToFahrenheit(temperature)+"&humidity="+String(humidity)+"&action=updateraw";
}

```

This will remove some intermediate String variables in the expression, etc.
> 1 votes

# Answer
That is just so wrong on so many levels.

Firstly, you should really not use `String`, especially not for constants.

Secondly, you do not need to manually concatenate string constants at all.

Thirdly, there is very rarely ever any need to concatenate things together into a single string before using them. Instead you can in general send individual parts separately:

```
#define STATION_ID "ABC123"
#define STATION_PASS "XYZ987"

client.print(F("/weatherstation/updateweatherstation.php?ID="
               STATION_ID
               "&PASSWORD="
               STATION_PASS
               "&dateutc=now&tempf="));
client.print(celsiusToFahrenheit(temperature));
client.print(F("&humidity="));
client.print(humidity);
client.print(F("&action=updateraw\r\n"));

```

By having multiple string constants next to each other (such as `"string one " "string two"`) the compiler will automatically join them together (into `"string one string two"`) for you. No plus, no comma, no nothing - just place them next to each other. And always use `F()` for string constants.
> 1 votes

---
Tags: string, code-optimization
---


# Question
Title: Combining two codes to jump back and forth between them
I have a code for both a magnetometer, and a GPS, both written to give off just one reading at a time. I'm trying to make a sketch that is able to go back and forth between these two codes so I get both sets of data.

Here is the GPS Code:

```
#include <NMEAGPS.h>
#include <NeoSWSerial.h>

NeoSWSerial gpsSerial(3, 2);
NMEAGPS     GPS;
gps_fix     fix;

void setup()
{
Serial.begin(115200);
Serial.println( F("Run once!") ); // F macro saves RAM!

gpsSerial.begin(9600);
gpsSerial.println( F("$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28") ); // RMC & GGA only
gpsSerial.println( F("$PMTK220,1000*1F") ); // 1Hz update rate

waitForFix();
printFix();
}

void loop()
{
}

void waitForFix()
{
uint8_t fixes = 0;

do {
if (GPS.available( gpsSerial )) {
  fix = GPS.read();
  fixes++;
}
} while ((fixes < 2) && !fix.valid.location);

} // waitForFix

void printFix()
{
Serial.print( F("Time: ") );
if (fix.valid.time) {
if (fix.dateTime.hours < 10)
  Serial.print( '0' );
Serial.print(fix.dateTime.hours);
Serial.print(':');
if (fix.dateTime.hours < 10)
  Serial.print( '0' );
Serial.print(fix.dateTime.minutes);
Serial.print(':');
if (fix.dateTime.hours < 10)
  Serial.print( '0' );
Serial.print(fix.dateTime.seconds);
Serial.print('.');
if (fix.dateTime_cs < 10)
  Serial.print( '0' );
Serial.print(fix.dateTime_cs);
}
Serial.println();

Serial.print( F("Date: ") );
if (fix.valid.date) {
Serial.print(fix.dateTime.day);
Serial.print('/');
Serial.print(fix.dateTime.month);
Serial.print('/');
Serial.print( fix.dateTime.full_year() );
}
Serial.println();

Serial.print( F("Fix status: ") );
if (fix.valid.status)
Serial.print( (int) fix.status );
Serial.println();

if (fix.valid.location) {
Serial.print( F("Location: ") );
Serial.print( fix.latitude(), 4 );
Serial.print( F(", ") );
Serial.println(fix.longitude(), 4);
}

if (fix.valid.speed) {
Serial.print("Speed (knots): ");
Serial.println( fix.speed() );
}

if (fix.valid.heading) {
Serial.print( F("Angle: ") );
Serial.println( fix.heading() );
}

if (fix.valid.altitude) {
Serial.print( F("Altitude: ") );
Serial.println( fix.altitude() );
}

if (fix.valid.satellites) {
Serial.print( F("Satellites: ") );
Serial.println( fix.satellites );
}
}

```

Here is the Magnetometer Code:

```
#include <Wire.h> //I2C Arduino Library

#define address 0x1E //0011110b, I2C 7bit address of HMC5883

void setup(){
//Initialize Serial and I2C communications
Serial.begin(9600);
Wire.begin();

//Put the HMC5883 IC into the correct operating mode
Wire.beginTransmission(address); //open communication with HMC5883
Wire.write(0x02); //select mode register
Wire.write(0x00); //continuous measurement mode
Wire.endTransmission();
}
void loop(){

int x,y,z; //triple axis data

//Tell the HMC5883L where to begin reading data
Wire.beginTransmission(address);
Wire.write(0x03); //select register 3, X MSB register
Wire.endTransmission();

//Read data from each axis, 2 registers per axis
Wire.requestFrom(address, 6);
if(6<=Wire.available()){

x = Wire.read()<<8; //X msb
x |= Wire.read(); //X lsb
z = Wire.read()<<8; //Z msb
z |= Wire.read(); //Z lsb
y = Wire.read()<<8; //Y msb
y |= Wire.read(); //Y lsb
}

//Print out values of each axis
Serial.print("x: ");
Serial.print(x);
Serial.print("  y: ");
Serial.print(y);
Serial.print("  z: ");
Serial.println(z);

delay(250);

while(1);

}

```

I don't know if this is even feasible, considering my lack of coding knowledge, but thanks for looking into it

# Answer
The solution in short.

Although the link is **very stupid**, it shows very well what you have to do.

Pretty much make a code that combines both of them together. Put both setup in the new setup and carry on like that. Note that you have declared the serial monitor at 2 different baud rates so you can only pick one. Don't repeat previously declared things in your new code and you should be good to go.

---

Simple example:

Code 1:

```
const int buttonPin = 2;

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

void loop() {
  buttonVal = digitalRead(buttonPin);
  Serial.println(buttonVal);
}

```

Code 2:

```
const int potPin = A0;

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

void loop() {
  potVal = analogRead(potPin);
  Serial.println(potVal);
}

```

Fusionned code:

```
const int potPin = A0;
const int buttonPin = 2;

void setup() {
  pinMode(buttonPin, INPUT);
  Serial.begin(9600); //go for the lowest baud rate for reliability
}

void loop() {
  buttonVal = digitalRead(buttonPin);
  Serial.print(buttonVal);

  Serial.print("  -  ")

  potVal = analogRead(potPin);
  Serial.println(potVal);
}

```
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: "return" not working to break out of a loop
I'm fairly new to this, and I haven't been able to find any answers after searching repeatedly.

I have a Startscreen() function that I run during my setup sequence, and within that function i use various while loops and if/else conditionals. This function runs the startup screen of my program on my touch screen.

Well, when certain conditions are met inside a switch case, inside a while loop, I want to load my main screen and then immediately stop the whole Startscreen() function, like this:

```
LoadMainScreen();
return;

```

However, I end up seeing my main screen load up, and then my Startscreen() function continues!

Apparently, "return;" does not work as advertised. If I wanted to break out of the current loop, I'd use "break;", right?

So my question is, does it matter that I'm using return; inside a while loop, inside a switch case? How do I exit the whole top-level function completely?

I already tried breaking out of the function and going straight to my main loop this way:

```
LoadMeasScrn();
loop();
return;

```

and the same thing happens.

So here's (most of) my entire code:

```
//////////REMOVED/////////THANKS FOR YOUR ANSWERS/////////////

```

# Answer
Your second outermost if() clause in StartScreen(), the one that begins with `if (frametype == 0 || frametype == -1)`, contains an infinite while loop. That loop contains no `break` statements, and calls StartScreen() -- it recurses into itself!

Without my trying to follow the program logic, I can at least posit that the code is in a second or higher recursion when it calls `return`, thus returning to where it had called itself. So, yes, if that is correct, it will still be executing within StartScreen() after the return statement. The return statement wouldn't have "failed" in that case; it would have resumed the at the point where the its prior instance called itself.

If that sounds convoluted, it's because *it is*! There can be good reasons to recurse, *if* you intended to, your know in what circumstances the code will recurse, and you know that recursiing will stop before you run out of stack space. Carefully review your program logic; this may not be one of those instances....
> 1 votes

# Answer
This part is wrong, for a start:

```
LoadMeasScrn();
loop();
return;

```

That would recursively call `loop` (which you almost never want to do) effectively putting you into `loop` a second time.

`return` does what is advertised to do. Your rather complex pseudo code demonstrates nothing. Please post a Minimal, Complete, and Verifiable example

---

> It's 800 lines long, anyway, so I doubt anyone would want to sift through it

I would much rather read 800 lines of code than try to **guess** what you are doing.

---

You have an incredible amount of recursion. You possibly think that if `StartScreen` calls itself then it goes back to the start (like a **goto**) but no, you are now two levels deep into `StartScreen`.

Plus here:

```
void StartScreen(void) {
...
  if (stuff)
...
                Recheckframe();

```

...

```
bool Recheckframe(void) {//For use in start screen, function rechecks frame
...
  if (otherstuf)
...
        StartScreen();  //Start all over
        }

```

It's a wonder it doesn't just crash by running out of RAM.

You say "//Start all over" but it **isn't** starting all over. You are now digging deeper and deeper into the call stack.

Your call stack will look something like:

```
StartScreen -> StartScreen -> Recheckframe -> StartScreen

```

You need a rewrite, frankly. A state machine would probably be very appropriate.
> 0 votes

---
Tags: programming
---


# Question
Title: Arduino IDE in conflict with pyserial for use of serial port in OSX Yosemite
I'm trying to communicate with an Arduino Uno via pyserial using a code that I wrote for Ubuntu. However, when I try to use the same code in OSX Yosemite after identifying the serial port for the case of OSX, it doesn't work. This is the offending line:

```
In [32]: ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

```

If I run the above line when the Arduino IDE is not running there is no error message, but the Arduino doesn't do anything (the Arduino IDE Serial Monitor must be open in order for the code to work). However, if I open the Arduino IDE and use the Serial Monitor (which works fine, i.e. it shows data that the Arduino is sending), I get the following error message:

```
SerialException: [Errno 16] could not open port /dev/cu.usbmodem1421: [Errno 16] Resource busy: '/dev/cu.usbmodem1421'

```

If I run `lsof | grep /dev/cu.usbmodem1421` then I get that the only program using said port is Arduino IDE:

```
Arduino   2012 germanchaparro   94u     CHR               18,7   0t15249    1285 /dev/cu.usbmodem1421

```

Clearly OSX is not letting Arduino IDE and pyserial to use the serial port (to which the Arduino UNO is connected) at the same time. I don't know how to fix this, and it's especially frustrating since Ubuntu doesn't put up a fight.

Any ideas?

# Answer
> 1 votes
Ok, I solved it. First I stopped using the IDE serial monitor as Majenko suggested, and focused on getting the Arduino readings within the python code. Besides trying to use the python code and the IDE monitor at the same time (which apparently you can do in Ubuntu but not in OSX), the original problem was that my python code was not clearing the serial buffer in the r/w process. In order to do this, I wrote the following function to be called before and after a serial write:

```
 ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

 def readarduino(ser):
    did=True
    while ser.inWaiting(): # Check number of characters left in buffer
        if did and ser.inWaiting() < 490: # Select last 500 characters in buffer
            for i in range(6):
                print ser.readline() # Print 6 lines in buffer
            did = False
        ser.readline()  # Clear buffer line by line until ser.inWaiting goes to 0

```

This ensures that the buffer is clear whenever I am writing to the Arduino.

This solution works for OSX Yosemite and Ubuntu 14.04

---
Tags: arduino-uno, serial, arduino-ide, ubuntu, osx
---


# Question
Title: MPU-6050 + Arduino Micro + nRF24L01 FIFO overflow!
So I have an Arduino Micro, nRF24L01, and MPU-6050 all attached together and its transmitting information to another nRF24L01 on an Arduino Uno. The problem is that I keep getting FIFO overflow on the sending side. If I leave the sensor holding still it goes going for some time, but when I start moving the sensor around it halts, like it can't take that much data when the sensor is moving around. So I think its something with the code:

```
// Include libraries necessary for the radios
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//set up name for serial communication of the radio
RF24 radio(9, 10);

// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */

/* =========================================================================
   NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
   when using Serial.write(buf, len). The Teapot output uses this method.
   The solution requires a modification to the Arduino USBAPI.h file, which
   is fortunately simple, but annoying. This will be fixed in the next IDE
   release. For more info, see these links:

   http://arduino.cc/forum/index.php/topic,109987.0.html
   http://code.google.com/p/arduino/issues/detail?id=958
 * ========================================================================= */

// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
//#define OUTPUT_READABLE_QUATERNION

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_EULER

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// We are using this output to obtain global coordinate acceleration
//and euler angles (coordinate system irrelevant)
#define OUTPUT_READABLE_WORLDACCEL_AND_GYRO

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT

#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 12; // 400kHz I2C clock (200kHz if CPU is 8MHz). Comment this line if having compilation difficulties with TWBR.
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    //Serial.begin(115200);
    //while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
    // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.

    // Initialize radio communication
    radio.begin();
    radio.setRetries(15, 15);
    radio.openWritingPipe(0xF0F0F0F0A1LL);

    radio.stopListening();

    Serial.begin(115200);

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    /*
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again
    */

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(54);
    mpu.setYGyroOffset(15);
    mpu.setZGyroOffset(33);
    mpu.setZAccelOffset(1613); // 1688 factory default for my test chip
    mpu.setXAccelOffset(-4009);
    mpu.setYAccelOffset(332);

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);

}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
        // .
        // .
        // .
        // if you are really paranoid you can frequently test in between other
        // stuff to see if mpuInterrupt is true, and if so, "break;" from the
        // while() loop to immediately process the MPU data
        // .
        // .
        // .

    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        char fifo_text[]="FIFO overflow!";
        radio.write(&fifo_text, sizeof(fifo_text));
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {

        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL_AND_GYRO
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion

            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            //Serial.print("aworld\t");
            //Serial.print(aaWorld.x);
            //Serial.print("\t");
            //Serial.print(aaWorld.y);
            //Serial.print("\t");
            //Serial.print(aaWorld.z);
            //radio.write(&aaWorld.z,sizeof(aaWorld.z));
            //String x=String(aaWorld.x);
            //const char*text=x.c_str();

            /*
            char x_text[]="X acceleration";
            radio.write(&x_text, sizeof(x_text));
            */
            typedef struct Value {
              int x;
              int y;
              int z;
              int e0;
              int e1;
              int e2;
            } Value;

            Value value;

            value.x=aaWorld.x;
            value.y=aaWorld.y;
            value.z=aaWorld.z;

            /*
            float acceleration[3];
            acceleration[0]=aaWorld.x;
            acceleration[1]=aaWorld.y;

            char x_value[8];
            char y_value[8];

            dtostrf(aaWorld.x,5,2,x_value);
            dtostrf(aaWorld.y,5,2,y_value);
            //char* coordinates[]={x_value,y_value};
            //char* coordinates[]={x_value,y_value};
            int coordinates[]={aaWorld.x,aaWorld.y};
            //radio.write(&y_value, sizeof(y_value));
            //radio.write(&coordinates, sizeof(coordinates));
            */

            //Serial.println(aaWorld);
            mpu.dmpGetEuler(euler, &q);

            //Serial.print("euler\t");
            int euler_0=euler[0] * 180/M_PI;
            value.e0=euler_0;
            //Serial.print("\t");
            int euler_1=euler[1] * 180/M_PI;
            value.e1=euler_1;
            //Serial.print("\t");
            int euler_2=euler[2] * 180/M_PI;
            value.e2=euler_2;
            //euler=(int[3])euler;
            //int euler[]={1,2,3};
            //Serial.write(euler*180/M_PI,3);
            //delay(50);

            radio.write(&value, sizeof(value));
            Serial.println(aaWorld.z);

        #endif
    /*
        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif
*/
        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}

```

# Answer
> 2 votes
I found the problem, I had to comment `out_put_readable_realaccel`. So it had to be `//#define OUTPUT_READABLE_REALACCEL` because it was running the yaw pitch and roll and the real acceleration at the same time so it was overloading.

Posted on behalf of the OP.

---
Tags: nrf24l01+, arduino-micro, mpu6050
---


# Question
Title: How to move my robot in the right direction?
After all there is more question poping up then answers i decide to upload the pdf where is everything writen, like the wire, motor type and what we can and can't use. Here is the link pdf format of the assignment

So i am working on a project for the school, it is first time for me to work with Microcontrollers. I and i got stuck with the rest of my assignment, so i hope a good soul can help me out with this.

So my code for now is this

```
#include <stdio.h>
#include "dev/uart.h"
#include <util/delay.h>
#include <avr/io.h>
#include "dev/adc.h"

#define LED_RED     (1 << PE5)
#define LED_YELLOW  (1 << PE3)
#define BUTTON      (1 << PF2)
#define SENSOR      (1 << PF3)
#define PUSH        (PINF & (BUTTON))
#define TILT        (!(PINF & (SENSOR)))

#define JOYSTICK_X  (1 << PF0)
#define JOYSTICK_Y  (1 << PF1)

typedef struct
{
    uint16_t x;
    uint16_t y;
} inputVector;

typedef struct
{
    int16_t x;
    int16_t y;
} convertedVector;

void joystick_init()
{
    adc_init(0x03);
}

convertedVector joystick_status()
{
    inputVector newVector;
    convertedVector vector;
    newVector.x = adc_get(0);
    newVector.y = adc_get(1);

    inputVector max;
    max.x = 896;
    max.y = 902;

    inputVector min;
    min.x = 8;
    min.y = 9;

    vector.x = 0;
    vector.y = 0;

    if(newVector.x >= 498 && newVector.x <= 518)
    {
        vector.x = 0;
    }
    else if(newVector.x < 498)
    {
        vector.x = ((newVector.x * 100) / 901) - 100;
    }
    else
    {
        int16_t half = 896/2;
        vector.x = ((newVector.x * 50) / half);
    }

    if(newVector.y >= 492 && newVector.y <= 512)
    {
        vector.y = 0;
    }
    else if(newVector.y < 492)
    {
        vector.y = ((newVector.y * 100) / 901) - 100;
    }
    else
    {
        int16_t half = 901/2;
        vector.y = ((newVector.y * 50) / half);
    }

    printf("x: %d, y: %d\n", vector.x, vector.y);

    return vector;
}

int main(void) {
    uart_init(9600);
    //uint8_t counter = 0;

    DDRE |= (LED_RED); /* OUTPUT */
    DDRE |= (LED_YELLOW);

    DDRF &= ~(BUTTON);  /* INPUT */
    DDRF &= ~(SENSOR);

    /*      JOYSTICK       */
    DDRF &= ~(JOYSTICK_X);  /* INPUT */
    DDRF &= ~(JOYSTICK_Y);
    joystick_init();

    while (1){

        if(!PUSH && !TILT)
        {
            PORTE |= (LED_RED);
            PORTE |= (LED_YELLOW);
            _delay_ms(50);
            PORTE = 0;
            _delay_ms(50);
        }

        if(PUSH && !TILT)
        {
            PORTE |= (LED_RED);
            _delay_ms(50);
            PORTE = 0;
            _delay_ms(50);
        }

        if(!PUSH && TILT)
        {
            PORTE |= (LED_YELLOW);
            _delay_ms(50);
            PORTE = 0;
            _delay_ms(50);
        }

        if(PUSH && TILT)
        {
            PORTE |= (LED_RED);
            _delay_ms(500);
            PORTE = 0;

            PORTE |= (LED_YELLOW);
            _delay_ms(500);
            PORTE = 0;
        }

        joystick_status();
        //_delay_ms(100);
    }
    return 0;
}

```

What it does now it reads the input values from joystick and it can be (x or y) min: 8 and max: 900, but we need to map it to \[-100,100\] this works but not perfect, so if someone can help to do the mapping better i would be grateful, but that is not the main point of my question.

But my real question is how i can programm the MCU to generate PWM signals ?

I need to implant those 3 functions :

* servo\_init(), to initialize the timer/counter2;
* servo\_left(int v), to set the angular velocity of the left wheel;
* servo\_right(int v), to set the angular velocity of the right wheel;

There are four registers to be set during the initialization: TCCR2A, TCCR2B, OCR2A, OCR2B.So what they mean ?

The two functions servo\_le f t(intv) and servo\_right(intv) set the corresponding Output Compare Register to control the pulse duration of the output control signal. The input parameter v of each function is an integer in the range \[−100, 100\] whose absolute value is proportional to the angular velocity of the corresponding servomotor and whose sign defines the direction of rotation. As overall, these functions map the input range \[−100, 100\] to the output range \[1.0, 2.0\] ms which corresponds to the pulse duration of the control signal, thus the angular velocity and rotation direction of the servomotor. Notice that, as the two servomotors are symmetrically mounted, one of the two functions has to invert the direction of rotation.

**Right wheel** : PortB, pin 4, **Output Compare Register** : OC2A, **TinkerKit Conn**: O1

**Left wheel** : PortH, pin 6, **Output Compare Register** : OC2B, **TinkerKit Conn**: O2

I spend all day on the internet finding anything that would help out, but i didn't have any luck.

# Answer
**||-----PWM Register Explanation-----||**

It will be easier to explain with an example.
Here is a sample of Timer setup on ATMega2560 (assuming that is the one you use due to the tag "Arduino-mega") based on datasheet section 20 : 8-bit Timer/Counter2 with PWM and Asynchronous :Operation:

```
TCCR2A= 0b10110001; //set COM2A1, COM2B1, COM2B0 and WGM20
TCCR2B= 0b00000001; //set CS20

```
* WGM22,WGM21, and WGM20 --\> 001 ==\> Using Phase correct PWM mode
* COM2A1, COM2A0 --\> 10 ==\> Clear OC2A on Compare Match when up-counting, and Set OC2A on Compare Match when down-counting
* COM2B1, COM2B0 --\> 11 ==\> Set OC2B on Compare Match when up-counting, and Clear OC2B on Compare Match when down-counting
* CS22, CS21 and CS 20 --\> 001 ==\> No clock prescaling

COM2A1, COM2A0 set the Timer2A on non-inverting mode, and COM2B1, COM2B0 set the Timer2B on inverting mode.

OCR2A and OCR2B is the duty cycle value of PWM. Because timer2 is 8 bit, so the value is ranging from 0-255. Its also the answer to your question

> How i can program the MCU to generate PWM signals ?

PWM Signal frequency is defined by its duty cycle :

> Duty cycle of Timer2x = (OCR2x/255)\*100%

for example :

```
OCR2A = 100;
OCR2B = 155;

```

Timer2A will work on 39.2% duty cycle and OCR2B will also work on 39.2% duty cycle. **What?** Because Timer2B works on inverted mode (100%-60.8%) ==\> 39.2%

**||-----PWM topic closed here-------||**

I've seen several people losing several hair while trying to control analog servo without manually (well, some even move to Arduino only because of its servo libs).
You can check this Servo Library which is (maybe) the most common library used to control servo using Arduino (which also mentioned in @st2000 answer).
**But**, it will be better if you also post a detail about your "motorservo". At first I though it was a motor DC (by its PWM - Dir configuration).

**||-----Additional-----------------------||**
In your `while(1)`, there are several `if` that can be optimalized by using simple `if-else if-..` statement. So this one would be better (also minimalized "bug" chance) :

```
while(1)
{
  if(!PUSH && !TILT)
       {...} else
  if(PUSH && !TILT)
       {...} else
  if(PUSH && TILT)
       {...} else
...
...
}

```

**--EDIT--**
After reading several page of the PDF, I assume you have to make your own library (not Arduino). Perhaps this will give you something :

```
void servo_init(void)
{
 TCCR2A= 0b10110001;
 TCCR2B= 0b00000001;
 /*phase correct PWM mode,
  *no clock prescaler,
  *Timer2A -> non inverted,
  *Timer2B -> inverted
  */
}

void servo_left(int v)
{
 int convertedvalue =//map angular velocity of left servo into 0-255
 OCR2A = convertedvalue;
}

void servo_right(int v)
{
 int convertedvalue = //map angular velocity of right servo into 0-255
 OCR2B = convertedvalue;

}

```
> 3 votes

# Answer
Your question is confusing. It appears you are creating code for an Atmel processor which directly interfaces with hardware. Atmel does make some of the processors used in Arduinos. However, all Arduinos abstract the hardware using libraries with very simple APIs. For example, to control a servo motor an application written in the Arduino paradigm only needs to include the servo header file, instantiate an instance of the servo class, call a servo class method to indicate which pin the servo is connected to then call a servo class method with a value equal to the angle the servo motor is to move to:

```
#include <Servo.h>

Servo myservo;

void setup()
{
  myservo.attach(9);
  myservo.write(90);  // set servo to mid-point
}

void loop() {}

```

If you decide to switch to the arduino paradigm, the above code should be all you need to control your normal servo motors.

On the other hand, you may be using continuous servo motors. Again, this is confusing because you did not say what type of servos you are using. But it may be that the angle in the above example will actually be interpreted as a speed when dealing with continuous servo motors.
> 0 votes

---
Tags: arduino-mega, pwm, servo, c
---


title: connecting lv maxsonar ez arduino

text:
# Question
Title: connecting lv maxsonar ez arduino
I am not 100% sure this question relevant here , but question is I have lv maxsonar ez which need 5v. I am powering my uno with 9v battery. And I have few other sensors also connected to 3.3v. But I have neopixel 3 meter LED which is powering with external power source which is 5v 4 amp. So My question is shall I connect my sonar sensor to the external power or keep with my uno 5v power ?

Thanks

# Answer
> 2 votes
I think the question is still relevant.
You should keep the maxsonar powered from Uno power if you don't want to burn it. Even if you use 9v Battery, Arduino Uno have internal 5v regulator. So it would be safer to supply the sensor from Arduino 5V (**not Vin**) pin.

---
Tags: arduino-uno, sensors
---


# Question
Title: What is an easy way to power a 3.3v BMP-180 barometer board from a 5v Arduino Nano?
## Scenario:

I have a functioning weather station (temp/humid, MQ-2 smoke sensor, anemometer), and want to add a barometer. The weather station is outside, linked to my inside display and RTC by the I2c&Power modules and ethernet cable. The cable supplies 12v and I use a small converter to provide the 5v to run the I2c&Power board and the rest.

So I have 12v and 5v available out at the weather box.

Inside along with the RTC and LCD display I have a 2-port I2C&Power which will be used in the future (with the new pgpio library) to feed the info to an Rpi3 to create a web page to show changes over time.

The barometer module I bought is the BMP-180. It is nice and tiny and looks perfect for the job, but the instructions all over the web tell me that it will burn up if powered by 5V. The Arduino Nano does not have a 3.3v output pin like the Uno does.

Q: What is the easiest way to accomplish adding this 3.3v board to the weather station?

# Answer
Here is the solution I settled on: a small part that will step 5 volts down to 3.3 volts. The price is right, but it will be shipped by the slow boat so will take a month or so to receive.

5Pcs 5V to 3.3V DC-DC Step-Down Power Supply Buck Module AMS1117 LDO 800MA

http://www.ebay.com/itm/5Pcs-5V-to-3-3V-DC-DC-Step-Down-Power-Supply-Buck-Module-AMS1117-LDO-800MA-/261983164332

It has 3 pins - Vin, Vout, GND. Easy to hook up.

Upvote to everybody for the discussion.
> 3 votes

# Answer
Consider attaching your +5V supply to a USB plug, and using that to power the Nano via its USB socket.

When the Nano is powered via its USB socket, the CH340 or FTDI FT232 supply up to 50mA of 3.3V power to the 3V3 pin located between Aref and d13. See for example 3v3 output from FTDI chip on Arduino Nano 3 at arduino.cc.

Actually, that thread apparently says the 3V3 is available no matter how the board is powered; you may want to run some tests and measurements. The only test I ran was to measure about 3.2 V at the 3V3 pin when a clone Nano 3 with CH340 was connected to a USB-power adapter.
> 3 votes

---
Tags: sensors, arduino-nano
---


# Question
Title: Calculate time between 2 data of a sensor
I'm working on a project in my university and I'm having a trouble in calculate time. I have a conveyor and an IR sensor which I use to calculate the maximum and minimum distances of a box when it is moving on the conveyor. Then I want to calculate the time between the max and min distances of box. I have used millis() for timing but it is not accurate. Here is my code:

```
int IRpin = 0;
float volts, distance,firstdata;
int k = 0;
float min;
float mang[150];
int m;
void setup() {
Serial.begin(9600);
}

void loop() {
volts = analogRead(IRpin) * 0.0048828125;
distance = 13 * pow(volts, -1.10);
if (distance < 20)
{
Serial.println(distance);
mang[k] = distance;
k++;
}
else
{
if (k > 0)
{
  min = mang[0];
  for (int i = 1; i < k; i++)
  {

    if (min > mang[i])
    {
      min = mang[i];
      m = i;
    }
  }
  firstdata=mang[1];
  }

```

I store data the sensor send to me in an array. Now I want to calculate the time between firstdata \[mang(1)\] and \[(min)\]. I use 0A41SK Sharp IR sensor. Thank you for your time and sorry for my bad english.

# Answer
Ok, yea...Please format this a little better (properly tabbed line spacing and such), and comments would go a long way to understanding this, because chances are people don't want to invest the time to decipher what's going on here without them. I'm not entirely sure what is going on here, but I'll just suggest what I would do in my understanding of the question, which is how to detect what the minimum and maximum value of the distance is and record the time at which each of these moments occurred.

I would have a float value to store the maximum and minimum distance as well as their times, and simply on every iteration of the loop check if the position was greater than the previous maximum distance or shorter than the previous minimum distance. If either of those are true, set the maximum/minimum distance to the current position and set the maximum/minimum distance time to the current time, using millis(). There's no reason I can see, if I'm understanding this correctly for an array to store all the data, it's just taking up memory space from what I see.

Hope this helps a bit, and, if I'm totally off base, again I'll emphasize the utility of comments in readability. Hope this helps and good luck.
> 1 votes

# Answer
I dont care much about code formatting, so i'll just leave you with 'indent' to satisfy the coding snobs that may have been flogged just a bit too hard by their programming teachers.. To the point (one of them) now; You're using int for your measurements against millis(). This will not fly if your measurements exceed 32 seconds, or if the runtime of the sketch exceeds 32 seconds. Please use unsigned long for all variables referencing millis().
> 1 votes

# Answer
I'm not exactly sure what you're trying to achieve with your code but from what i understood is that you're taking distance measurements to see if an object is front of your sensor and then you want to measure the time interval between each object passing by ....right?

Assuming my understanding is correct, what you need to do is first measure the distance to know if an object is there or not, and then if there isnt an object you start a 'timer' until an object appears and then print thy data to Serial Monitor....

```
//this is a comment...they make code easier to use and understand for you and others .....
int IRpin = 0;
float volts, distance,firstdata;
//don't Know why you need those...
/*int k = 0;
float min;
float mang[150];
int m;*/
boolean Exists;
boolean measured;

int startTime;
int Interval;
void setup() {
Serial.begin(9600);
}

void loop() {
volts = analogRead(IRpin) * 0.0048828125;
distance = 13 * pow(volts, -1.10);
if (distance < 20) //an object is in front of the sensor
{
Serial.println(distance);
Exists = true;//object is present
}
else
{
Exists = false; object isn't present
}

    if (Exists == false) {// no object present

if(measured == false){//to see if the timer already began
    startTime = millis();
    measured = true;// so the code only runs once
    Read = true; //so that we only measure the time when the timer begins
    }}
else
{ if(Read == true){
Interval = millis() - startTime;
measured = false;

Read = false;

Serial.print(Interval);
}}

```

What I'm trying to do in the last snippet is to make sure that we only measure the time when nothing is present.
> 0 votes

---
Tags: arduino-uno, sensors, time, ir
---


title: arduino not loading library

text:
# Question
Title: arduino not loading library
I am receiving a compilation error from

```
#include <HX711.h>

```

The error is

```
fatal error: HX711.h: No such file or directory

```

However, C:\Users\user\Documents\Arduino\libraries\HX711 is there and has the correct files in it. Sketch -\> Include Library -\> Manage libraries says that HX711 is installed. Strange thing is that I have another sketch that uses this library and it compiles. It uses quotes instead of angle brackets (which is strange because HX711.h is not in the same directory) and it works. I have tried both quotes and angle brackets.

EDIT: I am really sorry about typing "define" instead of "include" into the question my only excuse was that it was late. I copied the library directory to:

```
C:\Program Files (x86)\Arduino\libraries

```

and the problem remains.

I now have the HX711 directory in both the Arduino program files and the user directories and it still complains about it. The only way I can get it to compile is to place the hx711.h & hx711.cpp files directly into the sketch directory and change the line to #include "HX711.h"

EDIT: Running Arduino 1.6.5 on Windows 8.1 64bit

# Answer
> 2 votes
You're using `#define` when it should be `#include`.

# Answer
> 0 votes
Is the line of code really

```
#define <HX711.h>

```

If it is then replace `<` with `<` and that will fix it.

If the include statement has angle brackets \<\> around it then the file should be located in the system library folder, `C:\Program Files\Arduino\Libraries` on Windows. I think there can now be a user library folder as well `C:\Users\PHemans\Documents\Arduino\Libraries` and I *think* that the \<\> include will pick up from here too.

If the file is in you local folder (same place as the ino) then you should use "" the file name.

It is also possible that what you are seeing is not what the compiler is seeing, so deleting the whole line and then retyping it can sometimes work, as can checking the file endings and encodings using a tool like Notepad++.

---
Tags: library
---


# Question
Title: Odd symbols in ESP8266 responses to AT commands
I used the code below to control an ESP8266. I am getting some unknown symbols in the responses.

```
#include <SoftwareSerial.h>
const byte rxPin=2;
const byte txPin=3;
SoftwareSerial ESP8266( rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200);
  delay(1000);
  // put your setup code here, to run once:

}

void loop() {
  Serial.println("sending an AT command");
  ESP8266.println("AT");

  delay(100);
  while(ESP8266.available())
  {
    String inData = ESP8266.readStringUntil('\n');
    Serial.println("Got Response:" + inData);
    delay(1000);
      ESP8266.println("AT+RST");
    }
  // put your main code here, to run repeatedly:

}

```

The unknown symbols are shown in the screen shot.

What might the problem be?

# Answer
I nutted over this for quite a while. If you look up the reference for SoftwareSerial - https://www.arduino.cc/en/Reference/SoftwareSerial \- and look at the limitations, you'll find that it won't work above 57k baud rate and pins 2 and 3 wont support change interrupts, whatever they are. Sometimes I think some of these projects are untested. I think I'll use the hardware ports on two arduinos and use SoftwareSerial on the right pins and baud rate to get the two arduinos to communicate, or use Software serial to talk to the pc through a MAX232. I don't think you'll get a 115200 baud esp to talk SoftwareSerial
> 1 votes

---
Tags: arduino-uno, serial, esp8266, softwareserial
---


# Question
Title: XL335B accelerometer reports false readings
I'm using an XL335B accelerometer in a GY-61 breakout board. I'm powering the device using the UNO's built-in 3.3V power supply. The following code should convert the readings to m/s² (SI); however, it returns (-0.43|-0.52|-5.83) instead of the expected (0|0|-9.81) when lying untouched.

**Code:**

```
const float CYCLE_LENGHT_MILLIS = 1000;

// REFERENCE_VOLTAGE 5 & STEP_COUNT 1024
// => VOLTAGE_STEP 0.0048828125
// MAX_ACC_VOLTAGE 3.3
// => MAX_ACC_VOLTAGE_STEP 675.84
// MIN_ACC_VOLTAGE 1.65 = 0.5 MAX_ACC_VOLTAGE
// => MIN_ACC_VOLTAGE_STEP 337.92
// MAX_ACC_MEASUREMENT 29.43 = 3g

// acceleration = (read()-MIN_ACC_VOLTAGE_STEP) * MAX_ACC_MEASUREMENT/(MAX_ACC_VOLTAGE_STEP-MIN_ACC_VOLTAGE_STEP)
//This can be simplified to: acceleration = read()*j - k
// => j = MAX_ACC_MEASUREMENT / (MAX_ACC_VOLTAGE_STEP-MIN_ACC_VOLTAGE_STEP)
// => k = MIN_ACC_VOLTAGE_STEP * j

const float j = 29.43/(675.84-337.92);
const float k = 337.92*j;

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

void loop(){
  Serial.print("(");
  Serial.print(analogRead(0) * j - k);  //X-AXIS
  Serial.print("|");
  Serial.print(analogRead(1) * j - k);  //Y-AXIS
  Serial.print("|");
  Serial.print(analogRead(2) * j - k);  //Z-AXIS
  Serial.println(")");
  delay(CYCLE_LENGHT_MILLIS);
}

```

# Answer
> 1 votes
You are assuming here that 3g will result in the maximum voltage of 3.3v. This is not correct. The datasheet says it's 0.3v/g so; 0g-voltage + 3 x 0.3v =\> 1.65 + 3\*0.3 = 2.55volt.

To get the g value use `(analogRead(0)-337.92)/61.44` (337.92 is the 0g voltage in steps; 61.44 is 0.3V is steps).

To get the acceleration is m/s² just multiply by 9.81; so `(analogRead(0)-337.92)/61.44*9.81`

Like you stated in the comments, the result isn't that accurate. Just have a look at the datasheet. e.g. Volt per G is typically 300, but can be anything from 270 to 330. Same thing goes for the 0g voltage; 1.35V to 1.65V. So quite a bit of difference can occur between one chip and the next. Even between the 3 axis inside one chip.

So the best thing is to calibrate all 3 axis. For the Z axis; just lay the sensor flat, and get the analogRead value (-1g value). Flip the sensor upside down and get the analogRead value (+1g value). Optionally place the sensor on it's side to get 0g value or just calculate the value in the middle of the above two value. The steps-per-g will be the difference between the two divided by 2 (`+1g - -1g = 2g`). Put this value and the 0g step-value into the formula. Repeat the procedure for the other 2 axis.

# Answer
> 0 votes
An effective but yet simple calibration is explained in https://chionophilous.wordpress.com/2011/08/26/accelerometer-calibration-ii-simple-methods/

> We need to find the 0G mark and the sensitivity on each axis. Call them m\_x, delta\_x, m\_y, delta\_y, m\_z, and delta\_z (e.g. m\_z is the zero-G mark or the “middle” on the z-axis, delta\_z is the sensitivity on the z-axis). That makes 6 numbers, so we should expect to need at least 6 measurements.

Check also the more accurate setup: https://chionophilous.wordpress.com/2011/08/26/accelerometer-calibration-iii-improving-accuracy-with-least-squares-and-the-gauss-newton-method/

> Least-Squares
>
> Here is the idea. We’ve been assuming that there are just six numbers we need to find to get a good calibration: m\_x, m\_y, m\_z, delta\_x, delta\_y, and delta\_z. Now matter how we place our sensor before we take readings, we assume it is still and is detecting exactly 1G of acceleration in some direction.
>
> So if we read value x on the X-pin, y on the Y-pin, and z on the Z-pin we can look at the acceleration vector
>
> If our measurements have no noise and our parameters are correct, the length of this vector should be exactly 1 no matter which way it is pointing

---
Tags: analogread, accelerometer
---


# Question
Title: Reverse engineering of a bluetooth sensor
I have a problem. I'm trying to trigger some events with Arduino using some bluetooth LE sensor by a chinese manufacturer, Kaipule. I buy this sensor on Alibaba and I'm trying to understand how can I interface them in my sketch.

They are magnetic contact sensors and I know that they have just the BLE broadcasting mode (no GATT, profile etc): they send information when I open the contact or I close the contact.

I try to scan them with a BLE scanner and this is the log

```
kCBAdvDataIsConnectable : 0
Local Name : iSensor
Manufacturer Data : <beca2c02 4602f9f7>

```

I know that:

1) the scanner can see the sensor just when I open/close the contact to save battery, so the sensor broadcast data just when it need.

2) every hour the sensor send a status signal

3) every time I open and close the contact the code change a little. Here is a sequence

```
<beca2c02 46025856> - > open
<beca2c02 46005955> - > close
<beca2c02 46025a58> - > open
<beca2c02 46005b57> - > close
<beca2c02 46025c5a> - > open
<beca2c02 46005d59> - > close
<beca2c02 46025e5c> - > open
<beca2c02 46005f5b> - > close

```

etc

4) The first part of the code is the identification of the sensor.

3) From the changing code I assume that 2 is the status open, 0 is the status close and I see also a pattern for other bytes but I cannot understand why for example there is a rolling code.

I have the paper the company send to me, but I cannot find any useful reference.

Wireless sensor 1 Wireless sensor 2

# Answer
Looking at the datasheet, I interpreted it as:

**Byte 1 - 0x46**

Indicating this is a unidirectional device (bit7=0) that uses fixed time sending (bit 6=1 *which doesn't seem correct*) and it is of type 'door contact' (bits 0-5=0x06)

**Byte 2 - 0x00/0x02**

Indicating that the door is open or closed (bit 1 = 0 or 1). I also **think** that it indicates there is 'enough battery power' (bit 2 = 0), and the 'anti-tamper' has not been activated (bit 0 = 0)

**Byte 3 - 0xXX**

This is the 'Frame ID' - counting up for 0x40, to 0x5F then looping ?

**Byte 4 - 0xXX**

Checksum.

I'd do three things to test this theory:

1. Run the battery down a lot and see if the battery power indicator changes (byte 2, bit 2).
2. Open the case and see if the 'anti-tamper' bit changes (byte 2, bit 0)
3. Do sufficient switching to determine if byte 3 loops around as expected.

This these don't work out then you're likely looking at a different model.
> 1 votes

---
Tags: arduino-uno, bluetooth
---


title: Problem with microSD SPI mode in AVR

text:
# Question
Title: Problem with microSD SPI mode in AVR
I'm trying to read a microSD block. But I don't know why it doesn't work.

I do:

```
CS_UP;
for(uint8_t i = 0; i <14; i++){ /* Send 74+ clocks */
    spi_tranceiver(0xff);
}
_delay_ms(1); /* Wait 1 ms */

//CS_UP;

/* Initizalize microSD */
put_string("Go to idle state\n");
while (Reset_Card() != 0x01) // Go to idle state
    ;

put_string("Send IF COND\n");
while (Send_CMD8() != 0x01) // SEND IF COND
    ;

put_string("Send ACMD41 and CMD55\n");
for (int i = 0; i<100; i++)
    while (Send_CMD55() && Send_ACMD41())
        ;

setBlockLen(); // Set block read in 512 bytes
CS_DOWN;
put_string("\nConfigure finished correctly\n");

```

And then I just call:

```
readSingleBlock(0x00, &buf)

```

readSingleBlock is defined as follows:

```
uint8_t readSingleBlock(uint32_t block_address, unsigned char *buf)
{
    int i;

    block_address = block_address << 9;

    CS_UP;
    while (0x00 != sdsc_command(READ_SINGLE_BLOCK, block_address))
        ;

    while (0xfe != spi_rx ())
        ;

    for (i = 0; i < 512; i ++ ){
        //buf [ i ] = spi_rx();
        put_int(spi_rx());
        put_string("\n");
    }
    spi_rx();
    spi_rx();
    CS_DOWN;

    //for (i = 0; i<512; i++) put_int(buf[i]);

```

The problem is that the printout is:

0 0 0 ..(zeros).. 128 255 255 255 12 255 255 255 0 8 0 0 0 72 59 ..(zeros).. 85 170

Did somebody encounter this problem?

Do you have some suggestions?

# Answer
> 1 votes
I formated the SD card, and then work correctly

Thanks!

---
Tags: avr
---


# Question
Title: Arduino calculator: I'm struggling to write a sketch which parses inputted characters
I am attempting to make a calculator with arduino using a 16x2 Text-LCD and a 4x4 keypad. I've already programmed the part where the arduino board gets input from the keypad and displays characters on the LCD respectively, but I'm struggling to program the part where the '=' button is pressed and the arduino parses the sum and gives the answer. I'm not using the RW lin to read the LCD, instead I am adding characters pressed to a char\[\] variable. Can you guys please give me some code to parse the inputted characters? Thanks!

EDIT: Code:

```
#include <LiquidCrystal.h>
#include <Key.h>
#include <Keypad.h>

char keys[4][4]={
  '/','x','-','+',
  '=','9','6','3',
  '0','8','5','2',
  'C','7','4','1'
};

byte rowPins[4]={7,6,5,4};
byte colPins[4]={3,2,1,0};

Keypad input=Keypad(makeKeymap(keys),rowPins,colPins,4,4);

LiquidCrystal lcd(8,9,10,11,12,13);
int inputSize=1;
char inputSum[16];

int cursorNum=0;

void setup() {
 lcd.begin(16,2);
}
void loop() {
  char key = input.getKey();
  if(key) {
    if(key == 'C') {
      lcd.clear();
    }else if(key == '=') {
      parseInput();
    }

    else{
    lcd.print(key);
    inputSum[cursorNum]=key;
    cursorNum++;
    }
  }
}

int result;
void parseInput() {
  //Parse code goes here

  lcd.setCursor(0,1);
  lcd.print(result);

}

```

# Answer
Characters in a char\[\] variable may be encoded in ASCII or Unicode. You will want to convert them to numbers in this case. ~~Consider subtracting the ascii value of one less than `0` from each char to get the number.~~ Edit: @Matt informed me that `0` is the lowest ASCII number. As he suggested, you can subtract the character `'0'` from the digit to get the value. You want to specially handle any addition, division, or other operator symbols.

Then you can treat each number like a digit in a number. If you can break up the array of numbers by the operators, you can successively attach the operands to the operators. Keep in mind that each number to the left is a power of ten (assuming this is how it's implemented. This is called Endianess.)

If you post code I may be able to help further.
> 2 votes

# Answer
You could parse it with something like this:

```
int parserr;

int parse(char* input)
{
  parserr = 0;
  if (input == 0) return (0);
  char* ip = input;
  char c = *ip++;
  if (c == 0) return (0);
  int res = 0;
  char op = 1;
  while (1) {
    int num = 0;
    int neg = 0;
    if (c == '-') {
      neg = 1;
      c = *ip++;
    }
    int isnum = isdigit(c);
    while (isdigit(c)) {
      num = (num * 10) + (c - '0');
      c = *ip++;
    }
    if (neg) num = -num;
    if (!isnum) op = 0;
    switch (op) {
    case 1: res = num; break;
    case '+': res = res + num; break;
    case '-': res = res - num; break;
    case '*': res = res * num; break;
    case '/': res = res / num; break;
    default:
      parserr = (ip - input - 1);
      return (res);
    };
    if (c == 0) return (res);
    op = c;
    c = *ip++;
  }
}

```

The variable `parserr` holds the error position (+1), zero is no parse error. The function `parse()` will return the value of the simple expression with no operator priority.

This can be refactored to allow normal operator priority:

```
#include <ctype.h>

class Calculator {
public:
  int eval(char* input, int& result)
  {
    if (input == 0 || *input == 0) return (0);
    m_ip = input;
    if (expr(result)) return (0);
    return (m_ip - input + 1);
  }

private:
  char* m_ip;

  char getc()
  {
    return (*m_ip++);
  }

  int ungetc(int res)
  {
    m_ip--;
    return (res);
  }

  int number(int& value)
  {
    int neg = 0;
    char c = getc();
    if (c == '-') {
      neg = 1;
      c = getc();
    }
    value = 0;
    if (!isdigit(c)) return (ungetc(0));
    do {
      value = (value * 10) + (c - '0');
      c = getc();
    } while (isdigit(c));
    if (neg) value = -value;
    return (ungetc(1));
  }

  int fact(int& result)
  {
    return (number(result));
  }

  int term(int& result)
  {
    if (!fact(result)) return (0);
    int value = result;
    char op;
    while ((op = getc()) != 0) {
      if (op != '*' && op != '/') return (ungetc(1));
      if (!number(value)) return (0);
      switch (op) {
      case '*': result = result * value; break;
      case '/': result = result / value; break;
      }
    }
    return (ungetc(1));
  }

  int expr(int& result)
  {
    if (!term(result)) return (0);
    int value = result;
    char op;
    while ((op = getc()) != 0) {
      if (op != '+' && op != '-') return (ungetc(0));
      if (!term(value)) return (0);
      switch (op) {
      case '+': result = result + value; break;
      case '-': result = result - value; break;
      }
    }
    return (1);
  }
};

```

Cheers!
> 0 votes

---
Tags: c++, lcd, mathematics
---


# Question
Title: Is the MKS GEN V1.2 compatible with Arduino IDE as Arduino MEGA Board?
I need to do a Servo controller using Arduino and I have a spare MKS GEN V1.2 board right now, looking at the documentation from here http://reprap.org/wiki/MKS\_GEN it seems this board is actually an Arduino board which can be programmed with the Arduino IDE.

Is this a correct observation that the MKS GEN V1.2 board is, in fact, a Arduino MEGA board internally?

# Answer
> 1 votes
> It features an onboard ATmega2560.

This means that it is *internally* compatible with the Arduino Mega 2560. This does not mean that it is *completely* compatible with such since of course there is no way to use Mega shields with the board. This also means that there may be a core that provides *better* facility with the board, supporting its connections (LCD, positioning, heater/fan, etc.) better than the generic Mega core would.

---
Tags: arduino-mega
---


title: SIM800L always returns +CREG: 0,2

text:
# Question
Title: SIM800L always returns +CREG: 0,2
I'm using a SIM800L module, and I am checking the status of my network with the `AT+CREG?` command.

However, it always returns the same 0,2:

```
0 -> disable network registration unsolicited result code

2 -> not registered, but ME is currently searching a new operator to register to

```

How do I activate 2G or 3G network?

# Answer
* It can take a while to register - sometimes several minutes. Have you left it after power-up for enough time?
* If your operator has no signal in your area it will never register. National roaming is normally disabled. If you have national roaming available you will have to manually connect to another operator.
* Check that your modem can see your operator with `AT+COPS=?`
> 1 votes

---
Tags: arduino-uno
---


title: Arduino weather vane

text:
# Question
Title: Arduino weather vane
My little weather station is run on a Nano and has the anemometer and the temp/humidity sensor. A smoke detector is on the way because I live where wildfire is a big concern.

I would like to build a simple weather vane without spending a lot to buy the commercial solutions. Rotary potentiometers have dead spots and using a bunch of hall effect sensors would use up too many digital inputs to be useful, afaik.

Question: How can I build a simple direction sensor?

# Answer
I decided to go with 4 reed sensors. With experimentation I found I can successfully detect 8 distinct directions using 4 reed switches since the rare-earth magnet will switch two on at once when it is in between.

Thank you all for your answers. Upvotes for everyone for the discussion.
> 1 votes

# Answer
Its a long time since I looked at this and the details are a bit misty, so sorry for the inaccuracies, but I'm sure people will correct them for me :)

I originally brought one of these http://www.maplin.co.uk/p/maplin-replacement-wind-direction-sensor-for-n96fyn96gy-n81nf and then decided to take it to bits, like you do.

The vane spins a magnet around and this triggers 1 of 8 reed switches as it passes around. The read switch is connected to VCC and a resistor and the resistors feed into a common wire back to the microprocessor. The 8 resistors all have different values, so the result is a differing output voltage depending on which reed switch has been triggered.

So what you need is:

* A magnet
* A number of read switches positioned far enough apart so only one is triggered at a time
* A number of different resistors

Supply 5V from you Nano and read the result on an analogue pin, then come up with a calibration table to work out the direction.

I hope that makes sense. (Sorry I can't draw you a circuit diagram)
> 2 votes

# Answer
Another option (similar to reed switches) is to do it optically.

The vane is on an axle. The axle has a disc attached to it. The disc has a small notch out of the edge.

Positioned around the edge are a whole series of photo-interrupters. The disc spins between the infra-red beams and the notch allows only one of them to pass light at a time.

Make the notch the right size so that as one interrupter turns off the next one turns on - you need one on all the time. You could over-compensate slightly so that on occasion two adjacent interrupters are on at once, in which case you can say it's between the two.

A similar system is to use a disc with a series of special slots cut in it (see Gray Code) which allow light to pass through onto a line of photodiodes. In different rotations different combinations of photodiodes are on, and that gives you your direction.
> 1 votes

---
Tags: sensors
---


# Question
Title: Can I switch a pulse solenoid from the onboard 5V/3.3V power source?
I have two pulse solenoids. One is 6V...

http://www.ebay.com.au/itm/282002733837?\_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

and the other is 3.6V...

http://www.ebay.com.au/itm/131989042565?\_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

I have a Wemos R2 Mini with an `ESP8266` chip on it, and I'm running the switching operation through a H Bridge motor shield (which handily switches the polarity of the electricity for a short time, which opens/shuts the solenoid).

I want to run this thing off a smallish battery pack that will supply 5V to the WeMos. I have three questions:

1) Can I send a 3.6V solenoid a 60ms pulse to open/shut it from a 5V power source without burning out the coil or causing any other damage?

2) Is 3.3V too low to power a 3.6V solenoid?

3) Do pulse solenoids still generate back EMF?

I don't know a lot about solenoids or electromagnetic fields so, sorry if my questions are noobish.

# Answer
> 1) Can I send a 3.6V solenoid a 60ms pulse to open/shut it from a 5V power source without burning out the coil or causing any other damage?

No. If it's 3.6V then you need 3.6V - 5V will most likely make it smoke. Use a regulator (preferably a buck one, since it is apparently 500mA) to power your H-bridge.

> 2) Is 3.3V too low to power a 3.6V solenoid?

Maybe, maybe not. It may be that 3.6V is the absolute maximum and may switch from 3V to 3.6V.

> 3) Do pulse solenoids still generate back EMF?

Normally, yes, since they are just a coil like any other inductive load. Your H-bridge should deal with that though if designed right.

To get any meaningful answers you will need a datasheet. Buying such things from eBay is never a good idea unless you have used it before and know what it is, what its specifications are, and how you use it, or they provide a link to a datasheet. Without a datasheet most questions will be answered with a "maybe".
> 1 votes

---
Tags: esp8266
---


# Question
Title: Limiting motors to a specific position using while and if loops
I am currently building a prosthetic hand using an Arduino MEGA, an Advancer Tech Myoware sensor, and 3 TB6612FNG Dual H-bridge breakouts. I have the EMG sensor sending an analog value to the Arduino and want to use that value to open or close the hand.

The problem I have is that the motors cannot turn more than 1 second without tightening too much and breaking the hand, so I want to place a limit on the while loop telling them to move that will restrict their movement under the specified conditions to one second. Also, when the analog voltage is no longer present, I need the motors to reverse their movement so the hand releases.

Here is the code I have where `move(motor #, speed, direction)` is the function to move the hand (1 = forward, 2 = backward).

```
void loop(){

  int EMGv = analogRead(EMG);

  while(EMGv >= 900){
    move(0, 255, 1); //motor 1, full speed, left
    move(1, 255, 1); //motor 2, full speed, left
    move(2, 255, 1); //motor 3, full speed, left
    move(3, 255, 1); //motor 4, full speed, left
    move(4, 255, 1); //motor 5, full speed, left

  }

```

To reiterate. I need the motors to move while the EMG value is over 900, BUT not move more than 1 second, even if the value is 900 for 5 seconds. I then need the motors to move one second backwards when the value dips below 900.

Thanks!

# Answer
You can use `millis()` feature

```
unsigned long starttime;

void loop(){

  int EMGv = analogRead(EMG);
  starttime=millis();
  while(EMGv >= 900){
    if (millis()-starttime < 1000) //limit on 1000ms
    {
    move(0, 255, 1); //motor 1, full speed, left
    move(1, 255, 1); //motor 2, full speed, left
    move(2, 255, 1); //motor 3, full speed, left
    move(3, 255, 1); //motor 4, full speed, left
    move(4, 255, 1); //motor 5, full speed, left
    } else {/*turn off motor here*/}
  }

```
> 2 votes

---
Tags: arduino-mega, pwm
---


title: error: stray '\' in program with servo

text:
# Question
Title: error: stray '\' in program with servo
I'm doing a project for school using Arduino to make a catapult, but I have this error that I didn't have the previous week.

Can anyone see the program and search where is the error?

```
#include <Servo.h> //libreria necesaria para utilizar el Servo

Servo catac; //motor de giro continuo utilizado

int ledPin = 13; //led conectado a agujero 13
int button = 8; //boton conectado a agujero 8
int estado = 0; //varaible que permite saber el estado del boton

void setup()
{
    pinMode(ledPin,OUTPUT);
    pinMode(button,INPUT);
    catac.attach(12); // servo unido al agujero 12
    catac.write(180); //coloca al servo en 180 grados
}

void loop()
{
    estado = digitalRead(button); //la variable obtiene el estado del boton
    if(estado == LOW)
    {
        digitalWrite(ledPin,HIGH); //prende led
        catac.write(70); //servo levanta a 70 grados la catapulta
        delay(500);
        digitalWrite(ledPin,LOW); //apaga led
        catac.write(180); //servo coloca a la catapulta en posicion original
    }
}

```

Error:

```
cataoukta:6: error: stray '\' in program
cataoukta:8: error: stray '\' in program
cataoukta:9: error: stray '\' in program
cataoukta:10: error: stray '\' in program
cataoukta:13: error: stray '\' in program
cataoukta:14: error: stray '\' in program
cataoukta:15: error: stray '\' in program
cataoukta:16: error: stray '\' in program
cataoukta:20: error: stray '\' in program
cataoukta:22: error: stray '\' in program
cataoukta:23: error: stray '\' in program
cataoukta:24: error: stray '\' in program
cataoukta:25: error: stray '\' in program
cataoukta:26: error: stray '\' in program
cataoukta:9: error: expected constructor, destructor, or type conversion before 'void'
cataoukta:6: error: expected initializer before 'u037e'
cataoukta.ino: In function 'void loop()':
cataoukta:20: error: 'estado' was not declared in this scope
cataoukta:20: error: 'button' was not declared in this scope
cataoukta:20: error: expected `;' before 'u037e'

```

# Answer
> 6 votes
You have bad Unicode characters in your code. All your semicolons are something completely different and need replacing with *real* semicolons.

---
Tags: arduino-uno, servo
---


title: read AM signal only with an Arduino

text:
# Question
Title: read AM signal only with an Arduino
Some people have managed to send simple AM signals with just a bare Arduino. An example is here. This works thanks to the fact that the PWM can reach high frequencies and, setting the divider properly, it is possible to broadcast a 1337 kHz carrier over a short distance with just a wire acting as an antenna. I know it's not that useful, but it's really nice as an educational tool.

I was wondering if it would be possible to apply the same concept, but for the receiver. For instance simply using a pulseIn() detection on a pin connected to an antenna. Would it be possible to detect the carrier, and, maybe, even demodulate a message, eg, in morse code?

If not, would just a adding an amplifier be sufficient? Any recommendations for the amplfier and the circuit?

Thanks very much for your suggestions.

# Answer
> 1 votes
Generating an AM signal is child's play compared to detecting one.

To generate a signal you just need to create an oscillation and vary the amplitude, which can very crudely be done with PWM.

That's simple.

To *receive* a signal you first need to *isolate* that signal. There's a huge number of signals and noise around all the time, and you need to *tune in* to the signal that you are interested in. That's what you are doing when you twiddle the dial on a radio. You're selecting which frequency to listen to.

And to do that requires a *tuned circuit* \- a kind of band-pass filter which isolates and amplifies the frequency you are interested in.

Imagine you are in a large hall filled with people. Every single person there is just standing around talking out loud - everyone is saying something different. Some are even just screaming, or whimpering in the corner. It's just a cacophony of noise. Impossible to know what is going on. That's what the air waves are like. You need some way of "tuning in" to one person's voice so you can understand what they are saying. As humans we often do that using sight, to watch a person's lips and our clever brains link the movement to the sound and help us pick out their voice. Coupled with our ability to select on the tonal qualities of a voice as well, we can pick out a single voice in the noise. That's what the tuned circuit does. It picks out one voice from the mayhem.

The Arduino can't do that. It would need to use some fairly sophisticated filtering algorithms, and it just doesn't have the power for that. Firstly you'd need to sample the raw RF noise at a minimum of twice the frequency you are interested in (so multi-mega-samples per second), and then you'd need to do digital filtering to isolate that one frequency. From then you'd need to do more filtering to demodulate the original signal from the modulated signal.

It's all possible to do in software, but not with an Arduino. It takes a good ADC and a DSP to do all the hard work.

Easier to just build a small tuned circuit from a few passive components.

# Answer
> 1 votes
AM (*Amplitude Modulation*) varies the amplitude of the carrier based on the input signal. So, assuming you had some circuitry (LC circuit) to receive a particular carrier frequency and managed to boost the voltage so that it was in the range 0-5v then you would able to feed this to an analog input on the Arduino.

AnalogRead requires around 100uS per sample, so your max sampling rate would be 10K/s, which might **just** cut it for voice (up to 3.4Khz, sampling at least 2 * the highest freq).

However, you then need to do something with the sample value (in code) and depending on how long that 'something' takes, your *actual* sample rate will be reduced.

---
Tags: pwm, rf, pulsein
---


# Question
Title: Combining arduino leonardo code with water alarm code
I need to create something for a school assignment, but I'm stuck at the moment.
I have one code, which makes the Arduino Leonardo press space button on my laptop, which works.

I have another code, that turns on the LED when 2 wires are put in water.

Now I want to combine them, but I have no success.

Hope someone will help me with this.

These are the codes:

**The keyboard code leonardo:**

```
bool eenkeergeweest = false;

#include <Keyboard.h>

void setup()
{
    // make pin 2 an input and turn on the
    // pullup resistor so it goes high unless
    // connected to ground:
    pinMode(2, INPUT_PULLUP);
    // initialize control over the keyboard:
    Keyboard.begin();
}

void loop()
{
    // while (digitalRead(2) == HIGH) {
    //   // do nothing until pin 2 goes low
    //   delay(500);
    //  }
    delay(1000);
    // new document:
    if (!eenkeergeweest) {
        eenkeergeweest = true;
        Keyboard.print(' ');
        delay(100);
        //Keyboard.releaseAll();
    }

    // wait for new window to open:
    delay(1000);
}

```

**The code for the water LED:**

```
int out = 12;
int in = 4;

int rd;

void setup()
{
    pinMode(out, OUTPUT);
    pinMode(in, INPUT);
}

void loop()
{
    rd = digitalRead(in);
    if (rd == HIGH)
    {
        digitalWrite(out, HIGH);
        delay(100);
    }
    else
    {
        digitalWrite(out, LOW);
        delay(100);
    }
}

```

# Answer
How do you want them to work ? Do you want the spacebar pressed when there is a high signal read (when the light goes on)?

If you want the space bar press when it goes high this might work:

```
#include <Keyboard.h>

bool eenkeergeweest = false;
int out = 12;
int in = 4;

void toggleKeyPress (const char& keypress)
{
    if (!eenkeergeweest)
    {
        eenkeergeweest = true;
        Keyboard.print(' ');
        delay(100);
    }
}

void setup()
{
    pinMode(out, OUTPUT);
    pinMode(in, INPUT);

    // initialize control over the keyboard:
    Keyboard.begin();

}

void loop()
{
    const int rd = digitalRead(in);
    if (rd == HIGH)
    {
        toggleKeyPress(' ');
        digitalWrite(out, HIGH);
        // wait for new window to open:
        delay(1000);
    }
    else
    {
        digitalWrite(out, LOW);
    }
}

```
> 1 votes

---
Tags: led, arduino-leonardo
---


title: Servo Control using Pushbutton

text:
# Question
Title: Servo Control using Pushbutton
I was trying to build a system that when the user pushes the button, the servo rotates 45 degrees and than returns back to zero. This system is going to be duplicated as there will be two servos and pushbuttons.

Here's my code:

```
#include <Servo.h>
Servo solservo;  // create servo object to control a servo
Servo sagservo;
// twelve servo objects can be created on most boards

int possol = 0;    // variable to store the servo position
int possag = 0;
int degsol=0;
int degsag=0;

int ledPin = 13; // choose the pin for the LED
int solPin = 7;   // Pushbutton
int sagPin = 8;     // variable for reading the pin status
int valsag = 0;
int valsol = 0;

void setup() {
  solservo.attach(9);  // attaches the servo on pin 9 to the servo object
  sagservo.attach(10);
  pinMode(solPin, INPUT);
  pinMode(sagPin, INPUT);
  pinMode(ledPin, OUTPUT);

}

void loop() {
  digitalWrite(ledPin, HIGH);    //Arka İsik
  valsag = digitalRead(sagPin);  // read input value
  valsol = digitalRead(solPin);
//Sag Servo

  if (valsag == HIGH) {
    sagservo.write(45);              // tell servo to go to position in variable 'pos'
    delay(100);                       // waits 15ms for the servo to reach the position
    sagservo.write(-45);

  }
//Sol Servo
  if (valsol == HIGH){
    solservo.write(45);
    delay(15);
    solservo.write(0);
  }

}

```

There'll probably be lots of small errors in this code, like unnecessary ints and such, but when I upload this program and push the button, it just rotates 45 deg, and doesn't come back. Is there a way that I can solve it?

Thanks in advance

# Answer
> 0 votes
Change `sagservo.write(-45);` to `sagservo.write(0);`.

---
Tags: arduino-uno, servo, button
---


# Question
Title: Running Stepper motors (at least 2) at the same time
Is there a way to run a Stepper motor with Arduino MEGA 2560 with A4988 driver component.

I am using this https://github.com/laurb9/StepperDriver library and with this code,

```
Serial.println("Starting motor ALL");
int steps = atoi(third.c_str());
int duration = atoi(fourth.c_str());

BasicStepperDriver stepper1(steps, DIR, STEP, ENBL);
stepper1.enable();
stepper1.setMicrostep(MICROSTEPS);
stepper1.setRPM(MAX_RPM);

BasicStepperDriver stepper2(steps, DIR_2, STEP_2, ENBL_2);
stepper2.enable();
stepper2.setMicrostep(MICROSTEPS);
stepper2.setRPM(MAX_RPM);

int starttime = millis();
int endtime = starttime;
while ((endtime - starttime) <= duration) // mS
{
     stepper1.rotate(90);
     stepper2.rotate(90);
     endtime = millis();
}
stepper1.disable();
stepper2.disable();
Serial.println("DONE");

```

The problem with this is that each stepper motor in this code waits for each other and not simultaneously like a DC motor. What could be done to make it work simultaneously?

# Answer
> 1 votes
Try the AccelStepper library. It can control both steppers at the same time. Also provides some useful examples

AccelStepper with more than one stepper also requires the Adafruit Motor library to be installed.

---
Tags: arduino-mega
---