message:
arrange vector in descending order

im trying to arrange the vector in descending order but its not happening..

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

    int fibonacci[15]={0, 1};
    int a=0;

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

      for (int i=0; i<=14; i++) //loop to create the array
      {
        fibonacci[i+2]=(fibonacci[i])+(fibonacci[i+1]);
      }

      //Now arrange in descending order
      for (int i=0; i<16; i++)
      {
        for (int j=i+1; j<16; j++)
        {
          if (fibonacci[i]>fibonacci[j])
          {
            a=fibonacci[i]; //mux number
            fibonacci[i]=fibonacci[j];
            fibonacci[j]=a;
          }
        }
      }

      for (int k=0; k<16; k++)
      {
        Serial.println(fibonacci[k]);
      }
    }

    void loop() {
    }

body:
I guess that what you want is a descending sort algorithm, but in the case of Fibonacci numbers you can take advantage that they are already sorted at the beginning. Here are different strategies that you can try :

    /*
      SORTING IN DESCENDING ORDER
    */

    const int nbElem = 15; // 24 max
    int fibonacci[ nbElem ] = { 0, 1 };

    void createFibonacciArray( int inputArray[], int arraySize )
    {
      fibonacci[ 0 ] = 0;
      fibonacci[ 1 ] = 1;
      for( int i=0; i<nbElem-2; i++ )
        fibonacci[ i+2 ] = fibonacci[ i ] + fibonacci[ i+1 ];
    }

    void displayArray( int inputArray[], int arraySize )
    {
      for( int i=0; i<arraySize; i++ )
        Serial.println( inputArray[ i ] );
    }

    void displayArrayReverse( int inputArray[], int arraySize )
    {
      for( int i=arraySize-1; i>=0; i-- )
        Serial.println( inputArray[ i ] );
    }

    void reverseArray( int inputArray[], int arraySize )
    {
      for( int i=0; i<nbElem/2; i++ )
      {
        int fTemp = fibonacci[ i ];
        fibonacci[ i ] = fibonacci[ nbElem-i-1 ];
        fibonacci[ nbElem-i-1 ] = fTemp;
      }
    }

    void inverseBubbleSort( int inputArray[], int arraySize )
    {
      for( int i=0; i<arraySize-1; i++ )
      {
        for( int j=0; j<arraySize-1-i; j++ )
        {
          if( inputArray[ j ] < inputArray[ j+1 ] )
          {
            int temp = inputArray[ j+1 ];
            inputArray[ j+1 ] = inputArray[ j ];
            inputArray[ j ] = temp;
          }
        }
      }
    }

    void bubbleSort( int inputArray[], int arraySize )
    {
      for( int i=0; i<arraySize-1; i++ )
      {
        for( int j=0; j<arraySize-1-i; j++ )
        {
          if( inputArray[ j ] > inputArray[ j+1 ] )
          {
            int temp = inputArray[ j+1 ];
            inputArray[ j+1 ] = inputArray[ j ];
            inputArray[ j ] = temp;
          }
        }
      }
    }

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

      // Create and display Fibonacci array
      createFibonacciArray( fibonacci, nbElem );
      Serial.print( "\n\nFIBONACCI ARRAY\n" );
      Serial.print( "===============\n" );
      displayArray( fibonacci, nbElem );

      // Solution 1: Display array starting from the end
      Serial.print( "\n\nFIBONACCI ARRAY STARTING FROM THE END\n" );
      Serial.print( "=====================================\n" );
      displayArrayReverse( fibonacci, nbElem );

      // Solution 2: Reverse array
      reverseArray( fibonacci, nbElem );
      Serial.print( "\n\nFIBONACCI REVERSED ARRAY\n" );
      Serial.print( "========================\n" );
      displayArray( fibonacci, nbElem );

      // Solution 3: Inverse bubble sort array
      createFibonacciArray( fibonacci, nbElem );
      inverseBubbleSort( fibonacci, nbElem );
      Serial.print( "\n\nFIBONACCI SORTED IN DESCENDED ORDER WITH BUBBLE SORT\n" );
      Serial.print( "====================================================\n" );
      displayArray( fibonacci, nbElem );

      // Ascending order sort array
      bubbleSort( fibonacci, nbElem );
      Serial.print( "\n\nFIBONACCI SORTED WITH BUBBLE SORT\n" );
      Serial.print( "=================================\n" );
      displayArray( fibonacci, nbElem );
    }

    void loop()
    {}


sender: user

sender: assistant

body:
You can use it using bubble sort algorithm (which is most simple but inefficient)

    int fibonacci[15]={0, 1};
    int a=0;

    int arraysize=2; // variable to store size or array

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

      for (int i=0; i<=14; i++) //loop to create the array
      {
        fibonacci[i+2]=(fibonacci[i])+(fibonacci[i+1]);
     arraysize++;
      }

      //Now arrange in descending order using bubble sort
      for (int i=0; i<arraysize; i++)
      {
        for (int j=0; j<arraysize-1; j++)
        {
          if (fibonacci[j]<fibonacci[j+1])
          {
            a=fibonacci[j+1]; //max number
            fibonacci[j+1]=fibonacci[j];
            fibonacci[j]=a;
          }
        }
      }
      //------------------------------------------------

      for (int k=0; k<16; k++)
      {
        Serial.println(fibonacci[k]);
      }
    }


message:
Remote temperature sensor system without slave board

I want to build a temperature control network over my house reading data from each room and sending it to the main board for further processing. I need about 6 sensor nodes sending the data over the air to the main node.
There are tons of tutorials of making master-slave temperature/pressure etc control systems of 2 Arduino boards communicating via wireless channel.
I find it a bit expensive to have a board per sensor node. **Is that possible to build a sensor device without a controller using just a sensor, a battery and a wireless transmitter plus required radio components?** It's ok to send raw data to the main node. Assuming it knows the protocol it will be able to decode the data there from all the incoming channels.

body:
As @Majenko said on comment, its possible. One of the choice is ESP8266. Your project has been successfully accomplished, you can check [here][1], [here][2], or [here][3]. NSP8266 only needs 3-3.6V (low current) supply voltage.

  [1]: https://github.com/astoklas/ESP8266-Temperature-Sensor
  [2]: http://www.instructables.com/id/Low-cost-WIFI-temperature-data-logger-based-on-ESP/
  [3]: https://forum.mysensors.org/topic/2519/temperature-sensor-on-esp8266/10


body: @Sergey if its cost what's bothering you , there are numerous low-cost options for MCUs. For eg you can club a MSP 430 ( probably <1$) chip with a cheap RF transmitter which wont burn a hole in your pocket and is absolutely reliable. Wifi modules can be a little expensive and need constant connectivity. So, you have a choice on this.


message:
Simultaneous output from sonar array

I am working on a project that records the elevation changes of a 1 foot wide section using sonar distance measurement. I have 10 HC-SR04 sensors arranged in a straight line over this 1 foot section.

The issue I am having is that when I send an output from my sonar sensor, I must wait until the return signal is recorded before I can trigger the next sonar sensor to take a measurement. This is rather slow and decreases the sampling frequency significantly. I need each sonar sensor to take 1000 measurements per second for my project.

Is there a way to have the HC-SR04 sensors simultaneously output and listen for the return signal? I would want all 10 sensors to send a 40 kHz pulse at the same time, and then when a return signal is recorded, another 40 kHz pulse is sent out.

The average distance to the 1 foot wide section is about 11 inch. If the Arduino is limited and there are other control boards that can accomplish this, it would help a lot if you can point me in the right direction.

body:
1000 measurement for 10 sensors per seconds, it means there are 10000 measurement per sec with 0.1 mS time slot for each measurement.

According to [SRF-04 Documentation][1],

**(1)**
> If nothing is detected then the SRF04 will lower its echo line anyway after about 36mS.

So, **time slot for each reading is 36 mS** ("if" nothing is detected), which means for 10 SRF04 x 1000 reading, it will take 360000 mS = **360 Sec**.

**(2)**

> I would want all 10 sensors to send a 40kHz pulse at the same time, and then when a return signal is recorded, another 40kHz pulse is sent out.

Its seems reasonable. **But**,
[![enter image description here][2]][2]
According to the timing diagram, 1 cycle minimum period consist of :

 1. 100 us Trigger pulse ==> 0.0001 s
 2. 8 Cycle burst at 40 kHz = (1/40000)*8 s ==>  0.0002 s
 3. 100 us Echo pulse ==> 0.0001 s
 4. 10 ms delay time ==> 0.01 s

Total for 1 cycle is 0.0104 s, so for **1000 readings x 10 sensors (object to detect is present) will be 104 s**.

All sensor burst at the same frequency, great idea. **However** it's not advised (or rather not possible) because that will disturb each sensor reading unless you successfully change each sensors frequency or doing sound modulation. Even if you success in modulating 10 sensors frequency, the needed time is still not met 1 s interval

 1. 100uS for 10 sensors trigger pulse at once ==> 0.0001 s
 2. 8 Cycle burst at 40 kHz = (1/40000)*8 s ==>  0.0002 s
 3. 100 us (minimum) Echo pulse --> 0.0001 s x 10 sensors ==> 0.001 s, because Arduino does not support threading, which mean there is no way you can read all at same time
 4. 10 ms delay time ==> 0.01 s

Time for 1 cycle (10 sensors reading): 0.0113, **1000 readings : 11.3 s**

**(3)**

  "How about changing the beam pattern?"

> **Changing beam pattern and beam width**
You can't! This is a question which crops up regularly, however there is no easy way to reduce or change the beam width that I'm aware of. The beam pattern of the SRF04 is conical with the width of the beam being a function of the surface area of the transducers and is fixed.

So, rather than trying to modify the ultrasonic, more reasonable solution is changing the way you do elevation measurement.

  [1]: https://www.robot-electronics.co.uk/htm/srf04tech.htm
  [2]: https://i.stack.imgur.com/XMim8.gif


message:
Replacement crystal on Uno for cold temperatures

I want to run an arduino out in the cold (-40), and use the serial communication - I believe that the crystal is the weakest link (the one for the serial chip) - however I don't see any drop-in (through-hole) replacement crystals that would work in such cold, so would a SMT version work instead? if so, which one would be possible to solder (package?), and do I need to change the caps to match?

P.S. - Yes, I could heat it/insulate it, but that comes at a fairly high power/complexity cost

body:
There is a solution for just this problem, it's a "crystal oven". It is used to keep a crystal at a constant temperature so that the oscillating ferquency remains very stable.

Crystal ovens are usually expensive as they are quite precise and have good insultaion, but here's a kit that you might adapt for your uses: http://www.minikits.com.au/Oscillator-Heater, or google around to see if you find something that might suit you better.

You could also consider making a heater with a simple temperature regulator of your own to keep the crystal warm  (many temperature sensors for Arduino are available on the web).


message:
Sparkfun ESP8266 Wifi Shield does not receive data

When I make any GET request to my shield, the only thing I get when I read the request is '\r\n'.  I am sending query parameters, and when the request has been read in the past, there was the full http request.

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

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

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

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

    This code is released under the MIT license.

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

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

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

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

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

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

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

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

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

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

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

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

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

      serverSetup();
    }

    void loop()
    {
      serverDemo();
    }

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

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

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

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

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

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

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

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

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

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

    }

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

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

    boolean currentLineIsBlank = true;
    ....

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

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


body: It's an issue using String with arduino.  I've changed to use char[] and now it is working fine.


message:
My RTC DS1307 isn't returning any information. It seems to be stuck in the isrunning() function. Does anyone have debugging tips?

I'm using an RTC DS1307 to keep track of time for long periods. It seems to be stuck in a function. I'm using the RTClib suggested by adafruit.

How can I get it unstuck and get values returned? Are there any debugging or troubleshooting tips that would be helpful?

Referencing this excerpt for the code I'm running.

    void setup () {
      while (!Serial); // for Leonardo/Micro/Zero

      Serial.begin(57600);
      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }

      if (! rtc.isrunning()) { //// **Where I think my code errors.**
        Serial.println("RTC is NOT running!");
        // following line sets the RTC to the date & time this sketch was compiled
        // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
      }
    }

This is the example code modified slightly to increase logging, included with RTClib. It's for the DS1307.

Currently the output from the serial port is as follows:

>RTC is found.

I changed the code to the below:

        // Date and time functions using a DS1307 RTC connected via I2C and Wire lib
        #include <Wire.h>
        #include "RTClib.h"

        RTC_DS1307 rtc;

        char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

        void setup () {
          while (!Serial); // for Leonardo/Micro/Zero

          Serial.begin(9600);
          if (! rtc.begin()) {
            Serial.println("Couldn't find RTC");
            while (1);
          } else {
            Serial.println("RTC is found.");
          }

          if (! rtc.isrunning()) {
            Serial.println("RTC is NOT running!");
            // following line sets the RTC to the date & time this sketch was compiled
            // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
            // This line sets the RTC with an explicit date & time, for example to set
            // January 21, 2014 at 3am you would call:
            // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
          } else {
            Serial.println("RTC is RUNNING.");
          }
        }

        void loop () {
            DateTime now = rtc.now();

            Serial.print(now.year(), DEC);
            Serial.print('/');
            Serial.print(now.month(), DEC);
            Serial.print('/');
            Serial.print(now.day(), DEC);
            Serial.print(" (");
            Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
            Serial.print(") ");
            Serial.print(now.hour(), DEC);
            Serial.print(':');
            Serial.print(now.minute(), DEC);
            Serial.print(':');
            Serial.print(now.second(), DEC);
            Serial.println();

            Serial.print(" since midnight 1/1/1970 = ");
            Serial.print(now.unixtime());
            Serial.print("s = ");
            Serial.print(now.unixtime() / 86400L);
            Serial.println("d");

            // calculate a date which is 7 days and 30 seconds into the future
            DateTime future (now + TimeSpan(7,12,30,6));

            Serial.print(" now + 7d + 30s: ");
            Serial.print(future.year(), DEC);
            Serial.print('/');
            Serial.print(future.month(), DEC);
            Serial.print('/');
            Serial.print(future.day(), DEC);
            Serial.print(' ');
            Serial.print(future.hour(), DEC);
            Serial.print(':');
            Serial.print(future.minute(), DEC);
            Serial.print(':');
            Serial.print(future.second(), DEC);
            Serial.println();

            Serial.println();
            delay(3000);
        }

body:
First thing I see is the Serial setup seems a bit backward:

      while (!Serial); // for Leonardo/Micro/Zero
      Serial.begin(57600);

First, begin Serial; then wait for it to become ready:

      Serial.begin(57600);
      while (!Serial); // for Leonardo/Micro/Zero

Next, is this while(1); inside the if statement:

      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }

Which says "if !rtc.begin(), then println and go into an infinite loop that does nothing".

Try:

    while (!rtc.begin()) {
        Serial.println("Couldn't find RTC");
        //delay(500);  // depending on how fast you want this thing to retry/print
    }

the final thing I see, is the next section of code appears like it might be "work code" but is in the setup() function and is missing any kind of a loop.  So it's going to run the if statement once, then setup() exits (and loop() starts getting called).

Either replace the "if" with a "while" and wait for "rtc.running()"

    while (!rtc.running()); // Waiting for RTC to be running
    // Set the clock time

or move it out of setup() and put it inside loop()

    void loop() {
      if (! rtc.isrunning()) { //// **Where I think my code errors.**
        Serial.println("RTC is NOT running!");
        // Perhaps try and fix it?
      } else {
        // If the time hasn't been set; set it; then move on
      }
    }


body:
Wow, that was hard to figure out. My RTC DS1307 came with an extra pin. This tripped me up when wiring the circuitry. I was off by a pin on my breadboard. Thank you everyone for your help.

Specifically, I had the ground going to the empty pin, and the 5v line going to the ground. Perhaps the circuitry allowed some current to go from the ground up and triggered the "i am here" part of the circuitry.


message:
ArduinoUNO/MEGA, Is there a way to exceed 256 in analogWrite

I am using Arduino UNO/MEGA, I want to

    analogWrite(pin, val);

where the value is 0-1023.

How can I make that ?

Thanks.

body:
The simplest way is to change your value range to 0-255. You can't change analogWrite's range, since that is fixed in the core software.

    analogWrite(5, val >> 2);

The `>> 2` bit-shifts the value two bits to the right, turning a 10-bit value (0-1023) into an 8-bit value (0-255). It's by far the most efficient way of dividing by 4.

On more complex 32-bit boards, like the Arduino Due, or the chipKIT range of boards, etc, you have the function [analogWriteResolution()](https://www.arduino.cc/en/Reference/AnalogWriteResolution) which can change the range, but that cannot be done on the 8-bit boards.

From what I have read online it looks like the ATMega chips may support higher resolutions for PWM - however there is no support in the core for that. If you need a higher resolution for some specific reason then you will need to program the registers manually yourself and not rely on the Arduino API to do the work for you. For that you will need to consult the datasheet for your chosen chip.


body:
I agree with @Majenko's answer, though here is a more "beginner" friendly method of doing the same.

    val = map(val,0,1023,0,255);
    analogWrite(pin, val);

Not the most efficient, but still...


body:
Section 16, "16-bit Timer/Counter1 with PWM" of *[Atmel-8271J-AVR- ATmega-Datasheet_11/2015][1]* describes using Timer/Counter-1 for 16-bit PWM, including sample code in both C and assembler. It might take a couple of reads over that section to get familiar with the hardware and learn what else T/C-1 is used for, and that you might have to give up while using it for PWM, but the code is fairly straightforward.

Using this T/C would give you 2-bits more resolution in your PWM output than mapping onto an 8-bit counter, if that is what your project needs.

+1 for the question. Not having needed PWM output for anything more than a demo with my DMM (yet), it hadn't occurred to me to look for a higher resolution until now.

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf


body:
The other questions so far have correctly addressed one possible meaning of this question, "how can I increase the resolution?"  Here's another possible interpretation.

# How can I increase the output magnitude?

It sounds like you might want to output a higher maximum voltage than what you get from using `analogWrite(pin,255)` on the Uno or Mega.  This is not possible using the Arduino by itself, because PWM represents a fraction of the maximum output, not an absolute value.

On the Uno and Mega, that maximum output is 5V, so the approximate values come out to:

    analogWrite(pin,0);   // (0 / 255) * 5V   (0% of 5V == 0V)
    analogWrite(pin,127); // (127 / 255) * 5V (50% of 5V == 2.5V)
    analogWrite(pin,255); // (255 / 255) * 5V (100% of 5V == 5V)

If you want to make a higher absolute voltage, you will need an external power source and a method of translating the 0-5V output into another voltage range.  This is called "level shifting" and there are standalone ICs which can do this job.  Motor drivers and H-Bridge devices utilize this principle as well.

If you use some sort of level shifting circuitry, then you can map the analogWrite to a different range, such as 0-20V:

    analogWrite(pin,0);   // (0 / 255) * 20V   (0V)
    analogWrite(pin,127); // (127 / 255) * 20V (10V)
    analogWrite(pin,255); // (255 / 255) * 20V (20V)


message:
two dimensional array with 3 characters per entry?

my plan is to create a two dimensional array with 3 characters in each cell.

what i have tried:

    char keys[3][8][8] = {
      {' ','4','5','6','x','/',' ',' '},
      {'x10','7','8','9',' ',' ',' ',' '},
      {'.','rcl','eng','(',')','sd','m+','^2'},
      {'0','(-)','..,,','hyp','sin','cos','tan','hyp'},
      {' ','br','wur','^2','^x','log','ln',' '},
      {' ',' ',' ',' ',' ','mode','log',' '},
      {'=',' ',' ',' ',' ',' ','^3',' '},
      {'=','1','2','3','+','-',' ',' '}
    };

unfortunatelly this gives me the error:

> error: too many initializers for 'char [3][8][8]'

so what is wrong?

body:
> error: too many initializers for 'char [3][8][8]'

The order is wrong:

    char keys[8][8][3]

But then some of the literals are larger than int and give a warning as they are truncated.

Easiest is to define as string literals:

    const char* keys[8][8] = {
      {" ","4","5","6","x","/"," "," "},
      {"x10","7","8","9"," "," "," "," "},
      {".","rcl","eng","(",")","sd","m+","^2"},
      {"0","(-)","..,,","hyp","sin","cos","tan","hyp"},
      {" ","br","wur","^2","^x","log","ln"," "},
      {" "," "," "," "," ","mode","log"," "},
      {"="," "," "," "," "," ","^3"," "},
      {"=","1","2","3","+","-"," "," "}
    };

This can be further improved (stored in program memory, etc).

Cheers!


message:
Servos and Random Number

I am new to coding and this website so I apologize if I make any mistakes. I am trying to get servos to move when a random number is generated. Like if I roll a 2 I want servos 1, 2 and 3 to open and then if I roll a 3 after I want servos 4, 5 and 6 to open. I am able to hold the previous values in the code now but can't get the servos to go with it. Any help is great! Thanks!

    #include <Servo.h>

    Servo myservo;

    int pos = 0;    // variable to store the servo     position
    int x = 0;
    int button = 8;
    int BUTTON;
    int randomNumber;
    int xPrevious = 0;
    int oldNumber;

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

    void loop() {

    BUTTON = digitalRead(button);
    Serial.println(BUTTON);
     if(BUTTON == LOW){
      randomNumber = random(1,4);
      delay(275);
      Serial.print("Random Number ");
     Serial.println(randomNumber);
     if( xPrevious == 0) {
       randomNumber = randomNumber + 1;
     }

      // Only want it to do this on the first roll.
         xPrevious = randomNumber + xPrevious;
         Serial.print("xPrevious ");
         Serial.println(xPrevious);
        oldNumber = xPrevious;

     for (x = randomNumber; x <= xPrevious; x += 1) {
      myservo.attach(x);
      Serial.println(x);

      for (pos = 0; pos <= 180; pos += 1) { // goes     from 0 degrees to 180     degrees
     //in steps of 1 degree
        myservo.write(pos);              // tell servo to go   to position in variable 'pos'
        delay(15);                       // waits 15ms for the     servo to reach the position
      }
      for (pos = 180; pos >= 0; pos -= 1) { // goes  from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go    to position in variable 'pos'
        delay(15);                       // waits 15ms for the  servo to reach the position
      }

     }
     }
     }

body:
You planning to use multiple servo, but only declare one.
I still don't get about the pattern, but maybe this will give some image:

    Servo myservo[5]; // assuming you have 5-servo
          // servo[0]--> pin 0
          // servo[1]--> pin 1
          // servo[2]--> pin 2
          // servo[3]--> pin 3
          // servo[4]--> pin 4
    pos = 0;

    void loop() {

    BUTTON = digitalRead(button);
    Serial.println(BUTTON);
     if(BUTTON == LOW){
      randomNumber = random(1,4);
      delay(275);
      pos+=randomNumber;
      Serial.print("Random Number ");
      Serial.println(randomNumber);
      Serial.print("Current pos ");
      Serial.println(pos);

     for (x = 0; x < randomNumber; x++) {
      myservo[x+pos].attach(x+pos);
      Serial.print("attach servo-");
      Serial.println(x+pos); }

    //open (move from 0-180 degrees)
     for (x = 0; x < randomNumber; x++) {
      myservo[x+pos].write(180);
     }
     delay(2000);

    //close (move from 180-0 degrees)
     for (x = 0; x < randomNumber; x++) {
      myservo[x+pos].write(0);
     }
     delay(2000);

    //detach servo
     for (x = 0; x < randomNumber; x++) {
      myservo[x+pos].detach();
     }
     delay(2000);
    }
    }


message:
Arduino UNO Chinese Clone LEDs not lighting up

[![LED Circuit][1]][1]

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

Hi all,

In the screenshot of a circuit I've included, I'm attempting to light up 4 LEDs off of pin 2. In circuits.io, everything works great. 3 blue LEDs and 1 red LED light up and blink as planned. When I create this same circuit on a Arduino Uno Chinese clone, IF the LEDs are all blue, they all light up and blink. If I change one of them to red, yellow, or green, ONLY the red, yellow, or green one lights up. The three blue LEDs no longer light up. It also doesn't seem to matter, where the off blue LED is put.

Not sure what's wrong.

body:
Use one resistor per led, not one for all of them.

This is because different color leds have different forward voltages. Red requires a lower voltage to light up. So it will guzzle up all available current, while the blue leds are waiting for the voltage to go higher (which never happens).


message:
Arduino and C++ Serial communication

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

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.


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

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

EDIT:
Code:

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

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

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

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

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

    int cursorNum=0;

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

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

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

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

    }

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!


message:
How accurate the an attiny timer function

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?

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.


message:
Identify UUID of HC-06

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.

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


message:
10 bit PWM on Arduino UNO

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.

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


message:
eval() function for Arduino?

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?

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


message:
Using ATTiny85 as a USB HID Mouse

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"

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)


message:
Using an Arduino as a lithium ion charge controller

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.

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.


message:
control vibrator motor speed with ultrasonic sensors

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

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.


message:
Merging strings and constants causing scope errors

I'm getting a few errors when merging strings with constants.

Here's the pertinent code...

    #define STATION_ID ABC123
    #define STATION_PASS XYZ987

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

And then the errors...

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

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

Not sure where I'm going wrong on this.

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.


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

I'm fairly new to this, and I haven't been able to find any answers after searching repeatedly.

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

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

    LoadMainScreen();
    return;

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

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

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

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

    LoadMeasScrn();
 loop();
    return;

and the same thing happens.

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

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

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


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

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

Here is the GPS Code:

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

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

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

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

    waitForFix();
    printFix();
    }

    void loop()
    {
    }

    void waitForFix()
    {
    uint8_t fixes = 0;

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

    } // waitForFix

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

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

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

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

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

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

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

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

Here is the Magnetometer Code:

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

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

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

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

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

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

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

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

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

    delay(250);

    while(1);

    }

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

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


message:
Which external programmers work reliably with Arduino Mega?

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

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


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

After all there is more question poping up then answers i decide to upload the pdf where is everything writen, like the wire, motor type and what we can and can't use. Here is the link [pdf format of the assignment][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

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


message:
connecting lv maxsonar ez arduino

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

Thanks

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.


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

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

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.