message:
Is this a proper implementation of FreeRTOS for Arduino?

I'm using the **RGBLCDShield** library and a few analog input signals and since it seems the interrupts are being used by the SPI interface of the LCD Shield, I decided to try it with **FreeRTOS** instead.  I don't currently have my arduino with me (left if at parents') but I wanted to get some feedback on this code to see if it would run properly; I might not be getting my UNO back for a few days but I wanted to at least have a usable code ready to be tested when I do get it.

The Analog inputs are just 2 low level signals and the digital outputs just control some IC switches.  One PWM is fed through a lowpass filter and into an amplifier input.

**Here is my code in it's entirety:**

    #include <Arduino_FreeRTOS.h>
    #include <Adafruit_RGBLCDShield.h>
    #include <Wire.h>
    #include <math.h>

    // define tasks
    void TaskAnalogRead( void *pvParameters );  // Check voltage input
    void TaskLCDShield( void *pvParameters );   // Control Display
    void TaskUserInput( void *pvParameters );   // User Interface - System Process

    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
    unsigned int vSet = 0;  // Desired Voltage (potentiometer set)
    unsigned int vOut = 0;  // Voltage on capacitor

    // the setup function runs once when you press reset or power the board
    void setup() {

      // Set up Tasks to run independently
      xTaskCreate(
        TaskAnalogRead
        ,  (const portCHAR *) "AnalogRead"   // A name just for humans
        ,  128  // This stack size can be checked & adjusted by reading the Stack Highwater
        ,  NULL
        ,  2  // Priority, with 1 being the highest, and 4 being the lowest.
        ,  NULL );

      xTaskCreate(
        TaskLCDShield
        ,  (const portCHAR *) "LCDShield"
        ,  128  // Stack size
        ,  NULL
        ,  3  // Priority
        ,  NULL );

      xTaskCreate(
        TaskUserInput
        , (const portCHAR *) "UserInput"
        , 128
        , NULL
        , 1
        , NULL );

      // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
      lcd.begin(16, 2);
    }

    void loop()
    {
      // Empty. Things are done in Tasks.
    }

    /*--------------------------------------------------*/
    /*---------------------- Tasks ---------------------*/
    /*--------------------------------------------------*/

    void TaskLCDShield(void *pvParameters)  // This is a task.
    {
      (void) pvParameters;

      // Start Display
      lcd.setBacklight(0x7);
      lcd.setCursor(0,0);
      lcd.println(" PORTABLE SPARK ");
      delay(5000);
      lcd.clear();

      for (;;) // Continuously Update display
      {

        int volts = vSet * 100.0;
        int chg   = (vOut * 0.488)/volts;
        int vpos, cpos;
        lcd.setCursor(0,0);
        lcd.print("Voltage:       ");
        lcd.setCursor(15, 0);
        lcd.print("V");
        lcd.setCursor(0,1);
        lcd.print("Charge :       ");
        lcd.setCursor(15,1);
        lcd.print("%");

        lcd.setCursor(9,0);
        if(volts < 100)
          {
            lcd.print("    ");
            vpos = 13;
          }
        else if(volts < 1000)
          {
            lcd.print("    ");
            vpos = 11;
          }
         else if(volts < 10000)
         {
          lcd.print("     ");
          vpos = 10;
         }
         else vpos = 9;
        lcd.setCursor(vpos,0);
        lcd.print(volts, DEC);

        lcd.setCursor(9,1);
        if(chg < 10)
          {
            lcd.print("    ");
            cpos = 13;
          }
        else if(chg < 100)
          {
            lcd.print("   ");
            cpos = 12;
          }
        else cpos = 11;
        lcd.setCursor(cpos,1);
        lcd.print(chg, DEC);
        //digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
        vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
        //digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
        //vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
      }
    }

    void TaskAnalogRead(void *pvParameters)  // Read Analog Voltages (VSet, Emonitor)
    {
      (void) pvParameters;

      for (;;)
      {
        int eMon = analogRead(A0); // read input pins
        vTaskDelay(1);
        int vA = analogRead(A1);

        vSet = (vA/1024) * 15000;  // calculate actual values
        vOut = (5.0/1024.0) * 10000 * eMon;

        vTaskDelay(10);  // one tick delay (300ms) in between reads
      }
    }  // End Analog Read

    void TaskUserInput(void *pvParameters) // User Interface
    {
      (void) pvParameters;

      // initialize digital pin 13 as an output.
      pinMode(8, OUTPUT);  // Fire signal
      pinMode(7, OUTPUT);  // Charge/Discharge signal
      pinMode(5, OUTPUT);  // Eprgm PWM output
      pinMode(4, OUTPUT);  // Cam/DAQ trigger

      bool charge = false;   // charge flag

      for (;;)
      {
        uint8_t button = lcd.readButtons();
        switch(charge)
        {
          case true:
            analogWrite(5, (vSet * 0.0204)/5);
            vTaskDelay(1);
            digitalWrite(7, HIGH);
            vTaskDelay(1);
            break;

           default:
            analogWrite(5, 0);
            vTaskDelay(1);
            digitalWrite(7, LOW);
            vTaskDelay(1);
            break;
        } // End Switch(charge)

        if(button & BUTTON_UP)  // Charge/Discharge button
        {
          charge = !charge;
        } // end if

        else if(button & BUTTON_DOWN) // Fire!
        {
          digitalWrite(8, HIGH);
          vTaskDelay(1);
          digitalWrite(4, HIGH);
          vTaskDelay(1);
          digitalWrite(7, LOW);
          charge = false;
          vTaskDelay(1);
          digitalWrite(4, LOW);
          vTaskDelay(1);
          digitalWrite(8, LOW);
        } // End else if

      }  // End for

    } // End User Interface

My specific concern is with the 2wire interface of the LCD shield and whether it would be able to communicate with the Arduino - especially when it needs to read the button inputs.
Also, how do I determine the stack size for each task?  Is 128 for each enough to handle what I have?

body:
This is not a direct answer to the question. Instead, I suggest that you
do not need an RTOS to do what you want. A lightweight alternative is to
use `millis()` to decide when it is time to perform such or such task:

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

    void loop()
    {
        uint32_t now = millis();

        // Update the LCD every second.
        static uint32_t last_lcd_update;
        if (now - last_lcd_update >= 1000) {
            last_lcd_update = now;
            update_lcd();
        }

        // Read the analog inputs every 300 ms.
        static uint32_t last_analog_read;
        if (now - last_analog_read >= 300) {
            last_analog_read = now;
            do_analog_read();
        }

        // User input is handled continuously.
        handle_user_input();
    }

This will use significantly less resources (flash, RAM and CPU time)
than an RTOS. Another advantage is that you do not need to determine a
stack size for each task, which is definitely _not_ a simple thing to
do.


sender: user

message:
Creating a library

I created a simple library for formatting text output on the serial monitor. It has thee functions, one that creates carriage returns, one that sets the number of spaces between characters and the last one prints dashes. I followed the tutorial on the Arduino.cc site. The problem I have is that I can’t pass the value to each of the functions when I call them in the code. If you look at the screenshot from the sketch when I create an instance of nFormat it requires me to put a value in and it passes that value to each of the functions (lines, spaces, dashes). I want to be able to specify the value directly when I call the function. See the second red line on the output screenshot. I know this post is a bit long I would appreciate it if someone could point me in the right direction.

nFormat.h

    #ifndef nFormat_h
    #define nFormat_h

    #include "Arduino.h"

    class nFormat
    {
      public:
     nFormat(int counter);

        void lines();
        void spaces();
     void dashes();

       private:
     int _counter;
    };

    #endif

nFormat.cpp

    #include "Arduino.h"
    #include "nFormat.h"

    nFormat::nFormat(int counter)
    {
     _counter=counter;
    }

    void nFormat::lines()
    {
    for (int x = 0; x < _counter; x++)
     {
      Serial.println(" ");
     }

    }

    void nFormat::spaces()
    {
     for (int x = 0; x < _counter; x++)
     {
      Serial.print(" ");
     }
    }

    void nFormat::dashes()
    {
     for (int x = 0; x < _counter; x++)
     {
      Serial.print("-");
     }

[![output][1]][1]

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

sender: assistant

body:
If you want to specify the number of spaces/dashes/... every time you
call any of these methods, you just have to make that number a parameter
of the method:

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

    void lines(int count)
    {
        for (int x = 0; x < count; x++)
            Serial.println();
    }

Then, your class does not need its private `_counter`. Then, since there
is no data in the class, you do not need to instantiate it: just make
all the methods `static` and call the methods as
`nFormat::method_name()`. And since you are not making instances, you do
not need a constructor either. And since the methods are really trivial,
there is no point in implementing them in a .cpp file: you can just
inline them in the class declaration. Combining all this gives this small
demo program:

    class nFormat
    {
      public:
        static void lines(int count)
        {
            for (int x = 0; x < count; x++)
                Serial.println();
        }

        static void spaces(int count)
        {
            for (int x = 0; x < count; x++)
                Serial.print(" ");
        }

        static void dashes(int count)
        {
            for (int x = 0; x < count; x++)
                Serial.print("-");
        }
    };

    void setup()
    {
        Serial.begin(9600);
        nFormat::dashes(5);
        nFormat::lines(5);
        nFormat::spaces(5);
        nFormat::dashes(5);
    }

    void loop() {}

It could be noted than this class serves only to avoid putting all the
functions in the global namespace. It is essentially a namespace. You
could as well replace `class` by `namespace` (and remove the `public`
keyword) to make that more explicit.


message:
Is it possible to connect 2 ultra sonic sensors to 1 arduino?

I am currently using the Arduino Pro Micro board and I want to connect 2 ultrasonic sensors to 1 board, whilst knowing which sensor is being triggered. The sensor I am using is a HC-SR04 Ultrasonic sensor.

Please help me thank you :)

body:
Yes, you can, as long as you serialize the send/receive pulse cycles, to avoid interferences.
basically, you attach the Trig/Echo lines to a different pair of pins, then do the reading on one sensor, then do the reading on the other.


body:
What you need to do, for each sensor, is the following:

 - choose a GPIO that will drive the trigger line (make sure it is not a pin you are already planning to use, ex: TX/RX )
 - choose a pin that will receive the information from the Echo line, ideally using an interrupt driven implementation, instead of polling. The 328P supports exactly 2 independent interrupt lines: INT0 and INT1, so you could use one of them for each sensor.
 - have a time base and use it to time-stamp the Trig and Echo lines

Example for one sensor (for 2 just do the same and keep in mind that there might be interferences, like the OP said):

 1. toggle the Trig line for the required duration (strobe)and save it
 2. read the time
 3. wait for the interrupt to occur (you can do other things in the meanwhile)
 4. when the interrupt occurs, read again the time
 5. subtract the timestamp taken after toggling Trig from the timestamp taken after the Echo interrupt
 6. convert the delta time from the previous point into a linear measure, using the constant provided by the datasheet of the sensor


message:
Weird characters in Serial Monitor and not functioning ESP8266 ESP-12e

I did a bit of playing with my new ESP-12e, but suddenly it kind of fails on me. It gives me some weird looks it didn't give me (as much) before.

[![enter image description here][1]][1]

**This is what the Serial Monitor prints when I try to run a very simple sketch.** When I restart the module, it just adds some more of these chars.
**The following is the code for that:**

    const int statusLED = 16;

    void setup() {
      pinMode(statusLED, OUTPUT);
      digitalWrite(statusLED, HIGH);

      Serial.begin(115200);
      Serial.write("The ESP-12e has started.");
      delay(500);
    }

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

This doesn't even involve the WIFI...

**These are my board settings:**

*Board: Generic ESP8266 Module

Flash mode: QIO

Flash frequency: 40MHz

CPU frequency: 80MHz

Flash size: 4M (3M SPIFFS)

Upload speed: 115200*

**And finally, if it might help, how I connected the module:**

[![enter image description here][3]][3]
All connections are solid, so that shouldn't be a problem. *The connection board has GPIO15 printed on it twice, but the one I connected to the LED is actually GPIO16.* I noticed that the onboard LED of the ESP-12e doesn't light on anymore.

I use the CP2102 USB to UART module.

Thanks!

Rogier

  [1]: https://i.stack.imgur.com/L6EUc.png
  [3]: https://i.stack.imgur.com/6Wn1U.jpg

body: Check what baud rate is serial window displaying. It should be the same as defined in your code.


message:
How to filter a blank line received over serial - ESP8266

How can I filter a garbage completely blank line over my serial data? It comes from the wifi module ESP8266

How I read data:

      while (Serial1.available()){
           String inData = Serial1.readStringUntil('\n');

           Serial.println("Got: " + inData);

      }

Here is my common output:

    Got: AT+CIPSEND=6
    Got:
    Got: OK
    Got: >
    Got: Recv 6 bytes
    Got:
    Got: SEND OK
    Got:
    Got: +IPD,21:Volume From: 99 To 89AT+CIPCLOSE
    Got: CLOSED
    Got:
    Got: OK

body:
    inData.trim();
    if( inData.length() > 0 ){
       Serial.println("Got: " + inData + "\n");

::trim() removes all leading and trailing whitespace characters including newlines. A line of [zero or more whitespace] + [newline] will get trimmed to the null string. If the result isn't null, then append the stripped off newline and print it. Note that this will flatten any indentation or vertical spacing that was supplied in the incoming text.


message:
What is more power efficient: GPRS or SMS for a GSM sim Arduino application?

I have a GSM shield for my arduino and am wondering the most efficient way to receive and send data to the cloud.

The specific project I am looking to accomplish is starting my car from a web browser (or custom built ionic mobile app) that will send data to my GSM shielded arduino and the arduino then "press the button" of an already installed remote car starter (which is all probably in the car's trunk).

What is more power efficient, sending and receiving a SMS (text message) or sending and receiving data via GPRS?

What is best when considering strategies like sleep, or deep sleep cycles?

body:
Looking at it logically SMS is probably the most power efficient method.

The thinking is this:

**With SMS:**

* The shield sits there connected to the mobile network doing nothing much
* An SMS is sent by you which travels through the mobile network
* The SMS is sent from the mobile network to your GSM shield which then wakes up and does things with it
* The shield sits there connected to the mobile network doing nothing much

**With GPRS:**

* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service and sees a request is available
* The shield downloads the request
* The shield acts on the request
* The shield goes back to querying the on-line service
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* ... etc ad nausium ...

As you can see with SMS the onus is on the mobile network to send the data to the shield, whereas with GPRS the onus is on the shield to keep querying an on-line service to see if there is any requests to handle. There is no way of you sending data to the shield directly (indeed, most GPRS services include at least one layer of NAT gatewaying). So your shield has to be active all the time and constantly looking at something online - not only power hungry, but potentially financially expensive too.


body:
You could theoretically use a SIP Server in the middle to keep the session alive over GPRS or higher. And there are techniques you can use to make it as power efficient as can be, depending on your application (which is a rather simple one I assume with little data throughput).

However, as @Majenko stated above, it may not be as power efficient as SMS.

That said, there may be other considerations, such as cost of sending/receiving SMS messages that may matter as you weigh the totality of requirements for your application.

I haven't worked personally on a Particle board (particle.io) but they do have a MCU/3G board that provides a certain amount of free (as in no $) bandwidth per month that might be a reasonable solution to consider for your application.

Please keep us posted. I'm considering something similar myself.


message:
problem using GSM shield and GPS shield in one Arduino UNO R3

i try to program use the GSM shield Arduino with Arduino UNO i did it successfully but after that i try to use GPS shield but when i add the #include <SoftwareSerial.h> for the program i got the error

    #include <GSM.h>
    #include <TinyGPS.h>
    #include <SoftwareSerial.h> // when i add that one i got the output eroor
    // PIN Number for the SIM
    #define PINNUMBER ""

i got this error out put

    Arduino: 1.6.6 (Mac OS X), Board: "Arduino/Genuino Uno"

    libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `__vector_3':
    /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:227: multiple definition of `__vector_3'
    libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:499: first defined here
    libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::read()':
    /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:392: multiple definition of `__vector_4'
    libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:487: first defined here
    libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::read()':
    /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:392: multiple definition of `__vector_5'
    libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:487: first defined here
    collect2: error: ld returned 1 exit status
    exit status 1
    Error compiling.

      This report would have more information with
      "Show verbose output during compilation"
      enabled in File > Preferences.

body:
It appears the GSM library has its own conflicting copy of SoftwareSerial, and not necessarily a matching version unless you're lucky.

Not sure how well this would work but you can try removing the library reference to SoftwareSerial, and fiddle about to use the GSM library's SoftwareSerial.


message:
Building Multidimensional Arrays from simple arrays

Hi I am trying to write a functiont that will build a 2x4 array based on 2 1x4 arrays.

the two relevant functions are below. The first function gets information from some sensors and outputs it (I think) as a 1x4 array.

The second function is the problem and I have attached the error messages.

    {
    double quatCalib_mat[2][4];
    double quatCalib_ABC[4];
    double quatCalib_GHI[4];

     double  get_quat(Adafruit_BNO055 ref, double quatArray[])
    {
      imu::Quaternion quat2 = ref.getQuat();

      quatArray[0]= quat2.w();
      quatArray[1]= quat2.x();
      quatArray[2]= quat2.y();
      quatArray[3] =quat2.z();

    }

    void Calibrate()
    {
    quatCalib_ABC=get_quat(bnoABC, quatCalib_ABC);

    quatCalib_GHI=get_quat(bnoGHI, quatCalib_GHI);

    quatCalib_mat= {
      {quatCalib_ABC},
      {quatCalib_GHI}
      };
    }

the error messages

    Arduino: 1.6.9 (Windows 7), Board: "Arduino/Genuino Uno"

    E:\UNI2016\thesis\gizmo programming\Thesis_V3_M\Thesis_V3_M.ino: In function 'void Calibrate()':

    Thesis_V3_M:101: error: incompatible types in assignment of 'double' to 'double [4]'

     quatCalib_ABC=get_quat(bnoABC, quatCalib_ABC);

                  ^

    Thesis_V3_M:103: error: incompatible types in assignment of 'double' to 'double [4]'

     quatCalib_GHI=get_quat(bnoGHI, quatCalib_GHI);

                  ^

    Thesis_V3_M:105: error: assigning to an array from an initializer list

     quatCalib_mat= {

                  ^

    exit status 1
    incompatible types in assignment of 'double' to 'double [4]'

Cheers

Alex

body:
As Mikael Patel said, the compiler is already hinting you about what is
wrong. But there are other issues.

1. In `get_quat()`, there is no point in returning anything, as the
   function is already putting the relevant info in the `quatArray`
   parameter.
2. Then, when calling `get_quat()`, you don't want to assign the return
   value to anything.
3. You cannot assign an array like you did, unless it's an
   initialization. I would explicitly copy the sub-arrays with
   `memcpy()`:

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

    void get_quat(Adafruit_BNO055 ref, double quatArray[])
    {
        imu::Quaternion quat2 = ref.getQuat();
        quatArray[0] = quat2.w();
        quatArray[1] = quat2.x();
        quatArray[2] = quat2.y();
        quatArray[3] = quat2.z();
    }

    void Calibrate()
    {
        get_quat(bnoABC, quatCalib_ABC);
        get_quat(bnoGHI, quatCalib_GHI);
        memcpy(quatCalib_mat[0], quatCalib_ABC, sizeof quatCalib_ABC);
        memcpy(quatCalib_mat[1], quatCalib_GHI, sizeof quatCalib_GHI);
    }

It could be noted that storing the calibration array twice (as both one
2D array and two 1D arrays) is a waste of RAM. You could get rid of the
1D arrays and have instead `get_quat()` fill the lines of the 2D array
directly:

    void Calibrate()
    {
        get_quat(bnoABC, quatCalib_mat[0]);
        get_quat(bnoGHI, quatCalib_mat[1]);
    }


message:
Using HC-05 to play a sound on an app

I connected a HC-SR04 Ultrasonic Sensor to Arduino Uno and built the circuit as shown in the link below. I also used the code below the link. Together, this code and the circuit detect any motion that occurs in front of the ultrasonic sensor. When the sensor detects motion, the console in the Arduino IDE prints that it detects motion and how far away the moving object is. Otherwise, nothing is printed.

I created an app using MIT App Inventor. Every time the Arduino detects motion, I want a sound to be played on the phone of the person with the app. In order to do this, I plan on using a HC-05 Bluetooth Module.

Does anyone have any suggestions for how I should build the circuit and what code I should use?

arduinobasics.blogspot.de/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html

    #define echoPin 7 // Echo Pin
    #define trigPin 8 // Trigger Pin
    #define LEDPin 13 // Onboard LED

    int maximumRange = 200; // Maximum range needed
    int minimumRange = 0; // Minimum range needed
    long duration, distance; // Duration used to calculate distance

    void setup() {
     Serial.begin (9600);
     pinMode(trigPin, OUTPUT);
     pinMode(echoPin, INPUT);
     pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
    }

    int prevdist = 0;

    void loop() {
    /* The following trigPin/echoPin cycle is used to determine the
     distance of the nearest object by bouncing soundwaves off of it. */
     digitalWrite(trigPin, LOW);
     delayMicroseconds(2);

     digitalWrite(trigPin, HIGH);
     delayMicroseconds(10);

     digitalWrite(trigPin, LOW);
     duration = pulseIn(echoPin, HIGH);

     //Calculate the distance (in cm) based on the speed of sound.
     distance = duration/58.2;

     if (distance >= maximumRange || distance <= minimumRange){
     //Print "Out of range when there is no object within the range of the ultrasonic sensor.
     Serial.println("Out of range.");
     digitalWrite(LEDPin, HIGH);

     }
     else {

     /* Send the distance to the computer using Serial protocol, and
     turn LED OFF to indicate successful reading. */

       if((prevdist - distance) > 10 || (prevdist - distance) < -10)
       {
         prevdist = distance;
         Serial.println("[OBJECT MOVED]");
         Serial.print("Detecting object ");
         Serial.print(distance);
         Serial.println(" cm away");
         Serial.println();
         digitalWrite(LEDPin, LOW);
       }
     }

     //Delay 1 millisecond before next reading.
     delay(1);
    }

body:
> Every time the Arduino detects motion, I want a sound to be played on the phone of the person with the app. In order to do this, I plan on using a HC-05 Bluetooth Module.
>
> Does anyone have any suggestions for how I should build the circuit and what code I should use?

The Arduino sketch above is a good start.

The first step is to connect the Bluetooth module so that the Serial output can be sent. The circuit is simply connecting the Bluetooth module to RX/TX on the Arduino. I am assuming that you have written an app that can read from Bluetooth on the phone and write to the screen.

The second step is to parse the output and play the sound. That is also part of the app and not the code on the Arduino. To make this easier the sketch output statements can be changed to something easier to parse (detect).

All and all the work is mainly app programming.

Cheers!


message:
Arduino: put string through variable in array

I have a problem and I can't fix it.
I'm busy with an java to arduino project.

Java writes a string using writeString();
Arduino reads the serial monitor and put the incoming string into a function.

then I want to put the string into a variable and the variable into a char arr[];

The problem is: When I put the string directly in the arr[]; it works, but when I put first the incoming string in a variable and then the variable in the arr[]; it gives me the next error:

> string-parser:44: error: array must be initialized with a brace-enclosed initializer
>
> exit status 1
>
> initializer fails to determine size of 'arr'

this is the code that doesnt work:

    input = "2,5>2,6>2,7>4,8";

    String splitStringIntoCoordinates(String input){
      char arr[] = input; // Place incoming route in char array
    }

This is the code that does work:

    String splitStringIntoCoordinates(String input){
      char arr[] = "2,5>2,6>2,7>4,8"; // Place incoming route in char array
    }

I hope anyone can help me.
Thanks!

body:
A String isn't a char array. You can't assign one to the other.

You shouldn't be using String, it's too heavyweight, and how you are passing your String object is wrong, it wastes huge amounts of memory making clones.

You should read [this](https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/).

The only time you should ever consider using a String object is if you are using a third party library that requires a String object - and even then you should consider other methods.

Regardless of that, you need to copy the *content* of your string, not the string itself.  This code *should* work, but it doesn't address the underlying String issues:

    String splitStringIntoCoordinates(String &input){
      char arr[input.length() + 1]; // Create a char array big enough including the terminating NULL
      strcpy(arr, input.c_str()); // Place incoming route in char array
      // ... etc ...
      // return a string
    }

If you just want to reference the String as a C string you can just use the function `input.c_str()` to get the internal `char *` array pointer.


message:
How do I power my Arduino Micro directly?

I just need some confirmation, before I break something. So far I have been powering my project from USB, no I would like to power it from a battery. The official spec claims I should use a voltage anywhere from 7-12V, so I got myself a 9V block battery and would connect the positive lead to the VIN pin and the negative lead to the ground pin right next to it, based on this schematic: https://40.media.tumblr.com/cdadca4e95808b376de52a88a5468367/tumblr_mi61oww6cu1s5t695o1_1280.png
Do I need a resistor?

body:
According to [this][1] schematic, VIN goes to the on arduino-micro's 5 and 3 volt regulators.  So you should not need a resistor.

The 5 volt regulator needs a bit more than 5 volts at it's input to do a good job.  That is why the specification calls for 7 to 12 volts.

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-micro-schematic.pdf


message:
Sound or motion activated long term battery powered Arduino

Basically, I want an Arduino to power up whenever a "creature" enters viscinity (at least within up to 3 meters).

I would really like this to be able to keep monitoring for at least 4-8 weeks, without having to replace batteries. I don't want to use more than 1 or 2 18650 Liion cells.

Couple of methods that I believe would work:

- Changes in light-conditions.
- Sound.
- Small vibrations in the ground.

Approaches to conserve power:

- Checking for changes in light at most every 30 seconds (boot the Arduino, and power off quickly).
- Checking for 1 second for sound, every 10-15 seconds.
- Vibrations in the ground using an accelerometer?

The ideal solution does not run the Arduino at all, unless a trigger causes it to run. When the Arduino starts, it will have to turn itself off again to resume monitoring mode.

What approach should I go for? I'm not very good with electronics, and would like to avoid configurations involving transistors, resistors and so on - unless stricktly required.

Is it possible/easy to wire an Arduino Pro Mini to run directly off a 3.7 V battery, bypassing any power hungry voltage regulators?

body:
What you want to do after the triggering is an important part of this design.

An Arduino platform is not necessarily the best choice for power sensitive applications.  You identified one problem in your post: Linear regulators.  What you are likely wanting is an efficient switching power supply to support a wide range of voltages as your batteries drain.

Many embedded processor have low power modes.  Some are specially designed to reduce current draw down into the nA range when idle or sleeping.  However, all such processors require special care when configuring for these deep sleep modes.  That is to say, the application plays an important roll in deciding how to put a processor into such modes.

Supporting hardware is perhaps the most important aspect of a low power designs.  Contributions from the most advanced low power processors can be wiped out if supporting hardware runs at mA ranges.  A simple 10K pull up resistor will draw 0.5mA in a 5 volt circuit. The impact is meaningless in a mains powered application.  But for long term battery operation is could means days of lost time.

All that said, there are resources for Arduino low power operation.  [Here][1] is a low power library.  You will have to decide if it is sufficient for you application. Or if you need to also investigate low power hardware solutions.

  [1]: https://github.com/rocketscream/Low-Power


body:
Rechargeable lithium batteries have great energy density but they also have some significant self-discharge, making a bad choice for low-power applications. Have a look on this Arduino "clone": [https://talk2.wisen.com.au/product-talk2-whisper-node-avr/][1], which is designed to run from standard Alkaline batteries and consumes very little (under 4µA when sleeping).

For the sensors, you should look for smart ones. You can find some very sophisticated MEMs sensors which will produce interrupt based on thresholds. You normally use I²C interface to talk to those little devices.

For example, you could use something similar to this one for light sensing: [http://www.vishay.com/optical-sensors/list/product-83462/][2]. Although this is a proximity sensor, it also has thresholds for the ambient light as well as consumes very little current.

The most important is to design the solution to run at lower voltage (3.3V instead of 5V) and also use interrupts to wake-up everywhere. If you like to run a bare ATMega328p directly from a 18650 cell, make sure everything will be ok to run from 4.2V to 3.0V as you're not using any regulation.

  [1]: https://talk2.wisen.com.au/product-talk2-whisper-node-avr/
  [2]: http://www.vishay.com/optical-sensors/list/product-83462/


body:
For a truly low-power, Arduino-based, solution the following it's needed:

**A) HARDWARE SIDE:**

 1. Use a supply voltage and clock frequency as low as possible. The Arduino Pro Mini 3.3V @ 8Mhz board is a good starting point for a first project.
 2. Get rid of all the LEDs in the board. Their consumption is in the mA range, way too high.
 3. Get rid of the onboard regulator and replace it with a low quiescent current, low dropout regulator like the [MCP1700][1]. You don't need a switching regulator unless your Arduino spends most of the time awake and consuming a lot of current, which is a very unlikely scenario. The high quiescent current of switching regulators rules them out for this kind of applications.
 4. Select a low-power consumption sensor and signal conditioning circuitry. PIR and CMOS logic family 74HC are good technologies for this.
 5. The signal conditioning circuit must generate a level interrupt from whichever signal is delivered by the sensor. Timing elements (like capacitors) may be required for this. To be on the safe side, design it for a 100 ms resettable pulse.

**B) SOFTWARE SIDE:**

 1. Install a low power Arduino library like [this one][2]. Use the ATmega328p power-down sleep mode.
 2. Write a interrupt service routine (ISR). This is the piece of code  will deal with whichever needs to be done upon an interrupt event.
 3. Configure the interrupts as required. Note that only level-triggered interrupts can wake up ATmega328p from power-down sleep mode, as per its datasheet:

[![Wake-up sources][3]][3]

[Here][4] you can find really good information on the way to go low power.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/20001826C.pdf
  [2]: https://github.com/rocketscream/Low-Power
  [3]: https://i.stack.imgur.com/8m7Or.png
  [4]: http://www.home-automation-community.com/arduino-low-power-how-to-run-atmega328p-for-a-year-on-coin-cell-battery/


message:
Why is my potentiometer giving strange reading?

I have a 10kOhm linear Potentiometer. I connected it to analog 0, as in https://www.arduino.cc/en/Tutorial/Potentiometer.

The analogRead() gives a value between 0 and 1023, so I was expecting 0 if the potentiometer is at the lowest position, 1023 if it is at the highest position and 500 somewhere in the middle.

In fact I get ~40 at the lowest position, I get 1021 at the highest position (that's okay, I guess), and I also get 1021 at the middle. 500 is at a 1/4 position, I expected to have ~255 there.

I measured the resistance of the potentiometer. It reads ~200 Ohm at the lowest postion, 10kOhm (as expected) at the highest position and ~5kOhm in the middle, so, exactly as I expected.

So, what did I get wrong?

body:
It sounds like you have a *log taper* potentiometer rather than a *linear taper* potentiometer.  These are used in audio applications.

You can tell the difference by looking at the resistance code.  It may be written as:

> 103 B

or

> 10K B

both of which are 10KΩ LOG taper.  The letter A or B as a suffix is the taper type. A is linear, and B is logarithmic.  That's the "normal" standard, though, but Japan does it differently. They use A for Audio taper (log taper) and B for linear.


body:
Unfortunately I cannot comment. I can't really think of a reason why your readings are the way they are. Though you did not present to us an image of what potentiometer you are using and how you are really wring it up.

It is possible that your potentiometer is a center tapped type with 4 pins. You could have possibly connected the positive rail to the center tap pin, ground to the side pin and the wiper pin to the Arduino pin so that you would have the result you are getting.

Or potentially, you wired it correctly except for the fact the positive rail you connected to was 10V, but that is really dangerous.

Have you tried measuring the resistance of the potentiometer from one side pin to the other side pin?


message:
Generate particular pulse using Arduino

How can I generate this pulse with an Arduino Micro?

Is it necessary an external component?

[![enter image description here][1]][1]

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

body:
[![enter image description here][1]][1]

If both inputs are 0V, the output will be 0V.

If both inputs are 5V, the output will be 5V.

If one input is 0V and one 5V the output will be 2.5V.

However, if the device attached to the output doesn't have a high input impedance, the voltage will drop some. You could add an opamp to prevent this.

I think you can generate the 2 pins outputs using one of the timers in phase correct pwm mode. Freeing up the cpu and giving a very clean output signal, as using software "pwm" could be slightly of due to interrupts occuring.

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


body:
Take two 10K or so resistors:

        +5V
         |
        10K
         |
    Pin2-+---> output
         |
        10K
         |
        GND

The following program does the trick:

    const uint8_t kPin = 2;
    const uint32_t kDelay = 10;  // 100Hz

    void setup() {
    }

    void loop() {
      pinMode(kPin, OUTPUT);
      digitalWrite(kPin, HIGH);
      delay(kDelay);

      pinMode(kPin, INPUT);
      delay(kDelay);

      pinMode(kPin, OUTPUT);
      digitalWrite(kPin, LOW);
      delay(kDelay);

      pinMode(kPin, INPUT);
      delay(kDelay);
    }

When Pin2 (or any other pin for that matter) is set as `INPUT`, it is in high-impedance state (theoretically), so effectively you have a voltage divider giving you 1/2 Vcc. When it is set as `OUTPUT`, and now assuming that its output impedance is << 10KΩ, it drives the output to either +5V or 0V.

[![enter image description here][1]][1]

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


message:
Syncing/taking external clock for SPI on Arduino Due

I have an Arduino Due with a SAM3X8E chip and am trying to read SPI data from an external source that is communicating in SPI. I was able to get data by identifying specific bytes that are identifiers but realized that the clock for my board is not synced with the source coming in. I print out the bytes in hexadecimal format (08 00 FF AB etc) and each message is 128 bytes long.

To be clear, the source is an SPI master that is sending out data on its own MOSI line, but I am currently treating my board as a master as well since I do not know how to do Slave mode on Due. I connect the Slaves MOSI line to my boards MISO line, and just transfer data and read 128 bytes but it would appear that I am not getting the same data. Is there a way for my to take in the clock from the external clock and synchronize my board with that clock to make sure? My source code is below. The only methods I can think of are to either figure out how to implement the board in slave mode (i'm not familiar enough with the registers and how to change this, or read data in slave mode) or synchronize the clocks so my board is reading and sampling the source data correctly.

Could someone check if my thinking is correct, or do I not need to make any changes since the data is in a shift register?

Thanks

----

    void setup(){
    Serial.begin(9600);
    SPI.begin();
    SPISettings settings (50000000, LSBFIRST, SPI_MODE1); //Sampling rate    50Mhz, source's max speed
    SPI.beginTransaction(settings);
    }

    void loop(){
      int i = 0;
      uint8_t value;
      value = SPI.transfer(0x00);
      while (value != 8){//searching for identifier 0x08
        value = SPI.transfer(0x00);
      }
      SPI.transfer(buffer, 127);//get the rest of the 127 bytes
      Serial.print(value, HEX);
      Serial.print(" ");
      for (i = 0; i < 127; i++){
        if (buffer[i] == 0){
          Serial.print(buffer[i],HEX);
          Serial.print(0, HEX);
        }
        else{
          Serial.print(buffer[i], HEX);
        }
        Serial.print(" ");
      }
      Serial.println("\n");
    }

body:
For your external source to be an SPI bus master, it has to be the only one generating the clock signal. Yet, calling `SPI.transfer()` also generates a clock signal *from the Arduino*; both devices are attempting to drive the clock line simultaneously, hence your problems.

You have to bit-bang this or manipulate the SAM registers yourself to configure it as a slave; the SPI library doesn't support slave mode.
In order to bit-bang, you'll have to define your own MOSI, SCK, SS (and MISO, if you'll be writing to the master) pins and do all the sampling yourself with `digitalRead()`; there are no registers to be read from since you aren't using the SAM's SPI peripheral.

Since your SPI mode is MODE 1, it means the clock idle polarity is LOW, and that data is sampled on the falling edge. To bit-bang with `digitalRead()`, it is necessary that the SCK frequency be below 50 kHz (`digitalRead()` [takes][1] about 4us), taking overhead into account. You should use direct port manipulation, if you need a higher frequency. If you'll be blocking till you've read data, and assuming that the external source always sends data in byte units, then a basic algorithm:

 1. Create a `byte` array to hold all the expected bytes
 2. Define a `byte` variable (`curr_byte`, maybe) for holding each byte received
 3. Wait till the SS pin goes LOW
 4. Clear `curr_byte` to zero
 5. Wait till SCK goes HIGH
 6. Wait till SCK goes LOW
 7. Read the bit on the MOSI line and shift it into `curr_byte`
 8. If you've received up to 8 bits so far, save `curr_byte` to the `byte` array; if SS is still LOW, go to step 4, else exit this loop. But if you haven't received a complete byte yet, go to step 5.

After you leave the loop, you can then confirm the bytes you've received with Serial. If the external device can send data with any number of bits, then you should always check the SS line after you shift in a bit, to determine if the Due has been deselected or not i.e. if there are any more incoming bits.

  [1]: http://jeelabs.org/2010/01/06/pin-io-performance/


message:
ATTiny85, how to fix overwritten clock pins?

I'm using an ATTiny85 with an external 16MHz clock. I accidentally set pins 3 and 4 to output using pinMode() in a program and uploaded it, and now I'm getting an invalid device signature (the signature is 0) error when I try to upload a sketch.

How can I go about fixing this (if possible)?

I am using an Arduino UNO as ISP, with an external 16MHz clock and capacitors connected to pins 3 and 4, and have rechecked my wire setup multiple times.

body: Holding the chip in reset while powering it on will ensure that the pins are never reconfigured.


message:
Arduino/Genuino not in board list

I've downloaded the Arduino IDE and the Genuino isn't in the list of boards. I'm running Rasbian and used the command line to install.

body: "Genuino" is just a name, not an identifier. Pick the equivalent Arduino board from the list.


message:
MQTT and IR code Raw

I want to upload/pubish RAW IR Code to MQTT server received through my ESP8266. I have received the following RAW IR code from the Television using the IR receiver sensor:

    RAW IR CODE = {
      4650,4250, 700,1550, 650,1550, 700,1550, 650,450,
      650,500, 600,500, 600,500, 600,550, 550,1700, 550,
      1650, 600,1650, 550,550, 600,500, 600,550, 550,550,
      600,500, 600,550, 550,1650, 600,550, 550,550, 600,500,
      600,550, 550,550, 600,500, 600,1650, 600,500, 600,1650,
      550,1700, 550,1650, 600,1650, 550,1650, 600,1650, 600
    }

I want to create a new variable with the following structure:

    value = RAW IR CODE+";" + "ESP8266-01"(This is the ID of the esp8266)

    value =  {
      4650,4250, 700,1550, 650,1550, 700,1550, 650,450, 650,500,
      600,500, 600,500, 600,550, 550,1700, 550,1650, 600,1650, 550,550,
      600,500, 600,550, 550,550, 600,500, 600,550, 550,1650, 600,550,
      550,550, 600,500, 600,550, 550,550, 600,500, 600,1650, 600,500,
      600,1650, 550,1700, 550,1650, 600,1650, 550,1650, 600,1650,
      600
    }; ESP8266-01

I am unsure: which data type do I need to save the variable value so that it can later be retrieved/subscribed and sent to another IR sender using `irsend.sendRaw`, because I want to split the variable "value" into 2 parts after receiving it, the ID and the RAW code. After getting the RAW code, I want to use the `irsend.sendRaw`(RAW CODE, length of RAW , 38).

Could someone help me?

My attempts:
At first I tried to save it as a string, so that it can be retrieved and separated for `irsend.sendRaw`. However I am unable to compile it.

This is the code which I used to upload:

          /*
         * IRremoteESP8266: IRServer - MQTT IR server
         * An IR LED must be connected to ESP8266 RX port (GPIO-3)
         * An IR receiver to GPIO 0
         * used library:
         * https://github.com/markszabo/IRremoteESP8266
         */
        #include <WiFiClient.h>

       #include <ESP8266WiFi.h>

     #include <IRremoteESP8266.h>
        #include <PubSubClient.h>
        int RECV_PIN = 0; //an IR detector/demodulator is connected to GPIO pin 0

        IRrecv irrecv(RECV_PIN);
        decode_results results;

        const char* ssid = "MY-SSID";
        const char* password = "MY-WIFI-PSK";

        const char* topicRaportPrefix = "esp8266/02/info/";
        const char* topicSubscribe = "esp8266/02/sender/#";
        const char* topicPrefix = "esp8266/02/";

        const char* mqtt_server = "10.10.10.10";
        const char* mqtt_user = "mqtt_user";
        const char* mqtt_pass = "mqtt_pass";

        String clientName; // MQTT client name
        char message_buff[100];

         void dump(decode_results *results) {
            const int count = results->rawlen;
              Serial.println(c);
              c++;
              Serial.println("For IR Remote ");
              for (int i = 1; i < count; i++) {

              if ((i % 2) == 1) {
                Serial.print("+");
                Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
            uint16_t  raw_ir_code[count] = results->rawbuf[i]*USECPERTICK;
                client.publish( "esp8266/02/sender", raw_ir_code);

After doing the changes proposed, I still get an error in compiling:

> no matching function for call to 'PubSubClient::publish(const char [18], uint16_t [(int)count])'

body:
First create a topic and include the ESP8266 ID. Do **not** make it part of the published value.

Second publish the raw data as-is, `uint16_t raw_ir_code[RAW_IR_CODE_MAX]`. The alternative is to convert to string (characters). But if the subscriber has the same architecture (interpretation of data), there is no need to convert it to string and back. Simply publish the raw data as it is.

You will need to cast the `raw_ir_code` vector to the appropriate type for the MQTT publish call.

Cheers!


message:
Customize FTDI driver for custom PID and VID

I have changed PID and VID of my FTDI board for  arduino program because i wanted to rename the com port name.
The ic is  FT232R a USB to serial UART interface IC. I have store new vid and pid to EEPROM.
Now It is showing in unknown devices. I am not able to update driver of it.
I have followed this article http://forum.arduino.cc/index.php?topic=6929.0.

Can anyone tell how to make cutmoize driver for it.
Any suggestions will be very helpful.

body:
**On Windows**

You can refer to FTDI's documentation [here][1] for details on how to create your own custom device driver. The FTDI website has a lot of resources for this, however they seem to be a little outdated. Microsoft details how drivers work in it's [Hardware Dev Center][2].

**On Linux**

On Linux it may be as easy as registering the device with `modprobe`. For example, for a device with a VID of 0102 and a PID of 1234, execute the following from the shell:

    modprobe ftdi_sio
    echo "0102 1234" | sudo tee /sys/module/ftdi_sio/drivers/usb-serial\:ftdi_sio/new_id > /dev/null

  [1]: https://www.ftdichip.com/Support/Documents/TechnicalNotes/TN_149_Create_a_Custom_Driver_Executable.pdf
  [2]: https://docs.microsoft.com/en-us/windows-hardware/drivers/install/device-installation-files


body:
You can do it, but you cannot change the PID and VID without a new certificate.

Did you changed the name with the FT-Prog Tool (MProg is outdated)?
You can download the last version from here:
https://www.ftdichip.com/Support/Utilities.htm#FT_PROG

You can set everything on your FTDI chip, even change the PID and VID. But at this point, you will not be able to use the standard FTDI driver anymore as you need to sign it with a new certificate (it is about 400$/year).

What you can do is leave the PID and VID and just give another name. So you will be able to use the default driver and you will see your custom name in the device manager.

Of course, in the list you just see "USB Serial Port (COM X)". But in the description of the device (Serial port), you will find this string:
`FTDIBUS\VID_0403+PID_6011+YOURCUSTOMNAME&1\0000`

If you create an application, you can just check for this, to see if it is your module. If you want more, you have to develop and release your own driver. But you can't do it anymore without a certificate, or without start Windows in unprotected mode.


message:
Accessing configuration registers of OV7670 cam on i2c

I am a new user of Aurdino and want to interface OV7670 camera with aurdino uno which uses i2c mode of communication.I want to check the configuration of the device control registers and set them as per requirement. In this case, OV7670 is my slave device.

     How can I access a particular register inside the slave device?(The parameters for commands like wire.begin() etc., include slave address but not the address of the registers inside a slave device.)

body:
Take a look at the datasheet - that will show you the correct waveforms / transactions for this. However, something like this should work (assuming 8-bit addresses and registers)

    // reading

    Wire.beginTransmission(address);
    Wire.write(reg); // set address to read from our requested register
    Wire.endTransmission(false); // repeated start
    Wire.requestFrom(address,(unsigned char)1);  // just a single byte
    if(Wire.endTransmission()!=0){
     // put error code here
    }
    readValue = Wire.read();

    // writing

    Wire.beginTransmission(address);
    Wire.write(reg);
    Wire.write(value);
    if(Wire.endTransmission()!=0){
        // put error code here
    }


body:
To communicate with the OV7670:

 - SIOC => SCL
(pulled up to 3.3V)
 - SIOD => SDA
(pulled up to 3.3V)
 - RESET => 3.3V
 - PWDN => GND
 - XCLK => Clock signal is necessary (at least 10 Mhz)
 - Vcc => 3.3V
 - GND => GND

The XCLK needs at least 10 MHz according to the datasheet, but from other accounts, it seems that's not a hard limit. You can get a 4 MHz clock from the Uno using its `timer0`; check out this [post][1] on how to do it. After this, you can write a small sketch along the lines of:

    Wire.begin();
    Wire.beginTransmission(0x21);
    Wire.write(0x12);  // software reset
    Wire.write(0x80);
    Wire.endTransmission();
    delay(500); // wait for reset to complete

    Wire.beginTransmission(0x21);
    Wire.write(0x01);  // u now read from reg 0x01
    Wire.endTransmission();
    Wire.requestFrom(0x21, 1);
    while (Wire.available() == 0);  //block till u get something
    while (Wire.available())
      Serial.println(Wire.read(), HEX);

You can place everything in `setup()` after including the `Wire` library and setting up the XCLK clock signal. If all goes well, `80` should be printed in the serial monitor and this will confirm that you're now communicating over the SCCB with the camera.

I should warn you that while others have used the Uno to grab images from the OV7670, the process is moderately complex, especially for a beginner, and it's not what the Uno is intended for; all you'll be able to do is grab frames and pass them on to some TFT screen or your PC and even then you'll get at most 5 fps, I think, with QVGA or QCIF output. You'd be better off with some ARM dev board, one running Linux perhaps. Good luck.

  [1]: http://forum.arduino.cc/index.php?PHPSESSID=pt8le15alfme9abbohpu1grue2&topic=128269.msg964725#msg964725


message:
Adruino Yun's Linux environment not working

I was recently given an Arduino Yun board from my university. I am able to upload sketch to the board, and it seems to function properly. However, I am unable to see the Linux booting up. When I want to reset the WLAN, ressing the WLAN RST button does nothing at all, the WLAN LED doesn't even blink or light up. Pressing the YUN RST button also does nothing.

So I did some Googling and found out that I could upload the YunSerialTerminal to the Yun, so I did that. And when I am trying to monitor the Linux boot up from the serial monitor. Nothing is shown. I press the TUN RST button as taught by the Arduino website while monitoring the Serial Monitor, nothing shows. However, the RX button does blink whenever I press enter.

Can anybody help me?

body:
You might need to re-flash the operating system. Unfortunately it's not a trivial task.

I had to do something similar with a Dragino shield (like a Yun on a shield) that uses the same OS and core chip. Instructions were scarce and hard to follow, plus I run Linux, so there's even less instructions. I worked it out, though, and wrote a tutorial [here](https://hackingmajenkoblog.wordpress.com/2016/02/24/fixing-the-dragino-yun-board/).

While that is for Linux and the Dragino shield I am sure the basic principles are the same for the Yun - just make sure you get the right image file for your Yun (don't get the Dragino one I link to).

The main thing is to gain access to the boot manager (dr-boot, or whatever the Yun has), which means setting up a wired (ethernet) network and messing with UDP sockets (using `nc` in Linux - no idea what you can use in Windows).

I'm sure you can find a tutorial for fixing the Yun from Windows (or whatever OS you use) to help you get into the boot manager and upload a new OS image.


message:
How to determine Flash size?

I need to determine the flash size of my ESP8266 on my NodeMCU module in order to flash the AT firmware onto the board. Apparently different boards come with differently-sized flash memories. Can anyone tell me the easiest way to find the flash size?

body: The easiest way (windows at least) is to use Espressif's [flash download tool](https://espressif.com/en/support/download/other-tools) - don't select anything to flash to the device, select the appropriate com port, click start, and the details of the device will appear in the Detected Info window


body: Arduino's ESP8266 support includes an example sketch called **CheckFlashConfig**. This probes the board, and prints the flash memory size.


message:
Powering 3 servo motors and Arduino Uno with one 9 V battery

I wish to power an Arduino Uno board AND 3 servo motors using a single 9 V battery.

I have connected the positive terminal of the 9 V battery to the VIN pin. The negative terminal of the battery is connected to the GND pin immediately following. This, I believe, powers the Arduino Uno board.

Next, I have connected the power wires of all 3 servo motors to the 5 V pin on the Arduino board ( using jumper wires and a  breadboard). Similarly, all the servo ground wires have been connected to the second GND pin in the 'POWER' set of pins on the Arduino Uno board. And finally, the 3 signal wires from the servos have been connected to the three PWM pins on the 'DIGITAL' row, exactly pins 9, 10 and 11.

THE SERVOS ARE NOT OPERATED SIMULTANEOUSLY, THEY ARE BEING OPERATED ONE-BY-ONE (but the load is still attached to each of them, a couple of grams is all).

Since the servo motors operate between 4.8 V - 6 V, and I don't have any spare AA batteries to approximate a 6 V battery, I thought this could solve the problem.

My question is, does this pose any problems for the board or devices, does this draw a higher current? Will it damage the Arduino Uno board or the servo motors or any of the individual pins?

 Please let me know soon, thank you very much.

body:
I don't think anything should get damaged; the regulator is rated for 1A, and even beefy servos don't draw more than 200mA when moving against heavy load. The problem is that your battery won't last long. Even the heavy-duty Li primary 9V batteries are under 1000mAh, and the actual capacity is heavily dependent on the discharge rate.

Why can't you use a rechargeable Li-ion pack with an appropriate step-up or step-down converter?


message:
PID control arduino

I am hooking up an accelerometer to an arduino uno and running it through this pid controller. However the output isnt going to my setpoint. When i move the accelerometer back and forth the data goes to 255 or 0. Any ideas?

Datasheet for accelerometer:
https://www.sparkfun.com/datasheets/Components/SMD/adxl335.pdf

I get 336 for the x direction, which is the only direction i'm using, when its set flat on the table, which is my setpoint/desired output.

Note: Is the output the value away from the setpoint or the actual acceleration it calculates through the controller?

    #include <PID_v1.h>

    #define PIN_INPUT A0

    //Define Variables we'll be connecting to
    double Setpoint, Input, Output;

    //Define the aggressive and conservative Tuning Parameters
    double aggKp=4, aggKi=0.2, aggKd=1;
    double consKp=1, consKi=0.05, consKd=0.25;

    //Specify the links and initial tuning parameters
    PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

    void setup()
    {
      //initialize the variables we're linked to
    Serial.begin(9600); //Start a serial session
    int  xdata = analogRead(PIN_INPUT);
    Input = map(xdata, 0, 1024, 0, 255); //Change read scale to analog out scale
    int setPoint = 336;
    Setpoint = map(setPoint, 0, 1024, 0, 255); //Change read scale to analog out
    //turn the PID on
    myPID.SetMode(AUTOMATIC);
    }

    void loop()
    {
    int xdata = analogRead(PIN_INPUT);
    Input = map(xdata, 0, 1024, 0, 255); //Change read scale to analog out scale

    double gap = abs(Setpoint-Input); //distance away from setpoint
    if (gap < 10)
    {  //we're close to setpoint, use conservative tuning parameters
     myPID.SetTunings(consKp, consKi, consKd);
    }
    else
    {
      //we're far from setpoint, use aggressive tuning parameters
      myPID.SetTunings(aggKp, aggKi, aggKd);
    }

    myPID.Compute();

    Serial.print("Setpoint = ");
    Serial.print(Setpoint);
    Serial.print(" Input = ");
    Serial.print(Input);
    Serial.print(" Output = ");
    Serial.print(Output);
    Serial.print("\n");
    // analogWrite(PIN_OUTPUT, Output);
    }
OUTPUT:

    Setpoint = 83.00 Input = 87.00 Output = 0.00
    Setpoint = 83.00 Input = 81.00 Output = 0.00
    Setpoint = 83.00 Input = 64.00 Output = 255.00
    Setpoint = 83.00 Input = 64.00 Output = 255.00
    Setpoint = 83.00 Input = 68.00 Output = 255.00
    Setpoint = 83.00 Input = 79.00 Output = 0.00
    Setpoint = 83.00 Input = 91.00 Output = 0.00
    Setpoint = 83.00 Input = 96.00 Output = 0.00
    Setpoint = 83.00 Input = 99.00 Output = 0.00
    Setpoint = 83.00 Input = 88.00 Output = 0.00
    Setpoint = 83.00 Input = 68.00 Output = 0.00
    Setpoint = 83.00 Input = 58.00 Output = 255.00
    Setpoint = 83.00 Input = 64.00 Output = 255.00
    Setpoint = 83.00 Input = 78.00 Output = 255.00
    Setpoint = 83.00 Input = 95.00 Output = 0.00
    Setpoint = 83.00 Input = 97.00 Output = 0.00
    Setpoint = 83.00 Input = 95.00 Output = 0.00

body:
Ensure that your period for the PID execution routine is reasonable for your system.  I generally like to execute my PID loops at 5 to 20 times the system impulse response.  For instance, with a motor, I will apply 100% power from a standstill and measure the time it takes to get up to 90% of final value.  I will then multiply that time by 0.1 and start there.  If it takes 1s, then I will start my PID loop executing every 0.1s.  Sometimes I adjust this up or down, depending on system requirements, but this is not a bad starting point.

If your PID loop is executing too fast, then it will respond too quickly to actually have a real-world effect on the system.  The output will tend to oscillate.  Motors vibrate and make more noise.... different systems respond differently, but you see the point.

1. Start at `kp = 0`,` ki = 0`, `kd = 0`
2. Increase `kp` until you get a reasonable response.  Don't expect your error to go to 0.  As long as you aren't oscillating, that should be good.
3. Very slowly increase `ki`until you are happy.
4. You should probably keep `kd` to 0.  It is for advanced usage and PI loops will meet the vast majority of application requirements.

This is a very crude guide.  There are better on google, but this should get you started.  PID loops are fun, especially with motors.  Enjoy!


message:
Sketch not running as expected

I wrote this sketch along with an HC - SR 04 Ultrasonic transducer and a DC motor. Whenever the HC-SR 04 reads any distance less than 15 cm, the motor stops, otherwise it keeps running.

The problem is whenever I upload the sketch, the motor runs for a short while and stops. Then when I open my serial monitor, the motor runs until an object crosses the 15 cm threshold and stops right after the limit is crossed. But when I again put the object outside of the 15 cm range, the motor should start running again, but it doesn't.

I am using a [this] motor driver and a simple DC motor(12V).
[this]: http://robokits.co.in/motor-drives/dual-dc-motor-driver-20a
Here's the code-

    int trigPin1 = A0;
    int echoPin1 = A1;
    int distance1 = 0;
    int E1 = 10;
    int brake1 = 7;

    void setup() {
      pinMode(trigPin1, OUTPUT);
      pinMode(echoPin1, INPUT);
      pinMode(brake1, OUTPUT);
      pinMode (E1, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      analogWrite(E1, 153);
      distance1 = getDistance(trigPin1, echoPin1);
      printDistance(1, distance1);
      delay(250);
      if(distance1 <=15){
        digitalWrite(brake1, HIGH);
      }
      else{
        analogWrite(E1, 153);
      }

    }

    int getDistance (int initPin, int echoPin) {
      digitalWrite(initPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(initPin, LOW);
      long pulseTime = pulseIn(echoPin, HIGH);
      int distance = pulseTime / 58.2;
      return distance;
    }

    void printDistance(int id, int dist) {

      Serial.print(id);
      if (dist >= 120 || dist <= 0 ) {
      Serial.println(" Out of range");
      }
      else{
       Serial.print("\t");
       Serial.print(dist);
       Serial.println(" cm");
    }
    }

What mistake am I doing? Moreover I am currently running it with one motor, I'll add another later on along with more sensors, so the motors are controlled by the left or right sensor. How do I make my code work with them?

Thanks...

body:
It was too damn simple...

I just had to add a line inside the else block in the loop function.

    digitalWrite(brake1, LOW);

This was happening because the first time the threshold limit was crossed the `brake1` pin was left `HIGH` and was never set to `LOW` again, which caused a permanent brake in the motor.

I'm too damn stupid. But I still don't have any idea how will I use this code with multiple sensors and motors.


message:
Porting ATMega8 AVR based program to Intel Curie Processor

I'm currently trying to port a program called 'ArduinoUSBLinker' to work on my Arduino 101 (which has an Intel Curie CPU instead of the standard ATMega CPU).

The program is used to flash ESCs without the need of additional hardware.
[Arduino USB Linker][1]

Unfortunately the code is mainly based on the ATMega's built in AVR timers,
which uses several different predefined variables such as `TCCR0,TCCR1,TCTN2…`

These are not available (or are they?) in the Curie Module. Since the Arduino 101 has timer functionality, I was wondering if there is a way to translate those into the Curie Timer library.

  [1]: https://github.com/c---/ArduinoUSBLinker

body:
Those variables are the addresses of physical registers on the AVR that manipulate its timer/counters. Most other processors will have equivalent, but not likely identical, hardware. You'll need to port functionality, not the code.

You'll need to reverse-engineer (worst-case) the code you're trying to port (assuming you aren't intimately familiar with it, e.g., you designed it), develop a spec for it (at least in your head), and write to that spec for the Curie.

If the overall job is not (too heavily) processor-specific, you may be able to write it to be portable by writing the job-specific code in, e.g., in C, and call well-defined functions (in C or assembler) for the CPU-specific ones, that could easily be replicated on another processor.


message:
GSM GPRS for sending an sms

I want to know if it is possible to send an SMS from a SIM900 using Arduinos to another SIM900.

**Problem**: When the gsm is connected to the network, it does not send an sms; my airtime balance remains the same.

Here is the code I used:

    #include <SoftwareSerial.h>
    SoftwareSerial SIM900 (9,10);

    void setup()
    {
       serial.begin(9600);
       SIM900.begin(9600);
       delay(5000);
    }

    void loop()
    {
       sendSMS();

       while(SIM900.available()!=0)
         {
            Serial.println(SIM900.read());
         }
    }

    void sendSMS()
    {
        SIM900.println("AT+CMGF=1\r");
        delay(100);
        SIM900.println("AT+CMGS=\"+27769384488"\r");
        delay(100);
        SIM900.println("Hello");
        delay(100);
        SIM900.println((char)26);
        delay(100);
        SIM900.println();
        delay(5000);

    }

body:
Yes, it is possible.

Your code doesn't show any sign of board powering on and initialization.

SIM900 has some LED that show status - make sure you are connected to GSM network.

Please check this tutorial: https://www.youtube.com/watch?v=RUGV_64lQX8


body:
I had worked on GSM long back ago and sometimes it becomes very difficult to debug the problem. However u need to just check whether the AT commands are being sent properly to the GSM module. I had tried using Software Serial but it did not work for me but when I switched to the usual Serial port it worked like a charm. Few things that you need to check are:

 1. Check the baud rate of GSM module. Does it match with the baud rate of Software Serial.
 2. Do a if-else check to see whether the commands are actually being sent to the GSM module. The println() returns the number of bytes written so you can do like this in your sendSMS() function.

>`
int a; //To store the number of bytes written
a=SIM900.println("AT command to be sent");
if(a)
{
Serial.println("Command sent");
}
else
{
Serial.println("Command not sent");
}`

Now upload the code and open the serial monitor to see whether the command is actually being sent to the GSM module or not.

 3. You also need to check whether the format of your AT command is correct. Because you need to send **\n(newline) and\r(carriage return)** at the end of every AT command to ensure proper operation. For this you need to read the response sent back by the GSM module after every command. This can be done by reading the Software serial port and the printing the response onto the Serial monitor.
 4. You also need to check whether your GSM module has detected the SIM card. Usually this is indicated by an onboard LED that blinks after every **3 seconds**.

I think your code is pretty much correct but try to ensure that everything is setup properly as I said.
Here is my code but I used Serial port instead:

>`
void setup()
{
  Serial.begin(9600);
  delay(10000);  \\For initialization purpose
}
void sendSMS()
{
  Serial.println("AT+CMGF=1");
  delay(5000);
  Serial.println("AT+CMGS=\"Phone number with international code\"");
  delay(5000);
  Serial.print("Hello");
  delay(5000);
  Serial.println((char)26);
  delay(5000);
}
void loop()
{
  sendSMS();
  do
  {
  }while(1);
}`

This code will send the SMS once so you need to reset the board for sending another SMS or you can remove the do while loop for continuous operation.You can adjust the delay accordingly.


message:
How to upload one program into several Arduinos at once?

I am trying to upload a single program to a number of Arduinos one by one. But it is time consuming. So I would like to know if there is any way to upload the code at once to multiple Arduinos.

I have tried as follows:

3 Arduino with all the Rx, Reset, Vcc, Gnd line connected to each other. Only pin left is Tx line. So I just connect the Tx line of one arduino and program it and so on.

Is there any other way?

body:
Are you programming them for the first time or doing a update?

If is the first programming, I cant see another way.

Otherwise, If is a update and your Arduino have a Wifi module you could try something like an update on the air, where you put your new firmware in a server for example and all devices updates yourself automatically or by a command.

Google for Arduino OTA (on the air) you will get a lot of source code and examples of doing that.


body:
Arduino uses a microcontroller from Atmel and uses a programming tool that is designed for development use and not for production programming.

What you are looking for are tools that are called "production programming tools". Atmel has a nice documentation which describes their different programming solutions: [link][1].

  [1]: http://www.atmel.com/Images/Atmel-42215-Production-Programming-of-Atmel-Microcontroller_AP-Note_AT06015.pdf


message:
Accepting strings and integers via UART

My intention is to write a code that asks a user to enter the name and then the age. The code should then simply display the persons name and age. To do that, I have written a simple code. I find it difficult to get it to work.

 char temp = 0;
 char ArrayName [50];
 int positionArray = 0;
 int age =0;

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

 void loop() {

  positionArray = 0;
  Serial.println ("What is your name?");

  do {

   while (Serial.available()==0);
   temp = Serial.read ();
   ArrayName [positionArray++] = temp;
  } while (temp != '\r');

  ArrayName [--positionArray] = '\0';

  Serial.print ("Your Name is: ");
  Serial.println (ArrayName);

  // clear the UART Buffer
  while (Serial.available()==1){
   temp = Serial.read();
  }

  Serial.println ("What is your age?");
  while (Serial.available()==0);
  temp = Serial.read ();
  age = temp;

  Serial.print ("You are ");
  Serial.print (age);
  Serial.println (" Years old.");

  while (Serial.available()==1){
   temp = Serial.read();
   delay (10);
  }

 }

The error I receive is that the program already outputs age without me even typing it.  Would it be possible to know the error?
I use both NL and CR to send in characters to Arduino and the Arduino IDEs default UART terminal.

EDIT:

Listening to advice gotton from answers I got the code to work but in a very weird way. My new code works! but it proves the clearing of buffer **cannot be done** by just reading it. This is in contrast to Arduino documents. My new code is as follows.

 char temp = 0;
 char ArrayName [50];
 int positionArray = 0;
 int age =0;

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

 void loop() {

  positionArray = 0;
  Serial.println ("What is your name?");

  do {

   while (Serial.available()==0);
   temp = Serial.read ();
   ArrayName [positionArray++] = temp;
  } while (temp != '\r');

  ArrayName [--positionArray] = '\0';

  Serial.print ("Your Name is: ");
  Serial.println (ArrayName);

  // clear the UART Buffer **WHY IS THIS CODE NOT EFFECTIVE?**
  while (Serial.available() >= 1){
   temp = Serial.read(); // performing dummy reads untill buffer empty.
  }

  temp = Serial.read();
  delay (1000);
  temp = Serial.read();
  temp = Serial.read();
  temp = Serial.read();

  Serial.println ("What is your age?");
  while (Serial.available()==0);
  temp = Serial.read ();
  temp = temp - 48;
  age = temp*10;
  delay (1000); // providing the user a day to enter next digit of age

  if (Serial.available()){
   temp =  Serial.read ();
   temp = temp - 48;
   age = (int) temp + age; //whatever that is added have to be of same type. Else they need to be cased to same type.
  }

  Serial.print ("You are ");
  Serial.print (age);
  Serial.println (" Years old.");

  while (Serial.available() >=1 ){
   temp = Serial.read();
   delay (10);
  }

 }

body:
As we don't know what you are using as a terminal program we can't comment specifically on your choice of EOL characters.

It is likely you are receiving everything in [ASCII code][1].  That is, when you type the number 1 you are actually getting the ASCII equivalent (0x31) from your terminal.

This is fine when you are working with character strings.  But when you want to work with numbers that are to be used in equations you need to 1) make sure that the user is only entering a number (check to make sure the values are from 0x30 to 0x39) and 2) subtract the ASCII value for '0' from the value you received from the terminal.  That is, subtract 0x30.

It should now be obvious that you can only enter 1 digit at a time when using a terminal.  That you will have to reconstruct the number as the user types each digit.  For example the number 13 is a 1 and a 3 and you will have to multiply the 1 by 10 then add it to the 3.

Since this is such a common conversion, there are Arduino libraries that do this for you.  Consider using [ParseInt][2] for this purpose.

Added later...

In the modified code, consider the possibility the terminal program is sending both a Carriage Return (aka: CR, 0x0D, \r) and Line Feed (aka: LF, 0x0A, \n) each time the Enter key is pressed.  And that the code is only waiting for the CR.

The delays are necessary as UART communication, as most communications, takes a finite amount of time.  And additional characters, if any, and even if autonomously sent, will take a finite amount of time to arrive.

Consider "looking" for the LF character after finding for the CR character and removing the added delays.

  [1]: https://en.wikipedia.org/wiki/ASCII
  [2]: https://www.arduino.cc/en/Reference/ParseInt


message:
How to handle multiple simultaneous Arduino development environments?

I am developing for several different target microcontrollers (on OS X 10.11), which requires some unique combinations of (Arduino) IDE version, library versions, USB drivers, support software, etc.

What are the pros and cons of using separate logged-in users for each environment as opposed to using Virtual Machines? Are there other methods commonly in use to separate environments, and also keep the environments archived for any legacy needs?

Update: I also have a desire to keep these environments as standard as possible: installing released components (e.g., IDE, drivers) and customizing IDE app settings, but trying to avoid source-level forks. This is for my own sanity, and to give best chance of replicating the environment in the future.

body:
I'm yet to see evidence that there is a sound or comprehensive way to do this, so would be pleased to read better suggestions.  As for why you would want to, there are a number of board support plugins/extensions that are moderately functional on some recent Arduino versions, but partially or entirely incompatible with others.

You can achieve a very limited partial version segregation by creating a new sketchbook folder for each version, which would host your libraries and hardware folders.

To get the IDE to pick this up, you could have a custom preferences file (rather than `preferences.txt`) with that sketchbook location set.  You can specify the file to use on the command line, for example:

    /opt/arduino-1.6.8/arduino --preferences-file ~/.arduino15/alternate.txt

However, there is still quite a bit related to extra board support and similar stored in the settings folder, and at present that is hard coded to the same "Arduino15" or ".arduino15" path for all recent versions.

This hard-coding of the settings folder is implemented in the version of `Platform.java` applicable to the operating system you are running under, so it is not clear how you could change this except at the source level, by modifying the jar, or by playing file-system level tricks with the operating system (process-unique mounts, etc).


body:
I ended up running `arduino-buider`, available in Arduino IDE 1.6.6 and newer.

When laying out your project, put a `libraries/` and `hardware/` folder along side your sketch directory, like so:

    YourHipProject/
        Makefile
        hardware/
            Vendor/arch/{boards.txt,platform.txt}
        libraries/
            SomethingUseful/
            NoIdeaHowThisWorks/
        ProjectSketch/
            ProjectSketch.ino
            othersource.cpp

The `hardware/` directory is only needed if you need support for 3rd party boards. Then, in the `Makefile`:

 ARDUINO_DIR ?= /opt/arduino-1.6.13 # need to set this for your environment

 .PHONY: ProjectSketch

 ProjectSketch:
  arduino-builder -compile -verbose \
   -hardware $(ARDUINO_DIR)/hardware \
   -tools $(ARDUINO_DIR)/tools-builder \
   -tools $(ARDUINO_DIR)/hardware/tools/avr \
   -built-in-libraries $(ARDUINO_DIR)/libraries \
   -hardware ./hardware \
   -libraries ./libraries \
   -fqbn=Vendor:arch:board \
   ./ProjectSketch/ProjectSketch.ino

`ARDUINO_DIR` needs to point to where your Arduino is installed, be sure to set `-fqbn=` correctly too.

Running `make` should compile the firmware from `ProjectSketch/` with the accompanying libraries and hardware definitions. Also, with verbose compile output enabled, the Arduino IDE will show you how it runs `arduino-builder`.


message:
Is it possible to run 2 functions, that communicate with 2 different serial devices, in parallel using FreeRtos library?

This might seem like a very broad question but that's what i want it to be for multiple ways of implementation.

I've an Arduino UNO communicating with 2 Serial devices interfaced using SoftwareSerial flawlessly. I've used [SS_Object].listen() function to switch between the two. Right now, the entire code works sequentially meaning that, once it's work with the 1st Serial device is done, only then it will switch to the 2nd Serial device and work with it. Can i communicate with the 2 in parallel (Multitasking) using FreeRtos? I've heard that the scheduler switches between tasks when it encounters a delay. So may be a small useless delay is required, only for the scheduler, to switch between the two. May be! or May be things will be better if i use more advanced Arduino like Mega or Due.

Thanks for taking your time to read this. Please answer the question the way you've understood it as i am sure different people with different experiences will interpret this differently.

Thanks in advance!

body:
It is unlikely that FreeRTOS will allow you to do that. SoftwareSerial uses busy loops with interrupts disabled, which means it cannot be interrupted or preempted by the RTOS (or by anything for that matter).

If you want two serial connections in parallel, at least one of them should be done in hardware.


message:
wifi failled connection with yun and after upgrading openwrt

I recently bought an arduino yun. When trying to connect to the router following the procedure in [https://www.arduino.cc/en/Guide/ArduinoYun#toc14][1]. After the Configure & Restart, the Arduino network shut down after a few moments but it wasn´t linked to my router.

After reading a bit about it in the internet, i upgraded it following [https://www.arduino.cc/en/Tutorial/YunSysupgrade][2]. As i found that the firmware version 1.5.3 was from 2014 [https://github.com/arduino/openwrt-yun/blob/master/ChangeLog][3], and as Reflashing the OpenWrt-Yun image on the Yún would void warranty, i proceeded by [http://nootrix.com/software/upgrade-arduino-yun-openwrt/][4]. Everything occured as detailled there.

However now, when i turn on the yún, none network appear and the WLAN LED doesn't blink.

Thanks

  [1]: https://www.arduino.cc/en/Guide/ArduinoYun#toc14
  [2]: https://www.arduino.cc/en/Tutorial/YunSysupgrade
  [3]: https://github.com/arduino/openwrt-yun/blob/master/ChangeLog
  [4]: http://nootrix.com/software/upgrade-arduino-yun-openwrt/

body:
Find out if the Linux system is running. Maybe you mistyped your WiFi password.
Try the Following:

 - connect via Ethernet check your router to see if the Yun request an IP via DHCP
 - If unsuccessful connect via USB and install this [sketch][1] to see if you get a command prompt maybe your network settings are messed up

Still no success?

 - Press the WiFi reset button for at least 30 seconds to do a reset to
   factory defaults.

  [1]: https://www.arduino.cc/en/Tutorial/YunSerialTerminal


message:
Printing Time to Serial Port

I am reading sensory data that comes from the digital inputs(two DHT11 Humidity sensors using adafruit library.) and I would like to add a hh:mm:ss real time counts next to them. I try to use the time.h library but could not understand how to worked it in that way.

My code is;

    #include "DHT.h"

    #define DHT1PIN 4
    #define DHT2PIN 7

    #define DHT1TYPE DHT11
    #define DHT2TYPE DHT11

    DHT dht1(DHT1PIN, DHT1TYPE);
    DHT dht2(DHT2PIN, DHT2TYPE);

    void setup() {
      Serial.begin(9600);
      Serial.println("Humidity sensors DHT11 tests!");

      dht1.begin();
      dht2.begin();
    }

    void loop() {

      delay(2000);

      float h1 = dht1.readHumidity();
      float t1 = dht1.readTemperature();
      float h2 = dht2.readHumidity();
      float t2 = dht2.readTemperature();

      if (isnan(t1) || isnan(h1)) {
        Serial.println("Failed to read from DHT #1");
      } else {
        Serial.print(h1); Serial.print(" \t");
      }

      if (isnan(t2) || isnan(h2)) {
        Serial.println("Failed to read from DHT #2");
      } else {
        Serial.print(h2);
        Serial.print(" \t");
      }
      Serial.println();
    }

and my serial port out is;
[![enter image description here][1]][1]

and I want it to be like that;
[![enter image description here][2]][2]

Any help will appreciated.

  [1]: https://i.stack.imgur.com/vnCCn.png
  [2]: https://i.stack.imgur.com/lstbu.png

body:
I solved the problem by using millis() function. And now I ca get results like these;
[![enter image description here][1]][1]

My code is;

    #include <Sensirion.h>
    #include "DHT.h"
    unsigned long time;

    #define DHT1PIN 4
    #define DHT2PIN 7

    #define DHT1TYPE DHT11
    #define DHT2TYPE DHT11

    DHT dht1(DHT1PIN, DHT1TYPE);
    DHT dht2(DHT2PIN, DHT2TYPE);

    const uint8_t dataPin =  9;              // SHT serial data
    const uint8_t sclkPin =  8;              // SHT serial clock
    const uint8_t ledPin  = 13;              // Arduino built-in LED
    const uint32_t TRHSTEP   = 1000UL;       // Sensor query period
    const uint32_t BLINKSTEP =  250UL;       // LED blink period

    Sensirion sht = Sensirion(dataPin, sclkPin);

    uint16_t rawData;
    float temperature;
    float humidity;
    float dewpoint;

    byte ledState = 0;
    byte measActive = false;
    byte measType = TEMP;

    unsigned long trhMillis = 0;             // Time interval tracking
    unsigned long blinkMillis = 0;

    void setup() {
      dht1.begin();
      dht2.begin();
      Serial.begin(9600);
      Serial.println("In.(%) In.Tem(*C) Out.(%) Time");
      pinMode(ledPin, OUTPUT);
      delay(15);                           // Wait >= 11 ms before first cmd
      // Demonstrate blocking calls
      sht.measTemp(&rawData);              // sht.meas(TEMP, &rawData, BLOCK)
      temperature = sht.calcTemp(rawData);
      sht.measHumi(&rawData);              // sht.meas(HUMI, &rawData, BLOCK)
      humidity = sht.calcHumi(rawData, temperature);
      dewpoint = sht.calcDewpoint(humidity, temperature);
      logData();
    }

    void loop() {

      unsigned long curMillis = millis();          // Get current time

      // Rapidly blink LED.  Blocking calls take too long to allow this.
      if (curMillis - blinkMillis >= BLINKSTEP) {  // Time to toggle the LED state?
        ledState ^= 1;
        digitalWrite(ledPin, ledState);
        blinkMillis = curMillis;
      }

      // Demonstrate non-blocking calls
      if (curMillis - trhMillis >= TRHSTEP) {      // Time for new measurements?
        measActive = true;
        measType = TEMP;
        sht.meas(TEMP, &rawData, NONBLOCK);      // Start temp measurement
        trhMillis = curMillis;
      }
      if (measActive && sht.measRdy()) {           // Note: no error checking
        if (measType == TEMP) {                  // Process temp or humi?
          measType = HUMI;
          temperature = sht.calcTemp(rawData); // Convert raw sensor data
          sht.meas(HUMI, &rawData, NONBLOCK);  // Start humidity measurement

          float h2 = dht2.readHumidity();
          float t2 = dht2.readTemperature();

          Serial.print(humidity);
          Serial.print(" \t");
          Serial.print(temperature);
          Serial.print(" \t");

          if (isnan(t2) || isnan(h2)) {
            Serial.println("Failed to read from DHT #1");
          } else {
            Serial.print(h2);
            Serial.print(" \t");

            //time = millis();
            //prints time since program started
            Serial.println(curMillis);
          }
          Serial.println();
        }
        else {
          measActive = false;
          humidity = sht.calcHumi(rawData, temperature); // Convert raw sensor data
          dewpoint = sht.calcDewpoint(humidity, temperature);
          logData();
        }
      }
    }

    void logData() {
    }

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

But the difference is that I am using SHT75 instead of another DHT11 so I am simultaneously acquiring data from the both of them. Thanks for everyone!


message:
Router with arduino

Is it possible to send and receive data from a normal router using arduino? I need to create a little device that uses a router to communicate with a remote. It's a close circuit.

body:
If you have a network interface (wired or wireless), yes, of course it is.

Look into the ESP8266, and ESP-12E-based boards such as the Adafruit Huzzah; they can be programmed in an Arduino environment, and have built-in wifi.


message:
Arduino original motor shield can not supply enough torque to the motor?

I am using original Arduino motor shield L298P with Arduino uno.

I disassembled an electric screw driver which came out with a 4.8 v battery pack and a 4.8v specified DC motor.

I connected battery pack to the Vin and Ground pins of the motor shield, and connected the DC motor to A channel of the shield.

The thing is when I run a test code with PWM 255, the torque of the motor is way too low compared to connecting the motor directly to the battery pack. I also changed the batteries to a common 1.2v rechargeable 4 batteries connected in parallel. The result is the same.

What might be going wrong?

I also paste the code I am using below. Thanks in advance.

    const int motorPin = 3;
    int Speed;
    int flag;
    void setup()
    {
 pinMode(motorPin, OUTPUT); //Set pin 3 as an OUTPUT
 Serial.begin(9600); //Init serial communication
    //Print a message:
 Serial.println("Give a number from 50 to 255."); //Why minimun value 50?     Because with values below 50 the motor doesn't spin ;)
 Serial.println(""); //Blank line
    }

    void loop()
    {
 //Check if incoming data is available:
    if (Serial.available() > 0)
    {
      // If it is, we'll use parseInt() to pull out only numbers:
      Speed = Serial.parseInt();
      flag=0;
    }

 //Valid range is from 50 to 255
 if (Speed>=50 && Speed<=255){
  //Send PWM value with analogWrite to Arduino pin 3 and print a message to serial monitor
  analogWrite(motorPin, Speed);
     //Print message only once
     if (flag==0){
      //Print PWM value
      Serial.print("Motor spinning with ");
      Serial.print(Speed);
      Serial.println(" PWM");
      flag=1;
     }
 }

 delay(1000);
    }

body:
According to the [motor shield page](https://www.arduino.cc/en/Main/ArduinoMotorShieldR3):

> To avoid possible damage to the Arduino board on which the shield is mounted, we reccomend using an external power supply that provides a voltage between 7 and 12V. If your motor require more than 9V we recommend that you separate the power lines of the shield and the Arduino board on which the shield is mounted. This is possible by cutting the "Vin Connect" jumper placed on the back side of the shield. The absolute limit for the Vin at the screw terminals is 18V.

According to you:

> I disassembled an electric screw driver which came out with a 4.8 v battery pack and a 4.8v specified DC motor.
>
> I connected battery pack to the Vin and Ground pins of the motor shield, and connected the DC motor to A channel of the shield.

That's a lot less than 7V.

---

Also, from the motor shield page:

> Max current 2A per channel or 4A max (with external power supply)

How much current does your screwdriver use?


body:
From the Arduino playground:

Arduino: What Adapter?

by djmatic

Ever since the dawn of Arduino, one question has been asked over and over again: "what kind of DC adapter can I use to power my Arduino?"

The short answer is: 9 to 12V DC, 250mA or more, 2.1mm plug, centre pin positive.

The long answer is that an off-the shelf Arduino adapter:

must be a DC adapter (i.e. it has to put out DC, not AC);
should be between 9V and 12V DC (see note below);
must be rated for a minimum of 250mA current output, although you will likely want something more like 500mA or 1A output, as it gives you the current necessary to power a servo or twenty LEDs if you want to.
must have a 2.1mm power plug on the Arduino end, and
the plug must be "centre positive", that is, the middle pin of the plug has to be the + connection.
These important details are often contained right on the adapter.

Current rating: Since you'll probably be connecting other things to the Arduino (LEDs, LCDs, servos) you should get an adapter that can supply at least 500mA, or even 1000 mA (1 ampère). That way you can be sure you have enough juice to make each component of the circuit function reliably.

One final note. The Arduino's on-board regulator can actually handle up to 20V or more, so you can actually use an adapter that puts out 20V DC. The reasons you don't want to do that are twofold: you'll lose most of that voltage in heat, which is terribly inefficient. Secondly, the nice 9V pin on the Arduino board will actually be putting out 20V or so, which could lead to potential disaster when you connect something expensive to what you thought was the 9V pin. Our advice is to stick with the 9V or 12V DC adapter.

 Electronicalifragilistic: I use a power supply from an old HP laptop that I scrapped. The plug is center positive and puts out 12V. Fits perfectly into Arduino connector. Packs a Wallop - most laptops draw 2-2.5 amps. That ought to run your screwdriver.


message:
CC3000 gets wrong address when connecting to wireless AP

I tried using both the SparkFun and Adafruit CC3000 libraries first with what I actually wanted as a program, but when that didn't work, the examples for those libraries, and I always seem to get the same problem.

The CC3000 will connect to my AP, which uses a private address in the range `172.24.1.1/24`, and somehow it will end up with the address `192.168.1.64`.

I know that it is connecting, since iw event lists the device MAC address as it connects.

The only changes I have made to the source code at this point are the ssid and password, and changing the interrupt and vbat pins to match the configuration of the tinyduino cc3000 board.

The device has firmware 1.34. [Here][1] is the code.

The specific output I get from the arduino is as follows (Note I commented out the disconnect at the bottom):

    Connected at 115200

    ---------------------------------
    SparkFun CC3000 - Connection Test
    ---------------------------------
    CC3000 initialization complete
    Connecting to: my_wifi_ap
    Connected!

    CC3000 MAC Address: 70:FF:76:04:B9:5B
    IP Address: 192.168.1.62
    Subnet Mask: 255.255.255.0
    Default Gateway: 192.168.1.254
    DHCP Server: 0.0.0.0
    DNS Server: 192.168.1.254
    SSID: my_wifi_ap

    Finished connection test

running `iw event -f` on my AP before running a connection test gives me the following output:

    wlan0: new station 70:ff:76:04:b9:5b

When another device, like my phone, connects to this AP, we get `172.24.1.xx`, where `xx` is whatever number between `50` and `150` that DHCP assigns us.

**Edit:**
Also, if I comment out the disconnect at the end of the test, I can see the device is sending keepalives every three or four seconds using:

    iw dev wlan0 station get 70:ff:76:04:b9:5b  //(inactive time never exceeds 4000ms).
I can't `ping 192.168.1.64` because that network is obviously unreachable, but trying to `ping 172.24.1.64` gives me a exception:

    icmp open socket: Operation not permitted

Output from [Adafruit Example][2]:

    RX Buffer : 131 bytes
    TX Buffer : 131 bytes
    Free RAM: 1221

    Initialising the CC3000 ...
    Firmware V. : 1.32
    MAC Address : 0x70 0xFF 0x76 0x04 0xB9 0x5B
    Started AP/SSID scan

    Networks found: 20
    ================================================

    ...

    SSID Name    : my_wifi_ap
    RSSI         : 83
    Security Mode: 3

    SSID Name    : my_other_wifi_ap
    RSSI         : 67
    Security Mode: 3

    ...

    ================================================

    Deleting old connection profiles

    Attempting to connect to my_wifi_ap
    Started AP/SSID scan

    Connecting to my_wifi_ap...Waiting to connect...Connected!
    Request DHCP

    IP Addr: 192.168.1.62
    Netmask: 255.255.255.0
    Gateway: 192.168.1.254

The actual device being connected to is a Raspberry Pi AP, which was set up with DNSMASQ and hostapd. The configuration works, and has been proven to work with other embedded networking devices.

  [1]: https://codebender.cc/example/SFE_CC3000/ConnectionTest#ConnectionTest.ino
  [2]: https://codebender.cc/example/Adafruit_CC3000/buildtest#buildtest.ino

body: Welcome to the wonderful world of Adafruit software. Some genius decided that the CC3000 should save the first address it is ever given to nonvolatile storage, and use that ever since no matter what DHCP may subsequently tell it. Check the library source.


body:
I realized that I was using firmware v 1.34 on the board, which is what it was configured with when I got it, and decided I would try to downgrade it to one of the fir;ware sets supplied by adafruit to see if that would work.

The firmware modifying program didn't actually compile on the desktop version of the arduino ide, so I decided to use codebender instead.

I'm not sure whether or not I should be disappointed or relieved, but downgrading the firmware actually made it work. I used the file titled driverpath_1_11, which I believe the libraries refer to as firmware version 0x113 or 0x118, which identifies itself as firmware version 1.24, which somehow actually worked.

The solution is here: https://codebender.cc/sketch:318229

The pins have been changed to correspond with the fixed pings used by the tinyduino.