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

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

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

no it's true to begin with, because if we get a \n, then we are at the end of the first blank line.  If the first character is not \r or \n, then we set currentLineIsBlank = false because there is something on the line

have you tried checking (Serial.print(c)) the value of c after reading it from client.read();  What are you seeing here as the request coming in...

It's an issue with using String.  I've made a bunch of changes to switch from String to char[], and it is working, thanks for helping


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

What is the serial output?

@dpw per your suggestion, I included the serial output. I also included full code to review.

Try changing the battery.

@Gerben I've checked the battery voltage multiple times. It has 2.98 volts under load and 2.98 off load. Is this acceptable?

That's just fine.

@Gerben looks like min voltage is 2v max is 3.5v according to this datasheet.

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

You make a good point that I'm asking about my program not responding, and I have all these loops that don't end and don't respond!
This is the example code that came with the library. I believe it worked before.

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.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


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

It seems there are two types of answers emerging - those that increase the resolution of the PWM, and those that adapt your data to fit the existing resolution, using something like map.  I find both types of answers to be useful, but you might want to clarify what your intention is for going to 1023.

@GuitarPicker, the data that returns from analogRead is from 0-1023

@GuitarPicker  The data comes from analogRead is 0-1023, how can I output the same data using pwm, that's is .

Section 16, "16-bit Timer/Counter1 with PWM" of Atmel-8271J-AVR- ATmega-Datasheet_11/2015 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.

This is the correct answer. Neither of the other 2 answers say how to output the resolution he wants.

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

I'm pretty sure the compiler will optimize x / some_constant_power_of_two to x >> exponent_of_the_number.

@Kroltan Quite probably. It's something I would hope it did do. Personally I like to be explicit though, just on the offchance that it doesn't.

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

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)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


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

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!


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

 }
 }
 }

Can you explain more? I still don't get the "random" pattern

Yeah so it is basically going to be a game where you roll a random number and when you get that number servos will open. For example I roll a 2 on my first time so servo 1,2, and 3 will open. 1 will open because that is where a ball starts. Then on the next turn I roll a 5 so servos 4,5,6,7,8, and 9 open. Does that make more sense?

if "n" is a random number, the opened servo are servo(0+prevpos+1) through servo(n+prevpos+1)? correct?

I think that is it

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


text:
Arduino UNO Chinese Clone LEDs not lighting up

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.

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

I'd like to note that you may want to calculate the required resistor value. One pin can't supply a lot of current.

Good point @Paul. An Arduino pins shouldn't supply more than 20mA. That's 5mA per led, if you use 4 leds. If you use 1kOhm for each led, like in the diagram above, you should be fine.


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

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

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.


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

}

Perhaps putting your current code ?

Relevant: Smart design of a math parser?

Characters in a char[] variable may be encoded in ASCII or Unicode. You will want to convert them to numbers in this case. Consider subtracting the ascii value of one less than 0 from each char to get the number. Edit: @Matt informed me that 0 is the lowest ASCII number. As he suggested, you can subtract the character '0' from the digit to get the value. You want to specially handle any addition, division, or other operator symbols.
Then you can treat each number like a digit in a number. If you can break up the array of numbers by the operators, you can successively attach the operands to the operators. Keep in mind that each number to the left is a power of ten (assuming this is how it's implemented. This is called Endianess.)
If you post code I may be able to help further.

"one less than 1" ?? In other words zero?  The idea is correct the keypad libraries usually return a char so int number = KeyPad.getChar() - '0'; would work

I was thinking that ''1' was the lowest ascii number. I just checked a ascii table and it looks like '0' is. I'll update my answer.

You could parse it with something like this:
int parserr;

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

The variable parserr holds the error position (+1), zero is no parse error.
The function parse() will return the value of the simple expression with no operator priority.
This can be refactored to allow normal operator priority:
#include <ctype.h>

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

private:
  char* m_ip;

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

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

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

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

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

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

Cheers!

What if I input "2+53”? I believe it should do "53+2 = 17", and not (2+5)*3 = 21.

That is what "no operator priority" means :). Parsed and executed in order. It is easy to modify for priority operators.


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

Just measure how long it actually take. Then change 86400000 to a lower or higher value, depending on whether it took more of less that 24 hours to re-flash the led. You could still get some drift, depending mostly on the temperature, but probably accurate enough in your case.

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.


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

Voting to close: this is a question about the HC-06 or iOS development, not about Arduino.  That said, you might want to see what a BTLE scanner program like "light blue" or similar can find.

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

Android use the SPP protocol as the HC-05 and HC-06, but it seems iOS don't. So comunicating with an iOS machine would be difficult.

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


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

Do you know even what PWM is...?

If you want, you can teach me

Or you could ask Google...

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.
If you want to measure the PWM value, I suggest you read:
Can I connect a PWM pin on one Arduino to an analog input on another?

Thanks for your note, I just got output like that, which is wrong I guess.
0
0
1022
1021
0
1022
1021
0
0
1021
0
1021
1021
0
0
1021
0
0
1022

I update my answer

Thank you, does that allow me to make arduino output analg data like a potentiometer ?

Based on @Russell answer from the link above, yes.

but, why I don't write that code when I use a potentiometer for example ?

unless you put capacitor and resistor, (to make the signal "less square"), analogRead will keep returning HIGH and LOW value. While the other way is measure the time difference between pulseIn(3,HIGH) and pulseIn(3,LOW). That way you can get the duty cycle, which mean, calculating the rest is possible.


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

Guess there is more to this question as "String term = 12 + (2 * 5);" can be evaluated at compile time.

TinyExpr 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:
#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.

No, there are no alternatives. You need to parse the string and perform the operations yourself.
Personally I prefer to use RPN 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).

Here is a shell that works accordingly. A mix of Forth and Postscript syntax; https://github.com/mikaelpatel/Arduino-Shell

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.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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, 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?

Due to the lack of USB-Support of the ATtiny85 you will be forced to use something like V-USB 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.

If we use a breakout board with a USB like

If we use a breakout board with a USB like this one we won't need V-USB right? https://www.amazon.in/dp/B00Z09R3YC/ref=cm_sw_r_cp_apa_i_LKhnyb5J9FFWE

The description tells so. But it does not state how the USB is addressed. I suspect there is a boot loader that is used for programming (and therefore reduces the available space) basing on V-USB or similar. Perhaps it provides a wrapper so you can address USB easily.

There is a USB port right?

@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, 3.3V/8MHz)
Arduino Micro
Dreamer Nano V4

You forgot about the Arduino Leonardo

@Kwasmich, too big, never seen a mouse that big. I suggested the smallest models.

@Kwasmich we were aiming to be as portable as possible.


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

I'm not saying you can't.  All I'm saying is by the time you do have the equivalent of a "good" Power Management Chip (PMC), you will have used up a lot of trinket resources.  But it you are in it to learn - go for it!

Yeah, wondered if I could simplify it, not make it too complex, something similar to the way Arduino approximates a PID, monitor the voltage and toggle the charge on and off periodically

If you're new to this then you should consider using LiFePO4 instead. It's a little more forgiving of screw-ups.

Why not use a charging+protection IC?

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

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.
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.
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.
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 if you would like to research this subject in greater depth.

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). Protected cell can do this for you. I'm not knowledgeable enough to know if it's a good idea to rely on this.
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.

Never rely on the in cell protection. It is there as an emergency fail safe, not part of the battery management.

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

well, cost is an issue, was wondering if I could simplify it ... also I want to use a solar cell as the charger, so this chip would not work


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

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

The wiring diagram is very difficult to read. It would be better tor read if you redraw it with the builtin schematic editor.

Does this 'if(160 >= distance > 90)' actually work as intended in arduinoees? I don't believe it does in any flavor of C. You also have 3 lines of 'duration = ...' so you're just overwriting the 1st 2 with the last one.

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)

PS - You could streamline you setup function if you use arrays for the pin assignments, and you can do the same wit you motors too.

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.


text:
DHT22 reading weird values
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.

Since the sensed  value exceed the max value, perhaps code error?

Arduino Mega:
"
Temperature: 716.80 *C
Humidity: 1024.00%
"
library fake :-(

Have you tried this with the standard libraries (AdaFruit_Sensor & DHT)?  Plus, it is helpful if you show the code you are using.


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

Maybe? Not sure, but give this a try.
#define STATION_ID "ABC123"
#define STATION_PASS "XYZ987"

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.

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.

Calm down @Majenko, did you see this? Here's the pertinent code... I think he just gave an example. I think this: That is just so wrong on so many levels. is a little rude

You may think it's rude, but that doesn't stop it being completely true. It is so very very very wrong. On soooo many levels.


text:
"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/////////////

It's impossible to say from those tiny snippets. We need to at least see the structure of your whole code.

Well, I can't post my code. It's 800 lines long, anyway, so I doubt anyone would want to sift through it. Not sure what I could do to better explain the situation. This is more of a question of how the return function is supposed to work.

At the very least show us how and where those functions are being called.

Return does what it says it does. The problem isn't with the return - it's either with how you are using it, or the rest of the structure of your code.

Not here! In your question!

Ok, I'll try with some pseudocode in an update

At first glance that structure looks fine. Are you sure the board isn't crashing and resetting? Maybe due to lack of memory?

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

I follow you. I replaced the recursion cases with something else I found. I'm now using a label at the very beginning of startscreen()
`startover:`

I'm then calling goto startover; Does this effectively start the function over at the beginning without the recursion problem?

Yes, that's quite different to recursion. Did it alter or help with the original issue?

I think so! It had not occurred to me before that the program had gone back to a previous instance of startscreen(). Looking back though, I can see where it might have occurred without me knowing.

This part is wrong, for a start:
LoadMeasScrn();
loop();
return;

That would recursively call loop (which you almost never want to do) effectively putting you into loop a second time.
return does what is advertised to do. Your rather complex pseudo code demonstrates nothing. Please post a Minimal, Complete, and Verifiable example

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

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

You have an incredible amount of recursion. You possibly think that if StartScreen calls itself then it goes back to the start (like a goto) but no, you are now two levels deep into StartScreen.
Plus here:
void StartScreen(void) {
...
  if (stuff)
...
                Recheckframe();

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

It's a wonder it doesn't just crash by running out of RAM.
You say "//Start all over" but it isn't starting all over. You are now digging deeper and deeper into the call stack.
Your call stack will look something like:
StartScreen -> StartScreen -> Recheckframe -> StartScreen

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

Alright, fine. Hope I don't get fired.

See amended answer.

Incredible recursion!!!!!!!!!


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

The solution in short.
Although the link is very stupid, it shows very well what you have to do.
Pretty much make a code that combines both of them together. Put both setup in the new setup and carry on like that. Note that you have declared the serial monitor at 2 different baud rates so you can only pick one. Don't repeat previously declared things in your new code and you should be good to go.

Simple example:
Code 1:
const int buttonPin = 2;

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

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

Code 2:
const int potPin = A0;

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

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

Fusionned code:
const int potPin = A0;
const int buttonPin = 2;

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

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

  Serial.print("  -  ")

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


text:
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, USBtinyISP).
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 programmer, which doesn't look like its going to work. Does anyone have proven experience with a given programmer and a Mega?
The suggested AVR-mkII doesn't seem to be available anymore either.

I always use USBasp.

Voting to be "opinion based", basically any ICSP programmer for AVR should work. I also like the USBasp and have never had any troubles with it (even when bought for around 5$ from e-bay). It's very much of a shopping question, is very broad (since there are a lot of programmers, and ways to program) and opinion based, since everyone has his own thoughts on reliability of some programmers.

Yes, to some extent; however, I was hoping for a certain type of answer. For example, a "Use A because it offers X, Y, Z, even though it suffers from U, V, and W."

Currently the Arduino.cc page has nothing about why I should choose one programmer over the other, or even which programmers are actually compatible with their boards (it looks like most of the time the MEGA, as specifically addressed in this question, isn't compatible).

I have successfully used Arduino as ISP (not to be confused with Arduino ISP) 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.

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.

authors: 天九娱乐代理--平台总代


text:
How to move my robot in the right direction?
After all there is more question poping up then answers i decide to upload the pdf where is everything writen, like the wire, motor type and what we can and can't use. Here is the link pdf format of the assignment
So i am working on a project for the school, it is first time for me to work with Microcontrollers. I and i got stuck with the rest of my assignment, so i hope a good soul can help me out with this.
So my code for now is this
#include <stdio.h>
#include "dev/uart.h"
#include <util/delay.h>
#include <avr/io.h>
#include "dev/adc.h"

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

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

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

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

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

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

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

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

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

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

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

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

    return vector;
}

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

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

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

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

    while (1){

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

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

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

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

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

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

What it does now it reads the input values from joystick and it can be (x or y) min: 8 and max: 900, but we need to map it to [-100,100] this works but not perfect, so if someone can help to do the mapping better i would be grateful, but that is not the main point of my question.
But my real question is how i can  programm the MCU to generate PWM signals ?
I need to implant those 3 functions :

servo_init(), to initialize the timer/counter2;
servo_left(int v), to set the angular velocity of the left wheel;
servo_right(int v), to set the angular velocity of the right wheel;

There are four registers to be set during the initialization: TCCR2A, TCCR2B,
OCR2A, OCR2B.So what they mean ?
The two functions servo_le f t(intv) and servo_right(intv) set the corresponding
Output Compare Register to control the pulse duration of the output
control signal. The input parameter v of each function is an integer in
the range [−100, 100] whose absolute value is proportional to the angular
velocity of the corresponding servomotor and whose sign defines the direction
of rotation. As overall, these functions map the input range [−100, 100]
to the output range [1.0, 2.0] ms which corresponds to the pulse duration
of the control signal, thus the angular velocity and rotation direction of
the servomotor. Notice that, as the two servomotors are symmetrically
mounted, one of the two functions has to invert the direction of rotation.
Right wheel : PortB, pin 4, Output Compare Register : OC2A, TinkerKit Conn:  O1
Left wheel : PortH, pin 6, Output Compare Register : OC2B, TinkerKit Conn:  O2
I spend all day on the internet finding anything that would help out, but i didn't have any luck.

It's not wrong, but I just want to confirm something. You are using Arduino right? because your code does not seems like one

You may ask your teacher if it's okay to use the Arduino platform or servo libraries. Possibly it is, possibly he wants you to implement it in a low level fashion.

Don't cross post on multiple SE sites. Your other question was already put on hold for being off topic, but you asked here before that.

Because i din't know that we have this page.

||-----PWM Register Explanation-----||
It will be easier to explain with an example.
Here is a sample of Timer setup on ATMega2560 (assuming that is the one you use due to the tag "Arduino-mega") based on  datasheet section 20 : 8-bit Timer/Counter2 with PWM and Asynchronous :Operation:
TCCR2A= 0b10110001; //set COM2A1, COM2B1, COM2B0 and WGM20
TCCR2B= 0b00000001; //set CS20

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

COM2A1, COM2A0 set the Timer2A on non-inverting mode, and COM2B1, COM2B0 set the Timer2B on inverting mode.
OCR2A and OCR2B is the duty cycle value of PWM. Because timer2 is 8 bit, so the value is ranging from 0-255. Its also the answer to your question

How i can program the MCU to generate PWM signals ?

PWM Signal frequency is defined by its duty cycle :

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

for example :
OCR2A = 100;
OCR2B = 155;

Timer2A will work on 39.2% duty cycle and OCR2B will also work on 39.2% duty cycle. What? Because Timer2B works on inverted mode (100%-60.8%) ==> 39.2%
||-----PWM topic closed here-------||
I've seen several people losing several hair while trying to control analog servo without manually  (well, some even move to Arduino only because of its servo libs).
You can check this Servo Library which is (maybe) the most common library used to control servo using Arduino (which also mentioned in @st2000 answer).
But, it will be better if you also post a detail about your "motorservo". At first I though it was a motor DC (by its PWM - Dir configuration).
||-----Additional-----------------------||
In your while(1), there are several if that can be optimalized by using simple if-else if-.. statement. So this one would be better (also minimalized "bug" chance) :
while(1)
{
  if(!PUSH && !TILT)
       {...} else
  if(PUSH && !TILT)
       {...} else
  if(PUSH && TILT)
       {...} else
...
...
}

--EDIT--
After reading several page of the PDF, I assume you have to make your own library (not Arduino). Perhaps this will give you something :
void servo_init(void)
{
 TCCR2A= 0b10110001;
 TCCR2B= 0b00000001;
 /*phase correct PWM mode,
  *no clock prescaler,
  *Timer2A -> non inverted,
  *Timer2B -> inverted
  */
}

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

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

}

we are using two servomotor's to control the movements of the robot. He goes forward and backwards when the 2 motors have the same velocity and right or left if on has high velocity then other one.

If so, further information about the servomotor is needed. i.e : what is the motor series? do you use driver motor?  what about the wiring? You can edit your question with those information so that other user can quickly notice

so i edit the question and post a link to the pdf, because it would be just annoying to type it all

Let us continue this discussion in chat.

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.

please see my.comment about the motor above.

authors: 卧龙娱乐代理-平台q1530667-总代

authors: 恒行3娱乐代理--平台总代

authors: 门徒娱乐代理--平台总代


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

Don't cross post on other SE sites.

Sure, I got confused because I was afraid that this question won't be relevant here. But I got the answer :)

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.

To be precise, the pin labelled 5V.


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

post: How to connect ESP8266 12e directly to Arduino Uno (without shields)

In engineering, you'll have to use valid sources and constantly validate your choices (and explore options). Why would you even use an Arduino + ESP8266, if you can use an ESP8266 dev board (with USB) instead of an Arduino (+ESP)

Have you also checked the answer on that question? You could check other sources and see if they validate that connection, or simply do it conoletely different (try to explain why thuis connection is right, and other aren't)

i already bought arduino and because of my budget i am unable to buy dev board. So is there a way by which i can integrate esp8266 12e(without wifi shield) with arduino

They're around 4$, but you could also use an Arduino (or USB<->serial chip) to program the ESP8266 directly.

But, have you checked other sources? And what firmware is installed on your ESP8266?

i dont know about the firmware and unable to check it. I am unable to make esp8266 work with arduino. Is there a schematic and code available to make this happen

How can you be sure that you can communicate with the device, if you're not sure what firmware is installed. It may not have any firmware on it as far as we know?

A NodeMCU fits on breadboard. Check dev boards, because a standard NodeMCU might not fit in it.

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.

can you suggest which breakout board should i use. And what proper method i should follow to use esp8266 12 e perfectly. And guys i live in india and the things are 2 or 3 times costly, and where i live don't have varieties of this things even online i don't have much options.    I am trying to find out ideal breakout board for 12e .But in mean time i can use suggestions that how can i use 12e.   :)

Something like this item from AliExpress https://www.aliexpress.com/item/10Pcs-Set-ESP8266-WiFi-Modules-Breakout-Transfer-Board-Adapter-Plate-For-ESP-07-ESP-08-ESP/32655534675.html?spm=2114.01010208.3.37.hpB7yI&ws_ab_test=searchweb0_0,searchweb201602_3_10065_10068_10000007_10084_10083_10080_10082_10081_10060_10061_10062_10056_10055_10054_10059_10099_10078_10079_10073_10097_10100_10096_10070_10052_423_10050_10051_424,searchweb201603_6&btsid=3433ccd4-e3f2-4707-8e9f-7968b5f02360
Or something similar.  Just to make the ESP more useable.

You may be able to make you own break out boards depending on your soldering ability.
How do you use it properly?  In the Arduino IDE use the board manager to download the support for ESPs.  At the basic level it is so similar to an Arduino you will laugh.  There are loads of tutorials out there, the biggest problem is remembering that in the code digital pin 0 means GPIO 0 which may or may not be marked as zero on your board.  On my boards pin 0 is pin 6 :)

@Matt, for the pins, you may want to do a search on ”[name of your breakout/devboard] Arduino pins" and do defines such as: '#define PIN6 D0', to have a solution that has no runtime overhead and is as easy to use.

I am the author of the linked question. 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, embed below:

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!

There is also a library which can help you communicating with ESP2866 through Arduino called WiFiEsp.
It's like WiFi library for Arduino but instead for ESP8266.

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.

authors: 信无双2娱乐代理--平台总代