text:
Waking up async the Arduino while it is sleeping periodically
I´m using LowPower.h and PinChangeInt.h libraries to put my Arduino into the sleep mode every 8 seconds and then it wakes up, modifies a counter and it goes to sleep again, but also I need to wake it up when a button is pressed asynchronously.
I´ve reached to wake up the Arduino every 8 seconds using LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF) and, in other code, I´ve also reached to wake it up while it sleeps indefinitely with LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF) but I can´t combine that periodical awakening with the asynchronous awakening.
Here is my code:
void setup(){

    Serial.begin(9600);

    //Pines declaration

    loopsToSend = setTimeToSend();  //

    //The three async buttons
    PCintPort::attachInterrupt(4, readOpinion,RISING);
    PCintPort::attachInterrupt(5, readOpinion,RISING);
    PCintPort::attachInterrupt(6, readOpinion,RISING);
}

void loop(){

    if(loops < loopsToSend ){

        byte opinionValue = readOpinion(); //This method must awake the Arduino ASYNC to give a value to the opinionValue var, write the result in the file and go to sleep

        if(opinionValue != 0){
            Serial.println("Button pressed!");

            //Writing result in a file
            opiniones++;
            delay(500);
        }
        //Go to sleep 8 seconds
        LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
        opinionValue = 0;
    }
    else {
        wdt_disable();

        if(opiniones > 0){
            //Send file using GSM module
        }
        else{
            loops = 0;
        }
    }
    loops++;
}

Can anyone help me? Thanks

Which Arduino is it? Please post a Minimal, Complete, and Verifiable example. I don't see readOpinion declared anywhere.

It's an encouraged practice to answer your own question if you've solved your problem.

My aim was to attach multiple interrupts to my Arduino but my problem was that I didn´t know if when the board changed to sleep mode using LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF) then it could be awake using another interrupt instead of the timer.
The void loop() method must sleep the board every 8 seconds if no button is pressed. Aside there is a method that is called when a button is pressed, that´s because in the void setup () I´ve attached an interrupt using PCintPort::attachInterrupt(PIN_NUMBER, METHOD_TO_CALL,MODE);

OP (PinaGamer) posted this answer inside the question, hence the community wiki answer.

authors: Дмитрий Дымов


text:
What is the maximum current for each I/O pin?
Question
As far as I know each I/O pin has to keep around 20mA, what are the consequences of going higher or lower? But if I am using all I/O pins is there a maximum current value I should keep in mind? For example, the sum of all currents in all pins should not be greater than 100mA.

The 20 mA is a recommended MAXIMUM current per pin - you should always try to use less current.  There is no problem sinking or sourcing 5 mA, or even 1 mA per pin.

This comes up as first result when Googling your question:

And can be confirmed by page 313 and 314 of the datasheet:

To know where each pin is connected to (on the Arduino Uno) you can look the official (messy) schematic.
I provide an excerpt below that shows the Vin and 5V pins at the headers, and the power barrel connection.

If you want to control a 12V motor or a 12V LED strip or other DC loads you can use the following (which is also easy to find using Google):
*Note that your 12V Gnd and Arduino Gnd have to be connected.

simulate this circuit – Schematic created using CircuitLab

What means the "sink"? English not my first language so I not getting this. By the way is 150 mA total by each of that red square or both together?

"Sink" means that the Arduino is conducting current IN from the pin down to ground.  "Source" means that the Arduino is sending current OUT of the pin.  It is MUCH more common to use the chip to SINK current rather than SOURCE current.

Either way, you shouldn't be coming close to those values, as Richards answer says: if you need to drive significant current, you should use an external device.

@WesleyLee how do I safely get external power? For example I have here some batteries already in serie that gives me 7.2V and a 9V one. Can I just connect and Arduino regulate it for me?

What are you trying to drive? / What is your load?

There are MANY different Arduino models. We cannot answer questions about specific models without knowing what you are asking about.  WHICH MODEL of Arduino are you asking about?  WHAT are you trying to do with it?

It was a general purpose question. It is an Arduino Uno R3. If I for example need to turn on a 12V DC motor, putting it directly in Arduino pins would be stupid, right? This specific motor needs at least 9V.

You will almost certainly burn out your Arduino if you try to drive any motor with it. It is NOT made to do that!  You will destroy the Arduino.  The issue is not really how much voltage the motor takes, the Arduino can handle 9V. The issue is how much CURRENT the motor takes. If it is more than 20mA then do NOT connect it directly to an Arduino.  There are probably NO motors that need only 20mA.

@VitorCosta -- I added a schematic to control external loads. This is the last edit I do to my current answer. Next time I suggest you ask a clear question to begin with. Good luck.

Many questions do not work as "general purpose question". You are asking about details that are DIFFERENT depending on which model Arduino you are talking about.

The power limits per pin and per chip are listed for each model (based on the Atmel chip).  You can look up the Atmel chip number and see the power ratings.  For example, the chip may have a maximum of 40mA per pin, but a total of 200mA for everything on the chip. These numbers are just examples. The actual numbers depend on which Arduino and which chip you are talkng about.
Remember that microcontroller chips are NOT designed to SWITCH any significant amount of power. That is NOT the job of the microcontroller. Its job is to CONTROL external devices (transistors, thyristors,SSR, relays, etc.) which do the actual "heavy lifting" of switching larger amounts of power.
Your last question really does not make any sense. Can you clarify it?
VCC is the name of the main power bus and input to the microcontroller chip. It may or may not be 5V depending on which Arduino you are talking about. The older ones were 5V, but newer chips (including those used in Arduino) are tending more to 3.3V.

See edit. It is Arduino Uno. So when do I use vcc?

You use VCC whenever you want the Arduino to actually operate. VCC is the main power source to the Arduino. Your question seems very strange.

Omg sorry, did remove this strange question, I am truly sorry. I mean the Vin pin and the correct and safe way to use it!

The published specifications for Uno say that Vin can take 6~20V, but the recommended is 7~12V.  Please read the official details at: https://www.arduino.cc/en/Main/ArduinoBoardUno They will answer almost all of your questions

Sorry for one more noob question: if I supply 12V with Vin, will arduino regulate them for pins and they still at 5V?

Yes, if you put 12V into Vin, it will regulate on the Uno board down to 5V for VCC.  What does "regulate them for pins" mean?

source: Stack Exchange

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

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

sort: votes


text:
How to output a true analog voltage at output pin
Regarding my program, it is a program that does some calculations and then outputs a voltage based on the result using analogWrite function. However my problem is that I had done my programming based on a misconception that analogWrite function via PWM does output an analog voltage, where in fact it only "simulates" the analog voltage instead.
Here are the relevant parts of my code :
int pwmOutput = 11;
int pwm = 0;

void compareNewOldVoltageYes(void)
{
  if(pv_Vnew > pv_Vold && pwm != 255)
  {
    ++pwm;           //increasing value
  }
  else if(pwm != 0)
  {
    --pwm;           //decreasing
  }
}

void compareNewOldVoltageNo(void)
{
  if(pv_Vnew > pv_Vold && pwm != 0)
  {
    --pwm;
  }
  else if(pwm != 255)
  {
    ++pwm;
  }
}

void loop()
{
   reading();
   PowerCalculation();

   if(pv_NewP > pv_OldP)
   {
      compareNewOldVoltageYes();
   }
   else
   {
      compareNewOldVoltageNo();
   }

   analogWrite(pwmOutput, pwm);           //analogWrite

   float displayPWMvolt = pwm * 0.0196;

   Serial.print("Output Voltage: ");
   Serial.print(displayPWMvolt);
   Serial.println(" V");

   pv_OldP = pv_NewP;

   Serial.print("Previous Power: ");
   Serial.print(pv_OldP);
   Serial.println(" W");

}

As for the circuitry, output pin 11 is being connected to a 1 ohm resistor and then to GND. (Where I measured the voltage) I am using Arduino Uno board.
UPDATE:
As said in the comments by @DatHa, pwm does not output voltage. Is there a way to output voltage as said, without changing the board?

P.S. Analog write uses PWM and it DOES NOT produce an analog voltage.

@DatHa does that mean it cannot be done this way? Is there another function to output analog voltage?

See @Russell answer on http://arduino.stackexchange.com/questions/10041/can-i-connect-a-pwm-pin-on-one-arduino-to-an-analog-input-on-another

@dpw I don't think that works as my program has to connect to an electronic load via its external programming port and control it using 0-5V.

PWM outputs a specific voltage, or I'm a pirate in the year of our Lord 1734. You can't go above an 8-bit value, and there's always some inaccuracy in reading it.

You basically have three options:

Switch to an Arduino Due which has a built-in DAC which outputs a real voltage.
Add an external DAC chip (such as the MCP4821/2) to create the voltage for you
Use a low-pass filter (R-C network) on a PWM pin.

Of the three options I usually use an MCP4822 since it gives the best results and doesn't cost as much as using a Due.

Thank you. Option 2 sounds really good, but due to time constrains, I went ahead with Option 3 and got the results I wanted.

or use an R-2R ladder as a "poor man's DAC"

@AndreHolzner I count an R-2R ladder the same as a DAC chip but with too many wires to make it practical on your average Arduino.

@Majenko I just wanted to add that there exist "digital potentiometers" or "digipots" that are pretty much R-2R ladders inside a DIP-8 chip. They are cheaper then DACs. (For example X9C103)

@FilipFranik Except they're not R-2R ladders. They're just a chain of resistors with a FET connected to each connection between resistors. There is only R. Many Rs all the same. Yes, if you write it up with the two ends of the potentiometer to VCC and GND you get kind of a DAC, but it suffers the same kind of impedance problems a real potentiometer does. It provides a pair of resistances, whereas a DAC provides a voltage.

At 5V, a 1 ohm resistor will try to sink 1A and far exceed the 40mA specs.  Please use at least a 5/0.040=125 ohm resistor to protect your pin.  And if you put the a capacitor between your resistor and ground, the RC circuit of the capacitor will smooth out the PWM into an analog voltage.
Please try the suggested @russell answer with a 47K resistor and 1uF capacitor, you will get an analog voltage at the junction to use with your electronic load.

As far as I know Arduinos have ADC (Analog to Digital Converters) but do not have any DAC (Digital to Analog Converters). So you can not output a set voltage from any pins based on a digital value.

The ARM based Arduinos usually have at least one DAC channel.

There is no direct way.
In addition to @Majenko
Alternative way: you can use H bridge like L293d to provide continuous level. Many diy inverter circuits are useing this technique.
http://www.instructables.com/id/How-to-Make-an-Inverter-Using-ARDUINO/?ALLSTEPS

NO.. There is no way to get an analog voltage from the Arduino. The best that you can do is to use Arduino as a Buck Voltage converter in linear or boost mode using a voltage regulator, inductor and the mosfet transistor.  You will also might need to use a Mega or Dulorme which provide a PWM frequency other that the standard 50o Hz.
Best luck

I wondered if this would give a more stable output.

You need to add an R in parallel with C1 to discharge C1.

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

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


text:
Emulate non-standard keyboard from Arduino
I want to emulate keyboard presses in an old C64 microcomputer using an Arduino.
The keyboard connection is a non-standard 20-pin port (i.e. the Arduino keyboard libraries won't be useful) which, as I understand, works as a simple matrix of switches.
Since my Arduino Mega has more than 20 general purpose I/O ports, I understand I can approach the problem by simply mapping these 20 keyboard pins to individual "digital" Arduino ports, and then programming around it, right?
Or is this too naive and I'm missing something here?
I'm new to Arduino, so any comments highly appreciated. Thank you!

Please provide more information about the keyboard for the C64 computer. Is there a link perhaps?

Thanks sa_leinad. Here is one: http://www.waitingforfriday.com/images/b/be/C64-12.png

Emulating a keyboard matrix is actually harder than you would at first think. It's not just a case of setting certain combinations of pins as HIGH or LOW - you need to actively monitor one side of the matrix as it sweeps across each row and control the other side depending on the buttons that are pressed or not pressed on the current row. And all that has to be done fast enough that the C64 doesn't see buttons constantly bouncing up and down.
Further, you really need all your outputs to be open drain so as not to interfere with each other or the rest of the system (depending on just how the C64 system works), and Arduinos can't do open drain natively - instead you have to emulate it by switching between INPUT and OUTPUT + LOW which adds extra latency.
If you only want access to a few of the buttons a better arrangement would be to add a small N-channel (logic level) MOSFET or an NPN BJT between the two sides of the matrix for whichever button(s) you want to control (check the schematics for which pins and which way round to connect it). Activating the transistor would then be the same as pushing the button down. It can even be in parallel to the existing button so as to not break the keyboard.

Thank you Majenko! I'll reconsider the project given your valuable input -- not giving up yet, but more reading up to do... And I want to emulate the entire keyboard (including possible key combinations, e.g. Ctrl + something).

The main concern you have with emulating a matrix is "what is the time between a row being activated and the column being read?" - If there is a good sized delay between the two then you could be in luck and it will be easy. If it's almost instantaneous then you could well have problems. You have to make sure that all the outputs are set right before that read is done. You may end up having to do it with a different system, such as a CPLD, in order to get the speed you need.

I would go for two 4051 connected by common line and multiplexed lines to rows / cols (as Commodore keyboard is 8x8 matrix)

I know this is out there but how about using the Arduino to drive relays to re-enact the key being pressed. Just a crazy idea.

KIIV, as far as I understand 4051 demultiplexing, in this arrangement I would not be able to simulate key combinations. It seems 4051 enables you to select 1 output at a given time. So with two 4051s (one for row, one for column) I would be able to simulate 'F3' and 'Ctrl' at a time, but not 'Ctrl + F3' simultaneously.


text:
How to use while(1) loop in arduino?
I have been trying to exit from the while(1) loop by getting a value from the sensor and then run the code outside while(1).But the problem is that it does not exit. How may I fix this problem?
See Code Below.......
void setup() {
    pinMode(2,INPUT);
    Serial.begin(9600);
}

void loop() {
    int sensor;
    while(1)
    {
        sensor = digitalRead(2);
        if(sensor == 0)
        {
            Serial.println("inside while loop");
        }
        break;
    }
    Serial.println("Break......");
}

The while(1) loop executes once, every time loop() is called, printing or not, depending on the state of pin2. I would expect this code to print: either "inside while loop" (if pin 2 is false) or nothing, followed by "Break......"; over and over again. Is that what you're getting? Your question is incomplete. Please describe what you expected to see, and what you do see, on the terminal.

The loop function loops (is called repeatedly). Why do you put an indefinite loop inside a function that is called indefinitely?

In the Arduino paradigm, unlike ordinary C programming where there is only 1 entry point called "main()", there are 2 entry points called "setup()" and "loop()".  "setup()" is called only once after booting up.  But "loop()" is called over and over again right after "setup()" is called.  There is no need to create your own infinite loop (for example a "while(1)" statement) as in ordinary C programming.

Is there anyway to come out of while(1) loop inside void loop()

Sorry for the delay, holidays.  Yes, but most do not think this is good programming.  You can execute a 'break" inside the loop and exit the loop.   This Stackexchange question / answer goes into the details.

instead of while(1), one can use the variable name in while and change the value of the variable when you want to exit the loop. part of the code can be modified based on the following concept.
bool condition= true;
while(condition){
if (sensor==0)
condition=false;
This is my suggestion for the above problem.

Used like this
void setup() {
    pinMode(2,INPUT);
    Serial.begin(9600);
}

void loop() {
     bool cond = true;

int sensor;
while(cond)
{
    sensor = digitalRead(2);
    if(sensor == 0)
    {
        Serial.println("inside while loop");
    }
    cond = false;
}

  // like this you can used while inside the void loop()

}

Could you please add some explaination on how this solves the problem.


text:
Using 2D servo array in my class
I need to use a servo library in my class.
I read this question - Use object of other class within class and it works fine for my LCD application, but now I need to use a 2D servo array in my class. I made one approach, it worked, but I think it is bad programming approach, what is right way to solve my problem?

My main file
#include <SoftwareServo.h>
SoftwareServo servo[5][5];
Servolib Servoarray;

void setup(){
  blah blah blah

My cpp file
#include "Vending.h"
#include "Arduino.h"
#include <SoftwareServo.h>

Servolib::TurnSevo(){
  for(int row=0;row<5;row++){
    for(int collum=0;collum<5;collum++){
      servo[row][collum].attach(Object[row][collum]);
      servo[row][collum].write(0);
    }
  }
}

my .h file
#ifndef Vending_h
#define Vending_h
#include "Arduino.h"
#include <SoftwareServo.h>

class Servolib:SoftwareServo{
public:
  void TurnServo();

private:
  SoftwareServo servo[5][5];
  int Object[5][5]={
    {42,21,20,19,18},
    {37,41,36,38,35},
    {31,33,30,34,39},
    {67,28,66,29,65},
    {56,63,55,64,54}
  };
};
#endif

So this code worked, but please give me better solution.

What do you feel is wrong with that, please?  I could suggest you use a #define or a const int for your array dimensions, rather than having so-called "magic numbers" in the code, but apart from that it looks fine to me. (Also you spelled column wrong, but really this is nit-picking.)

I though i could pass servo object address and work with pointers, similar to this example -> http://arduino.stackexchange.com/questions/9296/use-object-of-other-class-within-class , but i don't know how to pass 2D array using pointers.

You can indeed use pointers, but passing multi-dimensional arrays is a bit of a pain in C(++).
There's a pretty good explanation here.

authors: ريناد الحربي


text:
arduino web client uploading data to mysql database
I have got this quick sketch that post data to mysql db using php add.php module.
#include <SFE_BMP180.h>
#include <SPI.h>
#include <Ethernet.h>
#include<dht.h>
dht DHT;

// You will need to create an SFE_BMP180 object, here called "pressure":
SFE_BMP180 bmp;

#define DHT11_PIN 2

double tempInC;
int humidity;

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);
char server[] = "192.168.1.3";

EthernetClient client;
byte php_server[] = {192 , 168 , 1 , 3};

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000; // READING INTERVAL

String data;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  if (bmp.begin()) {
    Serial.println("BMP init Success");
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");
  data = "";
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  char status;
  status = bmp.startTemperature();
  if (status != 0) {
    delay(status);
    status = bmp.getTemperature(tempInC);
  }
  else Serial.println("error retrieving temperature measurement\n");

  humidity = DHT.humidity;
  data = "?temp1=" + String(tempInC) + "&hum1=" + String(humidity);

  if (client.connect(server, 80)) {
    Serial.print("connected. My IP is ");
    Serial.println(Ethernet.localIP());
    client.println("POST /arduino/add.php HTTP/1.1");
    client.println("Host: 192.168.1.3");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
  }
  else {
    Serial.println("connection failed");
  }
  Serial.println(data);
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  if (client.connected()) {
    client.stop();  // DISCONNECT FROM THE SERVER
  }
  delay(300000); // WAIT FOR A WHILE BEFORE SENDING AGAIN
}

but its not updating the database, using the below add.php file from arduino web-client.ino
<?php
        include("connect.php");

        $link=Connection();

        $temp1=$_POST["temp1"];
        $hum1=$_POST["hum1"];

        $query = "INSERT INTO `tempLog` (`temperature`, `humidity`)
                VALUES ('".$temp1."','".$hum1."')";

        mysql_query($query,$link);
        mysql_close($link);

        header("Location: index.php");
?>

i checked in mysql prompt which is also the result displayed if I open the server url : 192.168.1.3/arduino/index.php
mysql> select * from tempLog;
+---------------------+-------------+----------+
| timeStamp           | temperature | humidity |
+---------------------+-------------+----------+
| 2016-11-28 11:50:37 |           0 |        0 |
| 2016-11-28 12:30:25 |           0 |        0 |
+---------------------+-------------+----------+
2 rows in set (0.00 sec)

I don't know how the first entry got created but second one I created by manually executing the url 192.168.1.3/arduino/add.php?temp1=26.64&hum1=18
the index page is showing he data from db as shown above in sql, that means connection is established and mysql and table is fetched from correct db. i.e. arduinoSensorData  in my case.
my serial monitor window got updated:
BMP init Success
connecting...
connected. My IP is 192.168.1.131
?temp1=26.64&hum1=18
connected. My IP is 192.168.1.131
?temp1=26.64&hum1=18
connected. My IP is 192.168.1.131
?temp1=26.57&hum1=18

which means arduino is not able to put data to db using add.php

When you manually executed the command it didn't write the temp&hum to the DB.  So you have a fundamental problem on the server side, before you even start involving an Arduino.  (Are you sure its not a firewall issue?)

I know on my router I have firewall turned off

I would suggest, that you give IP as another Parameter to the add.php and the insert-statement. With this you could test from where the call is made. If it is also 0. Then you got either a problem with the firewall as Matt stated, or it can be a probleml with the Variables of the add.php. (I don't know php so good)

POST data doesn't need a ?. Also you can't get GET parameters (from URL), from the $_POST variable.

yes, yesterday I realized and fixed it. thanks

I came to learn in my php code posted above, I am using $_POST variable when I should rather be using $_GET
In the PHP script, there are $_GET and $_POST variables that contain the data passed to the script, depending on the method used to to activate the script.
so using $temp1=$_GET["temp1"]; and $hum1=$_GET["hum1"]; fixes the problem.


text:
Running multiple motors simultaneously
I have this code for a DC motor (using this library)

#include <Arduino.h>
#include <Vnh2sp30.h>

//              ENA A   B   PWM   CS    inv
Vnh2sp30  mtrL( A0, 7,  8,  5,    A2,   0);

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

void loop() {
  if (Serial.available() > 0)   {
    String first  = Serial.readStringUntil(',');
    Serial.read();
    String second = Serial.readStringUntil(',');
    Serial.read();
    String third = Serial.readStringUntil(',');
    Serial.read();
    String echo = Serial.readString();
    Serial.println(echo);
       if(first == "start"){
                Serial.println("Starting DC motor");
                int duration = atoi(second.c_str());
                int power = atoi(third.c_str());
                int starttime = millis();
                int endtime = starttime;
                while ((endtime - starttime) <= duration) // mS
                {
                  endtime = millis();
                  mtrL.run(1023);
                }
                mtrL.stop();
                Serial.println("DONE");
       }
   }
}

Then I have this code to drive multiple stepper motors (using this library):
#include "BasicStepperDriver.h"

int incomingByte = 0;   // for incoming serial data
String readString = "";

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

void loop() {
    if (Serial.available() > 0) {
    String first  = Serial.readStringUntil(','); // start
    Serial.read();
    String second = Serial.readStringUntil(','); // motor number
    Serial.read();
    String third = Serial.readStringUntil(','); // motor steps
    Serial.read();
    String fourth = Serial.readStringUntil(','); // duration (millisec)
    Serial.read();
    String fifth = Serial.readStringUntil(','); // deg
                if(first == "start") {
                  if(second == "ALL") {
                    Serial.println("Starting stepper motor ALL");
                    int steps = atoi(third.c_str());
                    int duration = atoi(fourth.c_str());
                    int deg = atoi(fifth.c_str());

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

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

                    BasicStepperDriver stepper3(steps, DIR_3, STEP_3, ENBL_3);
                    stepper3.enable();
                    stepper3.setMicrostep(MICROSTEPS);
                    stepper3.setRPM(MAX_RPM);

                    BasicStepperDriver stepper4(steps, DIR_4, STEP_4, ENBL_4);
                    stepper4.enable();
                    stepper4.setMicrostep(MICROSTEPS);
                    stepper4.setRPM(MAX_RPM);

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

My goal is to merge this two codes together and still be able to run both the DC motor and one (or all) the stepper motors all together simultaneously. The first code is running on Arduino UNO and the other code runs on Arduino MEGA board and has been tested to work. The goal is to migrate the code from Arduino UNO to the MEGA board. Driving the motor for a specific time will block Arduino from executing the Stepper motors and vice versa with the DC motor. What can be done with these codes to make sure it can run the DC motor and Stepper motors at the same time?

The line while ((endtime - starttime) <= duration) // ms  is what you need to change because it keeps the loop from doing other actions while driving the motor, hence it is referred to as blocking.  The AccelStepper library mentioned by @Visual Micro uses a non-blocking approach but you need to change your approach.  Use some variable to detect the duration and let the code in loop() constantly check it each time though instead of using a while loop. That way each motor can get the attention it needs instead of taking turns.

Use the AccelStepper library along with the Adafruit MotorShield library
https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/install-software

I don't have a adafruit motor shield just the ones from China

The library is standard. You don't need the shield. Read the AccelStepper guide and it explains how to use motors and steppers at the same time.

Would it work for ST Vnh2sp30 driver hardware? I'm not sure if the pinouts match.

I managed to compile this for Stepper motor connections, problem is with the connection to the VNH2SP30 and if it would be non-blocking.

I think you van set the pins but the point of Accel is to do non-blocking.


text:
Arduino Due SAM3X ADC programmable input offset not working
In the datasheet of the SAM3X8E in Section 43.6.9 Page 1327 it clearly states that the SAM3X/A has a programmable offset for ADC input in Single-Ended mode and I believe that the Atmel ASF library also has a function dedicated to configuring analog offset for SAM's ADC (adc_enable_channel_input_offset). However the following lines of code did not work:
  adc_set_writeprotect(ADC,0);
  adc_enable_anch(ADC);
  adc_disable_channel_differential_input(ADC, ADC_CHANNEL_5);
  adc_set_channel_input_gain(ADC, ADC_CHANNEL_5, ADC_GAINVALUE_2);
  adc_enable_channel_input_offset(ADC, ADC_CHANNEL_5);
  adc_set_writeprotect(ADC,1);

Why??

I have very similar question http://arduino.stackexchange.com/questions/32062/arduino-due-adc-gain-adjustment-problem but no answer, unfortunately.


text:
Arduino Uno Digital to Analog Converter
I'm trying to read in an analog signal (a heartbeat) to pin A0 on the Arduino Uno and then convert it to digital. I'm hoping to use the digital signal to make an LED light up every time the voltage of the heartbeat signal goes over 1 volt. This is the code I have right now, but something is wrong because it isn't lighting up the LED.
unsigned int analog0;             // Raw data from A0 ranging from 0 to 1023
unsigned long data_range = 2000;  // Length of time to record data for
double volts;                     // The analog data from A0 converted to volts
int ledPin = 13;
unsigned long start_time;
unsigned long data_time;

void setup() {
  Serial.begin(9600);             // Initialize and set serial port baud rate
  pinMode(ledPin , OUTPUT);
}

void loop() {
  start_time = millis();
  while ((millis() - start_time) < data_range)
  {
    // Record current time of analog acquisition
    data_time = millis();

    // Record analog data on A0
    analog0 = analogRead(0);

    // Convert raw data into voltage
    volts = (analog0 / 1023.0) * 5;

    Serial.print(volts);
    Serial.println();

    // Slow the rate of data acquisition
    //delay(1);

    if (volts > 1.5){
      digitalWrite(ledPin, HIGH);
      //delay(50);
    }
    else{
      digitalWrite(ledPin, LOW);
    }
  }
}

Is it going over 1V?

Yes it is, the peak is around 1.2V on the oscilloscope.

I mean does the Arduino think it is going over 1V? And if the peak is 1.2V and you want to know if it is over 1V, why are you looking to see if it is over 1.5V?

We were just trying arbitrary values because nothing below that seemed to work, and whatever value we put there affects the voltage printed out to the serial monitor for some reason.

Try commenting out the serial in your sketch. In my experience serial communication takes time, and I assume you have a short window where the voltage peaks at more than a volt. Or initialize the serial with a stupidly high baud rate.
Edit: even better, you could try this for a faster response time:
void setup(){
  digitalWrite(13,0);
  pinMode(13, OUTPUT);
}

void loop(){
  if(analogRead(A0)>204){ //at ~1V the ADC will read between 204 and 205
    digitalWrite(13,1);
    delay(100);
    digitalWrite(13,0);
  }
}

I think your voltage formula is wrong. Try this:
float volts = analog0 * (5.0 / 1023.0);

This it the same formula, just written differently.

@emilyf dis you try printing the raw value of analog0 ? Also maybe try a different analog input in case of A0 being bad ?

We did try to print the raw value of analog0 and it was jumping from 0 to 5 within a second. We figured out how to make the LED light up using a comparator op amp configuration by comparing our heartbeat signal to a 0.8V signal, and when the heartbeat signal was above 0.8 our LED lights up. Unfortunately we couldn't do it with the Arduino, but any suggestions about how to fix the code are welcome!

@emilyf just tried your code on an Arduino UNO exactly as you have put it and it works as expected.
My theory is either a blown ADC pin on your Arduino board or a miswiring.


text:
Digispark / DigiKeyboard change keyboard layout
I'm trying to use the Digispark as a Rubber Ducky but the Digispark is only usable with the US laylout. German keyboard layout is QWERTZ. Some keys can be changed, like y and z, but if there are [ or ] this isn't possible. Trying to define a [-key in DigiKeyboard.h displays a ü.
Does someone know a solution?

You can edit the file scancode-ascii-table.h in your DigiKeyboard library.
It basically states which ASCII code corresponds to which keyboard scancode.
So if you try to print the ':' character but get a '>' instead, you know that in the above mentioned file at the ASCII position for ':' is the scancode for a '>'.
Using this, you can swap the scancodes around and basically create your own 'mapping'. For example, if you swap the values at ASCII 89, 90 and 121, 122 you for example solve the Y/Z switch.
However, I have not figured out how to correctly print a backslash. You might have to map that do a different ASCII character you don't need.
To add to this answer, there exists a workaround using mame82's duck2spark:
https://github.com/mame82/duck2spark

Solution is here:
Python script to convert RubberDucky payloads to DigiSpark sketch with respect to choosen keyboard layout:
duck2spark
Btw: The keys '<' '|' and '>' are on NON-US-KEY-100 on German keyboard layout. The key has value 0x64 for USB HID and the right modifiers have to be set (f.e. ALT_GR for '|' ). You could send them using
DigiKeyboard.sendKeyStroke(key,modifier);

For details see USB HID usage tables

here is a library version of Digistump with german keyboard support https://github.com/adnanonline/DigistumpArduinoDe
I adapted the keyboard library: digistump-avr/libraries/DigisparkKeyboard/DigiKeyboard.h to the german layout


text:
Serial 3 vs Software Serial
So I have a program that works great on the Mega, it uses serial 3 to read and streams out to the USB (I posted a previous question which someone answered)  I tried to use Serial (D0) to read and then write to serial, which did not work.  So now I am looking in to Software Serials
Is there a difference between a real serial and software serial as it does not seem to be working, It all runs a bit slower
#include <SoftwareSerial.h>

const int DesiredRPM=300;  // Setting Desired RPM Here.
const int MotorPWMPin=4;
int inByte = 0;         // incoming serial byte
unsigned char Data_status=0;
unsigned char Data_4deg_index=0;
unsigned char Data_loop_index=0;
unsigned char SpeedRPHhighbyte=0; //
unsigned char SpeedRPHLowbyte=0;

int SpeedRPH=0;
const unsigned char PWM4dutyMax=255;
const unsigned char PWM4dutyMin=100;
unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
    pinMode(MotorPWMPin, OUTPUT);
    Serial.begin(115200);  // USB serial
    Serial3.begin(115200);  // XV-11 LDS data

    // prints title with ending line break
    Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

    // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
    analogWrite(MotorPWMPin, PWM4duty );

    mySerial.begin(115200);
}

void loop() {
    // if we get a valid byte from LDS, read it and send it to USB-serial
  if (Serial3.available() > 0) {
    // get incoming byte:
    inByte = Serial3.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

  if (mySerial.available() > 0) {
    // get incoming byte:
    inByte = mySerial.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

}

void decodeData(unsigned char inByte){
  switch (Data_status){
  case 0: // no header
  if (inByte==0xFA)
  {
    Data_status=1;
    Data_loop_index=1;
  }
    break;
  case 1: // Find 2nd FA
    if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_status=2;
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      Data_loop_index++;
    }
    break;
  case 2: // Read data out

     if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      readData(inByte);
      Data_loop_index++;
    }
    break;
  }

}
void readData(unsigned char inByte){
  switch (Data_loop_index){
    case 1: // 4 degree index
    Data_4deg_index=inByte-0xA0;
//      Serial.print(Data_4deg_index, HEX);
//      Serial.print(": ");
    break;
    case 2: // Speed in RPH low byte
    SpeedRPHLowbyte=inByte;
    break;
    case 3: // Speed in RPH high byte
    SpeedRPHhighbyte=inByte;
    SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

    SpeedControl ( DesiredRPM ) ; //
//      Serial.print(SpeedRPHhighbyte, HEX);
//      Serial.println(SpeedRPHLowbyte, HEX);
    break;
    default: // others do checksum
        break;
  }
}

// Very simple speed control
void SpeedControl ( int RPMinput)
{
 if (Data_4deg_index%30==0) {  // I only do 3 updat I feel it is good enough for now
  if (SpeedRPH<RPMinput*60)
     if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
  if (SpeedRPH>RPMinput*60)
     if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
  }
  analogWrite(MotorPWMPin, PWM4duty ); // update value
}

There are huge differences. The most important ones are:

SoftwareSerial is half duplex (it can send or it can receive, it cannot do both at once)
SoftwareSerial is blocking - while it is sending or receiving nothing else can happen

SoftwareSerial is very much a poor-man's serial port. It should only really be used for very low volume data (things like NEMA messages once a second or so) and only if you have absolutely no choice (and, let's face it, you always have a choice).

Ok thank you, damn I need 2 serial ports then. I read on the serial and send on to USB.

That is often the case. That is why Atmel came up with the "upgrade" of the ATMega328PB which has a second UART. Another good choice is the ATMega32U4 (as used on the Leonardo) which separates the USB from the UART so you can use both separately.

Oh brilliant, I only need it for this project, so I should get a Leonardo,  hopefully it's smaller than the mega

It's the same footprint as the Uno.

Thanks you :) out of scope I know but any down point? Like not compatible with shield etc. Assuming the Leonardo uses serial1

If you want even smaller there is the Arduino Micro that has the same chip as the Leonardo.

The Leonardo has the real UART on pins 0/1 like the Uno. IIRC SPI and I2C may be in different places compared to the Uno.

I will go and read up, but I am assuming my code above won't need much work

Serial is the USB virtual UART, and Serial1 is the real UART (IIRC)


text:
Cannot move TM1637 from Uno to Pro Mini
I have a very simple setup which works fine with an Uno.

#include <SevenSegmentTM1637.h>
#include <SevenSegmentExtended.h>

const byte PIN_CLK = 2;
const byte PIN_DIO = 3;
SevenSegmentExtended display(PIN_CLK, PIN_DIO);

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

  display.begin();
  display.print(F("TEST"));
}

void loop() {}

When I use the very same setup with a Pro Mini (XCSOURCE ATMEGA 328P, 5V 16Mhz), the display doesn't light up. I get monitor outputs and can blink the onboard LED, but no reaction from the TM1637 display.
I get this output in the console:
�E%MA1e� 10001111
Acknowledged: 0
ADDR :  11000000
DATA0:  0
write byte: 84
ADDR :  11000000
DATA0:  1111000
write byte: 69
ADDR :  11000000
DATA0:  1111000
write byte: 83
ADDR :  11000000
DATA0:  1111000
write byte: 84
ADDR :  11000000
DATA0:  1111000

Does anyone have an idea how to debug or fix this?

Could you please post a schematic?

I just added it to my original question.

You haven't created the display object. Shouldn't you have a line somewhere that creates the object:
SevenSegmentTM1637    display(PIN_CLK, PIN_DIO);

Yes, sorry. I forgot to copy that in. I edited the question now.

What would be the output of the console on an UNO?

Include library link please

It doesn't appear that the code segment you posted corresponds to the actual code that creates the listed serial monitor output. Can you show the actual code?

Since you're using a Grove Display, I believe it will be using I2C.
For better debugging, try using the actual I2C pins on your Pro mini, which are A4 and A5.

I2C: A4 (SDA) and A5 (SCL). Support I2C (TWI) communication using the
  Wire library.
  https://www.arduino.cc/en/Main/ArduinoBoardProMini

I2C may need pull-up resistors on your data lines.
(https://en.wikipedia.org/wiki/I%C2%B2C)
It can also be nice to use "verified to be working" code, like example code from the manufacturer.
/*
 * TM1637.cpp
 * A library for the 4 digit display
 */
#include "TM1637.h"
#define CLK 39 //pins definitions for TM1637 and can be changed to other ports
#define DIO 38
TM1637 tm1637(CLK,DIO);
void setup()
{
    tm1637.init();
    tm1637.set(BRIGHT_TYPICAL);//BRIGHT_TYPICAL = 2,BRIGHT_DARKEST = 0,BRIGHTEST = 7;
}
void loop()
{
    int8_t NumTab[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};//0~9,A,b,C,d,E,F
    int8_t ListDisp[4];
    unsigned char i = 0;
    unsigned char count = 0;
    delay(150);
    while(1)
    {
        i = count;
        count ++;
        if(count == sizeof(NumTab)) count = 0;
        for(unsigned char BitSelect = 0;BitSelect < 4;BitSelect ++)
        {
            ListDisp[BitSelect] = NumTab[i];
            i ++;
            if(i == sizeof(NumTab)) i = 0;
        }
        tm1637.display(0,ListDisp[0]);
        tm1637.display(1,ListDisp[1]);
        tm1637.display(2,ListDisp[2]);
        tm1637.display(3,ListDisp[3]);
        delay(300);
    }
}

You will need to adapt the pin numbers.
But after these steps it should work just fine.
Source: http://wiki.seeed.cc/Grove-4-Digit_Display/

You will need pullups resistors 4.7K are normally a good value.

Your answer is false, the TM1637 uses CLK and DIO not I2C. http://playground.arduino.cc/Main/TM1637

http://olimex.cl/website_MCI/static/documents/Datasheet_TM1637.pdf
The wiring does show the pull-ups. And a note on the datasheet includes: "Microprocessor data realize the communication with TM1637 by means of two–wire bus interface (Note: The
communication method is not equal to 12C bus protocol totally because there is no slave address)". So I believe that, in hardware it's I2C but not completely in software. But it indeed appears that you can put it on any of the pins.

I'm actually unsure if the pull-ups are on the board already. And it seems to work with regular pins aswel, but then again, there also is a software I2C library. But if it doesn't work, I would use the hardware-wise method.

Holy s***. The pins A4 and A5 really are the solution.

@Railsana, so it works by only changing the pins? (With the same code as you used previously, and without the pull-up resistors?) Can you verify that pin 2 and 3 work with normal execution (checking the status of a button and/or controlling an LED), it may be worthwhile to check that out :)

How does it work on the UNO then???

Maybe s/he used A4 and A5 on the Uno. ;)

Well, pins 2&3 and VERY far from A4&A5 or even SDA&SDL. Very weird...

I believe it will be using I2C. spi can use just two wires. the datasheet is clearly written for spi.

4.7k resistors on 2 and 3 pins does not help.
Works great if the tm1637 directly connected to 12 and 13 pins.


text:
How do I change PGA gain in this Arduino program?
Below is the link to three files I am using with a 32 bit ADC from TI, ADS1262, plus a link to it's datasheet. It works fine but I'm not getting any better voltage resolution than with a 16 bit ADC. I am using it for small voltage, from 0 to 0.070 volts. For example, for a known stable voltage of 0.01000 volts from a Fluke thermocouple calibrator I get 0.010000 to 0.010006. I get this same 0.000006 volt jitter if I short the ADS1262 input pins together. I suspect it may be a programmable gain amplifier issue. I can put 2.5 volts into it and not damage it. There is a line in the .ino file, #define PGA 1. On a guess, I changed this to #define PGA 32 but it had no effect on the results, it's like my attempted program change didn't take. I read in the ads1262 datasheet that the PGA Gain is in the MODE2 Register, address 05h. A gain of one is set with 000 and a gain of 32 is set with 101. But I do not know how to proceed. Perhaps somebody can help me out.
https://github.com/Protocentral/ProtoCentral_ads1262/tree/master/Libraries
http://www.ti.com/lit/ds/symlink/ads1262.pdf

The symbol PGA appears in exapmle.ino (sic) twice, once each in lines 28 and 30:
 #define PGA 1                     // Programmable Gain = 1
 ...
 #define VFSR VREF/PGA

It is not used elsewhere in the example or the library code.  The only effect of changing its value from 1 to 32 is to change the value of VFSR, and asVFSR appears only in line 30, that effect is nil.
Looking at the ads1262.cpp file from github, it appears that ads1262::ads1262_Init() initializes register MODE2 to 0x6, via:
ads1262_Reg_Write(MODE2, 0x06);

which per the ADS1262 spec sheet, page 93, table 44, enables the PGA and sets its gain to 1 and sets the sample rate to 60 SPS.
Apparently, if you wish to use some other gain setting, you should define PGA appropriately and put a corresponding setting into MODE2.  For example, if you want to set up a gain of 16 and sample rate of 400 SPS, in setup() you could say
PC_ADS1262.ads1262_Reg_Write(MODE2, 4<<4 | 8); // 4=gain 16, 8=400 SPS

More generally, you could set up some constants for gain codes and SPS rates, and reference those constants when writing to MODE2.  For example, after
enum { GainCode1, GainCode2, GainCode4, GainCode8, GainCode16, GainCode32 };
enum { SPSCode2p5, SPSCode5, SPSCode10, SPSCode16p6, SPSCode20, SPSCode50,
       SPSCode60, SPSCode100, SPSCode400, SPSCode1200, SPSCode2400,
       SPSCode4800, SPSCode7200, SPSCode14400, SPSCode19200, SPSCode38400};

you would say
PC_ADS1262.ads1262_Reg_Write(MODE2, GainCode32<<4 | SPSCode2400);

to set the gain at 32 and the sample rate at 2400 SPS.
(Note, enum is a C language element used to define integer constants.  In an enum, each symbol mentioned without an explicit value has a value one more than the previous symbol, or zero if there's no preceding symbol.  So GainCode1 is 0, GainCode2 is 1, GainCode4 is 2, etc.)
Note, to get better ultimate resolution, you may need to combine multiple readings, or may need to set the ADS1262's filtering parameters.

Yes! Adding   PC_ADS1262.ads1262_Reg_Write(MODE2, 4<<4 | 8);   did improve the voltage resolution. Thank you for taking the time to look at the linked material. Can you tell me how to set the gain to 32 instead of 16?

@Rico, see edit

I wish I could up vote this wonderful answer! Big help.


text:
Arduino based Fan controller for PC
My fellow programmers,
I'm planning on creating a fan controller for my PC using an Arduino Duemilanove and a generic motor sheild. (Fan controllers are not exactly cheap here and i'd rather spend my money on an SSD than on a fan controller =)
On a normal scenario, I want my fans to spin slowly, just to keep some air flowing but not enough to make too much noise. Obviously, they should turn on at full speed (or so) during a demanding scenario, like playing a game.
My idea is to use a usb port to communicate with Windows, so that my arduino knows when a demanding application was started. Is there an easy way to do this or should I buy myself some cheap temperature sensors, place them on the more important parts and control my fans with these temperature readings?
I'd also like to have an option to turn of the communication between the arduino and whatever informs it about the computer usage, so that I can program it in order to test a different algorithm.
Thanks for any help!

Yes you can. One of the options is using Visual Studio if you are Windows user (using built in library is enough to meet your 'option to turn off' needs). There so many examples of serial communication using either C# or C++ with Arduino, so you can do communication between Laptop - Arduino via serial cable or even built in bluetooth in laptop (with extra bluetooth module for Arduino).
The most simple setup is your laptop act as master and arduino as slave. Arduino does not need any information about what program is running, instead just waiting command from Laptop wether to turn off or turn down the fan
You can read  information from your PC (for Windows), such as temperature or battery level

Any Arduino with a USB interface can communicate with a PC via pseudo-serial ports (that is, serial-over-USB links).  If you have a PC program that somehow monitors what processes are running, your plan of telling the Arduino to speed up the fan when certain programs are running is practical to do.
On Linux systems, fan speed can be controlled by user programs like fancontrol-gui and tpfanco.  Probably similar programs are available on Windows and Mac systems.  Your Arduino could measure temperatures and send them to the host OS for fan speed control.  Or vice versa, your PC could use DBus or ACPI calls to measure its chip temperature and send it to the Arduino to control a fan.
Note, there's a thermometer built in to several ATmega devices.  Its resolution isn't great and due to chip thermal mass it might not respond quickly, but you might find it worthwhile to experiment with.  For example, see §24.8, Temperature Measurement, on page 247 of the document Atmel-8271J-AVR-ATmega-Datasheet_11/2015, which says to select the internal 1.1 V ADC voltage reference, read ADC channel 8, and scale the result per Table 24-2 to get °C.

authors: Анатолий Соколов


text:
Servo Driven Through Custom Library Not working Properly
I'm a little new to Arduino, but not to programming or electronics in general.  I'm working on a library that will be more fleshed out later, but I'm having issues getting the basics working properly.
The following code produces the desired behavior if a servo is attached to pin 3:
#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(3);
}

void loop() {
  myServo.write(1);
  delay(1000);
  myServo.write(45);
  delay(1000);
  myServo.write(90);
  delay(1000);
  myServo.write(135);
  delay(1000);
  myServo.write(180);
  delay(1000);
}

However, when I try to implement similar functionality in my own library the servo locks and just sort of grinds.  Here's the header file:
#ifndef MotorControl_h
#define MotorControl_h

#include "Arduino.h"
#include "Servo.h"

class MotorControl
{
  public:
    MotorControl(int north, int south, int west, int east);
    void setNorth(int value);
    void setSouth(int value);
    void setWest(int value);
    void setEast(int value);
    int getNorth();
    int getSouth();
    int getWest();
    int getEast();
  private:
    Servo _north;
    Servo _south;
    Servo _west;
    Servo _east;
    int _northVal;
    int _southVal;
    int _westVal;
    int _eastVal;
};

#endif

And here's the .cpp file:
#include "Arduino.h"
#include "MotorControl.h"
#include "Servo.h"

MotorControl::MotorControl(int north, int south, int west, int east)
{
  _north.attach(north);
  _south.attach(south);
  _west.attach(west);
  _east.attach(east);
  _northVal = 0;
  _southVal = 0;
  _westVal = 0;
  _eastVal = 0;
}

void MotorControl::setNorth(int value)
{
  _north.write(value);
  _northVal = value;
}

void MotorControl::setSouth(int value)
{
  _south.write(value);
  _southVal = value;
}

void MotorControl::setWest(int value)
{
  _west.write(value);
  _westVal = value;
}

void MotorControl::setEast(int value)
{
  _east.write(value);
  _eastVal = value;
}

int MotorControl::getNorth()
{
   return _northVal;
}

int MotorControl::getSouth()
{
  return _southVal;
}

int MotorControl::getWest()
{
  return _westVal;
}

int MotorControl::getEast()
{
  return _eastVal;
}

And finally, the code using the above library which should produce the same behavior as the code up top, but does not:
#include <MotorControl.h>

MotorControl mc(3, 5, 6, 9);

void setup() {}

void loop() {
  mc.setNorth(1);
  delay(1000);
  mc.setNorth(45);
  delay(1000);
  mc.setNorth(90);
  delay(1000);
  mc.setNorth(135);
  delay(1000);
  mc.setNorth(180);
  delay(1000);
}

I'm not sure what else to add ... this is running on an Uno R3.
Edit:  This is interesting.  I've tried the code from this example:
How do I initialize a servo object in my own library?
which works out just fine.  I'm still not sure that I see what I'm doing incorrectly here.  I see the differences between my code and the example, but not how they are causing problems.
If it's worth mentioning, I've also stored my library in the libraries folder.  Just throwing out any random detail I can think of.

Hi @MattB, what is your question?

Try expanding you example to have 4 servos and see if that works.  I guess it won't because the Servo library uses timers and the different servos might interfere with each other.  Its just my guess, and I hope I'm wrong.

In you code you could set all the servos to 3, so that its only driving one servo.  The opposite of the above.

Interesting idea @Matt ... I will give that a shot.

@sa_leinad The library I've created is not driving the servo properly.  The servo responds, but does not move to the appropriate positions.

@Matt I just gave it a shot.  No change.  Very confusing...

In C++, when an object is declared as a member of another object, the constructor method of the inner object must be called explicity (see constructors and member initializer lists).
In your code, properties of Servo type can be constructed within the header of the MotorControl constructor:
MotorControl::MotorControl(int north, int south, int west, int east)
    : _north(), _south(), _west(), _east()
{
  _north.attach(north);
  _south.attach(south);
  _west.attach(west);
  _east.attach(east);
  _northVal = 0;
  _southVal = 0;
  _westVal = 0;
  _eastVal = 0;
}

When you create your instance at global scope then you have no control over when exactly the constructor gets called.  If it gets called before init() runs then your attach lines won't work out.  You should have a begin method in your class that handles attaching the servos and call that method from setup.


text:
Can you tell me if this circuit will work?

Here's an image of my circuit diagram. There are 8 9g servos connected to the arduino gpio pins. The servos have an external power supply of 3 volts (may vary depending on the voltage requirement of the 9g) and the arduino is powered through an adaptor. Is this a convenient way of doing it? Have I gone wrong somewhere? I am new to circuit designing so I am confused.
Thank you! :)

That diagram is impossible to read. Redraw it so that wires dink mask other wires. Keep wires to horizontal or vertical with 90 degree bends only.

@Majenko       Apologies. I've edited the post with a breadboard design. I'll re-draw the whole thing in case even this one is difficult. :)

These servo are driven off of a PWM signal. This means that you need to connect the control line to a pin that is capable of PWM.
For the Uno it is D3, D5, D6, D9, D10 & D11.
Unfortunately there are only 6 PWM capable pins and you need 8.
You could consider bit banging the PWM for the 7th & 8th motor.
Alternatively, if two of the motors are to be driven exactly the same, they could share the PWM control line between them.
If you need to control each motor separately (without bit banging) you may have to upgrade to a Arduino Mega 2560. The Mega has 15 PWM channels.
An Arduino example of controlling the servo motor can be found in the Libraries section of the Arduino website.
https://www.arduino.cc/en/Tutorial/Knob

Thanks a lot for your insight! :) I want all the motors to work independently therefore I will need another pwm connection. But once I connect all the control lines to the pwm, would this circuit diagram work?

Providing you do it right, yes.

Edited my answer to suggest using an Arduino Mega 2560, which has 15 PWM channels. Or you could even use 2 Arduino Unos.

Yeah, I'll consider using a 2560. I could always do with more channels. haha. Thanks again! :)

Was the answer helpful? If so, please accept it by clicking on the "tick" icon next to the answer, and also possibly upvote it. This indicates to other users that you found the answer useful, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer. Thanks for your understanding and cooperation!


text:
How to break out of a loop if it is contained in a function
I am trying to figure out how to break out of a loop if it is being called from a function.  I have a similar post, here, that I've decided to do something with the Arduino onboard LED, to isolate it from the NeoPixels Library and it is giving me the same issue.  The answers I have received there have been helpful but something is still puzzling me.
Using serial from the Arduino to my PC, the below "Example 1" code, can break out of a local loop successfully (and immediately) when the Arduino received keyboard input with key "2".
//Example 1
int ledPIN = 13; // sets up onboard LED on Arduino located near PIN13
char rx_byte = 0; // variable to hold serial input from console;
int count = 0; // placeholder for incrementing during debugging of loops

void setup() {

  Serial.begin(115200);

  pinMode (ledPIN, OUTPUT);

}

void loop() {

  if (Serial.available() > 0) {    // is a character available?
    rx_byte = Serial.read();       // get the character

    // check if a number was received
    if ((rx_byte >= '0') && (rx_byte <= '9')) {
      switch(rx_byte) {
        case '1':
          Serial.println("You've entered: 1");
          for (int i; i <=5000; i++) {
            rx_byte = Serial.read(); // must read character again
            if (rx_byte == '2') {
              Serial.println("Quitting...");
              digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
              break;
            }
            else {
              Serial.println(i);
              digitalWrite(ledPIN, HIGH); // turn LED pin 13 on
            }
          }
          digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
          break;

      }
    } // end: if (Serial.available() > 0)
  }
}

From what I've been told, you shouldn't necessarily perform a "serial.read()" inside of a loop.  However, if I do not include that in the for loop, it does not allow for any further input.
Since "Example 1" works, I am now trying to accomplish the same principle, but, this time, when calling a function which contains its own independent loop of course.  I've spent countless hours trying to resolve this.
I was under the impression that I could use a while loop within "void loop()" and call in a function which also contains a loop, then be able to break it from the while loop.  When attempting this various ways, the for loop within the function seems to blink the LED 10+ times and totally ignores my keystroke "2" to break the loop and is now infinite.  I know I could just put the for loop up in "void loop()" and it would work to break out similar to Example 1, but I'm sure it can be broken from a function as well.  I will eventually have similar functions that will contain parameters.
How would I go about doing this the correct way?
Below is "Example 2" that I am trying to break from the function.  I'm assuming it's an issue with doing it from the while loop?
Again, any assistance is greatly appreciated.
//Example 2
int ledPIN = 13; // sets up onboard LED on Arduino located near PIN13
char rx_byte = 0; // variable to hold serial input from console;
int count = 0; // placeholder for incrementing during debugging of loops

void setup() {

  Serial.begin(115200);

  pinMode (ledPIN, OUTPUT);

}

void loop() {

  if (Serial.available() > 0) {    // is a character available?

    rx_byte = Serial.read();       // get the character
    boolean forceTerminate = false;

    // check if a number was received
    if ((rx_byte >= '0') && (rx_byte <= '9')) {

      switch(rx_byte) {
        case '1':
          Serial.println("You've entered: 1");
          while(forceTerminate == false) {
            rx_byte = Serial.read(); // must read character again
            if (rx_byte == '2') {
              Serial.println("Quitting...");
              digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
              forceTerminate = true;
              break;
            }
            else {
              //count = count+1;
              //Serial.println(count);
              blinkPIN13(); // FUNCTION: blinkPIN13
            }
          }
          digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
          break;

      } // end: switch(rx_byte)

    }

  } // end: if (Serial.available() > 0)

}

/************************************************************************************
 * FUNCTION for blinking LED located on PIN 13 to the state of ON(1)/OFF(0)
 ************************************************************************************/
void blinkPIN13() {

  for (int i; i <=10; i++) {
    digitalWrite(ledPIN, HIGH);
    delay(1000);
    digitalWrite(ledPIN,LOW);
    delay(1000);
  }

}

To tell a function-caller what to do when the function exits, have the function return a status value.  You can do this at multiple levels.  For example:
byte doOtherStuff(int howLong) {
  digitalWrite(ledPIN, HIGH);
  delay(howLong);
  if (doneDoing()) return false;
  digitalWrite(ledPIN,LOW);
  delay(howLong);
  return !doneDoing();
}

void loop() {
  while(doMore) {
    doStuff();
    for (byte i=0; i<9 && doMore; ++i) {
      doMore = doOtherStuff(1234);
    }
    if (doMore) {
      doMoreOtherStuffInWhile();
    }
  }
}


text:
It seems like the math of arduino is off
[SOLVED] By changing the offset for the incoming data into int16_t type there won't be any rounding errors and the values I'm getting are all back to zero in the sensor its base position
This is my first project where I use Arduino.
Until today everything went good with the Arduino Pro Mini (3.3v).
But as of today I got a bit of a weird problem.
I am using a MPU gy-521 (doesn't really matter) and I'm working on calculating the actual movement.
The problem which occured is that I'm using a deadzone to negate the smallest numbers (I know, this isn't the right way to use data). The way I negate the numbers is with the following code
// Check deadzone values
  if (ax+axo < adz && ax+axo > -adz) ax = -axo;
  if (ay+ayo < adz && ay+ayo > -adz) ay = -ayo;
  if (az+azo < adz && az+azo > -adz) az = -azo;

  if (gx+gxo < gdz && gx+gxo > -gdz) gx = -gxo;
  if (gy+gyo < gdz && gy+gyo > -gdz) gy = -gyo;
  if (gz+gzo < gdz && gz+gzo > -gdz) gz = -gzo;

ax is accelerometer data over the x-axis, axo is the offset, adz is the accelerometer deadzone.
gx is gyroscope data over the x-axis, gxo is the offset, gdz is the gyroscope deadzone.
All of the other letters are the same, for different axis.
After getting the values within the offset basically set to 0 with the offset I'm doing the following.
// Calculate acceleration
  axa = (ax+axo) / aFactor * g;
  aya = (ay+ayo) / aFactor * g;
  aza = (az+azo) / aFactor * g;

  gxa = (gx+gxo) / gFactor;
  gya = (gy+gyo) / gFactor;
  gza = (gz+gzo) / gFactor;

The a- and gFactor are mentioned in the datasheet, but these values should all be 0 if the value of axis plus the offset is within the deadzone.
The problem is that I'm not just getting 0.00 values.
I'm also getting -0.00 and 0.01.
0.00    0.00    -0.00   0.00    0.01    0.01

Could someone enlighten me about what's wrong in my situation or if this is just a Arduino issue.
[EDIT]
The data originally from the sensor is from type int16_t (ax, ay, az, gx, gy, gz) and the other variables are doubles.
The values which are off are always the same ones: Accelerometer Z, Gyroscope Y and Z.

Are all your variables declared as float ('axa, axo, aFactor, g, ...`) ?

The variables are all declared as double except for the ax, ay, az values which are int16_t by default

What are changes between "Until today everything went" and "today I got a bit of a weird problem" (source code, sensors, wiring, other) ?

Change axo etc... to also be int16_t rather than floats. That way when you set ax = -axo; and then do (ax+axo) there is no risk of rounding errors converting from double to int and back, you should always get exactly 0.

If axo is not an integer, then the statement ax = -axo; will perform rounding, and the expression ax+axo will be non-zero.

Iirc before today I was just getting zero's which was fine for me. Since then I removed the wiring and place them back (same setup) mostly the same code, atleast it shouldnt have changed the output.
When I change all of my variables into into16_t I just get zero's as output, no decimals. Since I'm working with dt precision I can't have this.
I fixed it by just setting the axo variable to int16_t, Thanks guys!

If your program is basically working but gives you rounding errors, it can be that you are facing some problems related to conversion from floating-point to binary or reverse. It is a very common problem in computer science. For example, the decimal number 0.1 has no exact binary  representation, it is infinite. For more information, you can read these pages:
http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/
https://www3.ntu.edu.sg/home/ehchua/programming/java/datarepresentation.html
In order to solve your problem, you can try to apply appropriate rounding to your results and if possible avoid mixing different data types and use double only if absolutely needed (which I guess is the case in your application).


text:
Data acquisition/logging question
I want to use an Arduino Uno for a data-acquisition purpose.
Normally adhoc data acquisition boards can record each sample at a desired sampling rate. So that I can plot all the samples recorded. I want to do the same sort if thing with Arduino.
I want to record 30 minutes of analog voltage input at 4kHz sampling rate and record all the samples taken to a PC.
And at the end I want to be able to plot the data with all samples not the averages ect.
Is there an easy workaround for this?

Depending on your data format that could be up to 28MB of data. No way an Arduino alone can deal with that without somewhere to off-load the storage to, such as maybe an SD card (that is if the Arduino can store data on SD that fast). 4kHz is a reasonable sampling speed for the Arduino, though you can't really use analogRead() for that. Instead you want to investigate free-running and/or timer based sampling.

Here is a program I wrote that follows an approach somewhat similar to
Michael Stachowsky's answer:

The ADC is configured with the prescaler set to 128 (just like the
Arduino core does), which gives a 104 µs conversion time,
significantly shorter than the 250 µs sampling period you want.
The first conversion takes longer, and it is discarded.
It is also configured an auto-trigger mode, and the timer 1 overflow
flag is selected as its trigger source.
The timer 1 is configured to loop every 500 × 8 = 4000 CPU cycles
(clocked at F_CPU / 8, with TOP = 499), which
provides the required 250 µs sampling period. It is set in a PWM
mode even though the PWM outputs are not used, simply because in this
mode the overflow flag is set every time the timer loops.
An interrupt is triggered every time an ADC conversion is complete.
The interrupt service routine clears the timer overflow flag (this is
required because the ADC is triggered by the rising edges of this
flag), saves the result in a global variable and sets a global flag.
The main loop waits for that flag and sends the data through the
serial port, in binary, LSB first:

the sample number modulo 64 (6 bits)
the sample value (10 bits).

The serial port runs at 115.2 kb/s, it can then transmit the two bytes
of data in about 174 µs, which is less than the sampling period.
The sample numbers, and a 16-byte preamble can be used as a sanity
check by the receiving end.

#include <avr/interrupt.h>

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

    // Transmit preamble.
    for (int i = 0; i < 16; i++)
        Serial.write(0xff);

    // Start the ADC.
    ADMUX  = _BV(REFS0)   // reference = Vcc
           | 0;           // input = ADC0
    ADCSRA = _BV(ADEN)    // enable the ADC
           | _BV(ADSC)    // start first conversion
           | _BV(ADPS0)   // prescaler = 128,
           | _BV(ADPS1)   // ditto
           | _BV(ADPS2);  // ditto

    // Wait for the first conversion to complete.
    loop_until_bit_is_set(ADCSRA, ADIF);

    // Wait for the preamble to be fully transmitted.
    Serial.flush();

    // Stop timer 1.
    TCCR1A = 0;
    TCCR1B = 0;

    // Configure the ADC in auto-trigger mode.
    ADCSRA |= _BV(ADATE)   // enable auto-trigger
            | _BV(ADIF)    // clear interrupt flag
            | _BV(ADIE);   // enable interrupt
    ADCSRB  = _BV(ADTS1)   // trigger source = timer 1 overflow
            | _BV(ADTS2);  // ditto

    // Configure Timer 1.
    ICR1   = 500 - 1;     // period = 500 * 8 CPU cycles
    TCCR1A = _BV(WGM11);  // mode 14: fast PWM,
    TCCR1B = _BV(WGM12)   // ... TOP = ICR1,
           | _BV(WGM13)   // ... overflow flag set on TOP
           | _BV(CS11);   // clock at F_CPU / 8
}

volatile uint16_t reading = 0xffff;
volatile bool reading_available;

ISR(ADC_vect)
{
    TIFR1 |= _BV(TOV1);    // clear timer overflow flag
    uint16_t x = reading;  // work on a copy of the reading
    x &= ~0x03ff;          // remove previous ADC value
    x |= ADC;              // add current ADC value
    x += 0x0400;           // increment sample number
    reading = x;
    reading_available = true;
}

void loop()
{
    // Wait for a reading to be available.
    while (!reading_available) ;

    // Grab a copy.
    uint16_t x = reading;
    reading_available = false;

    // Transmit, LSB first.
    Serial.write(x >> 0);  // low byte
    Serial.write(x >> 8);  // high byte
}

How you deal with the data on the receiving end (save to file, skip
preamble, check sample number consistency, extract sample values, plot
them...) is up to you. You can use whatever language and tools you want.
It is not an Arduino-related question.
Addendum: More about the binary format used.
There is a preamble consisting of 16 0xff bytes. This can be useful
because it is not uncommon to get in one file a mix of data from two
different runs of the program. The buffering of the serial port on the
PC can lead to this happening. If you do not want that preamble, remove
the two lines right after the “Transmit preamble.” comment.
Then there is a continuous stream of 16-bit unsigned integers
(uint16_t), transmitted LSB first (i.e. little endian). The byte order
can be changed by swapping the two Serial.write() by the end of the
program.
Each of these integers contains an ADC reading in the lower 10 bits and
a sample number in the upper 6 bits. The sample number can be extracted
by right-shifting (x >> 10 in C) and could be used as a sanity check
(the number should increment by 1, modulo 64, from one sample to the
next). The ADC reading can be extracted by masking out the sample number
(x & 0x03ff).
If you do not want the sample numbers, you can simplify the ISR to:
ISR(ADC_vect)
{
    TIFR1 |= _BV(TOV1);    // clear timer overflow flag
    reading = ADC;         // read the ADC result
    reading_available = true;
}

and remove the (now useless) initialization of the reading variable.

Thanks I uploaded the code. In Arduino IDE's serial monitor I'm see weird characters not ones and zeros or numbers. How can I convert the upcoming data to numbers? And which analog input is this code sampling?

@user16307: It's sampling analog input 0. You can sample another input by replacing the 0 in the line | 0;  // input = ADC0. You see weird characters because it's binary data, not text. If you want text, you will have to convert it. How you do the conversion is up to you, and it's not an Arduino question.

Thanks a lot. But I would be glad at least of you tell me which binary format is this code sending data? If I save the data and when I convert the binary to text I need to know the format saved. Is it uint16? Im not so familiar with. MATLAB has functions to read such binary. I mean is this data uint16 little endian?

@user16307: Yes, it's uint16 little endian. I amended the answer to make the format more explicit, and to provide instructions on how you can change it.

Im still trying to extract the time and voltage readings from your code. Is 8 bit part is time in seconds and the other 8 bit part is voltage reading? Why dont you use Serial.print instead of Serial.write?

@user16307: No, it's 6 bits: sample number and 10 bits: voltage reading. Serial.print() would format the result in ASCII, which would be easier to deal with on the receiving end, but it takes more bytes to send. At 4 K samples/second, there is no time to send ASCII-formatted readings through Serial. Binary is your only option.

Amazing explanation. Thanks. So what I need to do is to divide the 16 bit to two parts 6 bit and 10 bit in C# part. I still couldn't manage it. Maybe I should only use the voltage readings. In that case I will update the ISR(ADC_vect) as you mentioned in addendum. In that case the line Serial.write(x >> 0);  // low byte will send the voltage readings right?

I think I was wrong.   Both Serial.write(x >> 0);  // low byte
Serial.write(x >> 8);  // high byte should be used to transmit 10 bit data. Now I only receive voltage data by setting ISR(ADC_vect) to ur suggestion. I use Realterm terminal program and get values of tens of thousands as voltage readings as uint16. Shouldnt the uint16(eventhough it can up to around 65000) format output max 255 since max ADC is 10 bit? Did you try this code before? Please test your code with Realterm if u have time. I dont understand why Im having that big numbers.

oh sorry my mistake again the baud rates were not matching before. now it works 5V corresponds 1024. is that ICR1   = 500 - 1;  line setting sampling  rate? is it possible to sample 1Hz modifying this code? thanks anyway..

@user16307: In order to get a 1 Hz sampling, you have to set the prescaler to 256 (replace CS11 by CS12 in the code), and set ICR1 = 62500 - 1.

This question is actually two or three different questions.
To the first: is it possible to record 30 minutes of data with an arduino uno at 4KHz: no.  Assuming even that you are only taking 1 byte of data at a time, the uno only has 2K of RAM, so you'd be out of RAM in under a second.
To the second: can you instead send this data to a PC at the desired rate: possibly, depending on how much data you are taking.  If it's just a single analog channel, then you can most likely do it.  Anything more and I doubt it.  The problem is that you'll simulutaneously have to read the analog at the correct time AND send the data to the PC, presumably over the serial.  As long as you use Serial.write, NOT Serial.print, then your UART should be more than fast enough at high baud rates to handle a single channel with minimal overhead.  However, that would mean that you have to reconstruct the data on the PC, but that's the third question, to which I shall turn shortly.
If you need absolute real-time operation, then you need to use timer interrupts, which are not native to the Arduino libraries, if I recall correctly.  However, a quick google for "Arduino timer interrupt" leads me here: http://playground.arduino.cc/Code/Timer1, which is where you should start.
In terms of plotting the data: that's not an Arduino problem, that's a problem for whatever you choose to use to collect and analyze your data.  I suggest Excel, since it's relatively common, or Google Sheets, since it's free.  If you have access to Matlab, though, that's a much more powerful program.  Either way, that is off topic for this forum.

Rather than a timer interrupt, I would use a timer to trigger the ADC, and the ADC interrupt to read the data. This will provide a more steady acquisition rate than triggering the ADC from a timer ISR.


text:
Arduino Simulator for Windows that can be detected by Arduino IDE through a Virtual COM Port
Hello is there an Arduino Simulator for Windows that can be detected by Arduino IDE through a Virtual COM Port?
I've seen simulator online but I can't seem to find a simulator that can be programmed using the Arduino IDE through a Virtual COM port.

Possible duplicate of Can I program for Arduino without having a real board?

One of the option is using Proteus simulator with Arduino library. You can build the program via Arduino IDE, then export the compiled binary (.hex file). Proteus also provided virtual terminal feature (not Virtual COM).


text:
what is the right way to parse JSON to Arduino?
i am trying to Turn an LED from a hosted website, though Arduino using the CC3000 wifi shield. It is working as it should. but i have to questions about optimising my code :
1) the Part where i parse my JSON is kind of sloppy, what is the right way to Parse the code so i can turn the LED on and off when clicking on the website buttons ?
2) i need to keep the arduino connected to the website, so i can always control the LED. Do i need to close the connection at the end ? if so, how can i activate the connection only when clicking the button on the website to active the LED.
#include <ArduinoJson.h>

// Include Libraries
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>

// Define Pins
#define ADAFRUIT_CC3000_IRQ   3
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10

// Define Variables
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER);

#define WLAN_SSID       "MyWeb"
#define WLAN_PASS       ""
#define WLAN_SECURITY   WLAN_SEC_UNSEC // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2

uint8_t dhcpTimeout;

#define host "mygarden.comli.com" // Your domain
uint32_t ip;
String path   = "/light.json";
int port = 80;

int pin = 9;

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

  pinMode(pin, OUTPUT);
  pinMode(pin, HIGH);

  // Connect to Wifi
  cc3000.begin();
  Serial.println(F("Initialising the CC3000"));
  if (!cc3000.begin())
  {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    while(1);
  }

  /* Delete any old connection data on the module */
  Serial.println(F("Deleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  // Connect to Network
  beginning:
  Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
  cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);
  Serial.println(F("Connected"));

  //Wait for DHCP to complete
  Serial.println(F("Requesting DHCP"));
  while (!cc3000.checkDHCP()) {
    delay(500);
    Serial.print(F("."));
    dhcpTimeout ++;
    if (dhcpTimeout == 60) {
      Serial.println(F(""));
      Serial.println("DHCP Timeout! Attempting to reconnect.");
      dhcpTimeout = 0;
      goto beginning;
    }
  }
  Serial.println(F(""));
  Serial.println(F("DHCP complete"));

  //get website IP
  ip = 0;
  Serial.print(host); Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(host, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }
  cc3000.printIPdotsRev(ip);
  Serial.println("");
}

void loop(void) {

  Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);

  client.print(String("GET ") + path + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: keep-alive\r\n\r\n");
  delay(500); // wait for server to respond

  Serial.println(F("----------"));
   while (client.connected()) {
    String response = "";
    bool begin = false;
      while (client.available() || !begin) {
      char c = client.read();
      if (c == '{') {
        begin = true;
      }
      if (begin) response += (c);
      if (c == '"}') {
        break;
      }
      delay(1);

      }
      int start = response.indexOf("light\":\"") + 12;
      int end = start + 3;
      String LED_Control = response.substring(start, end);

      if (LED_Control == "onn") {
        digitalWrite(pin, HIGH);
        Serial.println("LED ON");
      }
      else if (LED_Control == "off"){
        digitalWrite(pin, LOW);
        Serial.println("led OFF");
      }

   }

  delay(1000);
  Serial.println(F("\n\nClosing the connection"));
  client.close();
  cc3000.disconnect();

}

And this is my JSON output
{"light": "off"}

Did you try the "ArduinoJson library on Github" ?

I did, but i had difficulty implementing it in my exemple.

Is response equal to your json {"light": "off"} ?

@mounim Thanks buddy for asking this question. I have the same problem and finally solved it by reading this.

Assuming that String response will contain the json {"light": "off"} and your program is ready to use the ArduinoJson library (#include <ArduinoJson.h> on top), a simple solution could be:
Step1 - declare and initialize StaticJsonBuffer object.
StaticJsonBuffer<80> jsonBuffer;

Step2 - deserialize the json from response.
JsonObject& root = jsonBuffer.parseObject(response);

Step3 - if the deserialization doesn't succeed, warn and break,
if (!root.success())
{
  Serial.print("parseObject(");
  Serial.print(response);
  Serial.println(") failed");
  break;
}

Step4 - otherwise, use json object to get the LED_Control.

Is the json will really contain {"light": "onn"} or is a typo ?

String LED_Control = root["light"];

if (LED_Control == "onn") {  // 'on' or 'onn' ??
    digitalWrite(pin, HIGH);
    Serial.println("LED ON");
}
else if (LED_Control == "off"){
    digitalWrite(pin, LOW);
    Serial.println("led OFF");
}

That made alot of sens, thanks .... it ment to be "on" :)

Thank you so much for this answer. Finally, I'm able to parse my JSON data successfully.

If the response from the web server is just a boolean value, the 'right' way would IMHO be to return e.g. just a 0 and 1 instead of JSON encoded data. That saves you from parsing JSON on the Arduino completely. Instead you can simply read one character of the response and check for '0' or '1'.
HTTP is a request-response based protocol and not suitable for staying connected to the server. If you need immediate reaction from the Arduino to server-side changes and your web server supports WebSockets, you could use any of the WebSocket libraries for the Arduino. Otherwise, you can use HTTP and poll the web server at a set interval to get the current value of the switch. And if you don't implement HTTP keep-alive, you will have to close the TCP connection and make a new connection for each HTTP request.


text:
Using CLion as Arduino IDE — Cannot find Libraries
I'm having a problem using CLion as Arduino IDE when integrating 3rd-party libraries:
Here is the CMakeList.txt

cmake_minimum_required(VERSION 2.8.4)
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/cmake/ArduinoToolchain.cmake)
set(PROJECT_NAME ArduinoIceCream)
project(${PROJECT_NAME})

set(${CMAKE_PROJECT_NAME}_BOARD mega)
set(${CMAKE_PROJECT_NAME}_PORT COM4)
set(mega.build.mcu atmega2560)
LINK_DIRECTORIES(C:\\Users\\Xybrek\\Documents\\Arduino\\libraries)

set(${CMAKE_PROJECT_NAME}_SKETCH ArduinoIceCream.ino)
generate_arduino_firmware(${CMAKE_PROJECT_NAME})

Here is the log:
"C:\Program Files (x86)\JetBrains\CLion 2016.3\bin\cmake\bin\cmake.exe" --build C:\Users\Xybrek\ClionProjects\ArduinoIceCream\cmake-build-debug --target upload -- -j 4
-- Generating ArduinoIceCream
-- Using C:/Program Files (x86)/Arduino/hardware/tools/avr/bin/avr-objcopy.exe for converting firmware image to hex
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/Xybrek/ClionProjects/ArduinoIceCream/cmake-build-debug
[ 89%] Built target mega_CORE
Scanning dependencies of target ArduinoIceCream
[ 92%] Building CXX object CMakeFiles/ArduinoIceCream.dir/ArduinoIceCream_ArduinoIceCream.ino.cpp.obj
C:/Users/Xybrek/ClionProjects/ArduinoIceCream/ArduinoIceCream.ino:22:32: fatal error: BasicStepperDriver.h: No such file or directory
 #include "BasicStepperDriver.h"
                                ^
compilation terminated.
CMakeFiles\ArduinoIceCream.dir\build.make:65: recipe for target 'CMakeFiles/ArduinoIceCream.dir/ArduinoIceCream_ArduinoIceCream.ino.cpp.obj' failed
mingw32-make.exe[3]: *** [CMakeFiles/ArduinoIceCream.dir/ArduinoIceCream_ArduinoIceCream.ino.cpp.obj] Error 1
mingw32-make.exe[2]: *** [CMakeFiles/ArduinoIceCream.dir/all] Error 2
CMakeFiles\Makefile2:103: recipe for target 'CMakeFiles/ArduinoIceCream.dir/all' failed
mingw32-make.exe[1]: *** [CMakeFiles/upload.dir/rule] Error 2
CMakeFiles\Makefile2:211: recipe for target 'CMakeFiles/upload.dir/rule' failed
mingw32-make.exe: *** [upload] Error 2
Makefile:169: recipe for target 'upload' failed

authors: البطل القاهر


text:
Scan IP address of ESP8266
I am working on a project in which, the mobile app/browser sends HTTP command to ESP8266 in AP mode. The default IP address of ESP is 192.168.4.1. Therefore in order to connect the ESP to WiFi, the command goes like this :- 192.168.4.1/SSID=XYZ/Pass=XYZ.
On connecting to router, the ESP goes into STA mode and Doesn't create AP until WiFi is not found to which it was connected earlier. Now when ESP is connected to router, the router assigns the IP to ESP through which HTTP command will be sent. On Serial monitor, it does show the IP address to which it is assigned, but what if app controls the ESP, there is no serial communication. How will app know the IP address assigned to particular ESP8266? Is there any way app can scan the router? Or any other way to do this? If there are multiple ESP connected to router, how can I identify the IP of particular ESP.

Other than mDNS?

The de-facto standard way for devices to broadcast their IP address to clients is through the Multicast DNS system (mDNS). In this system the server sends a UDP message to a specific multicast group address and clients listen for it so they can work out what is where.
mDNS is also known as Zeroconf or Bonjour depending on who you talk to.
The ESP8266 Arduino core (if you are programming the ESP8266 directly) has mDNS examples with it. If you are using the AT command interface instead, then you will need to read the manual to find how to send UDP packets to multicast addresses.

Is it different from Multicast UDP by any chance?

mDNS uses multicast UDP.

Have the app send a broadcast UDP packet, and have the ESP listen for such  broadcasts. Now the ESP knows the IP address of the device on which the app is running, and it can somehow let it know its own IP address: perhaps connecting to a particular socket on which the app will listen, or sending a UDP broadcast of its own.

You can hard-code the required IP address for ESP8266. (That may not be possible all the times).
There's a sample code :https://www.arduino.cc/en/Reference/WiFiConfig
If you are not hard-coding IP address, you can read IP address of ESP by using WiFi.localIP() function in Arduino.

Please read question carefully before answering.

The hardcoded IP can conflict with existing devices connected to router with same IP.

The app has no way to know the the IP of devices, even after using the WiFi.localIP(). This can only be useful in serial.

You can use sockets

I know that, but question is different. Kindly do not provide vague answers.

Regarding mDNS is the solution but unfortunately it has limitation just like currently not supported with Android Platform.
My Suggestion is to keep listen the UDP port on all range of IP address of network as of token and on when you found right reply of UPD packet along with that device IP/MAC/port inside of that replayed packet then you will good to go.
No doubt this will take bit time to done but its only one time or until the IP has been changed.