message:
Wifi Data Logger without Delay

I am really new to Arduino so please bear with me.

I am running an Arduino Uno with several sensors to capture some data related to a fish tank. Here is basically what it does:

 - Capture data (light, temperature, etc.)
 - Display data on an LCD screen when a button is pressed
 - Upload data to thingspeak every 5 minutes, using a ESP8266
 - Feed the fish every 4 hours through a servo
 - An RGB led blinks at various colors to let me see what's happening (e.g. red when connecting to wifi).

Everything is working reasonably well. That being said, my code is super messy and I am not sure I have the right approach. With the code I have:
 - Nothing can be done while the Arduino uploads the wifi
 - Nothing can be done when the fish are fed.

This is not so much about the servo, it is more about the wifi problem. How would you suggest that I rewrite my code so that (1) I can run the wifi more than once every 5 minutes and (2) it does not block my sensors and LCD display while I am doing it.

Sorry for the poor quality of the code. Newbie here.
<!-- language-all: lang-cpp -->

    //Include LCD Libraries
     #include <Wire.h>
     #include <LiquidCrystal_I2C.h>
     #include <stdlib.h>

    //Include Water Probe library
     #include <OneWire.h>

    //Include DHT11 Libraries
     #include <dht11.h>

    //Include Servo Libraries
     #include <Servo.h>

    //Set Peripherals
     dht11 DHT11;
     LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display
     Servo myservo;  // create servo object to control a servo

    //Pins for LCD are SDA=A4 and SCL=A5

    //Variables for sensors
        String sunlight;
        String watertemp;
     float airtemp;
        float airhumid;
        OneWire  ds(10); //water temperature, pin 10

    //Variables for LCD button
     #define BUTTON_PIN A3    // Set pin Buttons for Backlight LCD.
     unsigned int currentLcdLightOnTime = 0; // For calculating the lcd light on time.
     unsigned long lcdLightOn_StartMillis;
     boolean isLcdLightOn;
     int buttonState = 0;// For checking push-button state.

    // Variables for Status LED
     int ledState = LOW;             // ledState used to set the LED
     long previousMillis = 0;
     long interval = 1000;           // interval at which to blink (milliseconds)

    //Variables to display LCD Numbers
     char bufferhours[5]; //Output of the itoa function for hours
     char bufferminutes[5]; //Output of the itoa function for minutes
     // We don't care for seconds. It's irrelevant.
     int moisture;

    //Variables for Wifi Update
     //long DELAYWIFI = 10000; //For test purposes
     long DELAYWIFI = 300000; //Every 5 minutes
     long endtimewifi;
     long nowwifi;

    //Variables for Servo
     long FEEDINGDELAY = 14400000; // Feed every 4 hours
     //long FEEDINGDELAY = 30000; //For test purposes
     int pos = 0;    // variable to store the servo position
     long endtime;
     long now;
     long timeuntilfeeding;

    //Variables for Sunlight
     float percent; //transform number above into a percent

    // Variables for Wifi Updates

     #include <SoftwareSerial.h>

     //Hardware Serial
     #define _baudrate 9600

     //Software Serial
     #define _rxpin      0
     #define _txpin      1
     SoftwareSerial esp8266( _rxpin, _txpin ); // RX, TX

     //Thingspeak and Wifi Information
     #define SSID "xxx"
     #define PASS "yyy"
     #define IP "zzz" // ThingSpeak IP Address: 184.106.153.149

     // GET /update?key=[THINGSPEAK_KEY]&field1=[data 1]&filed2=[data 2]...;
     String GET = "GET /update?key=www";

    // Initiates special characters. http://omerk.github.io/lcdchargen/

    byte thermometer[8] = //icon for thermometer
    {
        B00100,
        B01010,
        B01010,
        B01110,
        B01110,
        B11111,
        B11111,
        B01110
    };

    byte droplet[8] = //icon for water droplet
    {
        B00100,
        B00100,
        B01010,
        B01010,
        B10001,
        B10001,
        B10001,
        B01110,
    };

    byte degree[8] = { // degree centigrade
      B01000,
      B10100,
      B01000,
      B00011,
      B00100,
      B00100,
      B00011,
      B00000
    };

    byte sun[8] = {
     0b00100,
     0b10001,
     0b01110,
     0b11111,
     0b11111,
     0b01110,
     0b10001,
     0b00100
    };

    void setup()
    {
      lcd.init();// initialize the lcd

    //Initialize DHT/
     DHT11.attach(2);

    // set the digital pin as output for LED:
     pinMode(13, OUTPUT);
     pinMode(12, OUTPUT);
     pinMode(11, OUTPUT);

    //Connect to Wifi
     Serial.begin(9600);
       esp8266.begin(9600);
       boolean wifi_connected=false; //not connected yet...

       sendesp8266("AT");
       delay(2000);
     for(int i=0;i<5;i++) //attempt 5 times to connect to wifi - this is a good idea
     {
     if(connectWiFi()) //are we connected?
     {
     wifi_connected = true; //yes
     break; //get outta here!
     }
     }

    //Initiate characters
        lcd.createChar(0, thermometer);
      lcd.createChar(1, droplet);
      lcd.createChar(2, degree);
      lcd.createChar(3, sun);

    }

    void loop(){
     now = millis();
     endtime = now + FEEDINGDELAY;

     while(now < endtime) {   // While loop for the feeding
     timeuntilfeeding = endtime - millis();
     now = millis();

        nowwifi = millis();
     endtimewifi = nowwifi + DELAYWIFI;

        while(nowwifi < endtimewifi) {   // While loop for wifi update
     nowwifi = millis();

    //We capture sensors

        //Sunlight
        float value_sunlight = analogRead(A2);
        percent = value_sunlight / 1024.0 * 100;  //Convert dryness score into moisture percentage
        String sunlight =String(percent);// turn integer to string

        //Water Temperature
        float value_watertemp = getTemp();
       String watertemp= String(value_watertemp);// turn integer to string

     //Air Temperature and Humidity
     int chk = DHT11.read(); //Read DHT11 Sensor
      float airtemp=float(DHT11.temperature);// turn integer to string
       float airhumid=float(DHT11.humidity);// turn integer to string

        // LED Blinking
     unsigned long currentMillis = millis();
     if(currentLcdLightOnTime == 0){ //We only blink when LCD is not on
       if(currentMillis - previousMillis > interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;
        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW)
          ledState = HIGH;
        else
          ledState = LOW;
        // set the LED with the ledState of the variable:
        digitalWrite(11, ledState);
       }}

      buttonState = digitalRead(BUTTON_PIN);// Check the state of the push-button.

      if (buttonState == HIGH){// Button pressed.

          digitalWrite(11, LOW);

        lcdLightOn_StartMillis = millis();
        currentLcdLightOnTime = 0;
        isLcdLightOn = true;
        lcd.setBacklight(1); // switch on the backlight

        //Screen 0 Presentation

        lcd.setCursor(0, 0);
        lcd.print(" Aquaponics Bot ");

        lcd.setCursor(0, 1);
        lcd.print("  Version 1.0      ");
      }

      else{
        // Button not pressed.

        //Serial.println("Button not pressed - LOW");

        if(isLcdLightOn){
          currentLcdLightOnTime = millis() - lcdLightOn_StartMillis;

      //Screen 2
            if(currentLcdLightOnTime > 3000 && currentLcdLightOnTime <= 6000){

        //Screen 2 - Air Temperature & Humidity

        //Line 1
        lcd.setCursor(0, 0);
        lcd.print("  Air Sensors  ");

        //Line 2
        lcd.setCursor(0, 1);
        lcd.write(0);
     lcd.print(": ");
        lcd.println(airtemp);
        lcd.setCursor(5, 1);
        lcd.write(2);

        lcd.print(" - ");
        lcd.write(1);
        lcd.print(": ");
        lcd.print(airhumid);
     lcd.setCursor(14, 1);
        lcd.print("%   ");

           }

      //Screen 3
            if(currentLcdLightOnTime > 6000 && currentLcdLightOnTime < 9000){

         //Screen 3 - Water Data

        //Line 1
        lcd.setCursor(0, 0);
        lcd.print(" Water Sensors ");

        //Line 2
        lcd.setCursor(0, 1);
        lcd.write(0);
     lcd.print(": ");
        lcd.println(watertemp);
        lcd.setCursor(5, 1);
        lcd.write(2);

        lcd.print(" -  soon   ");

       }

        //Screen 4

            if(currentLcdLightOnTime > 9000 && currentLcdLightOnTime < 12000){

       //Screen 4 - Light Sensors

        //Line 1
        lcd.setCursor(0, 0);
        lcd.print(" Light Sensors  ");

        //Line 2
        lcd.setCursor(0, 1);
        lcd.write(3);
     lcd.print(": ");
        lcd.println(sunlight);
        lcd.setCursor(5, 1);
        lcd.print("% - soon   ");

          }

                if(currentLcdLightOnTime > 12000 && currentLcdLightOnTime < 15000){

         //Screen 5 - Next Feeding

        long hours=0;
         long mins=0;
         long secs=0;

         secs = timeuntilfeeding/1000; //convect milliseconds to seconds
         mins=secs/60; //convert seconds to minutes
         hours=mins/60; //convert minutes to hours
         secs=secs-(mins*60); //subtract the coverted seconds to minutes in order to display 59 secs max
        mins=mins-(hours*60); //subtract the coverted minutes to hours in order to display 59 minutes max
         //Display results
         itoa(hours, bufferhours, 10);//Convert the number of hours into readable by LCD
         itoa(mins, bufferminutes, 10);//Convert the number of minutes into readable by LCD
        lcd.setCursor(0, 0);
        lcd.print("Fish Feeding: ");
        lcd.setCursor(0, 1);
        lcd.print(bufferhours);
        lcd.print(" hours ");
         lcd.print(bufferminutes);
         lcd.print(" min.   ");

       }

      // Turn Off the Screen
          if(currentLcdLightOnTime > 15000){
            lcd.clear();
            isLcdLightOn = false;
            lcd.setBacklight(0); // switch off the backlight

            currentLcdLightOnTime = 0; //So that the blinking can start again.
            ledState = LOW;
          }
        }
      }

        } // End of the while wifi loop

     // Make sure we are still connected to the internet

       esp8266.begin(9600);
       boolean wifi_connected=false; //not connected yet...

       sendesp8266("AT");
       delay(2000);
     for(int i=0;i<5;i++) //attempt 5 times to connect to wifi - this is a good idea
     {
     if(connectWiFi()) //are we connected?
     {
     wifi_connected = true; //yes
     break; //get outta here!
     }
     }

        digitalWrite(13, HIGH);

        //We capture sensors again to send the value

        //Sunlight
        float value_sunlight = analogRead(A2);
        percent = value_sunlight / 1024.0 * 100;  //Convert dryness score into moisture percentage
        String sunlight =String(percent);// turn integer to string

        //Water Temperature
        float value_watertemp = getTemp();
       String watertemp= String(value_watertemp);// turn integer to string

     //Air Temperature and Humidity
     int chk = DHT11.read(); //Read DHT11 Sensor
      String airtemp=String(DHT11.temperature);// turn integer to string
       String airhumid=String(DHT11.humidity);// turn integer to string

       updateTS(sunlight,watertemp, airtemp, airhumid);
       delay(3000); //
        digitalWrite(13, LOW);

      } // End of the while feeding loop

      // Double Swipe to Feed the Fish

     //Intialize Servo
     myservo.attach(3);  // attaches the servo on pin 3 to the servo object
     //Display that the fish is being fed.
        digitalWrite(13, HIGH);

        for(pos = 0; pos < 180; pos += 5)  // goes from 0 degrees to 180 degrees
          {                                  // in steps of 1 degree
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(15);                       // waits 15ms for the servo to reach the position
           }

        for(pos = 180; pos>=0; pos-=5)     // goes from 180 degrees to 0 degrees
           {
             myservo.write(pos);              // tell servo to go to position in variable 'pos'
             delay(15);                       // waits 15ms for the servo to reach the position
           }

     myservo.detach();  // detattaches the servo from pin 3
        //Clears display
        digitalWrite(13, LOW);

        // SEND AN EMAIL OR UPDATE A DATABASE..

        }

        //----- update the  Thingspeak string with 4 values
        void updateTS( String L, String W , String T, String H)
        {
        // ESP8266 Client
        String cmd = "AT+CIPSTART=\"TCP\",\"";// Setup TCP connection
        cmd += IP;
         cmd += "\",80";
        sendesp8266(cmd);
          delay(2000);
        if( Serial.find( "Error" ) )
        {
          esp8266.print( "RECEIVED: Error\nExit1" );
        return;
        }

         cmd = GET + "&field1=" + L +"&field2="+ W + "&field3=" + T + "&field4=" + H +"\r\n";
         Serial.print( "AT+CIPSEND=" );
         Serial.println( cmd.length() );
         if(Serial.find( ">" ) )
         {
         esp8266.print(">");
         esp8266.print(cmd);
         Serial.print(cmd);
         }
         else
         {
         sendesp8266( "AT+CIPCLOSE" );//close TCP connection
         }
         if( Serial.find("OK") )
         {
         esp8266.println( "RECEIVED: OK" );
        }
        else
        {
        esp8266.println( "RECEIVED: Error\nExit2" );
         }
         }

        void sendesp8266(String cmd) //Send info to esp8266
         {
        esp8266.print("SEND: ");
         esp8266.println(cmd);
         Serial.println(cmd);
         }

         boolean connectWiFi()
          {
         digitalWrite(11, LOW);
         digitalWrite(12, HIGH);
         Serial.println("AT+CWMODE=1");//WiFi STA mode - if '3' it is both client and AP
         delay(5000);
         //Connect to Router with AT+CWJAP="SSID","Password";
         // Check if connected with AT+CWJAP?
         String cmd="AT+CWJAP=\""; // Join accespoint
         cmd+=SSID;
         cmd+="\",\"";
         cmd+=PASS;
         cmd+="\"";
         sendesp8266(cmd);
         delay(15000);

         digitalWrite(12, LOW);

         if(Serial.find("OK"))
         {
          esp8266.println("RECEIVED: OK");
          return true;
         }
         else
         {
           esp8266.println("RECEIVED: Error");
           return false;
         }

         cmd = "AT+CIPMUX=0";// Set Single connection
         sendesp8266( cmd );
         if( Serial.find( "Error") )
         {
         esp8266.print( "RECEIVED: Error" );
          return false;
         }
       }

       float getTemp(){ //Get the water temperature
        //returns the temperature from one DS18S20 in DEG Celsius

        byte data[12];
        byte addr[8];

         if ( !ds.search(addr)) {
          //no more sensors on chain, reset search
          ds.reset_search();
          return -1000;
         }

        if ( OneWire::crc8( addr, 7) != addr[7]) {
         Serial.println("CRC is not valid!");
         return -1000;
        }

        if ( addr[0] != 0x10 && addr[0] != 0x28) {
         Serial.print("Device is not recognized");
          return -1000;
        }

        ds.reset();
        ds.select(addr);
        ds.write(0x44,1); // start conversion, with parasite power on at the end

         byte present = ds.reset();
        ds.select(addr);
        ds.write(0xBE); // Read Scratchpad

        for (int i = 0; i < 9; i++) { // we need 9 bytes
         data[i] = ds.read();
        }

        ds.reset_search();

        byte MSB = data[1];
        byte LSB = data[0];

        float tempRead = ((MSB << 8) | LSB); //using two's compliment
        float TemperatureSum = tempRead / 16;

        return TemperatureSum;

        }

body:
Instead of using a delay, you may use some variable (maybe a struct or an object) to keep the status of your transmission or reading; every things that need a delay became a new state in this state-machine, every loop, based on witch status you have, you check if there are the information to execute the next step.

You may have multiple thing with status, but if they share a resource you'll need to add an abstraction layer on that resource to take care of that. (Like an event system or a message router or an output buffer)

Also you may have a status in witch you wait for a status in another state machine.


sender: user

sender: assistant

body:
As already pointed out,

You can use a while loop for your purposes:

    while(adc/send/recive_flag == 1){
    // do stuff
    }

instead of the very bad habit of using delay. (You don't need to wait any longer than you have to)

As for LCD and RGB leds, use them inside an interrupt. Make interrupt timer something like 50 ms. This way, whatever main code you are running, ISR will timout and LCD and RGB will be updated.

> Capture data (light, temperature, etc.)

Use dedicated atmega registers to read ADC. AnalogRead is **SLOW**. I think you can find information about this all over google.

> Upload data to thingspeak every 5 minutes

This should be fine. Increase transmission BAUD RATE if necessary.

To me the way it looks, you have to wait for data capture, theres no solution for that so make it faster.

As for Wifi, disable ISR, send a single message, enable ISR and wait for a bit and so on. Something like this could work.

As for feeding the fish, all you do is send PWM to servo, right? Use dedicated PWM registers on atmega for faster execution but it doesn't matter anyway for the LCD and RGB LED because they are in interrupt routine so they will be updated anyways.


body:
You can use several approaches.

Lesto already pointed out the finite state machine, but this approach will run the code as fast as possible and this might not be the behaviour you want. It's a good approach to manage, for instance, wifi connections and other communications but it won't let you schedule a task in a fixed pace.

Other options:

1) In the arduino default examples there's "Blink without delay" (\examples\digital), [here][1] you can read the code explanation. It's different from what you used

(`while(now < endtime)`)

because your code execution is kept inside the while.

If you otherwise use an

`if (currentMillis - previousMillis >= interval)`

the code will do the check but it  continues to run other instructions until the right time has come.

2) Use a [scheduler][2]!
This is handy if you have several different tasks that should run at a constant (and relatively slow for the MCU) pace.

For instance:

    #include "leOS.h"
    leOS myOS

    void setup() {
      myOS.begin();
    }
    void setup() {
      myOS.begin();
      myOS.addTask(updateTS, scheduleTime[30000, SCHEDULED]);
    }

With this code you'll run the updateTS function every 5 min, without blocking the execution of other tasks.

  [1]: https://www.arduino.cc/en/tutorial/BlinkWithoutDelay
  [2]: https://github.com/leomil72/leOS


message:
Bluetooth hc-06 and Standalone Atmega168(possible?)

I am making a project that requires bluetooth communication between a Raspberry Pi(equipped with a bluetooth dongle) and a standalone atmega168 circuit.

I want to be able to transfer information serially between the two devices over bluetooth.

I have selected the hc-06 for the arduino and some usb bluetooth dongle for the PI.

I would like to know if connecting the hc-06's TX and RX pins to the RX and TX (respectively) pins of my atmega will work or not. If not, I would like to know how to achieve that (bluetooth on a standalone arduino-powered microcontroller)

body:
The HC-0x Bluetooth transceivers are a drop-in replacement for a serial connection. Once the transceiver is configured (with baud-rate, device name, and pairing PIN #) you can plug it in in place of a serial line and expect to communicate. The device will take care of pairing and accepting a connection from the master device with no need for any code support from the AVR.

I use a separate program on an Arduino or a breadboarded AVR to configure my HC-06es. They retain their configuration across a power-down, and in fact, there is no hardware support for resetting them to a standard configuration; you need a program that figures out their current baud-rate in order to reconfigure them. It can save a bunch of hassle if you write down their configurations whenever you change them.


message:
Compile problem when using keyword 'new' on Raspberry Pi

I have the following line of code in my Arduino sketch:

    static double *temps = new double[arraySize];  //Declare array to hold tempratures, place the array on the heap where it will not be deleted and keep the pointer as a static
    //double temps[arraySize];

When I compile with the Arduino IDE on Ubuntu it compiles just fine. However, when I compile on the Raspberry Pi, it throws up the following error:

    xxx.cpp.o: In function `last Function in file()':
    xxx.cpp:[last line in file]: undefined referance to `operator new[] (unsigned int)'
    collect2: error: ld returned 1 exit status

Is this a bug? If so, how do I report it? If not, why is it throwing this error or how else can I declare a static array of doubles (needs to be static, I calculate an average of some incoming data over several function calls)?

body:
The Arduino uses [AVR libc](http://www.nongnu.org/avr-libc/) which does not provide a complete C++ environment.

Among other things AVR libc does not support `new` and `delete`. See the [FAQ](http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_cplusplus) for more information.

Some versions of the Arduino libraries may provide new and delete but they are just wrappers around `malloc` and `free`. I suggest not using new and delete on arduino because they do not have the same behavior as C++. For example destructors will not be called on the arduino when delete is called.


body:
> how else can I declare a static array of doubles (needs to be static,
> I calculate an average of some incoming data over several function
> calls)

When you find a bug in the Arduino software, please do report it to the appropriate place -- http://arduino.cc/en/Main/ContactUs has the contact details.

One way to declare a static array of doubles is like this:

    double boxcar_average(double new_sample) {
      const int arraySize = 3;
      static double old_sample[ arraySize ] = {0};
      double sum = new_sample;
      for(int i=0; i<arraySize; i++){
        sum += old_sample[i];
      }
      old_sample[0] = old_sample[1];
      old_sample[1] = old_sample[2];
      old_sample[2] = new_sample;
      return( sum / 4 );
    }


message:
What do these operators do?

Going through the "timeouts" example of the elapsedMillis library (https://github.com/pfeerick/elapsedMillis) I found the following statement:

digitalWrite(LEDPIN, flashPattern[ledIndex++] ? ledBrightness : !ledBrightness);

   - flashpattern is an array of boolean variables  (boolean flashPattern[] = { 1,1,1,1,1,1,1,0,1,1,0 };)
   - ledBrightness is a boolean as well.

What does the "?" and the ":" do there? are these boolean operators?

body: They are the conditional operator. If the expression before the `?` is true then the result is the expression before the `:`, otherwise it is the expression after.


message:
How to power both arduino and 1 color led strip from single power source

![enter image description here][1]

I'm trying to understand and adapt this tutorial:

https://learn.adafruit.com/rgb-led-strips/current-draw

to my own use. I am doing essentially the same thing, except I have this [single color LED strip][2], and I don't fully understand how to power both the arduino and the led strip from the same power source.

I tried to wire it using the diagram above, and something started smoking (I think the IR transmitter). I don't know much about circuits, but I'm pretty sure that's not good.

In this diagram, the 9v represents DC power, the IR sensor on the left represents the transmitter, the IR on the right is the receiver, and the white LED is the LED strip, with two outputs (+ - )

In the fritzing diagram for that tutorial, they have the + from the LED strip going straight in to Vin on the uno, but they don't show how either the LED strip or the uno themselves are being powered.

Do I need two power sources?

Do I need a mosfet considering I'm only using a one color LED strip?

I've got the IR sensors working, so I don't need help with that, and I can connect one of these [12V switching power supplies][3] to one of these [DC power screw terminals][4] to power the lights without any arduino control, so all I'm missing is how to turn the lights on and off with arduino, IE, how to go from the power supply to the arduino to the LED strip.

I don't need to PWM the LED strip - just shut it off and on.

If anyone can help me correct the fritzing diagram or explain what I'm doing wrong / what I should be doing instead, I'd greatly appreciate it.

  [1]: https://i.stack.imgur.com/kjlvF.png
  [2]: https://www.adafruit.com/products/887
  [3]: https://www.adafruit.com/products/352
  [4]: https://www.adafruit.com/products/368
  [5]: https://i.stack.imgur.com/XWzyY.gif

body:
![enter image description here][1]Note that VIN pin and the 2.5mm DC Jack are connected. So in the tutorial one of these is getting power from a +12Vdc source and the other is supplying +12V to the +12v labeled pin on the LED string. Where the R G and B pins of the strip should be connected to Collectors of NPN's. Each of the NPN's bases are driven by Arduino Output pin and all the Emitters are connected to Ground.

So +12V supplies the DC Jack (aka Vin) the Arduino's local regulator converts that to Ground. The +12V via Vin supplies the LED's. And the Digital Outputs drive the base's of the NPN's. Which in turn act like a relay closing the perspective LED's to Ground, so they can illuminate. Where a Digital ONE or HIGH or TRUE on the BASE results in 5V above ground, which causes it to have low resistance.

![enter image description here][2]

  [1]: https://i.stack.imgur.com/KcJSH.png
  [2]: https://i.stack.imgur.com/y5hCW.png


body:
You asked: "Do I need a mosfet considering I'm only using a one color LED strip?"

Yes, absolutely. An Arduino logic line can only put out about 20 mA of power at 5V. That's not an unreasonable amount of power for a single low-power LED. An LED strip is likely to draw a lot more current than that, and it's pretty common for LED strips to use 12V, not 5V.

What LED strip are you using, and what input voltage and current requirements does it have?

You should be able to use a single power 12V power supply for your project. (assuming your LED strip needs 12V.) You'd feed it into the barrel jack of the Arduino. The Arduino's voltage regulator would use that to generate its 5V power. You'd also feed 12V into the power for your LED strip. You'd use a logic-level MOSFET to switch the power to the LED strip on and off. A logic level MOSFET is able to use a low current 5V signal from the Arduino to switch higher voltage, higher current loads like your LED strip with very little resistance, and thus with very little waste heat generated.


message:
Location of examples folder in Ubuntu

I'm trying to add some additional example files to the Arduino IDE in Ubuntu 14.04. However, I can't for the life of me find where the examples are stored in my system. I checked the Arduino website, but can't find any information there. Does anyone know where I need to put my additional files?

body: After some more searching I found it in /usr/share/arduino/examples.


body: I found mine in Linux Mint 17.3 under `opt/arduino/examples`


body:
In Ubuntu I found arduino library on
/home/MYUSERNAME/snap/arduino

where MYUSERNAME is user name


message:
ADXL345 Arduino UNO data_ready interrupt

I would like the sensor values to be updated each 10ms(100Hz) and then run the algorithm and repeat the same process. However, after timing the algorithm it is taking only 2ms, I think the data_ready interrupt is not working as expected. Physical hardware connection is from INT1 of ADXL345 to pin2 of the UNO.

edit:

I have configured the accelerometer to have a data rate of 100Hz. I have set up an interrupt with data_ready to run the algorithm present in the loop each time a new sample comes that is each 10ms. However each sample is coming every 2ms which shows the interrupt is not working and I would like to know why. I have timed the interrupt with the millis(); function before and after calling the interrupt, also I have stored the samples in an array and printed it on the serial interface and the samples were repeated as it was updated every 2ms instead of 10ms. The algorithm I have developed needs the sampling rate to be 100Hz.

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_ADXL345_U.h>
    #include <avr/io.h>
    #include <avr/power.h>

    #define F_CPU 16000000UL

    volatile int sensor_update=0;

    //-----------------------------------------------------------------------------------     -----------
    //Write to ADXL345 registers
    void writeTo(int device, byte address, byte val) {
    Wire.beginTransmission(device); //start transmission to device
    Wire.write(address);        // send register address
    Wire.write(val);        // send value to write
    Wire.endTransmission(); //end transmission
    }

    //----------------------------------------------------------------------------------------------

    /////////////////////////////////////////////////////////////////////////////////////////////

    //ISR function

    void interrupt(void){
    sensor_update=1;

    }

    //////////////////////////////////////////////////////////////////////////////////////////////////

    void buzz(int targetPin, long frequency, long length) {
    long delayValue = 1000000/frequency/2; // calculate the delay value between     transitions
    //// 1 second's worth of microseconds, divided by the frequency, then split in half since

      //// there are two phases to each cycle
      //// calculate the number of cycles for proper timing
      long numCycles = frequency * length/ 1000;

      //// multiply frequency, which is really cycles per second, by
      //// the number of seconds to get the total number of cycles to produce
      for (long i=0; i < numCycles; i++){ // for the calculated length of time...
        digitalWrite(targetPin,HIGH); // write the buzzer pin high to push out the diaphram
        delayMicroseconds(delayValue); // wait for the calculated delay value
        digitalWrite(targetPin,LOW); // write the buzzer pin low to pull back the diaphram
        delayMicroseconds(delayValue); // wait againf or the calculated delay value
      }
    }

    /* Assign a unique ID to this sensor at the same time */
    Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12345);

    void setup(void)
    {
      if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
      Serial.begin(9600);
      //Serial.println("Accelerometer Test"); Serial.println("");

      pinMode(4, OUTPUT);// buzzer output pin

      /* Initialise the sensor */
      if(!accel.begin())
      {
        /* There was a problem detecting the ADXL345 ... check your connections */
        //Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
        while(1);
      }

      /* Set the range to whatever is appropriate for your project */
      accel.setRange(ADXL345_RANGE_16_G);
      accel.setDataRate(ADXL345_DATARATE_100_HZ);
      // displaySetRange(ADXL345_RANGE_8_G);
      // displaySetRange(ADXL345_RANGE_4_G);
      // displaySetRange(ADXL345_RANGE_2_G);

      //Create an interrupt that will trigger when a tap is detected.
      attachInterrupt(0, interrupt, RISING);

      writeTo(0x1D, 0x2E, 0);
      writeTo(0x1D, 0x2F, 0);
      writeTo(0x1D, 0x2E, 128);
      writeTo(0x1D, 0x2F, 127);
    }

    void loop(void)
    {

      if(sensor_update==1 ){
        //When sensor_update is set to 1 in the ISR,the algorithm process the data from the accelerometer being updated every 10ms(100Hz)
         sensor_update=0;//reset
      }
    }

body:
According to the [data-sheet](https://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf):

> The interrupt functions are latched and cleared by either reading the
> data registers (Address 0x32 to Address 0x37) until the interrupt
> condition is no longer valid for the data-related interrupts or by
> reading the INT_SOURCE register (Address 0x30) for the
> remaining interrupts.

Therefore, an ISR that just sets a flag will not be called a second time. At the very least, you need to read the INT_SOURCE register. If you are using the SparkFun ADXL345 library, then this would be a call of the form:

```c
ADXL345 adxl = ADXL345();
void setup() {
  adxl.powerOn();
  adxl.setInterruptBitLevel(true); // active low
  attachInterrupt(digitalPinToInterrupt(interruptPin), isr, LOW);
  pinMode(interruptPin, INPUT);
  adxl.singleTapINT(1);
  ...
}

void isr(void) {
  detachInterrupt(digitalPinToInterrupt(interruptPin));
  interrupts();
  byte source = adxl.getInterruptSource();
  ...
  attachInterrupt(digitalPinToInterrupt(interruptPin), isr, LOW);
}
```

Note that I use a level-triggered interrupt here and re-enable interrupts before calling `adxl.getInterruptSource()`. The issue is that this call may take some time to talk over the I2C bus. To ensure that there are no reentrant calls, I detach the interrupt first. Without this, the level-triggered mode causes an interrupt loop.

The use of a level-triggered interrupt makes sense because the ADXL won't produce another interrupt until you read from `INT_SOURCE`. It also avoids the problem of missing an edge detection, which tends to cause subtle bugs that are hard to find.

I was unsure about the soundness of turning on interrupts within the ISR and so asked a question about this - https://arduino.stackexchange.com/questions/66742/what-is-the-right-way-to-query-an-i2c-device-from-an-interrupt-service-routine


body:
Been bashing my head with this one. And have searched the internet for a solution And tried for hours to program a solution.
From my tests the problem seems to be the Register 0x30—INT_SOURCE is populated with triggers. But the INT pin is only triggered when the  Register 0x30—INT_SOURCE is read.
This means that firstly the Arduino can't be woken from sleep by the INT1 or INT2 pins because they don't change unless the Arduino is already awake and reading the Register 0x30—INT_SOURCE
Second problem is to trigger an interrupt INT pin to jump to the ISR interrupt service routine you have to read Register 0x30—INT_SOURCE. And if you are going to do that then you might as well forget the interrupt and just jump into the ISR() and check registers in that. Which is how the example in the Sparkfun_ADXL345_Example for arduino ended up with the  ADXL_ISR(); call in the main loop. To sum up. Unless some one knows away to get the ADXL345 to change state on its INT pins without the need to read Register 0x30—INT_SOURCE, then the device is useless for use with the INT pins. I have given up on it and looking for another device to wake my ESP32 from sleep. Such as the BMI160 - Bosch which looks like a contender and has a arduino library for.


message:
Can't figure out the error to this code

I've written up this very simply code to control transistors in an inverter circuit. The editor is flagging up errors which I can't see myself. I'm pretty new to Arduino programming but it's very simple code and can't see why it's being shown as having errors.

At first glance, what am I missing? I've pasted a section below:

    int Phase1pos = 13;
    int Phase2pos = 12;
    int Phase3pos = 11;
    int Phase1neg = 10;
    int Phase2neg = 9;
    int Phase3neg = 8;

    void setup() {
    pinMode(Phase1pos, OUTPUT);
    pinMode(Phase2pos, OUTPUT);
    pinMode(Phase3pos, OUTPUT);
    pinMode(Phase1neg, OUTPUT);
    pinMode(Phase2neg, OUTPUT);
    pinMode(Phase3neg, OUTPUT);
    }

    void loop() {
        delayMicroseconds(16);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(16);

        delayMicroseconds(7);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(7);

        delayMicroseconds(2);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(2);

        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(104);
        digitalWrite(Phase2pos, HIGH);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(208);
        digitalWrite(Phase1pos, LOW);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(104);
        digitalWrite(Phase3neg, LOW);

        delayMicroseconds(2);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase3neg, LOW);

        delayMicroseconds(7);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(7);

        delayMicroseconds(16);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase3neg, LOW);
        digitalWrite(16);

        delayMicroseconds(28);
        digitalWrite(Phase3neg, HIGH);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(180);
        delayMicroseconds(180);
        digitalWrite(Phase1pos, LOW);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(28);

        delayMicroseconds(16);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(16);

        delayMicroseconds(7);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase1pos, LOW);

        delayMicroseconds(2);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(2);

        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(104);
        digitalWrite(Phase2neg, HIGH);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(208);
        digitalWrite(Phase3neg, LOW);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(104);
        digitalWrite(Phase1pos, LOW);

        delayMicroseconds(2);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(2);

        delayMicroseconds(7);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(7);

        delayMicroseconds(16);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(16);

        delayMicroseconds(28);
        digitalWrite(Phase1pos, HIGH);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(180);
        delayMicroseconds(180);
        digitalWrite(Phase2neg, LOW);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(28);

        delayMicroseconds(16);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(16);

        delayMicroseconds(7);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(7);

        delayMicroseconds(2);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(2);

        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(104);
        digitalWrite(Phase1pos, HIGH);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(208);
        digitalWrite(Phase3pos, LOW);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(104);
        digitalWrite(Phase2neg, LOW);

        delayMicroseconds(2);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(2);

        delayMicroseconds(7);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(7);

        delayMicroseconds(16);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(16);

        delayMicroseconds(28);
        digitalWrite(Phase2neg, HIGH);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(180);
        delayMicroseconds(180);
        digitalWrite(Phase3pos, LOW);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(28);

        delayMicroseconds(16);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(16);

        delayMicroseconds(7);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(7);

        delayMicroseconds(2);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(2);

        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(104);
        digitalWrite(Phase1neg, HIGH);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(208);
        digitalWrite(Phase2neg, LOW);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(104);
        digitalWrite(Phase3pos, LOW);

        delayMicroseconds(2);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(2);

        delayMicroseconds(7);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(7);

        delayMicroseconds(16);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(16);

        delayMicroseconds(28);
        digitalWrite(Phase1neg, HIGH);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(180);
        delayMicroseconds(180);
        digitalWrite(Phase3pos, LOW);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(28);

        delayMicroseconds(16);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(16);

        delayMicroseconds(7);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(7);

        delayMicroseconds(2);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(2);

        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(104);
        digitalWrite(Phase2pos, HIGH);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(208);
        digitalWrite(Phase3pos, LOW);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(104);
        digitalWrite(Phase1neg, LOW);

        delayMicroseconds(2);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(2);

        delayMicroseconds(7);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(7);

        delayMicroseconds(16);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(16);

        delayMicroseconds(28);
        digitalWrite(Phase1neg, HIGH);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(180);
        delayMicroseconds(180);
        digitalWrite(Phase2pos, LOW);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(28);

        delayMicroseconds(16);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(16);
    }

body:
Here's line 109:

     digitalWrite(16);

As the error message says, there aren't enough arguments. It looks like you meant to call `delayMicroseconds()` there instead of `digitalWrite()`.


message:
delay() vs delayMicroseconds()

I just started using Arduino and so far I've used both `delay()` and `delayMicroseconds()`. I was wondering what the difference between these two is, because it seems to me that they're the same.

body:
From the documentation:

> #delay()
##Description

>Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are 1000 milliseconds in a second.)

So... milliseconds vs. microseconds.


message:
Why doesn't the Micro OLED library compile on my DUE?

I have an Arduino `DUE` and just got a `Micro OLED` display from SparkFun.

Using their library, when I try to compile I get the error below.  Other example code works just fine and I've programmed this thing a million times with my code.  So it's clearly in the SparkFun code.

Here is the SparkFun tutorial page with a description of the product:

https://learn.sparkfun.com/tutorials/micro-oled-breakout-hookup-guide?_ga=1.19136059.2055231411.1404437767

Here is the library I am using:

https://github.com/sparkfun/Micro_OLED_Breakout/tree/master/Firmware/Arduino/libraries/SFE_MicroOLED

Here is the error I get:

    Build options changed, rebuilding all

    /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp: In member function 'void MicroOLED::spiSetup()':

    /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:46:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
        ssport  = portOutputRegister(digitalPinToPort(csPin));
                ^
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:48:51: error: 'portModeRegister' was not declared in this scope
        ssreg  = portModeRegister(digitalPinToPort(csPin));
                                                         ^
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp: In member function 'void MicroOLED::i2cSetup()':
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:84:2: error: 'TWBR' was not declared in this scope
        TWBR = ((F_CPU / I2C_FREQ) - 16) / 2;
        ^
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp: In member function 'void MicroOLED::parallelSetup()':
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:109:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
        ssport  = portOutputRegister(digitalPinToPort(csPin));
                ^
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:111:51: error: 'portModeRegister' was not declared in this scope
        ssreg  = portModeRegister(digitalPinToPort(csPin));
                                                         ^
      /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:114:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
        wrport  = portOutputRegister(digitalPinToPort(wrPin));
                ^

    /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:119:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
        rdport  = portOutputRegister(digitalPinToPort(rdPin));
                ^
      Error compiling.

body:
That library is uses some AVR specific methods, that aren't implemented for the ARM processor in the Due.

I don't see a real easy way to port those methods.


message:
High Frequency Sine Wave Generation

I'm new to the world of Arduino and I'm working on a wireless charging project that needs a 5.7MHz sine wave. I've tried using a Due and changing the PWM and DAC, but I can't get a clean sine wave at that frequency using anything I've found online. My signal is either way too low, or too high and horribly distorted.

Any help would be appreciated. I have access to a Mega, Due, Uno, and Mini.

body:
To generate a **square wave**, you only need to update the output at a rate of two points per cycle. (*Technically, when the Arduino's PWM output is configured for 50% duty cycle, that's a square wave at some frequency.*)

But to generate a clean **sine wave** (without a lot of **distortion**), you need to update a lot more frequenclly than two points per cycle. Personally I wouldn't want to go much below 20 points per cycle.

Imagine the sine wave is generated by a wheel that spins at some rate. Viewed from the edge, a point on the edge of the wheel traces out a sine wave. Viewed from the axle, you see the point going around in a circle.

Now instead of spinning the wheel continuously, suppose the wheel moves in steps of 30 degrees, 12 steps for a complete turn. Instead of a continuous sine wave, you get discrete steps of 0, 0.5, 0.866, 1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5, 0, 0.5, ...   Although this sequence approximates an ideal sine wave, it's pretty coarse because the steps are so large.

Now try 15 degrees per step (24 steps per cycle). Now you get 0, 0.259, 0.5, 0.707, 0.866, 0.965, 1, ... Much smoother, although the steps are still fairly noticeable.

So there will be less **phase error**, the more steps there are per cycle of the signal. That's not the only source of distortion however. There is also round-off error due to the limited resolution of the Digital-to-Analog Converter (DAC). For example, the value 0.866 I mentioned above should actually be an irrational value, half the square root of 3. Since it's an irrational number, there's no way for a real DAC to get this value exactly right. DAC output step values are ideally based on powers of two (1/2, 1/4, 3/4, 1/8, 3/8, 5/8, 7/8, etc.). And furthermore a real DAC can have offset error, gain error, non-linearity, as well as uncertainty about precisely when the new programmed value is reached.

There's also **frequency error** when the system's highest-frequency master clock is divided by an integer. If the Arduino UNO's master clock frequency is 16MHz, and the SPI setup function `setClockDivider()` is used to divide the master clock by 2, that's 8MHz. Divide by 3 and you get 5.333MHz. Divide by 4, that's 4MHz. Divide by 5, that's 3.2MHz. There's no way to get a clock frequency that's between these discrete steps. For small divisors, there's a big jump between steps. So if you needed to be able to smoothly adjust the frequency, you'd need a much higher master clock frequency. And, if you needed to configure the 16MHz Arduino UNO to an SPI clock frequency of exactly 5.7MHz, that's just not possible -- setClockDivider(2) is too fast, setClockDivider(3) is too slow, and setClockDivider(2.807017543859649) isn't supported by the hardware.

If your system could write to a DAC at an **update rate** of 12MHz, then 12 points per cycle gives a 1MHz output, and 24 points per cycle gives a 500kHz output. Or taking it the other way round, if you need to generate a 5.7MHz output waveform, then the DAC update rate needs to be somewhere around 100MHz to get a clean, low-distortion waveform. This is probably beyond the limit of what you can directly synthesize in software using something like an Arduino or a Raspberry Pi. A 16MHz Arduino UNO could maybe synthesize a few 100kHz using software synthesis, but at 1MHz there's going to be significant distortion.

Software-controlled`Direct Digital Synthesis` is very sensitive to timing, so the actual DAC update would need to be implemented in an **interrupt service routine**, run by a periodic timer. ( See https://electronics.stackexchange.com/questions/26363/how-do-i-create-a-timer-interrupt-with-arduino )  If you just used a while loop with a delay statement, then whenever the code needs to do something else, the waveform would just freeze up. This is more of a problem if the Arduino is trying to manage several other tasks at the same time as it is synthesizing the waveform.

**Hardware** `Direct Digital Synthesis` (DDS) is possible. Same principles. There needs to be a `phase accumulator`, which is just a counter that keeps track of the phase angle of the "wheel" that's generating the sine wave. *(The phase accumulator needs to be modulus 360 degrees or 2 pi radians, but there's no requirement to count in 1 degree steps. Better to divide the circle into 2^N slices so that 360 degress maps to the natural counter overflow value.)* And there also needs to be a lookup table with the sine value for each of those steps. This lookup table only needs to cover 90 degrees of the sinewave, because the waveform is symmetrical -- the other three quadrants can be found by 2's complementing the values and indexing from the other end of the table. Or, the sine can be approximated by a polynomial calculation. More steps x more DAC resolution requires a deeper, wider lookup table. There are integrated circuits available that perform the timing-critical actions, all the software needs to do is send some initial configuration to set it up. Changing the frequency only requires configuring a new frequency divisor value into the DDS chip, so the Arduino can manage other things without causing distortion.

If the original problem only needs one **fixed frequency under 200MHz**, and doesn't need any adjustment to that frequency, then the hardware gets a whole lot simpler. The crystal oscillator circuits that we use to generate the timing for digital circuits, are in fact analog to begin with. You can contact a crystal vendor and request a custom **AT cut crystal**; google `custom quartz crystal frequency` for quartz crystal vendors. Construction requires a careful printed circuit board layout; the white solderless breadboard commonly used in Arduino projects just doesn't work well above 10MHz. Granted, this fixed-frequency solution doesn't involve Arduino in any way, but if it solves the problem, that's what's important.


body:
I wonder for which purpose you would use a micro controller at all.

If you need a fixed frequency circuit, you could design just that.

If you need a generator with variable frequency, that would justify the Arduino, but in this case I would use the Arduino to control the frequency indirectly.

Ex: create a [VCO][1] and use the Arduino to adjust the voltage, through a [DAC][2]

  [1]: https://en.wikipedia.org/wiki/Voltage-controlled_oscillator
  [2]: https://en.wikipedia.org/wiki/Digital-to-analog_converter


body:
One problem (for me) is to know how much time lines of (C) code take to execute on a (16) MHz Arduino. This and the coding you use would set an upper limit to the sinewave frequency you could synthesise at a given quality.

You probably can't beat assembly language when time is tight.


message:
Connect Arduino via TX RX Pins to Computer's USB Port

I want to avoid using the big USB B connector to program my Arduino Mega. Since there are those RX TX Pins I thought, it would be possible, to connect my USB - Wires from my PC directly to those RX TX Pins. `D+ -> TX and D- RX`. [This Post on Arduino Stackexchange][1] says, those wires are just connected, while [this post][2] says the exact opposite.

I'm confused. Is it possible or would I damage my board when connecting USB wireq to RX / TX pins on my Arduino?

  [1]: https://arduino.stackexchange.com/questions/3772/can-tx-and-rx-pins-on-the-uno-be-used-like-regular-digital-pins
  [2]: https://arduino.stackexchange.com/questions/4652/usb-d-d-to-arduino-mega-rx-tx

body:
Strictly Serial interfaces use ±15V, although this is uncommon these days (but then so are PCs with serial ports). ±12V, ±5V or even 0/+5V also exist. Connecting a ±15V interface to the Pi would destroy it. There are RS232 adapters to ensure safety.

If you are talking about connecting USB data lines to serial forget it. The voltages are the least of your worries, the USB serial encapsulates the data in a protocol.


body:
The first answer that you cite that you say says it is possible is in fact not talking about  what you are referring to  - it is discussing the use of the RX & TX pins directly when they are not being used for USB connection.

The second answer you cite is technically incorrect but "correct enough" in the context.

The answer to your question  is "It can be done but it requires a different boot loader, its slower, its technically inferior, it's less standard, it requires a degree of understanding (on someone's part) to get it going, and **it can be done**

It IS possible to access USB directly from digital I/O pins. As TX & RX are also standard digital I/O pins they could be used for this purpose BUT you need dedicated bootloader code to do this and it has inferior performance if a USB to serial converter is available. The eg ADAFruit Arduino Trinket uses this system.

_______________________________

Here is how the (or a)  [**ADAFRUIT Trinket Bootloader**](http://www.embedded-creations.com/projects/attiny85-usb-bootloader-overview/details) works. (The Trinket is not mentioned here but I'm told that this is what it uses. If not, it works in functionally the same manner).

This is in turn based on the [**USBaspLoader**](http://www.obdev.at/products/vusb/usbasploader.html)

A (very) simple "more or less Arduino compatible" development board which can use this system is [Metaboard](https://metalab.at/wiki/Metaboard). It's circuit diagram is shown below. As can be seen - it uses an ATMega168 and the USB connection is made to two standard digital I/O pins.

![enter image description here][1]

**"Metaboard" using ATMega168**

 - note USB connection to pins PD2 & PD4 - NOT via RXD on PD0 and TXD on PD1 via a serial to USB converter, as is more usual.

__________________

AND another version:  [**AVRUSBBOOT**](http://www.fischl.de/avrusbboot/)

![enter image description here][2]

________________

And **again**

[**BootloadHID**](http://www.obdev.at/products/vusb/bootloadhid.html)   They say  -

- BootloadHID is a USB boot loader for AVR microcontrollers. The uploader tool requires no kernel level driver on Windows and can therefore be run without installing any DLLs.

 BootloadHID is a USB boot loader for AVR microcontrollers. It can be used on all AVRs with at least 2 kB of boot loader section, e.g. the popular ATMega8. The firmware is flashed into the upper 2 kB of the flash memory and takes control immediately after reset. If a certain hardware condition is met (this condition can be configured, e.g. a jumper), the boot loader waits for data on the USB interface and loads it into the remaining part of the flash memory. If the condition is not met, control is passed to the loaded firmware.

 This boot loader is similar to Thomas Fischl’s avrusbboot, except that it is built on top of the HID device class. This implementation is more user friendly on Windows, since no kernel level drivers need to be installed.

  [1]: https://i.stack.imgur.com/ScLWt.jpg
  [2]: https://i.stack.imgur.com/uMRel.png


message:
Arduino Yun - Problem with bridge and client

I'm using this simple code

    #include <Bridge.h>
    #include <YunServer.h>
    #include <YunClient.h>

    YunServer server;

    void setup() {
      Serial.begin(9600);
      Bridge.begin();
      server.listenOnLocalhost();
      server.begin();
    }

    void loop() {
      YunClient client = server.accept();
      if (client) {
        Serial.println("client");
        process(client);
        client.stop();
       } else {
         Serial.println("no client");
       }
       delay(50);
    }

    void process(YunClient client) {
      String command = client.readStringUntil('/');
      Serial.println(command);
      if (command == "turnLeft") {
        Serial.println("Gira a sinistra");
      }
      if (command == "turnRight") {
        Serial.println("Gira a destra");
      }
      if (command == "goTo") {
        String value = client.readStringUntil('/goTo/');
        Serial.println(value);
      }
    }

but it seems to have problem with bridge (or server, or client, i cannot understand) because it only write "no client" on the serial.

I can not understand what is wrong.

body:
Probably too late to answer your question. Your problem is on line

    if (client)

Change it to

    if(client.connected())

which actually returns true when client is connected.


body:
I presume you are wanting the print output to show up on the Serial Monitor but you have connected the Arduino IDE to the Yun via the WiFi port on your network. If this is the case, then change all refs of Serial.print to Console.print
This will direct the ASCII text to the Serial Monitor.


message:
Connecting to Nano via USB3

I have a Uno (third party) that I connect to my Dell laptop with no problems at all. But I've just received a Nano (also third party) that I just can't get to upload. After lots of interneting, I hit Windows normally-useless troubleshooting tool. That tells me that the USB device (the Nano) doesn't understand USB3 and I should plug it into a USB2 port. Unfortunately, being a new machine there IS no USB2 port.

Is Windows Troubleshooting lying? Is there a problem interfacing with a Nano via USB3?

Edit: Error message is:

    stk500_recv(): programmer is not responding

body:
Windows troubleshooter is just trying to tell you that you've plugged a USB2 device into a USB3 port, thus wasting its USB3 capabilities which could be useful for another device. Of course, if you only have USB3, you can't do otherwise.

USB3 is fully backward-compatible with USB2, so whatever your problem is, it is not related to the fact that you plug the Nano into a USB3 port. Perhaps your problem comes from the fact that your Nano is "third party" - I suppose that means it's not the original device and thus it may not be fully compatible. If my guess is right, try to find out what programmer your Nano clone supports: chances are you just need to select a different programmer type in Arduino settings, or buy a separate programmer supported by your device.


body:
1- Check your COM ports, make sure it is correct

2- Arduino Nano will somethime require a driver, download it

3- Reboot your system and see what happens


body:
I have run in to similar symptoms while using USB based Arduino clones connected to USB3 ports. Connecting them to a USB2 port on the same PC worked (where this was an option).

For computers that only have USB3 ports, I found that connecting the device via a cheap USB 2.0 hub (not USB3 hub) solved the issue.

I'm not sure why these devices behave like this, but there seems to be something about USB3 ports that these boards don't like.


message:
Didn't have MAC address on Wiznet based ethernet shield (cloned)

My Ethernet shield dont have any MAC address, please tell me how to find the MAC address, I'm stucked! Here is the link from where I bought the Ethernet shield.
http://www.amazon.in/gp/product/B00AXVX5D0?ie=UTF8&at=&force-full-site=1&ref_=aw_bottom_links

body:
You can set the Mac address to whatever you want.  Many of the example sketches will have one already present, but as long you follow the standard mac format it should be happy (I am using the same shield).  In the Examples menu, you should see Ethernet then Webserver where you can find the following example.  You can change it a bit, but most of the time I just leave it alone.

    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };


body:
Ethernet will work as long as two different machine in the LAN don't have the same MAC address, as @Nathan wrote in his answer.

The MAC address [is built by two parts][1], a prefix which are given to manufacturers of network devices and is called *OUI*, and a suffix that is the node part that manufacturers can use as they wish.

If you want to build an MAC address yourself, use a *Locally administered* address.  Universally administered and locally administered addresses are distinguished by [setting the second-least-significant bit of the most significant byte of the address][1].
That will make this address to not use any OUI prefix, as that bit is zero on OUI, which minimize the risk of two or more devices have the same MAC address in same LAN.

If you get the same MAC addresses you will get very strange results if they happen to be in the same LAN, I tell you.  Been there, done that, and it wasn't fun to debug.

Here are a [site that looks up MAC addresses][2] (and generate random ones).  But if you want to see which manufacturer have that MAC address, [you read it from IEEE and their list][3].

  [1]: http://en.wikipedia.org/wiki/MAC_address#Address_details
  [2]: http://www.macvendorlookup.com/
  [3]: http://standards.ieee.org/develop/regauth/oui/public.html


message:
Internet of Things at home only

My question isn't specific to Arduino but can concern Raspberry Pi and all Internet of Things homemake projects.

As I'm preparing a personal projet with sensors, data storage and visualisation/reporting web page (not yet Android app) I'm looking about Internet of Things platform.

It seems all that I can find are cloud related system. I would prefer a home localized solution but I'm not able to find one (and maybe open source) where datas don't go outside home.

The goal is to be able to :

send datas from my Arduino to a home storage server

store these data into database for later query (may be MySql)

trigger some computation or aggregation job over datas

prepare some graphs

generate some html page from template

option: allow Android client to connect and get datas/graphs

Before starting thinking how to create my own (non standardized) system is anyone can give me some advice ? some name of such existing system ?

Thanks

Thomas

body:
I recently worked extensively on a Home Automation Project and here's what I would recommend based off of that:

 1. Use Arduino for hardware interfacing.
 2. Use Raspberry Pi for hosting your server.
 3. Write your server using Node.js (or Python if you wish).
 4. Use Express, Socket.io (or Python simple server). Google these.
 5. Use Serial (USB) for communication between Arduino and Raspberry Pi
 6. Use RF/BLE if you want to go wireless.
 7. Use Redis or MySQL for database.
 8. Use a graph JS API for charting.
 9. To build an android app, send http requests (or a Socket.io link), for communication.

This is a simple to implement, but you'll need to put some time. Good luck.
All of the above steps are abstracted from each other. This means that if you want to incorporate additional features, you can change any stage without affecting the whole.


body:
Setting up a basic webserver on the Raspberry Pi is fairly straightforward, and as long as you have a firewall and aren't port-forwarding the data will be restricted to your home network.  You can also setup the firewall on the Pi to allow only local access fairly easily.  I did a similar project, and here was my process.

1. Get the Arduino to output the data in a standard way.  I used CSV format, but as long as it easy to parse you should be fine.
2. Get the Arduino to make the data available.  I ended up using the webserver sketch to generate a page with all of my values, but you could just as easily have it send data instead.
3. Insert the data into a database.  I had a cron job that every x minutes would pull the webpage, parse the data, and insert it into the database.
4. Make the webpage.  There are a ton of open source graphing projects, and I chose a PHP based one as that is the language I am most comfortable with.  Javascript, Python, and CSS can also do it if you prefer.
5. Since I used PHP it was fairly easy to setup a template system.  Basically it had some standard include statements, then worked off of $_GET variables to call a variety of graphs.


message:
Arduino-like boards with other microcontrollers

Are there any *Arduino-like* board designs that are ***NOT*** using an AVR chip, but perhaps a chip like the Z80 or the 6502?

body:
You have to define what you mean by "Arduino-like" beyond just not using an AVR.

There's the Arduino Galileo using an Intel chip and supports the Arduino development tools, as well as the Arduino Due which is an Arm-based chip.

There's the Netduino which uses ARM chips (STMicro's) and is pin compatible with Arduino shields, but I don't know what the development framework is (other than it being in .NET), though this doesn't necessarily say much because not even all Arduino boards have the same pin compatibility (Nano boards are much smaller, LilyPad Arduinos which are round and semi-flexible, etc.)

Then there are related boards, but don't support the Arduino environment or any pin compatibility (TI Launchpad springs immediately to mind, but pretty much every manufacturer has some sort of demo board or development board for their MCU's).

There's a huge list of Arduino-like boards [here](http://en.wikipedia.org/wiki/List_of_Arduino_boards_and_compatible_systems) (split into levels of compatibility, includes the official Arduino boards).


message:
USB to TTL with switchable 5v and 3.3v in one

are there any USB to TTL with switchable 5v and 3.3v

i need to use it for raspberry pi and arduino

body:
Many 3.3V FTDI based devices are 5V tolerant and will work with both:

* [Adafruit's FTDI friend](https://www.adafruit.com/product/284)
* [Sparkfun FT231X Breakout](https://www.sparkfun.com/products/11736)

Here is general information about logic levels: https://learn.sparkfun.com/tutorials/logic-levels


message:
Adafruit motorshield disconnected but getting current from Arduino

my Adafruit motorshield is getting current from Arduino board even after disconnected from battery. I was planning to give separate dc power from 6 AA cells to motor shield but not sure if extra current will enter into Arduino and damage it. I have Ultrasonic sensor connected to motorshield which is getting +5v from board (may be Arduino).

Please suggest how to solve this problem.

Thanks

body:
If all else fails, read [**The Manual**](https://learn.adafruit.com/downloads/pdf/adafruit-motor-shield.pdf)

**The manual indicates that it is intended that the MS electronics may be operated by the Arduino power supply while using a separate external supply for the motor.**

Pages 37 to 39 explain about powering options.
The Arduino and the shield interconnect all of : 3V, 5V, Vin.
3V may not be used by the shield.

Arduino Vin to MS V+ is broken by jumper "PWRJMP" - purple rectangle in diagram below.
Arduino 5V to MS Vcc is not interrupted by a jumper - See labels in red squares below.

![enter image description here][1]
_____________________________

You did not say what version shield you had or which Arduino or what you mean by "disconnected from battery" or supply any links to relevant documents. ALL of these things will help people to help you better.

Assuming latest MS version,

[adafruit motor shield v1.2](http://www.adafruit.com/product/81)  - discontinued.

[github v1.2 schematic](https://raw.githubusercontent.com/adafruit/Adafruit-Motor-Shield-for-Arduino/master/mshieldv12schem.png) this appears to be pre V2 BUT is linked to from a ference in the V2 manual so is probably "more or less correct".

[**adafruit motor shield v2 manual**](https://learn.adafruit.com/downloads/pdf/adafruit-motor-shield-v2-for-arduino.pdf) - **probably what you have**

[adafruit current MS page](https://learn.adafruit.com/adafruit-motor-shield/use-it)

This probably tells you what you need to know.  Manual page 37-38

 - How to set up the Arduino + Shield for powering motors

 Servos are powered off of the same regulated 5V that the Arduino uses. This
is OK for the small hobby servos suggested. If you want something beefier, cut the trace
going to + on the servo connectors and wire up your own 5-6V supply!

 **The DC motors are powered off of a 'high voltage supply' and NOT the regulated 5V.**
Don't connect the motor power supply to the 5V line. This is a very very very bad idea unless you are sure you know what you're doing!

 There are two places you can get your motor 'high voltage supply' from. One is the DC jack on the Arduino board and the other is the 2-terminal block on the shield that is
labeled EXT_PWR. The DC Jack on the Arduino has a protection diode so you won't be able
to mess things up too bad if you plug in the wrong kind of power. However the EXT_PWR
terminals on the shield do not have a protection diode (for a fairly good
reason). Be utterly careful not to plug it in backwards or you will destroy the motor
shield and/or your Arduino!

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


message:
What are the implications of running an ATmega328P at 8 MHz and 3.3 V with the Arduino system?

I'm working on a custom arduino that will run at 3.3 V with no regulators or USB chips (for power consumption).  I've heard that overclocking the chip at 16 MHz/3.3 V is generally fine, but I'd like to stay within spec anyway.

First: to run at 8 MHz, do I just need to replace the crystal?  Or is there anything else I have to do?

Second: Do I need to make any code changes to reflect the new speed?  I'm using serial, SPI, and I2C connections in this project, along with the NilRTOS operating system and millis/delay functions.  Will any of these be broken?  Will the code run noticeably slower?

Third: How can I program the chip?  Is it ok to program it in an Arduino Uno at 16 MHz, then transplant it to the custom arduino?

Fourth: Will power consumption change at 8 MHz?

Thanks!

body:
The formula seems to be volt*5.9-6.6=mhz (valid between 1.8v and 4.5v), so at 3.3v, this would give 12.8mhz. Be aware that, if you are running at 12.8mhz, ANY drop below 3.3v MAY cause problems (and very hard to diagnose, too!) or you MAY get away with it.

However, Arduino Atmega328p chips have a "brown-out" detection set at 4.3v - any drop below that, the chip shuts down. You can get an ISP (AKA ICSP) to change the fuses - go to http://www.engbedded.com/fusecalc/ to work out what to set fuses to. You can also use the ISP to read the current fuses, or indeed reprogram the chip without an Arduino board - all my projects have a 6-pin header. If you do this, before reprogramming using the Arduino board, you will have to "Burn Bootloader" (in the tools menu). Note that programming can still be done via Arduino IDE.

Alternatively, if you want to go "light" (and have an ISP), you can change the fuses to use the internal 8mhz clock - this frees up 2 extra pins, too! Be aware, however, that the internal clock may drift 1.2 hours per day (=5%), compared to 1.7 seconds per day (=20 parts per million) on a typical quartz crystal. If you don't use it for timekeeping, this probably doesn't matter.

You will need to make changes to the timing, for your code - you need to add a boards.txt with correct settings for your chip/clockspeed etc - you can copy the settings from the entry for the board, change the name, and change the setting "build.f_cpu"; restart (or start) your Arduino IDE, go to "Tools->Board" and select the board you added.

You can move the chip on/off the board, and reprogram it there (note that the board selected in Tools->Board is the FINAL board, not the programming board). Be careful plugging/unplugging it - eventually, you WILL bend the pins! Alternatively, you can use ISP (ICSP), as mentioned above - much recommended. ISP programming will also work if the chip is factory default, so long as it has a working clock.

How much power is used by the chip depends hugely on what you do with it - not just clock speeds, clock source, etc but also sleep modes. If you are sleeping a lot, it may draw less when running faster than running slower - if almost all your time is asleep, then the power consumption should be counted per clock cycle, not per second - if your clock is half the speed, and half current, then you draw the same current per instruction. Since the rest of your time is spent asleep, you get no benefit. See http://www.gammon.com.au/power for a very good breakdown of power usage, tips on how to save power, etc.

If you slow your clock down too much, serial and i2c may become unreliable (unless you slow down the speed), but I would expect to be able to go down to  1mhz before this to be a problem - a 1mhz chip trying to do 9600bps has 104 instructions per bit of data transferred. i2c runs at 100khz, so you get 10 instructions per bit (at 1mhz) - possibly pushing it. 8mhz should be fine. Test, test, test.

UPDATE:
There are 3 possible settings for the brown-out detection - there are 3 possible values for the AtMega328p: disabled, 1.8v, 2.7v, and 4.3v. I was under the impression (above) that Arduinos were normally set to 4.3v; apparently that is not the case (see comment below). I recall seeing somewhere that there was brownout detection. This is something to keep in mind, if your arduino resets, especially when putting larger loads on the battery (running motors, multiple leds etc).


body:
> First: to run at 8 MHz, do I just need to replace the crystal? Or is there anything else I have to do?

No, run on the internal oscillator as suggested by AMADANON Inc.

Alternatively, set the "divide clock by 8" fuse (which would run it at 2 MHz from a 16 MHz crystal) and then in code change the division back up to 2. ie.

    #include <avr/power.h>

    void setup ()
      {
      // slow clock to divide by 2
      clock_prescale_set (clock_div_2);
      } // end of setup

Or for programming in another Uno leave the fuse alone, program at 16 MHz and then drop the clock down in the target chip, hoping it works long enough at 3.3V to execute that first instruction. The safest thing would be to just install an 8 MHz crystal or resonator on the target board. However if timing is not critical run with the internal oscillator.

> Second: Do I need to make any code changes to reflect the new speed? I'm using serial, SPI, and I2C connections in this project, along with the NilRTOS operating system and millis/delay functions.

If you tell the IDE you have an 8 MHz processor (eg. a Lilypad) then it should adjust delays, baud rate calculations etc. appropriately.

> Will any of these be broken?

I2C and SPI are self-clocked. They can run at a variety of rates. I doubt there will be any problems with them. As for serial, providing the calculations are done right a wide range of baud rates should still be available.

>  Will the code run noticeably slower?

Well yes, it will run at half speed compared to 16 MHz.

> Third: How can I program the chip? Is it ok to program it in an Arduino Uno at 16 MHz, then transplant it to the custom arduino?

You can do that. Or you could connect up an ICSP header or an FTDI header and program it in situ.

Examples here: http://www.gammon.com.au/breadboard

> Fourth: Will power consumption change at 8 MHz?

Yes, it is reduced somewhat.

You can reduce it considerably more by using other techniques as described at http://www.gammon.com.au/power, and referred to by AMADANON Inc.


message:
How to detect the absence of an RFID tag?

I have installed an [MFRC522 RFID reader][1] in my house. The main use so far is to tell the house I've arrived using an RFID keychain, by leaving it in the key holder.

I would also like for the house to detect when I'm gone, and I was thinking that, if I can detect when a tag is present, I should also be able to detect when it is not.
However, this poses some challenges like the following:

 - Should I be constantly reading the tag until it disappears from range? (when I take it from the key holder).
 - What if I have more than one RFID Keychain/Tag in the range of the reader? (because there could be other keychains in the same key holder). Would I get multiple readings or could one tag interfere with another in some way?

I realize that maybe this is not the typical RFID scenario when the tag is scanned and then moved away from the reader. I've been searching about "RFID tag absence detection" but I've only found what seemed to me like very theoretical papers.

Do you have any advice or experience in implementing something like this?

Thanks!

  [1]: http://playground.arduino.cc/Learning/MFRC522

body:
I don't think it is particularly practical, unless you make your own RFID scanner. The off-the-shelf ones generally only respond once when a particular card is in range, so you can't even detect if the card is left next the reader, or not.

Also, as the range is usually quite limited (a few cm) I don't see how it could tell the difference between you being out of the house, or taking a bath.

What might work better would be to have an active transmitter (eg. a nrf24l01) in your pocket, which every minute or so sent a "I'm home!" message to a central place. The absence of such a message after 10 minutes could indicate you are out.

The other approach would be to "check out" with your RFID scanner. I did an [RFID event management system](http://gammon.com.au/forum/?id=12869) a little while back. You use a special "admin" card to indicate that a person was leaving an event for a while (a pass-out). You could do that, or have a button by the door, which you press. The "I am leaving" button.


body:
Oh Yes it is possible.
I did a project which allows to transmit data from RFID card to a bluetooth device.
You can use below code to identify presence & gone:

    #include <SPI.h>
    #include <MFRC522.h>
    #include <SoftwareSerial.h>

    #define SS_PIN 10
    #define RST_PIN 9
    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

    SoftwareSerial BTserial(0, 1); // RX | TX
    int sensorPin = A0;
    int sensorValue = 0;
    String lastBlock="";
    void setup() {
        Serial.begin(9600); // Initialize serial communications with the PC
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card
    //mfrc522.setPassiveActivationRetries(0x9A); // for example
    //Serial.println("Scan PICC to see UID and type...");
    BTserial.begin(9600);
    Serial.println("Scan PICC to see UID and type...");
    }
    boolean flag=false;
    int counter=0;
    void loop() {
    // Look for new cards
    BTserial.println("Scan PICC to see UID and type...");
    if ( !mfrc522.PICC_IsNewCardPresent()) {
      if(mfrc522.PICC_IsNewCardPresent()){
        if(!flag){
        byte sector         = 1;
    byte blockAddr      = 4;
    byte dataBlock[]    = {
        0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
        0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
        0x08, 0x09, 0xff, 0x0b, //  9, 10, 255, 12,
        0x0c, 0x0d, 0x0e, 0x0f  // 13, 14,  15, 16
    };

    byte trailerBlock   = 7;
    byte status;
    byte buffer[18];
    byte size = sizeof(buffer);
    status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
    dump_byte_array(buffer, 16);

        flag=true;
        }
      }
      else{
        if(flag){
        flag=false;
        }
      }
          return;
    }
    }

    void dump_byte_array(byte *buffer, byte bufferSize) {
    String a=String((char)buffer[9]);
    String b=String((char)buffer[10]);
    String c=String((char)buffer[11]);
    String d=String((char)buffer[12]);
    String str="";
    str+=a;
    str+=b;
    str+=c;
    str+=d;
    lastBlock=str;
    Serial.println(str);
    BTserial.println(str);
    }


message:
Understanding Digital IMU 6DOF sketch

I am looking at the following code and getting confused by a few elements in it:

1) Why is there a writeto function being performed to the memory locations x053,0x31,x09 for accelerometer and 0x68,0x16 and 0x1A for gyro? We are only reading incoming values so what is the purpose of these functions?

2) the bitwise operation being performed in the getGyrscopeReadings and getAccelerometerReadings... are these operations to define how many bits data we will be reading?

        #include <Wire.h> //The I2C library

    int gyroResult[3], accelResult[3];

    //Function for writing a byte to an address on an I2C device
    void writeTo(byte device, byte toAddress, byte val) {
      Wire.beginTransmission(device);
      Wire.write(toAddress);
      Wire.write(val);
      Wire.endTransmission();
    }

    //Function for reading num bytes from addresses on an I2C device
    void readFrom(byte device, byte fromAddress, int num, byte result[]) {
      Wire.beginTransmission(device);
      Wire.write(fromAddress);
      Wire.endTransmission();
      Wire.requestFrom((int)device, num);
      int i = 0;
      while(Wire.available()) {
        result[i] = Wire.read();
        i++;
      }
    }

    //Function for reading the gyros.
    void getGyroscopeReadings(int gyroResult[]) {
      byte buffer[6];
      readFrom(0x68,0x1D,6,buffer);
      gyroResult[0] = (((int)buffer[0]) << 8 ) | buffer[1]; //Combine two bytes into one int
      gyroResult[1] = (((int)buffer[2]) << 8 ) | buffer[3];
      gyroResult[2] = (((int)buffer[4]) << 8 ) | buffer[5];
    }

    //Function for reading the accelerometers
    void getAccelerometerReadings(int accelResult[]) {
      byte buffer[6];
      readFrom(0x53,0x32,6,buffer);
      accelResult[0] = (((int)buffer[1]) << 8 ) | buffer[0]; //Yes, byte order different from gyros'
      accelResult[1] = (((int)buffer[3]) << 8 ) | buffer[2];
      accelResult[2] = (((int)buffer[5]) << 8 ) | buffer[4];
    }

    void setup() {
      Wire.begin();            //Open I2C communications as master
      Serial.begin(9600);    //Open serial communications to the PC to see what's happening

      writeTo(0x53,0x31,0x09); //Set accelerometer to 11bit, +/-4g
      writeTo(0x53,0x2D,0x08); //Set accelerometer to measure mode
      writeTo(0x68,0x16,0x1A); //Set gyro to +/-2000deg/sec and 98Hz low pass filter
      writeTo(0x68,0x15,0x09); //Set gyro to 100Hz sample rate
    }

    void loop() {
      getGyroscopeReadings(gyroResult);
      getAccelerometerReadings(accelResult);

      Serial.print(gyroResult[0]);
      Serial.print("\t");
      Serial.print(gyroResult[1]);
      Serial.print("\t");
      Serial.print(gyroResult[2]);
      Serial.print("\t\t");
      Serial.print(accelResult[0]);
      Serial.print("\t");
      Serial.print(accelResult[1]);
      Serial.print("\t");
      Serial.print(accelResult[2]);
      Serial.print("\n");

      delay(50);
    }

any help would be greatly appreciated!

body:
**The `writeTo` functions**

The accelerometer and gyro both have some memory inside that is used to store the configuration. The specific locations and values can be read from the datasheet, but for now I'll trust the comments. These writeTo functions seem to set the device modes and configure the scale used for the sensors.

Notice that they only happen once, right when the program starts. Maybe the devices have a way of storing persistent settings onboard, but setting them once at each startup is safe and easy.

**The Bitwise ops**

These don't set the number of bits we are reading *per se*, They reconstruct larger than 8-bit values. The I2C serial protocol is set up to use 8-bit data segments, so to send any value larger than 8-bits they must be broken down, sent, and then "stitched" back together in chucks.

`(((int)buffer[0]) << 8 ) | buffer[1];`

Whats happening here is that `buffer[0]` is converted to int (a 16 bit value), then shifted over by 8 bits. This means the 8 bits in the original `buffer[0]` are now located in the top 8-bits of the integer, and the lower 8 bits are zeros. Finally the lower 8 bits are set by the bitwise-or operator `|`, which will turn on any bits that were set in `buffer[1]` in the result. Since the bottom 8-bits were 0's from the shift, this just copies `buffer[1]` in exactly.

The net effect is a 16 bit value that contains the bits of both 8-bit buffer values and can be interpreted as a single number.


message:
Use RFID-RC522 with other Pins

I'm wondering where the pin setting is manifested in the library.
I want to use the RC522 with other digital pins than the default 50-53 pins, because I am using a shield for a display on theese ports.

Where can I change the used ports?
why are two ports user-defineable `#define RFID_SS  10 #define RFID_RST 5` while the rest is not?

I am with this [Playground-Guide][1] using this [library from Github][2] on my Arduino Mega

  [1]: http://playground.arduino.cc/Learning/MFRC522
  [2]: https://github.com/miguelbalboa/rfid

body:
    #define RFID_SS  10
stands for Slave Select on port 10, the SPI is a serial interface, meaning you can connect all kinds of SPI devices to the same wires, as long as slaves have different IO ports.

This is also the reason you don't need to define the other ports because they need to be connected to your SPI.

I suggest you make yourself familiar with this page: http://arduino.cc/en/Reference/SPI

To sum it up. You can change the reset and Slave Select pin out, (those set in the variables) but not the SPI Pins. But you can use the ISCP pins in the middle of the board.


body:
SPI
The RFID_SS pin is the slave select pin.
So you can have another arduino pin for a LCD_SS select.
Having RfID_SS =low - talk to RFID.
Having LCD_SS =low talk to LCD via MISO.
Note: Drive other slave select High otherwise they'll both get the data.
Having only one device in communication at a time.
Cheers
Nik V


body:
Sorry I'm a bit late (5 years late) but hopefully this can help someone who's just now trying to do this!

There's an old obscure Sunfounder library, "rfid1.h" that lets you declare every pin. Like this:

    rfid.begin(IRQ,SCK,MOSI,MISO,NSS,RST);

It's a bit hard to find the library online these days, but at the bottom of this page (http://wiki.sunfounder.cc/index.php?title=Mifare_RC522_Module_RFID_Reader) if you download the "RFID-RC522_test_experiment" zip file it will have the library in there. The secret is that this library includes a software SPI which is sort of like a software serial for SPI communication. Letting other digital pins be used as MISO etc...

This library also makes it much easier to use multiple RFIDs reliably since they don't have to share all the same pins.

You can find some example code here: https://www.sunfounder.com/learn/RFID_kit_V1_for_Arduino/lesson-29-rfid-entrance-guard-system-rfid-kit-v1-0-for-arduino.html