message:
How to merge HCSR04 code with DF Player mini mp3

As the title says, I have a problem to merging the HCSR04 code with DF Player mini mp3 codebases so that they are working together in the one sketch.

The idea is when the ultrasonic sensor reads a certain range, it will trigger a specific mp3 files via the DF player.

I'm using 5 Ultrasonic sensors, and I wanted each sensors to trigger different mp3 files.

***Ultrasonic code:***

    int trigPin1=2;
    int echoPin1=3;

    int trigPin2=4;
    int echoPin2=5;

    int trigPin3=6;
    int echoPin3=7;

    int trigPin4=8;
    int echoPin4=9;

    int trigPin5=10;
    int echoPin5=11;

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin1, OUTPUT);
      pinMode(echoPin1, INPUT);
      pinMode(trigPin2, OUTPUT);
      pinMode(echoPin2, INPUT);
      pinMode(trigPin3, OUTPUT);
      pinMode(echoPin3, INPUT);
      pinMode(trigPin4, OUTPUT);
      pinMode(echoPin4, INPUT);
      pinMode(trigPin5, OUTPUT);
      pinMode(echoPin5, INPUT);

    }

    void loop() {
      long duration1, distance1;
      digitalWrite(trigPin1, LOW);  // Added this line
      delayMicroseconds(10); // Added this line
      digitalWrite(trigPin1, HIGH);
      delayMicroseconds(15); // Added this line
      digitalWrite(trigPin1, LOW);
      duration1 = pulseIn(echoPin1, HIGH);
      distance1 = duration1/58;

    long duration2, distance2;
      digitalWrite(trigPin2, LOW);  // Added this line
      delayMicroseconds(10); // Added this line
      digitalWrite(trigPin2, HIGH);
      delayMicroseconds(15); // Added this line
      digitalWrite(trigPin2, LOW);
      duration2 = pulseIn(echoPin2, HIGH);
      distance2= duration2/58;

    long duration3, distance3;
      digitalWrite(trigPin3, LOW);  // Added this line
      delayMicroseconds(10); // Added this line
      digitalWrite(trigPin3, HIGH);
      delayMicroseconds(15); // Added this line
      digitalWrite(trigPin3, LOW);
      duration3 = pulseIn(echoPin3, HIGH);
      distance3= duration3/58;

      long duration4, distance4;
      digitalWrite(trigPin4, LOW);  // Added this line
      delayMicroseconds(10); // Added this line
      digitalWrite(trigPin4, HIGH);
      delayMicroseconds(15); // Added this line
      digitalWrite(trigPin4, LOW);
      duration4 = pulseIn(echoPin4, HIGH);
      distance4= duration4/58;

      long duration5, distance5;
      digitalWrite(trigPin5, LOW);  // Added this line
      delayMicroseconds(10); // Added this line
      digitalWrite(trigPin5, HIGH);
      delayMicroseconds(15); // Added this line
      digitalWrite(trigPin5, LOW);
      duration5 = pulseIn(echoPin5, HIGH);
      distance5= duration5/58;

      Serial.print (distance1);
      Serial.print (",");
      Serial.print(distance2);
      Serial.print(",");
      Serial.print(distance3);
      Serial.print(",");
      Serial.print(distance4);
      Serial.print(",");
      Serial.print(distance5);
      Serial.println(",");
      delay(100);

    }

***DF Player code:***

    #include "Arduino.h"
    #include "SoftwareSerial.h"
    #include "DFRobotDFPlayerMini.h"

    SoftwareSerial mySoftwareSerial(12, 13); // RX, TX
    DFRobotDFPlayerMini myDFPlayer;
    void printDetail(uint8_t type, int value);

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

      Serial.println();
      Serial.println(F("DFRobot DFPlayer Mini Demo"));
      Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

      if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
        Serial.println(F("Unable to begin:"));
        Serial.println(F("1.Please recheck the connection!"));
        Serial.println(F("2.Please insert the SD card!"));
        while(true);
      }
      Serial.println(F("DFPlayer Mini online."));

      myDFPlayer.volume(10);  //Set volume value. From 0 to 30
    }

    void loop()
    {
      static unsigned long timer = millis();

      if (millis() - timer > 2000) {
        timer = millis();
        myDFPlayer.next();  //Play next mp3 every 3 second.
      }

      if (myDFPlayer.available()) {
        printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
      }
    }

    void printDetail(uint8_t type, int value){
      switch (type) {
        case TimeOut:
          Serial.println(F("Time Out!"));
          break;
        case WrongStack:
          Serial.println(F("Stack Wrong!"));
          break;
        case DFPlayerCardInserted:
          Serial.println(F("Card Inserted!"));
          break;
        case DFPlayerCardRemoved:
          Serial.println(F("Card Removed!"));
          break;
        case DFPlayerCardOnline:
          Serial.println(F("Card Online!"));
          break;
        case DFPlayerPlayFinished:
          Serial.print(F("Number:"));
          Serial.print(value);
          Serial.println(F(" Play Finished!"));
          break;
        case DFPlayerError:
          Serial.print(F("DFPlayerError:"));
          switch (value) {
            case Busy:
              Serial.println(F("Card not found"));
              break;
            case Sleeping:
              Serial.println(F("Sleeping"));
              break;
            case SerialWrongStack:
              Serial.println(F("Get Wrong Stack"));
              break;
            case CheckSumNotMatch:
              Serial.println(F("Check Sum Not Match"));
              break;
            case FileIndexOut:
              Serial.println(F("File Index Out of Bound"));
              break;
            case FileMismatch:
              Serial.println(F("Cannot Find File"));
              break;
            case Advertise:
              Serial.println(F("In Advertise"));
              break;
            default:
              break;
          }
          break;
        default:
          break;
      }

    }

body:
I've refactored it a bit, to remove the need to repeat the same code, 5 times, for 5 sensors.

    #include "Arduino.h"
    #include "SoftwareSerial.h"

    #include "DFRobotDFPlayerMini.h"

    const byte SENSOR_COUNT = 5;
    byte triggerPins[SENSOR_COUNT] = {2,4,6,8,10};
    byte echoPins[SENSOR_COUNT]    = {3,5,7,9,11};

    SoftwareSerial mySoftwareSerial(12, 13); // RX, TX

    DFRobotDFPlayerMini myDFPlayer;

    void printDetail(uint8_t type, int value);

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

      for( byte i=0; i<SENSOR_COUNT; i++ )
      {
        pinMode(triggerPins[i], OUTPUT);
        pinMode(echoPins[i], INPUT);
      }

      Serial.println();
      Serial.println(F("DFRobot DFPlayer Mini Demo"));
      Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

      if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
        Serial.println(F("Unable to begin:"));
        Serial.println(F("1.Please recheck the connection!"));
        Serial.println(F("2.Please insert the SD card!"));
        while(true);
      }
      Serial.println(F("DFPlayer Mini online."));

      myDFPlayer.volume(10);  //Set volume value. From 0 to 30

    }

    int currentSound = -1;
    void loop()
    {

      for( byte i=0; i<SENSOR_COUNT; i++ ) // loop through all distance sensors
      {
        if( detectPresence(i) ) // check if there is an object near it
        {
          if(currentSound!=i) // check that it's a different sensor than the one that was last triggered
          {
            Serial.print("play song number ");
            Serial.println(i);
            myDFPlayer.play(i+1); // play song nr `i+1`
          }
          currentSound = i;
        }
      }

      if (myDFPlayer.available()) {
        printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
      }

    }

    // detectPresence will return TRUE if there is an object close to it.
    bool detectPresence(byte sensorNr)
    {
      if( sensorNr>=SENSOR_COUNT )
        return false;
      long duration, distance;
      //digitalWrite(triggerPins[sensorNr], LOW);  // Added this line
      //delayMicroseconds(10); // Added this line
      digitalWrite(triggerPins[sensorNr], HIGH);
      delayMicroseconds(15); // Added this line
      digitalWrite(triggerPins[sensorNr], LOW);
      duration = pulseIn(echoPins[sensorNr], HIGH);
      distance = duration/58;

      return distance<30;// choose your own value here, from which distance it should trigger a sound
    }

    void printDetail(uint8_t type, int value){

      switch (type) {
        case TimeOut:
          Serial.println(F("Time Out!"));
          break;
        case WrongStack:
          Serial.println(F("Stack Wrong!"));
          break;
        case DFPlayerCardInserted:
          Serial.println(F("Card Inserted!"));
          break;
        case DFPlayerCardRemoved:
          Serial.println(F("Card Removed!"));
          break;
        case DFPlayerCardOnline:
          Serial.println(F("Card Online!"));
          break;
        case DFPlayerPlayFinished:
          Serial.print(F("Number:"));
          Serial.print(value);
          Serial.println(F(" Play Finished!"));
          break;
        case DFPlayerError:
          Serial.print(F("DFPlayerError:"));
          switch (value) {
            case Busy:
              Serial.println(F("Card not found"));
              break;
            case Sleeping:
              Serial.println(F("Sleeping"));
              break;
            case SerialWrongStack:
              Serial.println(F("Get Wrong Stack"));
              break;
            case CheckSumNotMatch:
              Serial.println(F("Check Sum Not Match"));
              break;
            case FileIndexOut:
              Serial.println(F("File Index Out of Bound"));
              break;
            case FileMismatch:
              Serial.println(F("Cannot Find File"));
              break;
            case Advertise:
              Serial.println(F("In Advertise"));
              break;
            default:
              break;
          }
          break;
        default:
          break;
      }

    }


sender: user

message:
SPFD5408 for TFT in Arduino Due

I have interfaced HC024071 TFT Display with Arduino Due using SPFD5408 Adafruit library. It works perfect.

But using the same library with Arduino Due (with pin connections modified as follows):

    // For the Arduino Uno, Duemilanove, Diecimila, etc.:
    //   D0 connects to digital pin 8  (Notice these are
    //   D1 connects to digital pin 9   NOT in order!)
    //   D2 connects to digital pin 2
    //   D3 connects to digital pin 3
    //   D4 connects to digital pin 4
    //   D5 connects to digital pin 5
    //   D6 connects to digital pin 6
    //   D7 connects to digital pin 7

But unfortunately, errors occur (which made me guess Due is incompatible with the same)

    Build options changed, rebuilding all
    In file included from C:\Users\Arun Baby\Desktop\test\sketch_dec16c\sketch_dec16c.ino:2:0:

    sketch\TFTLIB.H: In function 'void Draw_Welcome_Screen()':

    sketch\TFTLIB.H:154:36: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       draw_text("Z.A.R.S",55,150,BLUE,3);

                                        ^

    sketch\TFTLIB.H:155:59: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       draw_text("Zone Adaptive Response System",25,180,BLACK,1);

                                                               ^

    sketch\TFTLIB.H:157:57: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       draw_text("Touch anywhere to continue!",30,280,BLACK,1);

                                                             ^

    sketch\TFTLIB.H: In function 'void Draw_Menu()':

    sketch\TFTLIB.H:166:48: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       draw_text("Z.A.R.S Main Menu",120,300,WHITE,1);

                                                    ^

    sketch\TFTLIB.H:168:42: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       draw_text("Driving Mode",20,45,0x1220,2);

                                              ^

    sketch\TFTLIB.H:169:46: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       draw_text("Zones Supported",20,135,0x1220,2);

                                                  ^

    sketch\TFTLIB.H:170:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       draw_text("Settings",20,225,0x1220,2);

                                           ^

    sketch\TFTLIB.H: In function 'void Draw_Settings()':

    sketch\TFTLIB.H:179:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       draw_text("Settings",160,300,WHITE,1);

                                           ^

    sketch\TFTLIB.H:181:43: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       draw_text("Re-Caliberate",20,45,0x1220,2);

                                               ^

    sketch\TFTLIB.H:182:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       draw_text("GPS Lock",20,135,0x1220,2);

                                           ^

    sketch\TFTLIB.H:183:34: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       draw_text("BACK",20,225,WHITE,2);

                                      ^

    sketch\TFTLIB.H: In function 'void Manual_Recaliberation()':

    sketch\TFTLIB.H:189:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         draw_text("Touchscreen \n   Recaliberation",60,100,WHITE,2);

                                                                   ^

    sketch\TFTLIB.H:191:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         draw_text("STEP 1",100,200,WHITE,2);

                                           ^

    sketch\TFTLIB.H:192:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         draw_text("Please touch the BLUE dot...",40,250,WHITE,1);

                                                                ^

    sketch\TFTLIB.H:198:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         draw_text("Touchscreen \n   Recaliberation",60,100,WHITE,2);

                                                                   ^

    sketch\TFTLIB.H:200:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         draw_text("STEP 2",100,200,WHITE,2);

                                           ^

    sketch\TFTLIB.H:201:59: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         draw_text("Please touch the RED dot...",40,250,WHITE,1);

                                                               ^

    sketch\TFTLIB.H:209:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         draw_text("Touchscreen \n   Recaliberation",60,100,WHITE,2);

                                                                   ^

    sketch\TFTLIB.H:211:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         draw_text("STEP 3",100,200,WHITE,2);

                                           ^

    sketch\TFTLIB.H:212:62: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         draw_text("Please touch the YELLOW dot...",40,250,WHITE,1);

                                                                  ^

    sketch\TFTLIB.H:224:61: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         draw_text("Recaliberation \n    Complete",30,100,WHITE,2);

                                                                 ^

    sketch\TFTLIB.H:227:36: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         draw_text("BACK",20,225,WHITE,2);

                                        ^

    In file included from C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_Adafruit_TFTLCD.cpp:30:0:

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\pin_magic.h:306:33: warning: backslash and newline separated by space [enabled by default]

       #define read8inline(result) { \

     ^

    In file included from C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/pins_arduino.h:20:0,

                     from C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:6:

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp: In member function 'TSPoint TouchScreen::getPoint()':

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

     #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                     ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:61:21: note: in expansion of macro 'digitalPinToPort'

       uint8_t xp_port = digitalPinToPort(_xp);

                         ^

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

     #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                     ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:62:21: note: in expansion of macro 'digitalPinToPort'

       uint8_t yp_port = digitalPinToPort(_yp);

                         ^

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

     #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                     ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:63:21: note: in expansion of macro 'digitalPinToPort'

       uint8_t xm_port = digitalPinToPort(_xm);

                         ^

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

     #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                     ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:64:21: note: in expansion of macro 'digitalPinToPort'

       uint8_t ym_port = digitalPinToPort(_ym);

                         ^

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

     #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                                ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:77:4: note: in expansion of macro 'portOutputRegister'

       *portOutputRegister(yp_port) &= ~yp_pin;

        ^

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

     #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                                ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:78:4: note: in expansion of macro 'portOutputRegister'

       *portOutputRegister(ym_port) &= ~ym_pin;

        ^

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

     #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                                ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:86:4: note: in expansion of macro 'portOutputRegister'

       *portOutputRegister(xp_port) |= xp_pin;

        ^

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

     #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                                ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:87:4: note: in expansion of macro 'portOutputRegister'

       *portOutputRegister(xm_port) &= ~xm_pin;

        ^

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

     #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                                ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:102:5: note: in expansion of macro 'portOutputRegister'

        *portOutputRegister(xp_port) &= ~xp_pin;

         ^

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

     #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                                ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:106:5: note: in expansion of macro 'portOutputRegister'

        *portOutputRegister(yp_port) |= yp_pin;

         ^

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

     #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                                ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:125:5: note: in expansion of macro 'portOutputRegister'

        *portOutputRegister(xp_port) &= ~xp_pin;

         ^

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

     #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                                ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:129:5: note: in expansion of macro 'portOutputRegister'

        *portOutputRegister(ym_port) |= ym_pin;

         ^

    C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

     #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                                ^

    C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:133:5: note: in expansion of macro 'portOutputRegister'

        *portOutputRegister(yp_port) &= ~yp_pin;

         ^

Is it actually true? Is SPFD5408 completely incompatible with Due?
Trying out UTFT Library with Due gave errors and with Uno, Blank white screen.

Is there any library that is compatible with Due then?

sender: assistant

body:
Yes, that is true. It looks like it tries to do some low-level port manipulation for speed, but it doesn't know how to do that on a Due since it's a completely different beast.

You could always read the datasheet and look at the initialisation code (the hardest part to work out yourself) and roll your own code to control the TFT - it's not actually that hard usually.


message:
Why do I get access denied when I do have mysql root user added to grant all privileges?

I am using the below mysql example sketch to upload data directly to mysql db.

    #include "SPI.h"
    #include "Ethernet.h"
    #include "sha1.h"
    #include "mysql.h"

    /* Setup for Ethernet Library */
    byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    // Set the static IP address to use if the DHCP fails to assign
    IPAddress ip(192, 168, 1, 177);
    IPAddress server_addr(192, 168, 1, 3);
    //char server_addr[] = "192.168.1.3";

    /* Setup for the Connector/Arduino */
    Connector my_conn; // The Connector/Arduino reference

    char user[] = "root";
    char password[] = "secret";
    char INSERT_SQL[] =
     "INSERT INTO test_arduino.hello VALUES ('Hello, MySQL!', NULL)";

    void setup() {
      Ethernet.begin(mac_addr, ip);
      Serial.begin(9600);
      delay(1000);
      Serial.println("Connecting...");
      if (my_conn.mysql_connect(server_addr, 3306, user, password))
      {
        delay(500);
        Serial.println("Connection Successfull,inserting to database.");
         /* Write Hello, World to MySQL table test_arduino.hello */
         my_conn.cmd_query(INSERT_SQL);
         Serial.println("Query Success!");
      }
      else
        Serial.println("Connection failed.");
    }

    void loop() {
    }

I am getting the error in serial Monitor:

> Connecting...

> Error: 76 = Access denied for user
> 'root'@'192.168.1.177' (using password: YES).

>  Connection failed.

even when I have all prvialages on `root` user for the ip of client !

    mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.177';
    Query OK, 0 rows affected (0.00 sec)

    mysql> SELECT host FROM mysql.user WHERE User = 'root';
    +---------------+
    | host          |
    +---------------+
    | 127.0.0.1     |
    | 192.168.1.177 |
    | ::1           |
    | localhost     |
    | raspberrypi   |
    +---------------+
    5 rows in set (0.00 sec)

I ran the following query :

    mysql> SELECT SUBSTRING_INDEX(USER(), '@', -1) AS ip,  @@hostname as hostname, @@port as port, DATABASE() as current_database;

and got the below result !

    +-----------+----------+------+------------------+
    | ip        | hostname | port | current_database |
    +-----------+----------+------+------------------+
    | localhost | ceres    | 3306 | test_arduino     |
    +-----------+----------+------+------------------+
    1 row in set (0.00 sec)

however I am trying to access the test_arduino database from a different IP other than the one mentioned above, does that mean where it says localhost, it is supposed to have `192.168.1.177` as well ? if so How do I insert ip to database `test_arduino` ?

then what am I missing ? please help.

body:
I finally figured out

 By default it may proabbly have an IP address `127.0.0.1` bind to the `3306` port . This won't let your Arduino Ethernet shield connect to mysql server running on a different machine. In my case, I have mysql server running on raspberry pi 3, and it has IP `192.168.1.145`. So for arduino to push directly to databse on remote mysql server, you should have mysql server IP `192.168.145` bind to `3306` port of mysql server running on it. So that MySQL server is visible to remote client on local network on which your arduino Ethernet shield is connected to via LAN.
Then you login to mysql server , and create a user :

    CREATE USER 'myuser'@'192.168.156' IDENTIFIED BY 'mypass';
    CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

then you grant privileges as shown below.

    GRANT ALL ON *.* TO 'myuser'@'192.168.156';
    GRANT ALL ON *.* TO 'myuser'@'%';

Important Note:  the ip address shown in above mysql queries `192.168.156` is the ip address of my ethernet client establishing connection with database on mysql remote server.

Thats it.


message:
I2C and SPI at the same time?

I would like to ask a question relating to the following communication setup:

STM32 -- Arduino Pro Mini -- ADNS3080 sensor

The interface between STM32 -- Arduino is I2C and the interface between Arduino Pro Mini--ADNS3080 is SPI.

I have tested the communication between the STM32 and the Arduino Pro Mini, and between the Arduino Pro Mini and the ADNS3080 sensor. Both of them work fine; I can successfully send and receive data in both cases.

Now, I want to read the register of the ADNS3080 sensor using the STM32. First, I start an I2C communication between the STM32 and the Arduino Pro Mini, then I send the register address of the ADNS3080 to the Arduino Pro Mini. The Arduino Pro Mini reads the register address and in the same function starts a communication, using SPI, with the ADNS3080 sensor.

But I receive I2C errors in the STM32. Is it possible to use I2C and SPI at the same time? Do I have to introduce delays between the I2C and SPI commands?

Regards, Ali

body: Your Arduino code probably needs to implement clock stretching as an i2c slave. This tells the master to chill for a little while as the slave does some work to get an answer.


body:
> is it possible to use I2C and SPI at the same time?

Yes it is. Both are implemented in hardware in the chip. They can operate "in the background" and raise an interrupt when there is something to do.

>  Do I have to introduce delays between the I2C and SPI commands?

No you don't.


message:
Random analog input

I'm trying to build a midi controller that takes the input from a photoresistor and a reed switch anemometer and outputs midi signal.

I've constructed the circuit as in the diagram below but when I test the inputs I receive only random numbers from analog input 3. I get a clear signal on A5.

I'm confused as to what's going on. I've seen other solutions to this problem mention the circuit not being grounded properly but as far as I can see I have the correct grounding.

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

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

body:
Random numbers usually mean that the pin is floating (i.e. not touching anything)

You need to check your connections to A3.

Try this:

- Remove the LDR and R6. Check their resistance using multimeter. (To see if they are not burnt etc.)
- Connect R6 to its place. You should get 0 V (0) because R6 is connected to GND.
- Remove R6 and put it in place of LDR. Now, you should be seeing 5V (1024) on A3.
- After you complete this for R6, try it with using LDR only. You should see same results (Make sure LDR has some light on it to lower its resistance)
- Put everything back in place. You should not be seeing random values because now everything is properly connected.

If you are still seeing random values, then that LDR may be disfunctional. Get another one.

Oh and one more thing, make sure LDR illumination does not change while you're getting readings.


message:
SIM800L GSM Module, no network signal RSSI

I am using a GSM 800L module to send SMS messages. When I test the module with Arduino, it shows a 0 : -115dbm signal strength.

So basically there is no signal. SIM800L is a quad-band GSM/GPRS module that works on frequencies GSM850MHz, EGSM900MHz, DSC1800Mhz, and PCS1900MHz.

My SIM card carrier uses the frequency bands GSM 900, GSM 1800 for 2G-capablities.

What might be the possible reasons my GSM module doesn't work properly with my SIM card? I have tried different locations, still no signal.

The code I use for testing is provided by [Adafruit-Fona][1].

  [1]: https://cdn-learn.adafruit.com/downloads/pdf/adafruit-fona-mini-gsm-gprs-cellular-phone-module.pdf

body: The Problem was that I used 5 V Dc to power the module , it worked but in order to function I must use lithium battery. ( its mentioned in the manual)


message:
How do I control arduino uno multiplexed digital pin (using HC74595)

**Edit:**

***I moved the whole initial post to avoid misunderstanding and confusing everyone, sorry***

after all the reading i came up with this:

this is my code for ultrasonic sensor that going into digital pins in my arduino:

    int trigPin1=2;
    int echoPin1=3;

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

    void loop() {
      long duration1, distance1;
      digitalWrite(trigPin1, LOW);  // Added this line
      delayMicroseconds(10); // Added this line
      digitalWrite(trigPin1, HIGH);
      delayMicroseconds(15); // Added this line
      digitalWrite(trigPin1, LOW);
      duration1 = pulseIn(echoPin1, HIGH);
      distance1 = duration1/58;

      Serial.print (distance1);
      Serial.print (",");
      delay(100);
    }

and this is the idea i wrote to set the "extra digital outputs" on the 595 chip:

    int DS_pin = 8;
    int STCP_pin = 9;
    int SHCP_pin = 10;

    void setup()
    { // put your setup code here, to run once:
      pinMode(DS_pin, OUTPUT);
      pinMode(STCP_pin, OUTPUT);
      pinMode(SHCP_pin, OUTPUT);
      writereg();
    }

    bool registers[8];

    void writereg()
    {
      digitalWrite(SHCP_pin, LOW);

      for (int i = 0; i<=7; i++)
      {
        digitalWrite(STCP_pin, LOW);
        digitalWrite(DS_pin,registers[1]);
        digitalWrite(STCP_pin, HIGH);
      }
        digitalWrite(SHCP_pin, HIGH);
    }

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

    }

now if you guys have a little time to check it, and tell me what should i wrote so the ultrasonic sensor will be working with the 595 chip's outputs?

Let say im going to put the Trigger pin into Q0 and Echo pin into Q1

thanks in advance

body:
It is good that you are thinking of abstraction in order to simplify programming.  Simplifying programming by using familiar names makes it easier to understand the code.

In your example:

    int triggerPin=2
    pinMode(triggerPin, OUTPUT)

..you are abstracting the actual pin used to trigger the ultrasound by calling it by a familiar name "triggerPin".  You could have just as easily wrote the same code as:

    pinMode(2, OUTPUT)

Now you are asking how to abstract the pins when connecting the Arduino to the 74HC595.  The truth is, you don't have to.  But to make it easier to write & read the code you can use what ever names make sense to you.  In [this example of connecting an Arduino to a 74HC595][1] there are 3 Arduino pins connected to the 74HC595.  They called them "dataPin", "latchPin" and "clockPin".  If these make sense to you use these names.

> Add: can i address the output like this?
>
>      #define LED_PIN     Q1

No, nothing knows what "Q1" is.  Remember, you are adding this hardware to the Arduino.  So nothing, not the compiler nor a library, knows about the hardware you added let alone a pin called Q1 on the added hardware.

First you need to understand how to set Q1 through Q8.  Refer to the 74HC595 Arduino tutorial linked to above.  Inspect the example programs.  Once you understand how to set / un-set Q1 through Q8, you can decide if you what to simply shift out a number or if you want to use abstraction giving names to the shift register output pins.

If I were only writing patterns, for example lighting up 8 LEDs, I would stick to numbers. However, if I were controlling different things, for example a light, a motor & a buzzer, I would assign each a unique name and build my program around the names.

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


message:
What is this shield? (AST Space Arduino Kit)

I recently got a box with Arduino components from someone who didn't want it (in part, because the manual was (probably) in Chinese). However, to my surprise, I could not find this kit on the internet. I would like to know: **is this a copy of another kit?**  Or, is there documentation available for this particular kit?

Box contents:

 - Arduino Uno
 - Unknow shield "by AST Space" with
   - AI-THINKER wi-fi module
   - Songle relais
   - YLB3641AH 4-digit LED display
   - DHT-11 relative humidity, temperature sensor
   - IR receivers, switches, microphone/buzzer, light sensor, connectors to the other components
 - MPU6050 accelerometer
 - HC-SR04 ultrasonic rangefinder
 - QAPASS LCD unit
 - "Car MP3" IR remote
 - 2x green, 2x red LED, 5x resistor
 - 17x10 green breadboard
 - 2x DC motor, 1x geared stepper motor
 - 40-wide female-female jumper ribbon cable
 - USB connector cable (black)

It came in an intricate folding box, bright orange. The QR code links to http://weixin.qq.com/r/2kgtNVXEKwhUrRFW9x3I (which did not get me anywhere - visiting this link is at your own risk). Pictures:

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

[![enter image description here][2]][2]

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/iyhFk.jpg
  [2]: https://i.stack.imgur.com/3l93S.jpg
  [3]: https://i.stack.imgur.com/vCNsL.jpg

body:
AST stands for Art, Science and Technology. The learning kit is produced by [AST Space][1] who also run maker competitions.

  [1]: https://translate.google.com/translate?depth=1&hl=en&prev=search&rurl=translate.google.co.uk&sl=zh-CN&u=http://www.yiweibiying.com/p/J9MPkxx.html


body:
On http://astspace.org/ you can download a PDF related to this [AST Space Kit][1][rar archive].

[![Shield Description][2]][2]

I took the schema in the PDF and translated in English. Looking at the examples (see below), it looks like the "Wifi Module" is an ESP8266.

The QR code in the PDF is actually readable, but you have to scan it in WeChat (a social platform that mixes chat, Instagram and shopping).

The QR code links to AST Space's account:

[![enter image description here][3]][3]

The download mentioned above contains schematics and sample code. Download that and you should have a much better understanding on how to use it.

[![enter image description here][4]][4]

  [1]: http://ast-space.b0.upaiyun.com/AST Arduino Kit资料包.rar
  [2]: https://i.stack.imgur.com/LjuC7.jpg
  [3]: https://i.stack.imgur.com/JixQV.png
  [4]: https://i.stack.imgur.com/olNHv.png


body:
My name is Bing Zhu. I the host of ASTSpace a community open lab sponsored by Zhejiang Association for Science and Technology(ZAST). AST is situated inside the Zhejiang Museum of Science and Technology. We are non-profit. The Kit you have gotten must be from someone got it free at one of ASTSpace's events. I remembered that we had brought some with us to the Manchester Science Festival where we did a tinkering activity for the public, 3 years ago.
This kit was designed by one of our members who is currently a Ph.D. student of automation at Zhejiang University. It was developed for the purpose to increase public experiences in a 90 minutes session. Therefore, in order to shorten the time of wiring while most times participants with no backgrounds or exposures to electronics make no sense anyway, we purposely had most of the functioning parts soldered on. In this way, we think it would be more manageable as well for teaching as most times one instructor has to manage more than a room full of over 25 participants. Making sure that parts are connected and in place can be a life-saver. We had it designed this way so the kit can be used in classes by schools in remote areas. These kits are given away and the introduction sessions are free to the public, and we intended to provide online help to those who decide to venture on with this kit at their own time. But, it never took off for time and resource restriction.  With this kit we have gone through two major cities in the Zhejiang Province and 4 remote rural areas.
All our expenses are supported by ZAST through two projects, one to make it and one to distribute it. When we did what we did, it was always for the public to know electronic control and coding was made easy by Arduino where it was first invented by an Italian who wanted to teach artists electronics.
This kit was used to demo how easily and readily everything can be controlled and through these electronics, we can take the parts of the physical world into our hands to follow our wills. We did use it to demo the on and off lighting system of the entire science center and controls of a remote camera inside the security room.
So, ASTSpace Arduino kit is a tailor-made kit for a specific purpose. We did not change anything but redesigned the wiring of the sensors for easy use for our events.


body:
I'm Xiaotian, the designer of this arduino learning Kit. We designed that for people who love DIY but without electronic backgrounds. In the past events, we found everybody (12-16 year old kids usually) could start wiring and coding and finish a little projects with the kit and its examples in 90 mins. All of hardware and software are modular, you could assembly them you want and make your great ideas real quickly.
If you want to know more details about it, feel free to let me know. My email is xtchen@zju.edu.cn.
Thanks for your attention!

Xiaotian


message:
Arduino add two spi slaves that has no slave select pin

I am working on a project where Arduino is communicating with two devices using SPI. Unfortunately, these two devices has no ss(slave select) pin to communicate with each one separately.

How Can I solve this issue?

[Sensor example][1]

Thanks

  [1]: https://www.alibaba.com/product-detail/MS5540C-miniature-barometer-module_60522099649.html

body:
Looking at the [MS5540C specifications][1] and assuming there are no other significant parts on the PCB you identified, there does not appear to be a SPI port available.

Neither "SPI" not "I2C" appear in the document.  Please check your self to verify.

Instead there is a section on serial communication with the MS5540C part its self.  In this section there are a number of diagrams.  Here is one:

[![enter image description here][2]][2]

In the text we find this:

> Every  communication  starts  with  an  instruction  sequence  at  pin
> DIN.  Fig.  6  shows  the  timing  diagrams  for  the  MS5540C.

Which is very nearly if not exactly how I2C works.

The text goes on to say:

> he  device  does  not  need  a  ‘Chip  select’  signal.  Instead
> there  is  a  START  sequence  (3-Bit  high) before  each  SETUP
> sequence  and  STOP  sequence  (3-Bit  low)  after  each  SETUP
> sequence.  The  SETUP  sequence consists in 4-Bit that select a
> reading of pressure, temperature or calibration data. In case of
> pressure- (D1) or temperature- (D2) reading the module acknowledges
> the start of a conversion by a low to high transition at pin DOUT
> during the last bit of the STOP sequence.

Unfortunately, this design appears to prohibit using more than one identical device on the same serial bus.

Workarounds to this design flaw (if it truly exists) include blocking the SCLK or the DIN signal to the un-selected MS5540C.

In many other cases where multiple identical I2C devices are used on the same bus, vendors provide a pin on the device which can be used to alter the address of an individual device.

  [1]: https://media.digikey.com/pdf/Data Sheets/Measurement Specialties PDFs/MS5540-CM.pdf
  [2]: https://i.stack.imgur.com/zQzB5.png


body:
Ss or cs pin ISS not mandatory for SPI.

A few solutions.

1. Power on or off the devices. A group pin can do that.

2. Cut off mclk.

3. Have a separate sclk pins for individual chips. You will need to share the serial data pins, ored with some diodes or pull up.

4. Software SPI.

...

I'm sure others will come up with more solutions.


message:
Can I use a HC-05 and a GPS without a breadboard on a Arduino Uno?

I was wondering if I can use a GPS (in my case a U-BLOX) and a hc-05 at the same time connected to a arduino uno without a breadboard? I have tried my GPS on the arduino uno alone and it works very good. Now my question is, can I add a hc-05 on the board directly and put the VCC on the empty 5v?

I put together a schematic of what I had in mind below:

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

Would this schematic work or would I need a breadboard?

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

body:
I don't see why not. The breadboard is just something to help you prototype yuproect, in the end, your project should always be on a perfboard or a custom PCB.

Note that some male-female header might get handy.

I'm not sure that the HC05 can handle 5V though. You migh want to check.


message:
Arduino Uno Bluetooth connection

I'm trying to connect two Arduino Unos with Bluetooth modules (HC-06 and HC-05). Does anyone know the steps required to do that?

I still haven't figured out:

- How to pair the two Bluetooth devices, and;
- How to pair each Bluetooth with each Arduino.

If you have any useful tutorials, please let me know.

body:
There is a nice example for Arduino here.

[Connecting 2 Arduinos by Bluetooth using a HC-05 and a HC-06: Pair, Bind, and Link][1]

The Uno works the same way as the board in the example.

Arduino 1

[![Arduino 1][2]][2]

Arduino 2

[![Arduino 2][3]][3]

  [1]: http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-pair-bind-and-link/
  [2]: https://i.stack.imgur.com/mkOqr.jpg
  [3]: https://i.stack.imgur.com/XaKRJ.jpg


message:
Reading values from SQL Arduino ethernet

I'm about to do this project where I will make some lights flash up depending on some values that are in an SQL database on a server. I have already bought my Arduino and waiting for it to arrive. But I've been stuck at how to read the SQL data from the Arduino, connected to ethernet only.

Is there a library where I can select from the database directly or do I have to make a web service, in which I can make a http request to when needed?

If it's a web service, can I be directed to some examples of this being used with Arduino? I've been looking around the past few days but haven't been able to find a decent example.

Best regards and thanks a lot in advance for your time! :-)

body:
I would make a small http REST API on your SQL server. The Arduino could use the API to get the data.
The API can easily be done in php, ruby or whatever.


body:
Connecting to an SQL database from the Arduino would be the hard way. Creating a simple web page that can read data from your database and display said data would be the easier way. You could then access this data on the Arduino via an http request.

Here's an example of how to write such a web page in PHP: https://www.w3schools.com/php/php_mysql_select.asp

And here's the Arduino example for an HTTP request with an ethernet shield: https://www.arduino.cc/en/Tutorial/WebClient


message:
Minimum circuitry required to program an AVR

Where is the information what is the minimum-required circuitry to program any AVR via ICSP?

Sometimes I see schematics that show just the [chip and the six wires](http://avrprojectsfiuady.blogspot.com/2011/07/programming-avr-with-avrisp-mkii.html) for the ICSP header (RESET, VCC, GND, MISO, MOSI, and SCK).

Other times, I see some [passive components connected to some of the pins](https://i.stack.imgur.com/lEp52.png).

So why is it different some times? How do people know when to use extra components when wiring up the chip for programming? Do the datasheet for these MPU's provide the details?

body:
I have [a page about a minimal board](http://www.gammon.com.au/breadboard). The minimal circuit is the chip itself, and a couple of decoupling capacitors. A pull-up on /RESET is advisable (however the processor has a weak pull-up on it).

[![Minimal Atmega328P board][1]][1]

The six wires you mention are required for ICSP programming. An example from my page is:

[![Programming minimal board][2]][2]

That is using an Arduino as an ICSP programmer.

I think most designers would mandate the decoupling capacitors. You may get away without the pull-up on /RESET but probably at the expense of reliability.

The wires changed colour between the two photos because my earlier board (shown second) had the capacitors further away from the chip pins than they should have been. They really should be next to the chip for maximum effectiveness.

---

Note that, depending on the fuses, you may need to supply an external clock. In my case I did it like this:

[![Clock crystal][3]][3]

The default chip fuses (from the manufacturer) does not require a crystal.

  [1]: https://i.stack.imgur.com/s7P4H.jpg
  [2]: https://i.stack.imgur.com/0yCkb.jpg
  [3]: https://i.stack.imgur.com/5bZq8.jpg


message:
Where is the inaccuracy of my arduino thermistor circuit coming from?

[![enter image description here][1]][1]I've setup four thermistors and a known resistor in series and connected them to the 3.3V output (as I've heard it's cleaner than the 5V) of an Arduino Uno (with the 3.3V also connected to ARef to increase accuracy), with the four analog inputs testing the voltage drop across each thermistor to determine its resistance, and hence temperature.

But even with no change in the thermistor temperatures, the voltages I get from the arduino vary significantly. See below an example readout of the four arduino inputs (with thermistor temperatures/resistances same throughout):

230 424 634 849

212 412 597 819

241 415 611 857

204 413 654 845

The accuracy I come out with is around 5-10 degrees - way more than I expected. Why is this? And what can I do to get it down to less than one degree? Many thanks

UPDATE:
A MASSIVE THANKYOU to all those who helped me on this, particularly @NickGammon, @Talk2 and most of all @JRobert for the brilliantly clear and simple to follow circuit instructions to follow, all of which helped to thoroughly solve my problem! The sensor works great now, many thanks!!

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

body:
Without exactly knowing part names, models and source code is difficult to tell what to expect. But a few techniques can be used to improve the stability of an analog reading. Here a few things you might want to consider:

1. Use INTERNAL vref of 1.1V, this is a very stable voltage reference
2. Use a stable/good quality series resistor, with little tolerance, like 1%
3. Add a 22pF capacitor, connecting the analog input to ground. This helps stabilizing the signal
4. Perform multiple consecutive readings, let's say 5 readings, and use the average. You might also want to remove the biggest and lowest values before averaging.


body:
I may be mistaking, but what you did is a voltage divisor where you read the voltage across resistors in series (your thermistors).

When resistors are in series as you know you add their value. So A4 is reading the value across TR1+TR2+TR3+TR4. A3 is reading the value across TR1+TR2+TR3 and so forth.


body:
Why are you using the voltage divider and measuring by parts? As @nickgammon points out, you are measuring only a 1/5 of full scale at each measurement, meaning your resolution is down by 5:1 over what the A/D is capable of. Also, the divider network comes to around 500KOhms. Work out the current through that and you get a very feeble <7 microAmps. The wires are antennas that could well be contributing noise at a significant fraction of that level.

Is there a reason for the divider circuit? Could you use a single thermistor from Vcc to Gnd plus a resistor in a 2-way divider? That will have the advantages of:

 - Using (more of) the full range of A/D;
 - Taking only one reading instead of several (and the several are necessarily skewed in time since you're multiplexing the one A/D);
 - A larger current (ok, only 33 microAmps, but 5x better than before);
 - Presumably less pickup into the network than with 5 leads. Keeping the measurement lead as short as possible may help, too.

Update:

Then you probably want a 2-component divider for each temperature you need to measure, paralleled between the power rails. I just guessed, not calculated, the resistances of R1, R3, R5, & R7. You'll want to estimate the maximum and minimum temperatures of interest in each channel and pick values that will give you the best ranges without drawing excessive currents when the thermistor values are low.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/X4nAD.png)

<!-- End schematic -->


message:
Does this code work as a PWM?

I'm working on an Arduino project and I need to write some code that controls the frequency and duty cycle of a square wave signal (pulse width modulation). I'm not allowed to use the PWM function, I have to write my own code.

I've tried this code on Proteus (virtual Arduino) but there are two problems:

1. The frequency is always high (hundreds of Hz) even if the input voltage is zero. It never reaches 0.5 Hz or 1 Hz.

2. The duty cycle is very high or very low. I never see 50% or 75% duty cycle on an oscilloscope. When I change the position of the potentiometer it becomes 90% or 10% (I think) and there are no other values.

Would you tell me what's wrong with this code please? I can not find my mistake:

    unsigned long Time = 2000000; unsigned int Volt; float dutyCycle = 0.5;
    void setup() {
      pinMode(13, OUTPUT); //set Pin 13 or On-board LED to output
    }

    // the loop function runs over and over again forever
    void loop() {

      Volt = analogRead (1);    // Frequency: input voltage is through potentiometer at analong pin 1
      dutyCycle = analogRead (0) / 1023;    // dutyCycle potentiometer is at analong pin 0
      Time = ( 2000954 / (1 + Volt) )- 954; //This equations is linear. When input voltage is zero, frequency = 0.5Hz. When input voltage is 5v, f=1000Hz.

      digitalWrite(13, HIGH);   // turn the LED on
      delayMicroseconds(Time * dutyCycle );              // wait
      digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
      delayMicroseconds(Time * (1-dutyCycle) );          // wait
    }

body:
    dutyCycle = analogRead (0) / 1023;    // dutyCycle potentiometer is at analong pin 0

Dividing a small integer by a bigger integer leaves you with 0. If `analogRead()` returns 1023 you will get a result of 1. Everything else will give you 0. You need to divide by a floating point number - either `1023.0` or `1023f`.

`analogRead()` is slow. Because it is happening between every single cycle of your square wave you can expect to never get to anywhere near 100% duty cycle. There will always be a LOW period where the analog input is being read.

You should:

1. Fix your integer division problem
2. Make the ADC "free running" or interrupt driven so it doesn't interfere with your PWM generation

... Or ...

1. Fix your integer division problem
2. Make your PWM generation timer driven, either using the OC peripheral or manually with interrupts, so it doesn't interfere with the analog reading.

... Or ...

You could even do both. Make everything as asynchronous as possible leaving your loop() free to just do the heavy work of calculating the values.


message:
Why FIFO is important in camera?

I want to buy a camera module for Arduino. I came across this **[OV7670 CMOS Camera Module Lens CMOS 640X480 SCCB W/ I2C Interface Arduino][1]** and **[CMOS With AL422 3M-Bits OV7670 FIFO Camera][2]** .

I want to know what difference does FIFO makes in a camera? If I dont use a FIFO will the quality of video be compromised?

  [1]: http://www.ebay.in/itm/M071-OV7670-CMOS-Camera-Module-Lens-CMOS-640X480-SCCB-W-I2C-Interface-Arduino-/111962115189?hash=item1a11764c75:g:KZoAAOSwbwlXB3er
  [2]: http://www.ebay.in/itm/M384-640x480-CMOS-With-AL422-3M-Bits-OV7670-FIFO-Camera-STM32-Chip-Driver-Module-/112230059284?hash=item1a216ecd14:g:QccAAOSwnHZYSPa2

body:
Its not FIFO that is the issue, its the FIFO *Buffer* that you need with an Arduino.  The Arduino can't download the data from the camera at the same speed as the camera can send it.  Adding this extra buffer in lets the camera generate the data and the Arduino download it (in the same order that it was generated) at its own pace.

You might not need the FIFO buffer for faster microprocessors, but you do need it for the Arduinos.  You could get your own buffer and rig that up, but for a few extra bucks let them do it for you.


message:
Stepper and Line tracker

I am making a program which will use stepper motors and a line tracking sensor. The idea is that when the linetracker detects a black surface both steppers must move forward, and when the linetrackers is not detecting black surface it should scan the surface for a black surface.

I made some code which makes the robot move forward if the linetracker has a set value. The problem is that when I implement the code for the line-tracker. My steppers are going to run very laggy probably because the arduino is constantly scanning if the value of the linetracker is below 500.

My question is, is there a way to program the line tracker without having it interfere on my stepper motors? (The stepper motors run smooth without the linetracker)

    #include <RedBot.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    //Code voor de LCD
    #define I2C_ADDR       0x3F // Define I2C Address (use i2c scanner if necessary)
    #define BACKLIGHT_PIN  3
    #define En_pin         2
    #define Rw_pin         1
    #define Rs_pin         0
    #define D4_pin         4
    #define D5_pin         5
    #define D6_pin         6
    #define D7_pin         7
    #define LED_OFF        0

    #define LED_ON         1
    //Hier worden de eigen functies gemaakt door HEX code
    uint8_t battery_1[8]=   {0xe,0x1b,0x11,0x11,0x11,0x11,0x11,0x1f};
    uint8_t battery_2[8]=   {0xe,0x1b,0x11,0x11,0x11,0x11,0x1f,0x1f};
    uint8_t battery_3[8]=   {0xe,0x1b,0x11,0x11,0x11,0x1f,0x1f,0x1f};
    uint8_t battery_4[8]=   {0xe,0x1b,0x11,0x11,0x1f,0x1f,0x1f,0x1f};
    uint8_t battery_5[8]=   {0xe,0x1b,0x11,0x1f,0x1f,0x1f,0x1f,0x1f};
    uint8_t battery_6[8]=   {0xe,0x1b,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f};
    uint8_t battery_7[8]=   {0xe,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f};
    LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

    RedBotSensor left_sen    =    RedBotSensor(A3);
    RedBotSensor right_sen   =    RedBotSensor(A2);
    int lineStandard         =    800;

    void setup()
    {
      scherm();
      //stepper 1
      pinMode(13,OUTPUT);   // Step
      pinMode(12,OUTPUT);   // Dir
      //stepper 2
      pinMode(11,OUTPUT);   //Step 2
      pinMode(10,OUTPUT);   //Dir 2
      Serial.begin(9600);
      Serial.println("IR Sensor Readings:: ");
      //delay(500);
    }

    void loop()
    {
      Serial.print(left_sen.read());
      Serial.print("\t");
      Serial.print(right_sen.read());
      Serial.println();

      if(right_sen.read() > lineStandard)
        {
          left();
        }

      else if(left_sen.read() > lineStandard)
        {
          right();
        }

      if((left_sen.read() > lineStandard) && (right_sen.read() > lineStandard) )
        {
          Stop ();
        }

      else
        {
          forward();
        }
    }

    void right()
    {
      //stepper 1
      digitalWrite(13,HIGH);
      delayMicroseconds(1500);
      digitalWrite(13,LOW);
      delayMicroseconds(1500);
      //stepper 2
      digitalWrite(11,LOW);
      delayMicroseconds(1500);
      //Oranje lampje, rechter kant
      //digitalWrite(3,HIGH);
    }
    void Stop ()
    {
      digitalWrite(13, LOW);
      delay(1500);
      digitalWrite(11, LOW);
      delay(1500);
      //Rood lampje aansturen
      //digitalWrite(2,HIGH);
    }
    void left()
    {
      //stepper 1
      digitalWrite(11,HIGH);
      delayMicroseconds(1500);
      digitalWrite(11,LOW);
      delayMicroseconds(1500);
      //stepper 2
      digitalWrite(13,LOW);
      delayMicroseconds(1500);
      //Oranje lampje, linker kant
      //digitalWrite(4,HIGH);
    }
    void forward()
    {
      //stepper 1
      digitalWrite(13,HIGH);
      delayMicroseconds(1500);
      digitalWrite(13,LOW);
      delayMicroseconds(1500);
      //stepper 2
      digitalWrite(11,HIGH);
      delayMicroseconds(1500);
      digitalWrite(11,LOW);
      delayMicroseconds(1500);
      //Groen lampje sturen
      //digitalWrite(1,HIGH);
    }

    void scherm()
    {
      lcd.begin(16,2);
      lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
      lcd.setBacklight(LED_ON);
      //Hier worden de eigen symbolen benoemd
      lcd.createChar(1, battery_1);
      lcd.createChar(2, battery_2);
      lcd.createChar(3, battery_3);
      lcd.createChar(4, battery_4);
      lcd.createChar(5, battery_5);
      lcd.createChar(6, battery_6);
      lcd.createChar(7, battery_7);
      lcd.home();
      lcd.print("Batterij Status");
      lcd.setCursor(0, 1);
      //Schrijf de batterij icoontjes naar het LCD
      lcd.write(1);
      lcd.write(2);
      lcd.write(3);
      lcd.write(4);
      lcd.write(5);
      lcd.write(6);
      lcd.write(7);
    }

body:
You could use a driver for stepper motors, so you can control the motors using PWM. You call the PWM from Arduino using analogWrite(). After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() ([Read this link from the Arduino page][1]). This will help you in your project, and maybe find the solution to your problems when reading the sensor at the same time. An advantage of using PWM is that you can also made smoother movement for your robot when it is crossing or finding its way.

I also recommend using two sensors (I suppose you're using IR), so if you want to track the black surface and there is a turn, one of the sensors will be detecting the line, and the other one wont. That way you can assume which way should the robot turn, making it more efficient.

  [1]: https://www.arduino.cc/en/Reference/AnalogWrite


body:
> is there a way to program the line tracker without having it interfere on my stepper motors?

you are simply generating a pwm signal to drive your steppers. So make that generation in the background, through a timer isr for example.

Thus your main loop() will just be doing the low priority stuff.


message:
8 bit arduinos: What happens to the data in registers during a function call? During an interupt?

If I have one function that uses registers heavily calling another that does the same thing, what happens?  Does the data get destroyed?  What, then, would happen on return to the first function?  Is this different for interrupt handlers?

body: The compiler is capable of analyzing which registers are used by the function or ISR, so it generates prologue and epilogue code that saves the registers on the stack on entry and restores them on exit.


message:
Problem using HC-12 graphical configuration utility, invalid responses

I'm trying to use this utility [first time] to config a pair of HC-12s to a different channel, as I already have the default address in use.  It's a very handy utility, though I can find almost no reference to it via Google.

I found reference to the command here:
http://www.thebackshed.com/forum/forum_posts.asp?TID=8246&PN=1

When I use to change the channel, i get 5 error messages of the form:
invalid response(1),
invalid response(3.2),
invalid response(3.3),
invalid response(3.4),
invalid response(3.5)

I am running on Windows 10 x6, using a standard USB cable to an Uno.
The wiring config is as follows:
VCC to 5v,
GND to GND,
RXD to pin 4,
TXD to pin 5,
Set to pin 6

I've also tried connecting the Set pin to GND, as I don't know whether this is necessary or not.

The board also has an 1N4007 diode in series with the power line, and a 1000uf capacitor twixt 5v and GND.  Nothing else.

There is a sample program at:
http://www.allaboutcircuits.com/projects/understanding-and-implementing-the-hc-12-wireless-transceiver-module/

that should accomplish the same function via use of line commands and I shall try that next.  However, the configuration utility is so handy that I would like to have it in my kit of useful tools.

Seeking:
Assistance with the graphical configuration utility by someone who knows more than I, or perhaps a better alternative.

body:
the 'SET' pin needs to be connected to ground to place (and keep) the HC-12 in setup mode. when this is done you should be able to click on the "check configuration" button and receive a popup response containing the device's current configuration.

if the popup response contains no configuration data then either the HC-12 is not in setup mode ('SET' pin not grounded), or the usb to serial bridge you are using is not working. check the bridge by disconnecting the HC-12 and shorting together TxD and RxD on the bridge. you can use any terminal emulator to check loopback is working.

feel free to join the backshed forums and ask further questions about the HC-12.

cheers,
robert rozee
(author of the HC-12 config utility)


message:
Connect 9 V battery to Arduino Mega 2560 directly?

Is it safe to connect a 9 volt battery to an Arduino Mega 2560 directly to power it?

body:
Yes. On [this](https://www.arduino.cc/en/Main/ArduinoBoardMega2560) page, you can see that you can safely connect 7-12V to the VIN pin.

Furthermore, you can simultaneously connect the USB; your Arduino will automatically draw power from the appropriate source.

Note that the power supply jack pin is connected to the Vin pin through a diode. Do **not** connect a battery *and* an external power supply, since a sufficiently high power supply voltage will try to charge your battery, which may be bad news for the battery.


body:
**DO NOT CONNECT IT TO Vcc, CONNECT IT TO VIn.**

By connecting it to VIn, your 9V will go from the battery, though the VReg, and then to your Arduino. This is what you **HAVE** to do. By connecting it directly to the Arduino Vcc pin, you are basicly frying it.

Note that once the battery has gone bellow 7V, it might start getting unsafe because you are not giving the Arduino enough power.


body:
Yes.

Batteries are acceptable power sources for the Arduino Mega and other Arduino boards.  I've used them for years for various applications where access to AC is inconvenient, impractical, or nearly impossible.

The [Mega page on the Arduino site](https://www.arduino.cc/en/Main/ArduinoBoardMega)  also explicitly permits battery power.

**Helpful Guidelines**

Here are some important criteria to meet.

 - The Voltage is within the published range for the Arduino model you are using, which is 7 to 12 Volts DC for the Mega 2560
 - The positive of the battery supply connected to Vin (NOT any of the other power pins)
 - The negative of the battery supply is connected to Gnd
 - Critical applications don't run under the assumption that the battery will never drop below the required 7 Volts
 - The header is never plugged in backwards or in the wrong location, which would likely damage the Arduino circuitry

**Connection Safety Using Plug and Jack**

If you are connecting and disconnecting the Arduino from your battery frequently or you just want .

See the Power section of the page to make sure you never plug in the header wrong, you can connect your battery supply to the Arduino board's [existing power jack](http://forum.arduino.cc/index.php?topic=4892.0).  When connecting a battery supply to an Arduino compatible plug, you can ensure that the plug's inner conductor is positive in Voltage relative to the outer sheath using a Voltmeter.

**Battery Use in Robotics and Flight Control**

A 9V battery will eventually drop in Voltage below 7V, upon which the operation of the board may fail at any time, so you may want to add more 9V batteries in parallel to extend your battery supply's life 1.

Another approach common in robotics or flight control applications, to preemptively avoid erratic behavior as the battery drains below operational thresholds, is to use the low voltage detection features of the CPU.  The Atmel CPU used by the Arduino Mega 2560 has a [Brown-Out Detection feature](http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf).  The Atmel CPU for the Due and other boards have under-voltage detection too.

A simpler approach for critical applications is a resistor divider on an analog input is another related approach.

.....

[1] Batteries may vary in Voltage when purchased, but some small variance above or below 9V hurts neither the batteries nor the Arduino.  They will equalize themselves without dissipating (wasting) much energy, so you will get close to N times the battery life, where N is the number of 9V batteries in parallel.  See this [Electronics StackExchange Q&A](https://electronics.stackexchange.com/questions/177204/will-connecting-two-batteries-in-parallel-increase-current-drawn-in-simple-led-c) and this [battery company article](http://www.zbattery.com/Connecting-Batteries-in-Series-or-Parallel) for more information.


message:
Two signal with delay

I have a two pins for two blinks leds but I need delay the second signal from first. I start the first signal and I need start the second signal 50ms later. The first signal is 500ms HIGH and 500ms LOW, and the second signal is 400ms LOW and 600ms HIGH. If I start the second signal 50ms later, I can center the high period of the first signal with the low period of the second signal.

This is my code:

 long DelaySecondSignal = 50;
 int A = 1;

 while (A == 1)
 {
  long millis_actuales = millis();

   //Control Salida_A
   if (millis_actuales - TiempoTranscurrido_SalidaA > (Estado_SalidaA ? 500 : 400)) {
    digitalWrite(SalidaA, Estado_SalidaA = !Estado_SalidaA);
    TiempoTranscurrido_SalidaA = millis_actuales;
   }

   if (millis_actuales > DelaySecondSignal)
   {
    //Control Salida_B
    if (millis_actuales - TiempoTranscurrido_SalidaB > (Estado_SalidaB ? 500 : 600)) {
     digitalWrite(SalidaB, Estado_SalidaB = !Estado_SalidaB);
     TiempoTranscurrido_SalidaB = millis_actuales;
    }
   }
 }

TiempoTranscurrido_?? is a int and Estado_Salida? is a boolean.

I need start the second signal with 50ms of delay but "if (millis_actuales > DelaySecondSignal)" no work.

Thanks.

body:
Your problem is that you are treating both signal separately. Instead you need to think about the *events* of turning LEDs on and off and where they lie on a *combined* timeline:

         0    100   200   300   400   500   600   700   800   900  1000
         |-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|
         ^  ^                       ^  ^
      1 on  2 off                2 on  1 off
      1: ooooooooooooooooooooooooooooooo
      2: oooo                       oooooooooooooooooooooooooooooooooo

You see how I have looped the time around so that the turning off of the second signal, which would normally come at 1050ms, in fact comes at 50ms. By just working in a single 1000ms block of time as a loop things become much simpler.

You can do it now with just a simple set of delays, now you have it laid out in a single timeline like that:

    void loop() {
        digitalWrite(led1, HIGH);
        delay(50);
        digitalWrite(led2, LOW);
        delay(400);
        digitalWrite(led2, HIGH);
        delay(50);
        digitalWrite(led1, LOW);
        delay(500);
    }

All the `delay()` calls add up to 1000ms and it keeps looping around.

If you want to make it non-blocking you should set it up with a small finite state machine. There are 4 steady states which are the four spaces between the events on the timeline. There are 4 transitions, which are the events on the timeline.  So you:

Start in state 0 with both LEDs on (which is how they are at the start of the timeline).

* 0: When 50ms have passed turn off LED 2 and move to state 1.
* 1: When 400ms have passed turn on LED 2 and move to state 2.
* 2: When 50ms have passed turn off LED 1 and move to state 3.
* 3: When 500ms have passed turn on LED 1 and move to state 0.


body:
I'd just base everything of `millis`.

<!-- language: c -->

    int A = 1;

    while (A == 1)
    {
        int phase = millis() % 1000;// modulo 1 second

        // turn on A for the first 500ms of a period, and off for the rest
        if( phase<500 )
            digitalWrite(SalidaA, HIGH);
        else
            digitalWrite(SalidaA, LOW);

        // turn on B for the first 50ms, and last 550ms of a period, and off for the rest
        if( phase<50 || phase>=450 )
            digitalWrite(SalidaB, HIGH);
        else
            digitalWrite(SalidaB, LOW);

    }


message:
Array variable name changes from readings1 to readings2

I've been using two MB1240 Ultrasonic Sensors with analogRead, and have found that after using bubble sort, the array is found in array readings2, and not readings1. This is important because I would like to find the distance from each sensor.

Below is the code I've put together that uses buttons to determine when each sensor should be triggered.

    const int anPin1 = 1;
    const int anPin2 = 2;

    const int triggerPin = 2;
    long anVolt1, anVolt2;

    // button Pins
    const int buttonPin1 = 11;
    const int buttonPin2 = 13;

    int buttonState1;
    int buttonState2;
    int lastButtonState1 = false;
    int lastButtonState2 = false;

    long lastDebounceTime1 = 0;
    long lastDebounceTime2 = 0;
    long debounceDelay = 50; //ms

    // initialise averaging array
    const int numberOfReadings = 10; // reasonable DOF
    long readings1[numberOfReadings];
    long readings2[numberOfReadings];
    long median;

    void setup() {
      Serial.begin(9600);
      pinMode(triggerPin,OUTPUT);
      pinMode(buttonPin1, INPUT);
      pinMode(buttonPin2, INPUT);
      delay(200); // Datasheet: Sensors require 175 ms to calibrate
    }

    void start_sensor(){
      digitalWrite(triggerPin,HIGH);
      delay(10);
      digitalWrite(triggerPin,LOW);
    }

    long read_sensor1(){
      //Used to read in the analog voltage output that is being sent by the XL-MaxSonar device.
      //Scale factor is (Vcc/1024) per centimeter. A 5V supply yields ~4.9mV/cm for standard range sensors
      anVolt1 = analogRead(anPin1);
      return anVolt1;
    }

    long read_sensor2(){
      anVolt2 = analogRead(anPin2);
      return anVolt2;
    }

    void printall(long readings[]) {
      int med = numberOfReadings/2;
      median = (readings[med-1] + readings[med])/2;

      Serial.print("Sensor: ");
      for (int i = 0; i < numberOfReadings; i++) {
        Serial.print(readings[i]);
        Serial.print("cm ");
      }
      Serial.println();

      Serial.print("Median: ");
      Serial.print(median);
      Serial.println(" cm");
    }

    void loop () {
      int reading1 = digitalRead(buttonPin1);
      int reading2 = digitalRead(buttonPin2);

      // for noise
      if (reading1 != lastButtonState1) {
        lastDebounceTime1 = millis();
      }

      // for noise
      if (reading2 != lastButtonState2) {
        lastDebounceTime2 = millis();
      }

      if ((millis() - lastDebounceTime1) > debounceDelay) {
        if (reading1 != buttonState1) {
          buttonState1 = reading1;
          if (buttonState1 == HIGH) {
            for (int i = 0; i < numberOfReadings; i++){
             start_sensor();
              readings1[i] = read_sensor1();
              delay(150); // From datasheet: Period = 99ms
            }

                **// bubble sort with flag
            for (int i = 0; i < sizeof(readings1)-1; i++) {
                bool flag = true;
                for (int j = 1; j < sizeof(readings1)-1; j++) {
                    if (readings1[j-1] > readings1[j]) {
                        int t = readings1[j-1];
                        readings1[j-1] = readings1[j];
                        readings1[j] = t;
                        flag = false;
                    }
                }
                if (flag) break;
            }
           printall(readings1);**
          }
        }
      }

      lastButtonState1 = reading1;

      if ((millis() - lastDebounceTime2) > debounceDelay) {
        if (reading2 != buttonState2) {
          buttonState2 = reading2;
          if (buttonState2 == HIGH) {
            for (int i = 0; i < numberOfReadings; i++) {
              start_sensor();
              readings2[i] = read_sensor2();
              delay(150);
            }
           printall(readings2);
          }
        }
      }
      lastButtonState2 = reading2;

      //clear previous readings
      memset(readings1, 0, sizeof(readings1));
      memset(readings2, 0, sizeof(readings2));
    }
Scenario: I have clicked the first button to return a reading from the first sensor, and I am expecting the results to be stored then sorted in array readings1. After the bubble sort, if I enter printall(readings1), it returns an array of zeros, but if I use a printall(readings2), it returns the sorted array I expected.

I can't find where I'm going wrong with this one, any help would be greatly appreciated. Thank you!

body:
>     for (int j = 1; j < sizeof(readings1)-1; j++) {

`sizeof(readings1)` is **not** the number of elements in the array, it is the size of the array in bytes (in your case, 40). You are exceeding the bounds of the array. You know the number of items (`numberOfReadings`) - why not use that?


message:
How many Ultrasonic sensors can be connected to an Arduino Uno R3?

How many Ultrasonic sensors (HC SR04 ) can be connected to an Arduino Uno R3 board?

body:
If you look into any example sketch, like this from sparkfun:

<!-- language: c -->

    /**
     * HC-SR04 Demo
     * Demonstration of the HC-SR04 Ultrasonic Sensor
     * Date: August 3, 2016
     *
     * Description:
     *  Connect the ultrasonic sensor to the Arduino as per the
     *  hardware connections below. Run the sketch and open a serial
     *  monitor. The distance read from the sensor will be displayed
     *  in centimeters and inches.
     *
     * Hardware Connections:
     *  Arduino | HC-SR04
     *  -------------------
     *    5V    |   VCC
     *    7     |   Trig
     *    8     |   Echo
     *    GND   |   GND
     *
     * License:
     *  Public Domain
     */

    // Pins
    const int TRIG_PIN = 7;
    const int ECHO_PIN = 8;

    // Anything over 400 cm (23200 us pulse) is "out of range"
    const unsigned int MAX_DIST = 23200;

    void setup() {

      // The Trigger pin will tell the sensor to range find
      pinMode(TRIG_PIN, OUTPUT);
      digitalWrite(TRIG_PIN, LOW);

      // We'll use the serial monitor to view the sensor output
      Serial.begin(9600);
    }

    void loop() {

      unsigned long t1;
      unsigned long t2;
      unsigned long pulse_width;
      float cm;
      float inches;

      // Hold the trigger pin high for at least 10 us
      digitalWrite(TRIG_PIN, HIGH);
      delayMicroseconds(10);
      digitalWrite(TRIG_PIN, LOW);

      // Wait for pulse on echo pin
      while ( digitalRead(ECHO_PIN) == 0 );

      // Measure how long the echo pin was held high (pulse width)
      // Note: the micros() counter will overflow after ~70 min
      t1 = micros();
      while ( digitalRead(ECHO_PIN) == 1);
      t2 = micros();
      pulse_width = t2 - t1;

      // Calculate distance in centimeters and inches. The constants
      // are found in the datasheet, and calculated from the assumed speed
      //of sound in air at sea level (~340 m/s).
      cm = pulse_width / 58.0;
      inches = pulse_width / 148.0;

      // Print out results
      if ( pulse_width > MAX_DIST ) {
        Serial.println("Out of range");
      } else {
        Serial.print(cm);
        Serial.print(" cm \t");
        Serial.print(inches);
        Serial.println(" in");
      }

      // Wait at least 60ms before next measurement
      delay(60);
    }

You can see it is used only two pins. So, as long as you **can provide power** to sensors and pins to it, you can have as much as you like. You can even expand with more IO pins using other electronics or go into some kind of multiplexing.


message:
What is micro C in a circuit diagram?

This is probably a simple question but I am a beginner with these things. What does the micro C part of the circuit diagram mean? The diagram is from the datasheet of the tssp77038 IR receiver. Does it want there to be a capacitor on the output?
(http://www.farnell.com/datasheets/1915248.pdf?_ga=1.234529246.1943069395.1480959857)

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

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

body: It means "Micro Controller" - you know it as "Arduino".


message:
Why does this code not respond promptly to changes in the LDR reading?

So, I wrote some simple code like this :

    void setup() {
      strip.begin();
      strip.show(); // Initialize all pixels to 'off'
      Serial.begin (9600);
    }

    void loop() {
      LDRValue = analogRead(LDRSensor);
      Serial.println(LDRValue);
      delay(50);
    }

The line will print the value of LDR sensor simultaneously, but when I add this "if" condition inside the loop :

     if (LDRValue < 100) {
       colorWipe(strip.Color(255, 0, 0), 50);
       colorWipe(strip.Color(0, 255, 0), 50);
       colorWipe(strip.Color(0, 0, 255), 50);
       colorWipe(strip.Color(0, 0, 0, 255), 50);
       theaterChase(strip.Color(127, 127, 127), 50);
       theaterChase(strip.Color(127, 0, 0), 50);
       theaterChase(strip.Color(0, 0, 127), 50);
       rainbow(20);
       rainbowCycle(20);
       theaterChaseRainbow(50);
      }

the LDR  value only printed once..

Is it a wrong "if" condition code ? I know it's kinda lame, but please give me some starting point, doesn't need to be fancy just a small lead will do, thanks!

***edit :*** [complete library][1]

  [1]: https://github.com/adafruit/Adafruit_NeoPixel/blob/master/examples/strandtest/strandtest.ino

body:
I'm going to lever off gre_gor's comment on the question.

The code you are calling (for example, `rainbow`) has delays in it:

    void rainbow(uint8_t wait) {
      uint16_t i, j;

      for(j=0; j<256; j++) {
        for(i=0; i<strip.numPixels(); i++) {
          strip.setPixelColor(i, Wheel((i+j) & 255));
        }
        strip.show();
        delay(wait);
      }
    }

So we can see straight away that calling `rainbow(20);` is going to take at least 20 x 256 ms (256 iterations of the loop with a 20 ms delay) plus more because of whatever else it does. That is over 5 seconds already!

Then you call `rainbowCycle(20);` and then `theaterChaseRainbow(50);` so you won't get back to the main loop for a while.

How to fix? Well, it isn't just a case of adding a line or two. One solution is to rewrite without delays, but instead have a state machine.

An alternative would be to test the sensor in each loop. Let's guess your objective is to stop the display if the LDR gives a higher reading. You could copy/paste the functions in question, but test the LDR inside them, eg.

    void rainbow(uint8_t wait) {
      uint16_t i, j;

      for(j=0; j<256; j++) {

        int LDRValue = analogRead(LDRSensor);   // <--- add these 3 lines
        if (LDRValue >= 100)
           return;

        for(i=0; i<strip.numPixels(); i++) {
          strip.setPixelColor(i, Wheel((i+j) & 255));
        }
        strip.show();
        delay(wait);
      }
    }

---

## Suggested improvement to example

The code below uses a technique of supplying a "callback function" to the functions that do the pixel displays. I modified the Adafruit example to show the idea:

    #include <Adafruit_NeoPixel.h>
    #ifdef __AVR__
      #include <avr/power.h>
    #endif

    #define PIN 6

    typedef bool (*AbortFunction) ();

    // Parameter 1 = number of pixels in strip
    // Parameter 2 = Arduino pin number (most are valid)
    // Parameter 3 = pixel type flags, add together as needed:
    //   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
    //   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
    //   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
    //   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
    //   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, PIN, NEO_GRB + NEO_KHZ800);

    // IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
    // pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
    // and minimize distance between Arduino and first pixel.  Avoid connecting
    // on a live circuit...if you must, connect GND first.

    void setup() {
      // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
      #if defined (__AVR_ATtiny85__)
        if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
      #endif
      // End of trinket special code

      strip.begin();
      strip.show(); // Initialize all pixels to 'off'
    }

    // function prototypes
    void colorWipe(uint32_t c, uint8_t wait, AbortFunction fAbort = NULL);
    void rainbow(uint8_t wait, AbortFunction fAbort = NULL);
    void rainbowCycle(uint8_t wait, AbortFunction fAbort = NULL);
    void theaterChase(uint32_t c, uint8_t wait, AbortFunction fAbort = NULL);
    void theaterChaseRainbow(uint8_t wait, AbortFunction fAbort = NULL);

    const byte LDRSensor = 0;

    bool checkLDR ()
      {
      int LDRValue = analogRead(LDRSensor);
      return LDRValue > 100;
      }

    void loop() {
      // start with black
      colorWipe(strip.Color(0, 0, 0), 0); // Black

      // Some example procedures showing how to display to the pixels:
      colorWipe(strip.Color(255, 0, 0), 50, checkLDR); // Red
      colorWipe(strip.Color(0, 255, 0), 50, checkLDR); // Green
      colorWipe(strip.Color(0, 0, 255), 50, checkLDR); // Blue
    //colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
      // Send a theater pixel chase in...
      theaterChase(strip.Color(127, 127, 127), 50, checkLDR); // White
      theaterChase(strip.Color(127, 0, 0), 50, checkLDR); // Red
      theaterChase(strip.Color(0, 0, 127), 50, checkLDR); // Blue

      rainbow(20, checkLDR);
      rainbowCycle(20, checkLDR);
      theaterChaseRainbow(50, checkLDR);
    }

    // Fill the dots one after the other with a color
    void colorWipe(uint32_t c, uint8_t wait, AbortFunction fAbort) {
      for(uint16_t i=0; i<strip.numPixels(); i++) {
        if (fAbort && fAbort ())
          return;
        strip.setPixelColor(i, c);
        strip.show();
        delay(wait);
      }
    }

    void rainbow(uint8_t wait, AbortFunction fAbort) {
      uint16_t i, j;

      for(j=0; j<256; j++) {
        for(i=0; i<strip.numPixels(); i++) {
          if (fAbort && fAbort ())
            return;
          strip.setPixelColor(i, Wheel((i+j) & 255));
        }
        strip.show();
        delay(wait);
      }
    }

    // Slightly different, this makes the rainbow equally distributed throughout
    void rainbowCycle(uint8_t wait, AbortFunction fAbort) {
      uint16_t i, j;

      for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
        if (fAbort && fAbort ())
          return;
        for(i=0; i< strip.numPixels(); i++) {
          strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
        }
        strip.show();
        delay(wait);
      }
    }

    //Theatre-style crawling lights.AbortFunction fAbort
    void theaterChase(uint32_t c, uint8_t wait, AbortFunction fAbort) {
      for (int j=0; j<10; j++) {  //do 10 cycles of chasing
        for (int q=0; q < 3; q++) {
          if (fAbort && fAbort ())
            return;
          for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
            strip.setPixelColor(i+q, c);    //turn every third pixel on
          }
          strip.show();

          delay(wait);

          for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
            strip.setPixelColor(i+q, 0);        //turn every third pixel off
          }
        }
      }
    }

    //Theatre-style crawling lights with rainbow effect
    void theaterChaseRainbow(uint8_t wait, AbortFunction fAbort) {
      for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
        for (int q=0; q < 3; q++) {
          if (fAbort && fAbort ())
            return;
          for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
            strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
          }
          strip.show();

          delay(wait);

          for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
            strip.setPixelColor(i+q, 0);        //turn every third pixel off
          }
        }
      }
    }

    // Input a value 0 to 255 to get a color value.
    // The colours are a transition r - g - b - back to r.
    uint32_t Wheel(byte WheelPos) {
      WheelPos = 255 - WheelPos;
      if(WheelPos < 85) {
        return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
      }
      if(WheelPos < 170) {
        WheelPos -= 85;
        return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
      }
      WheelPos -= 170;
      return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
    }

The important addition is to add another optional argument `AbortFunction fAbort` to each function call. The default is NULL, in which case the function behaves the same as before. However, if supplied, the function is called. If it returns `true` then the display function exits (thus avoiding the delays), like this:

    if (fAbort && fAbort ())
      return;

The first test is "does the function exist?" and if so, the second test calls the function and checks to see if it returns true or false.

The modified example shows the scrolling patterns on the NeoPixels, provided A0 returns 100 or less. The function that does this is here:

    bool checkLDR ()
      {
      int LDRValue = analogRead(LDRSensor);
      return LDRValue > 100;
      }

That function is passed as an argument to the other functions, eg.

    rainbow(20, checkLDR);

I have a [page about writing callback functions](http://www.gammon.com.au/callbacks).


message:
GSM module connected with arduino uno giving garbage values in response

I connected a GSM module with the Arduino UNO. The connections are as follows:

> Gnd of gsm -----> Gnd of arduino
>
> TX of gsm  -----> pin 9 of arduino
>
> Rx of gsm  -----> pin 10 of arduino

GSM is powered from a 9V-1Amp wall adapter.

The GSM is performing according to all the `AT` commands (like making a voice call, hanging a call, answering a call) which are given, but it is displaying garbage values on serial monitor in response.

Here is the code:

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

    void setup() {
        Serial.begin(115200);
        myserial.begin(9600);
        myserial.println("ATDXXXXXXXXXX;");
        delay(30000);
        myserial.println("ATH");
    }

    void loop() {
        if (myserial.available()>0){
            Serial.println(myserial.read());
        }
    }

What could be reasons for the GSM to output garbage values and how can I resolve it?

body:
        Serial.println(myserial.read());

`myserial.read()` returns an integer. That integer is either the ASCII code of the next character in the buffer, or -1 if there is no character to read.

You then print that integer, each one on its own line.

So the response "OK\r\n" from, say, "AT\r\n" would look like:

    79
    75
    13
    10

Instead you need to `write` the data, not `print` it:

    Serial.write(myserial.read());

Also, the way you have written your code, you will get no response for 30 seconds - that is, until everything has already happened. Only after it has all finished will you get some feedback - and that may not be complete since you may overrun the buffer depending on what the modem sends.


message:
Random numbers recived by wifi shield

So I am sending a web request to a server, but for some reason the result is the number: `728484804749464932504848327975131083101114118101114583213106897116101583284117101443250483268101993250484954325049585054585249327177841310671111101161011101164584121112101583211610112011647104116109108131067111110116101110116457610111010311`

Any ideas?

    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C Lcd(0x27, 16, 6);

    #include <SPI.h>
    #include <WiFi.h>

    char ssid[] = "AESRO2-2.4G";
    char password[] = "EA8TDKNFGE";

    int status = WL_IDLE_STATUS;

    WiFiClient client;

    String serverReturn;

    String page[]
    {
      "Flashlight",
      "Message",
      "S.O.S"
    };
    void displayPage(int pageNumber)
    {
      Lcd.clear();
      Lcd.print(page[pageNumber]);

      Lcd.setCursor(0,1);
      Lcd.print("[Open]");
      Lcd.setCursor(10, 1);
      Lcd.print("[Next]");
    }
    int currentPage = 0;
    int lastPage = 1;

    void setup()
    {
      Serial.begin(9600);
      pinMode(6, OUTPUT);
      pinMode(8,OUTPUT);

      Lcd.begin();

      Lcd.print("BrickOS V5.0.0");
      digitalWrite(6, HIGH);
      delay(300);
      digitalWrite(6, LOW);

      delay(1000);

      if(WiFi.status() == WL_NO_SHIELD)
      {
        Lcd.clear();
        Lcd.print("No wifi shield");

        while(true);
      }

      String fv = WiFi.firmwareVersion();
      if(fv != "1.1.0")
      {
        String secline = fv += "->1.1.0";
        Lcd.clear();
        Lcd.print("Firmware update");
        Lcd.setCursor(0,1);
        Lcd.print(secline);

        while(true);
      }

      while(status != WL_CONNECTED)
      {
        Lcd.clear();
        Lcd.print("Connecting to");
        Lcd.setCursor(0, 1);
        Lcd.print("network...");

        status = WiFi.begin(ssid, password);

        delay(3000);
      }

      Lcd.clear();
      Lcd.print("Connected to:");
      Lcd.setCursor(0, 1);
      Lcd.print(ssid);
      delay(1000);
    }

    void loop()
    {
      if(lastPage != currentPage)
      {
        if(currentPage > sizeof(page))
        {
          currentPage = 0;
        }
        displayPage(currentPage);
      }
      lastPage = currentPage;

      serverReturn = "";
      while(client.available()) {
        serverReturn += client.read();
      }
      client.stop();
      if(client.connect("www.nightfall.huskyclick.info", 80))
      {
        client.println("GET /msg.php?action=check&ID=1 HTTP/1.1");
        client.println("Host: nightfall.huskyclick.info");
        client.println();
      }
      else
      {
        Lcd.clear();
        Lcd.print("Failed to check");
        Lcd.setCursor(0, 1);
        Lcd.print("for messages");
      }

      Serial.println(serverReturn);

      if(serverReturn != "false" && serverReturn != "")
      {
        digitalWrite(8, HIGH);

        Lcd.clear();
        Lcd.print("Message received!");

        digitalWrite(6, HIGH);
        delay(500);
        digitalWrite(6, LOW);

        delay(1000);

        Lcd.clear();
        Lcd.print(serverReturn);

        delay(5000);
      }

      delay(5000);
    }

body:
The fault lies here:

    while(client.available()) {
      serverReturn += client.read();
    }

`client.read()` returns an integer. That integer is either the ASCII code of the next character in the buffer, or -1 if there are no characters in the buffer left to read.

You then append that integer to the end of a `String` which gets converted to the ASCII representation of that integer before being appended.

So the string `HTTP`, for instance, which is ASCII characters 72, 84 (twice) and 80 ends up as "72848480".

Instead you need to cast the integer to a char before appending:

    serverReturn += (char)client.read();

Or better still don't use any `String` variables at all and parse the data as it comes in pulling out any information you need to at the time it arrives.


message:
Serial - Send data to Arduino while Arduino sending data

Arduino send data to PC each iteration. When I'm trying to send data to Arduino while receiving data from it, it takes too long. `Serial.available()` returns false even I sent data from PC. But if I add delay like 20-30 ms, problem fixed. Can't I use serial simultaneously?

PS: It's Arduino mega and I'm using http://www.teuniz.net/RS-232/ library for serial communication.

Example code:

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

    void loop(){

      if(Serial.available())
        Serial.write("goodbye", 7);
        Serial.write("hello", 5);
      }

In this situation, it takes long time to write "goodbye" after I sent data to Arduino.

body:
Following up on what Nick Gammon says, don't try to use the serial output to debug serial.  Perhaps try using the built-in LED instead; you can use an oscilloscope to find out how much time it is spending reading characters.

The following is how I've been reading a line at a time using non-blocking operations:

    const int SERIAL_BUFFER_LENGTH = 100;

    // The +1 assures we'll always have room for null termination
    char g_serial_buffer[SERIAL_BUFFER_LENGTH+1];
    int g_char_count;         // index into serial buffer

    void setup() {
      Serial.begin(9600);  // or 115200 if your host supports it
      pinMode(LED_BUILTIN, OUTPUT);
      digitalWrite(LED_BUILTIN, LOW);
      g_char_count = 0;
    }

    void loop() {
      while(Serial.available() > 0) {
        digitalWrite(LED_BUILTIN, HIGH);
        char c = Serial.read();   // won't block because Serial.available() > 0
        if (c == '\n') {
          g_serial_buffer[g_char_count] = '\0';  // null terminate
          process_buffer(g_serial_buffer);
          g_char_count = 0;
        } else if (g_char_count < SERIAL_BUFFER_LENGTH) {
          g_serial_buffer[g_char_count++] = c;
        }
      }
      digitalWrite(LED_BUILTIN, LOW);
      Serial.print(".");
    }

    // process_buffer: do whatever it is you intended to do with a
    // line of received text...
    void process_buffer(char *buffer) {
    }


body:
Try this:

      if(Serial.available())
        while(Serial.read());
        Serial.write("goodbye", 7);
        Serial.write("hello", 5);
      }

I think you have to read what you get in the serial port.


message:
Building a GPS-controlled Camera

I've been trying to build an Arduino UNO controlled Camera using two servo motors that points in the direction of an object with a certain tag. <b>

Here's an Example: A camera is on the sideline of a gym, and the players are running around. One player has a portable GPS piece attached to him, and the camera should point in the player's direction in order to capture the player's movements along with his background. <n>

A few questions:
Would I use two different compasses in order to both record the direction and point the camera in this direction? Or would I use a GPS for the player and somehow convert the streaming data into compass direction(in which the camera will point)? <b>

In a way, what combination (Player-Camera) would I use (if I need a combination), a GPS-GPS, GPS-compass, or compass-compass?<b>

Do I actually need two location devices or just one? <b>

Thanks,
Mark

body: Take a look at the uTube site of "iforce2d". Chris has a couple of GPS projects, which use a GPS and nRF24L01 transceivers to implement a "GPS tag" and he has a model car follow the tag. He also has a ground station with a pan and tilt and a camera following his quadcopter (drone). Lots of useful stuff there.