text:
Scale Magnometer to Servo
I'm trying to determine what is the best way to scale a magnometer to a servo, I am using the BNO055 from Bosch I get a heading say 50 degrees, and I want to be able to input 45 degrees and have the servo motor move accordingly. I am using a 180 degree motor. I would like to be able to input 45 degrees, and then the motor if 50 degrees was 95, would decrease in value step by step until the magnometer read 45; I'm having difficulty creating the logic to do this.
Bosch output is between 0 and 360; so I could end up with servo 0 is 120; and servo 180 is 300. Meaning the values are 300 - 360, 0 - 120 making the full 180, so I am not sure how I could use something like map in arduino to solve this issue.

Okay, lets say the output of your BNO055 is called x and the value for your servo is y. We need to translate x to y and you are correct to use the map() function. But what you are forgetting is that you do not need to map all the values of x to all the values of y. You can split it up.
In your example the values of the BNO055 relate to the servo as follows:
x   | y
0   | 0
120 | 0
300 | 180
360 | 180

The servo only rotates from 0 degrees to 180 degrees between the BNO055 sensor values of 120 and 300. So you only need to map those values, while all values below should result in 0 and all values above should result in 180 degrees for the servo.
This translates into the following code:
//x is the output of BNO055 sensor
if(x < 120){
  servo.write(0);
}
if(x > 300){
  servo.write(180);
}
if(x > 120 && x < 300){
  y = map(x, 120, 300, 0, 180);
  servo.write(y);
}

Another way of coding this is:
if(x < 120){
  servo.write(0);
}
else if(x > 300){
  servo.write(180);
}
else{
  y = map(x, 120, 300, 0, 180);
  servo.write(y);
}

It's hard to tell from the question, but I got the impression the OP wanted 300-360 to map to 0-60 and 0-120 to 60-180, which means wrapping the values first to be -60 to +120.

Now I'm confused, haha. Regardless what OP's desired data is, I hope this code shows him he is able to specify ranges of map() instead of just mapping everything.

@Len is correct to clarify the sensor reads 0 to 360; and for the example we have 300 to 360 and then 0 to 120 because the sensor wraps around - so my plan was to set the servo to 0 get the min reading which was 300 and 180 is 120 so then I need to map for those values so I'm guessing that means I would map like 0 to 60 for 300 to 360 and 60 to 180 for 0 to 120; does that make sense for map function?

Yes, you can reverse map values. Say you need to map 0, 100 to 10,0 you just reverse the last two variables of map() as follows map(x, 0, 100, 10, 0);
Also, about the servo. You don't need to manually change the position of the servo. Servo's are made to rotate to a specific location and know at what position they are, even if they just got power.

You need to remember that you are working with a circle. You have degrees 0 to 360, but only if counting clockwise. If you work anticlockwise you also have degrees 0 to -360.
So your angles of interest are, clockwise from 0, 0-120, and anti-clockwise from 0, 0 to -60
To make things easier on you you need to create a range that is wrapped around so that anything in the "left" half of the circle is counted as anticlockwise from 0 and anything in the "right" half of the circle is counted clockwise from 0.
So values 0-180 are 0-180, but values of 180 to 360 are -128 to 0.  Then your entire range spreads from -180 to +180 instead of 0-360 (if that makes sense).
It's simple enough:
if (angle > 180) angle = 0 - (360 - angle);

So if angle is 300 you get:
0 - (360 - 300) = 0 - 60 = -60

If angle is 330 you get:
0 - (360 - 330) = 0 - 30 = -30

Now you can map the new values using the map function @Len has detailed above:
servo = map(angle, -60, 120, 0, 180);

It is also possible to combine it all into one line should you wish, using the C "inline if" format:
servo = map((angle > 180 ? (0 - (360 - angle)) : angle), -60, 120, 0, 180);

But that is kind of cryptic :)

Excellent this solution I believe will solve it - unfortunately during the test of this solution I ended up burning out the servo motor itself :P So now I'll have to try again sometime next week, will keep this updated.


text:
What's on an Arduino board? Can i build one of these boards myself?
My question is: What is on an Arduino board besides the microcontroller?

https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

Welcome to SE-A! This is a very vague question. Are you talking components (which can be found in links provided by others), are you talking about block diagrams (features broken down by sections?). What have you looked at and what have you found? Can you build one yourself. Yes, quite easily. Should you? Depends. What do you want to achieve? There are plenty of clones out there which are a great place to start. They're cheap and take some of the guesswork out. If you like the guesswork, start with nano's or even breadboards.

When I first built my first Arduino clone, I fount very useful the Fritzing examples (boards and schematics). http://fritzing.org/home/
Mind that in order to upload sketches, an FTDI module is very handy (unless you use ISP via another Arduino board).
In any case, I should recommend you to build an Arduino clone on a breadboard, before trying soldering.
Good luck.
Additionally, you may use this picture (this is how  I create an Arduino on breadboard):

External power (battery) is connected to the screw pins (bottom left of the breadboard).

Yea thats my idea...

This list is probably not exhaustive but comes reasonably close:

A power supply (voltage regulator and filter capacitor);
A USB connector for powering from a USB port and passing data to/from
your PC;
A second processor (Atmega 16U2) for handling USB <-> serial data
conversion;
A barrel-jack for powering it from a 7 - 12v;
A MOSFET for selecting whichever power source is being used;
An LED connected to the chip's digital pin 13;
A pushbutton for manual reset and a capacitor for auto-reset;
A 16 MHz crystal and load capacitors;
Several lengths of female headers for connecting plug-wires or shields to the Arduino.

And yes, it's relatively easy to build one - instructive, too! There are how-to project details all over the Internet. I've hand-built any number of them, just soldering up whatever parts I wanted.
Here is an Arduino home brew project, CSEDuino, that was easy and fun to build, with good detailed directions. It is an Arduino clone that does everything the Uno does, except that it isn't physically compatible with Arduino shields.
All of my gadgets are on home-brewDuinos. I usually skip the USB connector and 16U2 processor, and keep one or two FTDI USB to serial cables on my bench to power or program whatever board I'm currently working on. I usually skip the auto-reset capacitor too, and manually reset the board to upload it.
Have fun building!
In service, I just power them from a USB wall charger. Any of them that need to communicate get an radio of some kind, usually Bluetooth or Wifi. Some of them just collect data to non-volatile memory for me read out later.

source: Stack Exchange

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

sort: votes


text:
Sampling rate of analog read
I have a simple following analog reading code:
void setup()
{
  // initialize serial comms
  Serial.begin(9600);
}

void loop()
{
  // read A0
  int val0 = analogRead(0);
  int val1 = analogRead(1);
  int val2 = analogRead(2);
  // print to serial
  Serial.print(val0);
  Serial.print(" ");
  Serial.print(val1);
  Serial.print(" ");
  Serial.print(val2);
  Serial.print("\n");
  // wait
  delay(50);
}

How do I determine the sampling rate? I understand for the serial print, it's 3*4 bytes (for val0,1,2) + 2 bytes for space and 1 bytes for \n, which is 15/9600.
How much time is spent on analogRead?

The sample rate will be somewhat inconsistent since the first few samples' print output will go into the print buffer with little delay. Once the buffer fills, subsequent samples' time spent in Serial.print() will vary somewhat depending on how long printing the currently printing character takes to finish, when Serial.print() is called. But the average sample rate will settle to about to about 64 Hz (1 sec / (15/960 lines/sec).
The printing time for one line is about 15.6 msec, much longer (140 times) than analogRead() takes, about 0.111 msec, according to this author's measurements.
Update:

So I could just use 50ms + 15.6 for the sampling rate, ignoring
  analogRead?

That would get you pretty close to the average sampling interval. If consistency is important to you, you'd need to measure that.
How many samples do you need at a time? Another way is to store the data in an array and print it later. Then the jitter in the sampling interval will be much smaller. You'd be limited to the number of samples you could fit in memory, though. Each 10-bit sample would need 2 bytes of storage.
If the range of your data is less than 256, you could subtract from each sample, the lowest value you expect to see; the difference will fit in 1 byte, doubling your storage capability. Don't forget to add back that lowest value to each one when you print them, though.
It would also be a good idea to test each sample against that lowest number and the lowest + 255, and if any sample is outside those limits, store the low or high limit value instead. Then when you plot your data,
you'll see it "clipping" and know that it exceeded your bounds. Otherwise you'll get overflows in the arithmetic and the out-of-bounds numbers will appear to suddenly take on high values when they really are low, and vice versa.

Thanks! So I could just use 50ms + 15.6 for the sampling rate, ignoring analogRead?

A single call to analogRead() typically takes anywhere between 106.4 and 114.5 µs depending on the phase of the ADC clock prescaler at the time of the call. It can take up to 120.4 µs if it gets interrupted by the timer 0 overflow ISR.

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


text:
I2C communication between 2 Arduinos with updated wire library
I would like to enable communication between two Arduino 101. From what I have read, the best method is to use I2C using the wire library. However, it seems as though the newest Arduino IDE has an updated version of the Wire library that no longer includes the begin(int) and onRequest functions.
All of the tutorials for I2C communication use these methods, so I am unable to follow and use them. It looks like when I change the board to Arduino Uno these functions are found, but as soon as I change the board to Arduino 101 the following errors appear no matching function for call to TwoWire::begin(int).
When I try replacing my wire library with the older version, I get other errors for missing libraries and if I replace everything it is unable to compile on Arduino 101.
Can someone please help me or direct me to a I2C tutorial that uses the most updated version of the Wire library?

The problem I see is the Arduino 101 uses an Intel microprocessor (Curie) instead of an Atmel microprocessor.
The only information I could find is on the Arduino page for the 101, which mentions it has dedicated pins for I2C, but it also says that you can use the Wire library. Maybe you just need to update your IDE?
I'd help more, but I can't seem to find any useful information on the Curie...

Although I did not manage to get wire communication to work, I was able to get the Arduinos to communicate through serial port. You just need to ensure to use Serial1 rather than Serial.


text:
Increase the resistance of a photoresistor with increase in light intensity
I'm building a laser tripwire of sorts and instead of shutting up when the laser points on it (which is essential for my project) it beeps louder.
Here's the code
int buzzPin = 11; // buzzer connected to digital pin 11

void setup() {
    pinMode(buzzPin, OUTPUT); // sets the digital pin as output
}

void loop(){
    if(analogRead(0) < 750){ // this number depends on calibration of the photocell
        digitalWrite(buzzPin, HIGH); // turns buzzer on
        delay(5000); // waits for 1 second
        digitalWrite(buzzPin, LOW); // turns buzzer off
    } else{
        digitalWrite(buzzPin, LOW);
    }
}

You can't. That's not how physics works. Ask how to do what you're really trying to do instead.

Just reverse the logic in the code.  'if (analogRead(0) < 750)' turns into 'if(analogRead(0) > 750)'

Arduino can not measure resistance. It can measure voltage.
To measure resistance you can convert resistance to voltage using a voltage divider.
In Arduino world a voltage divider consists out of 2 resistors in series between 5V and gnd. The connection to the 2 resistors is connected to a analogue pin.
Depending whether your LDR is connected to gnd or 5V the measured value on the analogue pin will go up or down with the resistance of the LDR.
In other words swap the resistor and your LDR from position.

Just invert it in software. Instead of analogRead(0) use (1023-analogRead(0)).

You could change your circuit or just change analogRead(0) < 750 to analogRead(0) > 750.


text:
changing from long to bytes and vice versa
I want to converse data from long to bytes and vice versa. After searching around, I sticked together some code, which seems to work (the same code works for int and floats as well).
The long value LongVal changes to a byte array, and the four bytes construct LongVal2. Obviously LongVal = LongVal2.
long LongVal = -4080;
long LongVal2;

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

//byte* my_function(long LongVal){
//  byte *LongVal_byte = (byte *) & LongVal;
//  return & (LongVal_byte[0]);
//}

//long my_function2(byte & LongVal_byte){
//  long LongVal2;
//  memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
//  return  LongVal2;
//}

void loop(){

  byte *LongVal_byte = (byte *) & LongVal;
  memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
  Serial.println(LongVal2);
  Serial.println(" ");

//byte LongVal_byte = my_function(long LongVal);
//LongVal2 = my_function2(byte & LongVal_byte);

}

But should I try to wrap the two first lines of loop() in two individual functions, errors occur. The remarked lines are my attempts to create two functions.
How to wrap them up properly?
EDIT
This is what appears if I try to use the remarked functions:
 In function 'long int my_function2(byte&)':
15:51: error: invalid conversion from 'byte {aka unsigned char}' to 'const void*' [-fpermissive]
25:0,
1:
117:14: error:   initializing argument 2 of 'void* memcpy(void*, const void*, size_t)' [-fpermissive]

 In function 'void loop()':
26:33: error: expected primary-expression before 'long'
27:30: error: expected primary-expression before '&' token

And what do the "errors" say? Hint: they tell you what is wrong - they're not just printed for fun. Read them. They are generally self explanatory.

@ Majenko That is true, but due to my inexperience to C, I lack to interpreter  them.

But we can. Or we could if you told us what they were. By the way, I can already see some fundamental misunderstandings and mistakes in your code. I want to marry those up with the error messages you are getting so that you can understand the errors better in the future.

@ Majenko I just added the error comments.

So many problems here:
1) in function call there shouldn't be types, only arguments. byte LongVal_byte = my_function(LongVal);
2) & before variable means "get variable address". However in function prototype long my_function2(byte & LongVal_byte) it means reference to passed variable (and it must be byte), not a pointer.
3) pointer to local variable is returned from my_function. It might be working until pointed memory gets rewrited by something else (another function call or so)
And whole code might look like that:
long LongVal = -4080;
long LongVal2;

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

byte * my_function(long & LongVal) {
  return (byte*)&LongVal;
}

long my_function2(byte * LongVal_byte) {
  return *((long *)LongVal_byte);
}

void loop(){

  byte * LongVal_byte = my_function(LongVal);
  LongVal2 = my_function2(LongVal_byte);

  Serial.println(LongVal2);
  Serial.println(" ");
}

But it is basically exactly the same as before without functions (just no need for memcpy)

@ KIIV It works flawlessly, and even more, it works with every type of variables, (int, floats, even strings), providing that I set in the code the right type of variable.

15:51: error: invalid conversion from 'byte {aka unsigned char}' to 'const void*' [-fpermissive]

memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));

LongVal_byte is a single byte. It's not a pointer, and memcpy expects a pointer.

26:33: error: expected primary-expression before 'long'

byte LongVal_byte = my_function(long LongVal);

You do not specify the variable type when passing a variable to a function. The variable already knows what it is, and the function already knows what it wants.

27:30: error: expected primary-expression before '&' token

LongVal2 = my_function2(byte & LongVal_byte);

Same there.
You are showing a fundamental lack of understanding of some concepts of C.  Other errors you are making:
long LongVal2;
...
long my_function2(byte & LongVal_byte){
    long LongVal2;

You should never ever re-define a global variable inside a function. It's not actually syntactically incorrect, but from a reading perspective it becomes almost impossible to keep track of which LongVal2 variable is being used at any one time.
long my_function2(byte & LongVal_byte){

You are passing a reference to a single byte, not an array of bytes. For that you need a pointer.
You should re-write your functions to be like this:
byte* my_function(long LongVal) {
    return (byte *)&LongVal;
}

(although that is completely pointless, you just need to cast the value, you don't need a function to do it:
byte *byteval = (byte *)&LongVal;

)
long my_function2(byte *LongVal_byte){
    long LongVal2;
    memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
    return LongVal2;
}

That is a long winded, but "safe" way of doing it. It is needed only on CPUs where alignment matters.  On an 8-bit CPU the alignment is 8-bit, and so a 32-bit word can be at any address.  On a 32-bit system a 32-bit word will be at a 4-byte alignment, so that method is needed.  On an 8-bit though you can just cast the array into a long:
long *LongValue = (long *)&LongVal_byte;

A better solution to the whole thing, though, is to use a union:
typedef union {
    byte byteval[4];
    long longval;
} LongBytes;

LongBytes myVal;

You can then access:
myVal.longval = 4893723284;

And also:
myVal.byteval[i];

where i is 0-3.

@ Majenko Your comments were quite thorough and useful. Thank you for your interest.


text:
Force compiler to execute instructions sequentially?
Is there a way to force the Arduino compiler to compile individual commands sequentially?  Looking at the disassembly, lines of the assembly code for different C/Arduino commands are mixed.  I was thinking something like a dmb or dsb command in ARM assembly.  I realize it's done the way it is for timing optimization, but I would like to see if changing it fixes some other timing issues I'm having.  I'm working on an Arduino Zero.  Thanks!

You can use the optimize function attribute to change the compiler optimization level for an individual function. That's the closest you'll get.

optimize
The optimize attribute is used to specify that a function is to be compiled with different optimization options than specified on the command line. Arguments can either be numbers or strings. Numbers are assumed to be an optimization level. Strings that begin with O are assumed to be an optimization option, while other options are assumed to be used with a -f prefix. You can also use the #pragma GCC optimize pragma to set the optimization options that affect more than one function. See Function Specific Option Pragmas, for details about the #pragma GCC optimize pragma.
This attribute should be used for debugging purposes only. It is not suitable in production code.

E.g.,:
void __attribute__((optimize("O0"))) myFunction() {
    // ...
}

From what I saw, the default optimization option is -O0, which is also the lowest level of optimization.  Is that correct?  I didn't see one but I want to make sure, is there an option to disable this kind of timing optimization?

No. Simply because there isn't really a 1:1 relationship between C code and Assembly code. If you want specific instructions in a specific order you will have to write assembly code directly. However, instruction ordering is highly unlikely to be the cause of some unspecified errors you may be having. I suspect you are suffering from an XY Problem and need to step back and look at the problem, not your (probably incorrect) assumption about the cause.


text:
Send values to a PHP page using Arduino ESP8266
I still a noob, and I'm learning Arduino. I built a PHP page to send values using GET parameters.
I would like to send a specific value from Arduino to that PHP page. I bought an ESP8266, and I would like to see it working.
I found this code and I made some changes there, but the the code is not working. I don't receive any value on my database. Can you guys help me?
#include <SoftwareSerial.h>

SoftwareSerial esp8266(10, 11);
String cmd;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Started");
  // set the data rate for the SoftwareSerial port
  esp8266.begin(115200);
  esp8266.write("AT\r\n");
}

void loop() {
  if (esp8266.available()) {
    Serial.write(esp8266.read());
    teste();
  }
  if (Serial.available()) {
    esp8266.write(Serial.read());
  }
}

void teste(){
  // Connect to the server
  esp8266.write("AT+CIPSTART=\"TCP\",\"http://bubu.esy.es\",80\r\n");
  //make this command: AT+CPISTART="TCP","192.168.88.35",80
  //wait a little while for 'Linked'
  delay(300);

  //This is our HTTP GET Request change to the page and server you want to load.
  cmd = "GET /teste.php?test=5 HTTP/1.0\r\n";
  cmd += "Host: http://bubu.esy.es\r\n\r\n";
  //The ESP8266 needs to know the size of the GET request
  esp8266.write("AT+CIPSEND=");
  esp8266.write(cmd.length());
  esp8266.write("\r\n");
  esp8266.write("GET /teste.php?test=5 HTTP/1.0\r\nHost: http://bubu.esy.es\r\n\r\n");
  esp8266.write("AT+CIPCLOSE\r\n");
}

Maybe you should tell the ESP8266 to connect to your WiFi access point. You have about 10% of the required code there.

teste.php?test=5 - does this works (writes to DB) when opened by browser?

Host: http://bubu.esy.es needs to be Host: bubu.esy.es.

Why build up cmd and then write the string out rather than cmd??  i.e. esp8266.write("GET /teste.php?test=5 HTTP/1.0\r\nHost: http://bubu.esy.es\r\n\r\n"); should be esp8266.write(cmd);


text:
Can anyone help me spot where my buffer overflow might be occuring?
I'm using dtostrf() to transcribe a float into a string for my touchscreen. I'd leave it as a float, but my screen orientation library function only works with a string.
So I have a char array, then a float value. then dtostrf().
char buffer[6]
float X; //changes each loop with incoming sensor data from pixy camera
float thingposition = X * .0064  //float calculations are performed.

void loop(){
Camera.Get_X();   //retrieves X from the camera. waits until X has been recieved via UART serial
dtostrf(buffer, 5, 2, thingposition) // writes float to string with a controled decimal place and all that - dtostrf(floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, charBuf);
Tft.drawString(buffer, 70, 215, 5, WHITE);   //print output to screen
}

Note that this is a simplified version. In my code I also have methods for overwriting my last string value on the LCD when the new one has changed.
I also have several "if" conditionals that control whether I write the buffer value to the screen or instead send an error message. Those things do not seem to be causing me problems though, except to say that my buffer overflows only occur when I cause the sensors to flip the conditionals at just the right interval.
For example, when I place my hand in front of the camera, that triggers the error message. Take my hand away, and then the number "thingposition" is printed to the screen. But if I time my hand just right, the buffer overflows and numbers loop across the screen. Usually this freezes the whole sketch. The best I can figure is that since dtostrf() does not check bounds, and since the calculated float values can be longer than the buffer has room for, that sometimes dtostrf() tries to write too many digits to the buffer. Something timing-related seems to trigger the problem, but what I need is some way to prevent the overflow in the first place.
I've tried rounding "thingposition" to a certain number of sigfigs, but I can't seem to truncate it at the desired decimal point. That shouldn't matter though, since dtostrf has controls for the minimum total length including the decimal point, as well the number of digits after the decimal. I also tried making sure that the last byte in my char array is null by adding this right after dtostrf():
stringval[5] = NULL;   //make sure buffer is null-terminated to prevent buffer overflow

I've tried doubles, different ways of rounding, and anything I could find, but the problem has persisted for several weeks and a few steady days worth of searching for a solution. I'll be glad to provide further information if anyone has any ideas on what to try. Thanks everyone.

If thingposition is 100000 or more, then dtostrf() will use more than 5 characters to represent the number. It will use no more than 2 decimal digits (less if they won't fit in 5 characters), but it won't compromise the main number to fit it inside your buffer. If you don't want that, clip the number to less than 100000

The problem with using "simplified code" is that your 'simplification' may not have captured your problem. But I will take your code as given and assume that it's correct (which I'm afraid it isn't).
var
    char buffer[6]  // Won't compile - no semicolon (';')
    float X;        // Uninitialised value - could be 1000000000000
    float thingposition = X * .0064 // No ';', and .0064 of 10000000000 is huge!

void loop(){
    Camera.Get_X(); // Should this be "X = Camera.Get_X();" ?
    dtostrf(buffer, 5, 2, thingposition)  // No ';'. You NEED to recalculate thingposition!

If the above code is a good representation of what you've got, you seem to be assuming that you define the formula once (in the thingposition line), and it automatically applies that formula, like Excel, when you change its input, X. Sorry, programs don't work that way.
Once you calculate thingposition, it becomes independent of where it came from. If you change other variables, thingposition kees its value until you explicitly change it.
How do you fix it? You recalculate thingposition every time:
var
    char buffer[6];      // Hopefully big enough - see below
    float X;             // Used by Camera.Get_X()
    float thingposition;

void loop(){
    X = Camera.Get_X();        // Get X from Camera
    thingposition = X * .0064; // Calculate thingposition
    dtostrf(buffer, 5, 2, thingposition);

Note that dtostrf() will try to obey your size parameters, BUT. If the float is larger than your maximum size, it WILL print out the full number anyway. That is, if thingposition is 1000, it will produce 5 characters all right: "1000.". But if it's 1000000, it will produce "1000000" which is seven characters. You need to ensure that buffer is big enough to handle larger numbers than you expect.
Do the maths. If X is guaranteed to be between 0 and 255, then multiplying it by 0.0064 will result in a maximum value of 1.632, so the above dtostrf() woud produce " 1.63". No problem!

I'm interested in your comments on dtostrf() and buffer size. Not much of the other stuff applies, because of course I calculate at every loop. Apologies for not including everything, but I didn't want to take up all your time and bore you. Also it's proprietary. I didn't think much of laying out the whole thing because I had assumed anyone would overlook all that and focus on the buffer, assuming all else is functional.

My floats are almost always guaranteed to be a little longer than the buffer after the calculation is performed. I'd like to cut them off at the appropriate digit after rounding if I could because I think that would solve the problem. dtostrf() seems to handle it well... until it doesn't.

And there's your problem. dtostrf() won't "lie" in its output. Rounding's OK, but truncating orders of magnitude? Like I said: either increase the buffer size going into dtostrf(), or be explicit and truncate the number first: do a thingposition = fmod(thingposition, 100000); to knock off the hundred-thousands-and-above digits that won't fit. Then the onus is on you rather than the function!

I'm a little confused. You said that dtostrf() would produce "1.63" from     1.632. But you also are saying that dtostrf() can't lie to adjust its output. Is that a contradiction? And I'm not sure what you mean by "truncating orders of magnitude". the float value 1.63 is the same magnitude as 1.632, it's just been reduced an order of precision. Also, the function fmod() does not seem to work for truncating ending digits, and I can't find a function that does. In fact, your example seems to add more digits.
`Serial.println(fmod(x, 100000),24);`

output: `9.123456954956054687500000`

That is, if x = 9.123456789

I said "dtostrf() won't lie in its output". By "lie" I meant outputting "21.01" if the number was 987654321.012345 - which some people expect when they ask for ",5,2". I went on to say that rounding's OK, since that's (one of) its jobs. I then went on to say that if you wanted to print out "21.01" for that large number, you needed to chop off the higher digits yourself, which is what fmod() does - fmod(f, 100); If you're having decimal rounding problems, you have yet to state what you're getting versus what you expect...


text:
Relay for controlling a water pump motor
I want to switch on and off a motor with arduino, used for pumping water. I need to have a idea which relay could be used with arduino.
Here is a photo of a similar motor:

In this case an image does not tell a thousand words. In order to get a proper answer, we need to know the specifics of this pump. Voltage? Amperage? AC / DC? How does it work? Perhaps a datasheet?

You need a relay that can handle the amount of current the motor uses. So check the Amps ratings of the motor and of the relay.

@Gerben it must handle Starting current. I think some small opto-isolated relay module and big contactor would be the best.

A relay must also be spec'ed for the voltage it will be switching, to prevent arcing and burning its contacts when they make and break.

Fairly cheap and quite reliable relays which operate at 5V (5mA to switch closed/open) can be had at a decent price. Mine have an upper limit of 10A, either 250VAC or 30VDC.


text:
Controlling 4 motors using the Arduino Uno
I've decided to make a quadcopter but since I'm a rookie, i decided against doing it from scratch. I'm planning to order this kit, first understand the dynamics and then try and make a quadcopter on my own using the components in it.
My first question are

Can I control the 4 motors using 2 H-bridges (L293D)?
Are ESC's necessary if I use the PWM pins?

Thanks in advance!

I don't think this is Uno related. I think everything the copter needs is already in the kit.

I want to make a copter on my own, with the Arduino, not with this kit.

Alright, didn't read correctly. I don't know about ECS as I don't know what it is. About the h-bridge, as far as I know you need 1 per motor.

I have used 1 L293D to control 2 motors before @Len

That's because the L293D has four half H-bridges, so 2 H-bridges in total.

So then they should be sufficient?

For 2 motors, 1 L293D is enough. For 4 motors, you need two L293D.

Beware - the L293D isn't a very high current driver. You should first check what voltage and current that kind of motor needs to work properly. (Over an amp per motor - 2 amps per L293 chip - might be too much for it.)

Can I control the 4 motors using 2 H-bridges (L293D)?

Yes. Two per chip.

Are ESC's necessary if I use the PWM pins?

There is one thing you must understand first: there are two kinds of DC motor - Brushed and Brushless.
The Brushed motor is the "normal" kind - you apply power to it and it spins.  These you control with the likes of an L293D and use PWM to control the speed.
Brushless motors are the kind you have in hard drives and the like. They consist of a number of coils that get turned on and off at the right time to pull a magnet around in a circle (to put it crudely). These require special timing and control to get the coils energised at the right time and in the right way. This is what an ESC is for.
Brushless motors are smaller and lighter for the same power than brushed ones. They also have a longer life. Because of this they are generally preferred to brushed motors on quadcopters.
Brushed motors have a very high starting torque, don't require complex control logic and use less energy when not running full speed.
If you use brushless motors, which ideally you should (though I can't tell what kind of motors those are in that kit) then you must either use an ESC or build your own ESC using an Arduino and multiple motor driver circuits. Simplest to use an ESC.
If you don't use brushless motors then an ESC is not what you want to use - just the L293D chips and PWM.

Thank you for the answer. The motors in the kit are coreless motors

I saw that. I don't quite know what that means. It looks like they have 2 wires, which makes me assume they are probably brushed.

To be clear (because I was going to answer "No, you can't"), you need 4 H bridges to control the 4 motors on a quadcopter.  It just so happens each L293D already had 2 H bridges so you only need two L293D chips to get the jobs done.  Right?

That is correct.

A coreless motor is, by the look of things, a brushed motor.

I fully agree with the answer of Majenko but I think something is missing in the explanation.
When you say "I want to control a motor" then it is not yet clear what is needed.
There are the following options
1) on/off in one direction (forward).
2) on/off in 2 directions (forward and backwards).
3) on/off in on direction with speed control.
4) on/off in two directions with speed control.
For a brushed dc motor this can be achieved with.
1) a single pole single throw relay (this is similar to a on of switch)
2) a single pole single throw relay and a double pole double throw relays (this is a on off switch and a switch to change the wires to the motor)
3) a mosfet (this is similar to a single pole single throw switch that can go on/off very fast)
4) a H bridge. That is 4 mosfets that are controlled in a certain way.
Now here comes the trick: H bridges often come in 2 half H-bridges. And with a half H-bridge you can control a motor at level 3.
In other words ... with a chip that has 4 half H bridges (an as such 2 H- bridges) you can control 4 brushed DC motors at the level 3 (forward speed controlled) or 2 brushed DC motors at the level 2 (back and forward speed controlled).

I'm planning to use an Adafruit Shield, to control a quadcopter.

This board comes with support to control 4 brushed dc motors in 2 directions. because of the latch chip and a control library you can not control the separate half bridges (easily?).

I'm sorry, but I didn't get get you @jantje

@souvik because of the hardware you selected everything is available for 4 brushed dc motors controlled in 2 directions and with speed. You can not control 8 motors on level 3. But you don't care.

You also need to consider the current needed by your motors (they are DC brushed indeed) and the power/energy you will lose in your driver.
If you use a 3.7V power supply like provided, and the L293D "eats" 1.2V out of it, you lose nearly one third of your energy. See https://electronics.stackexchange.com/questions/108686/what-h-bridge-drivers-are-preferred-for-applications-controlling-a-low-voltage-m for an very interesting review of drivers.
If I can believe that, it looks like DRV883x is the only reasonable choice. It even allows you to use one cell (3.7V) for the logic and 2 cells (7.4V) or more for the motors. But don't do that with the motors you've got, you'd probably burn them.
Unfortunately the other ST or Allegro devices also covered in the article all need more voltage to work.
Regarding the Arduino, a UNO can't be recommended, too heavy, 5V only, power hungry etc. It won't fly. I'd recommend you use a pro mini 3V3 with some LDO power supply such as the TPS73633. Be careful that most LDO regulators (like 1117) have a too high dropout voltage to be used with a 3.7V input, more than 1V.
I'm not affiliated with TI at all, it just happens that when looking for "the right chip for the right job", I keep having to eliminate the others because of data sheet numbers.
On the SW part however, it becomes difficult to find SW for the 328P. Most addicts have moved to 32-bit CPUs. But that's another debate.


text:
Programming an Arduino Mini 05
So, I recently bought an Arduino Mini (5V, 16MHz), and a USB to Serial Converter.
Provided are the links to both the products:
Arduino Mini,
USB to Serial Converter
Now, I tried programming the mini by connecting the pins in this order:
Rx -> tx, tx-> rx, VCC -> 5V, GND -> GND, DTR -> DTR
The computer detected the USB to Serial converter after I installed the drivers manually. However, the Arduino IDE failed to program the Arduino Mini every single time, even after I swapped the TX, RX pins.
I tried to program the Arduino Mini using an Arduino Uno (I removed the onboard Atmel Atmega microcontroller on the Uno before programming). I connected the pins in this order: TX->TX, RX->RX, 5V-> VCC, GND-> GND, RST -> DTR. From the IDE, I chose Arduino Pro Mini (5V, 16Mhz).
The Mini was programmed successfully this time.
My question: What was wrong with the USB to Serial converter? Why couldn't it program the Arduino Mini with the USB to Serial Converter?

GND -> 5V; I hope that is a typo?

To test the converter, try connecting the TX on the serial converter to the RX of the same converter. Then in the Arduino IDE open the Serial Console. If you send some text, you should receive the same text back.

I did as you said.. It works.. The converter sends the same text back once I send something... But it still can't program the Mini.

I had a problem with a USB to Serial convertor.  It was because the device I had had a dodgy Chinese clone chip and the real manufacturer changed the driver so it wouldn't work properly unless it was a genuine chip.  You can hack the driver inf file to get round it, but I can't remember the details.

The chip on this USB to Serial converter is an Atmel Atmega 8A PU..

Maybe you need to manually reset the board, for programming.

I tried. doesn't work

Are you using windows 7? 32bit or 64bit?

As you have said the Arduino Mini seems to be fine and the USB to Serial Converter seems to be working too.
This might be a crazy idea but this might work
try connecting the boards like this,
TX -> TX  and  RX -> RX
I'm not totally sure, but this might work.

Try to reset manually just after compiling end

I tried.. it doesn't work.... I held the reset button down but the converter still won't program the Mini.... The Mini was programmed using the Arduino Uno successfully btw... It's the converter that is not behaving properly...

It's too late but don't hold the button. Just press once quickly, immediately while compiling going near %100

The Mini was programmed successfully this time

If so, one of them had its tx/rx pins mislabeled.


text:
Arduino Due SRAM
I'm trying to create an array in Arduino Due and when the
array exceeds the size of 32768 integer elements
the compiler (Atmel Studio) complains.
I read that Arduino Due SRAM size is 96K in 2 banks. 64Kb and 32Kb.
Anyone knows any details?

Size of int in arduino due is 4Bytes. If you're trying to create array of 32768 integers, it means you need 128kB of free space.

I've read in several places that e.g. PROGMEM const int foo[] = { 1, 2, 3, ... } would work, but was unable to do it in my environment ( debian, arduino-mk package ). I had a number of arrays I needed to commit to flash to conserve sram. This worked fine for all variables, but not for arrays. Try that... What say the wizards?
Note to moderators and others: I know I am not answering the question definitively, but it is relevant to OP's question.

On ARM chips, like all Princeton architecture chips, you don't need to do fancy things with PROGMEM - just make them const.

So it's completely unnecessary? How awesome is that ;)

PROGMEM is used to lock const data into flash and prevent CRT0 from copying it into RAM. On ARM it doesn't need to copy it into RAM because it can directly access it without special register instructions, so the PROGMEM isn't needed.


text:
motor does not move without Serial.println
having strange behavior with motor shield and steppers. when i'm trying to make onestep, motor just makes some high-frequent noise, but when i add Serial.println for debugging, it moves as intended.
what is going on here?
here is an example:

#include AFMotor.h //dunno how to put angle brackets here

AF_Stepper lrM(48, 1);

void rightStep() {
  lrM.onestep(BACKWARD, INTERLEAVE);
}
void leftStep() {
  lrM.onestep(FORWARD, INTERLEAVE);
}

void setup() {
  Serial.begin(9600);
  Serial.println("ready");
}

void loop() {
  rightStep();
//Serial.println("right");
}

We need Minimal, Complete, and Verifiable example

ok. i've added one, but it is very common usage

My guess is Serial.println adds additional delay so stepper motor can react. Without it changes are way too fast (= high frequency noise) to do whole step.
Try to add delay(1); or more into the main loop.

i thought that if onestep function is blocking, it would be ok, but it appeared that i need delay(10) so that motor can run. thank you!

Method step contains delays, but there are no delays in onestep (at least not obvious ones).

When you have a Serial print statement running really quickly the output buffer will fill up and the print command will have to wait for there to be room; That causes the command to take a substantial amount of time to complete.
When the statement is missing, you loop probably runs a few hundred times faster than without it (depending on how long onestep takes), probably fast enough that the physical motor can not keep up.
Try adding a delay of a few milliseconds or some kind of rate limiting to the program and then see how much of a difference serial.println makes.


text:
Burn arduino bootloader using ubuntu 16
I get the following error when I try to burn the arduino bootloader on an atmega328 mcu:
avrdude: verification error, first mismatch at byte 0x0000
         0xfd != 0x05

I am using an Arduino as ISP programmer. My computer runs Ubuntu 16.
This did not happen when I was using Ubuntu 14. I also tested it on another machine with Ubuntu 14 and this error does not appear. Seems to be something with Ubuntu 16. I installed Arduino IDE using the out of the box repo.
The avrdude command launched by the IDE is:
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -cstk500v1 -P/dev/ttyUSB0 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0x05:m -Uhfuse:w:0xde:m -Ulfuse:w:0xff:m

Am I safe replacing the -Uefuse:w:0x05:m with -Uefuse:w:0xfd:m ?? If answer is yes how can I get the IDE to do this correctly?
Uploading a sketch works pretty well.

This is not a real answer.
I have the same problem on Os X, but I can upload sketch via "upload using programmer", but this way I have no bootloader.
Problem arises only when trying to install boot loader.
I didn't have this problem some years ago on Linux Debian.
I your problem is solved, please let us know.

There is no functional differences between an efuse setting of 0x05 and 0xfd, as only the three lowest bits actually exist.  Your actual problem is elsewhere.

I had same problem and I think I have solved it.
In boards.txt file, I had:
##############################################################

diecimila.name=Arduino Duemilanove or Diecimila

diecimila.upload.tool=avrdude diecimila.upload.protocol=arduino

diecimila.bootloader.tool=avrdude diecimila.bootloader.low_fuses=0xFF
diecimila.bootloader.unlock_bits=0x3F
diecimila.bootloader.lock_bits=0x0F

diecimila.build.f_cpu=16000000L diecimila.build.board=AVR_DUEMILANOVE
diecimila.build.core=arduino diecimila.build.variant=standard

## Arduino Duemilanove or Diecimila w/ ATmega328
## --------------------------------------------- diecimila.menu.cpu.atmega328=ATmega328

diecimila.menu.cpu.atmega328.upload.maximum_size=30720
diecimila.menu.cpu.atmega328.upload.maximum_data_size=2048
diecimila.menu.cpu.atmega328.upload.speed=57600

diecimila.menu.cpu.atmega328.bootloader.high_fuses=0xDA
diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0x05
 diecimila.menu.cpu.atmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

diecimila.menu.cpu.atmega328.build.mcu=atmega328p

## Arduino Duemilanove or Diecimila w/ ATmega168
## --------------------------------------------- diecimila.menu.cpu.atmega168=ATmega168

diecimila.menu.cpu.atmega168.upload.maximum_size=14336
diecimila.menu.cpu.atmega168.upload.maximum_data_size=1024
diecimila.menu.cpu.atmega168.upload.speed=19200

diecimila.menu.cpu.atmega168.bootloader.high_fuses=0xdd
diecimila.menu.cpu.atmega168.bootloader.extended_fuses=0x00
 diecimila.menu.cpu.atmega168.bootloader.file=atmega/ATmegaBOOT_168_diecimila.hex

diecimila.menu.cpu.atmega168.build.mcu=atmega168

##############################################################

I have replaced the line containing:
diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0x05

with:
diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0xFD

Everything is ok now.
I can install boot loader on an ATMEGA328P (with an usbasp programmer), and I can install sketchs after that (via usb serial).
I don't know if it's the best way to solve the problem, but it works.
Hope this will help you, if not already solved.

As there are only 3 bits in the extended fuses of an ATmega328p, 0x05 and 0xFD are actually the same value as far as the bits that exist.  Different ways of handling the non-existent bits account for on the only difference, which is irrelevant.


text:
why am I losing data over serial communication between arduino and pc
I'm working on a project for school. I'm trying to rotate a servo by writing the letter that identify the servo and then the angle.
the problem is that sometimes the last number of the angle is lost or the whole angle all together. for example i want to rotate servo "a" 50 degrees. i enter a50 this works most of the time but sometimes i only get a 5 without the zero and sometimes i just get a zero. can anyone help, thanks.
please keep in mind i only did computer science in high school and intro to c++ in college. go easy on me please.
attached is the code and an image illustrating my problem.
#include <Servo.h>

Servo servo1;
Servo servo2;
Servo servo3;

String angle1="";
String angle2="";

char serialbuffer[4];
int index=0;
int charcount=0;

int lastangle;
int dif;

void setup() {
  servo3.attach(3);  // attaches the servo on pin 9 to the servo object

  Serial.begin(9600);

  serialbuffer[0]='0';
  serialbuffer[1]='0';
  serialbuffer[2]='0';
  serialbuffer[3]='0';
}

void loop() {

       charcount=0;
       index=0;
       serialbuffer[0]=99;

   while (Serial.available() > 0) {

      char charbuffer = Serial.read();
       if(charbuffer=='\n'){
          index=0;
        }
        else{

           serialbuffer[index]=charbuffer;
           index++;
           charcount++;
          }

      }

  angle1="";
  if(serialbuffer[0]=='a'){

      for(int i=1;i<charcount;i++){
         angle1+=serialbuffer[i];
      }
      move_servo3(angle1);
      index=0;
      serialbuffer[0]=99;
    }
  delay(15);
}

void move_servo3(String angle2){

   Serial.println(angle2.toInt());
   servo3.write(angle2.toInt());

  }

Are you hand-typing the commands? It is pretty difficult to do that consistently. I ask because your code collects data from the serial buffer until the buffer is empty - i.e. when you pause even slightly in your typing - and tries to act on whatever it has collected so far. That may be (probably will be!) an incomplete command. Even if your terminal uses line-by-line entry, there is still the risk that your code could notice an empty buffer between characters within a line.
Try collecting characters until it sees a newline, instead. That is probably what you intended, and it will be immune to your typing speed. You'll still need to test for .available, but that should only allow the code to collect more characters. Keep collecting until it sees a newline.
What (I think) is happening now is called a race-condition. That means that the program's behavior is dependent on which of two (or more) events happens first, and the order of their occurrence is indeterminate. Race conditions are especially hard to find when the order of two events is almost always the one you expected. Notice the "gotcha" word in that sentence? :)

thanks for your answer. for future viewers, i ended up adding a last latter to determine the end of the message and then sending the whole thing to the servo.

I don't understand why the problem is being caused, your code looks OK, but this is too big for a comment.

I think it would be better if you initialised you serialbuffer with NULL rather than '0'.  This way angle2.ToInt() will just read the number you have typed, rather than what was in there last time.  Try entering a111 and then a2.  You will get a211 second time.  NULL is the end of a string.
In loop() change your while loop to this:
char charBuffer = Serial.read();
while (charBuffer != '\n' && index < 4) // Index < 4 stops a buffer overflow.
{
  serialbuffer[index++] = charBuffer;
  charCount++;
  charBuffer = Serial.read();
}

This will keep reading until it sees a new line, which I think is what you want.

You don't need the delay statement now, the speed is controlled by
how fast you can type.
The for statement could be changed to:
for (int i = 0; i < 4 && serialbuffer[i] != NULL; ++i)

If you make these changes I think it might help see the problem.  Also printing the number that has been typed in before the for loop might help, it will print now because you have initialised it to NULL.


text:
Change max and min read value of potentiometer
I'd like to know if there is a function or some way to define min and max value to potentiometer, for example: I'm using a mechanical part that only tour the potentiometer a little bit, what means the potentiometer doesn't start in the beginning and doesn't finish in the end. So, how can I make this space the potentiometer tour means 0 to 255 the start to end, respectively?

You cannot declare that the min and max values of a potentiometer are x and y. What you can do is map() the values of the potentiometer to your own desired scale.
To do this, you'll have to get the following values:

Minimum value of the potentiometer, pMin
Maximum value of the potentiometer, pMax

But these values aren't what you want. For example, what you want is pmin to be 0 and pMax to be 100. So, you'll have to scale pMin and pMax to those values.
For this, you use the map() function. What map() does is changing the value in a given scale, to that of another scale. Let's get some example code:
int pMin = 14;  //the lowest value that comes out of the potentiometer
int pMax = 948; //the highest value that comes out of the potentiometer.

int x = 0;  //we will use this value to store the readings of the potentiometer

void setup(){
  Serial.begin(9600); //Serial monitor can be used to check the values
}

void loop(){

  x = analogRead(A0); //connect the potentiometer to the A0 pin of the Arduino

  Serial.print(x);  //prints the original reading

  x = map(x, pMin, pMax, 0, 100) //take the value of x, compared it to the scale of the potentiometer pMin to pMax, and translate that value to the scale of 0 to 100

  Serial.print("\t"); //a tab to make the reading more easy
  Serial.println(x);  //post mapped value, println is a linebreak as well
  delay(100); //so we don't post to much in the serial and you can read data better.
}

With this example you can clearly see how your potentiometer behaves and how you can use the 'weird' values from its readings in a useful way for your projects.

You can even make it auto-calibrating. In the loop, if (x > pMax) { pmax = x ), and vice versa for pMin. But then the user would have to twiddle the pot every time the device starts, unless you save the min and max to eeprom.

Either use a reference voltage closer to the maximum voltage the potentiometer is capable of, or use map() to map the existing limited range to a larger range. Note that using map() will not improve precision.

If the values from the pot are 0 - 1023 you can divide the number by 4 which would give you a closer range to what you need. The map() function can be used instead.


text:
using millis() for a timer
Basically the user presses a button and cycles thru 3 different modes. Mode 1 the LED is on, mode 2 the LED is off and mode 3 the LED is kept on for a certain amount of time. I'm using the millis() to keep track of the time. the LED in the third mode just stays on and never switches to off. I have the Serial.Writes in there to help me debug. I have the delay after the button read since if I didnt put it in it would register a lot of button presses.
int ledPin = 5;
int buttonApin = 9;
int ledMode = 0;

boolean lastButton = HIGH;
boolean currentAButton = HIGH;

// debounce button
boolean debounceFUNC(boolean last)
{
    boolean current = digitalRead(buttonApin);
    if (last != current)
    {
        delay(5);
        current = digitalRead(buttonApin);
    }
    return current;
}

void setMode(int ledMode)
{
    // turns on led
    if (ledMode == 1)
    {
        digitalWrite(ledPin, HIGH);
    }
    // turns off led
    if (ledMode == 2)
    {
    digitalWrite(ledPin, LOW);
    }
    // timer - turns off after 5000
    if (ledMode == 3)
    {
        long interval = 5000;
        unsigned long cMillis = millis();
        static unsigned long pMillis;

        if (cMillis - pMillis > interval)
        {
        pMillis = cMillis;
        digitalWrite(ledPin, HIGH);
        Serial.println("On");
        Serial.println(interval - cMillis);
        }
        else
        {
        digitalWrite(ledPin, LOW);
        Serial.println("Off");
        }

        }
    }

void setup()
{
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
    pinMode(buttonApin, INPUT_PULLUP);
}

void loop()
{
    // sets led mode
    currentAButton = debounceFUNC(lastButton);
    delay(500);
    if (currentAButton == LOW)
    {
        ledMode++;
        Serial.println(ledMode);
    }
    else if (ledMode > 3)
    {
        ledMode = 0;
    }
    // ledMode function call
    setMode(ledMode);
}

screenshot of the serial monitor.

I can't spot the question here.

The problem is in the logic, basically your statement:
    if (cMillis - pMillis > interval)
    {
       pMillis = cMillis;
       digitalWrite(ledPin, HIGH);
        Serial.println("On");
        Serial.println(interval - cMillis);
    }
    else
    {
       digitalWrite(ledPin, LOW);
       Serial.println("Off");
    }

will always be true, this is as the difference in time, cMillis - pMillis is always greater than interval.
This means that it never enters the else statement to turn off the LED, and thus means the else statement is usually the first thing that rune at ledMode = 3.
What you need to do as the simplest fix is to change your comparison, change > to <, in the is statement:
if (cMillis - pMillis > interval)

to
if (cMillis - pMillis < interval)

this will ensure the LED is always on during the 5000 mS and then as soon as it is greater it will definitely go to the else

There is a problem with your debounce logic. You want to compare the
current button state with the previous state, which is supposed to be
stored in lastButton. But that variable is initialized to true and
then never updated. Your program may work better if you issue
lastButton = currentAButton somewhere.
You can find lots of tutorials on button debouncing, and there are
several methods. The one you are using, which is based on delay(), is
probably the worst: it should work in this simple case, but delay() is
toxic as soon as your Arduino has more than one thing to do. A very
common (and my preferred) method is to just ignore the button for some
“debounce time” after you detect a state change. A debouncer function
can be based on something like:
if (now - last_state_change < DEBOUNCE_TIME)
    return last_state;

Then you have to detect the button presses, which is not the same as the
button being down: you don't want to interpret the down state as a
continuous stream of very fast button presses. Instead, a button press
is the button being down now whereas it was up on the previous read. A
button_press() function could call the debounce() function and then
have something like
bool press = last_state && !state;

This is effectively detecting falling edges of the debounced button. You
can combine the debouncer and the falling-edge detector into a single
function as follows:
bool button_press()
{
    static bool last_state;
    static uint32_t last_state_change;
    uint32_t now = millis();

    // Ignore the button during the debounce time.
    if (now - last_state_change < DEBOUNCE_TIME)
        return false;

    bool state = digitalRead(BUTTON_PIN);
    if (state != last_state) last_state_change = now;
    bool press = last_state && !state;
    last_state = state;
    return press;
}

Next there is the management of the LED states. What you are trying to
implement is called a finite state
machine, sometimes
abbreviated “FSM”. If you search the Web for that term, you will find a
few examples on how to implement it. It canonically revolves around a
switch statement that enumerates all the possible states and tells
what to do in each of those states. Something like
switch (state) {
    case STATE_FOO:
        if (some_condition()) {
            do_some_action();
            state = STATE_BAR;  // switch to the next state
        }
        break;
    case STATE_BAR:
        ...
}

Below is a FSM implementation of your LED logic. Note that you did not
completely specify what should happen when the “timed” state times out:
you could go to a forth “timed out” state, or you could just go back to
the “off” state. In the code below I've taken that last option:
void loop()
{
    static enum { OFF, TIMED, ON } state;
    static uint32_t timed_started;
    uint32_t now = millis();

    // Switch state on button press.
    if (button_press()) switch(state) {
        case OFF:    // -> TIMED
            digitalWrite(LED_PIN, HIGH);
            state = TIMED;
            timed_started = now;
            break;
        case TIMED:  // -> ON
            // LED is lready on.
            state = ON;
            break;
        case ON:     // -> OFF
            digitalWrite(LED_PIN, LOW);
            state = OFF;
            break;
    }

    // Turn off after LED_ON_TIME.
    if (state == TIMED && now - timed_started >= LED_ON_TIME) {
        digitalWrite(LED_PIN, LOW);
        state = OFF;
    }
}

Note that it would have been more “canonical” to have the tests
if (button_press()) inside the switch rather than the other way
around. Then the test for the timeout would also be inside the same big
switch. It's just that it seemed easier to me to write it this way.
For the sake of testability, here are the pieces that would be missing
for having a complete working program:
const int BUTTON_PIN = 9;
const int LED_PIN = LED_BUILTIN;
const uint32_t DEBOUNCE_TIME = 50;
const uint32_t LED_ON_TIME = 5000;

void setup()
{
    pinMode(BUTTON_PIN, INPUT_PULLUP);
    pinMode(LED_PIN, OUTPUT);
}

// button_press() and loop() as above.

Thank you very much. The debounce has been an issue and I really wanted to get away from using the delay function. Thank you for the finite state machine information. I will be looking more into it.


text:
Motion Tracking Using Arduino?
I'm trying to make a human following robot.Tried using ultrasonic sensors to follow a specific person by Having ultrasonic sensor with the person to send echo to the robot,But it didn't workout.
Any way to track a specific person and follow ?
Any sensors/algorithm to track fast moving object(a person but not specific)?

If you are clever with software you may be able to simplify your hardware requirements down to 1 IR ASK transmitter and 1 IR ASK IR receiver.
I mention IR ASK as the transmitter (simply a remote control with a button pushed down) and the receiver are COTS parts.
Consider your robot looking for an IR ASK signal by rotation until one is found.  Then consider your robot traveling in a serpentine path adjusting its average vector along the angle where the IR ASK transmitter is detected.
You might need to create an variable aperture the IR ASK receiver will look through.  This is because most IR ASK receivers have a built in AGC circuit which will abstract you from knowing how strong the signal is.
So, while searching, the aperture will be large allowing the IR ASK receiver a wide field of view.  But once locked on, the aperture should be reduced so that the robot will know in which direction the IR ASK signal is from.

You need the person to emit a signal and the robot to receive it, sounds simple, but it isn't.  What you are trying to do is position fix the transmitter, in the same way as an ATC locates a plane.
The robot will need at least two directional receivers positioned a certain distance apart (depends of frequency and accuracy) to allow the robot to triangulate the transmitter.  The more receivers the more complex the triangulation.  The frequency of the signal you transmit will affect the distance that the robot can be from the person, research Frequency spectrum and transmission distances.  The longer the distance the signal can travel the stronger the signal will be at close range.  You also have to counter reflections and side lobes which will give you inaccurate readings on the transmitter direction.
Once you have dealt with all of that all you need to do is scan for the strongest signal on your frequency, triangulate it and then head towards it.
Whatever sensor you use the theory is the pretty much the same.
Could you tag the person with a GPS receiver and WIFI/BT and get it to transmit its location.  The robot could then consult its GPS and calculate the delta and move accordingly.

considering tracking a person in a supermarket will it do work (Small Area)??


text:
How do you use an Arduino to control a 4 - 20 mA transmitter?
I am using an Arduino Mega to control the speed of an AC pump. This can be done by connecting to the variable frequency drive. Here is a link of the relevant datasheet, pages 66 and 67 relate to what I am doing.
http://www.parker.com/Literature/SSD%20Drives/AC%20Drives/AC650/HA464828U003.pdf
From what I have read and been told already, I should be able to control this using a 4 - 20 mA loop, which is fed into AIN2, as long as I connect the 0V terminal as well?
My question is what is the best way to make a current loop transmitter using an Arduino Mega.
So far the options I have are:

Create a circuit out of discrete components, this would then be controlled using the Megas PWM
Use an IC circuit, I was looking at the AD694JNZ
Use an add on board, I was looking at this one: http://uk.rs-online.com/web/p/products/8828929/?grossPrice=Y&cm_mmc=UK-PLA--google--PLA_UK_EN_Semiconductors-_-Semiconductor_Development_Kits&mkwid=sm9dTYvCc_dc|pcrid|88057061283|pkw||pmt||prd|8828929&gclid=CjwKEAjwk6K8BRDM3aCSkdCtzSQSJAA3Vf38mNs9lZrg2A1AjrVpS3SCubT0AbAr7L8OImUZbfCPzRoCIXjw_wcB

I have a budget for my project so cost is not an issue, however I am running out of time. What would be the easiest method to implement and how?
I have been thinking of using options 2 or 3, however my issues are that this is my first Arduino project. I understand what PWM is but I don't know how I would go about implementing it. I also can't find any tutorials online that demonstrate how to program the MIKROE board using an Arduino.
Thank you in advance for any help :)

I can recommend the Click boards from MikroElektronica (I am the chief engineer porting support for them, and the PIC32-based Clicker development board series, to the chipKIT™ system).
The 4-20mA-T Click board is controlled by the Microchip MCP4921 DAC. This is a common DAC family used in many Arduino projects and there are plenty of libraries around for them (mine is here though it's aimed at the 4822 not the 4921).
Basically you set the DAC output voltage which sets the current output from an XTR116 current loop transmitter.
The XTR116 takes an input of 0 - 4.095v, and provides a convenient 4.095v reference voltage to the MCP4921.

Datasheet for the XTR116
Datasheet for the MCP4921
Manual for the 4-20mA T Click

The whole thing is isolated from your main board through an ADu M1411 to keep everything safe from industrial process noise.

I don't know how I would go about implementing it.

Both option 2/3 require coding - generally simple and doable, even for newbies.
To go down the DAC route, current-feedback DACs are quite common, especially in the good old days. they are ideal here -> make sure your device matches up with the dac in terms of current source vs. current sink.
option 1 is good if you don't like coding. turning a voltage into a current is fairly simple.


text:
12 V 6 A power supply for Arduino
I have 3 motors which work at 12 V 3 A, I have attached a 12 V 6 A power supply and seems to be working fine. However I was wondering if this can also power the Arduino as well.

As that 3A total for the motors. or 3A per motor? If the latter, then you need a 9A power supply, not 6A.

@Majenko only if the OP uses all 3 motors at once, if only two are used at a time 6A will be fine.

If you have 3 motors that use 3Amps combined then you have 3Amps spare and that's more than enough for an Arduino.
I don't understand this part very well but depending on the type of motors you might get noise on the power lines and this might affect you Arduino.  In which case you will need to add in something to smooth the power, which means adding in a capacitor or two and their value depends on the frequency of the noise.  (http://www.valvewizard.co.uk/smoothing.html)
Personally I'd give it a try and see, but there again it wouldn't be the first Arduino I'd fried :)

If I understand correctly, the voltage regulator on the arduino will filter out a lot of this noise.

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


text:
Relay switching problem with ATmega328P + 10 relays
I am trying to switch ON/OFF 10 relays connected to ATmega328P via Bluetooth HC-06 module. The problem I am facing is that when I try to Switch ON more than 3-4 relays, some of the previously ON relays switch OFF and the ATmega328 restarts.
I am using a 12V 2A power supply.
I have set up my circuit as shown below

My code
int r1 = 4, r2 = 5, r3 = 6, r4 = 7, r5 = 8, r6 = 9, r7 = 10, r8 = 11, r9 = 12, r10 = 13;
char state;
String msg;
int r = 0;

void setup()
{

    pinMode(r1, OUTPUT);
    pinMode(r2, OUTPUT);
    pinMode(r3, OUTPUT);
    pinMode(r4, OUTPUT);
    pinMode(r5, OUTPUT);

    pinMode(r6, OUTPUT);
    pinMode(r7, OUTPUT);
    pinMode(r8, OUTPUT);
    pinMode(r9, OUTPUT);
    pinMode(r10, OUTPUT);

    Serial.begin(9600);
}

void loop()
{

    while (Serial.available())
    {
      state = Serial.read();

      if (state == '\n')
        break;

      msg += state;

    }

    if (msg.length() > 0)
    {
      /*Serial.print("Data: ");
      Serial.println(msg);*/

      if (msg == "on1")
      {
          digitalWrite(r1, HIGH);
          Serial.print("O1");
      }
      else if (msg == "on2")
      {
          digitalWrite(r2, HIGH);
          Serial.print("O2");
      }
      else if (msg == "on3")
      {
          digitalWrite(r3, HIGH);
          Serial.print("O3");
      }
      else if (msg == "on4")
      {
          digitalWrite(r4, HIGH);
          Serial.print("O4");
      }
      else if (msg == "on5")
      {
          digitalWrite(r5, HIGH);
          Serial.print("O5");
      }
      else if (msg == "on6")
      {
          digitalWrite(r6, HIGH);
          Serial.print("O6");
      }
      else if (msg == "on7")
      {
          digitalWrite(r7, HIGH);
          Serial.print("O7");
      }
      else if (msg == "on8")
      {
          digitalWrite(r8, HIGH);
          Serial.print("O8");
      }
      else if (msg == "on9")
      {
          digitalWrite(r9, HIGH);
          Serial.print("O9");
      }
      else if (msg == "on10")
      {
          digitalWrite(r10, HIGH);
          Serial.print("O10");
      }

      //off---------------------------------------------------------

      else if (msg == "off1")
      {
          digitalWrite(r1, LOW);
          Serial.print("F1");
      }
      else if (msg == "off2")
      {
          digitalWrite(r2, LOW);
          Serial.print("F2");
      }
      else if (msg == "off3")
      {
          digitalWrite(r3, LOW);
          Serial.print("F3");
      }
      else if (msg == "off4")
      {
          digitalWrite(r4, LOW);
          Serial.print("F4");
      }
      else if (msg == "off")
      {
          digitalWrite(r5, LOW);
          Serial.print("F5");
      }
      else if (msg == "off6")
      {
          digitalWrite(r6, LOW);
          Serial.print("F6");
      }
      else if (msg == "off7")
      {
          digitalWrite(r7, LOW);
          Serial.print("F7");
      }
      else if (msg == "off8")
      {
          digitalWrite(r8, LOW);
          Serial.print("F8");
      }
      else if (msg == "off9")
      {
          digitalWrite(r9, LOW);
          Serial.print("F9");
      }
      else if (msg == "off10")
      {
          digitalWrite(r10, LOW);
          Serial.print("F10");
      }
      else if (msg == "offall")
      {
          digitalWrite(r1, LOW);
          digitalWrite(r2, LOW);
          digitalWrite(r3, LOW);
          digitalWrite(r4, LOW);
          digitalWrite(r5, LOW);
          digitalWrite(r6, LOW);
          digitalWrite(r7, LOW);
          digitalWrite(r8, LOW);
          digitalWrite(r9, LOW);
          digitalWrite(r10, LOW);
      }

    }

    msg = "";

    delay(1000);
}

else if (msg == "off")        {           digitalWrite(r5, LOW); perhaps missing a 5 in text?

I can see lot of problems.

No decoupling capacitors on ATMega.
Capacitors on both sides voltage regulators are usualy essential for regulator stability.
Big voltage drop on regulator - if it's overheating, thermal shutdown might happen. For example 7V drop @ 350mA (about four relays) results into 2.45 Watts turned into heat.
Bare HC06 doesn't like 5 Volts on its 3.3V logic level input
Xtal oscilator usualy requies two capacitors (22pF) for better stability.

Where do the switching transistors get their +5v? The dropouts and shutdown suggest that the "+5v" is sagging as more relays try to draw off of it. Try supplying the relay current from a more capable supply, possibly a voltage regulator off the +12v supply - it will be wasteful but if it works, you'll know that was the problem.

The asker has never stated that they are using an Arduino board.

True - fixed it.


text:
Switch statements with Bluetooth serial input not working
I am trying to control the brightness of an LED using PWM. I am also trying to make it so that when I click a button on my bluetooth app, I can get it to change the frequency of the PWM pin.
For changing the frequency, I am changing the value of the timers. When I click "30 HZ" on my bluetooth app, I am sending a value of "A", 122 HZ = "B" etc..
I hooked up a oscilloscope and changing the frequency does work.
The problem is that when I click a button, it receives A or B etc.. but it doesn't enter the switch statement every time. It is very laggy. It will also receive inaccurate numbers at times.
I think I need something in differentiating between various serial inputs? (one for choosing frequency and one for the duty cycle of the LEDs)? and also being able to enter the switch statements and then staying in there until another char is received.
Below is my code and I would appreciate any help!
const int pwmPin = 11;
const int TurnLightPin = 13;

int ledState = LOW; // ledState used to set the LED
unsigned long previousMillis = 0;  // will store last time LED was updated
const long interval = 500;  // interval at which to blink (milliseconds)
int dutyCycle = 0;

char state =' ';

void setup() {
  // put your setup code here, to run once:
  //Change register values to adjust PWM frequency for PWM Pins 3 and 11:

  //TCCR2B = TCCR2B & B11111000 | B00000100;    // set timer 2 divisor to           64 for PWM frequency of   490.20 Hz (The DEFAULT)
  //TCCR2B = TCCR2B & B11111000 | B00000101;    // set timer 2 divisor to      128 for PWM frequency of   245.10 Hz
  //TCCR2B = TCCR2B & B11111000 | B00000110;    // set timer 2 divisor to   256 for PWM frequency of   122.55 Hz
  //TCCR2B = TCCR2B & B11111000 | B00000111;    // set timer 2 divisor to  1024 for PWM frequency of    30.64 Hz  pinMode(TurnLightPin, OUTPUT);

  pinMode(TurnLightPin, OUTPUT);
  pinMode(pwmPin, OUTPUT);

  Serial.begin(9600); // Default baudrate of bluetooth -- 9600 bits/second
  Serial.println("HC-06 Bluetooth connected!!!");
  Serial.flush();

}

void loop() {

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

   if (currentMillis - previousMillis >= interval) {
     // save the last time you blinked the LED
     previousMillis = currentMillis;

     // if the LED is off turn it on and vice-versa:
     if (ledState == LOW) {
       ledState = HIGH;
     } else {
       ledState = LOW;
   }

   // set the LED with the ledState of the variable:
  digitalWrite(TurnLightPin, ledState);
}

 //PWM Stuff:

while(Serial.available()){

   // if (Serial.available() > 0){
  state = Serial.read();
  Serial.print("State received - Before Switch Statement: ");
  Serial.println(state);
  //}

switch (state) {

case 'A':

  TCCR2B = TCCR2B & B11111000 | B00000111;    // set timer 2 divisor to  1024 for PWM frequency of    30.64 Hz

  while(Serial.available() && (Serial.read() != 'B' || Serial.read() != 'C' || Serial.read() != 'D')){

    dutyCycle = Serial.parseInt();
    int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a  value between 0-100 and max PWM value is 255
  //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
    analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
    Serial.print("A-30 HZ - PWMValue:");
    Serial.println(pwmValue);
    Serial.print("A-30 HZ - State:");
    Serial.println(state);
    }

    state = ' ';
    break;

case 'B':
    TCCR2B = TCCR2B & B11111000 | B00000110;    // set timer 2 divisor to   256 for PWM frequency of   122.55 Hz

    while(Serial.available() && (Serial.read() != 'A' || Serial.read() != 'C' || Serial.read() != 'D')){

    dutyCycle = Serial.parseInt();
    int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a value between 0-100 and max PWM value is 255
  //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
    analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
    Serial.print("B-122 HZ - PWMValue:");
    Serial.println(pwmValue);
    Serial.print("B-122 HZ - State:");
    Serial.println(state);
  }

  state = ' ';

  break;

case 'C':

   TCCR2B = TCCR2B & B11111000 | B00000101;    // set timer 2 divisor to   128 for PWM frequency of   245.10 Hz

    while(Serial.available() && (Serial.read() != 'A' || Serial.read() != 'B' || Serial.read() != 'D')){

    dutyCycle = Serial.parseInt();
    int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a value between 0-100 and max PWM value is 255
   //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
    analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
    Serial.print("C-245 HZ - PWMValue:");
    Serial.println(pwmValue);
    Serial.print("C-245 HZ - State:");
    Serial.println(state);
  }

  state = ' ';

  break;

case 'D':

    TCCR2B = TCCR2B & B11111000 | B00000100;    // set timer 2 divisor to    64 for PWM frequency of   490.20 Hz (The DEFAULT)

    while(Serial.available() && (Serial.read() != 'A' || Serial.read() != 'B' || Serial.read() != 'C')){

      dutyCycle = Serial.parseInt();
      int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a value between 0-100 and max PWM value is 255
    //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
      analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
      Serial.print("D-490 HZ - PWMValue:");
      Serial.println(pwmValue);
      Serial.print("D-490 HZ - State:");
      Serial.println(state);
    }

    state = ' ';

    break;
default:

  TCCR2B = TCCR2B & B11111000 | B00000110;    // set timer 2 divisor to   256 for PWM frequency of   122.55 Hz

  while(Serial.available()){

    dutyCycle = Serial.parseInt();
    int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a  value between 0-100 and max PWM value is 255
    //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
    analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
    Serial.print("default - PWMValue:");
    Serial.println(pwmValue);
    Serial.print("Default - State:");
    Serial.println(state);
  }

  state = ' ';

  break;
    }//End of Switch Statement
  } // End of While loop for PWM
} // End of void Loop

I don't like your serial parser at all. Lots of whiles, reads, places to get stuck in...
For example mine looks like:
void loop() {

  if (Serial.available()) {
    int ch = Serial.peek(); // check first character in buffer

    switch (ch) {
      case 'a' ... 'd':
        TCCR2B &= 0b11111000; // mask out prescaler (turn off timer 2)
        TCCR2B |= 0b111 - (ch - 'a'); // a => 7, b => 6, c => 5, d => 4
        Serial.read(); // remove character from buffer
        Serial.println(TCCR2B, HEX);
        break;

      case 'A' ... 'D':
        TCCR2B &= 0b11111000; // mask out prescaler (turn off timer 2)
        TCCR2B |= 0b111 - (ch - 'A'); // A => 7, B => 6, C => 5, D => 4
        Serial.read(); // remove character from buffer
        Serial.println(TCCR2B, HEX);
        break;

      case '0' ... '9':
        dutyCycle = Serial.parseInt();
        analogWrite(pwmPin, (int)(dutyCycle*2.55));
        Serial.println(dutyCycle);
        break;

      default:
        Serial.read(); // some invalid character? Drop it
        break;
    }
  }
}

However it needs some extra character after number (needed by parseInt)

i had major issues with ws2812 and the hm-10, and i couldn't get a great solution for it, and although your setup is different, it may help…
my solution was to stop things that were interrupting the interrupt, in this case, the leds, so to create;
void dataLow () {
  // drop the power on the data pins for the leds
  digitalWrite(DATA_PINA, LOW);
  digitalWrite(DATA_PINB, LOW);
  Serial.println("DATA_PINS - LOW");
}

void dataHigh () {
  // turn the power back on for the leds
  digitalWrite(DATA_PINA, HIGH);
  digitalWrite(DATA_PINB, HIGH);
  Serial.println("DATA_PINS - HIGH");
}

and then to clean the data. i was looking for 2 numerical characters, and if i got anything else, then dump the data.
bluetooth.listen();
while (bluetooth.available() > 0) {
    dataLow();
    char inChar = bluetooth.read();
      // if its a character, add it to the string
      if (isDigit(inChar)) {
        inString += (char)inChar;
      }
      // if the string is longer than 2, truncate and return nothing
      if(inString.length() > 2) {
        inString[2] = '\0';
      }
      // if the serial recieves bluetooth end of line /n print string data out
      if (inChar == '\n') {
        Serial.print("String: "); Serial.println(inString.toInt());
        program=inString.toInt();
        inString = "";
        dataHigh();
      }
      // read user input from serial monitor
      if (Serial.available()){
        delay(10); // The DELAY!
        bluetooth.write(Serial.read());
      }
  }

it was still twitchy, but it mostly works.


text:
Bluetooth module is neither sending nor receiving data at baudrate(115200)
Im sending data between my arduino and android via bluetooth, using a simple chat app called "Bluetooth Terminal" . the code work perfectly at baudrate(9600) but I need to increase the speed to that of (115200) but nothing gets transmitted, or at least visible, anymore.
here's my code
#include <SoftwareSerial.h>

const int TXD = 3;
const int RXD = 4;
SoftwareSerial mrBlue(TXD, RXD);
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  mrBlue.begin(9600);

}

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

  if (mrBlue.available() > 0) {

    String data = mrBlue.readString();
    Serial.println(data);

  }

  if (Serial.available() > 0) {

    String data = Serial.readString();
    mrBlue.println(data);
  }

  delay(20);
}

Software serial is not working good with 115200 speed because of too much CPU usage. When I'm using only the bluetooth communication in Arduino, I'm connecting HC-05 (for example) to hardware serial pins and everything works fine.
If you want to increase the speed you must also change it in AT mode.

Software serial is really limited because it needs relatively precise timing, full attention of CPU and there can't be any interruptions from other sources.
You can see source code for better understanding how it works.
And if you need faster communication, you should get board with more hardware serials.


text:
ESP8266 only responds to AT and AT+GMR
I purchased a pack of esp8266 (https://www.amazon.com/gp/product/B00PA3UQNI/) and a usb to serial converter (https://www.amazon.com/gp/product/B01FUA2BBU/) from amazon. I hooked them up and attempted to use the Arduino serial monitor to communicate with the esp8266. Here are the commands I used and the responses I got:
    AT
OK
AT+GMR

+GMR: 7.80.5.0

OK
AT+RST

ERROR

My current setup is (RX on serial -> TX on esp) and (TX on serial-> RX on esp), although I have also tried them swapped. I have tried running the serial monitor at 115200, 57600, and 9600 baud and they all put out the same response. I have tried with both boards. I am currently running the esp8266 off of two AA batteries. All grounds are connected, CH_PD is connected to Vsupply with a 10k resistor, RST is connected to ground with a 3k resistor.
I have not done anything with the firmware and I have not tried any other serial monitor.
Please let me know if there is anything else I can try to get these to work.

Your question is wrong, your ESP is responding to AT+RST, it just doesn't understand what AT+RST means. Have you tried any other documented AT commands?

I have tried AT+CWLAP and AT+CWMODE. Both return ERROR.

Looks like you have some odd (i.e. not the "standard" Espressif) firmware on there. Output of AT+GMR for me is AT version:1.1.0.0(May 11 2016 18:09:56)
SDK version:1.5.4(baaeaebb)
compile time:May 20 2016 15:06:44
OK - though, I have flashed the very latest version of the AT firmware, but you can see it outputs a lot more info than just a version number

Shouldn't flashing ESP8266 again with latest firmware fix your problem? I have this same esp8266 module but I do get proper version info like @jaromanda X


text:
How to filter out "jumpy" readings sent using Bluetooth
I'm using App Inventor to continuously send orientation values (as strings) to my Arduino, which are read using Serial.parseInt(). Using simple IF statements (if value > threshold), I'm trying to turn on an LED and otherwise turn it off.
What I'm getting however, is an LED that goes on and off along with these values, which alternate between the actual and desired values and extreme unwanted values as shown in the picture:

Given that my orientation values, as they are, alternate between -180 to 180, I'm using a simple IF statement that seems to work reasonably well, except when the unwanted readings give inaccurate values that are within my range.

My Arduino code:
#include <SoftwareSerial.h>

const int TXD = 3;
const int RXD = 4;
SoftwareSerial mrBlue(TXD, RXD);

void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);

  mrBlue.begin(9600);
  Serial.setTimeout(20);
  mrBlue.setTimeout(20);
}

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

  if (mrBlue.available() > 0) {

    int data = mrBlue.parseInt();
    if (data > 180 || data < -180) {

    }
    else {
      Serial.println(data);
    }
  }
}

Not sure if this works for your needs, but I usually smooth noisy data by keeping a small buffer of the last 3-5 values and averaging them. A larger buffer gives more stable values at the cost of latency after a legit change.

This data is terribly noisy. My first approach would be to understand why, and then decide whether I could fix it, or have to live with it. It's easy to filter out the out of range data, but why is it there? Is it the sensor? If the sensor is analog, is the noise to due electrical pickup in its leads? Until you know, how can you trust even the apparently "good" data?

@JamesMcManus: With this kind of “wide tail” noise, a running median filter is way more efficient than a running average.

authors: Дмитрий Печуркин


text:
How to check 8266 module
I am using an Arduino board with an ESP8266 module to connect to a WiFi device.
How do I check if the device is connected?

Which Arduino board? Check the associated stations on your router to see if the device is associated (connected) to your router

You can use:
AT+ CWJAP?

or
AT+ CIPSTATUS

to see if you're connected to wifi. (The first will tell you access point status, the second will tell you IP address.)

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review

Revised to be the form of an answer :-)

Firstly,If your ESP8266 module is coded then AT commands won't be responding directly, In that case You can check in Serial monitor(if u already wrote print in the existing code on module) else u have to flash a new code.
If didn't flash any code then use AT commands(AT+CWJAP?) for checking SSID.
(AT+ CIPSTATUS) for IP adress.


text:
How to delay outside loop
I am using a function outside loop(), which is called after an interrupt. Inside this function, I am setting several relays that need to change after a second or two, depending on my setting. I tried the delay, it doesn't work. millis() isn't working as well; I found out it stops counting when I exit the loop function.
My code looks something like this:
const long on_interval = 2000;
unsigned long currentMillis = millis();
bool hv_bool = false;

void hv_switch() {
    if (digitalRead(hv_pin)==HIGH){
        hv_startup();
    }
}

void hv_startup() {
    unsigned long previousMillis = 0;
    digitalWrite(pre_charge, HIGH);
    digitalWrite(main_charge, LOW);
    //Wait interval
    previousMillis = currentMillis;
    while (currentMillis - previousMillis < on_interval) {
        Serial.println(millis());
        //Wait
    }
    digitalWrite(pre_charge, LOW);
    digitalWrite(main_charge, HIGH);
    hv_bool = true;
    loop();
}

void setup(){
    //Set some ports

    //Initiate interrupt
    attachInterrupt(digitalPinToInterrupt(hv_pin), hv_switch, RISING);
}

void loop() {
    //Low voltage loop after startup, high voltage off
    while (hv_bool == false) {
        Serial.println("Waiting on high voltage");
        digitalWrite(hv_led, LOW);
        digitalWrite(pre_charge, LOW);
        digitalWrite(main_charge, LOW);
    }
}

millis() works fine in any function, except in interrupt context, where it doesn't increment.

@EdgarBonet has it - hv_startup() is part of the the interrupt handler. Interrupt handlers should be as short (timewise) as possible, doing only what has to be done with the interrupts off, and leaving longer tasks for the mainline (loop() and its sub-functions) to do.
But a bigger problem is that loop() is called from hv_startup(), also getting used as part of the interrupt handler, and loop() has a while{} loop that depends on hv_bool, which can never get changed, 1) because there is no statement to set it false (besides the initialization); and 2) because loop is now running at interrupt level and no more interrupts (at the same level) can be taken.
So I'd suggest several fixes:

Don't call loop from your interrupt handler. When your handler exits, loop() will resume from wherever it was when it got interrupted.
Don't delay in your interrupt handlers. If the interrupting hardware needs to be reset, do that and any other processing you have to do while the interrupts are off. But if some longer processing needs doing, set a flag in the interrupt handler (remember to declare it to be 'volatile'!), and exit.

In loop(), test the flag. If it is set, clear it and call another function to handle the less urgent processing required by the interrupt.


text:
The Right Com Port (COM 7) is NOT Showing
I just finished a camp for the arduino and the arduino uno that they gave us is not working with my computer even though everything was working on their computers. I am trying to upload with the same schematic, same Arduino, and the same code. It is not wanting to upload even after changing in the preferences to the same com Port. I have tried updating the drivers, but Windows 7 64 bit s saying this error message : This device cannot start. (Code 10) .  Also, there is an exclamation mark in the device manager but how hard I try, it doesn't go away.

-1 for improperly tagging this "arduino-uno" when what you actually have is a different design with a different USB serial solution.  You should accept your own answer for the ch340 based board you apparently have.

I found out that I could not use the arduino drivers because I am using a DCcduino uno that has a separate driver.

The DCcduino Uno clone uses a CH340 USB-serial chip. The Arduino IDE doesn't include the driver for that chip because none of the official Arduino boards use it. You need to download and install the driver from http://www.wch.cn/download/CH341SER_EXE.html

The Right Com Port (COM 7) is NOT Showing

It would appear that Microsoft Windows does not necessarily assign the same COM port for a given device from machine to machine.  It is usually up to the user to map which COM port is being used for which device.  Some applications which work with specific devices have been known to "search" for that specific device and automatically connect to the correct COM port.

...saying this error message : This device cannot start...

There is this Microsoft Web Page here about this error.
More specific help may be found here.  In particular, this passage looks promising:

On Windows 7 (particularly the 64-bit version), you might need to go
  into the Device Manager and update the drivers for the Uno or Mega
  2560. Just right click on the device (the board should be connected to your computer), and point Windows at the appropriate .inf file again.
  The .inf is in the drivers/ directory of the Arduino software (not in
  the FTDI USB Drivers sub-directory of it).


text:
how does serialEvent work?
I have come across several examples about serialEvent() function, which look like this:
void serialEvent(){
  if(Serial.available()){
    \\do something
  }
}

The serialEvent() function is called when data is available, so which is the necessity of the if (or while) structure since that would be always true?
(In several cases I have excluded the if structure, and the code works fine)

As far as I understand, using an if statement wouldn't make any difference, but using a while statement would.
The serialEvent() function is executed within each execution of your loop() function if there is data available, so it would be something like:
while (true)
{
    loop();
    if(data_available)
        serialEvent();
}

If you only have one byte of information in the buffer, then you wouldn't have any problem at all.
But if you want to read multiple bytes at the same time, you would have to wait until the loop() is executed again to read the next byte.
You will solve that problem if you write your  serialEvent()  like this:
void serialEvent()
{
    while (Serial.available())
    {
        // do something
    }
}

That way, you will read all the information available at once and then return to the loop.

It's a burdon how incomplete and hidden a lot of things are in the IDE of Arduino.
It took me five hours to discover how the serialEvent() function works for other ports (as serialEvent2() for the serial-port #2.
It's the same with how the function itself works. I still don't know...
As an example just insert a delay in the above answer and it proves that: "That way, you will read all the information available at once and then return to the loop." is NOT true.
void serialEvent()
  {
    while (Serial.available())
      {
        // do something
      }
    delay(1000);
  }

don't use serialEvent it has no advantage over if (Serial.available()) in loop()

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


text:
Convert a Double to an UnSigned Char
So, I'm working on RedBear Blend Micro V 1.0, and I must use the function:
ble_write(Serial.read());

To read some input from the serial monitor(Input being stuff I type in the Serial Monitor) and send it via bluetooth.
It works perfectly this way!
Now what I need to do is create a random double data type number, and insert it in the place of Serial.read()
Read This:
ble_write
Syntax:
    void ble_write(unsigned char data);
  ble_write sends a single byte data to the BLE Central.
So, can you please help me, to:
1)Generate a random double
2)Send it using the ble_write() function?
For a full list of function sin the ReadBear Library click on the link:
https://github.com/RedBearLab/nRF8001

If it's random then why not just send random unsigned chars?

@IgnacioVazquez-Abrams Thanks for the suggestion but the thing is, for now I want to send a definite NUMBER via the ReadBear BlendMicro, but later, instead of this number, i will be sending data from an ECG Sensor, the data from the ecg sensor is a Double..Dont worry Ive checked the ECG part

Edit: Chris Stratton rightfully points out that the question is
about a double, not a float:

a float is four bytes in every platform I know about, as per the
IEEE-754 standard
a double is eight bytes in almost all platforms, with the notable
exception of AVR: the AVR double is highly non-standard, four bytes
long, and essentially equivalent to float

Most, but not all Arduinos, are AVR-based.
In the following I assume you are talking about AVR doubles, i.e.
floats. If this is not the case, then just replace the array of 4 bytes
by an array of 8 bytes.

Original answer:
A float is four bytes, so it is somewhat equivalent to an array of
four unsigned chars, i.e. to unsigned char[4]. You can use this
equivalence with an union. For example, the following function will
send a float byte by byte:
void ble_write_float(float x)
{
    union {
        float f;
        unsigned char c[4];
    } data;

    data.f = x;
    ble_write(data.c[0]);
    ble_write(data.c[1]);
    ble_write(data.c[2]);
    ble_write(data.c[3]);
}

Notice that this will send the bytes in whatever is the natural order of
the sending processor. If it's an AVR (like most Arduinos), this will be
LSB (least significant byte) first. You have to make sure that this is
what the receiver expects.
Following Ignacio Vazquez-Abrams' suggestion, for sending a random float
you could just send four random bytes. However, it may be wiser to have
an idea of the random distribution you want for your float, and use
things like random() and map() to achieve that distribution. Using
four random bytes, you get a very wide distribution (all the possible
floats are equally likely) which includes weird things like denormals,
infinities and NaN (literally meaning “not a number”).

The question asks about a double while you answer with regard to a float so it would be helpful to mention that on the ATmega based Arduinos they are equivalent, however on some other varieties they are not.

@ChrisStratton: Thanks for pointing this out. I amended the answer.