message:
Use object of LiquidCrystal class within another class

I am quite new to C++ and hope that I don't bore you too much with my question.

I want to use an object of LiquidCrystal Class in another class called "Display_ManagerClass". I followed the instructions of the 2nd alternative in the following link:

https://arduino.stackexchange.com/questions/9296/use-object-of-other-class-within-class?newreg=5dd627937c1c4f94a0a47480f249445b

Unfortunately, I receive a linker error.

.ino-file:

    #include "Licht_Manager.h"
    #include "Display_Manager.h"
    #include "Zeit_Manager.h"

    LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7);

    void setup()
    {

     Licht_Manager.init();
     Display_Manager.init(&lcd);
    }

    void loop()
    {
     Display_Manager.showText("Hello", "World");
     while (1)
     {
      Licht_Manager.blink(1);
     }
    }

Display_Manager.h:

    #ifndef _DISPLAY_MANAGER_h
    #define _DISPLAY_MANAGER_h

    #if defined(ARDUINO) && ARDUINO >= 100
     #include "arduino.h"
    #else
     #include "WProgram.h"
    #endif

    #include <LiquidCrystal/src/LiquidCrystal.h>

    class Display_ManagerClass
    {
     protected:

     public:
      //void init();
      void init(LiquidCrystal* _p_lcd);
      void showText(String DisplayText1, String DisplayText2);
     private:
      LiquidCrystal* p_lcd;

    };

    extern Display_ManagerClass Display_Manager;

    #endif

Display_Manager.cpp:

    #include "Display_Manager.h"

    void Display_ManagerClass::init(LiquidCrystal* _p_lcd)
    {
     p_lcd = _p_lcd;
     p_lcd->clear();
    }

    void Display_ManagerClass::showText(String DisplayText1, String DisplayText2)
    {
      p_lcd->clear();
      p_lcd->setCursor(0,0);
      p_lcd->print(DisplayText1);
      p_lcd->setCursor(0,1);
      p_lcd->print(DisplayText2);
    }

    Display_ManagerClass Display_Manager;

I receive the following errors:

    Display_Manager.cpp.o:In function `Display_ManagerClass::init(LiquidCrystal*)
    Display_Manager.cpp:clear()
    Display_Manager.cpp.o:In function `Display_ManagerClass::showText(String, String)
    Display_Manager.cpp:clear()
    Display_Manager.cpp:setCursor(unsigned char, unsigned char)
    Display_Manager.cpp:setCursor(unsigned char, unsigned char)
    collect2.exe*:error: ld returned 1 exit status
    Error creating .elf

I made sure that the correct directory of the library is set up in the project properties. The library also works in the normal way, but in combination with the class it doesn't.

I work with Atmel Studio 7 in combination with VisualMicro, Arduino IDE 1.6 and Arduino Uno.

Thank you in advance.

body: You must also include `LiquidCrystal.h` in your sketch. That way the IDE will know to include it in the list of files to compile and link with your sketch.


sender: user

message:
CC3000 cannot sending post data with content length more than 104

I'm trying to post data from my Arduino due to my web server (php) through POST using the CC3000 breakout board and for some reason, data with content length more than 104 is not being sent?

I've tried posting directly with postmaster with content length value greater than 104 to verify that it wasn't my server denying the request and it wasn't. So something with the Arduino or cc3000?

Right now, my post request looks like this which works:

    POST /new/path/post.php HTTP/1.1
    Host:  www.mywebsite.com
    User-Agent: Arduino/1.0
    Connection: close
    Content-Type: application/x-www-form-urlencoded; charset=UTF-8
    Content-Length: 104

    userId=32&sscId=43&raVal=52&cvVal=62&bbvfgTempInF=723&bbvfgLevel=82345&humidity=92&lmassLevel=0283838383

And this is the one that doesn't (notice only one character difference in userId):

    POST /new/path/post.php HTTP/1.1
    Host:  www.mywebsite.com
    User-Agent: Arduino/1.0
    Connection: close
    Content-Type: application/x-www-form-urlencoded; charset=UTF-8
    Content-Length: 105

    userId=322&sscId=43&raVal=52&cvVal=62&bbvfgTempInF=723&bbvfgLevel=82345&humidity=92&lmassLevel=0283838383

And here is my full code:

    #include <Adafruit_CC3000.h>
    #include <ccspi.h>
    #include <SPI.h>
    #include <string.h>
    #include "utility/debug.h"

    // These are the interrupt and control pins
    #define ADAFRUIT_CC3000_IRQ   28  // MUST be an interrupt pin!
    // These can be any two pins
    #define ADAFRUIT_CC3000_VBAT  26
    #define ADAFRUIT_CC3000_CS    22
    // Use hardware SPI for the remaining pins
    // On an UNO, SCK = 13, MISO = 12, and MOSI = 11
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                                             SPI_CLOCK_DIVIDER); // you can change this clock speed

    #define WLAN_SSID       "mynetwork"   // cannot be longer than 32 characters!
    #define WLAN_PASS       "mypassword"
    // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
    #define WLAN_SECURITY   WLAN_SEC_WPA2

    #define IDLE_TIMEOUT_MS  10000      // Amount of time to wait (in milliseconds) with no data
                                       // received before closing the connection.  If you know the server
                                       // you're accessing is quick to respond, you can reduce this value.

    /**************************************************************************/
    /*!
        @brief  Sets up the HW and the CC3000 module (called automatically
                on startup)
    */
    /**************************************************************************/

    uint32_t ip;

    void setup(void)
    {
      Serial.begin(115200);
      Serial.println(F("Hello, CC3000!\n"));

      Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

      /* Initialise the module */
      Serial.println(F("\nInitializing..."));
      if (!cc3000.begin())
      {
        Serial.println(F("Couldn't begin()! Check your wiring?"));
        while(1);
      }

      // Optional SSID scan
      // listSSIDResults();

      Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
      if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println(F("Failed!"));
        while(1);
      }

      Serial.println(F("Connected!"));

      /* Wait for DHCP to complete */
      Serial.println(F("Request DHCP"));
      while (!cc3000.checkDHCP())
      {
        delay(100); // ToDo: Insert a DHCP timeout!
      }

      /* Display the IP address DNS, Gateway, etc. */
      while (! displayConnectionDetails()) {
        delay(1000);
      }

      ip = 0;
      // Try looking up the website's IP address
      Serial.print(WEBSITE); Serial.print(F(" -> "));
      while (ip == 0) {
        if (! cc3000.getHostByName(WEBSITE, &ip)) {
          Serial.println(F("Couldn't resolve!"));
        }
        delay(500);
      }

      cc3000.printIPdotsRev(ip);

      // Optional: Do a ping test on the website
      /*
      Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip); Serial.print("...");
      replies = cc3000.ping(ip, 5);
      Serial.print(replies); Serial.println(F(" replies"));
      */

      /* Try connecting to the website.
         Note: HTTP/1.1 protocol is used to keep the server from closing the connection before all data is read.
      */
      Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
      if (www.connected()) {
        Serial.println("Connected");
        String PostDatat = "userId=32&sscId=43&raVal=52&cvVal=62&bbvfgTempInF=723&bbvfgLevel=82345&humidity=92&lmassLevel=0283838383";

        Serial.println();
        Serial.println("POST /new/path/post.php HTTP/1.1");
        Serial.println("Host: www.mywebsite.com");
        Serial.println("User-Agent: Arduino/1.0");
        Serial.println("Connection: close");
        Serial.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        Serial.print("Content-Length: ");
        Serial.println(PostDatat.length());
        Serial.println();
        Serial.println(PostDatat);

        //HANGS HERE IF CONTENT LENGTH > 104

        www.println("POST /new/path/post.php HTTP/1.1");
        www.println("Host: www.mywebsite.com");
        www.println("User-Agent: Arduino/1.0");
        www.println("Connection: close");
        www.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        www.print("Content-Length: ");
        www.println(PostDatat.length());
        www.println();
        www.println(PostDatat);

        Serial.println();
        Serial.println("POST /new/path/post.php HTTP/1.1");
        Serial.println("Host:  www.mywebsite.com");
        Serial.println("User-Agent: Arduino/1.0");
        Serial.println("Connection: close");
        Serial.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        Serial.print("Content-Length: ");
        Serial.println(PostDatat.length());
        Serial.println();
        Serial.println(PostDatat);

        Serial.println("SENT");
      } else {
        Serial.println(F("Connection failed"));
        return;
      }

      Serial.println(F("-------------------------------------"));

      /* Read data until either the connection is closed, or the idle timeout is reached. */
      unsigned long lastRead = millis();
      while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
        while (www.available()) {
          char c = www.read();
          Serial.print(c);
          lastRead = millis();
        }
      }
      www.close();
      Serial.println(F("-------------------------------------"));

      /* You need to make sure to clean up after yourself or the CC3000 can freak out */
      /* the next time your try to connect ... */
      Serial.println(F("\n\nDisconnecting"));
      cc3000.disconnect();

    }

    void loop(void)
    {
     delay(1000);
    }

    /**************************************************************************/
    /*!
        @brief  Begins an SSID scan and prints out all the visible networks
    */
    /**************************************************************************/

    void listSSIDResults(void)
    {
      uint32_t index;
      uint8_t valid, rssi, sec;
      char ssidname[33];

      if (!cc3000.startSSIDscan(&index)) {
        Serial.println(F("SSID scan failed!"));
        return;
      }

      Serial.print(F("Networks found: ")); Serial.println(index);
      Serial.println(F("================================================"));

      while (index) {
        index--;

        valid = cc3000.getNextSSID(&rssi, &sec, ssidname);

        Serial.print(F("SSID Name    : ")); Serial.print(ssidname);
        Serial.println();
        Serial.print(F("RSSI         : "));
        Serial.println(rssi);
        Serial.print(F("Security Mode: "));
        Serial.println(sec);
        Serial.println();
      }
      Serial.println(F("================================================"));

      cc3000.stopSSIDscan();
    }

    /**************************************************************************/
    /*!
        @brief  Tries to read the IP address and other connection details
    */
    /**************************************************************************/
    bool displayConnectionDetails(void)
    {
      uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

      if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
      {
        Serial.println(F("Unable to retrieve the IP Address!\r\n"));
        return false;
      }
      else
      {
        Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
        Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
        Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
        Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
        Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
        Serial.println();
        return true;
      }
    }

So after running this code and changing the PostDatat variable to the two data being 104 char long and 105 char long, the 104 char long goes all the way through and prints the message `SENT` to the Serial monitor. But the 105 char long just hangs after the first `Serial.println()` blocks and before the "www.println(..." Has anyone had or encountered this problem or can suggest a solution to this? Thanks!

sender: assistant

body:
I've gone through the library to locate the buffer where data is stored before being transmitted and I noticed that the minimum TX buffer size is set to 130 bytes. Certain control information in the form of headers are sent along with your data to the CC3000. The CC3000 interprets these headers, strips them away and re-formats your data for transmission to your gateway. So when your 105-byte content was added to these headers, the whole packet exceeded the 130-byte buffer and so caused it to overflow, overwrite a 'magic number' at its end, that is meant to detect this condition, and cause the program to stall indefinitely; this is all by design. From `ccspi.h`:

    // The magic number that resides at the end of the TX/RX buffer (1 byte after the allocated size)
    // for the purpose of detection of the overrun. The location of the memory where the magic number
    // resides shall never be written. In case it is written - the overrun occured and either recevie function
    // or send function will stuck forever.
    #define CC3000_BUFFER_MAGIC_NUMBER (0xDE)

The value of the number itself doesnt matter; its presence/absence is what is important. So this is where your code most likely got stuck:

    /* The magic number that resides at the end of the TX/RX buffer (1 byte after the allocated size)
       * for the purpose of overrun detection. If the magic number is overwritten - buffer overrun
       * occurred - and we will be stuck here forever! */
      if (wlan_tx_buffer[CC3000_TX_BUFFER_SIZE - 1] != CC3000_BUFFER_MAGIC_NUMBER)
      {
        DEBUGPRINT_F("\tCC3000: Error - No magic number found in SpiWrite\n\r");
        while (1);  //Infinite loop; end of the road
      }

And the reason you didnt get this error message is because debug mode is disabled by default in the library. You can enable it by changing `#define DEBUG_MODE (0)` to `#define DEBUG_MODE  (1)` in `debug.h` in the `utility` folder in the library.
Note that this buffer limitation applies to incoming data, as well as outgoing data.

Now you can increase the buffer size by changing:

    #define CC3000_MINIMAL_TX_SIZE      (130 + 1)

to:

    #define CC3000_MINIMAL_TX_SIZE      (150 + 1) // buffer size is now 150 bytes

in `cc3000_common.h` in the `utility` folder in your library folder, save the file and try again.

Even if this works though, I suggest you choose a fixed chunk size for sending data, one that is reasonably below 130 bytes. What happens next time when you want to send a 200-byte string? You increase the buffer again and you deprive the rest of your sketch of valuable SRAM. What you do is pass your POST content to some function that splits the string into chunks and sends them one at a time.
Assuming you send only ASCII strings:

    #define CHUNK_SZ  80  // your chunk size

    void send_all(Adafruit_CC3000_Client * conn, const uint8_t * data, uint16_t len){
      while (len >= CHUNK_SZ){   // while the length is greater than your chunk size
        conn->write(data, CHUNK_SZ);  // write a chunk to the socket
        data += CHUNK_SZ;  // advance the pointer to the start of the next chunk
        len -= CHUNK_SZ;  // get how many bytes are left
      }
      if (len)  // send whatever remains if anything remains
        conn->write(data, len);
    }

    void loop(){
      ...

      Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
      const uint8_t[] PostDatat = "userId=32&sscId=43&raVal=52\r\n";
      send_all(&www, PostDatat, sizeof(PostDatat) - 1); // -1 is to ignore the null byte

      ...
    }

The function takes a pointer to your CC3000 socket object, a pointer to your data and the size of the data (array or not) in bytes. It should work for C strings. Note that I explicitly added `\r\n` at the end of the POST content, since `println()` isnt used here. I used the `uint8_t` type so that you can also use the function to send an arrays of `int`s or other numeric types, as long as you cast the array to `uint8_t *` and specify the length of the array in *bytes* with `sizeof()`.

Finally, try to make your chunk size as large as you can without getting too close to the limit. A large chunk size means fewer chunks, which means less overhead (remember those pesky headers) and time taken to transmit your whole request.


body: Does it print out the part "Free Ram: " If not, then I doubt its a memory problem. Not too familiar with the CC3000, but possibly related to a UART Break Condition.


message:
digitalPinToInterrupt() doesn't work

[![raindrop][1]][1]

I am working on a protection circuit with 2 raindrop sensors which would be hooked onto the arduinos 2 interrupt pins and as soon as they detect water they shut some relays off, turn a red led on and exit() the main program.

These sensors I have order are working fine as regular input pins with the following code:

    // lowest and highest sensor readings:
    const int sensorMin = 0;     // sensor minimum
    const int sensorMax = 1024;  // sensor maximum

    void setup() {
      // initialize serial communication @ 9600 baud:
      Serial.begin(9600);
    }
    void loop() {
      // read the sensor on analog A0:
     int sensorReading = analogRead(A0);
      // map the sensor range (four options):
      // ex: 'long int map(long int, long int, long int, long int, long int)'
     int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

      // range value:
      switch (range) {
     case 0:    // Sensor getting wet
        Serial.println("Flood");
        break;
     case 1:    // Sensor getting wet
        Serial.println("Rain Warning");
        break;
     case 2:    // Sensor dry - To shut this up delete the " Serial.println("Not Raining"); " below.
        Serial.println("Not Raining");
        break;
      }
      delay(1);  // delay between reads
    }

I will use the digital output not the analog but this doesn't change much. For the digital the pin is up at 5V at start and will be put to LOW once water is detected by the sensor.

I using the mega right now for breadbording but micro will be the final board.

Both the mega+micro should have 2,3 as interrupt pins:

    Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21
    Micro, Leonardo, other 32u4-based 0, 1, 2, 3, 7

I have modified the following code and tried all conditions:

    LOW to trigger the interrupt whenever the pin is low,
    CHANGE to trigger the interrupt whenever the pin changes value
    RISING to trigger when the pin goes from low to high,
    FALLING for when the pin goes from high to low.

It doesn't respond to any (the same time as I said the pin works fine as regular input).

Here in the setup I know that I am not using

    attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE);

but

    attachInterrupt(interruptPin, myISR, FALLING);

that is because the IDE doesn't recognize this function. Is there any problem with the code? If I understand interrupts correctly I don't even need to check for that if ( ISRRan ) to break off the while loop, once the interrupt comes in the ardu SHOULD be running my interrupt function and immediately run the protection code then abort.

    byte interruptPin = 0;  // your interrupt pin
    volatile boolean ISRRan = 0;  // this variable is set in your ISR to trigger a break in the while loop
    byte C = 0;  // this is just the counter var for the while loop

    void setup() {
     attachInterrupt(interruptPin, myISR, FALLING);
    }

    void myISR() {
     ISRRan = 1;
     // do other things in the ISR
    }

    void loop() {
     while ( C < 10 ) {
       if ( ISRRan ) {
         break;
       }
       //doing something inside the while loop
     C++;
     }
     // do other things outside of the while loop
     ISRRan = 0;  // Reset for whatever reason
    }

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

body:
I have solved this.

The problem was with the pinout indeed.

    attachInterrupt(0, myISR, FALLING);
 will use the DIGITAL PIN 2

I was using attachInterrupt 2, that's all.


message:
How to reduce current from a AC TO DC power supply for arduino use

I have a AC to DC converter that was originally used for recharging the PSP, I stripped the 2 wires of the output and was wanting to use it for my arduino instead of using a 9V battery, it's output is 5V 2000MA, is there a way to reduce the current in order to use it for the arduino and im guessing the 5V is enough to power it...right? Im kinda new to electronics and the arduino so any help is much appreciated :D.
Thanks,
Liam.

body:
You don't need to reduce the current.

2000MA (2 amps) means the power supply is CAPABLE of supplying this (without overheating). Anything less than this, and your device will work perfectly.

Your Arduino will DRAW a certain number of milliamps (amps), this is the amount of current that will ACTUALLY run through your circuit.


message:
Can't make my stepper motor run clockwise and counterclockwise with AccelStepper Library

I'm relatively new to arduino thus need your help to figure out why my stepper motor doesn't rotate clockwise and counterclockwise. All I could do was to make it rotate only in one direction.

Here is my code:

    #include <AccelStepper.h>

    int pos=16000;
    AccelStepper stepper(1,4,5);

    void setup() {
    stepper.moveTo(pos);
    stepper.setMaxSpeed(6400);
    stepper.setSpeed(6400);
    }

    void loop() {
    if (stepper.distanceToGo() == 0)
    {
      stepper.setCurrentPosition(0);
      pos = -pos;
      stepper.moveTo(pos);
      stepper.setSpeed(6400);
    }
       stepper.runSpeed();
    }
Will appreciate any help you can give me :)

body:
The  “Performance” paragraph of the “Detailed Description” section of [AccelStepper documentation](http://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html) says:

>The fastest motor speed that can be reliably supported is about 4000 steps per second at a clock frequency of 16 MHz on Arduino such as Uno etc. ...

and the [AccelStepper::setSpeed ()](http://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#ae79c49ad69d5ccc9da0ee691fa4ca235) documentation says:

> ... Speeds of more than 1000 steps per second are unreliable

Try changing your 6400-steps-per-second setting to a some plausible number, eg 500 or 1000.

Actually, it would make sense to start out with moderate destination settings and speeds, like a target position of 200 instead of 16000, and steps-per-second of 100, or whatever count it takes for say exactly two shaft revolutions.  Once you have that working right, then start doubling numbers until it no longer works, after which you can back off by a factor of say four (to allow for variations in load, etc).


body:
Actually after trying different options, I could finally find a solution that seems to work for me:

    if (stepper.distanceToGo() == 0 && stepper.currentPosition()==50000) {
        delay(1000);
        stepper.setCurrentPosition(0);
        stepper.moveTo(-50000);
        stepper.setSpeed(10000);
        stepper.runSpeedToPosition();
      }
      else if (stepper.distanceToGo() == 0 && stepper.currentPosition()==-50000) {
        delay(1000);
        stepper.setCurrentPosition(0);
        stepper.moveTo(50000);
        stepper.setSpeed(10000);
        stepper.runSpeedToPosition();
      }
      stepper.runSpeed();


message:
5V Trinket only outputting 3.3V?

Unless my multimeter is on the fritz, it would seem my [5V Adafruit Trinket][1] is only outputting 3.3V when connected w/ DC power.

When connected via USB, totally fun. Full 5V. But if I disconnect that and connect a 9V wall adapter, the output of the 5V pinout is just giving me 3.3V.

Is that even possible?

I noticed the issue b/c my program wasn't running properly when connected via the DC adapter (but ran just fine via USB). So I tested the voltage and sure enough, 3.3V all around at basically every +/- connection.

Any ideas?

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

  [1]: https://learn.adafruit.com/introducing-trinket?view=all
  [2]: https://i.stack.imgur.com/IonR3.jpg
  [3]: https://i.stack.imgur.com/tPVBp.jpg

body: Unfortunately I do not have the ability to comment. What I can suggest is to look at the small 5 pin regulator and look at its markings. If the IC is marked with "QT33" then adafruit has stupidly soldered the wrong chip onto your trinket board. If it says "QT50" then the regulator is not at fault.


message:
Is this bluetooth setup good?

I am trying to do this tutorial http://www.instructables.com/id/Chappie-Self-Balancing-Robot/  on building a self-balancing robot with uno. However, I bothered by the Bluetooth wiring. I've done Arduino projects with Bluetooth before and all the Hc-05 wirings I've seen have it connected to the Tx and Rx pins.Currently, I have my Bluetooth module wiring like this :   with http://cdn.instructables.com/FSK/AI30/HMMFE6UO/FSKAI30HMMFE6UO.MEDIUM.jpg.
Will the different wiring need a different implementation, the code I see on the chappie instructable link does not have any pin mentions but I'm not sure. Is the chappie wiring fine? should I change my wiring? should I change my code?
I'm confused.

body:
Which code are you reading? At step 5 he wrote

> Complete code can be found on the [GITHUB][1].

The sketch file ([here is the direct link][2]) has the following lines:

    const int rxpin = 11; // pin used to receive (not used in this version)
    const int txpin = 4; // pin used to send to LCD

    SoftwareSerial blue(rxpin, txpin); // new serial port on pins 2 and 3

This means that the bluetooth is using a software serial on pins 11 and 4.

I don't know where you got the image you posted, but anyway that wiring is not the same as the one in the instructable. With your wiring, you can either use the software serial on pins 0 and 1, or (better) use the hardware serial. To do so, remove or comment the lines I highlighted and then replace every call to `blue` with `Serial`.

  [1]: https://github.com/ManpreetSingh80/CHAPPIE
  [2]: https://github.com/ManpreetSingh80/CHAPPIE/blob/master/SelfBalance_robot0_67/SelfBalance_robot0_67.ino


message:
Is Gsm antenna effect on microcontroller working?

in my embedded system I used patch antenna and Atmega 328 microcontroller,but somehow it causes the abrupt function of a microcontroller or reset. how can it be solved?

body:
There are 3 possible causes that I can think of (it's difficult to say more without further details):

 - SW bug: this is hard to confirm without actually finding the bug, but it might cause a lock-up and trigger a watchdog reset (do you have a watchdog running?) or a pointer error cause a jump to some memory location along the boot path (not so likely, I suspect)

 - Too tight power envelope: when your system tries to transmit, it draws more power than the power supply/battery can provide. This cause a temporary voltage drop, to the point that the system kinda power cycles. You can try to use a power supply with higher maximum current.

 - Electromagnetic interference: somehow the transmission interferes with the AVR. You can try to direct the antenna further away from the AVR and to increase the distance in between.

But you should really add more information to your question.


message:
Is Arduino reliable for serious tasks, such as medical machines?

I'm just getting started with Arduino, and it has a LOT of uses, however, I would like to know how reliable is it? Can it be used for medical purposes (Measure vital signs, or to help surgeons perform surgeries), if it depends on the board, which one is the most accurate and reliable?

I know most robotic tasks will rely on the quality of the servo to interpret the Arduino commands, and sensors, and even the coding/logic, but we can replace/recode all of those things, but when it comes to the main board it gets more complicated

body:
You should NOT trust using an Arduino for life safety measures (medical purposes).

This discusses the reliability of an Arduino pretty well- https://electronics.stackexchange.com/questions/15535/reliability-of-the-arduino-platform-for-industrial-use


message:
Compiler doesn't like function code

I am getting this error from the Visual Studio compiler (I use the Visual Studio add-in Visual Micro for Arduino).

> ModelRailroadCrossingSignalController.ino:In function 'void loop()
ModelRailroadCrossingSignalController.ino:210:15: error: too few arguments to function 'Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer, const char*)
:onSignalSound()
ModelRailroadCrossingSignalController.ino:note  declared here
:Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
Error compiling project sources

Here is the function and loop (all the defines and instances left out for brevity, they aren't the issue

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

 signalEntrySensor = checkEntrySensor();
 if (signalEntrySensor == true) {
  if (crossingSignalInOperation == false)
  {
   Adafruit_VS1053_FilePlayer mp = onSignalSound(musicPlayer,"Trainxng.mp3");  //all other functions are called in the sound routine?
   if (debugMode)
   {
    Serial.println("Sound byte called");
   }
   while (mp.playingMusic) {
    // file is now playing in the 'background' so now's a good time
    // to do something else
    offRoadPower();
    lowerSignalArms();
    onSignalSound();
    startSignalFlashers();
    crossingSignalInOperation = true;
   }
  }
    }

    Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
 // Play the train crossing sound file
 if (debugMode)
 {
  Serial.println(F("Playing track - "));
  Serial.print(fileName);
 }
 //all sound files are on the micro sd card on the music player shield
 if (!mp.startPlayingFile(fileName)) {
  Serial.println(F("Could not open file "));
  Serial.print(fileName);
  while (1);
 }
 return mp;  }

I'm a C# guy, not ever using C++ until now, but this code should certainly work, not sure why the function is not compiling.

body:
The clue is in the error...

> too few arguments to function 'Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer, const char*)

You have defined the function as this:

    Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {

And yet you then try and call it like this:

    onSignalSound();

Spot the mismatch?

I suspect you don't want to be calling that function there since it seems to be in a bit where the sound has already been started.


message:
MQ135 Air Quality Sensor Signal Amplifier needed? Higher Quality Sensor?

I am trying to strengthen the signal from my MQ135 air quality sensor so it can detect aerosols from 3 feet away, as, currently as it stands the resolution is pathetic, it only blips from 0.21 to 0.58 when you practically insert the sensor into the nozzle of a bottle full of vinegar/rubbing alcohol.

It would be ideal if you could guide me as to what sort of signal amplifier to buy to strengthen the signal coming from this board?

Alternatively: Could I increase the sensitivity of this sensor?

I'd like to plot this to a graph at some point, so I will be working on an ASP.NET app that tells me if there are any aerosols in my room or not.

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

Here's the code:

    /*
      Graph

     A simple example of communication from the Arduino board to the computer:
     the value of analog input 0 is sent out the serial port.  We call this "serial"
     communication because the connection appears to both the Arduino and the
     computer as a serial port, even though it may actually use
     a USB cable. Bytes are sent one after another (serially) from the Arduino
     to the computer.

     You can use the Arduino serial monitor to view the sent data, or it can
     be read by Processing, PD, Max/MSP, or any other program capable of reading
     data from a serial port.  The Processing code below graphs the data received
     so you can see the value of the analog input changing over time.

     The circuit:
     Any analog input sensor is attached to analog in pin 0.

     created 2006
     by David A. Mellis
     modified 9 Apr 2012
     by Tom Igoe and Scott Fitzgerald

     This example code is in the public domain.

     http://www.arduino.cc/en/Tutorial/Graph
     */

    void setup() {
      // initialize the serial communication:
      Serial.begin(9600);
    }

    void loop() {
      // send the value of analog input 0:
      Serial.println(analogRead(A0));
      // wait a bit for the analog-to-digital converter
      // to stabilize after the last reading:
      delay(20);
    }

    /* Processing code for this example

     // Graphing sketch

    // This program takes ASCII-encoded strings
    // from the serial port at 9600 baud and graphs them. It expects values in the
    // range 0 to 1023, followed by a newline, or newline and carriage return

    // Created 20 Apr 2005
    // Updated 24 Nov 2015
    // by Tom Igoe
    // This example code is in the public domain.

    import processing.serial.*;

    Serial myPort;        // The serial port
    int xPos = 1;         // horizontal position of the graph
    float inByte = 0;

    void setup () {
      // set the window size:
      size(400, 300);

      // List all the available serial ports
      // if using Processing 2.1 or later, use Serial.printArray()
      println(Serial.list());

      // I know that the first port in the serial list on my mac
      // is always my  Arduino, so I open Serial.list()[0].
      // Open whatever port is the one you're using.
      myPort = new Serial(this, Serial.list()[0], 9600);

      // don't generate a serialEvent() unless you get a newline character:
      myPort.bufferUntil('\n');

      // set inital background:
      background(0);
    }
    void draw () {
      // draw the line:
      stroke(127, 34, 255);
      line(xPos, height, xPos, height - inByte);

      // at the edge of the screen, go back to the beginning:
      if (xPos >= width) {
        xPos = 0;
        background(0);
      } else {
        // increment the horizontal position:
        xPos++;
      }
    }

    void serialEvent (Serial myPort) {
      // get the ASCII string:
      String inString = myPort.readStringUntil('\n');

      if (inString != null) {
        // trim off any whitespace:
        inString = trim(inString);
        // convert to an int and map to the screen height:
        inByte = float(inString);
        println(inByte);
        inByte = map(inByte, 0, 1023, 0, height);
      }
    }

    */

    /* Max/MSP v5 patch for this example
     ----------begin_max5_patcher----------
    1591.3oc0YszbaaCD9r7uBL5RalQUAO3CvdyS5zVenWZxs5NcfHgjPCIfJIT
    RTxj+6AOHkoTDooroUs0AQPR73a+1cwtK3WtZxzEpOwqlB9YveAlL4KWMYh6
    Q1GLo99ISKXeJMmU451zTUQAWpmNy+NM+SZ2y+sR1l02JuU9t0hJvFlNcMPy
    dOuBv.U5Rgb0LPpRpYBooM3529latArTUVvzZdFPtsXAuDrrTU.f.sBffXxL
    vGE50lIHkUVJXq3fRtdaoDvjYfbgjujaFJSCzq4.tLaN.bi1tJefWpqbO0uz
    1IjIABoluxrJ1guxh2JfPO2B5zRNyBCLDFcqbwNvuv9fHCb8bvevyyEU2JKT
    YhkBSWPAfq2TZ6YhqmuMUo0feUn+rYpY4YtY+cFw3lUJdCMYAapZqzwUHX8S
    crjAd+SIOU6UBAwIygy.Q1+HAA1KH6EveWOFQlitUK92ehfal9kFhUxJ3tWc
    sgpxadigWExbt1o7Ps5dk3yttivyg20W0VcSmg1G90qtx92rAZbH4ez.ruy1
    nhmaDPidE07J+5n2sg6E6oKXxUSmc20o6E3SPRDbrkXnPGUYE.i5nCNB9TxQ
    jG.G0kCTZtH88f07Rt0ZMMWUw8VvbKVAaTk6GyoraPdZff7rQTejBN54lgyv
    HE0Ft7AvIvvgvIwO23jBdUkYOuSvIFSiNcjFhiSsUBwsUCh1AgfNSBAeNDBZ
    DIDqY.f8.YjfjV1HAn9XDTxyNFYatVTkKx3kcK9GraZpI5jv7GOx+Z37Xh82
    LSKHIDmDXaESoXRngIZQDKVkpxUkMCyXCQhcCK1z.G457gi3TzMz4RFD515F
    G3bIQQwcP3SOF0zlkGhiCBQ1kOHHFFlXaEBQIQnCwv9QF1LxPZ.A4jR5cyQs
    vbvHMJsLll01We+rE2LazX6zYmCraRrsPFwKg1ANBZFY.IAihr8Ox.aH0oAL
    hB8nQVw0FSJiZeunOykbT6t3r.NP8.iL+bnwNiXuVMNJH9H9YCm89CFXPBER
    bz422p8.O4dg6kRxdyjDqRwMIHTbT3QFLskxJ8tbmQK4tm0XGeZWF7wKKtYY
    aTAF.XPNFaaQBinQMJ4QLF0aNHF0JtYuHSxoUZfZY6.UU2ejJTb8lQw8Fo5k
    Rv6e2PI+fOM71o2ecY1VgTYdCSxxUqLokuYq9jYJi6lxPgD2NIPePLB0mwbG
    YA9Rgxdiu1k5xiLlSU6JVnx6wzg3sYHwTesB8Z5D7RiGZpXyvDNJY.DQX3.H
    hvmcUN4bP1yCkhpTle2P37jtBsKrLWcMScEmltOPv22ZfAqQAdKr9HzATQwZ
    q18PrUGt6Tst2XMCRUfGuhXs6ccn23YloomMqcTiC5iMGPsHsHRWhWFlaenV
    XcqwgCQiGGJzptyS2ZMODBz6fGza0bzmXBj7+DA94bvpR01MffAlueO7HwcI
    pWCwmzJdvi9ILgflLAFmyXB6O7ML0YbD26lenmcGxjVsZUN+A6pUK7AtTrPg
    M+eRYG0qD9j4I7eEbco8Xh6WcO.or9XDC6UCiewbXHkh6xm5LiPEkzpJDRTu
    mEB44Fgz4NCtJvX.SM1vo2SlTCZGAe7GZu6ahdRyzFOhYZ+mbVVSYptBw.K1
    tboIkatIA7c1cTKD1u.honLYV04VkluHsXe0szv9pQCE9Ro3jaVB1o15pz2X
    zYoBvO5KXCAe0LCYJybE8ZODf4fV8t9qW0zYxq.YJfTosj1bv0xc.SaC0+AV
    9V9L.KKyV3SyTcRtmzi6rO.O16USvts4B5xe9EymDvebK0eMfW6+NIsNlE2m
    eqRyJ0utRq13+RjmqYKN1e.4d61jjdsauXe3.2p6jgi9hsNIv97CoyJ01xzl
    c3ZhUCtSHx3UZgjoEJYqNY+hYs5zZQVFW19L3JDYaTlMLqAAt1G2yXlnFg9a
    53L1FJVcv.cOX0dh7mCVGCLce7GFcQwDdH5Ta3nyAS0pQbHxegr+tGIZORgM
    RnMj5vGl1Fs16drnk7Tf1XOLgv1n0d2iEsCxR.eQsNOZ4FGF7whofgfI3kES
    1kCeOX5L2rifbdu0A9ae2X.V33B1Z+.Bj1FrP5iFrCYCG5EUWSG.hhunHJd.
    HJ5hhnng3h9HPj4lud02.1bxGw.
    -----------end_max5_patcher-----------

     */

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

body:
    int sensorValue;
    int pin8 = 8;
    void setup()
    {
      Serial.begin(9600);
      pinMode(pin8, OUTPUT);

      }

      void loop()
      {
        sensorValue = analogRead(0); // read analog input pin 0
        Serial.print(sensorValue, DEC); //prints the value read
        Serial.println("ppm");
        if (sensorValue > 500) {
          //Activate digital output pin 8 - the LED will light up
          digitalWrite(pin8, HIGH);
        }
        else
        {
          // Deactivate digital output pin 8 - the LED will not light up
          digitalWrite(pin8, LOW);

        }
        delay(50);

    }


message:
Start program on PC using Arduino

I want to create arduino sketch that start program on my computer (i.e., browser) when I push button on Arduino itself.

Is it possible to make it using Arduino uno? I already know how to make a serial connection between PC and Arduino and use Processing software, but as I know, Processing cannot interact with another programs.

body:
Processing is just Java.  If Java can do it Processing can do it.

And Java can do it.

Just ask Google about the Java `ProcessBuilder` class.


body:
You can also make the Arduino look like a keyboard/mouse to the PC and then reproduce some key combo that will perform the action you want.
See reference [here][1].

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


message:
Employing C++ code for Arduino

I have Googled quite a lot regarding using a C++ program for uploading to Arduino and related, however I am confused now. Right, my problem is this:

I have written a C++ program which imports RGB data of a 24 bit bitmap (which was generated using Matlab) and now I would like to use this array (3 arrays - R,G,B) for an Arduino sketch to be used for a LED matrix project that I am working on. I am not exactly a programmer and hence had to resort to this path -- MATLAB to c++ and then Arduino, although this could be entirely done in C++ too (importing a bitmap and extracting pixel info). So, my C++ code spits out the 3 arrays and I am not sure how to get those into an Arduino sketch.

I read a lot about this and I understood this - As the Arduino "language" is C and C++ therefore it is possible to program an Arduino in C++/c. I need a maker file and a compiler. However my question is that isn't there a more non-programmer friendly way to get this done, some software or an IDE which supports Arduino programming in C++? I cannot understand much of this method, hence trying to bypass this.

If anybody's got any better method, I would be really glad if you could share it. I am also looking to use the Arduino package for MATLAB to send the array directly from there using serial communication. But I just wanted to make sure I at least tried this path.

Would really appreciate if somebody could offer some help. I am quite stuck here.

Can share any other info if required.

Thanks a lot!

---

EDIT 1:

To clarify as Nick Gammon pointed out in the comments below. In brief steps, this is what I have done till now:

1. Got a 24 bit bitmap (some random image)
2. Extracted the RGB data for each pixel using Matlab
3. Have 3 arrays of (for eg.) 122X300 dimensions whose every element has values between 0-255 (8 bit) and for R,G and B colors
4. Want to get these 3 arrays for use in Arduino sketch for further working
5. Stuck here - how to do that .....
6. So I did this - I imported that the RGB data into 3 separate text files and made a c++ program to read those arrays assuming that I should be able to then somehow use this program in Arduino sketch.
7. Now I am not sure what to do....my goal would be to have these 3 arrays (CRGB arrays, FastLED) in my arduino sketch which I can control and then upload to my Due.
8. On googling I found that to use c++ for arduino , you need the avr compiler and make file, which I want to avoid. Tried other IDEs too, Eclipse, PlatformIO too .. ummmm ... not that successful to be honest.
9. as per Paul's ans- Matlab to Arduino method I have to try.
Hope I have clarified my process till now :)

---

EDIT 2:

[![Snapshot of Red color data (122X300) in Text format (imported from Matlab)][1]][1]

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

---

C++ code for reading the above array (thought I could use the output in Arduino)

    #include <stdio.h>
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <conio.h>
    #include <sstream>
    #include <stdlib.h>

    const int HEIGHT = 4;

    const int WIDTH = 5;

    using namespace std;

    int main(){

      int array_req [HEIGHT][WIDTH];

    string userinputprompt, filename;

    userinputprompt = "COLORDATA FILENAME: ";

    cout<<userinputprompt<<endl;

    getline(cin,filename);

    ifstream inputfile;

    inputfile.open(filename.c_str());

     for (int i = 0; i < HEIGHT; ++i)
    {
      std::string tmpString;
      std::getline(inputfile, tmpString);

     std::stringstream ss(tmpString);

     for(int j=0;j < WIDTH; ++j)
      {
        ss >> array_req[i][j];
      }
     }

        for(int p=0; p<HEIGHT; p++)
        {
          for(int q=0; q<WIDTH; q++)
        {
            cout<<array_req[p][q]<<" ";
        }
        cout<<"\n";
    }

    inputfile.close();
    getchar();
    return 0;

    }

body:
Here's a sample program you could use as reference, just replace the values in the array and adjust VALUES_NUMBER accordingly.

Disclaimer: I didn't try to compile/run it, but it should give you an idea of how to use the values you already have.

    // These are Arduino Pins that support "analog" output.
    const unsigned short ANALOG_RED_PIN = 3;
    const unsigned short ANALOG_GREEN_PIN = 5;
    const unsigned short ANALOG_BLUE_PIN = 6;

    const unsigned int VALUES_NUMBER = 12;

    const unsigned short REDS[VALUES_NUMBER] = {
      0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
      0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B
    };

    const unsigned short GREENS[VALUES_NUMBER] = {
      0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
      0x00, 0x01, 0x02, 0x03, 0x04, 0x05
    };

    const unsigned short BLUES[VALUES_NUMBER] = {
      0x09, 0x0A, 0x0B, 0x03, 0x04, 0x05,
      0x00, 0x01, 0x02, 0x06, 0x07, 0x08
    };

    void setup() {
      pinMode(analogRed, OUTPUT);
      pinMode(analogGreen, OUTPUT);
      pinMode(analogBlue, OUTPUT);
    }

    void loop() {
      unsigned int counter;
      for (counter = 0; counter < VALUES_NUMBER; counter++) {
        analogWrite(ANALOG_RED_PIN, REDS[counter]);
        analogWrite(ANALOG_GREEN_PIN, GREENS[counter]);
        analogWrite(ANALOG_BLUE_PIN, BLUES[counter]);
        delay(1000); //sleep 1 second
      }
    }


body:
You've got quite an interesting project.

**Programming an Arduino (C++)**

Arduino is C++ (or atleast a subset).

The Arduino IDE uses the GNU AVR-GCC compiler. And it takes care of all "make" files and stuff. You shouldn't really bother too much. Just paste the code right in, and fix whatever is broken ;)

Also, the [Arduino IDE][1] is basically click&install, click&compile/upload, I'm not sure why you're even trying all the other options.

***

For the sake of clarity/simplicity I'll give you an example of sending a single R/G/B pixel to the Arduino.

**Matlab**

You should set up your Matlab code something like this.
I'm not a "Matlab guru" nor do I know whatever code you have.
You should open a COM port and write to it.

    s = serial('COM1','BAUD',115200);
    fopen(s);
    Pixel pix = getPixelFromBMP("image.bmp",0);
    fprintf(s,'%s',pix.r.to_String()+pix.g.to_String()+pix.b.to_String());
    fclose(s);

**Arduino**

In the Arduino IDE (withouth worrying about makefiles and toolchains).

You do the reverse of what you've done in your Matlab code.
Read the serial input and write it to the LED strip.
I'm quite sure this code won't compile, and there are a lot of fancier ways to read the serial buffer:

    #include <ledstrip.h>

    LedStrip ledStrip;

    int incomingByteR = 0;   // for incoming serial data
    int incomingByteG = 0;   // for incoming serial data
    int incomingByteB = 0;   // for incoming serial data

    void setup() {
            Serial.begin(115200);     // opens serial port, sets data rate to 115200 bps
            ledStrip.begin(1,RGB);    // initializes the ledstrip (RGB).
    }

    void loop() {
            // send data only when you receive data:
            if (Serial.available() > 3) {
                    // read the incoming byte:
                    incomingByteR = Serial.read();
                    incomingByteG = Serial.read();
                    incomingByteB = Serial.read();
                    // say what you got:
                    Serial.print("I received: ");
                    Serial.println(incomingByteR, DEC);
                    Serial.println(incomingByteG, DEC);
                    Serial.println(incomingByteB, DEC);
                    ledStrip.pixel[0].r = incomingByteR;
                    ledStrip.pixel[0].g = incomingByteG;
                    ledStrip.pixel[0].b = incomingByteB;
                    ledStrip.show();
            }
    }

**C++**

So, you don't really need C++ (other than to program the Arduino). You could interchange Matlab for C++ or Arduino for pure AVR C++, but I wouldn't recommend it.

  [1]: https://www.arduino.cc/en/Main/Software


body:
> As the arduino "language" is C and C++ therefore it is possible to program an Arduino in C++/c. I need a maker file and a compiler. However my question is that isn't there a more non-programmer friendly way to get this done, some software or an IDE which supports Arduino programming in C++?

Yes, it's called the **Arduino IDE**. You plug your board into the USB port, write your program, or use an existing example, and then hit the Upload button.


message:
Standalone chipset, power regulation & pinout

I have succesfully (or so the ide says) burned a bootloader on an ATMega328P-PU chipset, and uploaded my sketch on it.

It appears a voltage regulation is absolutely needed, if I want to solder a pcb with the standalone chip, rather than an arduino. Is that correct? Can I build one out of my starter kits parts (assortment of transistors, diodes, zeners, resistors and capacitors)?

In the meantime, I would like to make sure the chispet is functional. Can I power it from GND/5V of an arduino? Will it take care of that power regulation?

If I can, what is the correspondance between the arduino pins, and the ATMega328P-PU pins? I have this page here : http://www.learningaboutelectronics.com/Articles/Atmega328-pinout.php
referencing the chipset pinout. Am I correct in assuming there is a correspondance with the arduino pinout in the reading order of this chart, ie. :

PD0 to PD7 are Rx, Tx, digital pins 2 to 7 on the arduino, PB0 to PB5 are digital pins 8 to 13, and PC0 to PC5 are A0 to A5 on the arduino?

Thanks for reading.

body:
Voltage regulation is needed if the voltage you are providing to the chip is outside (or can drift outside) the allowed range for the chip to operate.

At the upper limit that is 5.5V. The lower limit is 1.8V. Note that at lower voltages you can only reliably run at lower clock speeds.

If your power source is between those two voltages (say a 3.4V LiPo battery) then you don't need a regulator.

If your power source is above 5.5V (say a 9V PP3 battery [urgh]) then you definitely need a regulator.

A proper regulator is quite a complex device, and it is highly unlikely that you have the components to make one.  A simple, very inefficient one, though, can be made using a resistor and a 5V Zener diode if you have one.

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

Until you have your own regulator of whatever form, yes, you can power the chip from the 5V pin of the Arduino.

The pin mapping for the chip -> Arduino IO numbers is in the file `pins_arduino.h` for the Uno variant in the IDE.  In the top of that file is this handy drawing:

    // ATMEL ATMEGA8 & 168 / ARDUINO
    //
    //                  +-\/-+
    //            PC6  1|    |28  PC5 (AI 5)
    //      (D 0) PD0  2|    |27  PC4 (AI 4)
    //      (D 1) PD1  3|    |26  PC3 (AI 3)
    //      (D 2) PD2  4|    |25  PC2 (AI 2)
    // PWM+ (D 3) PD3  5|    |24  PC1 (AI 1)
    //      (D 4) PD4  6|    |23  PC0 (AI 0)
    //            VCC  7|    |22  GND
    //            GND  8|    |21  AREF
    //            PB6  9|    |20  AVCC
    //            PB7 10|    |19  PB5 (D 13)
    // PWM+ (D 5) PD5 11|    |18  PB4 (D 12)
    // PWM+ (D 6) PD6 12|    |17  PB3 (D 11) PWM
    //      (D 7) PD7 13|    |16  PB2 (D 10) PWM
    //      (D 8) PB0 14|    |15  PB1 (D 9) PWM
    //                  +----+
    //
    // (PWM+ indicates the additional PWM pins on the ATmega168.)

  [1]: https://i.stack.imgur.com/oq9P6.gif


message:
ATmega328p simple shortcircuit button

I am trying to get a simple button (GPIO shortcircuit) to work. I have chosen Pin D0 as input and Pin D7 as output. It works fine in an Arduino sketch but I can't get it to run in pure C. What am I doing wrong? I bet I got the bits all wrong...

My code:

    DDRD = 0b11111110; // set all port D pins to Output besides pin 0, which is set to input
    PORTD = 0b11111111; // set all D pins to WRITE / PULL-UP
    int a = PIND & 1; // a is 0 or 1, depending on whether pins D0 and D7 are physically connected

It doesn't work though, `a` is never zero, whether the pins are connected or not.

Here is my complete code sample, where the on board LED depends on my pins connection state:

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

 int main(void)
 {
  DDRB |= _BV(DDB5);
  DDRD = 0b11111110;
  PORTD = 0b11111111;

   while(1) {
   int a =  PIND & 1;
   if(a != 0)
     PORTB |= _BV(PORTB5); // blink on
    else
     PORTB &= ~_BV(PORTB5); // blink off
    _delay_ms(1000);
  }
 }

body:
The problem here is you set pull-up on D0. So even if button is not pressed it will be at high state because of pull-up. You would need pull-down for this to work (Arduino does not have it).

The pullups are useful if you want to connect pin to GND when button is pressed. When button is not pressed it will have defined state (HIGH because of pull-up) and when pressed it will be pulled LOW by button. You can imagine pull-up as a resistor to Vcc.

So for this to work I would put the other end of button to GND and it will work (One end to D0, second on GND). Condition in code should be altered (a == 0) but otherwise all can be the same.

Other option is to connect external resistor in range 1K-100K Ohm between pin D7 and GND and turn off pull-up in code. That resistor would serve as pull down.

Just one more note. If you are not using other pins it is the best to leave them as inputs. Setting an "unused" pin as output and setting it to HIGH can damage the pin if you accidentally connected it to GND (because in previous sketch you experimented something).


message:
Digital pin output voltage, not triggering 71mA relay coil

I have a relay ([VRS4H-S-DC5V-C](https://www.fabtolab.com/Relay -5V- VRS4H-S)), for which the triggering voltage required is 5V Min.  If I directly use the 5V voltage of Arduino  I'm able to trigger it, but if I use any digital pin in OUTPUT mode in digitalWrite I'm not able to trigger the relay.

Earlier I thought that it must be that because it's a small board its digital pins would be giving HIGH state as 3.3.V, but the fact is when I checked both the voltage of 5V (which is obviously shown 5V on multi meter) and that digital pin one, both show 5V. So the question is why the hell is digital pin not able to trigger the relay, since trigger the relay by 5V is of no use for me since I can't control it, i.e., when it should trigger and when not?

body:
The digital output pin cannot output sufficient current to drive the relay directly. Iirc this question was already asked. You need to add between the Arduino and the relay a driving stage, for example with a FET. Or you can use a shield that already has this additional circuitry.

Just google for "Arduino relay driver circuit" and you will get various options.

[This][1] is pretty close to your setup.

  [1]: http://www.instructables.com/id/Connecting-a-12V-Relay-to-Arduino/


message:
Translating accelerometer angle to PWM output (was MPU-6050 DMP6 example)

I'm trying to make a self balancing robot with MPU-6050. When I try the DMP6 example it works good and the Serial Monitor gives me the yaw pitch roll angles but whenever I try to output PWM on pin 6 nothing happens and I don't know why.

Here is the code:

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

    // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
    // 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
    // Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
    //
    // Changelog:
    //      2013-05-08 - added seamless Fastwire support
    //                 - added note about gyro calibration
    //      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
    //      2012-06-20 - improved FIFO overflow handling and simplified read process
    //      2012-06-19 - completely rearranged DMP initialization code and simplification
    //      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
    //      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
    //      2012-06-05 - add gravity-compensated initial reference frame acceleration output
    //                 - add 3D math helper file to DMP6 example sketch
    //                 - add Euler output and Yaw/Pitch/Roll output formats
    //      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
    //      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
    //      2012-05-30 - basic DMP initialization working

    /* ============================================
    I2Cdev device library code is placed under the MIT license
    Copyright (c) 2012 Jeff Rowberg

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    ===============================================
    */

    // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
    // for both classes must be in the include path of your project
    #include "I2Cdev.h"

    #include "MPU6050_6Axis_MotionApps20.h"
    //#include "MPU6050.h" // not necessary if using MotionApps include file

    // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
    // is used in I2Cdev.h
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif

    // class default I2C address is 0x68
    // specific I2C addresses may be passed as a parameter here
    // AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
    // AD0 high = 0x69
    MPU6050 mpu;
    //MPU6050 mpu(0x69); // <-- use for AD0 high

    /* =========================================================================
       NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
       depends on the MPU-6050's INT pin being connected to the Arduino's
       external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
       digital I/O pin 2.
     * ========================================================================= */

    /* =========================================================================
       NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
       when using Serial.write(buf, len). The Teapot output uses this method.
       The solution requires a modification to the Arduino USBAPI.h file, which
       is fortunately simple, but annoying. This will be fixed in the next IDE
       release. For more info, see these links:

       http://arduino.cc/forum/index.php/topic,109987.0.html
       http://code.google.com/p/arduino/issues/detail?id=958
     * ========================================================================= */

    // uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
    // quaternion components in a [w, x, y, z] format (not best for parsing
    // on a remote host such as Processing or something though)
    //#define OUTPUT_READABLE_QUATERNION

    // uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
    // (in degrees) calculated from the quaternions coming from the FIFO.
    // Note that Euler angles suffer from gimbal lock (for more info, see
    // http://en.wikipedia.org/wiki/Gimbal_lock)
    //#define OUTPUT_READABLE_EULER

    // uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
    // pitch/roll angles (in degrees) calculated from the quaternions coming
    // from the FIFO. Note this also requires gravity vector calculations.
    // Also note that yaw/pitch/roll angles suffer from gimbal lock (for
    // more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
    #define OUTPUT_READABLE_YAWPITCHROLL

    // uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
    // components with gravity removed. This acceleration reference frame is
    // not compensated for orientation, so +X is always +X according to the
    // sensor, just without the effects of gravity. If you want acceleration
    // compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
    //#define OUTPUT_READABLE_REALACCEL

    // uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
    // components with gravity removed and adjusted for the world frame of
    // reference (yaw is relative to initial orientation, since no magnetometer
    // is present in this case). Could be quite handy in some cases.
    //#define OUTPUT_READABLE_WORLDACCEL

    // uncomment "OUTPUT_TEAPOT" if you want output that matches the
    // format used for the InvenSense teapot demo
    //#define OUTPUT_TEAPOT

    #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    bool blinkState = false;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    // packet structure for InvenSense teapot demo
    uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

    // ================================================================
    // ===               INTERRUPT DETECTION ROUTINE                ===
    // ================================================================

    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }

    // ================================================================
    // ===                      INITIAL SETUP                       ===
    // ================================================================

    void setup() {
      pinMode(6,OUTPUT);
        // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz). Comment this line if having compilation difficulties with TWBR.
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        // initialize serial communication
        // (115200 chosen because it is required for Teapot Demo output, but it's
        // really up to you depending on your project)
        Serial.begin(115200);
        while (!Serial); // wait for Leonardo enumeration, others continue immediately

        // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Arduino
        // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
        // the baud timing being too misaligned with processor ticks. You must use
        // 38400 or slower in these cases, or use some kind of external separate
        // crystal solution for the UART timer.

        // initialize device
        Serial.println(F("Initializing I2C devices..."));
        mpu.initialize();

        // verify connection
        Serial.println(F("Testing device connections..."));
        Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

        // wait for ready
        Serial.println(F("\nSend any character to begin DMP programming and demo: "));
        while (Serial.available() && Serial.read()); // empty buffer
        while (!Serial.available());                 // wait for data
        while (Serial.available() && Serial.read()); // empty buffer again

        // load and configure the DMP
        Serial.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        // supply your own gyro offsets here, scaled for min sensitivity
        mpu.setXGyroOffset(29);
        mpu.setYGyroOffset(44);
        mpu.setZGyroOffset(21);
        mpu.setZAccelOffset(1407); // 1688 factory default for my test chip

        // make sure it worked (returns 0 if so)
        if (devStatus == 0) {
            // turn on the DMP, now that it's ready
            Serial.println(F("Enabling DMP..."));
            mpu.setDMPEnabled(true);

            // enable Arduino interrupt detection
            Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
            attachInterrupt(0, dmpDataReady, RISING);
            mpuIntStatus = mpu.getIntStatus();

            // set our DMP Ready flag so the main loop() function knows it's okay to use it
            Serial.println(F("DMP ready! Waiting for first interrupt..."));
            dmpReady = true;

            // get expected DMP packet size for later comparison
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {
            // ERROR!
            // 1 = initial memory load failed
            // 2 = DMP configuration updates failed
            // (if it's going to break, usually the code will be 1)
            Serial.print(F("DMP Initialization failed (code "));
            Serial.print(devStatus);
            Serial.println(F(")"));
        }

        // configure LED for output
        pinMode(LED_PIN, OUTPUT);
    }

    // ================================================================
    // ===                    MAIN PROGRAM LOOP                     ===
    // ================================================================

    void loop() {
      analogWrite(6,255);
        // if programming failed, don't try to do anything
        if (!dmpReady) return;

        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {
            // other program behavior stuff here
            // .
            // .
            // .
            // if you are really paranoid you can frequently test in between other
            // stuff to see if mpuInterrupt is true, and if so, "break;" from the
            // while() loop to immediately process the MPU data
            // .
            // .
            // .
        }

        // reset interrupt flag and get INT_STATUS byte
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();

        // get current FIFO count
        fifoCount = mpu.getFIFOCount();

        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
            // reset so we can continue cleanly
            mpu.resetFIFO();
            Serial.println(F("FIFO overflow!"));

        // otherwise, check for DMP data ready interrupt (this should happen frequently)
        } else if (mpuIntStatus & 0x02) {
            // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

            // read a packet from FIFO
            mpu.getFIFOBytes(fifoBuffer, packetSize);

            // track FIFO count here in case there is > 1 packet available
            // (this lets us immediately read more without waiting for an interrupt)
            fifoCount -= packetSize;

            #ifdef OUTPUT_READABLE_QUATERNION
                // display quaternion values in easy matrix form: w x y z
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                Serial.print("quat\t");
                Serial.print(q.w);
                Serial.print("\t");
                Serial.print(q.x);
                Serial.print("\t");
                Serial.print(q.y);
                Serial.print("\t");
                Serial.println(q.z);
            #endif

            #ifdef OUTPUT_READABLE_EULER
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetEuler(euler, &q);
                Serial.print("euler\t");
                Serial.print(euler[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(euler[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(euler[2] * 180/M_PI);
            #endif

            #ifdef OUTPUT_READABLE_YAWPITCHROLL
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                Serial.print("ypr\t");
                Serial.print(ypr[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(ypr[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(ypr[2] * 180/M_PI);
            #endif

            #ifdef OUTPUT_READABLE_REALACCEL
                // display real acceleration, adjusted to remove gravity
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetAccel(&aa, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                Serial.print("areal\t");
                Serial.print(aaReal.x);
                Serial.print("\t");
                Serial.print(aaReal.y);
                Serial.print("\t");
                Serial.println(aaReal.z);
            #endif

            #ifdef OUTPUT_READABLE_WORLDACCEL
                // display initial world-frame acceleration, adjusted to remove gravity
                // and rotated based on known orientation from quaternion
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetAccel(&aa, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
                Serial.print("aworld\t");
                Serial.print(aaWorld.x);
                Serial.print("\t");
                Serial.print(aaWorld.y);
                Serial.print("\t");
                Serial.println(aaWorld.z);
            #endif

            #ifdef OUTPUT_TEAPOT
                // display quaternion values in InvenSense Teapot demo format:
                teapotPacket[2] = fifoBuffer[0];
                teapotPacket[3] = fifoBuffer[1];
                teapotPacket[4] = fifoBuffer[4];
                teapotPacket[5] = fifoBuffer[5];
                teapotPacket[6] = fifoBuffer[8];
                teapotPacket[7] = fifoBuffer[9];
                teapotPacket[8] = fifoBuffer[12];
                teapotPacket[9] = fifoBuffer[13];
                Serial.write(teapotPacket, 14);
                teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
            #endif

            // blink LED to indicate activity
            blinkState = !blinkState;
            digitalWrite(LED_PIN, blinkState);
        }
    }

body: It looks like the only `analogWrite(6...)` is the `analogWrite(6,255)` at the top of `loop(){}` which makes the output on pin 6 insensitive to any changes.


message:
Not being able to use pushbutton

I've been trying to detect a push button based on this [tutorial][1], but due to my lack of skills/knowledge I haven't been able to make it work, could you guys point out what I'm doing wrong?

Any help is appreciated

*My [project][2] on 123d circuits*

***My code:***

    void setup() {
      pinMode(2, INPUT);
      pinMode(3, OUTPUT);
      digitalWrite(3, HIGH);
      Serial.begin(9600);
    }

    void loop() {
      trigger();
    }

    void trigger(){
      if (digitalRead(2) == HIGH) {
        Serial.println("Hey");
        //turn();
      }
    }

  [1]: https://www.arduino.cc/en/Tutorial/Button
  [2]: https://123d.circuits.io/circuits/1945937

body:
You seem to be suffering from three problems here:

1. A lack of understanding how the button's pins are configured
2. A lack of understanding of how breadboard works
3. A strange notion (that I have seen around a lot recently for some reason) that a button needs to be driven from an output.

For the button's pins you should know that the pins are paired on the long sides. That is, if you hold the button so it is in "landscape" orientation (wider than it is high) the two upper pins are joined together, and the two lower pins are joined together.

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

Breadboard consists of strips of connections which, in your diagram, would be running horizontal. Pins plugged into holes horizontally in line with each other on the same side of the board (the gap in the middle is a gap in the connections too) will be connected together.

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

Finally for the wiring of the button. Nowhere in the tutorial you link to does it ever mention connecting the button to two IO pins. The button should only be connected to one IO pin. It also connects to +5V and, through the resistor, to ground.  Wire it up exactly as it shows you in the tutorial and make it work like that before you try fiddling with it.

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

  [1]: https://i.stack.imgur.com/7P6Qf.png
  [2]: https://i.stack.imgur.com/ZlNHZ.jpg
  [3]: https://i.stack.imgur.com/aIqtZ.png


message:
Why am I only receiving the first address byte? (I2C Protocol)

Expecting the slave to ACKnowledge and return data, but it does not. [This is my protocol][1]. [This is my Datasheet][2].

Also FYI I'm on an Arduino Fio but I am not inheriting the Arduino library.

    #include <avr/io.h>
    #include <util/delay.h>
    #include <stdlib.h>
    #include <uart.h>
    #include <i2c_master.h>

    #define LED PB5

    #define I2C_READ 0x5A

    char buffer[1];

    //char data[9];
    uint16_t val = 0;
    uint8_t status = 0;

    void getVal()
    {
      if(i2c_start(I2C_READ))
     {
      uart_puts("Start ");

      val = ((uint8_t)i2c_read_ack())<<8;
      val |= i2c_read_ack();

        status = ((uint8_t)i2c_read_nack());

       i2c_stop();

     } else
      {
      uart_puts("Error");

      i2c_stop();
     }
    }

    int main(void)
    {
      init_uart(57600);
      i2c_init();

      DDRB = _BV(5);

        for(;;)
        {

          getVal();

       itoa(status, buffer, 10); //convert decimal to string base 10
       uart_puts(buffer);

          PORTB = 0xFF;
          _delay_ms(500);
          PORTB = 0x00;
          _delay_ms(500);
        }
        return 0;   /* never reached */
    }

  [1]: https://gist.github.com/SensationSama/c60253c8553caf29f7353a725ee42fc4
  [2]: https://ams.com/eng/content/download/686523/1787697/file/iAQ-core_Datasheet_EN_v1.pdf

body:
(Acknowledging this is an old question.) The TI article "[Troubleshooting I2C Bus Protocol][1]", suggests several common reasons for no ACK:

    1. Timing
    2. Missing / Unexpected SCL pulses
    3. Incomplete 8 bit block
    4. Missing Bytes
    5. False slave address
    6. Unsuccessful address change

  [1]: https://www.ti.com/lit/an/scaa106/scaa106.pdf?ts=1610332691462&ref_url=https%3A%2F%2Fwww.google.com%2F


message:
Ultrasonic Range Sensor won't print distance in Serial Monitor

I'm using the red Ultrasonic Range Sensor with

Sig -> Digital Pin 4

VCC -> 5V

GND -> GND

The code uploads fine and i can hear the sensor clicking away, but for some reason it won't print the distance into the Serial Monitor.

    //Settings
    int echoPin= 4;
    int trigPin= 4;
    unsigned long pulsetime = 0;
    unsigned distance = 0;
    unsigned OldDistance = 0;

    void setup (){
      pinMode (echoPin, INPUT);
      pinMode (trigPin, OUTPUT);
      Serial.begin(9600);
    }

    void loop(){

      //Work out the distance
      digitalWrite(trigPin, LOW);
      delayMicroseconds(100);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(100);
      digitalWrite(trigPin, LOW);
      pulsetime = pulseIn(echoPin, HIGH);
      distance = pulsetime / 58;
      delay(10);

      //Send value if it's changed
      if (OldDistance != distance) {

      Serial.print(distance);

      OldDistance = distance;
      }

      delay(50);  // Wait .1 Seconds
    }

body:
You have to manually switch from OUTPUT (for sending the trigger pulse) and INPUT (for reading the distance) mode on the shared IO pin.

    //Work out the distance
    pinMode(trigPin, OUTPUT);    // << ADD THIS
    digitalWrite(trigPin, LOW);
    delayMicroseconds(100);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(100);
    digitalWrite(trigPin, LOW);
    pinMode(echoPin, INPUT);     // << ADD THIS
    pulsetime = pulseIn(echoPin, HIGH);
    distance = pulsetime / 58;
    delay(10);

To save some confusion you might like to change your code to just use `sigPin` instead of a pair of pins that are both the same pin.  That way you would avoid confusing bits like:

    pinMode (echoPin, INPUT);
    pinMode (trigPin, OUTPUT);

Which of course is the equivalent to:

    pinMode (4, INPUT);
    pinMode (4, OUTPUT);


body:
Two suggestions:

In `setup()` after you open the serial port, execute something like `Serial.println("Sensor Test Program");`, and in loop, print the distance value with something like `Serial.print("dist: "); Serial.println(distance);`

That will tell you two things:

 1. whether your port is open and working at all; and
 2. whether control reached your output statement (in loop) and that it tried to print something.

In this case, it seems unlikely that control didn't reach `Serial.print(distance);` but more information, at least in the early stages, helps when things don't work as you'd expected them to.

You should have seen _some_ output from your output statement, even if it was wrong. No output suggests:

 - control didn't get there (perhaps due to a program crash, especially if this is a fragment of a large program);
 - the terminal program and the Arduino's baud rates don't match;
 - the terminal program was opened to the wrong port;
 - the terminal program wasn't opened at all;
 - the calculation (or operation of the device, perhaps in the manner @majenko suggested) failed such that the distance calculation always yielded zero, and the 'if' statement was therefore never satisfied (my guess), i.e., back to my first point, control didn't get there.


message:
Proper way to run functions in loop

I am having a problem getting my functions to run properly from the loop.

I am building a model railroad crossing gate and need to run the 4 processes once the sensor signals the train entering the crossing zone. For right now I need to learn how to "function" in C++ running in loop, as I'm a C# ASP.Net guy.

My thought process was in loop to

 - Check entry sensor, this is all the loop should ever do UNTIL its tripped
 - Once tripped, run the 4 processes functions (close the gates, turn on the sound, turn on the flashers, power down the road that crosses the tracks)
 - After the entry sensor is tripped and the processes run (the sound and flashers should operate continuously until the exit sensor is cleared) the exit sensor must be monitored, and once its tripped, its monitored until it goes static again indicating the train has cleared. Then the 4 process are run to shut down the flashers, shut the sound, power up the road and raise the gates.

Right now I'm just trying to get the sound functioning properly. Right now, as the code stands, it plays for a split second then stops. I need that file playing until I call the function to stop it.

Here is the code so far. I've removed the includes and defines for brevity.

    // These are the pins used for the music maker shield
    #define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
    #define SHIELD_CS     7      // VS1053 chip select pin (output)
    #define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

    // These are common pins between breakout and shield
    #define CARDCS 4     // Card chip select pin
    // DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
    #define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

    // create shield-example object
    Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

    //global variables required
    boolean crossingSignalInOperation = false;
    boolean signalEntrySensor = false;
    boolean signalExitSensor = false;
    boolean debugMode = false;

    boolean checkEntrySensor() {
     //check entry sensor, if tripped return true otherwise false
     /*if () return true;
     return false;*/
     return true;  //hardcoded for testing
    }

    void setup() {
     // put your setup code here, to run once:
     Serial.begin(9600);
     debugMode = true;   //set this to false once code is fully operational
     //initialise music maker shield
      if (!musicPlayer.begin()) {
       if (debugMode)
       {
        Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
       }

      while (1);
     }
     // 1st parameter is left, second parameter is right
     musicPlayer.setVolume(20, 20);
     if (debugMode)
     {
      Serial.println(F("VS1053 found"));
     }

     // initialise the SD card
     SD.begin(CARDCS);

     //ensure our global booleans all start false
     crossingSignalInOperation = false;

    }

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

     signalEntrySensor = checkEntrySensor();
     if (signalEntrySensor == true) {  //only want to catch the FIRST time it senses
      if (crossingSignalInOperation == false)
      {
       //crossing signal is inactive, activate it
       // turn the sound on and return the music player object
       Adafruit_VS1053_FilePlayer mp = onSignalSound(musicPlayer,"trainxng.mp3");

       while (mp.playingMusic) {
        // file is now playing in the 'background' so now's a good time
        // to do something else
        if (!crossingSignalInOperation)
        {
         crossingSignalInOperation = true;
         //run the other three processes
         //offRoadPower();
         //lowerSignalArms();
         //startSignalFlashers();

        }
       }
      }
     }
     }

Here are the functions;

    Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
     // Play the train crossing sound file
     if (debugMode)
     {
      Serial.println(F("Playing track - "));
      Serial.print(fileName);
     }
     //all sound files are on the micro sd card on the music player shield
     if (!mp.startPlayingFile(fileName)) {
      Serial.println(F("Could not open file "));
      Serial.print(fileName);
      while (1);
     }
     return mp;
    }
    boolean offSignalSound(Adafruit_VS1053_FilePlayer mp) {
      if (mp.playingMusic)
     {
      mp.stopPlaying();
      return true;
     }
     return true;
    }

Any assistance would be appreciated.

Update:

New version using the state machine methodology suggested by JRobert and Edgar
Any comments on structure?

    // include SPI, MP3 and SD libraries
    #include <SPI.h>
    #include <Adafruit_VS1053.h>
    #include <SD.h>
    // include AccelStepper libraries
    #include <MultiStepper.h>
    #include <AccelStepper.h>
    using namespace std;
    /*-----( Declare Enums & Constants )-----*/
    // Arduino Digital I/O pin numbers for MEGA
    //note: digital pins 30-45
    //MEGA is a MUST for this project
    enum {
     Relay1 = 30, Relay2 = 31, Relay3 = 32, Relay4 = 33, Relay5 = 34, Relay6 = 35,
     Relay7 = 36, Relay8 = 37, Relay9 = 38, Relay10 = 39, Relay11 = 40,
     Relay12 = 41, Relay13 = 42, Relay14 = 43, Relay15 = 44, Relay16 = 45
    };

    enum { RELAY_OFF = HIGH, RELAY_ON = LOW };

    enum {
     CROSSINGZONE_CLEAR, // no train in crossing area, also initialized state
     CROSSINGZONE_OCCUPIED, // train detected by the entry sensor
     CROSSINGZONE_EXITING  // train detected by the exit sensor, when sensor clears state = CLEAR
    };

     enum {
      EXITSENSOR_CLEAR, // no train has passed the crossing gate exit sensor
      EXITSENSOR_ENTERED, // train detected by the exit sensor
      EXITSENSOR_WAITINGTOCLEAR // train passed by the exit sensor, when sensor clears state = CLEAR

     };

    byte state = CROSSINGZONE_CLEAR;
     //*-----( Declare Variables )-----*/
    // hardware is an optocoupler 16 channel 12V relay
    const byte relays[] = { Relay1,Relay2,Relay3,Relay4,
    Relay5,Relay6,Relay7,Relay8,
    Relay9,Relay10,Relay11,Relay12,
    Relay13,Relay14,Relay15,Relay16 };
    enum { maxRelayCount = sizeof relays / sizeof relays[0] };

    byte entrySensorPin = 26;
    byte exitSensorPin = 28;
    const char* soundFile = "trainxng.mp3";
    boolean debugMode = true;
    boolean exitSensorTripped = false;

    // These are the pins used for the music maker shield
    #define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
    #define SHIELD_CS     7      // VS1053 chip select pin (output)
    #define SHIELD_DCS    6      // VS1053 Data/command select pin (output)
    // These are common pins between breakout and shield
    #define CARDCS 4     // Card chip select pin
    // DREQ should be an Int pin, see  http://arduino.cc/en/Reference/attachInterrupt
    #define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

    AccelStepper gateMotor1Left(AccelStepper::DRIVER, 4, 3);  // 1=Stepper driver option, 4=Step pulse pin, 3=Direction
    AccelStepper gateMotor1Right(AccelStepper::DRIVER, 6, 5);  // 1=Stepper driver option, 6=Step pulse pin, 5=Direction
    AccelStepper gateMotor2Left(AccelStepper::DRIVER, 8, 7);  // 1=Stepper driver option, 8=Step pulse pin, 7=Direction
    AccelStepper gateMotor2Right(AccelStepper::DRIVER, 10, 9);  // 1=Stepper driver option, 10=Step pulse pin, 9=Direction
    Adafruit_VS1053_FilePlayer musicPlayer =
     Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

    class CrossingGate {
      public:
     // hmm voids or booleans?
     boolean GateFlashersOn(byte relayNumber) {
      digitalWrite(relayNumber, RELAY_ON);
      //need a check here to ensure its set LOW which is inactive for these relays
      return true;
     }
     boolean GateFlashersOff(byte relayNumber) {
      digitalWrite(relayNumber, RELAY_OFF);
      //need a check here to ensure its set HIGH which is inactive for these relays
      return true;
     }
     boolean GateArmFlashersOn(byte relayNumber) {
      digitalWrite(relayNumber, RELAY_ON);
      //need a check here to ensure its set LOW which is inactive for these relays
      return true;
      }
      boolean GateArmFlashersOff(byte relayNumber) {
       digitalWrite(relayNumber, RELAY_OFF);
      //need a check here to ensure its set HIGH which is inactive for these relays
      return true;
     }
     boolean GatesUp(byte relayNumber) {
      digitalWrite(relayNumber, RELAY_ON);
      //need a check here to ensure its set LOW which is inactive for these relays
      return true;
     }
     boolean GatesDown(byte relayNumber) {
      digitalWrite(relayNumber, RELAY_OFF);
      //need a check here to ensure its set HIGH which is inactive for these relays
      return true;
     }

    };

     class CrossingGateRoad {
       public:
        void PowerOn(byte relayNumber) {
         digitalWrite(relayNumber, RELAY_ON);

        }
        void PowerOff(byte relayNumber) {
         digitalWrite(relayNumber, RELAY_OFF);

        }
    };
    //  Sensor methods
    int CheckEntrySensor(byte esp) {
     if (digitalRead(esp) == HIGH)
     {
       state = CROSSINGZONE_CLEAR;
       return CROSSINGZONE_CLEAR;
     }
     else {
      state = CROSSINGZONE_OCCUPIED;
      return CROSSINGZONE_OCCUPIED;
     }
      return -1;
    }
    int CheckExitSensor(byte xsp) {
     if (digitalRead(xsp) == HIGH && state == CROSSINGZONE_OCCUPIED)
     {
      state = CROSSINGZONE_OCCUPIED;
      return CROSSINGZONE_OCCUPIED;
     }
     else if(digitalRead(xsp) == LOW && state == CROSSINGZONE_OCCUPIED)
        {
      state = CROSSINGZONE_CLEAR;
      return CROSSINGZONE_OCCUPIED;
     }
     return -1;
    }

    boolean CrossingBellsOn(Adafruit_VS1053_FilePlayer & mp, const char* soundFile) {
     if (!mp.startPlayingFile(soundFile)) {
      Serial.println("Could not open file trainxng.mp3 using the passed in object");
      while (1);
     }
     return true;
    }
    boolean CrossingBellsOff(Adafruit_VS1053_FilePlayer & mp) {
     if (mp.playingMusic) {
      mp.stopPlaying();
       return true;
     }
     if (mp.stopped())
     {
      return true;
     }
     return false;
    }

    CrossingGate xGate1Left;
    CrossingGate xGate1Right;
    CrossingGate xGate2Left;
    CrossingGate xGate2Right;

    CrossingGateRoad xGateRoad;

    void setup() {
     Serial.begin(9600);
     // Set max speed. Steps per second
     gateMotor1Left.setMaxSpeed(500);
     gateMotor2Left.setMaxSpeed(500);
     gateMotor1Right.setMaxSpeed(500);
     gateMotor2Right.setMaxSpeed(500);
     // set motor acceleration
     gateMotor1Left.setAcceleration(35);
     gateMotor2Left.setAcceleration(35);
     gateMotor1Right.setAcceleration(35);
     gateMotor2Right.setAcceleration(35);
     // set motor speeds
     gateMotor1Left.setSpeed(20);
     gateMotor2Left.setSpeed(20);
     gateMotor1Right.setSpeed(20);
     gateMotor2Right.setSpeed(20);

     Serial.println("Adafruit VS1053 Library Test");
     // initialise the music player
     if (!musicPlayer.begin()) { // initialise the music player
       Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
      while (1);
     }
     Serial.println(F("VS1053 found"));
     //musicPlayer.sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working
     // check the card reader
     if (!SD.begin(CARDCS)) {
      Serial.println(F("SD failed, or not present"));
      while (1);
     }
     Serial.println("SD OK!");
     // Set volume for left, right channels. lower numbers == louder volume!
     musicPlayer.setVolume(20, 20);

     // This option uses a pin interrupt. But DREQ must be on an
     //  interrupt pin. For Uno/Duemilanove/Diecimilla that's Digital #2 or #3
      // See http://arduino.cc/en/Reference/attachInterrupt for other pins
     // * This is the preferred method
     if (!musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT))
      Serial.println(F("DREQ pin is not an interrupt pin"));

    }
    void loop() {

     switch (state) {
         case CROSSINGZONE_CLEAR:
        // Check entry sensor. If tripped, turn on the sound.
       if (CheckEntrySensor(entrySensorPin) == 1) {
       // first go around i'll try to tun all these here otherwise
       // I will break out to more states
       //these happen instantly
       xGateRoad.PowerOff(relays[0]);
       xGate1Left.GateArmFlashersOn(relays[1]);
       xGate1Right.GateArmFlashersOn(relays[2]);
       xGate2Left.GateArmFlashersOn(relays[3]);
       xGate2Right.GateArmFlashersOn(relays[4]);
       xGate1Left.GateFlashersOn(relays[5]);
       xGate1Right.GateFlashersOn(relays[6]);
       xGate2Left.GateFlashersOn(relays[7]);
       xGate2Right.GateFlashersOn(relays[8]);
       //these take some time
       xGate1Left.GatesDown(relays[9]);
       xGate1Right.GatesDown(relays[10]);
       xGate2Left.GatesDown(relays[11]);
       xGate2Right.GatesDown(relays[12]);
       //this is the last process, if it completes change state
       if (CrossingBellsOn(musicPlayer, soundFile)) {
        state = CROSSINGZONE_OCCUPIED;
       }
      }
      else {
       state = CROSSINGZONE_CLEAR;
      }
      break;
     case CROSSINGZONE_OCCUPIED:
      // Once zone is occupied, monitor the exit sensor
      if (CheckExitSensor(exitSensorPin) == 0) { // Exit sensor not tripped yet
       state = CROSSINGZONE_OCCUPIED;
      }
      else {
       exitSensorTripped = true;
      }
      if (exitSensorTripped)
      {
        // need to code here to wait until Exit Sensor has 1500 milliseconds where its clear
       // to indicate that the last car of train has passed it
       // if above set exitSensorTripped back to false and state to EXITING
       state = CROSSINGZONE_EXITING;
      }
      break;
     case CROSSINGZONE_EXITING:
      // Check if the train has cleared, then shut the sound.
      if (CheckExitSensor(exitSensorPin) == 1) {
       // first go around i'll try to tun all these here otherwise
       // I will break out to more states
       //these happen instantly
       xGateRoad.PowerOn(relays[0]);
       xGate1Left.GateArmFlashersOff(relays[1]);
       xGate1Right.GateArmFlashersOff(relays[2]);
       xGate2Left.GateArmFlashersOff(relays[3]);
       xGate2Right.GateArmFlashersOff(relays[4]);
       xGate1Left.GateArmFlashersOff(relays[5]);
       xGate1Right.GateArmFlashersOff(relays[6]);
       xGate2Left.GateArmFlashersOff(relays[7]);
       xGate2Right.GateArmFlashersOff(relays[8]);
       //these take some time
       xGate1Left.GatesUp(relays[9]);
       xGate1Right.GatesUp(relays[10]);
       xGate2Left.GatesUp(relays[11]);
       xGate2Right.GatesUp(relays[12]);
       //this is the last process, if it completes change state
       if (CrossingBellsOff(musicPlayer)) {
        state = CROSSINGZONE_CLEAR;
       }
      }
      break;
     }
    }

body:
This is a classic state-machine problem. That isn't the only way to do it but it's just made for this kind of problem, one in which only certain external events are interesting at a given time; and when such an event occurs, the controller must tweak the outside world in some way, and then start paying attention to a different set of interesting events.

Does playing a sound file totally occupy the Arduino until the sound is done? And if so, can your process tolerate the controller being unresponsive for the duration of the sound track? Because otherwise you'll need something more capable than an Arduino, or you'll need to be able to program the Arduino to feed the sound in small pieces to a buffered sound card, so it (the Arduino) can continue monitoring the interesting set of possible events while the sound is playing. That probably means some clever programming with the SimpleTimer library or similar, or using interrupt service routines to inform some part of your code when an event occurs. Probably the ideal cases would be to have a "sound machine" that can play 'n' different tracks, and would do so autonomously when told to start playing track 'j'. Begins to sound like another MCU just handling sound, doesn't it?

Update:

Look up state machine diagrams - basically circles representing states and arrows representing transitions to a new state in response to an events. There are several ways to put the state machine's control of the external equipment; my choice is that each state "does something" then "waits for something to happen", where something to happen may include a clock signal indicating the event(s) it was waiting for didn't happen (i.e. a timeout). Look at some state diagrams to get an idea how they are used, then start diagramming your own project.

I draw the "happy path" straight down the page - that path that represents the normal or expected operation - with less usual or error paths drawn to either side. At that point you should be pretty confident in your algorithm.

There are several ways to code state machines - that'll be a further discussion.