# Question
Title: how to send large strings (> 100 characters) from arduino serial monitor
I am a newbie to arduino programming. I wish to send big strings which are in range of 100 to 1000 characters to my arduino uno. I saw that arduino cannot read more than 63 characters at a time.

The strings can be received in parts (~40 characters) which will be processed by my program and few minutes later they will get deleted. Then another ~40 characters will be received and the process continues till all the characters are received.

Can you please help me with this. If the question is not clear, you're free to ask in the comments. Thanks in advance :-)

# Answer
> I saw that arduino cannot read more than 63 characters at a time.

Not strictly true. The Arduino core HardwareSerial library has a 64 byte buffer, so it can only *buffer* up to 64 characters. If your sketch is reading the characters from the buffer whilst you are sending the characters from your PC then that limit is irrelevant. As long as you are reading the characters as fast as they are coming in.

Serial is actually quite slow (on the scale of things) and unless you're doing silly things like using `delay()` or long blocking loops, then reading the data fast enough is not that big a problem. If you do need more time the simplest way is just to slow down the serial data somewhat - i.e., use a lower baud rate. The slower you send the data the longer you get between each character arrives to do things.

For strings the size you are on about you are probably best off processing the data on the fly rather than storing it all then post-processing it - simply because the Arduino doesn't have much RAM, so storing large strings isn't always an option.
> 2 votes

---
Tags: arduino-uno, serial, sketch, string
---


title: How to convert String to Double?

text:
# Question
Title: How to convert String to Double?
I found the .toFloat() but that's not accurate enough.

```
String StrEx = "57.10598";
float FloatEx = StrEx.toFloat();

Serial.println(String(FloatEx)); //outputs 57.11
Serial.println(StrEx);           //outputs 57.10598

```

# Answer
It is a common misconception that, because when you print a float you only get 2 decimal places, that the float only has 2 decimal places.

That is not true. A float doesn't have a number of decimal places - that is how it gets its name - floating point: the decimal point floats around as needed.

The problem is actually that, by default, all the Arduino print and string conversion functions are set to 2 decimal places. Unless you specify the number of decimal places you want to print (or convert to) you get 2 decimal places.

By specifying 5 decimal places when you print or convert to a string you get 5 decimal places. It still won't always give you exactly the same number, but that is because a 32-bit float cannot store all possible numbers, so some are only an approximation. It's still a whole lot more accurate than 57.10598 -\> 57.11 though.
> 2 votes

---
Tags: string
---


title: Arduino Data to Cloud without shield []

text:
# Question
Title: Arduino Data to Cloud without shield []
I am performing basic analogue read like temperature and LDR, reading the data serially, but I would like to deploy it online to cloud platforms like (Plotly, Xively, ThingSpeak, or DataSparkFun). Is that feasible? Thank you in advance.

# Answer
Without a shield? Yes, it's possible.

You send it serially to your computer as you are doing now. Then you write some software for your computer to read that data serially and send it on to your chosen web service.

Can the Arduino magically send data to the internet by itself without you investing in a network connection of some form (WiFi shield, Ethernet Shield, etc)? No, of course not. If it could there would be no market for the network shields, and so they wouldn't exist.
> 1 votes

---
Tags: arduino-uno, shields, datalogging
---


# Question
Title: Is there a way to set an interrupt to go off after a certain period of time?
I'm trying to save power by putting my device to sleep once it has run through the code once and turn it back on every 33 milliseconds. So basically, if the code finishes executing in 20 milliseconds the device can go to sleep for the remaining 13 milliseconds and it will be turned on by the interupt which is set to go off every 33 milliseocnds.

According to the documentation an interrupt is based on a change to the pin state, but I'm sure there must be a way to base it on time. If there isn't then is there a way to set the total time that a device sleeps? The sleep function seemed to just turn the device off, but can it be given a parameter to just turn off for a certain amount of time?

# Answer
> 1 votes
The easiest way to achieve your purpose seems to be to configure a timer to fire every 33 ms, and use this interrupt to wake up the MCU. For this, you first have to choose what timer to use. On the Mega, I would rather use the 16-bit timer, but the ATtiny85 only has 8-bit timers. Next you have to choose a prescaler value (clock frequency division) among those available for that timer. The prescaler should be large enough to avoid overflowing your timer, but smaller prescaler values give better time resolution.

Then you configure the timer to run in “CTC mode” (clear timer on compare match). In this mode, it counts from zero to the value that you programmed in the `OCRxA` register (where `x` is the number identifying the timer), and then goes back to zero. This way you can get an interrupt every `OCRxA + 1` timer cycles.

In the example code below, you have to replace `x` with the appropriate timer number, and check the datasheet for the bits to set in the control registers `TCCR*`:

```
#include <avr/interrupt.h>

// Interrupt period, in prescaled clock cycles.
const uint16_t PERIOD = ...;  // or uint8_t for an 8-bit timer.

// The timer interrupt is used ONLY to wake the CPU, so there is no job
// to be done inside the interrupt service routine.
EMPTY_INTERRUPT(TIMERx_COMPA_vect);

void setup()
{
    // Disable Timer 0 interrupts.
    // Warning: this will prevent the Arduino from keeping time.
    TIMSK0 = 0;

    // Configure Timer x.
    TCCRxA = 0;            // undo the timer config done...
    TCCRxB = 0;            // ...by the Arduino core library
    TCNTx = 0;             // reset the timer
    OCRxA = PERIOD - 1;    // set the period
    TIMSKx = _BV(OCIExA);  // enable TIMERx_COMPA interrupt
    TCCRxA = ...;          // set the counting mode to CTC...
    TCCRxB = ...;          // ...and set the prescaler
}

void loop()
{
    // Sleep while waiting for the timer interrupt.
    sleep_mode();

    // Now that we have been waken up...
    do_the_job();
}

```

**Edit**: As noticed by Gerben, the Arduino core library configures Timer 0 to send periodic interrupts (one every 1024 µs), which are used for timekeeping (`millis()`, `delay()` and co.). This interrupts will wake up the MCU and prevent it from sleeping as long as you want. The simplest solution, which is implemented in the code above, is to disable the Timer 0 interrupts. The drawback is that the Arduino timekeeping functions will not work anymore.

If you need those timekeeping functions, then the proper solution is the one sketched by Gerben in his comment: set a boolean in the interrupt that can be checked in the main loop. Here is the naive implementation of this idea: `EMPTY_INTERRUPT(TIMERx_COMPA_vect);` is replaced by

```
volatile bool time_elapsed;

ISR(TIMERx_COMPA_vect)
{
    time_elapsed = true;
}

```

Then, in the main loop you sleep repeatedly until the ISR sets the flag:

```
void loop()
{
    // Warning: race condition here!
    while (!time_elapsed)
        sleep_mode();
    time_elapsed = false;

    // Now that we have been waken up...
    do_the_job();
}

```

As stated in the comment, this naive implementation suffers from what is known as a *race condition*. The problem is in the following scenario:

1. The main loop reads the value of `time_elapsed` and it turns out to be false
2. At this point the interrupt fires and the ISR sets that boolean to `true`
3. Returning from the ISR, the main loop does not test the flag again (since it just did it) and goes straight to `sleep_mode();`.

At this point the MCU ends up sleeping although it should be performing the job which is due now.

This race condition may not a be a big deal to you: The MCU will be eventually woken up by the Timer 0 interrupt no more than 1024 µs later. In some cases it *is* an issue, but fortunately there is a proper solution. It is described in the page about sleeping of the avr-libc documentation. It relies on the fact that when interrupts are disabled, then enabled again with `sei()`, the machine instruction right after the `sei()` is guaranteed to be executed before any interrupt is serviced. Then the proper way to test the flag and sleep is:

```
void loop()
{
    while (!time_elapsed) {
        cli();
        if (!time_elapsed) {
            sleep_enable();
            sei();          // interrupts enabled
            sleep_cpu();    // this will be executed before any ISR
            sleep_disable();
        }
        sei();
    }
    time_elapsed = false;

    // Now that we have been waken up...
    do_the_job();
}

```

With this version, if the interrupt fires right after the test `if (!time_elapsed)`, it will be serviced *after* `sleep_cpu()`, which will have the effect of waking the MCU right away.

# Answer
> 0 votes
There are many many kinds of interrupt. External interrupts (of the kind you use with `attachInterrupt()`) are but one.

Almost every internal peripheral in the AVR chip can generate an interrupt (or multiple interrupts in some cases). One of the most useful is the *timer interrupt* which is triggered by one of the timers when its timer has overflowed.

I am not familiar with the AVR's sleep mechanisms, but I would assume a timer interrupt can wake it from sleep - assuming the timer can run while sleeping.

You should check the documentation for the chip on your Arduino rather than relying on the (somewhat scant and basic, and often misleading) documentation on the Arduino website when it comes to doing anything low-level like this.

---
Tags: arduino-mega, sleep
---


# Question
Title: How to detect the pulse width from microphone as Input?
I'm working on a project that detects the pulse width of an audio signal, which uses a microphone as an input. The user gives 2 different types of sounds one last less 0.3 seconds and other lasting less than 0.7 seconds. I've attached the audio visualisation of the signal pic in the attachment. All want to detect is their pulse widths.

I tried Pulsein() - but as you can see that it has a variable until 0.3 or 0.7 seconds it only detect the first and most peak and returns the value which is almost zero.

But all I need is the total time taken for the pulse to rise from 0 and to variate and then become 0 this total time period is what I require. would duty cycle help ? or any other functions available to detect two different sounds in arduino ?

pulse width

# Answer
You will need some sort of interface circuit between your mic and your Arduino. Best would probably be to have some kind of external peak detection. This way the Arduino reads instantaneous wave amplitude. The other option is to only shift and scale the signal so that it fits the Arduino ADC, acquire the signal at a high enough sampling rate, and compute the instantaneous amplitude in software.

I suggest you take a look at this sound-meter program. You could use it as a basis for your own processing.

Then you just have to define a threshold and time how long the amplitude remains above that threshold.
> 1 votes

---
Tags: arduino-uno, pwm, audio
---


title: Inappropriate ioctl for device

text:
# Question
Title: Inappropriate ioctl for device
I am using an Arduino Uno and a Mac and trying to upload my code into the board. I tried uploading the program from different computers(MacBook Air and Pro) and I still have this problem.

How do I fix this? I tried downloading the FTDI driver. I went to the website that they suggested and tried following the instructions. I even followed other posts in Stack Exchange but I still cannot upload the code.

### EDIT

Programmer -\> AVRISP mkll

I am using a cable to connect to my Mac and I am using the Arduino software. The cable connected between the Arduino USB and Mac USB port.

I tried quitting and relaunching Arduino app. Once it launches I just press the upload button while my USB is plugged in. My available ports in the app are `/dev/cu.Bluetooth-Incoming-Port` and `/dev/cu.Bluetooth-Modem`

And this is the error

```
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1421": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

```

# Answer
> 7 votes
Plug your Uno into the Mac using a known good USB cable.

Go to the Apple menu -\> About This Mac -\> More Info -\> System Report

Under the USB selection (on the left) please confirm whether or not you see something like this:

You can also open a Terminal window and type:

```
system_profiler SPUSBDataType

```

Amongst other things you should see:

```
USB:

    USB High-Speed Bus:

      Host Controller Location: Built-in USB
      Host Controller Driver: AppleUSBEHCI
      PCI Device ID: 0x3b34
      PCI Revision ID: 0x0006
      PCI Vendor ID: 0x8086
      Bus Number: 0xfd

        Hub:

          Product ID: 0x2514
          Vendor ID: 0x0424  (SMSC)
          Version: 0.03
          Speed: Up to 480 Mb/sec
          Location ID: 0xfd100000 / 2
          Current Available (mA): 500
          Current Required (mA): 2

            Communication Device:

              Product ID: 0x0043
              Vendor ID: 0x2341
              Version: 0.01
              Serial Number: 9314036423335121A0B1
              Speed: Up to 12 Mb/sec
              Manufacturer: Arduino (www.arduino.cc)
              Location ID: 0xfd130000 / 8
              Current Available (mA): 500
              Current Required (mA): 100

```

Note the "www.arduino.cc" entry.

In your Arduino IDE you should see the Arduino as a tty.usbmodemfd131 (or some similar number).

If you see all that it should work.

If not, please state in what way it differs.

> Programmer -\> AVRISP mkll

The **Tools \> Programmer** menu selection is only used when you do **Tools \> Burn Bootloader** or "Upload Using Programmer. It is completely ignored when doing a standard "Upload". You should be doing an "Upload" (Command-U) not an "Upload using programmer" (Shift+Command+U). So it makes absolutely no difference what you select from the **Tools \> Programmer** menu.

# Answer
> 1 votes
I solved this problem. Maybe this post will help others.

I've come across this problem a couple of times. I literally searched for hours for the answer and ended up using several suggestions.

Both scenarios I solved are documented below as 'Scenario A' and 'Scenario B':

====================== Scenario A

Plugged in a new Arduino Uno R3 board, successfully compiled the standard "Blink" sketch. When I tried to upload it to the board, I got this message:

*Sketch uses 1,066 bytes (3%) of program storage space. Maximum is 32,256 bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes. avrdude: ser\_open(): can't open device "COM1": No such file or directory ioctl("TIOCMGET"): Inappropriate ioctl for device Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.*

The Port Options in the IDE (Tools--\> Port) only showed /dev/cu.incoming-bluetooth-port

Here's what worked:

1. Downloaded and Installed the CH340 driver
2. Removed the FTDI drivers from my mac. Apple recently installed a new utility that prevents removal of what it considers to be critical components.

The process that enforces this rule is called csrutil.

You'll have to disable this process to remove the FTDI driver. Then you'll need to re-enable it when you are done. This required a restart in recovery mode. Here's how to do that:

```
a.)  power off the mac then hold 'command'+R during the restart until the image of the apple appears.
b.)  when the screen refreshes, click on 'Utilities' menu then 'Terminal.
c.)  type csrutil disable
d.)  Hit enter
e.)  Restart  [Note:  You may be able to execute the next two commands in the terminal before restarting.  I just didn't test it that way.  If the system will allow you to, then by all means run all three commands one after the other THEN restart and you should be on your way.]

```
3. remove the FTDI drivers by opening the terminal program again and entering the following command:

```
   sudo rm -R /System/Library/Extensions/AppleUSBFTDI.kext

```

Type in your password when prompted.

4. Restore the apple csrutil by following steps a and b above. Task c will be the same EXCEPT you'll type this instead:

```
csrutil enable

```

Then follow steps d and e.

When you restart the arduino IDE, you should see a more comprehensive list of ports besides just the bluetooth port.

====================== Scenario B

This board was an import and clearly not an original Arduino/Genuino. Attempts to load sketches resulted in this lovely error:

```
    Using Port                    : /dev/cu.usbmodem1421
    Using Programmer              : arduino
    Overriding Baud Rate          : 115200

```

avrdude: ser\_open(): can't open device "/dev/cu.usbmodem1421": No such file or directory ioctl("TIOCMGET"): Inappropriate ioctl for device

There was only one Port listed in the IDE, dev/cu.Bluetooth-Incoming-Port.

It had been a while since Scenario A had occurred and since then I'd installed a few OS updates. Checked the drivers and low and behold, the darned FTDI drivers had RETURNED!!

I repeated the steps in scenario A above but the problem remained.

Then I installed an updated board configuration from arduino and it worked! Testing on the first board I'd used under scenario A were successful as well. Here's what I did:

1. In the IDE go to Tools-\> Boards -\> Boards Manager
2. I installed 'Arduino SAM Boards (32-bits ARM Cortex-M3) by Arduino version 1.6.8
3. Unplugged and replugged the USB cable into my arduino.
4. In the IDE go to Tools -\> Port. The /dev/cu.usbmodem1421 was listed as a port option. Selected that.
5. Uploaded my sketch.
6. Bask in glory of SUCCESS!

I hope this was helpful to you. I spent two days on Scenario A and 3 hours on Scenario B.

# Answer
> 0 votes
I've also had this error message when I've left another serial terminal connected to the same port the Arduino IDE is trying to use.

# Answer
> 0 votes
I got this error on my Macintosh system and the problem was that I needed to choose the correct port on the USB. Somehow it had auto-connected to a Bluetooth port which was listed under **Tools-\>Port** as `/dev/cu.Bluetooth-modem` and was my daughter's cell phone. I chose a port labeled `/dev/cu/wchusbserialfd`... and it worked fine.

---
Tags: arduino-uno
---


# Question
Title: Why does this not put my Arduino Mega to sleep?
I have the following program which is supposed to print the words "Program is on" once and then go to sleep. However it doesn't go to sleep and continues to print "Program is on" over and over again.

```
#include <avr/sleep.h>

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

void loop()
{
  Serial.println("Program is on");
  sleepNow();
}

void sleepNow()
{
  // Choose our preferred sleep mode:
  set_sleep_mode(SLEEP_MODE_IDLE);
  // Set sleep enable (SE) bit:
  sleep_enable();
  // Put the device to sleep:
  sleep_mode();
  // Upon waking up, sketch continues from this point.
  sleep_disable();
}

```

# Answer
In idle sleep, the timer interrupts will wake the processor, as Ignacio Vazquez-Abrams said in his comment.

A "higher" sleep mode works, however I had to add `Serial.flush ()` otherwise it only printed "P" because the processor goes to sleep before the serial output buffer has been emptied.

```
#include <avr/sleep.h>

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

void loop()
{
  Serial.println("Program is on");
  Serial.flush ();
  sleepNow();
}

void sleepNow()
{
  // Choose our preferred sleep mode:
  set_sleep_mode(SLEEP_MODE_PWR_SAVE);
  // Set sleep enable (SE) bit:
  sleep_enable();
  // Put the device to sleep:
  sleep_mode();
  // Upon waking up, sketch continues from this point.
  sleep_disable();
}

```

---

See my page about power savings.
> 1 votes

---
Tags: arduino-mega, sleep
---


title: Dynamicly sized array as a class member

text:
# Question
Title: 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!

# Answer
> 1 votes
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;

```

# Answer
> 2 votes
# 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 `String`s are only useful for `char`s. Arrays and pointers can be of and to anything - including `String`s and (***GASP!***) pointers! Uh oh - here we go again...

---
Tags: c++, class, array
---


# Question
Title: Servos Do Not Move to Specified Position
This code receives sine wave parameters from a serial connection, then formats and writes the sine wave positions to 8 servo motors.

The positions are successfully written to 6 of the 8 motors.

Of the two that don't work, I tried changing the motors to see if they were faulty; they are not. I changed the output pins to see if they were damaged; they are not.

I changed the order the equations are solved, and the positions are written to ensure there wasn't some bizarre timing issue. I saved a full cycle of the written positions and they output the correct numbers (i.e. the correct amplitude). You can see them here (format is "servo #" : "position"):

```
0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

```

The entire code is below. The relevant section begins after `if (Afreq > 0)` near the bottom. The positions that do not write correctly are pos\[6\] and pos\[7\]:

```
/*
This is a program that recieves sine wave parameters from a serial connection in a single string.
The string is parsed and converted into numbers, which are plugged into 8 sine equations to generate
positions for each joint of the robot.
*/

#include <Servo.h>

Servo SB, SF, HB, HF, EB, EF, KB, KF;
int iAmp, iF_offset, iB_offset, iFk_offset, iBk_offset, pos[] = {0,1,2,3,4,5,6,7};
unsigned int t = 0;
unsigned long previousMillis = 0;
float fKnee_amp, fAfreq, fPhase, fGait;

void setup(){
  //Start serial stream at 115200 baud
  Serial.begin(115200);

  //Connect servos to Arduino
  HB.attach(2);
  KF.attach(3);
  SB.attach(4);
  EB.attach(10);
  HF.attach(6);
  KB.attach(7);
  SF.attach(8);
  EF.attach(11);

  delay(3000);
}

void loop(){
  char c, buffer[10];
  String readString, amp, knee_amp, afreq, gait, phase, f_offset, b_offset, fk_offset, bk_offset;
  unsigned int sine_time = 50;

  while (Serial.available() && readString.length() < 37){
    //delay to allow buffer to fill
    delayMicroseconds(100);
    if (Serial.available() > 0){
      //get one byte from serial buffer
      char c = Serial.read();
      //creates the string "readString"
      readString += c;
    }
  }

  if (readString.length() > 36){
    //see what was received
    Serial.println("The string is: " + readString);
    Serial.println(readString.length());

    //parse serial string into separate parameters
    amp = readString.substring(0, 3);
    knee_amp = readString.substring(3, 7);
    afreq = readString.substring(7, 11);
    phase = readString.substring(11, 15);
    gait = readString.substring(15, 20);
    f_offset = readString.substring(20, 24);
    b_offset = readString.substring(24, 28);
    fk_offset = readString.substring(28, 32);
    bk_offset = readString.substring(32, 36);

    //convert string values to numbers
    iAmp = amp.toInt();

    knee_amp.toCharArray(buffer, 10);
    fKnee_amp = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    afreq.toCharArray(buffer, 10);
    fAfreq = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    phase.toCharArray(buffer, 10);
    fPhase = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    gait.toCharArray(buffer, 10);
    fGait = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    iF_offset = f_offset.toInt();
    iB_offset = b_offset.toInt();
    iFk_offset = fk_offset.toInt();
    iBk_offset = bk_offset.toInt();

    //clear strings
    readString="";
    amp="";
    knee_amp="";
    afreq="";
    gait="";
    phase="";
    f_offset="";
    b_offset="";
    fk_offset="";
    bk_offset="";
  }

  //if the joints should be oscillating
  if (fAfreq > 0){
    //determine joint positions
    pos[0] = iAmp * sin(fAfreq*t) + 1500 + iF_offset;
    pos[1] = iAmp * sin(fAfreq*t) + 1522 - iF_offset;
    pos[2] = iAmp * sin(fAfreq*t + fGait) + 1500 + iB_offset;
    pos[3] = iAmp * sin(fAfreq*t + fGait) + 1446 - iB_offset;

    pos[4] = iAmp*fKnee_amp * sin(fAfreq*t + fGait + fPhase) + 1500 + iFk_offset;
    pos[5] = iAmp*fKnee_amp * sin(fAfreq*t + fGait + fPhase) + 1581 - iFk_offset;
    pos[6] = iAmp*fKnee_amp * sin(fAfreq*t + fPhase) + 1500 + iBk_offset;
    pos[7] = iAmp*fKnee_amp * sin(fAfreq*t + fPhase) + 1538 - iBk_offset;

    //get time in milliseconds
    unsigned long currentMillis = millis();

    //if the time threshold has been passed
    if(currentMillis - previousMillis >= sine_time){
      previousMillis = currentMillis;

      //write servo positions

      SB.writeMicroseconds(pos[0]);
      SF.writeMicroseconds(pos[1]);
      HB.writeMicroseconds(pos[2]);
      HF.writeMicroseconds(pos[3]);
      EB.writeMicroseconds(pos[4]);
      EF.writeMicroseconds(pos[5]);
      KF.writeMicroseconds(pos[6]);
      KB.writeMicroseconds(pos[7]);

      //increment time parameter
      t+=1;
    }
  }
}

```

I don't know what to try next.

# Answer
Given that it's the last two that aren't working, perhaps you've got a timing problem. Now I don't know how good the compiler is about detecting common code, but you might want to make it easier for it, and perhaps speed things up by making some temporary variables:

```
//determine joint positions
int pos01 = iAmp * sin(fAfreq*t);
pos[0] = pos01 + 1500 + iF_offset;
pos[1] = pos01 + 1522 - iF_offset;

int pos23 = iAmp * sin(fAfreq*t + fGait);
pos[2] = pos23 + 1500 + iB_offset;
pos[3] = pos23 + 1446 - iB_offset;

int pos45 = iAmp*fKnee_amp * sin(fAfreq*t + fGait + fPhase);
pos[4] =  pos45 + 1500 + iFk_offset;
pos[5] = pos45 + 1581 - iFk_offset;

int pos67 = iAmp*fKnee_amp * sin(fAfreq*t + fPhase);
pos[6] = pos67 + 1500 + iBk_offset;
pos[7] = pos67 + 1538 - iBk_offset;

```
> 1 votes

---
Tags: arduino-uno, servo
---


title: Arduino sending data over MAX485

text:
# Question
Title: Arduino sending data over MAX485
I would like to introduce myself as a student from Czech Republic. I'm currently I'm working on a Meteostation project.

I've got Arduino set up, with plenty of weather sensors, as well as WH1080 sensors connected.

Right now, I'm only able to read the data via serial port on computer with Arduino IDE or show it on my 20\*4 display.

Because of the distance between source of data and recipient of data, wireless data transfer is unsuitable for my application.

I found these MAX 485 modules on eBay for cheap:

I quickly got 2 pieces, as well as 5v-3.3v logic level shifter, as I was concerned about different logics on Raspi. I don't know much about Raspi and their pins, as the only thing I ever used with them was DS3231 real time clock module.

Now, the thing I'm trying to achieve is this - I want to be running a bunch of sensors at roof of our house, and have the Arduino send the data to Raspi over the rs485 (on request? as the sensor loop would be like 10-15min so maybe communicate on interrupt?)

What I'm planning to do with the data on the raspi would be running a software like WeeWx or wfrog to process them and possibly render a local website, that I could make public as port forwarding (I have public IP).

However, there are few questions I have, hopefully its not too much to ask

1. How would the wiring look like? I was unable to find any dumb-proof tutorial online, as I don't know whether or how to use the logic level shifter.
2. If I can read the data over serial port, would it be just a plain text (as shown on PC in Arduino ide serial monitor), or has each value its address that I could then easily accessing to a variable then being used to process the weather data?
3. If I'm completely wrong in something, or there's some completely different way how these things are being done by more experienced people, I'd love to hear some suggestions.

Thanks in advance for any kind of response, as this is at the moment causing me headaches, as I'm unable to do this on my own. I don't expect anyone to do all the work for me, maybe just point me in the right direction.

# Answer
> 5 votes
> How would the wiring look like? I was unable to find any dumb-proof tutorial online.

I found this tutorial to be pretty usefull.

There really isn't much to it, I suggest trying a short range before going full range. It's a "half duplex bus system" the ends of the bus should have a "end termination resistor", usually 120Ohms, between the A and B signal. Since it's half duplex, the Pi and Arduino can't talk at the same time. You'll have to pull the DE and RE pins high when you want to transmit (and keep them low for receiving).

Basic sketch would be something like:

```
#define TXEnablePin 13

void setup(){
  Serial.setup(9600);
  pinMode(TXEnablePin,OUTPUT);
}

void loop(){
  String data = "";
  Unsigned int sensorValue1 = Sensor.getValue();
  Unsigned int sensorValue2 = Sensor.getValue();
  data += str(sensorValue1) + ":" + str(sensorValue2) + ";\r\n";
  send(data);
  delay(10000);
}

void send(String data){
  digitalWrite(TXEnablePin,HIGH);
  delay(1);
  Serial.send(data);
  Serial.flush();//Wait for everything to be transmitted, before disabling transmitter.
  digitalWrite(TXEnablePin,LOW);
}

```

> I don't know whether or how to use the logic level shifter.

These things are pretty straight forward. You should actually be able to figure it out yourself (given you have the power of the internet).

LV to 3.3V of Pi GND to GND of Pi GND to GND of Arduino HV to 5V of Arduino

Then, whatever 5V signal you want to connect to HVx and whatever 3.3V signal you want to connect to LVx

```
Example:
Arduino-TX -> HV1
Arduino-RX -> HV2
Pi-TX -> LV2
Pi-RX -> LV1

```

> If I can read the data over serial port, would it be just a plain text (as shown on PC in Arduino ide serial monitor), or has each value its address that I could then easily accessing to a variable then being used to process the weather data?

It would be ASCII (plain text) if you send strings. You could make different types of requests.

Like; If you send: "Temperature" to the Arduino, it will respond with: "TEMP:10" or something.

But the easiest thing would be to send all values of all sensors in a combined string every 10 seconds or so. And let the Raspberry Pi unpack that string.

> If I'm completely wrong in something, or there's some completely different way how these things are being done by more experienced people, I'd love to hear some suggestions.

I think it's pretty good that you actually already know of the existence of RS485 and why you'd want to use it.

But I also feel that you feel a little uncomfortable with the project as it is. It's important to handle problems one by one, to avoid getting overrun by problems. Try to make it working over (short) USB first. Then try a short RS485 link and eventually try a long RS485 link. You can then more easily spot where the problem is. Use facts from multiple tutorials, to boost the confidence you have in the system ;). It may just work if you wire it as said. If it doesn't work, you can always post a question.

If possible, it may also be worthwhile to follow some tutorials on Arduino (get a starter kit and book with tutorial projects?). Within these tutorials they give examples of problems and show what there is to solve them. Without throwing yourself into a dark pit of a project.

# Answer
> 2 votes
Ok, one simple step which might help you to get going.

**The no-brainer**

There is an RS232 link between your Arduino and the PC. (Of course, it might not be a real RS232, it can be the USB, and over the USB the PC sees the arduino as a serial port what you can write from Arduino. So far so good.

You can easily extend the USB with passive expansion cords, as well as with active USB expansion cords, easily getting an extra 30m. Of course it is not an RS485, but comes at no further thinking.

**The RS485**

RS485 is basically a clever variant of a serial port, which allows you sending your data over up to 1.5km twisted wire pair.

* get an USB-RS485 adapter for your PC or Raspberry side. These are widely available, e.g. http://usb-rs485.eu/?cms=eu85xl&gclid=CjwKEAjwq6m3BRCP7IfMq6Oo9gESJACRc0bNkhzTSQU3wUW\_5tebRZDD-zAqflcvcFOq9V8nmZIlRhoCvyPw\_wcB
* get an RS485 driver chip such as MAX485 (I prefer LTC485, that works straight from 5V, costs like 1 EUR) for your Arduino side.
* you'll need two ardino pins - serial read and write, therefore you may prefer an Arduio supporting also Serial1 - so a TxD and RxD wire from the board. When you write to this serial port instead of Serial, the data comes out from the TxD pin of the Ardino panel, instead of going to the PC via the USB.
* now, if you can have a simplex system - i.e. only Arduino talks to the PC or Raspberry - then it makes your life a lot easier. Then you only need the TxD from the Arduino, and connect it to the DI of the RS485 driver chip. Connect RE and DE and connect both of them to 5V. That's all.
* if you want a two direction communication between the Arduino and PC, that makes things a bit more complicated. RS485 is a half-duplex thing, so your Arduino needs to control when it wants to talk to the line or listen. For that you need a separate pin to be connected to RE and DE together. Put it to 1 to write, 0 to read from the RS485 lines. Note that Arduino is having write buffers, so it will be a little tricky to know exactly when to switch back to listening after writing. Solving this properly worths of a separate question :)
* connect A of the MAX485/LTC485 to the A of the USB RS485 interface. Connect B to B. Now you're almost there... Connect also GND of the Arduino to the GND of the RS485 interface. (Although you can see many examples on the net of using only two wires, A and B, in the real life you either need a common GND, or an additional overvoltage protection circuit made of four zener diodes to have it running well forever.)
    + you're advised of using a twisted pair wire for A and B. This is not a requirement though, you can go well with any wires. One of my friend used a garden fence made of metal as A, and the soil as B, which worked well for 50 meters :) However for 1.5Mbit, 1km you definitely need a twisted pair
    + Note that if you go with long wires (over 50 meter) and higher speed (over 9600 bps), you need to have line-terminator resistors. This means a simple 120 ohm resistor connected between A and B on the PC side. Another 120 ohm resistor to be connected at A and B on the MAX 485 side - so the two farthest end of the long communication wire.

Now the software side:

* The USB RS485 interface will look like just a regular serial port for the PC (e.g. COM9) or Raspberry. So you can read and write the RS485 bus just like a standard com port.
* On the Arduino side, you can use the Serial1 (or equal) to write data out to the MAX485, which drives the wires.
* I suggest again to start with a simplex system, i.e. Arduino only writes data, the PC just reads data.
* Note that you have to use exactly the same bit rate on Arduino as well as on the PC side. Watch out when you open up the terminal.

---
Tags: serial, sensors, hardware, communication, rs485
---


# Question
Title: Not detecting Arduino Mega 2560. It worked before but now not detecting
I am using Windows 8.1 64 bit. I have an Arduino Mega 2560. I configured and installed it with the Merlin firmware before. I had a system format in between. I tried to connect my Arduino again.

I have the following problems:

1. Not detecting any hardware when plugging in the Arduino board: the green LED is on and the yellow LED is blinking. I checked the Device manager. It doesn't come in either COM ports or other devices. (The last time it came in COM ports as Arduino Uno). I installed legacy hardware on COM 3 (which was used before) and tried to update the driver from a newly downloaded version of Arduino. No success. I disabled the certification signature requirement from boot menu and tried: again no success.
2. The serial port on Arduino is greyed out.

I need some help. I am running out of ideas. I tried uninstalling COM port. I cleaned the registry with CCleaner. I uninstalled all Arduino software. I rebooted the system. I downloaded everything again, then connected the board. Still not detecting the new hardware. :P

Help me out.

# Answer
> 1 votes
What you said has happened to me before.This happened to me as I supplied over 20v to the arduino.Did you supply a higher voltage than recommended or pull too many amps from the board?If you did so,it is almost futile to try to repair it.

# Answer
> 1 votes
Assuming the board is not fried...

Sounds like 'USB \<--\> serial' chip issue. Not sure which chip it is, could be CP2102 or FT232 or CH340G. If it is FT232R and not a genuine one and you are using a specific version of the driver - you could have bricked the USB \<--\> serial converter.

Without assumptions, I would start with a bootable USB pen-drive with some flavour of Linux - I prefer Linux Mint/Ubuntu. Here is how I would go:

1. Boot the system with the pen-drive with Arduino disconnected
2. Open terminal and tail the system log (e.g. tailf /var/log/syslog)
3. Attach the Arduino board and see what shows up.
4. If Arduino is detected, there will be a message with the serial port device name (e.g. /dev/ttyUSB0)
5. Arduino IDE could run on Linux. If the port is detected, run Arduino IDE and see if it detects the board.

If not detected, the board is still useable, but you might need to find a way to connect external USB \<--\> Serial converter and disconnect the on board one. That means cutting traces and probably soldering some pins.

# Answer
> 1 votes
It's possible it's fried - but I have had recovered some boards like this that the boot software had gotten corrupted. It's easy enough to reapply the bootloader to the device - you will need either a second arduino:

https://www.arduino.cc/en/Tutorial/ArduinoISP

or an usbasp programmer (about $10 on eBay).

There is also a tutorial on reflashing the USB chip (link below) - but I would try the above first.

https://www.virtuabotix.com/how-to-cure-sudden-uno-death-syndrome/

---
Tags: arduino-mega
---


title: Why doesn't the time update?

text:
# Question
Title: Why doesn't the time update?
I am making an arduino clock/alarm. I use an LCD screen to display the time.

```
void loop(){
    static unsigned long timing=micros();
    if (mode == 0) {//mode 0 is when the time should show
        timing=countTime(timing);
        writeTime(minutes, hours);//display time
  }
}
  unsigned long countTime(unsigned long timing){
            if (micros() - timing >= 59946970) {
              return timing += 59946970;//more precise because Arduino timing is not perfect
              minutes++;

    }
        else{

         return timing;
        }

      }

    void writeTime(int minute, int hour) {
      lcd.setCursor(6, 1);
      if (minute >= 60) {
        minute = 0;
        hour++;
      }
      if (hour >= 24) {
        hour = 0;
      }
      if (minute < 10) {

        if (hour < 10) {
          lcd.print(String("0") + hour + ":" + "0" + minute);
        }
        else {
          lcd.print(hour + String(":") + "0" + minute);
        }
      }
      else {
        if (hour < 10) {
          lcd.print(String("0") + hour + ":" + minute);
        }
        else {
          lcd.print(hour + String(":") + minute); //possibly split if problems arise
        }

      }

  }

```

I used to do all this within the loop, but decided to make it separate. Why isn't this code working?

# Answer
This statement:

```
static unsigned long timing=micros();

```

...only gives it an initial value. It is not executed during `loop`. These kinds of variables should be assigned an initial value in an executable section, perhaps when the alarm time is set.

This requires the definition to be pulled out, to the file scope:

```
static unsigned long timing;

void loop(){
    if (mode == 0) {//mode 0 is when the time should show
        timing=countTime(timing);

```

Here, the `static` keyword has a different meaning, although I usually use it to reduce the chances of colliding with other global variable names.

Make sure to give it an initial value in executable code somewhere:

```
void setup()
{
  ...
  timing = millis();  // Just once?  When the alarm is set?
}

```

... and update it as you do in `countTime`.

---

**UPDATE** It's not clear from your snippet as to *when* the `timing` variable should be initialized, so I originally avoided addressing that. If it is really initialized just once, at program startup, you can set it in `setup`. Otherwise, it should be set when the initial `timing` value is finally known.
> 1 votes

---
Tags: arduino-uno, c++, timing
---


# Question
Title: How to wake up Arduino Mega when in Power Saving Sleep Mode?
I'm using sleep mode to turn off my device after the routine has finished executing and want to use interrupts to wake it up every 33 milliseconds. Basically, the idea is that if the routine completes in less than 33 milliseconds the processor can shutdown and save power for whatever remaining time, which will hopefully translate to reduced power consumption. I've currenlty managed to turn off my device with the `sleepNow()` function you see below, but the interrupt I have programmed in doesn't seem to work. The program simply goes to sleep and never wakes up. What am I doing wrong?

```
#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/sleep.h>

const uint16_t PERIOD = 2150;

void setup()
{
  noInterrupts();
  TCCR1A = 0;            // undo the timer config done...
  TCCR1B = 0;            // ...by the Arduino core library
  TCNT1 = 0;             // reset the timer
  OCR1A = PERIOD - 1;    // set the period
  TIMSK1 = _BV(OCIE1A);  // enable TIMERx_COMPA interrupt
  TCCR1B |= (1 << CS12); // ...and set the prescaler
  interrupts();

  Serial.begin(9600);
}

ISR(TIMER1_COMPA_vect)
{
  Serial.println(millis());
}

void loop()
{
  Serial.println("Program is on");
  Serial.flush();
  sleepNow();
}

void sleepNow()
{

    // Choose our preferred sleep mode:
    set_sleep_mode(SLEEP_MODE_PWR_SAVE);

    // Set sleep enable (SE) bit:
    sleep_enable();

    // Put the device to sleep:
    sleep_mode();

    // Upon waking up, sketch continues from this point.
    sleep_disable();

}

```

# Answer
It is certainly tempting to go into a very deep sleep in order to save power, but you still need to keep awake whatever peripheral you want to use as a wakeup source. If you want to use a 16 bit timer, there is no other choice than `SLEEP_MODE_IDLE`.

But it may not be that bad. In IDLE mode you can selectively disable the clock (and hence put to sleep) the peripherals you do not use. Or maybe put them *all* to sleep, and then wake up the few ones you do need. This is achieved with the `power_*_disable()` and `power_*_enable()` family of functions.

In the edited code below: all peripherals but the Timer 1 are disabled while the CPU sleeps. The USART is enabled only for the time it needs to send its message:

```
#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <util/delay.h>

const uint16_t PERIOD = 2150;  // 34.4 ms

void setup()
{
  // Disable all but the needed peripherals.
  power_all_disable();
  power_timer1_enable();

  // This is for debug pulses.
  pinMode(22, OUTPUT);

  // Configure Timer 1 to wake us up every 34.4 ms.
  TCCR1A = 0;            // undo the timer config done...
  TCCR1B = 0;            // ...by the Arduino core library
  TCNT1 = 0;             // reset the timer
  OCR1A = PERIOD - 1;    // set the period
  TIMSK1 = _BV(OCIE1A);  // enable TIMERx_COMPA interrupt
  TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
         | _BV(CS12);    // ...and set the prescaler /256

  Serial.begin(9600);
}

ISR(TIMER1_COMPA_vect)
{
  // Send a debug pulse.
  digitalWrite(22, HIGH);
  _delay_ms(2);
  digitalWrite(22, LOW);
}

void loop()
{
  // Enable the USART only while needed.
  power_usart0_enable();
  Serial.println("Program is on");
  Serial.flush();
  power_usart0_disable();

  // And go to sleep in IDLE mode.
  sleep_mode();
}

```

Notice also that the ISR does not print to the serial port: it just sends a debug pulse to watch with the scope. This should be removed from production code. The delay is achieved with the avr-libc function `_delay_ms()` because the standard Arduino `delay()` would not work: it relies on Timer 0, which has been disabled.
> 1 votes

---
Tags: arduino-mega, power, sleep
---


title: CAN communication with Arduino

text:
# Question
Title: CAN communication with Arduino
I'm a member of a Formula SAE team and we use the Performance Electronics ECU which uses the CAN protocol with a speed of 250 kbit/s and works fine with our 2D Recording Systems Data logger, but we're trying to build a telemetry system which gathers the same data from the CAN bus using an Arduino Uno and CAN shield provided by SparkFun Electronics.

However the CAN shield we're trying to use has failed to initialise the communication with the bus. Kindly help me out on what can be done or are there any alternatives of communicating using CAN with Arduino?

P.S. The link for the CAN shield: CAN-Bus Shield Hookup Guide

# Answer
> 2 votes
Beware, the industry standard pinout for CAN on DB9 connectors is different to what Sparkfun use on their shield:

Which software have you been using on the Arduino? Any additional info on the ECU you're using, and the wiring in your system?

# Answer
> 0 votes
I found this wiki particularly useful: CAN-Bus Shield Wiki

And yes, like CQuinson said, you have to pay attention to the pins used. I know Sparkfun is known for having an issue with which pin the CS pin is assigned to (D9 or D10).

---
Tags: can-bus
---


# Question
Title: How can you determine the duration of a timer interrupt?
So I understand that when setting a timer interrupt you don't use nanoseconds or milliseconds, but the actual number of clock cycles. However, I don't understand how you would be able to setup a specific time this way. If I wanted my interrupt to go off every 20 milliseconds would I have to divide that by the duration of each clock cycle?

# Answer
The timer takes its time from the system clock. That may be, typically, 16MHz. We call this *F\_clk\_io* for the **F**requency of the **IO** **CL**oc**K**.

Every time that clock ticks the timer counts. Or, depending on settings, every time that clock ticks the prescaler counts, and eventually the output of the prescaler ticks and then the timer counts.

So first you need to divide the *F\_clk\_io* by the prescaler. That may be 1:1, 1:2, 1:4, 1:8, etc, depending on settings. No prescaler is the same as a prescaler of 1:1.

So say you have selected a 1:4 prescaler. The timer's frequency is then *F\_clk\_io / 4*, or if it's 16MHz you're running at, then the timer's frequency is *16/4 = 4MHz*.

So at 4MHz each tick lasts for *1/4000000 = 250ns*.

If you want 20ms you need to know how many ticks that would be.

20ms in nanoseconds would be 20000000. 20000000 / 250 = 80000 ticks.

Now, there's a problem there. 80000 won't fit into the 16-bit registers of a 16-bit timer. The maximum you can have is 65535. So we're going to need to slow things down a bit.

Set the prescaler to 1:8 and see what happens...

*16/8 = 2MHz. 1/2000000 = 500ns. 20000000 / 500 = 40000 ticks.*

That fits. See how doubling the prescaler has simply halved the number of ticks you get in the same time?

So setting it to a prescaler of 1:8 and letting it tick 40000 times should give you 20ms.

Except it doesn't.

It gives you 20.0005ms.

Why? Because the interrupt triggers and the counter resets when it *reaches* the target count, not when it *passes* the target count. And since it starts counting at 0, there's actually 40001 ticks there. So you have to subtract 1 from the number of ticks.

So the finished formula is:

```
ticks = ((F_clk_io ÷ Prescale) × time) - 1

```

Things get more tricky when you are working with a smaller chip though and only have an 8-bit timer to use. With that the maximum ticks you can have is a mere 255. So you will have to use a much bigger prescale to get it to fit in. If that's even possible. If it's not, then there are other tricks you can use. My favourite is a manual pre-scale:

1. Run the timer at a multiple of your target frequency (10x is easy)
2. Count the number of times the interrupt triggers
3. When the interrupt has triggered 10 times (if using a 10x faster timer) then reset the count to 0 and trigger your real ISR code.

10x is simple to program and visualize, but it's not very programatically efficient. Better is to use a "power of two" multiple since you can examine a single bit in your counter to see if it's reached the target count. Only minimal differences though, and not really worth worrying about unless you are having a very fast timer interrupt.
> 2 votes

---
Tags: arduino-mega, sleep, oscillator-clock
---


title: Building a Vector class in Arduino

text:
# Question
Title: Building a Vector class in Arduino
I'm struggling with this issue that I can seem to get around of. When defining a vector class, I'm seeming to get some issues when deleting the allocated pointer.

Oddly enough, this only happens after I "read" the memory. What I mean by this is that if I push back a series of values to the vector, they seem to stay there. But once I read the values, the data pointer seems to become invalid of some sort so I crash when trying to deallocate it.

Code:

```
#ifndef VECTOR_H
#define VECTOR_H

#include <string.h>     /* memcpy */

#define min(a,b) (a < b) ? a : b

template <typename T>
class vector {
public:
    vector() : __capacity(0), __count(0), __data(0) {} //empty constructor
    vector(T obj, int count = 1) {

        if (this->__data) { // free data ptr if used
            delete this->__data;
        }

        this->__data = new T[count];
        this->__count = count;
        this->__capacity = count;

        for (int i = 0; i < count; i++) //populate array with given object
            this->__data[i] = obj;

    }

    ~vector() {

        if (this->__data) { // free data ptr if used
            delete [] this->__data;
        }

        this->__count = this->__capacity = 0;
    }

    T const & operator[] (unsigned int idx) const {
        if (idx < this->__count) {
            return this->__data[idx];
        }
        else {
            // throw exception or handle error to be implemented
        }
    }

    T& operator[] (unsigned int idx) {
        if (idx < this->__count) {
            return this->__data[idx];
        }
        else {
            // throw exception or handle error to be implemented
        }
    }

    void resize_to_fit() {
        resize(this->__count);
    }

    T& pop_back(){
        return this->__data[--this->__count];
    }

    void push_back(T obj) {

        if (this->__capacity == this->__count) {
            resize(this->__capacity + 1);
        }

        this->__data[this->__count++] = obj;
    }

    bool isempty() {
        return !this->__data ||
            !this->capacity ||
            !this->size;
    }

    void clear() {
        this->~vector();
    }

    T* data() {
        return this->__data;
    }

    int size() {
        return this->__count;
    }

    int capacity() {
        return this->__capacity;
    }
private:
    void resize(int capacity) {
        if (this->__data == nullptr) {
            this->__data = new T[capacity];

            this->__count = 0;
            this->__capacity = capacity;
        }
        else if (capacity != this->__capacity) { //else do nothing

            T* data = new T[capacity];

            this->__count = min(this->__count, capacity);
            this->__capacity = capacity;

            memcpy(data, this->__data, sizeof(T) * this->__count);

            delete this->__data; //program crashes here, but the pointer is already broken...
            this->__data = data;
        }
    }
protected:

        int __capacity;
        int __count;
        T* __data;

};
#endif//VECTOR_H

```

I was using this code in my Arduino, not sure if it helps

```
void print_vec(vector<int> v){
  Serial.println("Printing new vec!");
  for( int i = 0; i < v.size(); i++){
    Serial.println(v[i]);
  }
}

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

  Serial.begin(9600); // Open serial connection to report values to host

  while(!Serial); //Waiting for serial to open

  vector<int> i = vector<int>();

  i.push_back(10);
  i.push_back(2);
  print_vec(i); //prints 10 and 2, perfect so far
  i.push_back(3);

  while(true){
    print_vec(i);
    i.pop_back();
    delay(2000);
  }
}

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

}

```

This code outputs: Printing new vec! 10 2 Printing new vec! 0 2 3 Printing new vec! 0 2 Printing new vec! 0 (...)

What could be causing this? I'm stonewalled for a while now, any insight on how to solve this is appreciated. Thanks!

# Answer
You had a lot of problems with your code so it's hard to know where to start. :)

I agree with what John Burger said.

I took your code onto my PC to save mucking around uploading it each time, and also so I could use valgrind on it. Certainly valgrind reported an error after you printed the vector. The reason for that is simple. You passed a **copy** of the class to `print_vec` which meant that the destructor got called when `print_vec` exited, thus deallocating the memory. You should have had a *copy constructor*. Without it the compiler makes a bitwise copy of the class, which means you now have two objects sharing the same allocated memory.

A quick and dirty fix is to call `print_vec` by reference:

```
void print_vec(vector<int> & v){

```

However that leaves the bug lurking around for the future.

I implemented the copy constructor in my example below, however calling `print_vec` by reference saves the class having to be copied, reducing the number of `new/delete`s you are doing, thereby possibly reducing memory fragmentation.

---

As John Burger said: **do not call the destructor yourself!** You can't do that. If you want to do the same thing in the destructor and the `clear` function, just get the destructor to call `clear()`.

---

The use of leading double-underscores in variables is contrary to the C++ Standard. Don't do that. Use a trailing underscore if you want to indicate a member variable. Lose all the `this->` references. They just clutter things up.

---

Since you allocate an array you should use `delete []` \- you did that in one place but not the other.

---

Why do this? It's an unnecessary assignment:

```
  vector<int> i = vector<int>();

```

Just do:

```
  vector<int> i;

```

If you are going to assign the class for some reason you should also implement an `operator=` or you will have the same problems as you had with the copy constructor. (See my example).

---

Here you are testing functions (capacity and size) without calling them:

```
bool isempty() {
    return !this->__data ||
        !this->capacity ||
        !this->size;
}

```

---

You can't really do this:

```
  T const & operator[] (unsigned int idx) const {
        if (idx < this->__count) {
            return this->__data[idx];
        }
        else {
            // throw exception or handle error to be implemented
        }
    }

```

If you take the "else" path then the function is returning no value (you get a compiler warning if you turn warnings on).

---

My reworked example, with my suggestions in it. It compiles without warnings or errors and runs without crashing (on a PC):

```
//      g++ -std=c++11 -g3 test.cpp -o test
// OR:  clang -std=c++11 -g3 -Wall test.cpp -lstdc++ -o test
//
// valgrind --leak-check=yes ./test

#include <stdio.h>      // printf
#include <string.h>     /* memcpy */

#define min(a,b) (a < b) ? a : b

template <typename T>
class vector {
public:
    //empty constructor
    vector() : capacity_(0), count_(0), data_(nullptr) {}

    // copy constructor
    vector (const vector & rhs) : capacity_(0), count_(0), data_(nullptr)
      {
      data_ = new T [rhs.capacity_];
      capacity_ = rhs.capacity_;
      count_ = rhs.count_;
      memcpy (data_, rhs.data_, sizeof (T) * count_);
      }  // end of copy constructor

    // operator=
    vector & operator= (const vector & rhs)
      {
      // gracefully handle self-assignment (eg. a = a;)
      if (this == &rhs )
        return *this;

      data_ = new T [rhs.capacity_];
      capacity_ = rhs.capacity_;
      count_ = rhs.count_;
      memcpy (data_, rhs.data_, sizeof (T) * count_);
      return *this;
      }  // end of operator=

    // destructor
    ~vector()
      {
        clear ();
      }  // end of destructor

    T const & operator[] (unsigned int idx) const {
       return data_[idx];
    }

    T& operator[] (unsigned int idx) {
       return data_[idx];
    }

    void resize_to_fit() {
        resize(count_);
    }

    T& pop_back(){
        return data_[--count_];
    }

    void push_back(T obj)
        {
        if (capacity_ == count_) {
            resize(capacity_ + 1);
        }

        data_[count_++] = obj;
    }

    bool isempty() {
        return count_ == 0;
    }

    void clear() {
      delete [] data_;
      data_ = nullptr;
      count_ = capacity_ = 0;
    }

    T* data() {
        return data_;
    }

    int size() {
        return count_;
    }

    int capacity() {
        return capacity_;
    }
private:
    void resize(int capacity) {
        if (data_ == nullptr) {
            data_ = new T[capacity];
            count_ = 0;
            capacity_ = capacity;
        }
        else if (capacity > capacity_) { //else do nothing

            // allocate new memory
            T* data = new T[capacity];
            // count can't be higher than capacity
            count_ = min(count_, capacity);
            capacity_ = capacity;
            // copy data across to new pointer
            memcpy(data, data_, sizeof(T) * count_);
            // delete old pointer
            delete [] data_;
            // now remember the new pointer
            data_ = data;
        }
    }
protected:

        int capacity_;
        int count_;
        T* data_;
};

void print_vec(vector<int> v){
  printf("%s\n", "Printing new vec!");
  for( int i = 0; i < v.size(); i++){
    printf("%i\n", v[i]);
  }
}

int main() {

  vector<int> i;

  i.push_back(10);
  i.push_back(2);
  print_vec(i);
  i.push_back(3);

  vector<int> j;

  // test assignment
  j = i;
  print_vec(j);
  print_vec(i);

  while(i.size () > 0){
    print_vec(i);
    i.pop_back();
  }

}

```
> 1 votes

# Answer
### In your second constructor you start with the following code:

```
if (this->__data) { // free data ptr if used
    delete this->__data;
} // if

```

This is deadly! You've not initialised `__data`, so it could hold *any* value under the Sun. And there is *no way* that it could *possibly* be a valid pointer to existing data - it's a brand-new uninitialized object. Returning this garbage pointer to the heap is simply asking for trouble.

Remove those lines - or even better, use an initialiser list like you did with the first constructor:

```
vector(T obj, int count = 1) :
       __data(new T[count]),
       __count(count),
       __capacity(count)
{
    for (int i = 0; i < count; i++) //populate array with given object
        __data[i] = obj;
} // vector(T, count)

```

### Another problem: In your `clear()` member you wrote:

```
void clear() {
    this->~vector();
}

```

You should never, *never*, **never** directly call a destructor like this. The compiler can put all sorts of other code in the destructor code, since it "knows" that it's the only one that will ever call it. For example, some compilers pre-push a flag to say whether to `delete` the object from the heap after doing the destruction. You haven't done that, so the above can corrupt all sorts of things.

Instead, move the code that is in the destructor into `clear()`, and then simply call `clear()` from the destructor.

### Another one, this one picked up by @Nick Gammon:

```
bool isempty() {
    return !this->__data ||
           !this->capacity ||
           !this->size;
}

```

This is testing whether the `__data` member is false, and whether the `capacity` and `size` functions have been defined. Don't worry: the latter two have been... you missed the prefix `__`...

> \[Also, stop it with the `this->` everywhere. You've used a `__` before all your member variables (which is itself against convention); you don't need to hammer home the fact that they are member variables: the compiler already knows.\]
> 2 votes

# Answer
There is something I would like to add.
Others have already pointed out numerous errors in the code. And I could point many more, but that is not the point.
IMO, the biggest mistake is - implementing a Vector class for the Arduino!
Even if it works, it is just a bad idea. Keep in mind, that the Arduino has VERY limited amount of memory. Dynamic memory allocation in such a constrained space just sounds like a bad idea - you are wasting memory, you're fragmenting the heap and you gain almost nothing, except some coding convenience.
I have yet to see a case where one really needs dynamic memory allocation in an Arduino project. And even if you do, there are many other tools you can use (like stack-allocated temp buffers, arena allocators, pool allocators and whatnot). But again, probably the code and memory cost of these "generic" solutions will be unfeasible on the Arduino.
Most of the time it's fine to use vectors, maps and whatever you like on platforms like PC (I work as a PC games programmer, so I often encounter situations where extras like these are big "no-no", but for most applications it's fine).
But, on a "tight" platform like the Arduino, I think you should stay "close to the metal" and be in total control of what is going on (memory and CPU cycles wise). Ideally, you should only afford "luxuries" like these when you know what is going on "underneath" and you know you can get away with it. Which is rarely the case on "tight" platforms like the Arduino.
> 0 votes

---
Tags: programming, c++, vector
---


title: Why are pull-up resistors needed?

text:
# Question
Title: Why are pull-up resistors needed?
Please tell me why is it necessary to access pull-up resistors and how can we access them in arduino?

# Answer
Pull-up resistors are used to define the state of an otherwise "floating" input by pulling the voltage at the pin to a set voltage.
The most typical example is a switch - let's say you have some signal, which is connected to your input through a switch. If the switch is open, the state of your input is "floating". If you try to digitalRead or analogRead that input, the value will be pretty much just noise.
But, if you have a resistor connected from your input to ground (pull-down) or VCC (pull-up) your reading will be consistent (HIGH or LOW, depending on where the resistor goes) while the switch is open.
When the switch is closed, the voltage at the pin will be pulled to the voltage at the other end of the switch. Because of the lower resistance of the switch relative to your pull-up resistor, this is the input level that will be read by the microcontroller. Pull-up resistors are usually pretty big value (5k-100k) in order to be much higher resistance than the switch and to decrease the current that is used by the switch to produce a signal.
If, for example, you have a *pull-up* resistor and a switch that connects your input to the ground, when the switch is open you will read HIGH and when it is closed you will read low. Note that many components act similar to switches, for example transistors, open-drain / open-collector devices and many more, so the switch was just an example.

You can use external pull resistors (just add a resistor from your pin to ground or VCC) or use the internal pull resistors of your MCU. The Arduino only has internal pull-up resistors (no internal pull-downs) - their value depends on the model, but usually is between 20K-150K.
To activate the internal pull-up resistor for a given pin on Arduino, use the following code:

```
pinMode(N, INPUT);
digitalWrite(N, HIGH):

```

where "N" is your pin number or with recent IDEs:

```
pinMode(N, INPUT_PULLUP);

```
> 6 votes

# Answer
A short answer from Arduino Playground:

> Pull-up resistors are used in electronic logic circuits to ensure that inputs to the arduino settle at expected logic levels if external devices are disconnected or high-impedance. 'Just because you have nothing at all connected to an input pin doesn't mean it is a logical zero.'
> 1 votes

---
Tags: arduino-uno
---


title: arduino usb android controller

text:
# Question
Title: arduino usb android controller
i am pretty much newbie with arduino and want to start my first project so i may be asking stupid questions.

My goal is to make usb controller for android tv (running on raspberry pi or s905). I want it rotary, so turning will be "arrow up/down" or "left/right" (i dont know exact android tv menu controlling) and "return" on push. I found this rotary switch on ebay, is it suitable?

To communicate i want to use arduino. I found libraries MouseKeyboard, which might be suitable for my needs, will arduino nano support this library or do i need arduino uno?

Do i need something else, or just connect switch to pins on arduino and plug arduino to raspberry?

As i need this controller to operate in menu, not just in some application, will this work as some mouse or keyboard connected via otg to android and function immediately?

Thanks.

# Answer
> 0 votes
Yes, that rotary encoder is fine.

Neither the Nano nor the Uno support that library. You will need a device that has native USB support such as the Leonardo or Due, just like it says on the page.

The rotary encoder library you use will tell you how to connect it.

As for specific Android functionality, you will need to ask on Android.SE.

---
Tags: android, usb
---


# Question
Title: How to connect the 3.3v pin of arduino mega to multiple sensors
I am connecting 3 accelerometers to an arduino mega. I have everything except how to connect them to the 3.3v pin. I know that I can just connect the 3 of them to the same ground pin but I have been told I can't do the same with 3.3v pin. Can anyone tell me what is the best way to power them from the arduino mega?

# Answer
> 3 votes
You can connect all of them as long as the total current draw is not over 50mA as described here. If you need more than 50mA, you need to create your own 3.3v supply or use something like a breadboard power supply for instance (keep in mind to make a shared ground line).

---
Tags: arduino-uno, arduino-mega
---


# Question
Title: Where can I find magnetic declination lookup table?
Is there a way to get approximate value of magnetic declination from GPS coordinates?

My Arduino-based device has a Magnetometer and a GPS, and uses magnetic declination in calculations. I would like to avoid having to configure it by hand.

I have found references to https://www.ngdc.noaa.gov/geomag/WMM/soft.shtml online, but the site seems to be down (Google has a cache of the site but not of the code).

Is there another way of getting magnetic declination from GPS coordinates? Doesn't have to be precise, +/- 10% would work just fine.

# Answer
No, the North pointed by GPS coordinates are extracted using the velocity heading which would represent the true North. If you get the ECEF (earth centered earth fixed) coordinates from the GPS you can convert it to a local ENU (east north up frame) and calculate the heading from the velocity vectors (take a look here if you need the formulas for that).

However, this site http://www.magnetic-declination.com/ can provide you a estimate for magnetic declination at your location.

**EDIT** From the comment I came across this topic which lead to this

you can play with the code provided and take it as a template for your needs to create a lookup table. The software used for creation of the files is the one present in the site you pointed. Just downloaded the linux zip file and tested it with the sample txt coordinates provided and all seems ok.

For the record the command used was (yes for some reason the extension exe is present but this is linux binary):

```
./wmm_file.exe f sample_coords.txt out.txt

```

which created a out.txt equal to sample output file provided. Now this file can be used by the function `void build_lookup_table()` (present on grab60\_char.c) to build the lookup table you need.
> 2 votes

---
Tags: library, gps, magnetometer
---


title: Arduino Micro Println prints 0

text:
# Question
Title: Arduino Micro Println prints 0
I am having troubles with my arduino micro. In my programming, I am using the serial. When I use println, nothing shows up in the serial monitor except for `0`. So if I type `1`, I get back `0` instead of `1`, same goes for `3241234` or any random number. Here is the code:

```
void setup() {
  Serial.begin(9600); //Connect to the serial monitor console
}

void loop() {
    while (Serial.available() == 0); //Wait until Serial is available

    //Read val
    int val = Serial.read() - '0'; //Val that represents input
    delay(500);
    Serial.println(val);
}

```

So I have another problem and people have asked for the code. Basically, printing a string returns 0.

```
 void setup() {
  Serial.begin(9600); //Connect to the serial monitor console
}

void loop() {
    while (Serial.available() == 0); //Wait until Serial is available

    //Read val
    int val = Serial.read(); //Val that represents input

    delay(1000);
    if (val == 1) {
      Serial.print('Firing the motor');
    } else {
      Serial.print('Please press 1 to fire the motor.');
    }

    delay(4000);
}

```

Instead of printing Please press 1 to fire the motor, I get 0 in the console.

Thanks for the help!

# Answer
> 1 votes
Try without

```
- '0'

```

You read your data and save into in int. then print that int, when you pass only the int, you get the int as an ASCII-encoded decimal. Why r u doing

```
- '0'

```

?

# Answer
> 0 votes
This time you are comparing an integer 1 with a character '1'.

```
int val = Serial.read();

```

Is reading you pressing the one key and storing it in an integer variable as the number 49 (ASCII '1')

```
if (val == 1) {

```

You are now seeing it 49 is the same as 1, which it isn't.

To make your code easier stick to characters.
Change the Serial.Read line to:

```
const char val = Serial.read(); // Val that represents input
                                // (const because it will not change).

```

and the if line to:

```
if (val == '1')  // '1' character 1

```

By making val const you stop yourself accidentally changing it so if you do

```
if (val = '4') // Compilation error.

```

Hope that helps.

# Answer
> 0 votes
To your second question, strings in C are surrounded by the double-quote character: `"`, not the the single-quote or apostrophe character.

---
Tags: arduino-micro
---