text:
Getting a binary string and convert it to decimal
I have a 4 dipswitch to get a 1 or a 0, try to get that into a string and from that get a decimal, therefor if I get for example a 0011 a 3.
so, I know that from the variations of 0000 to 1111 is a decimal from 0 to 15, I already have my string but how do I convert the "binary string" to decimal?
to get the string I'm using this (the I is at 5because there is where is the dipswitch):
      for(int i = 5; i <= 9; i++){
           Serial.println(digitalRead(i));
           Dstate = Dstate + digitalRead(i);
      }

What has a String got to do with anything?

What you want are the bit-shifting operators << and >>, and the OR operator |:
for(int i = 0; i < 4; i++) {
    Serial.println(digitalRead(5 + i));
    Dstate = Dstate | (digitalRead(5 + i) << i);
}

You'll notice I changed the loop so it runs from 0 to 3 instead of 5 to 9 - it makes other parts easier if you start counting from 0.
Then the line:
Dstate = Dstate | (digitalRead(5 + i) << i);

is where all the magic happens.  Let's break it down:
digitalRead(5 + i)

That of course gives you a 0 or 1 for pins 5, 6, 7 and 8 in turn.
<< i

That shifts the value returned by digitalRead() left i bits.  For instance, if digitalRead() returns 1 and i is 0 then 1 is left shifted 0 times so remains as 0b0001.  If i is 1 then it left shifts one bit, so the value becomes 0b0010.  If i is 2 then it shifts two bits, so you get 0b0100.
Finally the result is combined with the current value of Dstate with OR, so the four values basically get laid over the top of each other.
So say you have the four switches in the positions ON-OFF-ON-OFF and Dstate starts off as 0, then the sequence would be:
i = 0, digitalRead = 1, shifted = 0b0001, OR = 0b0001
i = 1, digitalRead = 0, shifted = 0b0000, OR = 0b0001
i = 2, digitalRead = 1, shifted = 0b0100, OR = 0b0101
i = 3, digitalRead = 0, shifted = 0b0000, OR = 0b0101

awesome response, but then how do I change the value 0b0101 to decimal and get a number from 1 to 15?  because if I try 0b0101 in a binary to decimal calculator from google, it obviously won't work

It already is a number from 0 to 15.

yeah you are right! I messed up when I copied and pasted your code and then started playing with the dipswitches to notice the change.


text:
How to wire a small quadcopter drone with resistor and breadboard (If possible)?
http://www.instructables.com/id/SpeechVoice-Controlled-Arduino-Drone/?ALLSTEPS
Hi guys!
I am following this project but I do however not have all the items currently at home so I was thinking if there is an optional solution.
I do not have any resistors or a breadboard currently at home so I was wondering if there is an optional solution.
What I have is, arduino uno + arduino mini and hc-05 bluetooth and of course 4 small drone motors. On top of this I have TIP-122 transistors and a l293d motor driver.
Could I somehow make it work with that considering i do not have resistors or a breadboard at home?
I know how to solder of course so if I need to solder wires that is not a problem. I appreciate any help very much!!

That's not a breadboard, that's a PCB.

Resistors are probably the single most basic item that every EE needs without question. A good selection of the common ones.

You need resistors where that article puts them, otherwise you could brownout the whole thing. You may be able to get away without a PCB, at the cost of reduced stability. Find or borrow the three resistors needed for the project, and then I recommend that you order both a large pack of 1% resistors as well as a variety of PCBs when you are able to.

source: Stack Exchange

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

sort: votes


text:
How can I split a string into multiple parts?
I currently gather a string via bluetooth to my arduino and the string only has 5 different letters. "HELLO". I now wish to store these individual letters in a string on their own. Right now i have this code:
First I create a single string:
String readString;

Then I read my BTLEserial which is where I get the value that is being sent to the arduino and i store it in my string:
char c = BTLEserial.read();
readString += c;

readString now has the value "HELLO". Now i want to split it and what I have tried is to do it like this:
String stringOne = readString.substring (0,1); //H
String stringTwo = readString.substring (1,2); //E
String stringThree = readString.substring (2,3); //L
String stringFour = readString.substring (3,4); //L
String stringFive = readString.substring (4,5); //O

But with this i do not get the correct values in each string.
Appreciate every help I can get! :)

An array is 0 indexed, which means that number 5 is out of index. "Hello" should be index valued 0-4 and not 0-5.
Here is a better code to try out:
void setup() {
    Serial.begin(9600);
}

void loop() {

String recivedMessage = "";

// Read
while (Serial.available())
{
    recivedMessage += Serial.read();
}

// Print debug
Serial.print("recivedMessage: ");
Serial.println(recivedMessage);

//// Uncomment the row under if you are not sure that the splitting is working
// recivedMessage = "Hello";

// Split
char first  = recivedMessage.substring(0, 1)[0];    // H
char second = recivedMessage.substring(1, 2)[0];    // E
char third  = recivedMessage.substring(2, 3)[0];    // L
char forth  = recivedMessage.substring(3, 4)[0];    // L
char fifth  = recivedMessage.substring(4)[0];       // 0

// Print debug
Serial.print("Cut message: ");
Serial.println(first);
Serial.println(second);
Serial.println(third);
Serial.println(forth);
Serial.println(fifth);

}

Yea i changed that but it is not working very good. I think I need to create another solution without strings and use char instead. Do you have any example? Would appreciate it a lot

Just change Serial.available() and Serial.Read() to whatever channel(Bluetooth) you are listning to. I have tried this code and its working. If this doesn't work for you then you have a problem with the library or something else. This code is = true; =)

I just tried it with my BLE and if i use the same type of code i only get numbers and not letters when I try this solution.

You are getting/reading bytes, thats how serial communication works, or is it binary? Anyway you need to translate it from byte to char and then concat to string. If you lookup that number on a ACSII table you will see every number correlate to that char ex. 80 is A

Found an easy solution. Just put char before the read, it will cast it as char. Ex.  (char)Serial.Read()

Seems to work well! I get out the different letters now consistently on their own. However i now face a different issue of course haha. The word i send first starts with a "H" and that prints out to the serial monitor just fine. However 5 seconds later that first letter changes to a "B" but the serial monitor still prints out "H" even though it should change to "B".

Hey are you Polling as they recommend in library? " It's important to constantly call pollACI if you want to efficiently handle data over BLE. Be sure to include this function at the top of your 'loop' function in your sketch. And as often as possible  "

What board are you using, Uno, mega, nano?

I am using a Uno! I fixed it now though. The problem was that the value kept adding onto the result. So i just added a simple function to remove the first 5 letters everytime a new result come in with 5 new letters.

Awesome! Yeah you are right. I thought it would reset itself every cycle. With Variable = "";  Anyway nicely done!

Yeah exactly i thought so to that it should reset everytime with the "" of the variable. Anyway thanks a ton for your awesome help! :)

String are the not the recommended way to use with Arduino although try using single parameter instead of two like substring(1) and let me know
char data[5];
for(int i=0;i <5 ;i++)
{
 data[i]=Serial.read();
}
char data1=data[0];
char data2=data[1];

so on and so forth ..

Yeah I guess I will need to create a solution without a string. Do you have quick examples I could see codewise? Would appreciate it a ton

You can simply declare a character array

ok and how do i get each character in the char? data[0] for the first letter ("H")? data [1] for the second  ("E") etc?

which Bluetooth library you are using by the way ?

i am using a adafruit BLE and here is the codeexample: https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/nrf-uart-in-detail

try the above code and let me know also you can take character array in place of character pointers whichever you consider  better.

That solution will not be optimal though because i only use "HELLO" as an example and sometimes the text will change to something else. The amount of numbers in the text (5) will always be the same though

would this work for you i can't understand what do you want exactly ??

will try it! one second

alright try it and let me know if further help needed

I get the correct value the first time in the monitor! But once it keeps gathering the data over n over the letter instead turns to this symbol: �
Any idea why?

your baud value might be wrong which baud value you are using also try to keep you serial monitor close sometimes serial monitor creates problems

9600 baud rate in serial monitor and Serial.begin(9600);

ok try closing serial monitor and verify values by some other ways like lighting up the leds

yea could try that but i do not currently have leds at home. if i send numbers instead of letters, would that change anything you think? so instead of 5 letters i send 5 different numbers that i store in 5 different int's?

Actually, serial monitor create conflicts between the serial connection and produces jibberish characters so you have to find a way to somehow verify it some other way if you don't have led's try some other components

yeah i do not know how to go at it because my current logic/setup is this: I send values from a phone to my arduino and the value is one word containing 5 different letters. When I recieve this word to the arduino i create "if-statements" and run certain commands if a letter is something. So for example, if the first letter in the 5 letter word i send is "H". I have an if-statement that says if (data[0] == "H") run a certain command. But as the data[0] produces jibberish characters after the first time this option will not work

you have to understand the moment you open your serial monitor the same moment you will start receiving the jibberish character so instead of using the serial monitor why don't you simply execute the commands.

I think it would be easier if you used a char array. Here's some sample code.
char recievedData[100]
int numChars = 0
//Now we are in the receiving loop
recievedData[numChars] = BLTEserial.read()
numChars++

Now that you have a character array with all of the members, you can simply use the numChars variable to figure out how much you got from the serial buffer (for example, using it as the upper limit for a for loop).

And to get the first letter out It gets stored here? recievedData[0]? I think I am missing the last part

Yes, it starts from index 0 and it will go to the counter - 1.

Also, you need to go out and learn the basics. Everything I just told you is within the material that you would learn in the first month of an intro to programming class.

it is weird because if i write it out like this: Serial.println (recievedData[0]); and check the serial monitor i see no letter but only blank space that gets recieved. I should get a "H" from that

What about when you print index 1?

Also blank space

Now i suddently get a "?" sign in a black square triangle

Is your baud rate correct?

I have it on 9600 baud in my serial monitor and in my void setupi have it on 9600 also looking like this: Serial.begin (9600); and   BTLEserial.begin();

Here is my BLE documentation and a code example that i use also: https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/nrf-uart-in-detail

authors: 064นายพงศ์ปณต ตุ้มทอง

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


text:
all in one Arduino robot
Can I make all in one arduino robot? Example - line follower, bluetooth control, sonar sensor,dtmf in one arduino robot just switch to any mode without change the parts.

Sure. Just get a large enough device.

Pls tell me how.

@Suny please show some effort of your own.
What have you tried? What works, what doesn't work? What do you think that's wrong? What have you observed? What sources have you found? What do/don't you understand?

I just want to make a robot with arduino.I want to add line flower,sonar,bluetooth control and dtmf. I want these 4 thing in different 4 switch with one arduino.I want to turn on/off 1/2/3/4 or all feature at the same time without changing parts.I want all of them in same place together but with different switch.

Yes, actually it has been done before (multiple times).
I, along with some other students did such a project at my school.
https://www.youtube.com/watch?v=GTJQ2VXtmk0
https://www.youtube.com/watch?v=sXXh3Q8WoEM
Materials needed

Arduino (or other programmable microcontroller board with voltage regulation)
Battery pack (and charger)
2 to 5 line sensors
ultrasonic sensor
Bluetooth module
Robot chassis
Atleast two motors (with encoders is nicer, but not neccesary)
Motor driving circuitry
Switch and emergency stop button

It can be useful to buy a "line follower robot kit"
Connection
This is the connection we used. You're free to make your own adjustments.

Programming
We used a server that (was connected via bluetooth) and has the map and a user-interface.
When you press the end-point on the server, it would generate the shortest route, calculate the directions, and send it to the robot.
The robot would then drive until it comes to a junction and then executes the direction command.
I've attached some preview code. It's better to do it yourself, but if you really don't know where to get started, you can try this.
You will have to implement the low-level code yourself.
The robot will wait for Bluetooth messages. You can set it to a "direct drive" modus or "line following" modus.
void setup() {
  // put your setup code here, to run once:
  setupBluetooth();
  setupUltrasonicSensor();
  setupMotors();
  setupLinesensors();
  state=waiting;
}

void loop() {
  char receivedCharacter = bluetoothReceiveCharacter();

  switch (state) {
    case waiting:
      switch(receivedCharacter){
        case 'd':
          bluetooth.println("Direct Drive enabled!");
          state = directDrive;
        break;
        case 'l':
          bluetooth.println("Line following enabled!");
          state = following;
          motor1.setSpeed(50);
          motor2.setSpeed(50);
        break;
      }
      break;
    case directDrive:
        directDrive(receivedCharacter);
      break;
    case following:
        followLine(receivedCharacter);
      break;
    default:
      bluetooth.println("STATE ERROR!");
      buzzer.buzz();
      led.blink();
    break;
  }
}

void followLine(){
    long distance = ultrasonicSensor.measureDistance();
    unsigned char lineSensorsPattern = lineSensors.getPattern();

    switch(receivedCharacter){
      case 'X':
        bluetooth.println("Line following disabled! (Now waiting)");
        state = waiting;
      break;
    }

    if(distance > 100 || distance == -1){
      switch(lineSensorsPattern){
        case 0b00000000:
          motor1.setSpeed(0);
          motor2.setSpeed(0);
          bluetooth.println("Following interrupted, lost path!");
          findPath();
        break;
        case 0b00000100:
          motor1.setSpeed(100);
          motor2.setSpeed(100);
          bluetooth.println("Following line, middle sensor on.");
        break;
        case 0b00000100:
          motor1.setSpeed(100);
          motor2.setSpeed(100);
          bluetooth.println("Following line, middle sensor on.");
        break;
        case 0b00000110:
          motor1.setSpeed(70);
          motor2.setSpeed(100);
          bluetooth.println("Following line, middle & right sensor on.");
        break;
        case 0b00001100:
          motor1.setSpeed(100);
          motor2.setSpeed(70);
          bluetooth.println("Following line, middle & left sensor on.");
        break;
        case 0b00000010:
          motor1.setSpeed(0);
          motor2.setSpeed(100);
          bluetooth.println("Following line, right sensor on.");
        break;
        case 0b00001000:
          motor1.setSpeed(100);
          motor2.setSpeed(0);
          bluetooth.println("Following line, left sensor on.");
        break;
      }
    }else{
      bluetooth.println("Following interrupted, obstacle in path!");
    }
}

void directDrive(char receivedCharacter) {
  switch (receivedCharacter) {
    case 'X':
      motor1.setSpeed(0);
      motor2.setSpeed(0);
      state = waiting;
      bluetooth.println("Direct Drive disabled! (Now waiting)");
      break;
    case 'w':
      motor1.setSpeed(motor1.getSpeed()++);
      motor2.setSpeed(motor2.getSpeed()++);
      break;
    case 'a':
      motor1.setSpeed(motor1.getSpeed()++);
      motor2.setSpeed(motor2.getSpeed()--);
      break;
    case 's':
      motor1.setSpeed(motor1.getSpeed()--);
      motor2.setSpeed(motor2.getSpeed()--);
      break;
    case 'd':
      motor1.setSpeed(motor1.getSpeed()--);
      motor2.setSpeed(motor2.getSpeed()++);
      break;
  }
}

My advice
My best advice is to work in iterations. Slowly add more features until you've got the product that you desire. Or develop parts of it individually.

Get a bluetooth link working, send some messages back and forth.
Connect motors to an Arduino and chassis let it drive a pre-programmed path.
Get some line sensors to work (non reflecting black tape!)
Get a ultrasonic sensor to work.
Start combining these! Control the robot over bluetooth. Let the robot follow the lines. Add a breaking when it sees something within range.

As addition/clarification.
You could make a button, that increases the state every time you press it.
If you then check which state the robot is in, you can make it perform his task for that state.
if(buttonPressed){state++;}
if(state>3){state=0;}

if(state==0){
  //code for DTMF handling
}else if(state==1){
  //code for bluetooth
}else if(state==2){
  //code for sonar
}else if(state==3){
  //code for line sensors
}

I'm sure the OP sill just write "there are compiler errors in your code, can you fix them?", according to the amount of effort he put in the question. And by the way, great answer, even if it is wasted for this question

How to without ATMEGA? I want to use only a anduino r3

@Suny the Arduino R3 is an "Atmega328P development board". In our project, we "made our own Arduino". You can easily use the Arduino Uno R3 in your case, it doesn't really matter ;)

I just want to make a robot with arduino.I want to add line flower,sonar,bluetooth control and dtmf. I want these 4 thing in different 4 switch with one arduino.I want to turn on/off 1/2/3/4 or all feature at the same time without changing parts.I want all of them in same place together but with different switch

I hope u understand.

@Suny, yes, but I think it's better to just get started. Do you have all the parts required? Do you know how to hook them up? Try to get it working and if one thing won't work, you can ask again. You can easily change from "mode" by pressing a button or sending a command, so I don't think it'll be a problem.

But what about arduino code? can I upload all code for 4 defferent iteam at the same time?

@Suny if you look at my code. You can keep a "state" variable, this can be an integer or anything to keep track of what your robot should be doing. In your code you can then call the code that is used for that state. I've added a little clarification at the bottom of my answer.

Ok.I am trying. Hope it will work.


text:
Sidestep one second log rate with NeoGPS when another sensor on the board need to log faster
The sample rate of an accelerometer, like an MPU6050, is much faster than the GPS log rate, different technology, different issues.
A common GPS Reciver has, approximatly, one second log rate.
In my specific case the accelerometer has a 100hz log rate.
With a previous code the gps log rate was slowing down the accelerometer log rate so i thought to introduce two counters:

one for the gps
one for the accelerometer

What i tried to do was:
  if ((lastLogGPS + LOG_RATE_GPS) <= micros()) {
  //Log accelerometer and gps data
  } else ((  if ((lastLog + LOG_RATE) <= micros()) {
  //Log only Accelerometer data
  }

1. Is that a speed and memory efficient solution? Or better way exist*?
2. During a 60 seconds test the board return me only the accelerometer value, never the satellites informations, i think there are some dumb errors in my code

Thanks for your help :)
This is the void loop section
void loop()
  {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU,14,true);   // request a total of 14 registers
    AcX=Wire.read()<<8;
    AcX|= Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    AcY=Wire.read()<<8;
    AcY|=Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ=Wire.read()<<8;
    AcZ|=Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    GyX=Wire.read()<<8;
    GyX|=Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY=Wire.read()<<8 ;
    GyY|=Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ=Wire.read()<<8;
    GyZ|=Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
    if ((lastLogGPS + LOG_RATE_GPS) <= micros()) {
    while (gps.available( gpsPort )) {
    fix = gps.read();  // get the entire fix structure, once per second

    if (logGPSData()) { // Log the GPS data
    SerialMonitor.println( F("GPS logged.") ); // Print a debug message
    } else {// If we failed to log GPS
    // Print an error, don't update lastLog
    SerialMonitor.println( F("Failed to log new GPS data.") );
      }
    }
   lastLogGPS=micros();
  }
  else{
    if ((lastLog + LOG_RATE) <= micros()) {

      printImuData(dataFile,lastLog, AcX, AcY, AcZ, GyX, GyY, GyZ);
      dataFile.flush();
      }
    lastLog=micros();
    }
  }

This the function that print only the accelerometer informations:
static void printImuData(Print &printer, unsigned long lastLog,
        int16_t AcX, int16_t AcY, int16_t AcZ,
        int16_t GyX, int16_t GyY, int16_t GyZ)
{//Printing the mpu6050 information

  printer.print("0");   printer.print(",");   //0 longitude
  printer.print("0");   printer.print(",");   //0 latitude
  printer.print("0");   printer.print(",");   //0 altitude
  printer.print("0");   printer.print(",");   //0 speed
  printer.print("0");   printer.print(",");   //0 course
  printer.print("0");   printer.print(",");   //0 date
  printer.print("0");   printer.print(",");   //0 time
  printer.print("0");   printer.print(",");   //0 satellites
  printer.print(lastLog); printer.print(",");
  printer.print(AcX);     printer.print(",");
  printer.print(AcY);     printer.print(",");
  printer.print(AcZ);     printer.print(",");
  printer.print(GyX);     printer.print(",");
  printer.print(GyY);     printer.print(",");
  printer.println(GyZ);

}

And this is the part for the GPS informations:
byte logGPSData()
{
  if (dataFile.isOpen())
  { // Print longitude, latitude, altitude (in feet), speed (in mph), course
    // in (degrees), date, time, and number of satellites.

    if (fix.valid.location)
      dataFile.print(fix.longitude(), 6);
    dataFile.print(',');
    if (fix.valid.location)
      dataFile.print(fix.latitude(), 6);
    dataFile.print(',');
    if (fix.valid.altitude)
      dataFile.print(fix.altitude() * 3.2808, 1);
    dataFile.print(',');
    if (fix.valid.speed)
      dataFile.print(fix.speed_mph(), 1);
    dataFile.print(',');
    if (fix.valid.heading)
      dataFile.print(fix.heading(), 1);
    dataFile.print(',');

    if (fix.valid.date) {
      dataFile.print( fix.dateTime.full_year() );
      if (fix.dateTime.month < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.month );
      if (fix.dateTime.date < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.date );
    }
    dataFile.print(',');

    if (fix.valid.time) {
      if (fix.dateTime.hours < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.hours );
      if (fix.dateTime.minutes < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.minutes );
      if (fix.dateTime.seconds < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.seconds );
    }
    dataFile.print(',');

    if (fix.valid.satellites)
      dataFile.print(fix.satellites);
  dataFile.print(',');
  dataFile.print(lastLogGPS);
    dataFile.print(',');
    dataFile.print(AcX);
    dataFile.print(',');
    dataFile.print(AcY);
    dataFile.print(',');
    dataFile.print(AcZ);
    dataFile.print(',');
    dataFile.print(GyX);
    dataFile.print(',');
    dataFile.print(GyY);
    dataFile.print(',');
    dataFile.print(GyZ);

    dataFile.println();
    dataFile.flush(); // make sure the file contains at least this much

    return 1; // Return success
  }

  return 0; // If we failed to open the file, return fail
}

Here a pic of some data returned by Arduino

*I need to load easily the *.csv whith the recorded data on matlab so i have some constraints.

I'd be tempted to go about this a different way. Check if there is data waiting on the GPS serial port, if so log GPS data. If not assume this is an IMU only time. That way you will log GPS data whenever it is generated even if the GPS rate is set to something other than 1 Hz. Also your GPS data will be at exactly 1 Hz (or whatever rate you set). If you use the arduino clock to time reading GPS data then things will get out of sync over time. You'd need a very long log file for it to matter much but it's good practice to allow for different clocks to be slightly off from each other.

@Andrew I solved moving out of the statement   if ((lastLogGPS + LOG_RATE_GPS) <= micros()) {   the statement  while (gps.available( gpsPort )) {     fix = gps.read();, but is very very slow now and is logging at one second rate very useless. By now i can log gps information, but at one second log rate, so i resolved nothing. I attached a string example [link[(http://imgur.com/a/0CWFc)

Ok, I won't recreate your whole code, but here is a logic snippet that you can use.
Let's suppose that you have 2 sensors, sensor1 and sensor2.
sensor1 is read every 10 milliseconds and sensor2 is read every 16 milliseconds.
Here is what you would do:
Make 2 global variables for your timers :
unsigned long timer1 = 0;
unsigned long timer2 = 0;

Then make 2 constants for the frequency, this example will set the frequency in milliseconds.
const int frequency1 = 10;
cosnt int frequency2 = 16;

Then in your void loop, you would do something like this:
void loop () {
    if (timer1 + frequency1 >= millis()
        read(sensor1);
        timer1 = millis();
    }

    if (timer2 + frequency2 >= millis()
        read(sensor2);
        timer2 = millis();
    }
}

This method makes sure that your code isn't going to get stuck anywhere. I would also suggest to remove any while loops because of that danger that it might freeze& your code.

Yep i made 2 global variabiles and defined the frequency, but i did not attached that part of code.  The While is inside the GPS loop, and Arduino doesn't write any data from the GPS(because It seems is Never satisfied the if condition for the GPS, or another sort of problem). More over  i am not sure the GPS will works without the "While" statement,  until now or with tinygps or neogps that Command is widey used in the tutorials :)

The suggested code will fail after some time, please read the answer to this question and update your code example accordingly.

@PatrickTrentin : This is a logic snippet, not a full code, we don't write full code for people here on SE.

@DatHa are you really arguing that it is fine for an  answer on S.E., viewed by who knows how many people, to contain a not-so-obvious implementation bug, especially for the hobbyist audience that is typical for Arduino?

@PatrickTrentin : my answer is mean't to give a direction, not the full map. Eventually, when they find that problem, they will search that question up and land on the question that you found. I am not arguing that my code is perfect, I'm just saying that this is not mean't to cover all the problems in the world. I can name many more if you really wanted to. But as I said, this is just pointing someone on the right path because here, on SE, we don't write full code for people, no matter what. So either stop complaining or write your own answer.

@DatHa I actually never asked you to write full code of any type, I simply suggested a quality improvement that is holding back my upvote.

@DatHa i implemented yet your suggestions(before reading your answer but are not useful in my case, i see on git hub that i have to use a format like while (gps.available [...])). By now I partially solved the problem, as you can see reading the comment above but, i log at one second rate (i think the limit is gps.available)


text:
autoCalibrateAccelerometerOffset() Why does my Z values swing from 0 to 1g in static condition?
I tried to implement the autoCalibrateAccelerometerOffset() function, through the code below on Arduino Genuino 101.
In a static test, without any stress or noise, I read the three axis value.
When I see the data on the serial monitor or on my file created with processing, the Z acceleration values changes from 1~0,99 to 0,00 g.

I think there is an error in my code.
#include "SoftwareSerial.h"
#include "CurieIMU.h"

float sensorVals[] = {0,0,0};

void setup() {

    Serial.begin(9600);
    while (!Serial);

    Serial.println("Inizializzazione del device...");
    CurieIMU.begin();

    CurieIMU.setAccelerometerRange(2);
    CurieIMU.autoCalibrateAccelerometerOffset(X_AXIS,0);
    CurieIMU.autoCalibrateAccelerometerOffset(Y_AXIS,0);
    CurieIMU.autoCalibrateAccelerometerOffset(Z_AXIS,1);
}

void loop() {

    sensorVals[0] = CurieIMU.readAccelerometerScaled(0);
    sensorVals[1] = CurieIMU.readAccelerometerScaled(1);
    sensorVals[2] = CurieIMU.readAccelerometerScaled(2);

    Serial.print(sensorVals[0]);
    Serial.print(",");
    Serial.print(sensorVals[1]);
    Serial.print(",");
    Serial.println(sensorVals[2]);
    delay(100);
}

What happens if you add CurieIMU.autoCalibrateGyroOffset(); right after CurieIMU.begin(); ?

Do you know you have Z oriented as expected?

I'm voting to close this old abandoned question as information to make it answerable has never been provided.  The obvious way to debug this is to print out both the raw and calibrated values.  That would show if it is a reading error, or the more likely case of the calibration "calibrating out" gravity.

If it is calibrating out gravity, why does it flip between values? I would be interested to see it calibrated, then tipped slightly in X/Y to see if the rows with "Z: 0" also have X/Y: 0 (they shouldnt), and if they do, then it's likely an issue with the sensor or reading too quickly from the sensor, or similar. I just dont see how calibrating out the Z would flip between 0 and 1 as per sample

@SDsolar because is a specific function of CURIE IMU library compatible only with Arduino and Genuino 101 only

@ChrisStratton the problem is related in my opinion to the Official Library function not with the sensor reading, because without applying the calibration function  in the same condition and without perturbations the sensors reading doesn't have any swinging values

Assuming you aren't jumping up and down while this is happening then it could be:

A loose wire
A dodgy power supply
A bad earth connection
A fault sensor
A weird magnetic field/flux thing

Check you wiring, make sure all the connections are secure, etc.  I bet you have done that already.
I have no idea how to check a power supply, but if you have a different one you could switch that in.  Also look into smoothing the power supply with decoupling capacitors (?)
A bad earth, all sorts of weird [stuff] happens when you haven't earthed things properly.  Different power supplies need to share earths, but I suspect that doesn't apply here.
A faulty sensor - again, unless you have a duplicate you might not know.
Weird flux.  I think the sensor is a magnetic sensor and so it could be the natural eddies and flows of magnetic flux have conspired against you.  Move the sensor away from power supplies, electrical things and specifically anything you are hacking.  Also rotate the sensor through 90 degrees and see if it still happens (With RF it will polarise the fields in a different way, and school was a long time ago and I can't remember if that works with magnetic fields too)

If i don't use the autoCalibrateAccelerometerOffset(), and i get the raw data  the values are not calibrated but stable, so i think i can exclude: Fault sensor, Power Supply, Loose Wire, Faulty Sensor, a weird magnetic field :) Thanks

An accelerometer has nothing to do with magnetic fields, unless the fields are strong enough to physically move the device.

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


text:
What is importance of the reflow profile?
I was reading the MPU6050 datasheet to understand all the type of errors that affect the accelerometer, after finding information on the Reflow Profile i look up on wikipedia the Reflow Soldering Definition
As a noob i can't understand the importance, initially i though it was correlated with the temperature effect on the accelerometer bias, but i was wrong.
Why is important?
How do you read this values?(or when you use this data)

This is not an Arduino question, it's an electronics assembly process question which would belong not here, but on electronics.stackexchange.com however it has already been asked and answered multiple times there.  Realistically most Arduino enthusiasts would buy this chip already on a board.  If you want to deal with the bare part for non-critical prototypes, skilled use of a hot air wand usually produces an acceptable outcome. If you are going for automated assembly, you would discuss this with your assembly provider; actually programming a reflow oven is far beyond the scope of things here.

Sorry for that,my mistake, i read now this link the idea to post this question here was to give the possibility to find information on this section about to the relevance or not to understand this concept related to Arduino. Before posting here i searched on electronics.stackexchange.com but i didn't find a suitable question, now i am studying this for example  Thanks for the suggestion :)

The reflow profile is of no interest to the end user - only to the manufacturer building a PCB. You don't need to know or understand it unless you are becoming a PCB manufacturer.

You use solder to attach components to a PCB. Reflowing is a specific soldering technique, manufacturers of components will specify which heating/cooling pattern will match the component(s). This having said, it's probably irrelevant to you, but atleast you now know why :)

@ChrisStratton Majenko  Paul Yep my question was offtopic, sorry for that. The story is the following: i went to a Fablab in Rome, with no previous experience, they suggest me  for a deep understanding on how Arduino works with an accelerometer to read all the datasheet, i was studiyng the "Sensitivity Scale Factor Variation Over Temperature" and arrived to the reflow profile, i made a mistake :) Thanks for your time, and sorry again :)

Reflow soldering is an assembly process for printed circuit boards (PCBs) in which surface-mount parts are placed on a PCB prepared with solder paste.  The solder is melted by heating in a temperature-controlled oven, which then electrically connects component leads to pads on the PCB.  ICs can be damaged by high temperatures/rapid changes in temperatures, so the thermal profile defines the acceptable limits on the temperature of the reflow to avoid damaging the component.


text:
How to get each byte in byte array out and be able to work with them on their own?
I am currently sending data via my bluetooth and to it I send with me 4 different values looking like this:
byte[] myByte = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};
WriteAsync(myByte);

And now I am looking for a way to store all these Hello's in different values.
What I have started with is something like this:
if (Bluetooth.available())
{
 while (true)
 {
   delay (50);
   char c = Bluetooth.read();
   readString += c;

   if (readString.length() >0) {

    if (readString[0] == "HelloOne")
    {
       Serial.println ("Hello One has been sent!");
    }

    if (readString[1] == "HelloTwo")
    {
       Serial.println ("Hello Two has been sent!");
    }

    if (readString[2] == "HelloThree")
    {
       Serial.println ("Hello Three has been sent!");
    }

    if (readString[3] == "HelloFour")
    {
       Serial.println ("Hello Four has been sent!");
    }

   }

 }

}

And I have not actually been able to debugg (not currently at home but eager to get to fix this problem asap) so there is a slim chance that my current code might be working? Very unlikely though.
So my question is, what is the correct way to get each value out in a byte array that is being sent with bluetooth to arduino?

No, not a chance of that working, I am afraid. FOr a start you need a 2D array not a 1D array, since you can only store 1 byte in a byte variable, and you want to store 4 groups of multiple bytes. You should read up on using C strings. https://en.wikibooks.org/wiki/C_Programming/Strings

Ok will take a look at that and see if i understand! I am a bit new to c++ as you can probably tell :) Thanks a lot for the link

Is it possible to do a solution to chop up the byte[]? Because I know how much chars that each byte in the array contains.

Sorry if this sound patronising, its not meant to, I'm just trying to cover all aspects.
byte[] myByte = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};
WriteAsync(myByte);

You are assigning 4 strings to the array mByte.  A string (lets ignore the Arduino type string for now) is a char* or a char[], so:
char hello1[] = "HelloOne";
char hello2[] = "HelloTwo";
char hello3[] = "HelloThree";
char hello4[] = "HelloFour";

(You don't need to do this in the code, how you have done it is fine, it just shows what you are really saying)
In English mByte should be an array of strings which in code is
char* mByte[] = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};

You could do it as
char mByte[][] = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};//ERROR

But this won't compile, because the inner array (the text) is different length and the compiler doesn't like that.
Assuming that writeAsync takes a byte as a parameter then the code to write the data becomes this:
for (int stringCounter = 0; stringCounter < 4; ++stringCounter)
{
    // get a pointer to the first element of the string
    // & means get the address (so the value can be set to a pointer)
    // (byte*) means cast (change) the value into a byte pointer.
    byte* currentLetter = (byte*)(&mByte[stringCounter][0];)
    // currentLetter != NULL means the pointer is not equal to NULL, because looking at a null pointer will crash the code.
    // *currentLetter != NULL means the thing pointed to by currentLetter is not the end of the string.
    while (currentLength != NULL || *currentLength != NULL)
    {
        // Write the thing pointed to by the pointer to the function.
        writeAsych(*currentLetter);
        currentLetter++;  // Move on the pointer
    }
}

Sorry I can't compile that at the moment, but it looks about write.  I hope it helps you understand it.

Hey thanks a lot for the answer, Matt! Will take a look in a few hours :) Thanks

To much stuff to take care off today. Trying it tomorrow


text:
MPU-6050, why is pitch, yaw and roll data not being consistent (value keeps getting higher/lower when it is stable)?
I recently bought a MPU 6050 that I plan to use with a drone. However I face some difficulties now because the MPU is not giving me steady results.
The results (pitch, roll, yaw) i get are not consistent. If I for example keep the chip stable on a table the value keeps increasing/decreasing even though it is not being touched/moved.
I also seem to get different results if i restart it even though i use it at the same angles.
Is something off with my code or is there anything else I need to do in order to fix this issue?
Appreciate any help I can get! :)
Here is my current code:
#include <Servo.h>
#include <Wire.h>

int gyro_x, gyro_y, gyro_z;
long acc_x, acc_y, acc_z, acc_total_vector;
int temperature;
long gyro_x_cal, gyro_y_cal, gyro_z_cal;
long loop_timer;
int lcd_loop_counter;
float angle_pitch, angle_roll;
int angle_pitch_buffer, angle_roll_buffer;
boolean set_gyro_angles;
float angle_roll_acc, angle_pitch_acc;
float angle_pitch_output, angle_roll_output;

void setup() {

Wire.begin();
Serial.begin(9600);

setup_mpu_6050_registers();
for (int cal_int = 0; cal_int < 2000 ; cal_int ++){

read_mpu_6050_data();
gyro_x_cal += gyro_x;
gyro_y_cal += gyro_y;
gyro_z_cal += gyro_z;
delay(3);
}

gyro_x_cal /= 2000;
gyro_y_cal /= 2000;
gyro_z_cal /= 2000;
loop_timer = micros();

}

void loop(){

read_mpu_6050_data();

gyro_x -= gyro_x_cal;
gyro_y -= gyro_y_cal;
gyro_z -= gyro_z_cal;

angle_pitch += gyro_x * 0.0000611;
angle_roll += gyro_y * 0.0000611;

angle_pitch += angle_roll * sin(gyro_z * 0.000001066);
angle_roll -= angle_pitch * sin(gyro_z * 0.000001066);

acc_total_vector = sqrt((acc_x*acc_x)+(acc_y*acc_y)+(acc_z*acc_z));
angle_pitch_acc = asin((float)acc_y/acc_total_vector)* 57.296;
angle_roll_acc = asin((float)acc_x/acc_total_vector)* -57.296;

angle_pitch_acc -= 0.0;
angle_roll_acc -= 0.0;

if(set_gyro_angles){
angle_pitch = angle_pitch * 0.9996 + angle_pitch_acc * 0.0004;
angle_roll = angle_roll * 0.9996 + angle_roll_acc * 0.0004;
}
else{
angle_pitch = angle_pitch_acc;
angle_roll = angle_roll_acc;
set_gyro_angles = true;
}

Serial.println(angle_pitch_output);
Serial.println(angle_roll_output);

while(micros() - loop_timer < 4000);
loop_timer = micros();
}

void read_mpu_6050_data(){

Wire.beginTransmission(0x68);
Wire.write(0x3B);
Wire.endTransmission();
Wire.requestFrom(0x68,14);
while(Wire.available() < 14);
acc_x = Wire.read()<<8|Wire.read();
acc_y = Wire.read()<<8|Wire.read();
acc_z = Wire.read()<<8|Wire.read();
temperature = Wire.read()<<8|Wire.read();
gyro_x = Wire.read()<<8|Wire.read();
gyro_y = Wire.read()<<8|Wire.read();
gyro_z = Wire.read()<<8|Wire.read();

}

void setup_mpu_6050_registers(){

Wire.beginTransmission(0x68);
Wire.write(0x6B);
Wire.write(0x00);
Wire.endTransmission();

Wire.beginTransmission(0x68);
Wire.write(0x1C);
Wire.write(0x10);
Wire.endTransmission();
Wire.beginTransmission(0x68);
Wire.write(0x1B);
Wire.write(0x08);
Wire.endTransmission();
}

Did you put together pieces of code you found on the internet ? Can you tell where you found them ? It is a confusing mix of different programming styles and the formulas, the usage of the Wire library, the mixing of int, long and float are also confusing. The MPU-9250 has a magnetometer for the yaw. There are a number of good libraries for sensor fusion with filters for the 6DOF or 9DOF sensors. The MPU-6050 and MPU-9250 can also use the internal dmp firmware. You could start with the Sparkfun.com website and search for MPU-9250.

I do not use mpu-9250, i use the mpu-6050. And yea when it comes to the code i have found it everywhere and put together something on my own also which makes it a bit chaotic!

The MPU-6050 is outdated and the modules on Ebay could have a wrong capacitor making it even more noisier. Can you give a reference for those formulas ? Without reference I have a lot of doubts. Looking at the code, I even have doubts about the 4ms delay. Your loop is probably more slowed down by the full output buffer of Serial than by micros(). I strongly suggest to use a library and you might consider to buy a MPU-9250. Are you perhaps using a 5V Arduino without I2C level shifter ?

I bought it from ebay so perhaps the quality is not great :( My arduino has a I2C i believe.
Do you think this example could work well? https://github.com/jarzebski/Arduino-MPU6050/blob/master/MPU6050_gyro_pitch_roll_yaw/MPU6050_gyro_pitch_roll_yaw.ino

I see some problems: the use of the Wire library is wrong (a endTransmission after requestFrom, a while loop after requestFrom); no sensor fusion; shifting a 8-bit variable 8 times to the left. This one tests new formulas. I think the results are a little noisy. Remove the display calls: https://github.com/kriswiner/MPU-6050/blob/master/MPU6050IMU.ino  This one works: http://forum.arduino.cc/index.php?topic=58048.0  This one is most often used: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050 but there have been some complaints that it does not use a real Kalman filter.


text:
How can I adjust my code so that the value that I print with my BLE device does not get chopped up when I receive it on an app?
I am using a BLE device (https://www.adafruit.com/product/1697) that I use to print data to an app. I can successfully connect the BLE to the app and receive the data but the result however gets chopped up.
What I am sending is a lat, lng value (that I gather with a library called TinyGPS++ http://arduiniana.org/libraries/tinygpsplus/) and the code looks like this:
BTLEserial.Print::print(gps.location.lat(), 8);
BTLEserial.print (", ");
BTLEserial.Print::print(gps.location.lng(), 8);

So for example if the latitude is: 32.12345678, it comes like this to the app: 3, new row, 2, new row etc.
So my question is, how can I adjust my code to make sure it does not send the result chopped up but instead sends it's complete value?

Your app code is invalidly assuming the data will arrive in a single receive API call.  You can only fix the issue by fixing the app.  Timing related things you do on the arduino mightvstatistically influence the outcome, but the only sound solution is fundamentally correct receiving code.

The answer below fixed my issue though by sending it as string

No, not really.  It may unreliably appear to work more often but it is wrong and based on fundamental misunderstanding.   Between your ardunio and your app you have a serial link and a packetized one neither of which respects your original grouping in a more than happenstance way.

As far as i can see it sends data my app and i receive it nicely just the way i want it (not chopped). I have tested it like 30 seconds though (as it keeps sending data each 2 seconds) and maybe i could face issues with a longer connection you mean? Or will there be a issue with lat, lng accuracay (value not updating)?

Or you could face an issue when the computational load on your phone or the phase of the moon or the local RF environment changes. That is the cost of invalid assumptions in software.  The only valid solution is to find the end of a message by an explicit condition.

how can I adjust my code to make sure it does not send the result chopped up but instead sends it's complete value?

The BLE device uses a package approach and the print member functions only support strings (char vectors and Arduino String). Construct the message as a String:
double lat = gps.location.lat();
double lng = gps.location.lng();
String msg = String(lat, 8) + String(", ") + String(lng, 8);
BTLEserial.print(msg);

Cheers!

The first lat value works! But with the lng value a new row is created after 4 decimals has been made, so it look like this when I get it on the app now:
36.02331400, 19.7794(new row)4300

So 4300 in this case gets on a new row

Ah, is it because 20 bytes is max to send?

With "." and "," and "space" the totalt amount of byte is 24

So i cannot send so precise gps values i suppose

Yes, there is a max size on the message. Why not send as two messages/prints?

Yeah that is true. I might as well do that. Will it delay any process by sending two prints instead of one? Like make connection slower or something? Upvoted answer by the way, works great!

Or fix your app so that it reconstructs a line of text, i.e. reads messages until new-line/carriage-return.

This answer was fundamentally erroneous.  There is no problem with the arduino code, rather the app code makes invalid assumptions.


text:
Do I need to use the PWM pins in order to control brushless motors Arduino Uno?
I am building a quadcopter with this schematic:

It works very good but i have the pins on 3,5,6,9 = PWM pins. Is it possible to use "regular" pins instead? I will add more modules later on so i will most likely run out of PWM pins.
I could of course try it right now but i want to ask first so i could potentially avoid to destroy any items!

No, you need to use PWM in order to control the ESCs which, in turn, control the motors. If you need more PWMs you might add daugtherboard based on other ICs which might provide additional PWM outputs via I2C or serial interface.
In some non critical conditions (ESCs are critical for a quadcopter) you can simulate PWM by switching a plain digital pin HIGH and LOW very quickly, but that is not as reliable as using hardware PWM.

Damn it! I am missing 1 PWM then. I use this BLE device: https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/hooking-everything-up and if you check the schematic they require 3 PWM pins which means that there are only 3 left for my 4 motors. do you think i could change a PWM to a regular pin from that BLE device instead?

Ok i read it a bit more carefully now. Seems like i can change both REQ (pin 10) and RST (pin 9)  after i upload code if i am not mistaken

That's correct: they use pin 10 and pin 9 as plain digital, no PWM is required so by re-mapping those pins you can retain the PWM functionalities of pin 9 and 10 to your goals


text:
Ultrasonic sensor returns random values on external power supply
my Problem is, that I get random values from my ultra sonic sensor if my arduino is connected to any external power supply (vin port 30) on my arduino nano.
If I power up from the laptop usb port, I get consistent values.
I have tested 3 different power supplies between 7-17V and up to 2000mA.
I have tested this on 2 different nano boards.
Also tested with an extra 2000uF capacitor between vin and gnd
pls help if you got an idea :)

What voltage are you reading on a +5 pin? (Ie "pin 27" in your 30-pin numbering scheme, or pin 6 on the ICSP header.)  Also, what model of ultrasonic sensor do you have, and which sketch is running?  And do some other sketches seem to work ok with external power?

I got the HC-SR04 Ultrasonic Sensor and the basic demo code. I found the solution see below. Thanks for your comment anyway :)

I've been facing this problems as well. Different readings with different power supplies. In fact, i get wrong readings with a good 5v 2A power supply, but get good reading with a cheap 5v 1 A power supply. Not sure why this is happening. Similar results with ultrasonic library mentioned above as well.

as I wrote above, this seems to be a floating ground thing. On the good supply the mains ground is routed through to the arduino (-) ground so it is not floating. I would have expected to get invaild readings in floating condition, but it seems to be the other way around. On pc USB you also have proper ground and you also get invalid results with newPing.

I was running into this issue as well. For me I was plugged in via USB to my computer, and i had my breadboard powering the sonic sensor through a 30v lab supply tuned to 5.02v.(5v at the other end of the meter). I solved my spurious ranging by "giving" the 5V back to my arduino by plugging my lab bench supply and the 5v pin on the arduino to the same rail.

So i tried to used a stable 5V input on the 5V input pin and got the same more or less random values (jumping all around... especially on targets more than 1m away)
So I changed form newPing lib (http://forum.arduino.cc/index.php?topic=37712.0) to Ultrasonic lib (http://forum.arduino.cc/index.php?topic=37712.0).
Now the values are correct on each power supply and even more accurate on high distance than with newPing on USB power supply.
Don't know whats broken with the newPing v1.7 lib -.- but this works!

Glad the library helped. I think perhaps the problem had to do with reference voltages. If you are using two supplies, you need to make sure they are grounded together very well. One library could stand the different voltages and the other couldn't. But the key to using two power supplies for anything is to make sure they are grounded together.

Is it possible that one library reports instantaneous values, and the other uses averaging?  Or even if both use averaging, that one is synchronous with 60Hz mains?

the arduino side (dc) don't has access to the mains frequency (ac), so I don't think this is the difference. The only obvious difference seems to be the ground level as @SDsolar wrote below. I don't have access to my setup anymore but you could test this by temp connecting main ground to the arduino gnd and see if the values change.


text:
I have two 6 volts DC motors connected to L298N motor Driver. Do I need to use 12 Volts battery?
I have two 6 volts DC motors connected to L298N motor Driver. Do I need to use 12 Volts battery?

No, you need to use a (roughly) 6V battery. They are 6V motors, so they need a 6V battery.
However, you do need to sum the currents not the voltages. The battery must be able to provide at least the current required by both motors together.


text:
arduino PWM temperature inexpected results
I am making a system which regulates the temperature of a plate.
using the PID library
I programed the system as followed:
/********************************************************
 * PID Basic Example
 * Reading analog input 0 to control analog PWM output 5
 ********************************************************/

#include <PID_v1.h>
#include "math.h"

int val, output2;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
PID myPID( &Input, &Output, &Setpoint,0,20,20, DIRECT);

void setup()
{
  //initialize the variables we're linked to
  Setpoint = 37; //temperature a reguler

  //turn the PID on
  pinMode(9, OUTPUT);
  myPID.SetOutputLimits(-100, 100);
  myPID.SetMode(AUTOMATIC);
  Serial.begin(57600);
  while (!Serial);
}

void loop()
{
  // phase haute
  //delay(100-output2);
  val = analogRead(1);
  float mv = ( val/1024.0)*5000;
  Input = mv/10;
  myPID.Compute();
  {   output2 = map(Output, -100, 100, 0, 200);
      Serial.print("output is :");
      Serial.println(output2);
      digitalWrite(9,HIGH);
      delay(output2);
      // phase basse
      digitalWrite(9,LOW);
  }
  //analogWrite(5,Output);
  //Serial.print("input temperature is :");
  //Serial.println(Input);
  // Serial.println(Output);
  // Serial.println(Input);

}

As you can see in the code the output result is between 0 and 100.
the temperature desired in the plate is 37 degre. and the actual temperature is 24 degre. consequently, the program supposes to set the value of the output to the max value to reach to 37 degre.
But the problem is my output is setting to different values as you can see here:
what can be the problem here ? thank you in advance

Could you add the value of Input to the serial print?

As Gerben said in a comment, you should add the value of Input to the serial print, to facilitate problem diagnosis.  As your question stands, one can only speculate about what the problem might be.  My speculation is that the system is unable to cope with parameters (Kp, Ki, Kd) = (0, 20, 20), ie, that it's unstable and unresponsive without proportional control.

you are right jwpat7. after changing the value of Ki. the output works very well, and the value of it is setting to the max which is 200.

@zakaria, I meant to call the first parameter Kp instead of Ki (and your 0 value for Kp was why I referred to "without proportional control") and have now corrected that in my answer.  That is, the parameter order in the PID constructor is (&inputreading, &controloutput, &setpoint, Kp, Ki, Kd, direction).  Glad it worked!


text:
Arduino Temperature sensor with a LED
I want to program a temperature sensor with a LED using Arduino.
the goal is to make a sensor, when the temperature is over than Temperature max, the LED turns off and when the temperature is small than temperature max we turn on the LED.
my problem is when I programed the void setup() as followed, the LED doesn't work, and when I comment Serial.begin (9600) the LED work but I cannot diplay the value of the temperature.
void setup() {
   Serial.begin(9600);
   pinMode(tempPin, INPUT);
   pinMode(led, OUTPUT);
}

here you find my complet code:
    int tempPin = A0;   // the output pin of LM35
float Max_temp = 24.0;
int led = 1;

float  temp, cel;
void setup() {
   Serial.begin(9600);
   pinMode(tempPin, INPUT);
   pinMode(led, OUTPUT);
}
void loop() {
      cel = readTemp();
  if(cel< Max_temp) {        // if temp is higher than tempMax
      digitalWrite(led, HIGH);  // turn on led
      delay(300);
     }
     else {                    // else turn of led
       digitalWrite(led, LOW);  // turn on led
      delay(100);
  }
   Serial.print("TEMP: ");
   Serial.print(cel);      // display the temperature
   Serial.print("C ");
   Serial.println();
   delay(300);
}

float readTemp() {  // get the temperature and convert it to celsius
  temp = analogRead(tempPin);
  return temp * 0.48828125;
}

thank you very much in advance

I think that the others have more than enough covered it, but next time please edit your question (link). If you have any questions please feel free to respond to me with @AnnonomusPenguin. Thanks!

there are 2 excellent answers below.  it is only polite to extend the authors the courtesy of an upvote and/or comment and/or accept it.  ;)

int led = 1;

You do know that pins 0 and 1 are the serial port don't you?
Take your pick.... Either use pin 1 for the LED OR use pin 1 for the serial connection.  You can't do both!
As it says in the manual:

In addition, some pins have specialized functions:

Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. These pins are connected to the corresponding pins of the ATmega8U2 USB-to-TTL Serial chip.

Your logic is backwards. Your program says if the temp is LESS THAN max then turn on the LED.
But worse than that, you should not use pin 1.  Pick any other pin.


text:
Regulation of the temperature using PID
I'm making a control system for the heating of a plate using a PID control.
the goal is to regulate the temperature of the plate by changing the power dissipated by the resistance. By using a sensor I read the temperature  of the plate and is then used as the input in the PID control.
I programmed also a signal wave square for the PWM.
but the thing I don't understand is what I'm exactly supposed to do with the output signal I receive.
and I cannot connect between the PWM and the PID.
Code of the square signal:
void setup()
{
  pinMode(9, OUTPUT);
}
void loop()
{
   // phase haute
   digitalWrite(9,HIGH);
   delay(30);
   // phase basse
   digitalWrite(9,LOW);
   delay(70);
   //ton+toff = 0.1;
//   ton = 0.1*Output;
}

Code of PID and the sensor
/********************************************************
 * PID Basic Example
 * Reading analog input 0 to control analog PWM output 3
 ********************************************************/

#include <PID_v1.h>

int val;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);

void setup()
{
  Serial.begin(9600);
  //initialize the variables we're linked to
  Input = analogRead(1);
  Setpoint = 37; //temperature a reguler

  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}

void loop()
{
  val = analogRead(1);
  float mv = ( val/1024.0)*5000;
  float Input = mv/10;
  myPID.Compute();
  analogWrite(3,Output);
  Serial.print("input temperature is :");
  Serial.println(Input);
  delay (1000);
//  delay(1000);
  Serial.print("output is :");
  Serial.println(Output);
  delay(1000);
}

Thank you in advance

The default output of the PID is bound between 0 and 255, corresponding to the n/255 fraction of the output.  You can push the output directly into a PWM-controlled pin with analogWrite(pin,Output), as in your code, but maybe add an pinMode(3,OUTPUT); or you could use the fraction to control a slower frequency like in your first chunk of code.  delay(Output);...delay(255-Output);

A PID only has one input and one output. In your case, the input will be the temperature. The use of the arduino would be to process the raw data of the temperature sensor and relay the temperature to the PID. Depending on the make and model of the PID, there could be certain transfer protocols you must adhere to. There are most likely open source libraries that will take care of transferring the data properly.
Your PID is the piece of hardware that will "decide" when it is appropriate to turn the heater on and off, therefore it shall be responsible for driving the heater. That is what the output of the PID is responsible for.
Lastly, your PID has a set point. In your case, the set point would be the desired max temperature of the plate. This set point is set and altered manually through user input.
On a side note, if this is a personal project or a non deliverable, I'd recommend not using a PID. Try processing and analyzing all of the data exclusively on the Arduino, as it would be a challenging and rewarding task.


text:
graph of a function Arduino
I am making a temperature circuit with arduino.
is there any way to plot the value of the temperature in a graph using arduino?
thank you very much in advance

Yes, there are many many ways of doing it. What kind of graph do you want, and where do you want to display it?

On what? A TFT screen? LCD screen? On your computer? A slice of processed cheese?  And do you want to see live data or analyse historical data? You need to give specifics or we can't help you.

yes, on my computer. and I want to see Data in real time

Do you want to program your own graphing system or use an off-the shelf product?

Did you just casually drop the Matlab requirement in your comment? If so, please edit you question to reflect this requirement. Otherwise, if you want something simple, use processing to graph the data

Yes you can use the Plot menu command in the new Arduino 1.6.6 or you can use the Visual Micro debugger to create graphs in Visual Studio

I tried with new arduino 1.6.6 but I don't know how to use the plotter. in the menu i found Serial plotter, can you tell me how can I do to plot my function ?

it works. because if we want to plot we cannot write;
Serial.print("Output is :"); Serial.println(Output);  so we have to write just :
Serial.println(Output);

Yes that's right. In visual micro you can have multiple values with descriptions without editing your code. In Arduino you have simpler system and must change your code to use Serial.println(number) :)


text:
Using Johnny-five API with RFID Controller Shield
Is it possible to use the Adafruit PN532 NFC/RFID Controller Shield with the Johnny Five API? I've searched the depths of google and I'm unable to find anything so far. If it is possible, how can I go about this?
I'm using an Arduino Uno with this.

Have you tried routing through the serial port as suggested in https://github.com/rwaldron/johnny-five/issues/804 ? I might try this as I'm trying to do the same thing.


text:
How to turn two LED's on and off with one button?
I was wondering how to write a code that would do this, WITHOUT using IF and ELSE: when the button is pressed, one LED is on and the other one is off, but when the button is not pressed, the LED that was on turns off and the other one turns on.

Other than with the ! operator?

Commenting instead of replying because you asked for code, but this could be done in hardware.  If you wire in a PNP transistor to switch the second LED, it will free up the second DIO pin.

Can I ask why you don't want to use if and else?  Is this just hypothetical fun?

@KJP if you add an x amount of shift registers, you'll free up an (x*8)-6 amount of in/outputs? ;D

Just use the return value of digitalRead (which is 1 or 0) as the input to digitalWrite:
int btnVal = digitalRead(3);
digitalWrite(4, btnVal);      // On when button is HIGH
digitalWrite(5, 1 - btnVal);  // Off when button is HIGH

Or using boolean instead:
bool btnVal = digitalRead(3);
digitalWrite(4, btnVal);      // On when button is HIGH
digitalWrite(5, !btnVal);     // Off when button is HIGH

You can also use ! with int values.

You don't say....

Wasn't necessarily telling that to you, but leaving that comment as a note to the OP, which seems to be a beginner, or to any future reader.

in C, bool and int are interchangeable.

There is no such thing as bool in C.

@Majenko: In C99 there is _Bool, and bool if you #include <stdbool.h>.

@EdgarBonet It may be called a _Bool but it's still an integer: Boolean values still behave as integers, can be stored in integer variables, and used anywhere integers would be valid, including in indexing, arithmetic, parsing, and formatting. This approach ("Boolean values are just integers") has been retained in all later versions of C.

Yes, C bools are integers, yet (bool) 1 == (bool) 2.

And also (1 != 0) == (2 != 0)

You could do it with only a switch/case statement. You do not even need to de-bounce the switch.


text:
Networking multiple Arduino Megas and updating their programs from one master
Is it possible to link multiple Arduino Megas using RS485, for example, and update the program on client Megas from one master Mega, as well as for them to communicate with each other? Whilst I found multiple examples of networks, nothing comes up for programming the boards other than through a PC
Thanks for any pointers!

In principle, yes, you can do it. It's what existing bootloaders do -- they take code over the serial port, or USB, load it to flash, and then branch to it. Not to mention OTA.
So yes, you can modify the bootloader to use different pins, talk rs485, come up with code-integrity checks, specify particular bit patterns to signal "reboot" or "now load new code", and so on. If you have enough flash, you can even keep two copies, a working and a new, like most OTA code does.
I am not aware of a ready-made library that does that. If I wanted to roll my own, I would start by studying the OTA code.


text:
Getting RGB values from camera
I have a camera I'm planning on attaching to an arduino uno, that I want to take pictures and extract the average RGB value from each image.
This is the camera I have, but I've now realized that it takes pre-compressed JPEG images, and so I cannot make use of the data it's giving me.
I realize that an arduino is not the optimal tool to use in this case, but I'm curious as to whether there would be any way to decompress the images and convert them to a format I could use. It does not need to be fast, and I do not need to take the pictures quickly. I have experience with programming but have not done many projects with the arduino, so any help or advice is appreciated.

Here is the JPEG decoding algorithm if you want to give it a try. You only need the DC coefficient of every block, so you can skip a few parts of the decoding.

No. The Arduino (or not the "normal" Arduinos) doesn't have enough memory to decompress JPEG.
I made a JPEG decompressor for chipKIT boards the other day, and it uses the absolute bare minimum memory possible, and still comes it at close to 128kB. Far more than any "normal" Arduino board.
You can possibly do it with one of these new-fangled Linux-based Intel boards that are being sold as Arduino these days, but they are not your normal run-of-the-mill Microcontroller but closer to a Raspberry Pi.
Speaking of which, the Raspberry Pi is probably a much better choice than any Arduino board for the kind of thing you are trying to do.

Notice that for getting the average color you only need the DC coefficient of every 8×8 block, which should significantly simplify the problem (at least you do not need to reverse the DCT). I'm not claiming it will fit in 32 KiB, but the OP may try if he finds it amusing.

Alright, this was what I was expecting to hear. Thanks!


text:
Wiring light sensor OPB704WZ to Arduino Due
I would like to create a tachometer with the light sensor OPB704WZ.
I followed this schema https://tonyrobotdt081.wordpress.com/2014/04/10/report-on-the-light-sensor-opb704wz/ on a bread board (for now), and tried to measure the voltage difference on the signal pin (green on the schema).

Problem is, I don't see a clear difference between a white surface and a black one; It does change if I put the sensor closer or further away, but that's about all I can see.
Is there something else I need to add to my wiring to make the difference between high and low depending on the luminosity more obvious? I know others have been able to use this sensor for the same purpose.

Are you sure that the LED is on? You can check it using a camera.

As with most links Arduino users "find" that one displays a complete lack of basic electronic understanding.

Regardless of the colour of the reflector you are most likely driving the transistor into saturation. You'll never see any difference in the reflectivity with it like that.

If you read the datasheet you see no mention is made of colour - only how diffuse the surface is. Even a black card can still be highly reflective to infra-red - you just can't see it.  A sheet of polished black metal is more reflective that a piece of white paper. You can't see your face in the paper (unless you're a criminal) but you can see it in the polished black metal.

@Majenko None of your comments are helping in any way.

You expect that the white surface to reflect the infrared light and the black surface does not.
Your theory is correct; white surfaces should reflect pretty much all light and the black surface should absorb all light.
The problem is that the black surface is reflecting enough light to turn the photo-transistor on.
The theory is correct but in the real world this is not perfect. For example a white surface is not completely white. Likewise no black surface is completely black.
We also know that a mirror is much better at reflecting light than a white surface. The black surface could be shiny. I am looking at my shiny black monitor stand, and even though it is black I can still see the reflection of the window.
I suggest trying with a number of black surfaces (such as paint, card, cloth) and finding the one that works best. I would imagine that chalk board paint would work well at absorbing and diffusing the infrared light. Also experiment with the distance away from the surface. You may have to move it further away from the surface.
If I am imagining your tachometer right, your sensor will see a reflective surface and then it will see empty space (and then repeat). This should work fine. Give it a try.

You want some Vantablack 2.0 ;)

Vantablack is a substance made of vertically aligned carbon nanotube arrays and is one of the darkest artificial substances known, absorbing up to 99.965% of radiation in the visible spectrum. -Wikipedia

Vantablack 2.0 is even blacker.

I see and understand your point. I need to measure (and change) the number of rpm on a tool. It has a stainless steel surface, and I intend to grind a stripe about  a 1/4" wide, and paint with mat black. I do believe this will work, as there should be a maximum contrast between the shiny steel and mat black
BUT, before getting there, I would like to test, just moving by hand this sensor. I will try your suggestion.

@BernardG, I look forward to your results.

@sa_leinad, tested a bit further today, and yes, it does works as expected! Thanks. Now I can start working on the actual thing.... :-)


text:
Does Serial.read() ever return a character?
I'm trying to program my Arduino Mega to work with a TSL1401 line scan module and while looking over someone else code I came across this:
void loop()
{
    int b = Serial.read();      //Reads incoming serial data. Returns the first byte of
                                //incoming serial data available (or -1 if no data is available)

    if (b == 's')
    {
        getCamera();
        delay(2000);
    }
}

For the most part I understand what it's doing but I got confused when I saw that he was setting the return value of Serial.read() equal to a variable and then checking to see if that variable was a character. To my understanding Serial.read() returns an integer so why would you compare it to a character?

On an 8 bit arduino a character is a byte.  A byte can represent values between -128 and 127, or between 0 and 255, depending on how you "look" at them (signed or unsigned).
The whole concept of a character is a purely human thing. The Arduino only knows numbers.
For instance the character 'A' is actually the number 65. We, as humans, choose to represent it as an 'A' and call it "ASCII".
Again, the character 'a' is actually the number 97. You can also subtract characters from each other.  'a' - 'A' = 32

Part of the answer is in the comment in your given example:
int b = Serial.read();      //Reads incoming serial data. Returns the first
                            //byte of incoming serial data available
                            //(or -1 if no data is available)

If you're reading raw 8-bit data from the serial port (basically, could be any value from 0-255), how do you represent errors?   Per the comment: if nothing is available, it returns -1.  But... as @Majenko pointed out, -1 is a valid CHAR too, it all depends on how you look at the data (signed, or unsigned).
But an INT can hold a value from 0-255 easily, and also a -1 to represent 'nothing'.  The Serial.read function is non-blocking (it doesn't WAIT for a data byte), so it needs to be able to return a status that indicates 'empty bucket', meaning there's actually 257 (256+1) different possible values... thus you need more than 8 bits.
It's a painful lesson with usage of fgetc(3), getc(3) and similar functions.  You need to be able to represent EOF, while also returning valid 8 bit data.  Hence the use of INT's as return value size.  Often someone (ok, me... but it was a long time ago!) will figure that since they're reading CHAR's, you can use a CHAR sized variable... but then EOF never seems to be found... oops!
Hope this helps.

On the Arduino an int value can range from -32,768 to 32,767. You can easily differentiate that from a char value. And Serial.read() returns a int value.

@ott why this example uses char? https://www.arduino.cc/en/Reference/SoftwareSerialRead


text:
Can ESP8266 replace Arduino?
I’m a hobbyist and have used Arduino so far for simple projects. Now I want to build a project involving addressable LEDs, I want to write several programs on the Arduino for the LEDs and on my phone I select which ones to run.
I found ESP8266 as a good and cheap solution to talk to my Arduino. Searching on the web to learn getting it to work I found that It has its own mcu on it and I can write and upload my code in Arduino IDE! 20kB of RAM, 80MHz CPU and 4MB of flash for 3 USD (However I’m not sure of these numbers but even one fourth of it is great)!! If I just need a few GPIOs why should use an Arduino UNO? Is this module reliable?

The internal ESP8266 processor is able to run user programs. The language used depends on what you have access to. LOA is commonly used.

@OlinLathrop If people use terms such as "LM324", "BC337", 1N4148 it is generally accepted that they are well enough known that inclusion of opamp, bipolar low power NPN transistor and silicon small signal diode, respectively is not required for understanding. | The ESP8266 family is a range of modules with WiFi + processor in a single IC and a companion memory for program. These are very very well known and something extremely worth knowing about if you have not met them. While not (yet) quite as ubiquitous as eg an LM324 they are quite possibly the most common "IOT" WiFi interface overall.

I really do not think this question deserves a negative

@RussellMcMahon It's "LUA" not "LOA".

@linhartr22 LOL

@linhartr22
Quoting from www.lua.org/about.html:
"Lua" (pronounced LOO-ah) means "Moon" in Portuguese. As such, it is neither an acronym nor an abbreviation, but a noun. More specifically, "Lua" is a name, the name of the Earth's moon and the name of the language. Like most names, it should be written in lower case with an initial capital, that is, "Lua". Please do not write it as "LUA", which is both ugly and confusing, because then it becomes an acronym with different meanings for different people. So, please, write "Lua" right!

Well, the answer of the question "Can it replace Arduino" - yes, in many cases it can.
Whether it would be "the Arduino killer" - I doubt it.
There are multiple arduinos and ESPs in my home and 1 ESP in my office running 24/7 as a part of my self-made (and constantly under development) smart home solution, together with 1-2 PCs. On top of that I have several experiments / unfinished projects involving the ESP.
So, from my not-so-limited experience, here are the pros and cons of ESP compared to Arduino:

++++ Internet connectivity built in!
++ Faster clock and more memory.
+ Runs on 3V3 (most, but not all Arduinos are 5V) so it can interface 3v3 devices (like most of the display modules) directly, without level shifters.
+ The "basic" ESP-12E costs about as much as an Arduino nano or pro micro.

- The "basic" ESP-12E is 2.0mm pitch, not 2.54mm, making it a pain in the ass to work with.
- There are breakouts that make it easier for prototyping, but they increase the cost and take too much space on a breadboard / protoboard.
- The most common breakout - NodeMCU - is more expensive and has pins remapped, major annoyance, unless you program it in Lua, which is only ok for very simple projects. IMO, it should be used for prototyping only.
- They run on 3v3, making it hard to interface 5V modules, fully turn on most MOSFETs, etc.
- They are extremely picky on their power supply.
- They draw significantly more power than the Arduino when not transmitting and much more when transmitting.
- They are almost always worse for battery operated projects - you need 3v3 regulator (which has quiescent current), you need to sleep a lot (and you need GPIO16 broken out for that) and at the end of the day an arduino + a low-power radio will do the same job while lasting significantly longer on battery.
- They have less GPIO pins and some of them must have set voltages at startup (GPIO0 - high, GPIO2 - high or floating, GPIO15 - low), also they "wiggle" some of their IO pins on startup, often making them unusable for many devices.
- They only have one ADC, and to my knowledge it is slower than the already slow Arduino ADCs, plus you can only use it with 0-1.1V (internal reference).
- Many of the Arduino libraries work out of the box or are already ported, but many don't. You either have to port them yourself or wait for someone to do it. In general, the Arduino community is much bigger and more mature, so most "noob-friendly" tutorials, libraries, etc. are provided for the Arduino.

Having that said, the ESP8266 is still great and extremely useful. Even Lua is useful for quick small projects. In most cases where internet connectivity is required, they seem to be the best solution. In many other cases, whether you will use ESP or Arduino actually doesn't matter. And sometimes the Arduino (or the little ATTiny85) is the better choice.
As always, "the right tool for the job" is the way to go.
Or combination of tools.

Strongly disagree that it is "just wrong" to use an ESP as a secondary device to an Arduino with a UART interface. You point out reasons for this yourself - if you want to use libraries that aren't yet ported to the ESP, why not have the Arduino as the primary device and use the ESP to do one job well? Or if you are more familiar with 8-bit AVR devices and can afford $5 for a very capable WiFi addon, why not do that? In engineering, excluding stupidity, there is no right or wrong way, provided it works - only more or less appropriate to a particular challenge.

There is nothing wrong with having an arduino (or attiny) connected with ESP via UART. What feels "wrong" is using AT commands and having the Arduino parse HTML requests and responses, etc. It sure works (I've done it), but sounds wrong - the "logical" way would be for the more powerful chip (the ESP) to act as a master and offload specific tasks to the less powerful chip, not the other way around. Most of the time, it is also the easier way - fiddling with AT commands parsing on the Arduino is neither fun nor efficient. Yes, you have to program both chips this way, which is inconvenient.

Might be worth editing your answer to include this clarification.

This was just a remark at the end of my answer, finished with a smilie, and it clearly mentions AT commands already. And, it is already a bit offtopic, I dont know why you picked that up.

Because the rest of the answer is good, but that last sentence is unclear and misleading imho. Clarifying for those seeking answers would help those who do not understand why this might be a bad idea - and get them away from the idea that there is such a thing as "just wrong" without clear reasoning. But the answer is yours - obviously you are free to do as you see fit.

There you go :)

@Mishony Thank you for your detailed answer. Excuse me for my ignorance, but if I want to use an Ardunio and not use AT commands, how should I talk to the Arduino? I'm new to this module and know very little. I would appreciate it if you could give me some keywords to start with.

If you really need to use an Arduino AND an ESP (instead of just the ESP) then you can still use Serial communication, but on a higher level - for example Arduino sends "temp=26.5" to the ESP, your code on the ESP recognizes that and sends an HTTP request to thingspeak.com or whatever. For this to work, you must program both the Arduino and the ESP, which is a bit inconvenient, but not really harder than fiddling with AT commands. In many situations you can simply ditch the Arduino and only use the ESP.

Yes there are a few I/O pins, so in theory you could drive one or a few leds or use an I/O port expander (I2C) for example.
And yes you can develop software and download it into even the low cost modules.  The Arduino-like angle is just one way to do this.  It is not an ARM as one might be lead to believe.  But there is a gnu toolchain for the esp8266, etc.  Yes 80 or 160MHz, 32 bit RISC, some flash, some ram.

The Arduino Uno board and the ESP module are not the same, but as long as the GPIO of the ESP8266 provides the hardware that you need for your application it will work.
One of my concerns is certification.  The product has received several certifications, you'ld need to check if your version is also certified.
You can lookup the manufacturer's certifications (and some documentation) from the FCC Search Page by entering 2AC7Z as the grantee code.
The board you use may depend on those or require their own certification.
As you noticed, it can be added as a board type to the Arduino tool which makes it a lot easier for hobiests to play with it.
I just checked the grants and all three of them require that the WiFi antenna is kept at least 20 cm of all persons.


text:
Flashing ESP8266 over WiFi whith samrtphone?
I'm working on a project in which an ESP8266 is the brain of the device. I want to add new features to the device controller later but this requires that the user open the controller and reprogram the ESP8266.
I want the user to be able to update the firmware with his smartphone (maybe through an application). How can I do that? Is this possible with this chip?

yes, you can use an http POST to push in a new firmware, look at the OTA examples

ESP8266 OTA can be performed through a web browser as detailed in the ESP8266 OTA information page.
Since a smartphone has a web browser I can see no reason why you can't use that.


text:
Communication with ESP, HTTP requests or WebSocket?
Here is my problem. I'm working on making a wifi addressable RGB LED (like WS2812b) controller, I'm using an ESP8266 as the hardware. I'm also creating a phone application for controlling the device and setting different modes. What I'm doing right now is that I communicate with the module by sending GET commands from my phone app. For example to change the brightness I send http://192.168.4.1/I125I Then on the ESP side the code is as follows:
WiFiClient client = server.available();
  if (client) {
  String inData= client.readStringUntil('\r');
  if (inData.indexOf("I")!=-1){
 BRIGHTNESS=str2int(inData.substring(inData.indexOf("I")+1,inData.lastIndexOf("I")));
}}

It works, but I'm not sure if this way of sending data is efficient at all. if change colors too rapidly the ESP resets. I recently found another code that uses GET and POST commands but different methods are used, like the following
server.on("/brightness", HTTP_POST, []() {
    adjustBrightness();
  });

Then inside adjustBrightness function brightness is adjusted. This way it looks more professional but Is it more efficient?
I recently bought a commercial RGB LED controller that uses ESP8266 as its core. I tried to see what the phone app sends to the controller using the Drony app. For my app I could see all the get command the app was sending
192.168.4.1/I255I

192.168.4.1/R200RG90GB76B

...

but for the commercial controller I just saw one connection, something like "157.10.12.10:5172"
Is this using websockets?
Is using websocket a better way? is it more robust?
I'm writing the code in Arduino IDE.

This way it looks more professional but Is it more efficient?

No, the differences are minuscule. It's only really the location of any parameters that are different - either as part of the URL (GET) or as part of the body (POST).

Is this using websockets? Is using websocket a better way? is it more robust?

No, it's just a TCP connection (or maybe UDP connection, it's hard to tell from your description) sending unknown data. It's impossible to tell what the data us from the port number, you would have to actively sniff the data and work out what it is.
Yes, it is generally more efficient doing that kind of thing (though not necessarily more "robust") - HTTP is a very generic system that can transfer many different kinds of data in a request so needs large amounts of superfluous information that is not applicable to controlling an LED, whereas a simple TCP or UDP socket only transfers the minimal amount of data needed to get the job done.

So that's why I get slower responses when I use POST request instead of GET. I think I will get better results with websockets when I bombard the ESP whit color changing commands and hopefully get fewer restarts. Thanks for your answer.


text:
Menu system without libraries
I was wondering if there are a way to do a menu system for arduino UNO using buttons and without libraries.
I tried to do it by myself but the code was too long and heavy.
I don't want full code, just a pseudo-code idea and how does it works.
I know there are libraries that to this, but I want to practise C++.
Thanks!

Interactive menus are certainly not a "simple" task. That is why people use libraries.
Whatever you try you will end up with complex code - either long winded with lots of duplication, or somewhat cryptic with lots of pointers, arrays, and structures. Not an easy task for a beginner in C++.
How I would set about it would involve the following things:

A structure that defines a menu entry, including pointers to one of: sub-menu array, numeric variable (including max/min limits), option array, function to execute.
Arrays of the above structure to define each menu
Array or linked list of "breadcrumbs" through the menu to track where you are and go back up properly
Functions to display and navigate the menu arrays on an LCD.

All of that uses fairly advanced C coding techniques, especially when it comes to managing all the pointers, etc.
The "simpler", though more long winded way, would be to write individual functions for each menu and sub-menu, but that would make your program incredibly long and prone to have errors when duplicating (copy/paste) code.

agree, i would add that all those structures probably will end up taking a lot of ram.. and sooner or later you will end up wanting them on flash memory, bringing even more complexity to your code, but yes, go for it! its a good chance to later appreciate a library and still learn a lot of c++ :D


text:
Arduino Uno ADC behavior in free running mode
I'm using my ATmega328P to sample an analog signal in free running mode. The ADC clock frequency is set to ÷128. I've read that a single analog conversion lasts 13 clock cycles. I would like to know if the number of clock cycles changes if I make the ADC trigger an interrupt after every conversion (ADIE bit set to one). Or will the ADC still use 13 clock cycles and start again on the 14th?
If ADIE is set to zero (no interrupts) will the result of the conversion still be written to ADCL and ADCH? And at what time of the 13 clock cycles is this result written to those registers? This is important to me so I can calculate how much time I have to read those registers.
Would it be possible to set ADIE to zero and instead use a timer interrupt to read ADCL and ADCH every ~1 millisecond. Or am I missing something important?

What are you trying to achieve? 13 clock cycles are way below 1 ms.

Can no one answer these questions about the adc behavior (1. & 2.)? It isn't really made clear in the data sheet. I know that 13 clock cycles are below 1 ms but those questions are still important to me.

You might take a look at Amanda Ghassaei's tutorial on Arudino Frequency Detection, she has a neat trick where she toggles a pin in her ISR to get a mark on a scope trace which allows her to see the time interval between ADC conversions.

Yes, it would still be written to the ADCx registers, or just test it out? But why would you want to read out the ADC value if it hasn't changed? How you mean, how much time you have to read it out, these are two registers and could be read in like 2 or 3 cycles. Are you afraid the reading and writimg would be at the same time?

I want to sample with a constant rate of ~1000/500/200 Hz. The ADC runs in the background with a frequency of 9615 Hz, so I  only need every ~10th/... result. I don't want to interrupt the processor everytime an conversion finished bc I don't need those results. That's why I want to set a timer interrupt to read those values from ADCL and ADCH with the right frequency.

In that case, why don't you use the timer to read the value, and then start a new conversion, instead of using free running mode.

You may want to take a look at Amanda Ghassaei's tutorials on Arduino DSP techniques or the FFT/FHT code at the Open Music Labs. Both use the Arduino ADC in free running mode. Amanda's code uses interrupts, the Open Music Lab code sits in a tight loop waiting for the conversion to complete.
Based on the Open Music Lab code I can say, yes, the conversion is still written to ADCL and ADCH regardless of the interrupt setting in ADIE. I can't tell from your question how concerned you are about cycle counts, but I don't think you'd see a significant change using interrupts (I'd expect it to be zero). But using interrupts you'll take a hit as you enter and return from the ISR.
As I mentioned in the comment, take a look at Amanda Ghassaei's code. She toggles pin 12 which creates a spike in the trace if you have a scope attached to pin 12 (or a logic analyzer). That will give you a very easy way to determine the actual time to handle the conversion.

So the result is written to ADCL and ADCH at some time (probably at the end) of these 13 clock cycles and I can read those registers until the same time in the next round (then they are overwritten)?


text:
How does one upload a synthesized solution to the Arduino Vidor FPGA?
I've compiled a solution and have received a ttf file from Intel Quartus which is designed for the Vidor 4000 Arduino board. The file represents a synthesized bitstream to be sent to the FPGA. How do I upload the file to the FPGA onboard the VIDOR board? I've got a JTAG programmer if necessary.

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


text:
I can send AT Commands, but cannot upload sketch to ESP8266 via Generic ESP Module
I can send AT commands to the ESP8266 - 01 but I am not able to upload the sketch.
I have connected TX-RX of module to TX-RX of Arduino, GND to GND, CH_PD, RST and VCC to 3.3V.
Here is the code I'm trying to upload -
#include <ESP8266WiFi.h>

const char* ssid = "ssid";
const char* password = "password";

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println(".");
    Serial.println("Connected to ");
    Serial.println(ssid);
  }
}

void loop() {
  Serial.println("Hello, Internet");
  delay(1000);
  Serial.println("IP Address");
  Serial.println(WiFi.localIP());
  delay(2000);
}

Here is the error I am getting.
Arduino: 1.8.1 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

Sketch uses 225921 bytes (52%) of program storage space. Maximum is 434160 bytes.
Global variables use 31864 bytes (38%) of dynamic memory, leaving 50056 bytes for local variables. Maximum is 81920 bytes.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

Please suggest something.

In order to put the ESP into programming mode, you need to connect GPIO0 to ground as you power it up.
(I have a push button attached to my proto board for this purpose.)

Every implementation that I've seen connects TX->RX & RX->TX when going between devices. :)


text:
How to send data in response to HTTP get request from ESP8266?
I'm trying to control some RGB LEDs with ESP8266. I have built an HTML page to set the color and send the RGB color code to the ESP using HTTP get request. Everything works as expected. I just want to send an HTTP get request to the ESP and ask what the current color is. But after a couple of hours of searching and trying I don't know how to send data in response to get request, I just can send HTTP ok code. I'm using jquery to send get command as below
$.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
    //I don't know how to send data fram ESP get it here.
});

this is the corresponding ESP response code written in Arduini IDE
WiFiClient client = server.available();
   if (client) {
  String req = client.readStringUntil('\r');
  client.print("HTTP/1.1 200 OK\r\n");
  client.print("Access-Control-Allow-Origin: *");
.
.
.

This is the HTTP header, How do I send some data(text)?

look at the webserver example. something like server.send(200, "text/plain", someStringOfContentHere); build up the string with the data you need.

Thak you for your input. To use send method I have to include ESP8266WebServer.h and modify my code. I think there should an easy way to send some text (like HTML markup) after the header.

After the last header you need to send two newlines (\r\n\r\n) and then send your data.

Thank you @Gerben! I spent hours searching but no success. It worked like a charm.

@Gerben answered my question in a comment all credit goes to him. I retype it here maybe it helps someone in the future.
I had to send two new line after setting up the header
//header
client.print("\r\n\r\n");
clinet.print("Hello, I'm comming from ESP!!");

And in jQuery I get it like this:
$.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
    var receivedData=data;  //=Hello, I'm comming from ESP!!
});

It is simple but it may help some newbie like me.


text:
Send commands to ESP8266 over WiFi
I want to send commands to ESP8266 over WiFi from my phone(I'm working on building an App using PhoneGap). I'm new to this module and WiFi. What I'm doing right now is that I communicate with the module by sending GET (or POST) commands. I'm sure there should be a better way but I can't seem to find how. What is the correct way to talk to ESP8266 over WiFi?

Could you clarify whether you are using the ESP8266 in the Arduino environment -- that is, you are compiling code (a sketch) that runs directly on the ESP8266 and responses to the GET/POST commands?

Forgot to mention that. Yes, I'm using Arduino IDE.

You could use websockets, I think there is a library for the ESP8266 around somewhere (I cant remember what its called)

fwiw, i've had better luck with http than sockets and mqtt; fewer resets/freezes, lower ping times, and more bandwidth, provided you keep responses under 4kb...

Depending on what best suits your needs, you could use:

http GET/POST commands
Websockets over http
MQTT protocol
Your own TCP or UDP socket protocol
etc.

In all cases, what you code into the ESP8266 processor/flash will need to receive and process the commands. The possibilities are near endless, since you are writing the App and the code for the module and can make those design decisions.

Thank you for your answer. Currently I'm using http GET/POST commands and on the ESP side I analyse the received string. I don't know how to use the other methods, what is the most common/reliable option? I would appreciate it if you could give me some practical references.

All of those methods listed above use IP (either TCP or UDP), so they are relatively the same reliability. MQTT requires a broker daemon to be running, so you don't talk directly to the ESP device from your app - that's an additional point of failure. I would say there is not a clear winner, however.