text:
Dynamicly sized array as a class member
I want to create a dynamic sized array of chars as a member in a class.
This is being done inside a library that I've created.
I have the .h and the .cpp files created. I'm not sure how to declare the array in the .h file. I've tried a few things so far:
char* content;
char content[];
But these don't seem to work.
Here's what I have in my .h file:
class bufr{
    public:
    //constructor and deconstructor
    bufr(char* _chars, uint8_t _len);
    ~bufr();

    //variables
    uint8_t len;
    char content[];

};

Here's what I have in my .cpp file (this is the constructor):
bufr::bufr(char* _chars, uint8_t _len){
    char* content = new char[_len];
    content = _chars;
    len = _len;
}

I've also tried replacing the line content = _chars with:
for (int i = 0; i < _len; i++){
    content[i] = _chars[i];
}

But this also doesn't work.  When I print the content member to the serial port from within the constructor, or in the main loop it prints nonsense characters, not what I passed it.
Here's my main loop:
void loop(){
    char chars[] = "1234";
    bufr buf(chars, 4);
}

Have I explained myself well enough?  Can anyone give me a hand?
Much appreciated!
Oh, and yes, I know - in my deconstructor that's not shown, I have delete [] content
I plan on using this class nested inside another class in a few spots and hoping to take advantage of the dynamic mem allocation.  I know I can simply declare an array of fixed length, but I wanted to learn the proper way to use new and delete.
Thanks!

Actually, I lied above... I was just doing some more testing. If I print to the serial port from WITHIN the constructor the member content is printed correctly: "1234".  But, if I print from the main loop like this:  serial.println(buf.content); shows up incorrectly.  What am I doing wrong?

This is wrong on a number of levels. First in the class declaration:
char content[];

That gives you a pointer to an array of zero length.
This gives you an array of char, of zero length. This is not useful.
char* content = new char[_len];
content = _chars;

That does a new into a new variable content - not the class variable. Then you assign (overwrite) the passed pointer into content (discarding the memory you just allocated). That pointer is then discarded when the constructor ends. Perhaps using strcpy would be better.
I made up a small example based on your code which prints the correct result:
class bufr
  {
  public:
    //constructor and deconstructor
    bufr(char* chars, uint8_t len);
    ~bufr();

    //variables
    uint8_t len_;
    char * content_;
  };    // end of class bufr

bufr::bufr(char* chars, uint8_t len)
  {
  content_ = new char[len];
  memcpy (content_, chars, len);  // copy into allocated memory
  len_ = len;   // remember length
  }   // end of constructor

bufr::~bufr()
{
  delete [] content_;
} // end of destructor

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

  char chars[] = "1234 ";
  bufr buf(chars, sizeof chars);

  Serial.println (buf.content_);
} // end of setup

void loop()
{
} // end of loop

Can you explain to me why it was making a new variable content and not using the class variable?

Small example:
char * content;

void loop ()
  {
  char * content = "foo";  // makes a NEW variable
  }

In this example there are two variables named content. The one in the function "shadows" the global one. However the code below only has one variable:
char * content;

void loop ()
  {
  content = "foo";  // uses existing variable
  }

In the destructor, when you delete the pointer to the array, does this free up the memory allocated to the array? It's now free to be assigned again by something else? Or does it sit there still initialized as that array, not being able to be used again?

You aren't deleting the pointer. You are deleting the memory it points to. The pointer is now pointing to freed memory, so using it as a pointer at this stage would be wrong. You can do another new to make it point to something else.

they delete pointer and then delete[] pointer.

You misinterpreted that. You either delete pointer or delete [] pointer depending on whether pointer is an array or not. I reworked content to not be an array, thus deleting it without the brackets is correct however as it is allocated using new [] it must be deleted with delete [].

on the link posted above they say to use delete this way: delete pointer if it was a single element allocated with new or delete [] pointer to release memory allocation for arrays of elements allocated with new and a size in []'s. So in my case I want to use delete [] content_?

No, you don't want to be setting up an array in the first place. Take a look at this small example:
struct   {
  char bar [];
  } foo;

void setup()
{
Serial.begin (115200);
Serial.println ("Starting");
Serial.println (sizeof (foo));
Serial.println (sizeof (foo.bar));
}

void loop()
{
}

That prints:
Starting
0
0

The variable bar is a zero-length array. Thus the entire struct foo is also zero length. It isn't even a pointer (that would be two bytes on this platform).
It is wrong to use an array of char like that, when you want to dynamically allocate memory. Look at this:
char foo [4];

That allocates 4 bytes of memory for foo. You can't later on make it longer by doing a new.
What you want is:
char * foo;

Now you have allocated a pointer and can do a new, like this:
foo = new char [10];  // allocate 10 bytes

And then delete it:
delete [] foo;

You use the brackets on the delete, as you used them with the new.
If you allocated one char you wouldn't use brackets. eg.
char * foo;
foo = new char;  // allocate a pointer to one byte
...
delete foo;

Actually, char content[]; doesn't give you a pointer - it gives you a buffer of zero length.

Thanks for your help. Can you explain to me why it was making a new variable content and not using the class variable?

Another question regarding your answer:  In the destructor, when you delete the pointer to the array, does this free up the memory allocated to the array? It's now free to be assigned again by something else? Or does it sit there still initialized as that array, not being able to be used again?

On this page: link they show creating the dynamic array the same way as you did, but when they delete it, they delete pointer and then delete[] pointer.  Did you leave this out? Or is this necessary?

Sorry, one more edit.. I made a mistake, on the link posted above they say to use delete this way:  delete pointer if it was a single element allocated with new or delete [] pointer to release memory allocation for arrays of elements allocated with new and a size in []'s.  So in my case I want to use delete [] content_?   Thanks again!

@JohnBurger - I wrote that initially, and then changed it because the assignment seemed to work. But you are right. :)

See amended answer.

@Killerb81 You wrote char* content = new char[_len]; in the constructor. This says "I need a brand new char* variable that I'm gonna call content (never mind that there's a member called that!), and I want you to initialise it with a new pointer from the heap of _len characters." If you want to modify the member content, remove the char * at the beginning.

Thanks for taking the time guys, I really appreciate it. @NickGammon, in your example above delete foo;, even though foo is a pointer, this lets the full 10 bytes allocated to RAM (and the two bytes for the pointer?) available in RAM again?  That's the part that's confusing me and why I asked if it was correct to put the [] in the delete statement.

@JohnBurger well, isn't foo actually a pointer to a char?  Not the 10 bytes allocated for the array of chars itself.  I just don't get how using delete on a pointer frees up the 10 bytes (his example) that was allocated for the array.

Yes, foo is a pointer to char. But it got that way courtesy of foo = new char[10]; - which makes it a pointer to not only the first char, but the following 9 as well, all of them on the heap. If you did the following code: 'char c = 'A'; char *p = &c; delete [] p;thendelete[]` would be happy - while totally corrupting your heap. Shudder !

ok, I see what you mean.  So it's definitely correct to use the delete [] content ?  I just don't get why he wrote "foo is not an array so you don't use the brackets."  I don't want to inadvertently corrupt my RAM during runtime.

John Burger and Killerb81 are correct. I got confused about the brackets on the new/delete. I have corrected my answer. I had to work through this in this recent post. I just don't get why he wrote "foo is not an array so you don't use the brackets." - I was wrong. Oh well, won't be the last time. :)

Many programmers have a disjoint between a pointer and an array. Here's an explanation.
Here is a variable of type char, initialised with the value 'A':
char c = 'A';

'A' has the ASCII value of 65, so that means that there's a byte in memory that holds the value 65. Let's say that byte in memory is at address 0x2000. If you were to add 1 to that byte, it would become 66, and if you were to print it as a character, it would print B (ASCII 66).
Here is a pointer to a char, initialised with the address in memory of c:
char *p_c = &c; // Get the address of c into p_c

[Note that char *p_c = c; would be invalid: you can't initialise a pointer with a char! That'd give p_c the value 65 - not what you want!]

In Arduino, p_c represents two successive bytes of memory that together store the address of a char: in this case the value 0x2000. Where those two bytes are doesn't matter for this explanation - but trust that they too have an address...
If you were to change c into a 'Z', that would change c's contents, but not p_c's (it would still be 0x2000). But if you were to use p_c to look at the byte it was pointing to (c), then you'd see the 'Z'.

If you were to do a printf("%c", c); you'd get a 'Z'.

%c means "I've got a character as the next variable in the printf() list".

If you were to do a printf("%c", *p_c); you'd also get a 'Z'.
If you were to do a printf("%c", p_c); you'd get horrible results.

You lied to printf() - you didn't give it a one-byte character, you gave it a two-byte pointer!

Now let's move on to arrays.
Here is a variable of type char [], initialised with the value "John".
char s[] = "John";

'J' has the ASCII value 74, 'o' 112, 'h' 104, and 'n' 111. That means that in memory there are four sequential bytes with the values 74, 112, 104, 111. Let's say that those bytes are at addresses 0x3000 through 0x3003.
And here is another pointer to char, this time initialised with the address in memory of s.
char *p_s = s; // Point to s with p_s

I hate that the C language allows the above. It is one of the roots of the whole array/pointer confusion. It kind-of implies that p_s somehow gets all of "John" assigned to it. Nope!

A better statement would have been:
char *p_s = &s; // Initialise p_s with the address of s // ILLEGAL!

That gives a MUCH better idea of what's happening - alas, it's not how it's done...
But also note that neither of the above could possibly store 0x3000-0x3003 (the addresses for all of s), so they have to be satisfied with only storing the start of the string: p_s will get the value 0x3000.
Note that s does NOT have the value 0x3000 in it. That is its address, like 0x2000 was c's address (it too doesn't have 0x2000 in it). But p_s does have 0x3000 in it - and don’t forget that p_s also has its own address (I won't bother with that here).
And this is where the "equivalency" (they're not) between a pointer and an array starts to get people confused:

s[2] = 'h'; and p_s[2] = 'h'; do the same thing - but in different ways!

The first accesses 0x3002 directly.
The second needs to find out that p_s is 0x3000 and add 2 to it before it can access 0x3002.

*(p_s + 2) = 'h'; is yet a third way to do the same thing.

So now let's printf() these new variables:

printf("%c", *s); wouldn’t compile.

s is not a pointer, so you can’t dereference it with *.

printf("%c", *p_s); would print the character at where p_s was pointing.

This would print out J.

printf("%c", s[0]); would print the character at s[0].

This would print out J.

printf("%c", s); would give horrible results.

Again, you lied to printf()!

printf("%s", s); would work (but see below).

%s means "I've got a sequence of characters that I'd like you to print. I've provided the address of the first character."

printf("%s", p_s); would be identical to the previous one.

After all, the same address value was passed!

printf("%s", *p_s); would give horrible results.

Again, you lied to printf()!

But note something: you've given printf() the beginning of the string, so it can start printing. How does printf() know where the end of the string is? You didn't provide the number 4; it's not stored anywhere; how can it know when to stop?
That's where a C convention for strings steps in. By convention, when the compiler sees a string "between quotes", it stores the ASCII values of the characters, and then follows them with a 0. Not an ASCII '0' (with value 48), but an ASCII NUL (with value 0). Thus if you looked at address 0x3004 (the byte directly after John), you'd see a 0 in that memory byte. That's how printf() knows to stop printing - and yes, many a bug has resulted from forgetting to maintain a NUL at the end of a sequence of chars!
That then leads me to the sizeof() function
sizeof() always returns a constant at compile time using information that the compiler then knows about:

sizeof(c) would return 1.
sizeof(p_c) would return 2.
sizeof(p_s) would also return 2.

It is after all merely a pointer too.

sizeof(*p_c) would return 1.
sizeof(*p_s) would also return 1.

It's only pointing to a single char...

sizeof(s) would return 5.

The compiler knows what s is: an array of 5 bytes (including the final NUL).

Given a pointer, there is no (native) way to find out how large the buffer it is pointing to can be.

OK: so if you've got a char [] you can find out its size. Note that that is its maximum size - the string inside it could be a lot shorter! If you did the following:
s[3] = 0; // Overwrite the fourth character (arrays start at 0)
printf("%s", s);

[Note a better version of the first line would be s[3] = '\0'; which means "store the ASCII character 0 (NOT '0')" instead of "store the number 0".]

you'd get Joh printed out. Note:

sizeof(s) remains 5;
You can't get the length with sizeof(*p_s);
The string inside it is only 3 characters long.

So... if you've got a string buffer, or a pointer to one, how do you know how long it is? Count the number of characters until you reach a NUL - and there's already a function to do that for you: strlen().
Which now leads to the final point about pointers: dynamic allocation of memory.
The array s above was sized by the compiler at compile time: it could count the characters, add one for the NUL, and reserve the right number of bytes. You could also have written:
char s[10] = "John";

which would have reserved 10 bytes and only initialised the first 5 of them. The following would be an error:
char s[3] = "John"; // Buffer too small!

Scarily, char s[4] = "John"; works... (The compiler says to itself "No room for the NUL?! Ah well...”) Better never pass that string to strlen() or printf() then!

What if you don't know at compile time how big a string is going to be? If you know at runtime, you can ask the system for a lump of memory from the heap - a reserved area that can have chunks taken from it and returned as required. There are two ways to do this:
char *p_b = (char *)malloc(size); // Where size is a variable
char *buffer = new char[size];    // Grab 'size' new chars

The first calls malloc(), passing in the number of desired bytes. If malloc() can give those bytes it will reserve them and return a pointer to them. If it can't it will return 0. You should always test the return value! If not, you'll corrupt things horribly...
The second uses the more sophisticated new[] syntax, which is more object oriented. Notice how malloc()'s return value needed to be turned into a (char *)? That's because it doesn't know what type of pointer it's returning, so it just picks void *. new does know, so it returns the correct type - but it still may return 0 if there's no room!
Once you've got either pointer, you use them just like p_s before. There is nothing stopping you from accessing outside the boundaries of the buffer - just like there isn't for p_s! Be careful!
Oh, and once you've finished with the lump of memory, you need to return it to the heap:
free(p_b);
delete [] buffer;

If you used malloc(), return it with free(). If you used new[], return it with delete[].
And all of the above is why they invented the String object.
It manages the memory; keeps track of the string's length; lets you access and modify individual characters; lets you resize the string as needed; and gets rid of the used memory once you're finished with it. No wonder people start to use String syntax when they see string pointers...
But Strings are only useful for chars. Arrays and pointers can be of and to anything - including Strings and (GASP!) pointers! Uh oh - here we go again...

That should be a chapter in a text book!!!  Thanks @John.

@Killerb81 probably multiple chapters in a text book ;)

Thanks, people. I've proposed it as an entry in the Tag Wiki for pointer. We'll see...

I forgot to include what would happen if you wrote printf("%s", p_c); . Needless to say, you'd get a good result - and then horrible ones, as it continued to print characters until it finally got to a NUL...


text:
Ethernet Controlled Arduino Arm
Good day, I am currently attempting to write code that will allow a user to connect to an Arduino Mega via IP address and control a robotic arm on the X and Y axis as well as open and close the claw. I am facing 2 issues and hope someone can help me

when it connects for the first few seconds the servos twitch and I'm not sure why
In my current code i am reading in the URL of the button pushed and moving the arm 5 degrees each time, but i would like to be able to hold the button down and have the arm move instead but I'm not sure how to go about that

/*
 Jamil Gaufr and Eva Santos
 Bridges Project @ SUNY Purchase
 Robotic Arm Control & Interface
 */

#include <SPI.h>
#include <Ethernet2.h>
#include <Servo.h>

//Represents servo to open/close claw
Servo microservo;
//Represents servo to move forward/away
Servo Yax;
//Represents servo to swivel left/right
Servo Xax;

int pos = 0;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //physical mac address
EthernetServer server(80);                             //server port
String readString;
String x = "x =";
String y = "y = ";
String cl = "claw  = ";

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  Yax.attach(4);
  Xax.attach(5);
  microservo.attach(6);
  // start the Ethernet connection and the server:
  Ethernet.begin(mac);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  //Initializes every axis to start at the 45 degree position
  Yax.write(100);
  Xax.write(60);
  microservo.write(90);
  //1 second delay
  delay(1000);
}

void loop() {
  // Create a client connection
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += c;
          //Serial.print(c);
        }

        //if HTTP request has ended
        if (c == '\n') {
          //Serial.println(readString); //print to serial monitor for debuging

          client.println("HTTP/1.1 200 OK"); //send new page
          client.println("Content-Type: text/html");
          client.println();
          //begins html code
          client.println("");
          client.println("");
          client.println("<TITLE>Bridges Program </TITLE>");
          //CSS style code for buttons
          client.println("");
          //end of CSS code
          client.println("");
          client.println("");
          //Page header
          client.println("
Welcome to Robo-Farm!
");
          client.println("
");
          client.println("
");
          //Sub-heading
          client.println("
Robotic Arm
");
          client.println("
");
          //Creates buttons and corresponding URL extension
          client.println("Close Claw");
          client.println("Open Claw
");
          client.println("
");
          client.println("
");
          //Creates buttons and corresponding URL extension
          client.println("Move forward");
          client.println("Move Away
");
          client.println("
");
          client.println("
");
          //Creates buttons and corresponding URL extension to IP address
          client.println("Swivle left");
          client.println("Swivle right
");
          client.println("
");
          client.println("
");
          //Footer text
          client.println("
Created by Gafur & Santos.
");
          client.println("
");
          client.println("");
          client.println("");
          //end of html file
          delay(1);
          //stopping client
          client.stop();
          //controls the Arduino if you press the buttons
          //parses the URL for the corresponding extension
          if (readString.indexOf("?button1on") > 0 && microservo.read() <= 175) { // button1 on is close claw
            microservo.write(microservo.read() + 5);  // tell servo to go to position in variable 'pos'
            delay(15);                        // waits 15ms for the servo to reach the position
            Serial.println(cl + microservo.read());
          }
          if (readString.indexOf("?button1off") > 0&& microservo.read() >= 95) { // close claw
            microservo.write(microservo.read() - 5);  // tell servo to go to position in variable 'pos'
            delay(15);                                // waits 15ms for the servo to reach the position
            Serial.println(cl +microservo.read());
          }
          if (readString.indexOf("?button2on") > 0 && Yax.read() < 150 ) { // button2 on is move forward on y ax (towards the servo on the claw)
            Yax.write(Yax.read() - 5);                // tell servo to go to position in variable 'pos'
            delay(15);                                // waits 15ms for the servo to reach the position
            Serial.println(y + Yax.read());
          }
          if (readString.indexOf("?button2off") > 0&& Yax.read() > 70 ) {
            Yax.write(Yax.read() + 5);                // tell servo to go to position in variable 'pos'
            delay(15);                // waits 15ms for the servo to reach the position
            Serial.println(y + Yax.read());
          }
          if (readString.indexOf("?button3on") > 0 ) { // button3 is swivle in direction of sticker
            Xax.write(Xax.read() - 3);                // tell servo to go to position in variable 'pos'
            delay(15);                                // waits 15ms for the servo to reach the position
            Serial.println(x + Xax.read());
          }
          if (readString.indexOf("?button3off") > 0) {
            Xax.write(Xax.read() + 3);                // tell servo to go to position in variable 'pos' S
            delay(15);                // waits 15ms for the servo to reach the position
            Serial.println(x + Xax.read());
          }
          //clearing string for next read
          readString = "";

        }
      }
    }
  }
}

If you are using a webpage, obviously you cannot implement it with links (since links work by "reloading" the page). You will need to use AJAX and write some functions in Javascript to send multiple requests.

Question 1 will need more information about your code and your wiring of the arm to offer any reasonable answer.
Question 2: There really isn't much to go on but I'll take a guess that you're sending a single message to the arm server on each button press - ? I'd try instead, sending another message every 't' starting at (.75 * t) from message-1, where 't' is the time taken for the arm to move 5 degrees. That's a totally wild guess based on unfounded assumptions of what's happening now, and what fraction of 't' I guess would make sense, but that would be my first, very experimental approach. And even so, given the non-determinism of internet packet arrival times, I wouldn't bet on getting very smooth motion, nor instant stopping on button release.
My next experiment would be send start moving/keep moving commands to the arm on button-press, stop moving on button-release, with the arm controller being smart enough to 1) stop anyway after some short period of no messages or it reaches its limit, and 2) not let commands accumulate (or the arm will keep driving until it limits).
Update:
Yes, if you're using a terminal emulator that has the ability to send each keystroke rather than line-by-line, and doesn't suppress key-repeat. As above, don't accumulate incoming keystrokes but when you're looking for another, drain the buffer first then watch for an incoming one. If you don't find it within <TIMEOUT>, stop moving. <TIMEOUT> should be slightly longer than the key-repeat interval.
(I like my second way better - winging it at the keyboard, heh! - but if it were me, I'd probably try both anyway just for what I could learn from either one).

For wiring it on a keyboard is there any way to read in data/keystrokes and have a live stream being implemented in the arduino; Example press up the the hand moves up until i let it go?

In case I used an unfamiliar idiom, "Winging it" means doing something without a great deal of fore-thought or research, similar to "off the cuff", if that helps. In this case I meant I was thinking and forming new ideas, even as I was typing the first idea I had thought of.

gotcha, sorry for that

source: Stack Exchange

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

sort: votes


text:
Arduino Uno: Pullup Resistor
I have been reading a bit about the internal pullup resistor. I know from past projects in school that resistor themselves are fragile (burnt one by accident due to higher current than was made for).
I have two different Arduino models. One by Intel and rest are standard Arduino Uno.
So I was wondering about safely using the internal pullup resistor on the Arduino Uno. Hence my question is about the internal pullup resistor pinmode; How many pin can you connect to it safely and not overload it?

Each pin has its own, separate, pullup resistor.
I don't believe you can damage it by drawing current from the port, because the pullup resistor is only active when the port is in high impedance (hi-Z, input) mode.
The pullup resistor can be damaged by overvoltage, static discharge, and the like.
The Uno has 20 kOhm pullup resistors according to this tutorial. If you feed it a 0V signal while the Atmega is running at 5V, the current will be a quarter of a milliamp, which is miniscule.

The question was pretty much are there only one internal pullup resistor for all pin? If so is there any dangerous of overlord with so many connections. But apparently not if each pin has it's own resistor.

Yes, to clarify: They are separate resistors, with approximately the same value (~20 kOhm on the Atmega328/Arduino Uno).

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


text:
How can you reduce the clock frequency of an Arduino Mega?
I'm trying to debug a problem and need to reduce the speed of the clock on my Arduino Mega from 16MHz to 8MHz.
I can't find any simple way of doing so, so I wanted to know if there were any gurus here who knew if this was possible, as well as how to do it.
WITHOUT PRESCALER:
long int runTime;

void setup()
{
  Serial.begin(9600);     //Setting the data transfer rate
}

void loop()
{
  delay(1000);
  runTime = millis();
  Serial.print("Runetime: ");
  Serial.println(runTime);
  delay(100);
  exit(0);
}

OUTPUT: 999

WITH PRESCALER:
long int runTime;

void setup()
{
  Serial.begin(19200);   //Setting the data transfer rate for when CLK Freq. is Halfed

  CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
  CLKPR = _BV(CLKPS0);  // divide frequency by 2
}

void loop()
{
  delay(1000);
  runTime = millis();
  Serial.print("Runetime: ");
  Serial.println(runTime);
  delay(100);
  exit(0);
}

OUTPUT: 999

In your test code, you should put the changing of the clock prescaler between noInterrupts() and interrupts(). Otherwise there is a small possibility of this failing. Also, your test only proves the clocks of delay() and millis() have changed consistently. Which is to be expected since it's the very same clock.

So how can I test if the clock is in fact running at 8MHz instead of 16MHz?

The only way to test a clock is to compare it with another clock. This other clock could be your own sense of time (that's how the test in my answer works), or the UART at the other end of the serial connection (that's how you own program, with 19200 bps nominal and 9600 bps actual baud rate, is actually a valid test). High end solution: hook a GPS with a 1PPS output to your Arduino. Low end solution: program the watchdog, which has its own independent clock, to generate periodic interrupts.

You can set the clock prescaler for that:
void setup() {
    noInterrupts();
    CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
    CLKPR = _BV(CLKPS0);  // divide frequency by 2
    interrupts();
}

This is explained in section 10.12 and 10.13 of the
ATmega2560
datasheet.
Of course, changing the clock frequency will mess with the time-related
function (millis(), delay() and co.) and the baud rate of the serial
port.
Edit: Here is a small program to demonstrate the slowing of the
clock:
//#define SLOW_CLOCK

void setup()
{
#ifdef SLOW_CLOCK
    noInterrupts();
    CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
    CLKPR = _BV(CLKPS0);  // divide frequency by 2
    interrupts();
#endif
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
    digitalWrite(LED_BUILTIN, HIGH);
    delay(500);
    digitalWrite(LED_BUILTIN, LOW);
    delay(500);
}

This makes the LED flash at 1 Hz. If you uncomment the line
#define SLOW_CLOCK, it instead flashes at 0.5 Hz.

So when I added that I got a bunch of random symbols (i.e. †fæ†žf) and I'm not sure why. Are the setting different for an Arduino Mega?

Note that delay(1000); will now take 2 seconds, instead of 1.

You should also half the baud rate of your serial console, or double the baudrate in Serial.begin().

I wrote some test code and there didn't seem to be any change. Is this what @EdgarBonet  was talking about? Am I not supposed to see a difference in the output of millis()? is so then is there another way for me to test if it's working.

@IsabelAlphonse: What test did you do? The wacky symbols on the serial port kind of prove that the baud rate was unintentionally changed.

@EdgarBonet I added the test code to the console. I'm not getting wacky symbols anymore. I just get the same value for runtime which confuses me because I thought this would make one of them smaller.


text:
Want to create bluetooth audio control (volume up/down, play, pause, etc.) for smartphone
I want to create a bluetooth remote audio control to control smartphone audio, essentially identical in function to this type of equipment:

https://www.amazon.com/FAVOLCANO-Bluetooth-Button-Smartphone-Samsung/dp/B01C5E95XG/ref=pd_lpo_147_bs_t_1?ie=UTF8&refRID=1GRBCPDRMD9YPYPGK73Y
This device is simply a bluebooth remote control which allows you to play or pause audio, skip forward or backward and change media volume on the smart phone.
All of the Arduino tutorials I see are about either using the iPhone to control a bluebooth device, or about using bluetooth to control an arduino, neither of which are what I want to do.
Can you point me in the right direction?

You need a BLE shield with library support for acting as a Bluetooth HID device.

@Majenko Thank you!  It's the library that needs bluetooth HID support, not the shield, correct?  Or do both need to support it?

Both need to support it.

AVRCP is usually used by Bluetooth remotes, not HID. Not sure if BLE supports AVRCP though.

@IgnacioVazquez-Abrams - Is HID is normally for non-audio purposes?  I don't think it matters to me its BLE or not - it's more just a matter of whether I can accomplish my purpose.  Is there a way to (by looking at diagnostics etc) to see if an individual device (eg the one in the pic above) is AVRCP and/or BLE?

They're all AVRCP. I have a remote that also does HID, but that's for the camera trigger; the audio controls are still AVRCP.

Bluetooth supports multiple protocols for multiple purposes.  There is low latency low quality monorail bi-directional communication with a little bit of bandwidth for control for Bluetooth phone calls.  This is called HFE Bluetooth protocol.  If you are interfacing a keyboard or a mouse you would use the Human Interface Device protocol or HID.  If you wanted to listen to music and control it's playback you would use the high latency high quality 2 audio sending channels (stereo) no return audio channel with a little bit of bandwidth for controlling playback called Advanced Audio Distribution Profile or A2DP.
In this specific case we are only interested in controlling playback.  So we could use the HID Bluetooth protocol.  However, the native music players on the platform you are using (Android or iPhone) likely will not be listening to such a device.  In order for this to work you will probably have to write your own Android or iPhone music player.
On the other hand, it is likely the native music players will work with A2DP Bluetooth protocol.  Unfortunately, it is also suspected that once the A2DP Bluetooth connection is established, the phone's speaker will be shutdown and all audio will be diverted to the Bluetooth connection.
Finally, there is the Audio/Video Remote Control Profile or AVRCP.  This protocol is used to control media playback.  There are several versions of this protocol so what features are available for a given device / music-application may vary greatly.

+1 nice answer. I do have one thing to add. I've tested media control via HID and it works for me on Android. (Perhaps HID support has improved in the past 2.5 years.) It's easy enough to test using a bluetooth keyboard that has media buttons. HID may be easier to implement, but I found one drawback. If I haven't hit a key after several minutes, there is a delay in processing the next key. (Power saving mode?) One of my goals was to skip podcast commercials, the delay made HID less useful for this purpose. AVRCP a better choice, even if it's harder to get working.

Thanks for the +1.  Assuming the devices you are using are powered off of batteries, I wonder if the delay can be avoided if devices were powered off main instead.

I didn't spend the time to dig into this, I only made some assumptions about the delay. I tested with a BT keyboard, not a device I programmed. The keyboard would go into a stand by mode presumably to save power. This indicated to me that maintaining a full connection used too much power, and behavior seemed to be driven by the keyboard because it was documented in its user manual After that I looked at at AVRCP. But now I'm reading up on BLE's HID over GATT Profile, HOGP which has been supported by Android since KitKat. It's looking like the right solution for me.

I can add something to @st2000's excellent answer (in a better format than our discussion in the comments there).
The original question is vague. Does Bluetooth mean Classic or is Low Energy (BLE) acceptable or preferred. Which smartphones must be supported? Apple and/or Android? And what minimum version must be supported?
The 2.5 years that have passed since this question was asked makes it easier to choose BLE because adoption is so prevalent now.
I've been researching what it would take to implement a media control device as described in the original post. My target smartphone is Android Nougat. My goal is to skip podcast commercials. I have tested using a Bluetooth Classic keyboard. The media control buttons, Play/Pause, skip forward, skip back, etc. seem to do what I need.
I'd prefer to use BLE's support for keyboards and other Human Interface Devices: HID over Gatt Profile (HOGP). The KitKat release notes say that's when HID over GATT support was added, so it's been around for a while.
Having decided on a Bluetooth LE profile, device selection remains. Adafruit Bluefruit LE UART Friend has a HIDKeyboard example. I prefer an MCU with integrated BLE support. While total overkill for this application, I have an ESP32 that I plan to use for this. It has good community support and is cheap. If battery life (or size) becomes a problem, I'll look for a lesser device.

I did it on HC-05 (reflash to RN-42) and use HID profile to send command: Play/pause fwd/rwd vol+/-
I can post sample code if needed.
Here's the video https://youtu.be/y8PcNbAA6AQ

Please edit your answer to add the sample code.

I'm trying to do exactly the same, would you mind sharing your code please?

Yes, some sample code would be much appreciated.

Posting Arduino code that shows how to use the AVRCP would be great, if you've done it.

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


text:
How can I generate a sinewave with Arduino Uno?
I would like to generate a sine wave with my Arduino Uno. As far as I know, there is no library for Uno to generate such a signal (correct me if I'm wrong), so the only option available is to write a function to generate the signal from scratch.
As far as my understanding of digital electronics goes, I believe it is possible to generate a sine wave signal by using PWM and varying the duty cycle accordingly. However, this route seems to me quite long, what other options do I have?

As far as I know, there is no library for Uno to generate such a
  signal (correct me if I'm wrong)

You are wrong, there is Mozzi, the sound synthesis library for
Arduino. It works essentially along the lines sketched by uint128_t.
Take a look at the Sinewave.ino for an example on how to make a
(lookup table-based) sine wave. It can also do much more.
In its default mode, Mozzi works with a 16,384 Hz sample rate and a
32,768 Hz (not audible) PWM frequency.

I found Mozzi to be very heavyweight for a limited memory footprint. It is fine if there is no plan to perform a number of tasks with one Arduino board, pushing the limits of program executable space.

There are two parts to this:
One is the creation/derivation/storage of the digital representation of a sine wave. The other is the conversion of the digital representation of a sine wave to an analog voltage (if I understand what you want).

The easiest way to obtain the digital representation of a sine wave is a lookup table. Precompute the digital values, and store them in an array. Simple. It is up to you to decide how much resolution (both in vertical accuracy/number of bits and horizontal accuracy/number of samples) you require.
It is also possible to compute the values directly. There are a number of ways of doing this, but be aware that using floating point math on the Arduino is very slow and space-intensive. You may want to look at CORDIC for one possible solution to this.

Next is the conversion to analog. You are right, PWM is one way to do this, and one of the easiest as far as external components go: you only need an RC filter to smooth the PWM. However, PWM is limited in resolution, and performs poorly when your wave frequency becomes a significant fraction of your PWM frequency. Also, the Arduino doesn't run very fast, so your PWM frequency is limited.
Other DAC solutions (there are many many many, so I'm not going to go in depth on this):

R2R DAC: simple to construct, but requires precision resistors for decent resolution, limited in resolution, and requires many IO pins.
"proper" DAC: an I2C/SPI DAC can give you far better performance, but you will have to learn how to communicate with it. And it's going to be more expensive, and involve several components.

However, this route seems to me quite long, what other options do I have?

I'm not sure what you mean by "quite long", but this is pretty straightforward. For example, here's how I'd go about it:

store a sine wave in a lookup table
set up an interrupt to trigger at regular intervals
in the interrupt, pull a value from the lookup table and write it to PWM

You can now vary the frequency of your sine wave by either adjusting your interrupt interval, or adjusting the increment of your LUT position. You can vary the amplitude by simply multiplying the LUT values by a variable.
This is quite straightforward.

I meant that using the PWM option would be longer to implement compared to something easier such as a lookup table as you suggested. I think the lookup table option you suggested is exactly what I was looking for. It is fast and provides a quick way to tune frequency. Thanks.

You still need both. And the PWM option is very difficult to implement, at most, you'll need to learn how interrupts work, and how PWM works, which might be a lot of work, but should be worthwhile if you're interested in Arduino in general.

@uint128_t: Did you mean "not very difficult..."?

@JRobert I did, thank you. OP: PWM is not very difficult.

You can get a very fast, accurate, and compact sin(theta) function using a simple table of values.  Just pull the code you need from the cordic.c here: https://people.sc.fsu.edu/~jburkardt/c_src/cordic/cordic.html.  C runs in Arduino sketches almost out of the box.  You may or may not need some things from the cordic.h.  That's why I said "almost".  The cordic_prb.c test file has a function test002() that shows you how to call the sine function.
Because the Uno does not have a real D-to-A converter, you will only get a rectangular wave that has digital noise over the primary harmonic.  That's the down side of the pulse width modulation of the lower end Arduino chips.  You will need a filter on the analog output if you need to remove the higher frequency noise harmonics.

I found that the Mozzi sinewave.ino demanded more and more include files during compile efforts, and once these (easy) problems were resolved, it ended up with horrific compile errors due to something missing in the code. NBG for a "C" dummy like me!

Douglas, So did I (have endless trouble) with Mozzi. It was said elsewhere in stack exchange that I might not have picked up on all the include files. If I solve in 2017 I'll post the solution!

Am also a C dunmy

You could look at.          http://interface.khm.de/index.php/lab/interfaces-advanced/arduino-dds-sinewave-generator/     which gives badly commented code and a PWM output on a digital pin. You need a low-pass filter to clean up the signal & reveal the sinewave. I still don't understand how the interrupt works . . .

Actually this code although it works (I think) is possibly the worst example of coding I have ever seen. Sorry!


text:
Sleep and Wake Arduino according to LDR interrupt
I have to sleep the system in the night and have to wake the system in day time. I am using LDR to get input. LDR input is connected to interrupt pin 0 of Arduino Uno.
Here is my code.
#include <avr/sleep.h>
int led =13;
int triggerPin = 2;

void wakeUpNow()
{

}

void setup()
{
pinMode(triggerPin, INPUT);
pinMode(led, OUTPUT);
attachInterrupt(0, sleepNow, LOW);
}

void loop()
{
digitalWrite(led, HIGH);;
delay(1000);
digitalWrite(led, LOW);
}

void sleepNow()
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
attachInterrupt(0,wakeUpNow, RISING);
sleep_mode();
sleep_disable();
detachInterrupt(0);
}

Cannot we attach two function in a interrupt?
Edited
The following code works perfectly. I want to replace the conditional check with interrupt.
#include <avr/sleep.h>
int led =13;
int wakePin = 2;

void wakeUpNow()
{
delay(100);
}

void setup()
{
pinMode(wakePin, INPUT);
pinMode(led, OUTPUT);
//attachInterrupt(0, sleepNow, LOW);
}

void loop()
{
digitalWrite(led, HIGH);;
delay(1000);
digitalWrite(led, LOW);

if(digitalRead(wakePin)==LOW)
  sleepNow();

}

void sleepNow()
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
attachInterrupt(0,wakeUpNow, RISING); function
sleep_mode();
sleep_disable();
detachInterrupt(0);
}

I want to replace `
if(digitalRead(wakePin)==LOW)
  sleepNow()

with`
attachInterrupt(0, sleepNow, LOW);

Please let me know how I can do that.
Thank you.

Looks to me like you're attaching an interrupt and then immediately detaching it. Could you explain why?

After attach the interrupt, it goes to sleep. When it wake up from sleep, it detach from the interrupt.

I want to replace the conditional check with interrupt.

Why? If it is awake it might just as well be testing the pin as doing anything else.
If you make it an interrupt, in the ISR interrupts will be off. Then if you go to sleep it will never wake.
So, your current design is the correct one, except:
attachInterrupt(0,wakeUpNow, RISING); function

What is function doing there?

The function is not necessary. The normal interrupt automatically wakes up the system.  Is that so?

But we have to add the interrupt to wake up the system when LDR gives output high. Isn't it? Otherwise how will the system wake up?

Yes, you wake when the LDR goes high. But why do you want to have an interrupt when it goes LOW? It is already awake.


text:
Can I connect a camera to an arduino mini?
I was wondering if it was possible to connect a camera like this onto an Arduino mini and have the Arduino save video and audio to a micro SD card.

Not really (at least, not with any appreciable quality). Basically, the bandwidth involved is simply too much for the Arduino's relatively slow 16MHz core speed. You might be able to periodically capture greyscale lowres frames, but capturing the full 1280x960 resolution at any decent framerate is basically impossible.
If you want to find Arduino projects that involve capturing video like this, the search term is arduino composite video input. There are many projects out there that interface the Arduino with a composite input, but none that I know of that can capture full video. Consider the following: your Arduino runs at 16 MHz. If you were to handle 640x480 greyscale video (1 byte per pixel), that would be a data bandwidth (disregarding signal bandwidth) of 640*480*30 = 9216000 bytes/second. That's a pretty tall order: even if you could process each pixel in two (single cycle) instructions with no overhead, you still wouldn't have enough processor bandwidth.
If all you want to do is record composite video to an SD card, there are far easier options out there, search composite video recorder sd.


text:
MPU9250 - Calibration Not Saved with RTIMULib EEPROM Issues
I'm using the MPU9250 and the RTIMULib to perform sensor fusion, however, when I run ArduinoMagCal, and save the calibration, and follow that with running the main ArduinoIMU it claims the calibration file is not saved, and there is no data to use. I'm trying to determine why this is - I have tried the other MPU9250 libraries without luck, as this one is working on my setup (Arduino Micro -> eventually NodeMCU).
Repo : https://github.com/maxouille/RTIMULib-Arduino
ArduinoMagCal
////////////////////////////////////////////////////////////////////////////
//
//  This file is part of RTIMULib-Arduino
//
//  Copyright (c) 2014-2015, richards-tech
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
//  Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
//  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
//  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include <Wire.h>
#include "I2Cdev.h"
#include "RTIMUSettings.h"
#include "RTIMU.h"
#include "CalLib.h"
#include <EEPROM.h>

RTIMU *imu;                                           // the IMU object
RTIMUSettings settings;                               // the settings object
CALLIB_DATA calData;                                  // the calibration data

//  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

#define  SERIAL_PORT_SPEED  115200

void setup()
{
  calLibRead(0, &calData);                           // pick up existing mag data if there

  calData.magValid = false;
  for (int i = 0; i < 3; i++) {
    calData.magMin[i] = 10000000;                    // init mag cal data
    calData.magMax[i] = -10000000;
  }

  Serial.begin(SERIAL_PORT_SPEED);
  Serial.println("ArduinoMagCal starting");
  Serial.println("Enter s to save current data to EEPROM");
  Wire.begin();

  imu = RTIMU::createIMU(&settings);                 // create the imu object
  imu->IMUInit();
  imu->setCalibrationMode(true);                     // make sure we get raw data
  Serial.print("ArduinoIMU calibrating device "); Serial.println(imu->IMUName());
}

void loop()
{
  boolean changed;
  RTVector3 mag;

  if (imu->IMURead()) {                                 // get the latest data
    changed = false;
    mag = imu->getCompass();
    for (int i = 0; i < 3; i++) {
      if (mag.data(i) < calData.magMin[i]) {
        calData.magMin[i] = mag.data(i);
        changed = true;
      }
      if (mag.data(i) > calData.magMax[i]) {
        calData.magMax[i] = mag.data(i);
        changed = true;
      }
    }

    if (changed) {
      Serial.println("-------");
      Serial.print("minX: "); Serial.print(calData.magMin[0]);
      Serial.print(" maxX: "); Serial.print(calData.magMax[0]); Serial.println();
      Serial.print("minY: "); Serial.print(calData.magMin[1]);
      Serial.print(" maxY: "); Serial.print(calData.magMax[1]); Serial.println();
      Serial.print("minZ: "); Serial.print(calData.magMin[2]);
      Serial.print(" maxZ: "); Serial.print(calData.magMax[2]); Serial.println();
    }
  }

  if (Serial.available()) {
    if (Serial.read() == 's') {                  // save the data
      calData.magValid = true;
      calLibWrite(0, &calData);
      Serial.print("Mag cal data saved for device "); Serial.println(imu->IMUName());
    }
  }
}

ArduinoIMU
////////////////////////////////////////////////////////////////////////////
//
//  This file is part of RTIMULib-Arduino
//
//  Copyright (c) 2014-2015, richards-tech
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
//  Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
//  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
//  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include <Wire.h>
#include "I2Cdev.h"
#include "RTIMUSettings.h"
#include "RTIMU.h"
#include "RTFusionRTQF.h"
#include "CalLib.h"
#include <EEPROM.h>

RTIMU *imu;                                           // the IMU object
RTFusionRTQF fusion;                                  // the fusion object
RTIMUSettings settings;                               // the settings object

//  DISPLAY_INTERVAL sets the rate at which results are displayed

#define DISPLAY_INTERVAL  300                         // interval between pose displays

//  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

#define  SERIAL_PORT_SPEED  115200

unsigned long lastDisplay;
unsigned long lastRate;
int sampleCount;

void setup()
{
    int errcode;

    Serial.begin(SERIAL_PORT_SPEED);
    Wire.begin();
    imu = RTIMU::createIMU(&settings);                        // create the imu object

    Serial.print("ArduinoIMU starting using device "); Serial.println(imu->IMUName());
    if ((errcode = imu->IMUInit()) < 0) {
        Serial.print("Failed to init IMU: "); Serial.println(errcode);
    }

    if (imu->getCalibrationValid())
        Serial.println("Using compass calibration");
    else
        Serial.println("No valid compass calibration data");

    lastDisplay = lastRate = millis();
    sampleCount = 0;

    // Slerp power controls the fusion and can be between 0 and 1
    // 0 means that only gyros are used, 1 means that only accels/compass are used
    // In-between gives the fusion mix.

    fusion.setSlerpPower(1);

    // use of sensors in the fusion algorithm can be controlled here
    // change any of these to false to disable that sensor

    fusion.setGyroEnable(false);
    fusion.setAccelEnable(true);
    fusion.setCompassEnable(true);
}

void loop()
{
    unsigned long now = millis();
    unsigned long delta;
    int loopCount = 1;

    while (imu->IMURead()) {                                // get the latest data if ready yet
        // this flushes remaining data in case we are falling behind
        if (++loopCount >= 10)
            continue;
        fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
        sampleCount++;
        if ((delta = now - lastRate) >= 1000) {
            Serial.print("Sample rate: "); Serial.print(sampleCount);
            if (imu->IMUGyroBiasValid())
                Serial.println(", gyro bias valid");
            else
                Serial.println(", calculating gyro bias");

            sampleCount = 0;
            lastRate = now;
        }
        if ((now - lastDisplay) >= DISPLAY_INTERVAL) {
            lastDisplay = now;
//          RTMath::display("Gyro:", (RTVector3&)imu->getGyro());                // gyro data
//          RTMath::display("Accel:", (RTVector3&)imu->getAccel());              // accel data
            //RTMath::display("Mag:", (RTVector3&)imu->getCompass());              // compass data
            RTMath::displayRollPitchYaw("Pose:", (RTVector3&)fusion.getFusionPose()); // fused output
           Serial.println();
        }
    }
}

Lastly in the repo, you will see a CalLib folder with the CalLib.cpp program inside, wondering if it is saving to the EEPROM incorrectly?
////////////////////////////////////////////////////////////////////////////
//
//  This file is part of RTIMULib-Arduino
//
//  Copyright (c) 2014-2015, richards-tech
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
//  Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
//  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
//  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "CalLib.h"
#ifdef __SAM3X8E__

// Due version

#include "DueFlash.h"

DueFlash flash;

void calLibErase(byte device)
{
    uint32_t data = 0;

    flash.write(CALLIB_START + sizeof(CALLIB_DATA) * device, &data, 1); // just destroy the valid byte
}

void calLibWrite(byte device, CALLIB_DATA *calData)
{
    calData->validL = CALLIB_DATA_VALID_LOW;
    calData->validH = CALLIB_DATA_VALID_HIGH;

    flash.write(CALLIB_START + sizeof(CALLIB_DATA) * device, (uint32_t *)calData, sizeof(CALLIB_DATA) / 4);
}

boolean calLibRead(byte device, CALLIB_DATA *calData)
{
    memcpy(calData, CALLIB_START + sizeof(CALLIB_DATA) * device, sizeof(CALLIB_DATA));
    return calData->valid == CALLIB_DATA_VALID;
}

#else

// AVR version

#include <EEPROM.h>

void calLibErase(byte device)
{
    EEPROM.write(sizeof(CALLIB_DATA) * device, 0); // just destroy the valid byte
    //EEPROM.commit();
}

void calLibWrite(byte device, CALLIB_DATA *calData)
{
  byte *ptr = (byte *)calData;
  byte length = sizeof(CALLIB_DATA);
  int eeprom = sizeof(CALLIB_DATA) * device;

  calData->validL = CALLIB_DATA_VALID_LOW;
  calData->validH = CALLIB_DATA_VALID_HIGH;

  for (byte i = 0; i < length; i++) {
    EEPROM.write(eeprom + i, *ptr++);
    //EEPROM.commit();
  }
}

boolean calLibRead(byte device, CALLIB_DATA *calData)
{
  byte *ptr = (byte *)calData;
  byte length = sizeof(CALLIB_DATA);
  int eeprom = sizeof(CALLIB_DATA) * device;

  calData->magValid = false;

  if ((EEPROM.read(eeprom) != CALLIB_DATA_VALID_LOW) ||
      (EEPROM.read(eeprom + 1) != CALLIB_DATA_VALID_HIGH)) {
    return false;                                  // invalid data
  }

  for (byte i = 0; i < length; i++)
    *ptr++ = EEPROM.read(eeprom + i);
  return true;
}
#endif

I'm not sure if you're flashing your device, but anytime you flash an Arduino the EEPROM is cleared. This might be the issue.

There was a compilation error which was preventing me from seeing that the data was indeed being saved to EEPROM, as far as I know there are no more issues. Just be mindful if you want to test it to add this in your calibration file after the save line:
  if (imu->getCalibrationValid())
      Serial.println("Using compass calibration");
  else
      Serial.println("No valid compass calibration data");

authors: Юрий Демидов


text:
Set PWM frequency to 25 kHz
I currently can set four PWM pins to around 31 kHz with the following code:
void setup()
{
    TCCR1B = TCCR1B & B11111000 | B00000001; // Set PWM frequency for D9 & D10:
    pinMode(pwmPin9, OUTPUT); // Sets the pin as output
    pinMode(pwmPin10, OUTPUT); // Sets the pin as output

    TCCR2B = TCCR2B & B11111000 | B00000001; // Set PWM for D3 & D11
    pinMode(pwmPin3, OUTPUT); // Sets the pin as output
    pinMode(pwmPin11, OUTPUT); // Sets the pin as output
}

I found this setup somewhere, but I don't know how I can set these four PWM pins to around 25 kHz instead. How is that possible?

Do you understand how the AVR timers work?

See my page about timers.

@IgnacioVazquez-Abrams Im not familiar and I need to set those four pins to around 25kHz at the beginning . I have hurry to finish a project and I would be glad any help. The code I have sets to 31kHz. Can I modify it to 25kHz? DC motors require that freq.

@NickGammon Thanks but I really dont have enough time to study these at the moment. Could you provide me the code part to setup 25kHz. Im lost

Why four pins? Are they all going to have different duty cycles? Why not one pin and send it to four different places?

I currently can set four pwm pins to around 31kHz with the following code - I just tried your code and it did not output anything.

I need to tune their exact rpm so their duty cycles will be slightly different. How about is it possible to set 2 pins only to 25kHz?

This code can be easily adapted to set the frequency to 31400, 3920, 490, 123 or 30.6 Hz. Other frequencies would not be so simple, and will most likely involve a change in the resolution of the PWM output. Can you live with a resolution of only 41 steps? Or 80 steps but loosing the “phase correct” feature? Or 321 steps but only on pins 9 and 10?

I think the last option would be great then I use two Ard. boards. Can you help me with that part? Im not familiar

While discussing with Gerben, I just thought about a fourth possibility: You could slow down the main system clock to 8 MHz and use the three timers. You would then have 4 PWM channels at 25 kHz with 161 steps on a single Arduino Uno. The cost would be loosing the timing functions (millis(), delay() and co.), having to adjust the serial baud rates, and having the whole program run half as fast. Would that be an interesting option?

@EdgarBonet Thanks for your detailed great answers. In my current code I can control 31kHz four pwm pins. At the same same time I can use LCD screen(I use delay() here to prevent flickering) and baud-rate is 9600. So if I use your 8MHz suggestion, which baudrate should I use?

With the CPU @ 8 MHz, if you Serial.begin(19200), the actual baud rate will be 9600 bps. delay() may kind of work, but in units of 39.0625 µs.

The best material explaining PWM with the AVR timers I have found so far is the YouTube video "8. Arduino Timers and Counters" (1 h 00 m 08 s).

searched this out, it's right what I need.
How can modify it to output about 14 KHz? in fact between 11 - 19 khz OK.
Thanks

I am posting this second answer since I realized it is possible to have
4 PWM channels at 25 kHz with 161 steps on a single Arduino Uno. This
involves changing the main clock frequency to 8 MHz, which
has some side effects since the whole program will run half as fast. It
also involves reconfiguring the three timers, which means loosing the
Arduino timing functions (millis(), micros(), delay() and
delayMicroseconds()). If these trade-offs are acceptable, here is how
it goes:
void setup()
{
    // Set the main system clock to 8 MHz.
    noInterrupts();
    CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
    CLKPR = _BV(CLKPS0);  // divide frequency by 2
    interrupts();

    // Configure Timer 0 for phase correct PWM @ 25 kHz.
    TCCR0A = 0;           // undo the configuration done by...
    TCCR0B = 0;           // ...the Arduino core library
    TCNT0  = 0;           // reset timer
    TCCR0A = _BV(COM0B1)  // non-inverted PWM on ch. B
        | _BV(WGM00);  // mode 5: ph. correct PWM, TOP = OCR0A
    TCCR0B = _BV(WGM02)   // ditto
        | _BV(CS00);   // prescaler = 1
    OCR0A  = 160;         // TOP = 160

    // Same for Timer 1.
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1  = 0;
    TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
        | _BV(COM1B1)  // same on ch. B
        | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
    TCCR1B = _BV(WGM13)   // ditto
        | _BV(CS10);   // prescaler = 1
    ICR1   = 160;

    // Same for Timer 2.
    TCCR2A = 0;
    TCCR2B = 0;
    TCNT2  = 0;
    TCCR2A = _BV(COM2B1)  // non-inverted PWM on ch. B
        | _BV(WGM20);  // mode 5: ph. correct PWM, TOP = OCR2A
    TCCR2B = _BV(WGM22)   // ditto
        | _BV(CS20);   // prescaler = 1
    OCR2A  = 160;
}

void loop()
{
    analogWrite( 3,   1);  // duty cycle = 1/160
    analogWrite( 5,  53);  // ~ 1/3
    analogWrite( 9, 107);  // ~ 2/3
    analogWrite(10, 159);  // 159/160
}

Unlike the other answer, this does not need a modified version of
analogWrite(): the standard one will work fine. Only care should be
taken that:

The value written should be between 0 (meaning always LOW) and 160
(always HIGH), inclusive.
Only pins 3, 5, 9 and 10 are available. Attempting to analogWrite()
to pins 6 or 11 will not only fail to deliver a PWM output, it will
also change the frequency on pin 5 or 3 respectively.

Been very long time and now I'm stuck with the same thing with Arduino Due which uses another processor. I would be glad if you hae any input here https://arduino.stackexchange.com/questions/67053/trouble-with-setting-the-pwm-frequency-for-arduino-due

You can configure Timer 1 to cycle at 25 kHz in phase correct PWM mode, and use it's two outputs on pins 9 and 10 like so:
// PWM output @ 25 kHz, only on pins 9 and 10.
// Output value should be between 0 and 320, inclusive.
void analogWrite25k(int pin, int value)
{
    switch (pin) {
        case 9:
            OCR1A = value;
            break;
        case 10:
            OCR1B = value;
            break;
        default:
            // no other pin will work
            break;
    }
}

void setup()
{
    // Configure Timer 1 for PWM @ 25 kHz.
    TCCR1A = 0;           // undo the configuration done by...
    TCCR1B = 0;           // ...the Arduino core library
    TCNT1  = 0;           // reset timer
    TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
           | _BV(COM1B1)  // same on ch; B
           | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
    TCCR1B = _BV(WGM13)   // ditto
           | _BV(CS10);   // prescaler = 1
    ICR1   = 320;         // TOP = 320

    // Set the PWM pins as output.
    pinMode( 9, OUTPUT);
    pinMode(10, OUTPUT);
}

void loop()
{
    // Just an example:
    analogWrite25k( 9, 110);
    analogWrite25k(10, 210);
    for (;;) ;  // infinite loop
}

Writing a value of 0 with analogWrite25k() means the pin will be
always LOW, whereas 320 means always HIGH. The regular analogWrite()
should almost work, but it will interpret 255 the same as 320 (i.e.
always HIGH).
This code assumes an Arduino Uno or similar board (ATmega168 or 328 @
16 MHz). The method used here requires a 16-bit timer, and thus it
uses Timer 1 as it's the only one available on the Uno; that's why only
two outputs are available. The method could be adapted to other
AVR-based boards with a 16-bit timer. As Gerben noted, that timer should
have a corresponding ICRx register. There are 4 such timers on the
Arduino Mega, each with 3 outputs.

It might be useful to explain that this method only works for timer1, as the other timers don't have a ICRx register. At most, you can only have one PWM pin per timer, for timers 0 and 2.

@Gerben: Don't all the 16-bit timers have that register? At least on the Mega they do.

Yes, but only timer1 is 16-bit  on the ATMega328. The rest are 8-bit. And  the OP wants 4 PWM output, and your solution only provides 2. Or am I mistaken?

@Gerben: No, you are right. I just say that requiring ICRx seems to be redundant with requiring the timer to be 16-bits. For the Uno and Mega at least, not sure about other AVR-based Arduinos. The OP understand this only provides 2 PWM channels: see my comment on his question and his answer.

On the ATMega328 (which the OP is using) only timer1 has the ICRx register. For the others you'd have to use OCRxA as TOP, which will make it impossible to use PWM on the OCxA pin. The OP said he/she was okay with only two PWM pins, but then says he/she would be using 2 Arduinos. It should still be possible to do with only 1 Uno, if the OP's willing to loose millis and delay.

@Gerben: Only one Uno? Are you talking about the other two options I proposed (i.e. setting the prescalers to 8)? Oh, one could also change the frequency of the main clock and have 161 steps, I hadn't though about that one. Is that what you have in mind?

I wasn't really following the main comment thread. I was indeed talking about your 41 step alternative. (I'm not sure if the OP really needs more thatn 41 steps for RPM control.)

@Edgar Bonet
I am trying to follow this and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4; I dont see any success; could you please help?

@techniche: 1. Works for me. Maybe you forgot to set COM4C1 in TCCR4A? 2. If that's not the problem, then read How do I ask a good question?, then update your question by including your full source code and clearly stating what you expect the program to do and what it does instead (“I dont see any success” is not considered a valid problem statement).

@EdgarBonet - thanks a lot for the response and help; I am able to generate the pwm signal and someone else verified it with an alpine 64 gt fan and it seems to work; its not working with the fan I have https://www.amazon.in/StorinTM-CPU-Cooler-Cooling-Connector/dp/B06XJV1SH8/ It is a standard CPU fan with 4 wires and its infact used a lot; could it be an issue with the fan and the pwm wire is just for show off?


text:
How can I understand the circuit diagram for Arduino Starter Kit Project 4?

I have acquired the arduino starter kit project book, and the explanations seem at times confusing and difficult to understand.
Concerning the above circuit diagram, the book states (I am translating from French): "The resistor and the photoresistor are in series and together they divide up the voltage. The voltage at the point where they meet is proportional to the ratio of their resistances, according to Ohm's Law."

What does "the voltage at the point where they meet" mean? The voltage/ p.d. is always supposed to be across something, e.g. a certain component. This statement makes no sense to me at all.
The above misunderstanding leads on to me not understanding what the input pins A0-A2 actually receive. I understand that they receive a voltage, but don't know across what. Also, if the voltage inputs from these pins are used later on, are they digital? (these pins have an analogue-digital converter).

The important thing to remember, which will help you understand everything else, is that voltage is measured with respect to another point.
In this (and almost every) case it is measured with respect to ground. So when you say the voltage at point X is Y volts you are actually saying that the difference in voltage between point X and GND is Y volts.
So on your schematic A0 measures the difference in voltage between it's IO pin (the junction between the 10KΩ resistor and the LDR) and ground. And looking at it, what is between its IO pin and ground? The 10KΩ resistor. So it is actually the voltage across that resistor that you are measuring.
Doing the sums:
Assume there is enough light falling on the LDR to make it have a resistance of 5KΩ.  Current flows through both the LDR and the 10KΩ resistor in series, so it has a total resistance of (10,000 + 5,000) 15KΩ. With 5V across the whole lot (5V -> LDR -> 10KΩ -> GND) you get:
I = V/R = 5/15,000 = 0.000333... or 333µA.

333µA flowing through 10KΩ drops how much voltage?
V=RI = 10,000 × 0.000333... = 3.333...V

So A0 would be measuring 3.333V at that point.
Now, you turn out the lights, and the resistance of the LDR rises to, say, 50KΩ. What happens to those sums now?  Well, let's look:
Total resistance = 50,000 + 10,000 = 60,000Ω
I=V/R = 5/60,000 = 0.00008333...
V=RI = 10,000 × 0.00008333... = 0.8333...V

The formulae can be simplified into just the ratio of the two resistances:
           R2
Vout = --------- × Vin
        R1 + R2

So that is, with the lights on:
        10,000
Vout = --------- × 5 = 0.666... × 5 = 3.333...
        15,000

And with the lights on:
        10,000
Vout = --------- × 5 = 0.1666... × 5 = 0.8333...
        60,000

From that measured voltage, of course, you can then calculate what the resistance of the LDR must have been at the time. Rearranged the formula looks like:
      R2 × Vin
R1 = ---------- - R2
        Vout

Plug in the numbers for the voltage with the lights on:
      10,000 × 5              50,000
R1 = ------------ - 10,000 = -------- - 10,000 = 5,000Ω
       3.333...              3.333...

The kind of circuit is known as a Voltage Divider or Potential Divider and you can read more about them here: https://en.wikipedia.org/wiki/Voltage_divider

I think what it means is that A0 = (5V / (Photo Resistor + 10K)).  Since the Photo Resistor will vary the voltage you get at A0 will be proportional to the light.  So by rearranging the formula above (I'm no good at doing that so you are on your own) you can convert the number received by A0 into the resistance that the photo resistor as applying and presumably turn that into Lux (?).
The analog pins report a number between 0 and 1023.  I can never remember if this equates to receiving a voltage of 0 - 5V or 0 - 2.5v.  Either way it is a linear conversion, so you can use (5V/1024)*reading to work out what the voltage at the pin is (or (2.5C/1024)*Reading).

Hope that helps.

The analog inputs of the arduino can't read resistances. They read voltages and compare them with a reference voltage. They give you a number between 0 and 1023 so the read voltage is 1/1024 of the reference voltage.
The configuration of the LDR and the resistor is called a voltage divider. It is needed to get a voltage that the analog pin can read.
The intersection of the LDR and the resistor is where you can measure that voltage (or connect it to the analog pin of the arduino).
More info about this subject was already given in this question:
Why do you need a second resistor when using a photoresistor/LDR?
Wiki page about voltage dividers and the relevant formulas
https://en.wikipedia.org/wiki/Voltage_divider


text:
How to properly receive data from accelerometer @ arduino in processing and map it?
I'm busy making a project where my accelerometer @arduino can controle a ellipse @processing
But the problem is, it doesn't work. With the code I have now, I can receive the data from the accelerometer in processing. But my map function doesn't seem to work because with my code, the ellipse doesn't move at all. When i want to map the val (string) it says it must be a float to be mapped. I've tried to convert the string into a float but it doesn't work at all..
Hope someone can help me out!
My arduino Code:
#include <Wire.h>
#include <Adafruit_MMA8451.h>
#include <Adafruit_Sensor.h>

int waardeX;
int waardeY;

Adafruit_MMA8451 mma = Adafruit_MMA8451();            //maak object acceleromter aan

void setup(void) {
  Serial.begin(9600);                                 //begin Seriële verbinding
  Serial.println("Adafruit MMA8451 test!");           //print waardes accelerometer

  if (! mma.begin()) {                                //mma.begin() om de sensor te herkennen.
    Serial.println("Couldnt start");                  //"MMA8451 found!" bij goed signaal, "Couldnt start" bij slecht signaal
    while (1);
  }
  Serial.println("MMA8451 found!");

  mma.setRange(MMA8451_RANGE_2_G);                    //lees range van 2_G (voor relatief slome bewegingen)

  Serial.print("Range = "); Serial.print(2 << mma.getRange());
  Serial.println("G");

}

void loop() {

  // Read the 'raw' data in 14-bit counts
  mma.read();                                         //lees rauwe data accelerometer uit
  Serial.print("X:\t"); Serial.print(mma.x);          //lees x waardes
  Serial.print("\tY:\t"); Serial.print(mma.y);        // lees y waardes
  Serial.println();                                   //print de waardes met een delay van 500ms
  delay(500);

  /* Get a new sensor event */
  sensors_event_t event;

  Serial.write(waardeX);
  Serial.write(waardeY);
}

Processing code:
import processing.serial.*;

Serial myPort;                                   //Maak Serial object aan
String waardeX;                                      //Ontvangen data van serial poort.

//int waardeX;
int waardeX1;
int waardeY2;
int waardeY;

void setup() {
  printArray(Serial.list());
  String portName = Serial.list()[0];            //0 is mijn Arduino poort.
  myPort = new Serial(this, portName, 9600);     //open de poort. Zelfde als serial.begin(9600) bij arduino zodat arduino en processing hetzelfde communiceren.

  size(500, 500);                                //Grootte van het scherm
}

void draw() {
  background(255);                               //Achtergrondkleur
  ellipse(waardeX1, waardeY, 20, 20);               //20,20 is grootte/breedte cirkel
  fill(200, 10, 100);                                       //maak het bolletje zwart

  waardeX1 = (int)map(waardeX, 4000, -4000, 0, 500);        //waardeX mappen naar waa
//  waardeY = (int)map(waardeY2, -4000, 4000, 0, 500);

  {
    if ( myPort.available() > 0)
    {  // Als de data beschikbaar is:
      val = myPort.readStringUntil('\n');         //Lees het en zet het in val
    }
        println(waardeX); //print it out in the console
  }
}

Hi, Welcome to SE Arduino.  I'm sorry but, its really difficult for me to follow your code.  You seem to be mixing the use of waardeX and waardeX1 and using values before you have calculated them, meaning they are old values.  Can I suggest you put this code on the shelf and start a new minimal program that creates an ellipse at 10, 10, 20, 20 and 20, 20, 20, 20 and 30, 30, 20, 20 and map those.  If they work as expected then we now its not the functions that are the problems, just the data.  (Also a simple program like that will help people understand your code better, hopefully).

The problem you are facing is that you are sending the string:
X:⇥23.87⇥Y:⇥11.34

and trying to interpret that as a single number. It's just not going to happen. There's two numbers and two labels there.
Instead you are going to have to parse the string to get at the individual components.
You might want to look at the java String.split() function to convert the string into an array of 4 items, then you can use the second and fourth slices (slices 1 and 3 since it's zero-based) and convert them to floats.


text:
MPU6050 hanging/freezing
I am really short of interrupt pins on my Arduino because I have a project that already uses a lot of Arduino pins and to read DMP data from MPU6050 you always have to use an interrupt pin. I searched A LOT in the internet and many people says it's impossible to retrieve DMP data without interrupt pin. Some people also said the only way to do that would be if I could reverse engineer the MPU6050 code (which I don't know how to do).
But today, playing with MPU6050 I could finally get all of its DMP data without the interrupt pin, you just have to connect 4 pins (VCC, GND, SCL and SDA). Upload the code below to your Arduino and see that it works!
#include "MPU6050_6Axis_MotionApps20.h"
MPU6050 mpu;
uint16_t packetSize;
uint16_t fifoCount;
uint8_t fifoBuffer[64];
Quaternion q;
VectorFloat gravity;
float ypr[3];

void setup() {
  Wire.begin();
  TWBR = 24;
  mpu.initialize();
  mpu.dmpInitialize();
  mpu.setXAccelOffset(-1343);
  mpu.setYAccelOffset(-1155);
  mpu.setZAccelOffset(1033);
  mpu.setXGyroOffset(19);
  mpu.setYGyroOffset(-27);
  mpu.setZGyroOffset(16);
  mpu.setDMPEnabled(true);
  packetSize = mpu.dmpGetFIFOPacketSize();
  fifoCount = mpu.getFIFOCount();

  Serial.begin(115200);
}

void loop() {
  while (fifoCount < packetSize) {
    fifoCount = mpu.getFIFOCount();
  }

  if (fifoCount == 1024) {
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));
  }
  else {
    if (fifoCount % packetSize != 0) {
      mpu.resetFIFO();
    }
    else {
      while (fifoCount >= packetSize) {
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        fifoCount -= packetSize;
      }

      mpu.dmpGetQuaternion(&q, fifoBuffer);
      mpu.dmpGetGravity(&gravity, &q);
      mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

      Serial.print("ypr\t");
      Serial.print(ypr[0] * 180 / PI);
      Serial.print("\t");
      Serial.print(ypr[1] * 180 / PI);
      Serial.print("\t");
      Serial.print(ypr[2] * 180 / PI);
      Serial.println();
    }
  }
}

There is only one problem: Intermittently the Arduino hangs in the getFIFOBytes function for no reason. I am pretty sure it's a bug because when you call too many times getFIFOBytes for some reason the Arduino freezes.

Actually, removing the interrupt completly solves it all!

I added a mpu.resetfifo after de mpu.dmpGet.... lines.
Since then 2 different systems work for at least 5 hours and with the original interupt pin attached


text:
WiFi thermometers: save different location string as const across many devices
I've built a very simple WiFi thermometer out of an Adafruit ESP8266 HUZZAH breakout board and a TMP36 temperature sensor. I have it reporting the temperature over wifi to my computer which will be storing the data in a database for monitoring purposes. I'd like to make multiple of these devices and place them around the house. My question: I currently have the location of the board as a const char* on the board itself. Doing this for multiple devices is just a bad idea and a nightmare to manage. Is there some way of setting a location variable on the board that will persist across shutdowns? Or am I coming at the problem from completely the wrong direction?

Why not just use the (unique) IP address of each module to identify it and map that to a name on the PC?

I was thinking that would solve the issue, but I'd rather have the resolution contained within this system rather than relying on configuring my router as well.

With a set of DIP switches or jumpers on some of the GPIO, you could encode a unique number for each one - 16 of them with 4 I/Os f/ex. The same code could run on all of them, sample the unique ID  report it along with the temperature. Let the PC-side map IDs to locations.

I like this. Your answer gave me an idea though. I can get a MAC address from the breakout board. Would the MAC ever change? If not, I could send the MAC of the board along with the other data and do some server side mapping with the MAC.

I don't know how the Lua firmware works, but the AT+ interpreter firmware includes commands to set the chip's MAC address, so, yes, it can be changed, but that's a change you would have to make, not one that I could ever imagine would be programmed to happen without you taking explicit action.

The MAC address comes from the ESP8266 chip, not from the breakout board

@JaromandaX: Yes, that's correct. And ?

Just clearing up @Taelsin's misconception that the breakout board has something to do with the MAC address, if that's OK with you


text:
Do I need more voltage to close this circuit?
I'm hacking together a RF-controlled garage door opener. I'm tapping the "receiving" end in to the push button wires.
When the two wires touch, it toggles the garage door motor.
I'm trying to basically "close" this circuit through a 5V Trinket Pro with...
pinMode(A0,OUTPUT); in setup and digitalWrite(A0,LOW); in the loop.
Using the multimeter, it would seem that the wires for the push button are normally closed (I think that's correct) as I get a 15v read on the multimeter when I check the current.
When I touch the wires, the current drops to 0.
My understanding was that the digitalWrite(A0,LOW); would basically "complete" the circuit, but it doesn't seem to do anything.
So, my question is: Given I've only got 5v running through the Trinket Pro, is that not enough to toggle the garage door circuit given it's putting out  15v in it's NC state?
If that's the case, is there some other way around that without needing to push 15v of power?

The Trinket really doesn't want to see 15v across one of its I/O pins. You'll do better using a solid-state (SSR) or mechanical relay to close the 15v motor-start circuit, one that can be activated by the 5v output of the Arduino pin.
Update:
A relay has 4 specs that you need to consider up front:

The coil (or switching input of a SSR) voltage, and
The coil (or switching input) current;

These are what the Arduino or an add-on switching circuit will have to drive. And:

The contact max voltage, to limit arcing when they open
the contact max current, to limit them heating,

Or, in the case of an SSR, to prevent letting out the Magic Smoke that makes them work.
If you use a relay you'll need a driver circuit between the Arduino pin and the relay, with a snubber - a diode that grounds the reverse voltage "kickback" from the relay coil when you open its circuit - also to protect the Magic Smoke in your Arduino.
You're hacking into your remote "clicker", not the garage-door tractor itself, right? If that's the case, just about anything with a 5v coil 15v+ contacts will do. The remote button only has to switch a tiny transmitter on/off. If you do need to hack into the tractor, you'll want to find out what's behind its receiver terminal. It's probably not the motor but another relay, but....
A ready source of such a relay is your/another garage door remote receiver. It has a relay in it that is already doing that job.

Is there a certain type of relay I'm looking for in regards to the 5v/15v pairing?


text:
ADXL345 I2C setup not returning anything
My hookup is like this:
GND - GND  VCC - 5V  CS - 5V  SDO - GND  SDA - A4  SCL - A5
Here is the code:
#include <Wire.h>
#include <ADXL345.h>

ADXL345 accelerometer;

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

  // Initialize ADXL345
  Serial.println("Initialize ADXL345");

  if (!accelerometer.begin())
  {
    Serial.println("Could not find a valid ADXL345 sensor, check wiring!");
    delay(500);
  }
  if (accelerometer.begin())
  {

  // Values for Free Fall detection
  accelerometer.setFreeFallThreshold(0.35); // Recommended 0.3 - 0.6 g
  accelerometer.setFreeFallDuration(0.1);  // Recommended 0.1 s

  // Select INT 1 for get activities
  accelerometer.useInterrupt(ADXL345_INT1);

  // Check settings
  checkSetup();
  }
}

void checkSetup()
{
  Serial.print("Free Fall Threshold = "); Serial.println(accelerometer.getFreeFallThreshold());
  Serial.print("Free Fall Duration = "); Serial.println(accelerometer.getFreeFallDuration());
}

void loop(void)
{
  delay(50);

  // Read values for activities
  Vector norm = accelerometer.readNormalize();

  // Read activities
  Activites activ = accelerometer.readActivites();

  if (activ.isFreeFall)
  {
    Serial.println("Free Fall Detected!");
  }
}

It comes from this Github link: https://github.com/jarzebski/Arduino-ADXL345/blob/master/ADXL345_free_fall/ADXL345_free_fall.ino
Initially, it would return "Could not find a valid ADXL345 sensor, check wiring!" in serial monitor. After messing with some wiring and changing to SPI
and back to I2C, it only returns "Initialize ADXL345".
I've added the second if() statement because it wouldn't say anything other than "Initialize ADXL345" even with the first if() statement, or with the first if() followed by an else. It should print the Free Fall Threshold and Duration but it hasn't. I have to leave and won't be back until tomorrow, so when I get back I'll try removing the checkSetup() command and maybe put something else in it's place to verify it's working. I feel like the answer is staring me in the face.
EDIT: Okay so after I finally got up from my computer for once, a thought popped into my mind and I figured the reason why checkSetup() isn't returning either string is because it's declared after setup() calls checkSetup()? Am I right? I feel like this would be the case in other languages.

Provide a link to the specific module you have; are you sure that I2C pullups are built-in? What did you change in the wiring? You're calling begin() twice; if you want to test the return value, call it once and store the result in a variable which you can then test as often as you wish. Also try using a more popular library like Adafruit's.

Here is the link to the Sparkfun ADXL345 I have: https://www.sparkfun.com/products/9836
I've gone ahead and changed from 5v to 3.3v, have a small wire that just leads from VCC to CS, and have 2 220 ohm resistors going from 3.3v on my breadboard to SDA and SCL which have wires that go into pins A4 and A5 on my microcontroller, respectively. The microcontroller is a Sparkfun Redboard, which is the same as an Arduino Uno it seems. I've removed the second begin(), and now it will say "ADXL345 Initialize" followed by "Free fall Threshold = " but no value and that's it.

You may have damaged the chip with 5 V already. Sparkfun didn't include a regulator in their breakout. Your pull-ups are also too small; significant current flows when the I2C lines are pulled low. Use two 4.7k or 10k resistors instead. Assuming your Redboard is just like the Uno, connect pin 2 to the INT1 pin of the breakout, to make use of the interrupt capabilities. You also need to call attachInterrupt() and register a handler.
However, you bought this module from Sparkfun, as well as your Redboard. You should first follow their tutorial and library before trying any others. Theirs is SPI-based though. If you must use I2C, try out the Adafruit library.


text:
Real time Cross Correlation...?
I saw the one of your Answer that dated the 13th May 2015, i want to cross- correlate the vibration signal (with Predefined Signal) to remove the unwanted signals.But i want to do that real time so can we use the Arduino or have to use the Another platform. please advise .
Kaveendra Sampath

What answer? Link please. Please read How do I ask a good question?.

You will have to be a lot more specific if you want any kind of useful answer. What type of Arduino? Sampling rate? Length of the reference signal? What does that reference signal look like? What information do you want to extract from the cross-correlation?

Please add more details to your question. It is not really answerable as you've written it.

The way worded your question only allows for this type of answer: "If you are only cross correlating a few bytes then you might be able to use an Aruduino Uno at low sampling speeds.  If you want to do more then you need a more powerful Arduino like a Intel Galileo."

authors: Евгений Макжанов