message:
Distance finder technology 0-24inches

Can anyone point me towards whats best for relatively low cost distance measuring in the 0-36" range (or 0 - 1m range) with 1/16"/1mm accuracy.  My initial approach was going to be to hack a laser tape measure, but wanted to know if that was the best in cost vs accuracy.

Essentially looking to measure how close I am to a stationary metal plate.

Thanks for any help.

body:
You will likely find the best accuracy is derived from a laser-based measurement. My Bosch is laser only, no ultrasound component and has 1/16" resolution. For your application, the six inch minimum distance limitation of the Bosch is outside your specifications.

Because laser measurement devices use time versus distance, it's possible you could construct a mirror chamber with front-surface mirrors that would cause the laser to travel six inches before exiting the chamber, overcoming that limitation. The calibration should be straight-forward, as you'd place the chamber flush and adjust your mirror placement until you read the exact expected compensation distance.

You would need only small mirror panes, which would not "break the bank," but if you find a discarded large-screen projection television, the mirror within is front surface and quite large. Front surface mirrors should not have contamination from touching and should be cleaned with care, as you can erode or otherwise degrade the reflective surface.

I found this site:
http://blog.qartis.com/arduino-laser-distance-meter/
which looks promising for a different model of laser rangefinder, although the creator has run into a stumbling block or two.

It would appear that the key is to overcome the minimum distance limitation, perhaps as I suggested above, and interfacing with serial communications of the arduino.

One of the links I pursued involved the creator contacting the technical support of the manufacturer. The support ticket was closed as "resolved," in the manner of advising the user that the warranty was void by opening the case. Yeah, like that matters to makers and hackers!


sender: user

message:
Not able to upload program to "Arduino Due"

[![Arduino due Programming Port ][1]][1]

  [1]: https://i.stack.imgur.com/Yi55D.png

I'm not able to upload sketch on Arduino Due, using Programming Port.

Even blink sketch from examples is not working. So tried with blank sketch, I got following messages.

sender: assistant

body:
Go to device manager, and make sure that you can see the change in your com ports when you unplug and plug the Arduino into your computer.

You may also have to follow the instructions here: https://www.arduino.cc/en/Guide/Cores

I will also occasionally find that uploading won't work when I have something external connected to the RX,TX,3.3 and 5V, and GND pins.

It also helps to go to File-Preferences- and enable both options for "Show verbose output during". If you do that and post the output, we might have a better idea as to what is going wrong.


message:
Arduino as an automation controller

I am considering using an Arduino as a controller for a water treatment system and would love to hear your opinions. All it has to do is open/close a water gate (by starting/stopping a motor) at predefined times. It would have to...

 - Be able to connect to a phone using a usb cable. The phone would act as a UI to change settings and water flush times on the Arduino (via a custom app)
 - Log data which would be easily retrievable
 - Ideally, be able to connect to a cell network and send/receive packets. I believe there is a shield for this
 - Consume MINIMAL POWER. All it has to do is flush once every few days, log data, and possibly receive data from shield/usb. It would be running off of a solar panel and battery. In winter it could run out of power.

And thats pretty much it! Can this project be done with an Arduino? I would greatly appreciate any advice and recommendations!

body: So first of all, if the voltage of your systems is too high, arduino cannot provide that on its own. Arduinos can only provide 5v out with the rail. So you could use a relay shield, an add on board to stack on top of it, or just plain old relays with some soldering. Now, for connectivity, try this thing. http://www.annikken.com/andee/ It is relatively easy to learn, and you can build a decent UI without the need for coding an app. I think you can get them for ~30$. However, I do not know how well the arduino can run with so many shields. For data logging, a few companies make data logging shields, or you can get an external read/write and wire it up. I have a small, probably 3" by 8" solar panel for my arduino and it is quite unreliable even in low power applications. However, if you have a good one, that is cool. Best of luck -Peter


body:
Have a look at my [Temperature and humidity sensor - battery powered](http://www.gammon.com.au/forum/?id=12106). That works from 3 x AA batteries, and has been going for a few years. I think I replaced the batteries once. It keeps track of the time, and logs data to the disk (SD card).

[![Temperature logger][1]][1]

I don't have room to describe the whole project here, but the general idea is that the processor sleeps most of the time (consuming around 6 µA). Now this particular project doesn't turn on a motor, but adding a solid-state relay should be all you need to do that.

> Be able to connect to a phone using a usb cable. The phone would act as a UI to change settings and water flush times on the Arduino (via a custom app)

I think this will take a lot of power, keeping the phone active. One possible thing to try would be to power up the phone (eg. using another relay) during a certain "window" of time (eg. 6 pm to 7 pm). Then you would know to try to configure the device during that time.

  [1]: https://i.stack.imgur.com/3rtDL.png


message:
Average response time of Esp8266 module

I'm planning a project where I'd like to control an RC car with Arduino and an Esp8266 module.

A software running on a computer would read the input from an USB analog controller and send the data to the Esp8266 module through the wifi network, and the Arduino would read this data and send signal to the ports accordingly.

What I'd like to know is: would ping/delay be an issue? Considering a dedicated wifi network for this, so the only devices connected to it would be the computer and the Esp8266 module.

I need to know what is the average response time of the Esp8266 module before I buy it, because if it is too high I'll think of something else since for this project I'd need a reasonably high response time.

body:
I think response time would be a big problem. I used the ESP8266 with a temperature and humidity sensor, complete with a small web server on the ESP8266, and it works fine. But I wouldn't want to control an RC car with it. But if you buy it on ebay from China, it is only a few dollars, so buy one anyway.

Use Bluetooth, either a couple of HC-05 modules, or the Bluetooth Low Energy HM-10 modules. Both can communicate at 115200 baud. The HM-10 modules may be a bit tricky, because some Chinese sellers put a stripped down version of firmware on the module, and forces you to search online how to flash a usable firmware version.


body:
I'm pretty sure it can be made to work.

I have a home server with several devices attached to it, including 2 ESP8266 modules - one at home and one in my office. All devices connect using permanent TCP connection and respond to my custom "ping" requests over that connection. Typical round-trip response times are bellow 50ms and often bellow 10ms. There are occasional "hickups" of 100+ms, but they are rare and could be a result many factors. Note that these 2 ESPs are programmed in Lua, which is not optimal efficiency - I was just lazy and the tasks they do are simple enough to not matter.

Most probably if you start an HTTP server on the ESP and bombard it with HTTP requests every time you move the joystick it would be horribly laggy. But with a plain old TCP connection or even a consistent flow of UDP packets I'm pretty sure you will get good results.

Also, I would ditch the Arduino and use only the ESP - you should have no problem controlling two motors (most probably via motor driver board or chip) and perhaps a servo from the ESP directly. This would eliminate the additional lag of serial communication and parsing the serial data. It would also reduce the cost and size of the project.

Having that said, other solutions, like bluetooth or even RF modules should also work, but you asked whether the ESP can do it - and my answer is yes.


body:
If you use websocket it will have a really good response time.

It is a test about it:
https://www.youtube.com/watch?v=8ISbmQTbjDI

I use it for a quadcopter controller.


message:
Strange RPM Readings on Teensy 3.2

While trying to read RPM from a computer fan using the [4-wire protocol][1], I am getting strange readings. +12 and GND from the fan are connected to a power supply, and the tachometer to the PIN-0 or a Teensy 3.2.

I wrote code to read the tachometer pulse using the internal pull-up and interrupts. The strange thing happening is that the number of recorded revolutions is **increasing** as I manually slow the fan using my fingers.

Here is the code :

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <elapsedMillis.h>

    const int fanPulse = 0;
    volatile long half_revolutions;
    elapsedMillis timeElapsed;

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

      pinMode(fanPulse, INPUT_PULLUP);
      attachInterrupt(fanPulse, rpm_fun, FALLING);

      half_revolutions = 0;
      // analogWriteFrequency(20, 25000); // Teensy 3.0 pin 3 also changes to 375 kHz
    }

    void rpm_fun() {
      half_revolutions++;
    }

    void loop() {
      if (timeElapsed < 1000)
        return;

      Serial.printf("%d revolutions in %d miliseconds\n", half_revolutions / 2, (unsigned long)timeElapsed);

      timeElapsed = 0;
      half_revolutions = 0;
    }

Here is the strange output :

    0 revolutions in 1000 miliseconds  // Start
    0 revolutions in 1000 miliseconds
    82 revolutions in 1000 miliseconds
    394 revolutions in 1000 miliseconds  // "normal" reading
    412 revolutions in 1000 miliseconds
    576 revolutions in 1000 miliseconds
    456 revolutions in 1000 miliseconds
    554 revolutions in 1000 miliseconds
    585 revolutions in 1000 miliseconds
    799 revolutions in 1000 miliseconds  // Slowing the fan
    712 revolutions in 1000 miliseconds
    691 revolutions in 1000 miliseconds
    683 revolutions in 1000 miliseconds
    625 revolutions in 1000 miliseconds
    531 revolutions in 1000 miliseconds
    239 revolutions in 1000 miliseconds
    0 revolutions in 1000 miliseconds
    0 revolutions in 1000 miliseconds  // End

  [1]: http://www.formfactors.org/developer\specs\rev1_2_public.pdf

body: Without the ground of the teensy connected to the ground of the fan all you will be measuring is noise. Ground is required to complete the circuit between the teensy and the fan.


message:
Unable to replicate Arduino code into ATmega8 code

I am trying to replicate an LTC Audio Decoder code from Arduino Uno into AVR ATmega8 which I got from [here][1].

My Arduino Uno code is working great. Here is my Arduino Uno code:

    #define one_time_max          588 // these values are setup for NTSC video
    #define one_time_min          422 // PAL would be around 1000 for 0 and 500 for 1
    #define zero_time_max          1080 // 80bits times 29.97 frames per sec
    #define zero_time_min          922 // equals 833 (divide by 8 clock pulses)

    #define icpPin 8        // ICP input pin on arduino
    #define end_data_position      63
    #define end_sync_position      77
    #define end_smpte_position     80

    volatile unsigned int bit_time;
    volatile boolean valid_tc_word;
    volatile boolean ones_bit_count;
    volatile boolean tc_sync;
    volatile boolean write_tc_out;
    volatile boolean drop_frame_flag;

    volatile byte total_bits;
    volatile byte current_bit;
    volatile byte sync_count;

    volatile byte tc[8];
    volatile char timeCode[11];

    /* ICR interrupt vector */
    ISR(TIMER1_CAPT_vect)
    {
     //toggleCaptureEdge
     TCCR1B ^= _BV(ICES1);
      //Serial.println("Inter");
     bit_time = ICR1;

     //resetTimer1
     TCNT1 = 0;

    if ((bit_time < one_time_min) || (bit_time > zero_time_max)) // get rid of anything way outside the norm
     {
       //Serial.println(bit_time, DEC);
       total_bits = 0;
     }
     else
     {
       if (ones_bit_count == true) // only count the second ones pluse
         ones_bit_count = false;
       else
       {
         if (bit_time > zero_time_min)
         {
           current_bit = 0;
           sync_count = 0;
         }
         else //if (bit_time < one_time_max)
         {
           ones_bit_count = true;
           current_bit = 1;
           sync_count++;
           if (sync_count == 12) // part of the last two bytes of a timecode word
           {
             sync_count = 0;
             tc_sync = true;
             total_bits = end_sync_position;
           }
         }

         if (total_bits <= end_data_position) // timecode runs least to most so we need
         {                                    // to shift things around
           tc[0] = tc[0] >> 1;

           for(int n=1;n<8;n++)
           {
             if(tc[n] & 1)
               tc[n-1] |= 0x80;

             tc[n] = tc[n] >> 1;
           }

           if(current_bit == 1)
             tc[7] |= 0x80;
         }
         total_bits++;
       }

       if (total_bits == end_smpte_position) // we have the 80th bit
       {
         total_bits = 0;
         if (tc_sync)
         {
           tc_sync = false;
           valid_tc_word = true;
         }
       }

       if (valid_tc_word)
       {
         valid_tc_word = false;

         timeCode[11]= '\0';
         timeCode[10] = (tc[0]&0x0F)+0x30;      // frames
         timeCode[9] = (tc[1]&0x03)+0x30;      // 10's of frames
         timeCode[8] =  '-';
         timeCode[7] = (tc[2]&0x0F)+0x30;      // seconds
         timeCode[6] = (tc[3]&0x07)+0x30;      // 10's of seconds
         timeCode[5] =  '-';
         timeCode[4] = (tc[4]&0x0F)+0x30;      // minutes
         timeCode[3] = (tc[5]&0x07)+0x30;      // 10's of minutes
         timeCode[2] = '-';
         timeCode[1] = (tc[6]&0x0F)+0x30;      // hours
         timeCode[0] = (tc[7]&0x03)+0x30;      // 10's of hours

           drop_frame_flag = bit_is_set(tc[1], 2);

         write_tc_out = true;
       }
     }
    }

    void setup()
    {
     Serial.begin(9600);
     pinMode(8, INPUT);                  // ICP pin (digital pin 8 on arduino) as input

     bit_time = 0;
     valid_tc_word = false;
     ones_bit_count = false;
     tc_sync = false;
     write_tc_out = false;
     drop_frame_flag = false;
     total_bits =  0;
     current_bit =  0;
     sync_count =  0;

     Serial.println("Finished setup ");
     delay (1000);

     TCCR1A = B00000000; // clear all
     TCCR1B = B11000010; // ICNC1 noise reduction + ICES1 start on rising edge + CS11 divide by 8
     TCCR1C = B00000000; // clear all
     TIMSK1 = B00100000; // ICIE1 enable the icp

     TCNT1 = 0; // clear timer1
    }

    void loop()
    {
      if (write_tc_out)
       {
         write_tc_out = false;
         //if (drop_frame_flag)
           //Serial.print("TC-[df] ");
         //else
           //Serial.print("TC-[nd] ");
         Serial.println((char*)timeCode);
       //  Serial.print("  ");
         //Serial.print("\r");
       }
    }

Now to replicate this code for AVR ATmega8, I just copy this code in AVR studio and make small changes like initializing UART, initializing Input Capture Mode etc. Here is my AVR ATmega8 code:

    #define F_CPU 16000000UL

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <util/delay.h>
    #include <avr/sfr_defs.h>

    #define one_time_max          588 // these values are setup for NTSC video
    #define one_time_min          422 // PAL would be around 1000 for 0 and 500 for 1
    #define zero_time_max          1080 // 80bits times 29.97 frames per sec
    #define zero_time_min          922 // equals 833 (divide by 8 clock pulses)

    #define icpPin 8        // ICP input pin on arduino
    #define end_data_position      63
    #define end_sync_position      77
    #define end_smpte_position     80

    volatile unsigned int bit_time;
    volatile char valid_tc_word;
    volatile char ones_bit_count;
    volatile char tc_sync;
    volatile char write_tc_out;
    volatile char drop_frame_flag;

    volatile unsigned char total_bits;
    volatile unsigned char current_bit;
    volatile unsigned char sync_count;

    volatile unsigned char tc[8];
    volatile char timeCode[11];

    void USARTInit(uint16_t ubrr_value)
    {

     UBRRL = ubrr_value;
     UBRRH = (ubrr_value>>8);
     UCSRC|=(1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
     UCSRB=(1<<RXCIE)|(1<<RXEN)|(1<<TXEN);

    }

    unsigned char USARTReadChar()
    {

     while(!(UCSRA & (1<<RXC)));
     return UDR;
    }

    void USARTWriteChar(char data)
    {

     while(!(UCSRA & (1<<UDRE)));
     UDR=data;
    }

    void send_string(char s[])
    {
     int i =0;

     while (s[i] != 0x00)
     {
      USARTWriteChar(s[i]);
      i++;
     }
    }

    int main(void)
    {

     USARTInit(103);
     DDRB=0;
      bit_time = 0;
      valid_tc_word = 0;
      ones_bit_count = 0;
      tc_sync = 0;
      write_tc_out = 0;
      drop_frame_flag = 0;
      total_bits =  0;
      current_bit =  0;
      sync_count =  0;

     send_string("FINISHED SETUP");
     _delay_ms(1000);

     TCCR1A = 0;
     TCCR1B = (1<<ICNC1)|(1<<ICES1)|(1<<CS11);
     TIMSK = (1<<TICIE1);
     TCNT1 = 0;
     sei();
        while(1)
        {

      if (write_tc_out==1)
      {
       write_tc_out = 0;
       send_string((char*)timeCode);
            }
    }

    }

    ISR(TIMER1_CAPT_vect)
    {

     //toggleCaptureEdge
     TCCR1B ^= _BV(ICES1);
      //Serial.println("Inter");
     bit_time = ICR1;

     //resetTimer1
     TCNT1 = 0;

    if ((bit_time < one_time_min) || (bit_time > zero_time_max)) // get rid of anything way outside the norm
     {
       //Serial.println(bit_time, DEC);
       total_bits = 0;
     }
     else
     {
       if (ones_bit_count == 1) // only count the second ones pluse
         ones_bit_count = 0;
       else
       {
         if (bit_time > zero_time_min)
         {
           current_bit = 0;
           sync_count = 0;
         }
         else //if (bit_time < one_time_max)
         {
           ones_bit_count = 1;
           current_bit = 1;
           sync_count++;
           if (sync_count == 12) // part of the last two bytes of a timecode word
           {
             sync_count = 0;
             tc_sync = 1;
             total_bits = end_sync_position;
           }
         }

         if (total_bits <= end_data_position) // timecode runs least to most so we need
         {
             // to shift things around
           tc[0] = tc[0] >> 1;

           for(int n=1;n<8;n++)
           {
             if(tc[n] & 1)
               tc[n-1] |= 0x80;

             tc[n] = tc[n] >> 1;
           }

           if(current_bit == 1)
             tc[7] |= 0x80;
         }
         total_bits++;
       }

       if (total_bits == end_smpte_position) // we have the 80th bit
       {
         total_bits = 0;
         if (tc_sync)
         {
           tc_sync = 0;
           valid_tc_word = 1;
         }
       }

      if (valid_tc_word==1)
       {

         valid_tc_word = 0;

         timeCode[11]= '\0';
         timeCode[10] = (tc[0]&0x0F)+0x30;      // frames
         timeCode[9] = (tc[1]&0x03)+0x30;      // 10's of frames
         timeCode[8] =  '-';
         timeCode[7] = (tc[2]&0x0F)+0x30;      // seconds
         timeCode[6] = (tc[3]&0x07)+0x30;      // 10's of seconds
         timeCode[5] =  '-';
         timeCode[4] = (tc[4]&0x0F)+0x30;      // minutes
         timeCode[3] = (tc[5]&0x07)+0x30;      // 10's of minutes
         timeCode[2] = '-';
         timeCode[1] = (tc[6]&0x0F)+0x30;      // hours
         timeCode[0] = (tc[7]&0x03)+0x30;      // 10's of hours

           drop_frame_flag = bit_is_set(tc[1], 2);

         write_tc_out = 1;
       }

     }
    }

Now when I run this code, I don't get any time stamps. I have gone through this code many times but I am unable to figure out the mistake in my code. Can any one help me figure out the issue?

  [1]: http://forum.arduino.cc/index.php/topic,8237.0.html

body:
I figure out the issue , I just add a small delay in ISR and my code is running fine now. I don't know reason behind it but anyway my code is running now. Here is my new code:-

    #define F_CPU 16000000UL

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <util/delay.h>
    #include <avr/sfr_defs.h>

    #define one_time_max          588 // these values are setup for NTSC video
    #define one_time_min          422 // PAL would be around 1000 for 0 and 500 for 1
    #define zero_time_max          1080 // 80bits times 29.97 frames per sec
    #define zero_time_min          922 // equals 833 (divide by 8 clock pulses)

    #define icpPin 8        // ICP input pin on arduino
    #define end_data_position      63
    #define end_sync_position      77
    #define end_smpte_position     80

    volatile unsigned int bit_time;
    volatile char valid_tc_word;
    volatile char ones_bit_count;
    volatile char tc_sync;
    volatile char write_tc_out;
    volatile char drop_frame_flag;

    volatile unsigned char total_bits;
    volatile unsigned char current_bit;
    volatile unsigned char sync_count;

    volatile unsigned char tc[8];
    volatile char timeCode[11];

    void USARTInit(uint16_t ubrr_value)
    {

     UBRRL = ubrr_value;
     UBRRH = (ubrr_value>>8);
     UCSRC|=(1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
     UCSRB=(1<<RXCIE)|(1<<RXEN)|(1<<TXEN);

    }

    unsigned char USARTReadChar()
    {

     while(!(UCSRA & (1<<RXC)));
     return UDR;
    }

    void USARTWriteChar(char data)
    {

     while(!(UCSRA & (1<<UDRE)));
     UDR=data;
    }

    void send_string(char s[])
    {
     int i =0;

     while (s[i] != 0x00)
     {
      USARTWriteChar(s[i]);
      i++;
     }
     USARTWriteChar('\n');
    }

    int main(void)
    {

     USARTInit(103);
     DDRB=0;
     bit_time = 0;
     valid_tc_word = 0;
     ones_bit_count = 0;
     tc_sync = 0;
     write_tc_out = 0;
     drop_frame_flag = 0;
     total_bits =  0;
     current_bit =  0;
     sync_count =  0;

     send_string("FINISHED SETUP");
     _delay_ms(1000);

     TCCR1A = 0;
     TCCR1B = (1<<ICNC1)|(1<<ICES1)|(1<<CS11);
     TIMSK = (1<<TICIE1);
     TCNT1 = 0;
     sei();
     while(1)
     {

      if (write_tc_out==1)
      {
       write_tc_out = 0;
       send_string((char*)timeCode);
      }
     }

    }

    ISR(TIMER1_CAPT_vect)
    {

     //toggleCaptureEdge
     TCCR1B ^= _BV(ICES1);
     //Serial.println("Inter");
     bit_time = ICR1;

     //resetTimer1
     TCNT1 = 0;
    _delay_us(13);

     if ((bit_time < one_time_min) || (bit_time > zero_time_max)) // get rid of anything way outside the norm
     {
      //Serial.println(bit_time, DEC);
      total_bits = 0;
     }
     else
     {
      if (ones_bit_count == 1) // only count the second ones pluse
      ones_bit_count = 0;
      else
      {
       if (bit_time > zero_time_min)
       {
        current_bit = 0;
        sync_count = 0;
       }
       else //if (bit_time < one_time_max)
       {
        ones_bit_count = 1;
        current_bit = 1;
        sync_count++;
        if (sync_count == 12) // part of the last two bytes of a timecode word
        {
         sync_count = 0;
         tc_sync = 1;
         total_bits = end_sync_position;
        }
       }

       if (total_bits <= end_data_position) // timecode runs least to most so we need
       {
        // to shift things around
        tc[0] = tc[0] >> 1;

        for(int n=1;n<8;n++)
        {
         if(tc[n] & 1)
         tc[n-1] |= 0x80;

         tc[n] = tc[n] >> 1;
        }

        if(current_bit == 1)
        tc[7] |= 0x80;
       }
       total_bits++;
      }

      if (total_bits == end_smpte_position) // we have the 80th bit
      {
       total_bits = 0;
       if (tc_sync)
       {
        tc_sync = 0;
        valid_tc_word = 1;
       }
      }

      if (valid_tc_word==1)
      {

       valid_tc_word = 0;

       timeCode[11]= '\0';
       timeCode[10] = (tc[0]&0x0F)+0x30;      // frames
       timeCode[9] = (tc[1]&0x03)+0x30;      // 10's of frames
       timeCode[8] =  '-';
       timeCode[7] = (tc[2]&0x0F)+0x30;      // seconds
       timeCode[6] = (tc[3]&0x07)+0x30;      // 10's of seconds
       timeCode[5] =  '-';
       timeCode[4] = (tc[4]&0x0F)+0x30;      // minutes
       timeCode[3] = (tc[5]&0x07)+0x30;      // 10's of minutes
       timeCode[2] = '-';
       timeCode[1] = (tc[6]&0x0F)+0x30;      // hours
       timeCode[0] = (tc[7]&0x03)+0x30;      // 10's of hours

       drop_frame_flag = bit_is_set(tc[1], 2);

       write_tc_out = 1;
      }

     }
    }


message:
Linker error when trying to use functions in separate header and source files

It is my first day of working with Arduino (it is a Due). I want to read from TMP102 through I2C. I wrote some code and it works just fine. But now I want to separate the TMP102 code from the main source code. But I get linker error:

> sketch_jun15a.ino.cpp.o: In function `setup':
> C:\Users\Saeid\Desktop\sketch_jun15a/sketch_jun15a.ino:62: undefined
> reference to `tmp102_allocate(int)' collect2.exe: error: ld returned 1
> exit status

My code is at the moment consist of 3 files:

**tmp102.h**

    #ifndef TMP102_H
    #define TMP102_H

    //TP102 sensor struct
    typedef struct TMP102 {
      int   address;
      float celsius;
      float fahrenheit;
    } tmp102_t;

    tmp102_t* tmp102_allocate(int address);

    void tmp102_init_struct(tmp102_t * t, int address);

    #endif

**tmp102.c**

    #include "tmp102.h"

    tmp102_t* tmp102_allocate(int address) {
      tmp102_t* t = (tmp102_t*) malloc(sizeof(tmp102_t));
      if(t) { //allocation success
        tmp102_init_struct(t, address);
        return t;
      } else {
        return 0; //null pointer
      }
    }

    void tmp102_init_struct(tmp102_t* t, int address) {
      t->address = address;
      t->celsius = 0.0;
      t->fahrenheit = 0.0;
    }

and here is the setup function of the sketch:

    #include "tmp102.h"
    void setup(){

      //setup TP102 sensors
      tp_1 = tmp102_allocate(72); //error is here
      tempSensors[0] = tp_1;

      //rest of stuff...

    }

I think there is no mistake in the code. There is also no option in the Arduino IDE so that I can meddle with the compiler/linker options.

All the files are inside the sketch folder. I created these files using the drop down button in the IDE...

body:
This is talked about [here][1].  Evidently, the C++ compiler changes names of *.c files when compiling.  Try changing the names of your files from *.c to *.cpp so that the C++ compiler does not change the names. Then recompile.

  [1]: http://forum.arduino.cc/index.php?topic=57691.0


body:
The reason you are getting the undefined reference to  `tmp102_allocate(int)' is because your c source file is being converted to a cpp file and the function name is being mangled to support overloading etc etc. You need to flag that the functions are c code with  extern "C" blocks. If you change your header file to  the following it should compile. Alternatively, if you change the extension of your source file to .cpp you won't have any issues with name mangling but your code will probably not work (malloc). Note that by checking if __cplusplus is defined you can use this header in both cpp and c projects.

**tmp102.h**

    #ifndef TMP102_H
    #define TMP102_H

    #ifdef __cplusplus
      extern "C" {
    #endif

    //TP102 sensor struct
    typedef struct TMP102 {
      int   address;
      float celsius;
      float fahrenheit;
    } tmp102_t;

     tmp102_t* tmp102_allocate(int address);

    void tmp102_init_struct(tmp102_t * t, int address);

    #ifdef __cplusplus
      }
    #endif

    #endif

  [1]: http://forum.arduino.cc/index.php?topic=69952.0


message:
Ethernet Controlled Arduino Arm

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

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

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

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

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

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

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

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

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

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

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

            }
          }
        }
      }
    }

body:
Question 1 will need more information about your code and your wiring of the arm to offer any reasonable answer.

Question 2: There really isn't much to go on but I'll take a guess that you're sending a single message to the arm server on each button press - ? I'd try instead, sending another message every 't' starting at (.75 * t) from message-1, where 't' is the time taken for the arm to move 5 degrees. That's a totally wild guess based on unfounded assumptions of what's happening now, and what fraction of 't' I guess would make sense, but that would be my first, very experimental approach. And even so, given the non-determinism of internet packet arrival times, I wouldn't bet on getting very smooth motion, nor instant stopping on button release.

My next experiment would be send start moving/keep moving commands to the arm on button-press, stop moving on button-release, with the arm controller being smart enough to 1) stop anyway after some short period of no messages or it reaches its limit, and 2) not let commands accumulate (or the arm will keep driving until it limits).

Update:<br>
Yes, if you're using a terminal emulator that has the ability to send each keystroke rather than line-by-line, and doesn't suppress key-repeat. As above, don't accumulate incoming keystrokes but when you're looking for another, drain the buffer first then watch for an incoming one. If you don't find it within <TIMEOUT>, stop moving. <TIMEOUT> should be slightly longer than the key-repeat interval.

(I like my second way better - winging it at the keyboard, heh! - but if it were me, I'd probably try both anyway just for what I could learn from either one).


message:
Arduino Uno: Pullup Resistor

I have been reading a bit about the internal pullup resistor. I know from past projects in school that resistor themselves are fragile (burnt one by accident due to higher current than was made for).

I have two different Arduino models. One by Intel and rest are standard Arduino Uno.

So I was wondering about safely using the internal pullup resistor on the Arduino Uno. Hence my question is about the internal pullup resistor pinmode; How many pin can you connect to it safely and not overload it?

body:
Each pin has its own, separate, pullup resistor.

I don't believe you can damage it by drawing current from the port, because the pullup resistor is only active when the port is in high impedance (hi-Z, input) mode.

The pullup resistor can be damaged by overvoltage, static discharge, and the like.

The Uno has 20 kOhm pullup resistors according to [this tutorial](https://www.arduino.cc/en/Tutorial/DigitalPins). If you feed it a 0V signal while the Atmega is running at 5V, the current will be a quarter of a milliamp, which is miniscule.


message:
How can you reduce the clock frequency of an Arduino Mega?

I'm trying to debug a problem and need to reduce the speed of the clock on my Arduino Mega from 16MHz to 8MHz.

I can't find any simple way of doing so, so I wanted to know if there were any gurus here who knew if this was possible, as well as how to do it.

WITHOUT PRESCALER:

    long int runTime;

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

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

    OUTPUT: 999

WITH PRESCALER:

    long int runTime;

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

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

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

    OUTPUT: 999

body:
You can set the clock prescaler for that:

<!-- language-all: lang-c++ -->

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

This is explained in section 10.12 and 10.13 of the
[ATmega2560
datasheet](http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf).

Of course, changing the clock frequency will mess with the time-related
function (`millis()`, `delay()` and co.) and the baud rate of the serial
port.

**Edit**: Here is a small program to demonstrate the slowing of the
clock:

    //#define SLOW_CLOCK

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

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

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


message:
Want to create bluetooth audio control (volume up/down, play, pause, etc.) for smartphone

I want to create a bluetooth remote audio control to control smartphone audio, essentially identical in function to this type of equipment:

[![Bluetooth audio control][1]][1]

https://www.amazon.com/FAVOLCANO-Bluetooth-Button-Smartphone-Samsung/dp/B01C5E95XG/ref=pd_lpo_147_bs_t_1?ie=UTF8&refRID=1GRBCPDRMD9YPYPGK73Y

This device is simply a bluebooth remote control which allows you to play or pause audio, skip forward or backward and change media volume on the smart phone.

All of the Arduino tutorials I see are about either using the iPhone to control a bluebooth device, or about using bluetooth to control an arduino, neither of which are what I want to do.

Can you point me in the right direction?

  [1]: https://i.stack.imgur.com/COMqF.jpg

body:
[Bluetooth][1] supports multiple protocols for multiple purposes.  There is low latency low quality monorail bi-directional communication with a little bit of bandwidth for control for Bluetooth phone calls.  This is called [HFE Bluetooth protocol][2].  If you are interfacing a keyboard or a mouse you would use the [Human Interface Device protocol or HID][3].  If you wanted to listen to music and control it's playback you would use the high latency high quality 2 audio sending channels (stereo) no return audio channel with a little bit of bandwidth for controlling playback called [Advanced Audio Distribution Profile or A2DP][4].

In this specific case we are only interested in controlling playback.  So we could use the HID Bluetooth protocol.  However, the native music players on the platform you are using (Android or iPhone) likely will not be listening to such a device.  In order for this to work you will probably have to write your own Android or iPhone music player.

On the other hand, it is likely the native music players will work with A2DP Bluetooth protocol.  Unfortunately, it is also suspected that once the A2DP Bluetooth connection is established, the phone's speaker will be shutdown and all audio will be diverted to the Bluetooth connection.

Finally, there is the [Audio/Video Remote Control Profile or AVRCP][5].  This protocol is used to control media playback.  There are several versions of this protocol so what features are available for a given device / music-application may vary greatly.

  [1]: https://en.wikipedia.org/wiki/List_of_Bluetooth_protocols
  [2]: https://en.wikipedia.org/wiki/List_of_Bluetooth_profiles#Hands-Free_Profile_.28HFP.29
  [3]: https://en.wikipedia.org/wiki/List_of_Bluetooth_profiles#Human_Interface_Device_Profile_.28HID.29
  [4]: https://en.wikipedia.org/wiki/List_of_Bluetooth_profiles#Advanced_Audio_Distribution_Profile_.28A2DP.29
  [5]: https://en.wikipedia.org/wiki/List_of_Bluetooth_profiles#Audio.2FVideo_Remote_Control_Profile_.28AVRCP.29


body:
I can add something to @st2000's excellent answer (in a better format than our discussion in the comments there).

The original question is vague. Does Bluetooth mean Classic or is Low Energy (BLE) acceptable or preferred. Which smartphones must be supported? Apple and/or Android? And what minimum version must be supported?

The 2.5 years that have passed since this question was asked makes it easier to choose BLE because adoption is so prevalent now.

I've been researching what it would take to implement a media control device as described in the original post. My target smartphone is Android Nougat. My goal is to skip podcast commercials. I have tested using a Bluetooth Classic keyboard. The media control buttons, Play/Pause, skip forward, skip back, etc. seem to do what I need.

I'd prefer to use BLE's support for keyboards and other Human Interface Devices: HID over Gatt Profile (HOGP). The [KitKat release notes](https://developer.android.com/about/versions/kitkat#44-bluetooth) say that's when HID over GATT support was added, so it's been around for a while.

Having decided on a Bluetooth LE profile, device selection remains. [Adafruit Bluefruit LE UART Friend](https://www.adafruit.com/product/2479) has a [HIDKeyboard](https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend/hidkeyboard) example. I prefer an MCU with integrated BLE support. While total overkill for this application, I have an ESP32 that I plan to use for this. It has good community support and is cheap. If battery life (or size) becomes a problem, I'll look for a lesser device.


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


message:
How can I generate a sinewave with Arduino Uno?

I would like to generate a sine wave with my Arduino Uno. As far as I know, there is no library for Uno to generate such a signal (correct me if I'm wrong), so the only option available is to write a function to generate the signal from scratch.

As far as my understanding of digital electronics goes, I believe it is possible to generate a sine wave signal by using PWM and varying the duty cycle accordingly. However, this route seems to me quite long, what other options do I have?

body:
There are two parts to this:

One is the creation/derivation/storage of the _digital representation_ of a sine wave. The other is the conversion of the digital representation of a sine wave to an analog voltage (if I understand what you want).

---

The easiest way to obtain the digital representation of a sine wave is a lookup table. Precompute the digital values, and store them in an array. Simple. It is up to you to decide how much resolution (both in vertical accuracy/number of bits and horizontal accuracy/number of samples) you require.

It is also possible to compute the values directly. There are a number of ways of doing this, but be aware that using floating point math on the Arduino is very slow and space-intensive. You may want to look at [CORDIC](https://en.wikipedia.org/wiki/CORDIC) for one possible solution to this.

---
Next is the conversion to analog. You are right, PWM is one way to do this, and one of the easiest as far as external components go: you only need an RC filter to smooth the PWM. However, PWM is limited in resolution, and performs poorly when your wave frequency becomes a significant fraction of your PWM frequency. Also, the Arduino doesn't run very fast, so your PWM frequency is limited.

Other DAC solutions (there are many many many, so I'm not going to go in depth on this):

- R2R DAC: simple to construct, but requires precision resistors for decent resolution, limited in resolution, and requires many IO pins.

- "proper" DAC: an I2C/SPI DAC can give you far better performance, but you will have to learn how to communicate with it. And it's going to be more expensive, and involve several components.

---

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

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

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

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

This is quite straightforward.


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

You are wrong, there is [Mozzi][], the sound synthesis library for
Arduino. It works essentially along the lines sketched by uint128\_t.
Take a look at the [Sinewave.ino][] for an example on how to make a
(lookup table-based) sine wave. It can also do much more.

In its default mode, Mozzi works with a 16,384 Hz sample rate and a
32,768 Hz (not audible) PWM frequency.

[Mozzi]: http://sensorium.github.io/Mozzi/
[Sinewave.ino]: https://github.com/sensorium/Mozzi/blob/master/examples/01.Basics/Sinewave/Sinewave.ino


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


body:
You can get a very fast, accurate, and compact sin(theta) function using a simple table of values.  Just pull the code you need from the cordic.c here: https://people.sc.fsu.edu/~jburkardt/c_src/cordic/cordic.html.  C runs in Arduino sketches almost out of the box.  You may or may not need some things from the cordic.h.  That's why I said "almost".  The cordic_prb.c test file has a function test002() that shows you how to call the sine function.

Because the Uno does not have a real D-to-A converter, you will only get a rectangular wave that has digital noise over the primary harmonic.  That's the down side of the pulse width modulation of the lower end Arduino chips.  You will need a filter on the analog output if you need to remove the higher frequency noise harmonics.


message:
Sleep and Wake Arduino according to LDR interrupt

I have to sleep the system in the night and have to wake the system in day time. I am using LDR to get input. LDR input is connected to interrupt pin 0 of Arduino Uno.

Here is my code.

    #include <avr/sleep.h>
    int led =13;
    int triggerPin = 2;

    void wakeUpNow()
    {

    }

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

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

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

Cannot we attach two function in a interrupt?

**Edited**
The following code works perfectly. I want to replace the conditional check with interrupt.

    #include <avr/sleep.h>
    int led =13;
    int wakePin = 2;

    void wakeUpNow()
    {
    delay(100);
    }

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

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

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

    }

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

I want to replace `

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

with`

    attachInterrupt(0, sleepNow, LOW);

Please let me know how I can do that.

Thank you.

body:
> I want to replace the conditional check with interrupt.

Why? If it is awake it might just as well be testing the pin as doing anything else.

If you make it an interrupt, in the ISR interrupts will be off. Then if you go to sleep it will never wake.

So, your current design is the correct one, except:

    attachInterrupt(0,wakeUpNow, RISING); function

What is `function` doing there?


message:
Can I connect a camera to an arduino mini?

I was wondering if it was possible to connect a camera like [this][1] onto an Arduino mini and have the Arduino save video and audio to a micro SD card.

  [1]: http://www.ebay.com/itm/HD-Mini-CCTV-Camera-Security-Micro-Audio-Wired-600TVL-1-4-5Mp-0-5LUX-/171421181800?hash=item27e97fa768:g:MbMAAOSwEK9T7Fwt

body:
Not really (at least, not with any appreciable quality). Basically, the bandwidth involved is simply too much for the Arduino's relatively slow 16MHz core speed. You might be able to periodically capture greyscale lowres frames, but capturing the full 1280x960 resolution at any decent framerate is basically impossible.

If you want to find Arduino projects that involve capturing video like this, the search term is `arduino composite video input`. There are many projects out there that interface the Arduino with a composite input, but none that I know of that can capture full video. Consider the following: your Arduino runs at 16 MHz. If you were to handle 640x480 greyscale video (1 byte per pixel), that would be a data bandwidth (disregarding signal bandwidth) of 640*480*30 = 9216000 bytes/second. That's a pretty tall order: even if you could process each pixel in two (single cycle) instructions with no overhead, you still wouldn't have enough processor bandwidth.

If all you want to do is record composite video to an SD card, there are far easier options out there, search `composite video recorder sd`.


message:
MPU9250 - Calibration Not Saved with RTIMULib EEPROM Issues

I'm using the MPU9250 and the RTIMULib to perform sensor fusion, however, when I run ArduinoMagCal, and save the calibration, and follow that with running the main ArduinoIMU it claims the calibration file is not saved, and there is no data to use. I'm trying to determine why this is - I have tried the other MPU9250 libraries without luck, as this one is working on my setup (Arduino Micro -> eventually NodeMCU).

Repo : https://github.com/maxouille/RTIMULib-Arduino

ArduinoMagCal

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

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

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

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

    #define  SERIAL_PORT_SPEED  115200

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

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

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

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

    void loop()
    {
      boolean changed;
      RTVector3 mag;

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

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

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

ArduinoIMU

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

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

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

    //  DISPLAY_INTERVAL sets the rate at which results are displayed

    #define DISPLAY_INTERVAL  300                         // interval between pose displays

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

    #define  SERIAL_PORT_SPEED  115200

    unsigned long lastDisplay;
    unsigned long lastRate;
    int sampleCount;

    void setup()
    {
        int errcode;

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

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

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

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

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

        fusion.setSlerpPower(1);

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

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

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

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

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

Lastly in the repo, you will see a CalLib folder with the CalLib.cpp program inside, wondering if it is saving to the EEPROM incorrectly?

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

    #include "CalLib.h"
    #ifdef __SAM3X8E__

    // Due version

    #include "DueFlash.h"

    DueFlash flash;

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

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

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

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

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

    #else

    // AVR version

    #include <EEPROM.h>

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

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

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

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

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

      calData->magValid = false;

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

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

body:
There was a compilation error which was preventing me from seeing that the data was indeed being saved to EEPROM, as far as I know there are no more issues. Just be mindful if you want to test it to add this in your calibration file after the save line:

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


message:
Set PWM frequency to 25 kHz

I currently can set four PWM pins to around 31 kHz with the following code:

<!-- language: lang-cpp -->

    void setup()
    {
        TCCR1B = TCCR1B & B11111000 | B00000001; // Set PWM frequency for D9 & D10:
        pinMode(pwmPin9, OUTPUT); // Sets the pin as output
        pinMode(pwmPin10, OUTPUT); // Sets the pin as output

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

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

body:
You can configure Timer 1 to cycle at 25 kHz in phase correct PWM mode, and use it's two outputs on pins 9 and 10 like so:

<!-- language: lang-c++ -->

    // PWM output @ 25 kHz, only on pins 9 and 10.
    // Output value should be between 0 and 320, inclusive.
    void analogWrite25k(int pin, int value)
    {
        switch (pin) {
            case 9:
                OCR1A = value;
                break;
            case 10:
                OCR1B = value;
                break;
            default:
                // no other pin will work
                break;
        }
    }

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

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

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

Writing a value of 0 with `analogWrite25k()` means the pin will be
always LOW, whereas 320 means always HIGH. The regular `analogWrite()`
should _almost_ work, but it will interpret 255 the same as 320 (i.e.
always HIGH).

This code assumes an Arduino Uno or similar board (ATmega168 or 328 @
16 MHz). The method used here requires a 16-bit timer, and thus it
uses Timer 1 as it's the only one available on the Uno; that's why only
two outputs are available. The method could be adapted to other
AVR-based boards with a 16-bit timer. As Gerben noted, that timer should
have a corresponding ICRx register. There are 4 such timers on the
Arduino Mega, each with 3 outputs.


body:
I am posting this second answer since I realized it is possible to have
4 PWM channels at 25 kHz with 161 steps on a single Arduino Uno. This
involves [changing the main clock frequency to 8 MHz][8MHz], which
has some side effects since the whole program will run half as fast. It
also involves reconfiguring the three timers, which means loosing the
Arduino timing functions (`millis()`, `micros()`, `delay()` and
`delayMicroseconds()`). If these trade-offs are acceptable, here is how
it goes:

<!-- language: lang-c++ -->

    void setup()
    {
        // Set the main system clock to 8 MHz.
        noInterrupts();
        CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
        CLKPR = _BV(CLKPS0);  // divide frequency by 2
        interrupts();

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

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

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

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

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

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

[8MHz]: https://arduino.stackexchange.com/questions/25591
[other answer]: https://arduino.stackexchange.com/a/25623


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

[![Circuit diagram][1]][1]

  [1]: https://i.stack.imgur.com/mfLOP.jpg

I have acquired the arduino starter kit project book, and the explanations seem at times confusing and difficult to understand.

Concerning the above circuit diagram, the book states (I am translating from French): *"The resistor and the photoresistor are in series and together they divide up the voltage. The voltage at the point where they meet is proportional to the ratio of their resistances, according to Ohm's Law."*

1. What does "the voltage at the point where they meet" mean? The voltage/ p.d. is always supposed to be across something, e.g. a certain component. This statement makes no sense to me at all.

2. The above misunderstanding leads on to me not understanding what the input pins A0-A2 actually receive. I understand that they receive a voltage, but don't know across what. Also, if the voltage inputs from these pins are used later on, are they digital? (these pins have an analogue-digital converter).

body:
1. I think what it means is that A0 = (5V / (Photo Resistor + 10K)).  Since the Photo Resistor will vary the voltage you get at A0 will be proportional to the light.  So by rearranging the formula above (I'm no good at doing that so you are on your own) you can convert the number received by A0 into the resistance that the photo resistor as applying and presumably turn that into Lux (?).

2. The analog pins report a number between 0 and 1023.  I can never remember if this equates to receiving a voltage of 0 - 5V or 0 - 2.5v.  Either way it is a linear conversion, so you can use (5V/1024)*reading to work out what the voltage at the pin is (or (2.5C/1024)*Reading).

Hope that helps.


body:
The analog inputs of the arduino can't read resistances. They read voltages and compare them with a reference voltage. They give you a number between 0 and 1023 so the read voltage is 1/1024 of the reference voltage.

The configuration of the LDR and the resistor is called a voltage divider. It is needed to get a voltage that the analog pin can read.

The intersection of the LDR and the resistor is where you can measure that voltage (or connect it to the analog pin of the arduino).

More info about this subject was already given in this question:

https://arduino.stackexchange.com/questions/7921/why-do-you-need-a-second-resistor-when-using-a-photoresistor-ldr

Wiki page about voltage dividers and the relevant formulas

https://en.wikipedia.org/wiki/Voltage_divider


body:
The important thing to remember, which will help you understand everything else, is that *voltage is measured **with respect to another point***.

In this (and almost every) case it is measured *with respect to* ground. So when you say the voltage at point X is Y volts you are actually saying that the difference in voltage between point X and GND is Y volts.

So on your schematic A0 measures the difference in voltage between it's IO pin (the junction between the 10KΩ resistor and the LDR) and ground. And looking at it, what is between its IO pin and ground? The 10KΩ resistor. So it is actually the voltage across that resistor that you are measuring.

Doing the sums:

Assume there is enough light falling on the LDR to make it have a resistance of 5KΩ.  Current flows through both the LDR and the 10KΩ resistor in series, so it has a total resistance of (10,000 + 5,000) 15KΩ. With 5V across the whole lot (5V -> LDR -> 10KΩ -> GND) you get:

    I = V/R = 5/15,000 = 0.000333... or 333µA.

333µA flowing through 10KΩ drops how much voltage?

    V=RI = 10,000 × 0.000333... = 3.333...V

So A0 would be measuring 3.333V at that point.

Now, you turn out the lights, and the resistance of the LDR rises to, say, 50KΩ. What happens to those sums now?  Well, let's look:

    Total resistance = 50,000 + 10,000 = 60,000Ω
    I=V/R = 5/60,000 = 0.00008333...
    V=RI = 10,000 × 0.00008333... = 0.8333...V

The formulae can be simplified into just the ratio of the two resistances:

               R2
    Vout = --------- × Vin
            R1 + R2

So that is, with the lights on:

            10,000
    Vout = --------- × 5 = 0.666... × 5 = 3.333...
            15,000

And with the lights on:

            10,000
    Vout = --------- × 5 = 0.1666... × 5 = 0.8333...
            60,000

From that measured voltage, of course, you can then calculate what the resistance of the LDR must have been at the time. Rearranged the formula looks like:

          R2 × Vin
    R1 = ---------- - R2
            Vout

Plug in the numbers for the voltage with the lights on:

          10,000 × 5              50,000
    R1 = ------------ - 10,000 = -------- - 10,000 = 5,000Ω
           3.333...              3.333...

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


message:
How to properly receive data from accelerometer @ arduino in processing and map it?

I'm busy making a project where my accelerometer @arduino can controle a ellipse @processing

But the problem is, it doesn't work. With the code I have now, I can receive the data from the accelerometer in processing. But my map function doesn't seem to work because with my code, the ellipse doesn't move at all. When i want to map the val (string) it says it must be a float to be mapped. I've tried to convert the string into a float but it doesn't work at all..

Hope someone can help me out!

My arduino Code:

    #include <Wire.h>
    #include <Adafruit_MMA8451.h>
    #include <Adafruit_Sensor.h>

    int waardeX;
    int waardeY;

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

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

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

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

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

    }

    void loop() {

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

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

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

Processing code:

    import processing.serial.*;

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

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

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

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

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

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

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

body:
The problem you are facing is that you are sending the string:

    X:⇥23.87⇥Y:⇥11.34

and trying to interpret that as a single number. It's just not going to happen. There's two numbers and two labels there.

Instead you are going to have to parse the string to get at the individual components.

You might want to look at the java [String.split()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)) function to convert the string into an array of 4 items, then you can use the second and fourth slices (slices 1 and 3 since it's zero-based) and convert them to floats.


message:
MPU6050 hanging/freezing

I am really short of interrupt pins on my Arduino because I have a project that already uses a lot of Arduino pins and to read DMP data from MPU6050 you always have to use an interrupt pin. I searched A LOT in the internet and many people says it's impossible to retrieve DMP data without interrupt pin. Some people also said the only way to do that would be if I could reverse engineer the MPU6050 code (which I don't know how to do).

But today, playing with MPU6050 I could finally get all of its DMP data without the interrupt pin, you just have to connect 4 pins (VCC, GND, SCL and SDA). Upload the code below to your Arduino and see that it works!

<!-- language: lang-cpp -->

    #include "MPU6050_6Axis_MotionApps20.h"
    MPU6050 mpu;
    uint16_t packetSize;
    uint16_t fifoCount;
    uint8_t fifoBuffer[64];
    Quaternion q;
    VectorFloat gravity;
    float ypr[3];

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

      Serial.begin(115200);
    }

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

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

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

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

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

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


message:
WiFi thermometers: save different location string as const across many devices

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

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


message:
Do I need more voltage to close this circuit?

I'm hacking together a RF-controlled garage door opener. I'm tapping the "receiving" end in to the push button wires.

When the two wires touch, it toggles the garage door motor.

I'm trying to basically "close" this circuit through a 5V Trinket Pro with...

`pinMode(A0,OUTPUT);` in `setup` and `digitalWrite(A0,LOW);` in the `loop`.

Using the multimeter, it would seem that the wires for the push button are normally closed (I think that's correct) as I get a 15v read on the multimeter when I check the current.

When I touch the wires, the current drops to 0.

My understanding was that the `digitalWrite(A0,LOW);` would basically "complete" the circuit, but it doesn't seem to do anything.

So, my question is: Given I've only got 5v running through the Trinket Pro, is that not enough to toggle the garage door circuit given it's putting out  15v in it's NC state?

If that's the case, is there some other way around that without needing to push 15v of power?

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

Update:<br>
A relay has 4 specs that you need to consider up front:

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

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

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

Or, in the case of an SSR, to prevent letting out the Magic Smoke that makes them work.

If you use a relay you'll need a driver circuit between the Arduino pin and the relay, with a snubber - a diode that grounds the reverse voltage "kickback" from the relay coil when you open its circuit - also to protect the Magic Smoke in your Arduino.

You're hacking into your remote "clicker", not the garage-door tractor itself, right? If that's the case, just about anything with a 5v coil 15v+ contacts will do. The remote button only has to switch a tiny transmitter on/off. If you do need to hack into the tractor, you'll want to find out what's behind its receiver terminal. It's probably not the motor but another relay, but....

A ready source of such a relay is your/another garage door remote receiver. It has a relay in it that is already doing that job.


message:
ADXL345 I2C setup not returning anything

My hookup is like this:

GND - GND  VCC - 5V  CS - 5V  SDO - GND  SDA - A4  SCL - A5

Here is the code:

    #include <Wire.h>
    #include <ADXL345.h>

    ADXL345 accelerometer;

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

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

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

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

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

      // Check settings
      checkSetup();
      }
    }

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

    void loop(void)
    {
      delay(50);

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

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

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

It comes from this Github link: https://github.com/jarzebski/Arduino-ADXL345/blob/master/ADXL345_free_fall/ADXL345_free_fall.ino

Initially, it would return "Could not find a valid ADXL345 sensor, check wiring!" in serial monitor. After messing with some wiring and changing to SPI
and back to I2C, it only returns "Initialize ADXL345".

I've added the second if() statement because it wouldn't say anything other than "Initialize ADXL345" even with the first if() statement, or with the first if() followed by an else. It should print the Free Fall Threshold and Duration but it hasn't. I have to leave and won't be back until tomorrow, so when I get back I'll try removing the checkSetup() command and maybe put something else in it's place to verify it's working. I feel like the answer is staring me in the face.

EDIT: Okay so after I finally got up from my computer for once, a thought popped into my mind and I figured the reason why checkSetup() isn't returning either string is because it's declared after setup() calls checkSetup()? Am I right? I feel like this would be the case in other languages.

body:
You may have damaged the chip with 5 V already. Sparkfun didn't include a regulator in their breakout. Your pull-ups are also too small; significant current flows when the I2C lines are pulled low. Use two 4.7k or 10k resistors instead. Assuming your Redboard is just like the Uno, connect pin 2 to the INT1 pin of the breakout, to make use of the interrupt capabilities. You also need to call `attachInterrupt()` and register a handler.

However, you bought this module from Sparkfun, as well as your Redboard. You should first follow their [tutorial][1] and library before trying any others. Theirs is SPI-based though. If you must use I2C, try out the Adafruit library.

  [1]: https://www.sparkfun.com/tutorials/240