body:
I am using this header: http://playground.arduino.cc/Interfacing/CPPWindows

My main:

    #include <iostream>
    #include <stdio.h>
    #include <tchar.h>
    #include "SerialClass.h"
    #include <string>

    int main(int argc, _TCHAR* argv[])
    {
     Serial* SP = new Serial("\\\\.\\COM4");

     if (SP->IsConnected())
      printf("We're connected\n");

     std::string tryStr;
        int value;
        DWORD bytesSend;

        /* Loop */
     while(SP->IsConnected())
     {
             /* Take a value from user */
             printf("Value: "); scanf("%d",&value);

             /* Send Arduino */
             BOOL retVal = WriteFile(SP->hSerial, &value, sizeof(value), &bytesSend, NULL);

            /* I have no idea what is this for? (SP->status.cbInQue) */
            ClearCommError(SP->hSerial, &SP->errors, &SP->status);

            /* Read string from arduino */
            DWORD bytesRead;
            tryStr.assign("");
            bool check = true;
            char tempCharacter;
            while (check==true){

                ReadFile(SP->hSerial, &tempCharacter, sizeof(char), &bytesRead, NULL);
                tryStr += tempCharacter;

                if(tempCharacter == '$'){
                    check = false;
                }
            }

            /* Print the string */
            std::cout << tryStr  << std::endl << std::endl ;
     }
     return 0;
    }

My Arduino Code:

    int LedPin= 10;
    int value;
    String  incomingData = "hello$";

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

    void loop (){

      while(!(Serial.available() > 0)){
        /*Wait until take data */
      }

      value=Serial.read();

      if (value == 20)
      {
          digitalWrite (LedPin, HIGH);
          incomingData.setCharAt(0,'o');
          incomingData.setCharAt(1,'p');
          incomingData.setCharAt(2,'e');
          incomingData.setCharAt(3,'n');
          incomingData.setCharAt(4,'n');

          Serial.print(incomingData);
      }
      else if (value == 15)
      {
          digitalWrite (LedPin, LOW);
          incomingData.setCharAt(0,'c');
          incomingData.setCharAt(1,'l');
          incomingData.setCharAt(2,'o');
          incomingData.setCharAt(3,'s');
          incomingData.setCharAt(4,'e');

          Serial.print(incomingData);
      }

    }

This code works perfectly. Output:

> We're connected  Value: 20  openn$
>
> Value: 15  close$
>
> Value: 20  openn$
>
> Value: 20  openn$
>
> Value: 15  close$
>
> Value: 15  close$
>
> Value: 20  openn$

But now I want to add another condition in my Arduino code:

    int LedPin= 10;
    int value;
    String  incomingData = "hello$";

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

    void loop (){

      while(!(Serial.available() > 0)){
        /*Wait until take data */
      }

      value=Serial.read();

      if (value == 20)
      {
          digitalWrite (LedPin, HIGH);
          incomingData.setCharAt(0,'o');
          incomingData.setCharAt(1,'p');
          incomingData.setCharAt(2,'e');
          incomingData.setCharAt(3,'n');
          incomingData.setCharAt(4,'n');

          Serial.print(incomingData);
      }
      else if (value == 15)
      {
          digitalWrite (LedPin, LOW);
          incomingData.setCharAt(0,'c');
          incomingData.setCharAt(1,'l');
          incomingData.setCharAt(2,'o');
          incomingData.setCharAt(3,'s');
          incomingData.setCharAt(4,'e');

          Serial.print(incomingData);
      }
      else{                                      // new line added
                                                 // new line added
          incomingData.setCharAt(0,'g');         // new line added
          incomingData.setCharAt(1,'g');         // new line added
          incomingData.setCharAt(2,'g');         // new line added
          incomingData.setCharAt(3,'g');         // new line added
          incomingData.setCharAt(4,'g');         // new line added
                                                 // new line added
          Serial.print(incomingData);            // new line added
      }                                          // new line added

    }

But it didn't work. ScreenShot:
[![ScreenShot][2]][2]

What went wrong? The led blinked correctly but the output string is wrong.

  [1]: https://i.stack.imgur.com/8s7uA.png
  [2]: https://i.stack.imgur.com/5M71R.png

title: Arduino and C++ Serial communication

Answers: 1

body:
    BOOL retVal = WriteFile(SP->hSerial, &value, sizeof(value), &bytesSend, NULL);

You're writing `sizeof(value)` bytes to the Arduino. Since `value` is an `int`, which is typically 4 bytes in size for PC compilers/processors, when you send `20`, what actually gets to the Arduino is 0x00000014. Your processor is apparently little-endian so the order of bytes sent is `0x14, 0x00, 0x00, 0x00`.

You're reading a single byte in every `loop()` iteration. Your first sketch worked because you didn't provide any `else` clause for unrecognized bytes. The Arduino merely ignored those leading zeros. However, your second sketch handled unknown bytes (such as 0x00) by printing `gggg`. So what you get for every value you send to the Arduino is exactly what you'd expect and what you see in your shell -- the result you want (`openn` == 0x14), followed by 3 gibberish results (because of the leading zero bytes).

You can fix it by either declaring `value` as a `uint8_t` in your CPP code (after including `stdint.h`) or only reading chunks of 4 bytes on the Arduino and then parsing what you get. The former solution seems more reasonable/reliable.


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

    }

title: Arduino calculator: I'm struggling to write a sketch which parses inputted characters

Answers: 2

body:
Characters in a char[] variable may be encoded in ASCII or Unicode. You will want to convert them to numbers in this case. <s>Consider subtracting the ascii value of one less than `0` from each char to get the number.</s> 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.

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


body:
I have an AT-Tiny (trinket) and I want to trigger LED on for 30 seconds every 24 hours. I'm using the timer library as follows

    timer.setInterval(86400000, toggleit());

    void toggleit()
    {
      turnLightOn();
      delay(6000);
      turnLightOff();
    }

How accurate will this be, if it's off by a few minutes each day that's fine, but will this drift over time? Also does it make a difference if I'm running it in 8 or 16 bit mode?

title: How accurate the an attiny timer function

Answers: 1

body:
The on-chip systemclock is not very accurate. You can calibrate it to some degree but it also depends on the temperature and load of the MCU. You will need a high quality quartz oscillator as external clock source to reduce it. But it will still have a drift. Switching from 8-bit to 16-bit won't make a difference.

In your case an RTC sounds like the way to go.


body: I'm currently learning about using BLE with Arduino and iOS. From what I understand (correct me if I'm mistaken), each type of BT device has a UUID. I'm using a HC-06 module connected to my Arduino. How do I find out what the UUID of a HC-06 is? I've been looking through data sheets to no avail.

title: Identify UUID of HC-06

Answers: 2

body:
In Android, I used this UUID to connect to HC-06,

      socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));

      inputStream = socket.getInputStream();
      outputStream = socket.getOutputStream();

You can use this UUID in your Android code, But over iOS, I think the Bluetooth is really a completely different hardware specs.

Hope I helped

body: Well guess what, HC-06 is not low energy so no iOS device will ever see that module despite whatever uUid you have, so go and get a bluetooth 4.0 aka BLE module


body:
I am using this code to make 10 bit PWM on port number 9, it seems like everything printed is 0,1022 rather than printing 0, 512, 1023. Is there a problem in my code ?

I wired pin9 to A3 to get the output and print it.

      void setup() {
      Serial.begin(9600);
      pinMode(A3,INPUT);
      // Set PB1/2 as outputs.
      DDRB |= (1 << DDB1) | (1 << DDB2);

      TCCR1A =
          (1 << COM1A1) | (1 << COM1B1) |
          // Fast PWM mode.
          (1 << WGM11);
      TCCR1B =
          // Fast PWM mode.
          (1 << WGM12) | (1 << WGM13) |
          // No clock prescaling (fastest possible
          // freq).
          (1 << CS10);
      OCR1A = 0;
      // Set the counter value that corresponds to
      // full duty cycle. For 15-bit PWM use
      // 0x7fff, etc. A lower value for ICR1 will
      // allow a faster PWM frequency.
      ICR1 = 0x03ff;
    }

    void loop() {
      // Use OCR1A and OCR1B to control the PWM
      // duty cycle. Duty cycle = OCR1A / ICR1.
      // OCR1A controls PWM on pin 9 (PORTB1).
      // OCR1B controls PWM on pin 10 (PORTB2).
      OCR1A = 0x0000;
      delay(500);
      Serial.println(analogRead(A3));
      OCR1A = 0x0200;
      delay(500);
      Serial.println(analogRead(A3));
      OCR1A = 0x03ff;
      delay(500);
      Serial.println(analogRead(A3));
    }

The output looks like that:

      0 0 1022 1021 0 1022 1021 0 0 1021 0 1021 1021 0 0 1021 0 0 1022

no data between 0 and 1022 are presented.

thanks.

title: 10 bit PWM on Arduino UNO

Answers: 1

body:
On your code, you using `analogRead` but declaring the pin (A3) as output. Change it to `pinMode(A3,INPUT);`

Aside from that, PWM is basically a digital output which changing (HIGH and LOW) at specified frequency. When the result you got is

>  0 0 1022 1021 0 1022 1021 0 0 1021 0 1021 1021 0 0 1021 0 0 1022

There's nothing wrong. 0 --> LOW, and 1021++ --> HIGH
If you want "measure" something from the PWM, use `pulseIn()` instead, you can check the documentation [here][1].

If you want to measure the PWM value, I suggest you read:
[https://arduino.stackexchange.com/questions/10041/can-i-connect-a-pwm-pin-on-one-arduino-to-an-analog-input-on-another][2]

  [1]: https://www.arduino.cc/en/Reference/PulseIn
  [2]: https://arduino.stackexchange.com/questions/10041/can-i-connect-a-pwm-pin-on-one-arduino-to-an-analog-input-on-another


body:
I plan to do the following:

    void setup(){
      String term = "12 + (2 * 5)";
      int result = eval(term); // eval function (from Python)
      Serial.println(result); // expecting 22
    }

However there is no eval function. Are there any alternatives?

title: eval() function for Arduino?

Answers: 3

body:
No, there are no alternatives. You need to parse the string and perform the operations yourself.

Personally I prefer to use [RPN](https://en.wikipedia.org/wiki/Reverse_Polish_notation) since it is so much easier to parse. Your string could be re-written then as:

    2,5,*,12,+

Tokenise on `,` and look to see if it's a number (push on a stack) or an operator (pop operands off stack, do operation, push result on stack).

body:
I Googled and the news isn't good.  There isn't an off the shelf function that does this in C/C++.  There are plenty of links to algorithms that you could implement.  But would you have the memory to do it on an Arduino?

So, looking at the problem for a different perspective why don't you run python on the Arduino?  There is a version called pymite which runs on a mega.

body:
[TinyExpr][1] does what you want, and more.

> TinyExpr is a very small recursive descent parser and evaluation engine for math expressions. It's handy when you want to add the ability to evaluation math expressions at runtime without adding a bunch of cruft to you project.
>
> In addition to the standard math operators and precedence, TinyExpr also supports the standard C math functions and runtime binding of variables.

# Your example

You'd just need to save `tinyexpr.h` and `tinyexpr.c` next to your Sketch.

    #include "tinyexpr.h"

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

    void loop() {
      char term[] = "12 + (2 * 5)";
      Serial.println(term);
      int error;
      double result = te_interp(term, &error);
      if (error){
        Serial.println("Problem with expression.");
      } else {
        Serial.printf(" = %.10g\n", result);
      }
      delay(1000);
    }

It outputs:

    12 + (2 * 5)
     = 22

Since `term` is known at compile-time, this example is not very useful, and it simply outputs `22` in an endless loop.

# Basic interactive console

If you use the input from `Serial`, you can write a very basic interactive console. A `String` has been used for conciseness, but this example could be rewritten with [cstrings][2]:

    #include "tinyexpr.h"

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

    void loop() {
      if (Serial.available() > 0) {
        String expression = Serial.readStringUntil('\n');
        Serial.print("> ");
        Serial.println(expression);

        int error;
        double result = te_interp(expression.c_str(), &error);

        if (error) {
          Serial.print(" ");
          for (int i = 0; i < error; i++) {
            Serial.print(" ");
          }
          Serial.println("↑");
          Serial.println("I didn't understand this part.");
        } else {
          Serial.printf(" = %.10g\n", result);
        }
      }

      delay(50);
    }

TinyExpr knows the order of operations, and it understands many other mathematical expressions:

    > 12 + 2 * 5
     = 22
    > 3^5
     = 243
    > exp(7)
     = 1096.633158
    > (1 + sqrt(5)) / 2
     = 1.618033989
    > 1 + 2 * 3 + 4 * 5
     = 27
    > sin(pi/2)
     = 1
    > sin(pi/3)
     = 0.8660254038

If there's a syntax error somewhere, `error` tells you the position of the first encountered error:

    > 3 +
          ↑
    I didn't understand this part.
    > sin() * 5
          ↑
    I didn't understand this part.
    > 3 / (4 + 5 * 7
                    ↑
    I didn't understand this part.

  [1]: https://github.com/codeplea/tinyexpr
  [2]: http://www.gammon.com.au/serial


body:
Our project involves using an arduino compatible microcontroller to control a mouse on a computer with an accelerometer and flex sensor. We had narrowed down to the ATTiny85 due to its small size.

We found a particular tutorial on the Adafruit tutorial  [website][1], using the Adafruit Pro Trinket using the same ATTiny85.

Is there a reason to believe that this won't work?

Also, does anyone have suggestions as to which board to use apart from Micro as it isn't too available here?

  [1]: https://learn.adafruit.com/pro-trinket-usb-hid-mouse/overview "here"

title: Using ATTiny85 as a USB HID Mouse

Answers: 2

body:
Due to the lack of USB-Support of the ATtiny85 you will be forced to use something like [V-USB](https://www.obdev.at/products/vusb/index.html) as the tutorial does. This might have implications when you are targeting a commercial product.

Personally I'd suggest using the ATmega32u4. It has USB build right in.

But basically I don't see any reasons why it should not work.

body:
@Kwasmich raises a good point about the 32u4. Here is a little more information about it.

 - Works at 5V and 3.3V
 - Compatible with the Arduino IDE
 - Built-in USB
 - Very close to the ATmega328

Here are a couple of cheap breakouts for it

 - Arduino Pro Micro ([5V/16MHz][1], [3.3V/8MHz][2])
 - [Arduino Micro][3]
 - [Dreamer Nano V4][4]

  [1]: https://www.sparkfun.com/products/12640
  [2]: https://www.sparkfun.com/products/12587
  [3]: https://www.arduino.cc/en/Main/ArduinoBoardMicro
  [4]: https://www.dfrobot.com/wiki/index.php/Dreamer_Nano_V4.0_(DFR0213)


body: I have a trinket that I'm going to be powering off of a small lithium ion battery. I was also considering adding a small solar panel to the mix, and using the solar panel to charge the battery. I'm wondering if I can use the trinket itself as a smart charge controller to charge and monitor the battery.

title: Using an Arduino as a lithium ion charge controller

Answers: 3

body:
Try [this][1]. It's the Adafruit PowerBoost 1000 Charger - Rechargeable 5V Lipo USB Boost @ 1A - 1000C.

It's designed for Lipo, but I **think** it should work for Li-ION

  [1]: https://www.adafruit.com/product/2465

body:
If you are going to design your own battery management system here are a few issues you will need to deal with:

 1. You need to understand the methods to determine the End Of Charge (EOC).  This could be monitoring cell temperature, measuring cell voltage or current for patterns, or integrating current over time (coulomb counter).  Different battery chemistries usually dictate which approach to take.

 2. You need to check with the specific battery manufacturer to determine what charge rate you should use for this specific battery.  Knowing the chemistry is good.  But it is usually best to use the charge rate data from reputable manufactures.

 3. Some batteries can not be completely drained.  If not already part of the LION battery, you will need to design a protection circuit to cut the battery off before this happens.

 4. For such batteries, you need to add a trickle charging circuit in case the battery has been overly discharged.  Such a circuit only allows a small amount of current in.  The current is usually so small that normal monitoring is not necessary.  This is a last resort procedure built into most good chargers to recover overly discharged LION batteries.

...this is not a complete list. These are some of the issue which might be considered when designing a secondary battery charger.  There is a lot more [good information about batteries here][1] if you would like to research this subject in greater depth.

  [1]: http://batteryuniversity.com/

body:
If you have a small solar panel, you probably don't have to worry about limiting the charge current (as the battery will be able to handle more that the solar panel can supply).

So the only thing left to do is prevent over-charge (i.e. disconnect the solar panel if the voltage on the battery goes above 4.2V). <strike>Protected cell can do this for you. I'm not knowledgeable enough to know if it's a good idea to rely on this.</strike>

Also make sure the solar panel isn't connected when it's dark, as the solor panel will use current when it's not generating it. Though a simple diode will do this trick. But you'd get a 0.6V drop on the diode, so you might want to get some extra efficiency by detecting output and switching the solar panel using the Arduino.

The last problem is overdischarge, unless you have a protected cell. But that's a problem you have, even without the charging bit.


body:
First, thank you for taking the time to read my post.

I am attempting to use 3 ultrasonic sensors to control 3 DC vibrator motor using the PWM output of an Arduino. Fairly simple, I know, but I'm just a beginner. :)

Here's my code,

    int trigpin_1 = 2;
    int echopin_1 = 3;
    int trigpin_2 = 4;
    int echopin_2 = 5;
    int trigpin_3 = 6;
    int echopin_3 = 7;
    int motor_1 = 8;
    int motor_2 = 9;
    int motor_3 = 10;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin (9600);
      pinMode(trigpin_1, OUTPUT);
      pinMode(echopin_1, INPUT);
      pinMode(trigpin_2, OUTPUT);
      pinMode(echopin_2, INPUT);
      pinMode(trigpin_3, OUTPUT);
      pinMode(echopin_3, INPUT);
      pinMode(motor_1, OUTPUT);
      pinMode(motor_2, OUTPUT);
      pinMode(motor_3, OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:

      long duration, distance;
      digitalWrite(trigpin_1, HIGH);
      digitalWrite(trigpin_2, HIGH);
      digitalWrite(trigpin_3, HIGH);
      delayMicroseconds(1000);
      digitalWrite(trigpin_1, LOW);
      digitalWrite(trigpin_2, LOW);
      digitalWrite(trigpin_3, LOW);
      duration = pulseIn(echopin_1, HIGH);
      duration = pulseIn(echopin_2, HIGH);
      duration = pulseIn(echopin_3, HIGH);
      distance = (duration/2) /29.1;
      if (distance > 200)
      {
        analogWrite(motor_1, 0);
        analogWrite(motor_2, 0);
        analogWrite(motor_3, 0);
      }
      else if(200 == distance > 160)
      {
        analogWrite(motor_1, 50);
        analogWrite(motor_2, 50);
        analogWrite(motor_3, 50);
      }
      else if(160 >= distance > 90)
      {
        analogWrite(motor_1, 100);
        analogWrite(motor_2, 100);
        analogWrite(motor_3, 100);
      }
      else if(90 >= distance > 60)
      {
        analogWrite(motor_1, 150);
        analogWrite(motor_2, 150);
        analogWrite(motor_3, 150);
      }
      else if(60 >= distance > 40)
      {
        analogWrite(motor_1, 200);
        analogWrite(motor_2, 200);
        analogWrite(motor_3, 200);
      }
      else if(40 >= distance)
      {
        analogWrite(motor_1, 255);
        analogWrite(motor_2, 255);
        analogWrite(motor_3, 255);
      }

      Serial.print (distance);
      Serial.println (" cm");
      delay(100);
    }

[![here the Connections][1]][1]

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

  [1]: https://i.stack.imgur.com/es4er.jpg
  [2]: https://i.stack.imgur.com/W9jEW.jpg

but the problem is the DC motors it will be on all the time with 100% duty cycle. if anyone can help me will be thankful

title: control vibrator motor speed with ultrasonic sensors

Answers: 2

body:
There is quite a bit wrong with your code I'm afraid.

Firstly the if statements.  If the values are kept in descending order then you can do this:

    if (distance > 200)
    {...}
    else if (distance > 160)  // This point won't be reached unless the value is less than 200.
    {...}
    else if (distance > 100)
    {...}

I think what you were trying to do was:

    if (distance < 200 && distance > 160)
    {...}
but its not necessary.

You are reading the pulse lengths into a single variable overwriting the previous values.  This means you are only reading sensor 3.  If you want to average the values then try this:

    duration = pulseIn(echopin_1, HIGH);
    duration += pulseIn(echopin_2, HIGH); // take the result and add it to duration.
    duration += pulseIn(echopin_3, HIGH);
    duration /= 3;   // divide duration by three and assign the result to duration.

Also I'm not sure about the positioning of your sensors, its possible that they might interfere with each other.  In which case write a function to read from the sensor and store the results in an array.

i.e.
    const int sensorTriggerPins[] = {2, 4, 6};
    const int sensorEchoPins[] = {3, 5, 7};

    long readSensor (const int& triggerPin, const int& eechoPin)
    {
      digitalWrite(triggerPin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(triggerPin, LOW);
      return pulseIn(echoPin, HIGH);
    }

    void setup()
    {
       long duration[3]; // Define a three element array.
       for (int sensor = 0; sensor < 3; ++sensor)
       {
          duration[index] = readSensor(sensorTriggerPin[index], sensorEchoPin[index]);
       }
    }

I don't know if this will fix all your problems, but it should help.
(It might have been better if you posted this in the Arduino forum)

body: You don't want to use GPIO outputs to drive motors directly.  You'll likely burn-out your Arduino with the schematic you've given.  At a minimum you'll want to use transistors (that can handle the motor current load) to switch the motors on/off.


body:
I just hooked up a DHT22 I had laying around in a parts drawer to test something and it is giving out some crazy wrong values, I am running the adafruit library's unified example and this is the output:

    Resolution:   0.10%
    ------------------------------------
    :   1
    Unique ID:    -1
    Max Value:    100.00%
    Min Value:    0.00%
    Resolution:   0.10%
    ------------------------------------
    DHTxx Unified Sensor Example
    ------------------------------------
    Temperature
    Sensor:       DHT22
    Driver Ver:   1
    Unique ID:    -1
    Max Value:    125.00 *C
    Min Value:    -40.00 *C
    Resolution:   0.10 *C
    ------------------------------------
    ------------------------------------
    Humidity
    Sensor:       DHT22
    Driver Ver:   1
    Unique ID:    -1
    Max Value:    100.00%
    Min Value:    0.00%
    Resolution:   0.10%
    ------------------------------------
    Temperature: 588.80 *C
    Humidity: 998.40%
    Temperature: 563.20 *C
    Humidity: 1049.60%
    Temperature: 563.20 *C
    Humidity: 1024.00%
    Temperature: 563.20 *C
    Humidity: 1024.00%
    Temperature: 563.20 *C
    Humidity: 1024.00%

Had anyone seen behaviour like this before? of course my room isn't 600 *C or 1000% humidity XD

Its connected to an arduino UNO that I am pretty sure works fine.

title: DHT22 reading weird values

Answers: 0


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

title: Merging strings and constants causing scope errors

Answers: 3

body:
Maybe? Not sure, but give this a try.

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

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

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


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

title: "return" not working to break out of a loop

Answers: 2

body:
This part is wrong, for a start:

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

    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](https://stackoverflow.com/help/mcve)

---

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

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

    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](http://www.gammon.com.au/statemachine) would probably be very appropriate.

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


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

title: Combining two codes to jump back and forth between them

Answers: 1

body:
[The solution in short.][1]

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

  [1]: https://www.youtube.com/watch?v=1W3sslyiUfg


body:
When looking for alternate external programmers (ISPs), I am noticing that many are not Arduino Mega 2560 compatible (e.g. [Pocket AVR Programmer][1], [USBtinyISP][2]).

I am looking for a reliable external programmer for the Arduino Mega that is compatible with the Arduino IDE. What are my options? Currently I have been struggling with the retired [ArduinoISP][3] programmer, which [doesn't look like its going to work][4]. __Does anyone have proven experience with a given programmer and a Mega?__

The suggested AVR-mkII doesn't seem to be available anymore either.

  [1]: https://www.sparkfun.com/products/9825
  [2]: https://learn.adafruit.com/usbtinyisp
  [3]: https://www.arduino.cc/en/Main/ArduinoISP
  [4]: https://arduino.stackexchange.com/questions/30946/arduinoisp-external-programmer-produces-verification-error

title: Which external programmers work reliably with Arduino Mega?

Answers: 2

body:
I have successfully used [Arduino as ISP][1] (not to be confused with [Arduino ISP][2]) on a Mega clone that has a funky FTDI-clone onboard, and would not let me upload bootloader through serial. This worked fine, and is cheap.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP
  [2]: https://www.arduino.cc/en/Main/ArduinoISP

body:
a test would be if any of those programmers mentioned about could program a big file (64KB+).

if I were you, I would look into that instead.


body:
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][1]

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.

  [1]: http://docdro.id/SMFZHAg

title: How to move my robot in the right direction?

Answers: 2

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

body:
**||-----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][1]:

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

[![register description][2]][2]

 - 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][3] 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;

    }

  [1]: https://www.google.co.id/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjd55a7773QAhWCgI8KHShGB6UQFggaMAA&url=http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf&usg=AFQjCNHs4keTJWThJb5ooVtTVJP6OPi7fA&sig2=6RGz6d_qEfhkFuSR1ardTw&bvm=bv.139782543,d.c2I
  [2]: https://i.stack.imgur.com/lwMHt.png
  [3]: https://www.arduino.cc/en/Reference/Servo


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

title: connecting lv maxsonar ez arduino

Answers: 1

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


body:
I am doing my engineering degree. I want to make a project connecting multiple ESP8266 with a router and control multiple relay boards. I am unable to use ESP8266 12E with Arduino. I used this connection shown in the link below, but it didn't work. So please help me with the solution. I also referred to all possible posts, but it didn't help. Please help me as soon as possible.

Connection:

![](https://i.stack.imgur.com/9H6Wc.png)
post: https://arduino.stackexchange.com/questions/26709/how-to-connect-esp8266-12e-directly-to-arduino-uno-without-shields

title: I am not able to use ESP8266 12E with Arduino

Answers: 4

body:
I agree with Paul, you shouldn't use the Arduino, you can get break out boards at £1 for 10, but that's not what your problem is...

You are using a couple of resistors to do the level shifting taking the 5V to 3.3V.  This is a bad plan, you need a proper bidirectional level shifter, particularly at higher baud rates, i.e. above 1000.

You are supplying the top VCC rail with both 3V from the batteries and 3.3V from the Arduino, not the best plan IMO.

You are not supplying the Arduino with any power, I guess this is a drawing error but just in case it isn't I though I best mention it.

You have no level shifting on the Arduino's Rx line.  Its not technically needed, but you might require it particularly when the batteries are going flat.

You are using batteries and that's not a great plan.

Have you configured the ESPs using the AT command set, since you won't program them.

Just for the record the ESP has more memory it has a faster processor (80MHz) and you can still use the Arduino IDE.  You should be able to pick up boards to mount the ESPs so you can use them more easily for less that the price of the level shifters, but its your call.

body:
I am the author of the [linked question][1]. Just to clarify, the image you're using has the old connection, which wasn't working for me. [Please refer to the updated version of that connection][2], embed below:

[![Updated connection][3]][3]

The main changes were: the GPIO15 pin needs to be grounded, and the RESET pullup is now wired to the battery's 3.3v. Also the resistors were changed from 220ohms to 10k, but since it's a voltage divider it shouldn't make much of a difference.

Hope this helps anyone out there!

  [1]: https://arduino.stackexchange.com/questions/26709/how-to-connect-esp8266-12e-directly-to-arduino-uno-without-shields
  [2]: https://i.stack.imgur.com/qjykI.png
  [3]: https://i.stack.imgur.com/qjykI.png

body:
There is also a library which can help you communicating with ESP2866 through Arduino called [WiFiEsp][1].

It's like WiFi library for Arduino but instead for ESP8266.

  [1]: https://github.com/bportaluri/WiFiEsp

body: Bruh that ain't even an esp8266 12e that is a different esp board. The esp8266 12e is basically an Arduino with an added wifi feature which increases the number of tasks you can do. If you are using an esp8266 12e then you can connect it directly to your laptop and start programming on the Arduino IDE software. It is super awesome and I have worked with it once for my plans home automation system. With a bit of research, you can find out which esp board that is if you really want to work with that circuit diagram.


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

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

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

title: MPU-6050 + Arduino Micro + nRF24L01 FIFO overflow!

Answers: 1

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


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

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

Answers: 2

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

body:
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](http://forum.arduino.cc/index.php?topic=177059.0) 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.


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

[![my sensor][1]][1]

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][2]
[Wireless sensor 2][3]

  [1]: https://i.stack.imgur.com/RbiVf.jpg
  [2]: https://forum.dday.it/uploads/default/original/1X/084a35afaefa0753541a18bda6f97b2d640e13a3.pdf
  [3]:
https://forum.dday.it/uploads/default/original/1X/1c3502099d8eeca36b57187511f8516407530d05.pdf

title: Reverse engineering of a bluetooth sensor

Answers: 1

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


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

title: arduino not loading library

Answers: 2

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

body: You're using `#define` when it should be `#include`.


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

title: Problem with microSD SPI mode in AVR

Answers: 1

body:
I formated the SD card, and then work correctly

Thanks!


body:
I have a project to connecting dual esp8266 using client server method, my expectation the server can get command from user from web request, and the request will be forward to client from server to turn on led. But the connection from server always failed

I'm using ESP-12F and programming using Arduino IDE

the code of server :

    //--------------------------------------------------------------------------
      #include <ESP8266WiFi.h>
    //--------------------------------------------------------------------------
    // Membuat Variabel Autentikasi
    //--------------------------------------------------------------------------
      const char* ssid = "master-sport";
      const char* password = "1234567890";
    //--------------------------------------------------------------------------
    // Mengatur IP Address
    //--------------------------------------------------------------------------
      IPAddress CLIENTA(192,168,4,100);
    //--------------------------------------------------------------------------
    // Create an instance of the server
    // specify the port to listen on as an argument
    //--------------------------------------------------------------------------
      WiFiServer server(80);
      WiFiClient client;
    //===========================================================================
      void setup() {
       Serial.begin(115200);
       delay(10);

      // Mengatur WiFi ----------------------------------------------------------
       Serial.println();
       Serial.print("Configuring access point...");

       WiFi.mode(WIFI_AP);
       WiFi.softAP(ssid, password);

      // Start the server -------------------------------------------------------
       server.begin();
       Serial.println("Server dijalankan");

      // Print the IP address ---------------------------------------------------
       Serial.println(WiFi.localIP());
     }

    //===========================================================================

      void loop() {
      // Check if a client has connected ----------------------------------------
        client = server.available();
        if (!client) {
        return;
      }

      // Wait until the client sends some data ----------------------------------
       Serial.println("new client");
       while(!client.available()){
         delay(1);
      }

      // Read the first line of the request -------------------------------------
       String req = client.readStringUntil('\r');
       Serial.println(req);
       client.flush();

      // Match the request ------------------------------------------------------
       const char* host;
       int val;
       if (req.indexOf("/sr/0") != -1){
          host = "sa";
          val = 0;
        }
       else if (req.indexOf("/sr/1") != -1){
          host = "sa";
          val = 1;
        }
       else {
         Serial.println("invalid request");
         client.stop();
         return;
        }

       client.flush();
       Serial.println("Client disonnected");

      // Pengiriman data ke client -----------------------------------------------
       int value  = 0;
       delay(5000);
       ++value;

       Serial.print("connecting to ");
       Serial.println(CLIENTA);

      // Memebuat TCP Connection Menggunakan WiFiClient --------------------------
       const int httpPort = 80;
       if (!client.connect(CLIENTA, httpPort)) {
         Serial.println("connection failed");
         return;
       }

      // Membuat URL untuk dikirimkan -------------------------------------------
       String url = host;
       url += "/";
       url += val;

       Serial.print("Requesting URL: ");
       Serial.println(url);

      // Mengirimkan Request ke Client ------------------------------------------
       client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                   "Host: " + CLIENTA + "\r\n" +
                   "Connection: close\r\n\r\n");
       unsigned long timeout = millis();
       while (client.available() == 0) {
         if (millis() - timeout > 5000) {
           Serial.println(">>> Client Timeout !");
           client.stop();
           return;
        }
      }

      // Melihat semua line balasan dari server dan menampilkan di Serial -------
       while(client.available()){
         String line = client.readStringUntil('\r');
         Serial.print(line);
       }

       Serial.println();
       Serial.println("closing connection");
    }
    //=============================================================================
Client code :

    //--------------------------------------------------------------------------
      #include <ESP8266WiFi.h>
      #include <Adafruit_NeoPixel.h>
      #ifdef __AVR__
      #include <avr/power.h>
      #endif
      #define PIN 13
    //--------------------------------------------------------------------------
    // Membuat Variabel Autentikasi
    //--------------------------------------------------------------------------
      const char* ssid = "master-sport";
      const char* password = "1234567890";
    //--------------------------------------------------------------------------
    // Mengatur IP Address
    //--------------------------------------------------------------------------
      IPAddress IP(192,168,4,100);
      IPAddress NETMASK(255,255,255,0);
      IPAddress NETWORK(192,168,4,1);
    //--------------------------------------------------------------------------
    // Create an instance of the server
    // specify the port to listen on as an argument
    //--------------------------------------------------------------------------
      WiFiServer server(80);
    //--------------------------------------------------------------------------
    // Menasukan LED RGB
    //--------------------------------------------------------------------------
      Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800);
    //===========================================================================
      void setup() {
       Serial.begin(115200);
       delay(10);

      // Connect to WiFi network ------------------------------------------------
       Serial.println();
       Serial.println();
       Serial.print("Connecting to ");
       Serial.println(ssid);

      // Mengatur WiFi ----------------------------------------------------------
       WiFi.mode(WIFI_STA);
       WiFi.begin(ssid, password);
       WiFi.config(IP, NETMASK, NETWORK);

       while (WiFi.status() != WL_CONNECTED) {
         delay(500);
         Serial.print(".");
       }
       Serial.println("");
       Serial.println("WiFi connected");

      // Start the server -------------------------------------------------------
       server.begin();
       Serial.println("Server dijalankan");

      // Menjalankan LED RGB ----------------------------------------------------
       strip.begin();
       strip.show();

      // Print the IP address ---------------------------------------------------
       Serial.println(WiFi.localIP());
     }

    //===========================================================================

      void loop() {
      // Check if a client has connected ----------------------------------------
        WiFiClient client = server.available();
        if (!client) {
        return;
      }

      // Wait until the client sends some data ----------------------------------
       Serial.println("new client");
       while(!client.available()){
         delay(1);
      }

      // Read the first line of the request -------------------------------------
       String req = client.readStringUntil('\r');
       Serial.println(req);
       client.flush();

      // Match the request ------------------------------------------------------
       int val;
       if (req.indexOf("/sa/0") != -1){
          strip.setPixelColor(4,0x000000); //LED menjadi mati -------------------
          strip.show();
        }
       else if (req.indexOf("/sa/1") != -1){
          strip.setPixelColor(4, 0xFF0000); //LED menjadi merah -----------------
          strip.show();
        }
       else {
         Serial.println("invalid request");
         client.stop();
         return;
        }

       client.flush();
       Serial.println("Client disonnected");
    }

    //============================================================================

whats wrong that code ?

title: Connection ESP8266 to ESP8266 Client Server can't Connect, Help me?

Answers: 1

body:
You do not need 2 ESPs, one is enough. Here you are the code so you can turn on the NeoPixel using web interface:

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>

    IPAddress ip(192,168,1,81);         // choose IP address
    IPAddress subnet(255,255,255,0);

    ESP8266WebServer server(80);

    void handleRoot() {
      String page = "<!DOCTYPE html>\n";

      page += "\n\n
Some heading

Generated by ESP8266\n\n";
      server.send(200, "text/html", page);
    }

    // what to do when accessed through http://ip_address/something_undefined
    void handleNotFound(){
      String message = "File not found\n\n";
      message += "URI: ";
      message += server.uri();
      message += "\nMethod: ";
      message += (server.method() == HTTP_GET)?"GET":"POST";
      message += "\nArguments: ";
      message += server.args();
      message += "\n";
      for (uint8_t i=0; i<server.args(); i++){
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
      }
      server.send(404, "text/plain", message);
    }

    void setup(void){
      Serial.begin(74880);                      // so you can see debug messages automatically sent by ESP8266
      WiFi.mode(WIFI_AP);
      WiFi.softAPConfig(ip, ip, subnet);        // declared as: bool softAPConfig (IPAddress local_ip, IPAddress gateway, IPAddress subnet)
      WiFi.softAP("SOME_NAME", "password", 7);  // network name, network password, wifi channel

      IPAddress myIP = WiFi.softAPIP();
      Serial.println();
      Serial.print("AP IP address: ");
      Serial.println(myIP);

      server.on("/", handleRoot);               // what to do when accessed through browser using http://IP_address

      // what to do when accessed through http://ip_address/test
      server.on("/test", [](){
        server.send(200, "text/plain", "This is another page");
      });

      server.on("/sa/1", [](){
        // ... <-- put here the code for NeoPixel = on
        server.send(200, "text/html", "NeoPixel is now on");
      });

      server.on("/sa/0", [](){
        // ... <-- put here the code for NeoPixel = off
        server.send(200, "text/html", "NeoPixel is now off");
      });

      server.onNotFound(handleNotFound);

      server.begin();
      Serial.println("HTTP server started...");
    }

    void loop(void){
      server.handleClient();
    }

Now you can use `xx.xx.xx.xx/sa/1` and `xx.xx.xx.xx/sa/0` (where xx.xx.xx.xx is an IP address you've chosen) to turn on/off the NeoPixel.

Just add the Adafruit library for controlling NeoPixel and copy the NeoPixel setup and the code to turn it on/off from your code #2 to the appropriate places (I marked the place where to put the code to turn the NeoPixel on/off with the comments).

If you really want to add another ESP8266 then you have to set it up as a server using the same code - just change the `network name`, `password` & `IP address` and add sending GET request from your first ESP to the second.


body:
I'm using Arduino and Adafruit to control 4 motors for a little robot.

I have this code example:
<!-- language-all: lang-cpp -->

    #include <AFMotor.h>

    AF_DCMotor motor1(1, MOTOR12_1KHZ); // create motor #2, 64KHz pwm
    AF_DCMotor motor2(2, MOTOR12_1KHZ); // create motor #2, 64KHz pwm
    AF_DCMotor motor3(3, MOTOR12_1KHZ); // create motor #2, 64KHz pwm
    AF_DCMotor motor4(4, MOTOR12_1KHZ); // create motor #2, 64KHz pwm

    void setup() {
      Serial.begin(9600);           // set up Serial library at 9600 bps
      Serial.println("Motor test!");

      motor1.setSpeed(200);     // set the speed to 200/255
      motor2.setSpeed(200);     // set the speed to 200/255
      motor3.setSpeed(200);     // set the speed to 200/255
      motor4.setSpeed(200);     // set the speed to 200/255
    }

    void loop() {
      Serial.print("tick");

      motor1.run(FORWARD);      // turn it on going forward
      motor2.run(FORWARD);
      motor3.run(FORWARD);
      motor4.run(FORWARD);
      delay(1000);

      Serial.print("tock");
      motor1.run(BACKWARD);
      motor2.run(BACKWARD);
      motor3.run(BACKWARD);
      motor4.run(BACKWARD);
      delay(1000);

      Serial.print("tack");
      motor1.run(RELEASE);
      motor2.run(RELEASE);
      motor3.run(RELEASE);
      motor4.run(RELEASE);
      delay(1000);

    }

I want to reduce speed, because now is very fast. If I change setSpeed, the motor have no more force and don't run or not good. Do you know what I'm doing wrong?

Thanks
Best regards

title: How can I reduce speed of motor with motor shield?

Answers: 0


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

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

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

title: Is the MKS GEN V1.2 compatible with Arduino IDE as Arduino MEGA Board?

Answers: 1

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


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

title: SIM800L always returns +CREG: 0,2

Answers: 1

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