body:
so I have a circuit with a buzzer and a resistor:
[![enter image description here][1]][1]

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

This circuit should be working, but for some reason the buzzer doesn't sound. I pushed the buzzer into the breadboard as hard as I could, I put the + side to positive and the - side to negative but it still doesnt work :(. How can I fix this?

Quick curiosity question: When I was doing electricity in school, the teacher just called the buzzers 'buzzers' but when I started doing arduino I noticed that the arduino community seems to call them 'Piezo buzzers/piezo speakers'. Is there any significance in the word 'Piezo' and should I start referring to them as 'Piezo buzzers' myself?

title: Circuit with buzzer not working :(

Answers: 3

body:
There is two kinds of buzzers - active and passive

 1. Passive buzzer means they can be operated by applying  just logic high to + and low to ground.

Digitalwrite function will do this job

2. Active buzzers needs pulses to make sound. Sound produced depends on the frequency.  Your buzzer might be a passive one. You can make a symphony by applying different frequencies..

'tone' function will help you for this

body: Try the toneAC library if it is a two pin piezo speaker... It generates weak alternating current, using two arduino pins. Your piezo will last longer. Works like old tone library. Remember to put a 100 ohm resistor in series :)

body: Buzzer coils get locked if a higher voltage is applied to the terminals - it could be 5-9 V. Once it gets locked it won't work even if you put direct battery to it. The only solution is to first take out your buzzer and give it a reverse voltage that will get the coil out of the lock position, then put 180 Ω resistor and run. It will work and it will never lock again.


body:
I am having a double value for example: 34.26 or 11.92 or 2.51. It should be rounded to the nearest 0.5 so 1.34 -> 1.50 and 32.78 -> 33 and 21.09 -> 21.00

How do to do this?

title: Arduino round to nearest 0.5

Answers: 3

body:
I made a little algorithm from the first thing that popped into my mind.
I'm using integers, since I believe it works better as floats.

For example, you can represent euro's (with floating points) by expressing them in cents.

    unsigned int roundToFifty(unsigned int nonRound){
        unsigned int rest = nonRound % 50;
        unsigned int fits = floor(nonRound / 50);
        unsigned int add = 0;
        if(rest >= 25){
            if(rest >= 75){
                add = 100
            }else{
                add = 50
            }
        }
        return fits*50+add
    }

I actually think the algorithm is a tad weird and something simpler/more effective could also exist. It was just the first thing that popped into my mind.

body:
It is a very bad idea to use float.
That being said. multiply by 2 and do a standard round.
Then divide back by 2.

For example:

    1.34     *2 = 2.68
    round(2.68) = 3
    3        /2 = 1.5

and

    32.78    *2 = 65.56
    round(65.56)= 66
    66       /2 = 33

body:
    float i=1.5237475984328953;
    #include "math.h"
    void setup()
    {
     Serial.begin(9600);
    }

    void loop() {
     Serial.println(i,6);
     float price = i*1000;
     Serial.println(price,2);

     float roundNearest = roundf(i*1000) ; // x 100 for two decimal place
      roundNearest = roundNearest/1000;
     Serial.println(roundNearest,6);

     price = (roundNearest*1000);
     Serial.println(price,2);
     while(1){}
    }

you u can use roundf()
like in this video [Demo Video][1]

  [1]: https://www.youtube.com/watch?v=pCcANoDHIdU


body:
I recently wrote the code for this project but it's weird because when I press button on the remote nothing shows up on the Serial Monitor and consequently the robot doesn't respond. I know it's not a hardware issue because when I used the IRrecv Demo sketch values were displayed on the serial monitor

Please tell me what's wrong! I'm sure there are a lot of talented programmers out there!!

    #include <IRremote.h>
    #include <AFMotor.h>
    AF_DCMotor rightMotor(1); // Right motor connected to port 1
    AF_DCMotor leftMotor(2); // Left motor connected to port 2
    IRrecv irrecv(A2);// IR receiver connected to pin A2(ANALOG PINS ON MOTOR             SHIELD USED AS DIGITAL INS!)
    decode_results results;
    #define Straight 0xC1CC42BD
    #define Right 0xC1CCA25D
    #define Left 0xC1CC22DD
    #define Back 0xC1CCC23D

    void setup(){
      Serial.begin(9600); // Establishing Serial Communication, THIS IS     IMPORTANT!!
      irrecv.enableIRIn(); // Start the receiver
    }
    void loop() {
      if (irrecv.decode(&results))
      {
          Serial.println(results.value, HEX);

          if((results.value)== Straight)
          {
          moveForward();
          }
          if((results.value)== Right)
          {
            turnRight();
           }
          if((results.value)== Left)
          {
            turnLeft();
          }
          if((results.value)== Back)
          {
            moveBackward();
          }
          else
          {
            Stop();
          }
          irrecv.resume();
      }
      delay(100);
    }

    void moveForward() {

        leftMotor.setSpeed(255);
        rightMotor.setSpeed(255);
        leftMotor.run(FORWARD);
        rightMotor.run(FORWARD);
    }

    void turnRight(){

      leftMotor.setSpeed(200);
      rightMotor.setSpeed(200);
      leftMotor.run(FORWARD);
      rightMotor.run(BACKWARD);
      delay(400);

      leftMotor.run(FORWARD);
      rightMotor.run(FORWARD);
    }

    void turnLeft() {

      leftMotor.setSpeed(200);
      rightMotor.setSpeed(200);
      leftMotor.run(BACKWARD);
      rightMotor.run(FORWARD);
      delay(400);

      leftMotor.run(FORWARD);
      rightMotor.run(FORWARD);
    }
    void moveBackward() {

        leftMotor.setSpeed(200);
        rightMotor.setSpeed(200);
        leftMotor.run(BACKWARD);
        rightMotor.run(BACKWARD);
    }

    void Stop(){
        leftMotor.setSpeed(0);
        rightMotor.setSpeed(0);

    }

title: Problem with code for IR remote controlled robot

Answers: 2

body:
Try replacing you loop function with this one.  It won't fix it.

    void loop()
    {
     if (irrecv.decode(&results))
     {
      Serial.println(results.value, HEX);

      switch (results.value)
      {
      case Straight:
       moveForward();
       break;
      case Right:
       turnRight();
       break;
      case Left:
       turnLeft();
       break;
      case Back:
       moveBackward();
       break;
      default:
       Stop();
      }
      irrecv.resume();
     }
     else
     {
      Serial.println ("Nothing received"); // This message will annoy you so comment it out as soon as you are happy with what is happening.
     delay(100);
    }

The switch statement is just a neater way of doing your ifs.  The Nothing received message will show you if decode is ever returning.  If it is returning you need to work out why it is returning false, by looking in the library code.  If it isn't returning then you need to look in the library code and see why.  If it is returning, but not giving you an expected value, you need to look in the library code and see why.

Sorry but from what you describe it seems to be an issue with the library or your use of it, could be anything, but when you can get some more info post it back here.

body:
You are using two libraries ([Arduino-IRremote][1] & [Adafruit-Motor-Shield-library][2]) which both use Timer2 on the microcontroller.

The motor library actually changes the setup of timer 2 (see line 92 of AFMotor.cpp) which will disrupt the timing that the IR sensor uses to determine the IR code received.

As far as I can see, the IR library is using Timer2 only. This means you should be able to change your motors over to port 3 & 4 which use Timer0 instead.

    AF_DCMotor rightMotor(3); // Right motor connected to port 3
    AF_DCMotor leftMotor(4); // Left motor connected to port 4

  [1]: https://github.com/z3t0/Arduino-IRremote
  [2]: https://github.com/adafruit/Adafruit-Motor-Shield-library


body:
I work on my first arduino car project and i want to turn my servo to a position with a letter input

This is my code so far

     #include <Servo.h>
    Servo servo;

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

     void loop() {

     if(Serial.available()>0){
     int  caz=Serial.read();
     switch(caz)
    {
      case 'w':
          digitalWrite(8,LOW);
          digitalWrite(7,HIGH);
          break;
      case 's':
          digitalWrite(7,LOW);
          digitalWrite(8,HIGH);
          break;
      case'd':
           servo.attach(12);
           servo.write(0);
           break;
      case'a':
           servo.attach(11);
           servo.write(180);
           break;
       default:
           digitalWrite(7,LOW);
           digitalWrite(8,LOW);
           servo.attach(0);
      }
    }

when i input 'a' or 'd' it starts turning until i input something else and i want it to stop after 10-30 degree .

And also i would like to do that to my motor , moving a bit when i input the key.

title: How to turn servo to a specific location and then turn over

Answers: 1

body:
Rather than writing to 180 and 0 write to a variable.

    static const int MovementAmount = 30; //degrees
    int position = 90;  // 90 is the start position.
    ...
    case 'd':
       servo.attach(12);
       position += MovementAmount;
       if (position > 180)
       {
         position = 180;
       }
       servo.write(position);
       break;


body:
I am working on a project where I am trying to send data using HTTP and POST method from my Arduino Mega2560 to a website which I host on localhost. I am living to a students' accommodation and thus, I do not have access to the router. However, I have bought a router and have connected it to the wall via the WAN. Also, the Arduino is connected to one of the ethernet plugs of the router via an Ethernet shield and my laptop to another ethernet plug. I am trying to retrieve the data from the website, but I cannot seem to load them.

**Arduino Code**

    #include <dht.h>
    #include <SPI.h>
    #include <Ethernet.h>

    dht DHT1;
    int temperatureSensorPin1 = 25;

    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    EthernetClient client;
    EthernetServer server(80);

    long previousMillis = 0;
    unsigned long currentMillis = 0;
    long interval = 250000;
    String data;

    long lastUpdate = 0;

    void setup() {

      Serial.begin(9600);
      if(Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
      }

      data = "";

      pinMode(temperatureSensorPin1, INPUT);
    }

    void loop() {

    int temp1 = DHT1.read11(temperatureSensorPin1);

    switch (temp1)
      {
        case DHTLIB_OK:
            Serial.print("OK,\t");
            break;
        case DHTLIB_ERROR_CHECKSUM:
            Serial.print("Checksum error,\t");
            break;
        case DHTLIB_ERROR_TIMEOUT:
            Serial.print("Time out error,\t");
            break;
        case DHTLIB_ERROR_CONNECT:
            Serial.print("Connect error,\t");
            break;
        case DHTLIB_ERROR_ACK_L:
            Serial.print("Ack Low error,\t");
            break;
        case DHTLIB_ERROR_ACK_H:
            Serial.print("Ack High error,\t");
            break;
        default:
            Serial.print("Unknown error,\t");
            break;
      }

      currentMillis = millis();
      if(currentMillis - previousMillis > interval) {
        previousMillis = currentMillis;
      }
      String data="temp1="+String(DHT1.temperature, 0)+"&temp2="+String(DHT2.temperature, 0)+"&temp3="+String(DHT3.temperature, 0)+"&temp4="+String(DHT4.temperature, 0)+"&temp5="+String(DHT5.temperature, 0)
                      +"&hum1="+String(DHT1.humidity, 0)+"&hum2="+String(DHT2.humidity, 0)+"&hum3="+String(DHT3.humidity, 0)+"&hum4="+String(DHT4.humidity, 0)+"&hum5="+String(DHT5.humidity, 0)+"&gas="+gasValue;

      Serial.println(Ethernet.localIP());
      if(client.connect("192.168.0.1", 80)) {
        client.println("POST /home/visualisation.php HTTP/1.1");
        client.println("Host:  192.168.0.1");
        //client.println("User-Agent: Arduino/1.0");
        //client.println("Connection: close");
        client.println("Content-Type: application/x-www-form-urlencoded;");
        client.print("Content-Length: ");
        client.println(data.length());
        client.println();
        client.print(data);
        //Serial.println(data);
        Serial.println("We have connection");
      }

      if(client.connected()) {
        Serial.println("We have abc");
        client.stop();
      }

      delay(4000);
    }

**PHP Code**

    <?php
    $temp1 = "";
    if(isset($_POST['temp1'])) {
     $temp1 = $_POST['temp1'];
    }
    echo $temp1;
    ?>
[Windows ip configuration][1]
[Router ip configuration][2]

Is the connection that I have made the appropriate one? How should I do it in order to work?

P.S.: I would like to clarify that I do not have an extended knowledge regarding networking.

**Router ip configuration**
*LAN*
MAC Address: 60-E3-27-E7-70-7A
IP Address: 192.168.0.1
Subnet Mask: 255.255.255.0

*Wireless*
Wireless Radio: Enable
Name (SSID): TP-LINK_707A
Mode: 11bgn mixed
Channel Width: Automatic
Channel: Auto (Current channel 3)
MAC Address: 60-E3-27-E7-70-7A
WDS Status: Disable

*WAN*
MAC Address: 60-E3-27-E7-70-7B
IP Address: 100.66.166.2 Dynamic IP
Subnet Mask: 255.255.255.192
Default Gateway: 100.66.166.1

DNS Server: 77.244.128.44 , 77.244.128.45

[![Windows ip configuration][1]][1]

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

title: POST data from Arduino to website

Answers: 1

body:
The ip that I have Arduino send data to is the router's and thus, I should have used the 192.168.0.100 ip which is the one of my computer.

I also needed to save the value to a database to notice the changes because *echo $temp1;* did not seem to work, probably I should have it included into HTML *label* tags. Anyway, I just loaded the value from the database into a PHP variable and I was able to accomplish the task.


body:
Well, I hope this question won' t be buried to the dark depths of this forum as my previous q' s:) But I suppose it won' t this time cause it's pretty short without this introduction part...

I have an Arduino pro mini works with 3.3V and in the other hand, I have a DS1307 DIP ic, works with +3V. I was wondering if I could connect the ic to my Arduino directly.

Thats all. Thanks already:)

title: connecting 3.3V to +3V

Answers: 1

body: The 3V input on the DS1307 is for a 3V battery, usually a CR2032 or similar. The *supply* voltage of the DS1307 is 5V, which means that it won't work with a 3.3V Arduino without a separate supply and level shifter.


body:
I am using a GeeeTech voice recognition module, I have recorded my voices using CoolTerm, and imported these voice commands in my sketch. However, when I plug in that voice recognition module, an error gets thrown: `avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00`; otherwise, it uploads normally. How can the computer and the Arduino lose connection when the voice recognition module gets plugged in? [![This is the USB that I used to record my commands][1]][1][![This is the Geetech voice recognition module I am using][2]][2]. I have checked my com ports, and checked the everything that it is connected to is correct.

  [1]: https://i.stack.imgur.com/LNtvb.png
  [2]: https://i.stack.imgur.com/rl7BJ.png

    #include <avr/sleep.h>
    #include <avr/power.h>
    //#include "math.h"
    //This sketch is a metronome, in which each led pin shows one beat.
    /**************************************/
    const int speaker = 13;//speaker at pin 13
    int ts = 6;//highest led pin
    int count = 3;//"beat 1 pin"
    const int keyPin = 11;//button to change time signature
    const int keyPinR = 10;//button to change rhythm
    const int keySwitch = 2;//sleep mode/wake up button

    //All pins below use a pull-up resistor, so the states are inverted
    int buttonState = LOW;
    int buttonState2 = LOW;
    int switchState = LOW;
    int silentState = LOW;

    int bpm = 120;//you do not need to know this,
    //it's just a variable for the potentialmeter to change the tempo
    int comdata;

    int rthm = 1;//rhythm
    int pressed = 0;//
    long silent = 0;

    byte com = 0; //reply from voice module
    /**************************************/

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

     for(int thisPin = 3;thisPin <= ts;thisPin++)
      {
         pinMode(thisPin,OUTPUT); //initialize thisPin as an output
         pinMode(12, INPUT); //potentialmeter for changing tempo

       //Pin 9 to 11, along with pin 2, are all push buttons with pull-up resistors
        for(int i = 9; i<=11; i++)
        {
          pinMode(i, INPUT);
          digitalWrite(i, HIGH);
        }
        pinMode(2, INPUT);
        digitalWrite(2,HIGH);
      }
    delay(2000);

    //imported voice commands
    Serial.write(0xAA);
    Serial.write(0x37);
    delay(1000);
    Serial.write(0xAA);
    Serial.write(0x21);

     Serial.print("Type in beats per minute");

    }

    /****************************************/
    void loop()
    {
      turnOn();
      getTS();
      getVoiceCommand();
    }

    void turnOn()
    {
        buttonState = digitalRead(keyPin);//key for
        buttonState2 = digitalRead(keyPinR);
        switchState = digitalRead(keySwitch);
        silentState = digitalRead(9);

        if(switchState==LOW) pressed++;

        if(pressed!=0)
        {
          sleep_enable();
          set_sleep_mode(SLEEP_MODE_PWR_DOWN);
          attachInterrupt(0, interrupt, LOW);
          sleep_cpu();
        }

      else{
        //The beat starts at pin 3, runs in consecutive pins, and ends at pin 8 at maximum

         if(buttonState==LOW){//changing time signature - up to 5 beats
                ts++;
              if(ts==8) ts = 3;  //8 - 3 = 5 beats max
         }
         if(buttonState2==LOW){//changing rhythm - quarter note to eighth, then
                 //triplets and sixteenths, back to quarter notes
               rthm++;
              if(rthm==5) rthm = 1;
         }
         if(silentState==LOW) silent++; //if silent key pressed, go to silence (only LED's showing)

          runMetronome();//Run the metronome
         }
      }

      void runMetronome(){
        for(int thisPin = 3;thisPin <= ts;thisPin++)
          //LED's blinking beats (thisPin - LED pin (beat number + 2))
          {
               for(int r = 1; r<=rthm; r++){//nested loop for the rhythm
                   bpm = pulseIn(12, HIGH);//pin 12 - tempo potentialmeter
                   digitalWrite(thisPin,HIGH);//each LED blinks
                   pinMode(13,OUTPUT); //pin 13 - speaker

                  silent%2==0 ? noTone(13) : (count==3 && r==1 ? tone(13,4400,80) :
                       r==1 ? tone(13,2500,80) : tone(13,2200,60));
                  delay((bpm-52)/rthm);
                  digitalWrite(thisPin,LOW);//turn each off as we proceed to the next beat (LED)
                  pinMode(13,INPUT);//speaker input
                }
              count++;//beat++

              if(count>ts) count = 3; //go back to beat 1
            }
        }

      void interrupt()  {
          sleep_disable();
          detachInterrupt(0);
      }

       void getTS(){
          if(Serial.available()>0){
              comdata = Serial.read();
              switch (comdata){
                  case '1': ts = 3; break;
                  case '2': ts = 4; break;
                  case '3': ts = 5; break;
                  case '4': ts = 6; break;
                  case '5': ts = 7; break;
                }
         }
       }
         void getVoiceCommand(){
            while(Serial.available()){
                com = Serial.read();
                switch(com){
                    case 0x11: ts = 3; break;
                    case 0x12: ts = 4; break;
                    case 0x13: ts = 5; break;
                    case 0x14: ts = 6; break;
                    case 0x15: ts = 7; break;
                  }
              }
          }

title: Voice recognition module: avrdude: stk500_getsync(): not in sync: resp=0x00

Answers: 1

body:
It's not loosing connection, there just can't be two devices on the same serial port (I suppose this setup)

You can use software serial for VR module, arduino with more hardware serials (=mega) or you can use another arduino as ISP programmer.


body:
I'm trying to program an Arduino MKR1000 and I am using the `millis()` function to emulate a traditional timer.  The problem is that any call to `millis()` inside the `debounceTimer()` function returns the same value.  I only added the `Serial.print` to debug.

I left out a decent bit of the code to simplify your reading of it.  It works by waiting for an interrupt on pin 4 which then calls the `runTimers()` function and that calls the `debounceTimer()` function and within that the `millis()` function is called. The `debouncetimer()` function keeps getting called until the 10 ms has elapsed and then should end the timer.  The problem is that the `millis()` function stops returning a value that goes up.

    #define doorIntPin 4
    unsigned char sysEnabled = 0;
    unsigned long debounceTimerPlace =0;
    unsigned char debounceTimerOn =0;

    void setup() {
      Serial.begin(9600);
      attachInterrupt(doorIntPin, doorOpens, LOW);
      interrupts();
    }

    void loop() {

    }
    void runTimers(){
      Serial.print('r');
      while(alarmTimerOn || debounceTimerOn || enablingTimerOn){
         if(alarmTimerOn)
          alarmTimer();
        if(enablingTimerOn)
          enablingTimer();
        if(debounceTimerOn)
          debounceTimer();
      }
    }

    void debounceTimer(){
      unsigned long time = millis()- debounceTimerPlace;
      Serial.println(millis() & 0xFFFF, DEC);
      if(sysEnabled && time> 10){
        debounceTimerOn=0;
      }
    }
    void doorOpens() {
      Serial.print('o');
      if(!debounceTimerOn){
          debounceTimerPlace = millis();
          debounceTimerOn=1;
      }
      runTimers();
    }

I suspect that in the background an interrupt is being called than increments the value `millis()` returns and somehow my external interrupt is disabling that.  I don't know why this is happening or how to fix it.

Any ideas?

title: millis() function always returns same value

Answers: 3

body: You never exit the ISR, hence all interrupts are disabled. Do the *minimum* work possible within an ISR, and have the main loop outside.

body: To answer your question about millis(), it uses interrupts to function, and so you can't call it within an ISR.  According to this: https://www.arduino.cc/en/Reference/AttachInterrupt, you should be able to use delayMicrosconds() within an ISR, since it (reportedly) doesn't use interrupts.

body:
> The problem is that the millis() function stops returning a value that goes up.

That's right. The value returned by `millis()` is incremented by an ISR which won't be called inside your other ISR.

You can use `micros()` which *will* increment. However that will only be good up to approximately 1 ms. The main rule of ISRs is that you don't attempt to do delays inside them.


body:
I found this [post][1] and I am having almost the exact same issue. Nick Gammon (the god of arduino) has an excellent answer but I can't for the life of me implement it myself. I am not an advanced user like the initial question asker.

So What I want to do is use 2 MCP23S17's ([picture here][2]).
I have been messing with one of them all week and have it reading like a charm. I am using the [githib library][3] by n0mjs710 to do this. But writing to one will not work.

Along with the zipped library is a few examples. I am trying to read some BCD switches off of one "input MCP" and then display the digits on the "output MCP"

I have used external pullups so I did make one change to the code by commenting out the call for pullups. Here is what Doesn't work:

    #include <SPI.h>              // We use this library, so it must be called here.
    #include <MCP23S17.h>         // Here is the new class to make using the MCP23S17 easy.

    MCP inputchip(1, 10);             // Instantiate an object called "inputchip" on an MCP23S17 device at address 1
                 // and slave-select on Arduino pin 10
    MCP outputchip(2, 10);            // Instantiate an object called "outputchip" on an MCP23S17 device at address 2
                // and slave-select on Arduino pin 10

    void setup() {
      inputchip.begin();
      outputchip.begin();
      inputchip.pinMode(0xFFFF);     // Use word-write mode to set all of the pins on inputchip to be inputs
      //inputchip.pullupMode(0xFFFF);  // Use word-write mode to Turn on the internal pull-up resistors.
      inputchip.inputInvert(0xFFFF); // Use word-write mode to invert the inputs so that logic 0 is read as HIGH
      outputchip.pinMode(0x0000);    // Use word-write mode to Set all of the pins on outputchip to be outputs
    }

    void loop() {
      int value;                        // declare an integer to hold the value temporarily.
      value = inputchip.digitalRead();  // read the input chip in word-mode, storing the result in "value"
      outputchip.digitalWrite(value);   // write the output chip in word-mode, using our variable "value" as the argument
      // outputchip.digitalWrite(inputchip.digitalRead()); // this one line replaces the three above, and is more efficient
    }

I have tried:

 - slowing the SPI bus by changing the library to SPI_Divide the clock by 2
 - changing the ss line and even splitting the lines so one chip uses pin 10 and the other uses pin 9

So after reading Mr. Gammon's post I have made some changes to the code attempting to rid myself ***of the old slave select pin low trick*** he mentioned. Here is my attempt:

    MCP inputchip(1, 10);             // Instantiate an object called "inputchip" on an MCP23S17 device at address 1
                 // and slave-select on Arduino pin 10
    MCP outputchip(2, 9);            // Instantiate an object called "outputchip" on an MCP23S17 device at address 2
                // and slave-select on Arduino pin 10
    int ssPin = 9;

    void setup() {
      pinMode(ssPin,OUTPUT);

      inputchip.begin();
      digitalWrite(ssPin, HIGH);
      digitalWrite(ssPin, LOW);
      outputchip.begin();
      inputchip.pinMode(0xFFFF);     // Use word-write mode to set all of the pins on inputchip to be inputs
      //inputchip.pullupMode(0xFFFF);  // Use word-write mode to Turn on the internal pull-up resistors.
      inputchip.inputInvert(0xFFFF); // Use word-write mode to invert the inputs so that logic 0 is read as HIGH
      digitalWrite(ssPin, HIGH);
      digitalWrite(ssPin, LOW);
      outputchip.pinMode(0x0000);    // Use word-write mode to Set all of the pins on outputchip to be outputs
    }

    void loop() {
      int value;
      // declare an integer to hold the value temporarily.
      value = inputchip.digitalRead();  // read the input chip in word-mode, storing the result in "value"
      digitalWrite(ssPin, HIGH);
      digitalWrite(ssPin, LOW);
      outputchip.digitalWrite(value);   // write the output chip in word-mode, using our variable "value" as the argument
    }

So any advice would be great to get this working. Help me Obi wan Gammon your me only hope.

  [1]: https://arduino.stackexchange.com/questions/14191/mcp23s17-programming-iodirx-register-works-in-loop-but-not-in-setup
  [2]: https://i.stack.imgur.com/XZman.jpg
  [3]: https://github.com/n0mjs710/MCP23S17

title: Arduino MCP23S17 I/O Expander (SPI)

Answers: 2

body: Majenko's library works. All praise to Majenko https://github.com/MajenkoLibraries/MCP23S17

body:
This sketch uses the [Majenko Library][1] with two MCP23S17 chips to demonstrate the library functions.

It was tested on an Arduino Uno with IDE 1.6.5.

    /*
     * MultiTest_Majenko_02.ino
     * Library Ref: github.com/MajenkoLibraries/MCP23S17
     *
     * Lowell Bahner
     * 2016-12-11
     *
     * Hardware: Arduino UNO
     * IDE: Arduino 1.6.5
     *
     * Useful SPI Ref: gammon.com.au/spi
     *
     * Wire the SPI Interface common lines (Mega2560 SPI pins shown in [ ]):
     * Arduino SPI_MOSI pin 11 [51] <->   SI  MCP23S17 pin 13
     * Arduino SPI_MISO pin 12 [50] <->   SO  MCP23S17 pin 14
     * Arduino SPI_CLOCK pin 13 [52]<->   SCK MCP23S17 pin 12
     * Arduino SPI_CS pin 10 [53]   <->   SS  MCP23S17 pin 11
     * MCP23S17 VDD pin 9 to +5V
     * MCP23S17 VSS pin 10 to Gnd
     * MCP23S17 Reset pin 18 to +5V
     * MCP23S17 Interrupt pins 19-20
     * MCP23S17 A0,A1,A2 pins connect to Gnd or +5V (000 = Address 0, 100 = Address 1, 010 = Address 2, etc)
     * MCP23S17 Port A pins are chip pins 21-28
     * MCP23S17 Port B pins are chip pins 1-8
     *
     * This sketch runs a series of functions to demonstrate library capabilities.
     * This sketch does not demonstrate interrupt functionality.
     *
     * This sketch instantiates 2 MCP23S17 chips.
     * Bank2 (MCP23S17 address 1) pins are set as INPUT or INPUT_PULLUP.
     *    Normally HIGH, use switch to set a pin LOW.
     * Bank1 (MCP23S17 address 0) pins are set as OUTPUT.
     *    MCP23S17 outputs will power LEDs up to 25ma through 1000ohm resistor to ground.
     *
     * Majenko MCP23S17 library functions (see .h,.cpp files for details):
     *
     *  bank.pinMode(uint8_t pin, uint8_t mode)
     *    where modes are:
     *      OUTPUT - sets pin HIGH
     *      INPUT  - sets pin LOW for sensing change to HIGH +V
     *      INPUT_PULLUP - sets pin HIGH for sensing change to LOW 0V
     *
     *  bank.digitalWrite(uint8_t pin, uint8_t value)
     *    if mode=OUTPUT, pin value = LOW (0) or HIGH (1)
     *    if mode=INPUT, value LOW disables pullup on pin, value HIGH enables pullup on pin
     *
     *  uint8_t value = bank.digitalRead(uint8_t pin)
     *    read the state of the pin
     *
     *  uint8_t value = bank.readPort(uint8_t port)
     *    read entire 8-bit port of all INPUT pins on Port A (port=0) or Port B (port>=1)
     *
     *  uint16_t longValue = bank.readPort()
     *    read both ports as 16-bit combined
     *
     *  bank.writePort(uint8_t port, uint8_t val)
     *    write val (0 or 1, hex example 0x55) to all OUTPUT pins on Port A (port=0) or Port B (port>=1)
     *
     *  bank.writePort(uint16_t val)
     *    write val (hex example 0x55AA) to all OUTPUT pins on Port A and Port B
     *
     *  Also, interrupt functions are defined:
     *      enableInterrupt(uint8_t pin, uint8_t type);
     *      void disableInterrupt(uint8_t pin);
     *      void setMirror(boolean m);
     *      uint16_t getInterruptPins();
     *      uint16_t getInterruptValue();
     *      void setInterruptLevel(uint8_t level);
     *      void setInterruptOD(boolean openDrain);
     *
     *
     *
     *
    Run Sketch: Serial Monitor Output

     -- RWpins() --

    Bank2: Switch i15: 1 (Push button switch not pushed, Bank2 INPUT pin 15 is HIGH +5V)
    Bank1: Output j4:  1 (Bank1 OUTPUT pin 4 is HIGH.
                          Arduino pin 7 is set HIGH.
                          LED on pin 4 is ON. LED on pin 7 is ON.)

    Bank2: Switch i15: 0 (Push button switch pushed, grounds Bank2 INPUT pin 15)
    Bank1: Output j4:  0 (Bank1 OUTPUT pin 4 switches to LOW.
                          Arduino pin 7 is set LOW.
                          LED on pin 4 is OFF. LED on pin 7 is OFF.)

     -- RWport() --

    Bank1: Port A BIN: 00000000
    Bank1: Port B BIN: 00000000

    Bank1: Port A BIN: 11110100  DEC: 244
    Bank1: Port B BIN: 00001011  DEC: 11

     -- RWlongPortValue() --

    Bank1: Port A & B BIN: 0000101111110100  HEX: 0x0BF4    DEC: 3060

     -- RWlongPort() --

    Bank1: Port A & B BIN: 1011100101000010  HEX: 0xB942    DEC: 47426

     -- CyclePins() --

    Bank1: Port A & B BIN: 0000000000000000  HEX: 0x0000    DEC: 0
    Bank1: Port A & B BIN: 0000000000000001  HEX: 0x0001    DEC: 1
    Bank1: Port A & B BIN: 0000000000000011  HEX: 0x0003    DEC: 3
    Bank1: Port A & B BIN: 0000000000000111  HEX: 0x0007    DEC: 7
    Bank1: Port A & B BIN: 0000000000001111  HEX: 0x000F    DEC: 15
    Bank1: Port A & B BIN: 0000000000011111  HEX: 0x001F    DEC: 31
    Bank1: Port A & B BIN: 0000000000111111  HEX: 0x003F    DEC: 63
    Bank1: Port A & B BIN: 0000000001111111  HEX: 0x007F    DEC: 127
    Bank1: Port A & B BIN: 0000000011111111  HEX: 0x00FF    DEC: 255
    Bank1: Port A & B BIN: 0000000111111111  HEX: 0x01FF    DEC: 511
    Bank1: Port A & B BIN: 0000001111111111  HEX: 0x03FF    DEC: 1023
    Bank1: Port A & B BIN: 0000011111111111  HEX: 0x07FF    DEC: 2047
    Bank1: Port A & B BIN: 0000111111111111  HEX: 0x0FFF    DEC: 4095
    Bank1: Port A & B BIN: 0001111111111111  HEX: 0x1FFF    DEC: 8191
    Bank1: Port A & B BIN: 0011111111111111  HEX: 0x3FFF    DEC: 16383
    Bank1: Port A & B BIN: 0111111111111111  HEX: 0x7FFF    DEC: 32767
    Bank1: Port A & B BIN: 1111111111111111  HEX: 0xFFFF    DEC: 65535

    Bank1: Port A & B BIN: 1111111111111111  HEX: 0xFFFF    DEC: 65535
    Bank1: Port A & B BIN: 0111111111111111  HEX: 0x7FFF    DEC: 32767
    Bank1: Port A & B BIN: 0011111111111111  HEX: 0x3FFF    DEC: 16383
    Bank1: Port A & B BIN: 0001111111111111  HEX: 0x1FFF    DEC: 8191
    Bank1: Port A & B BIN: 0000111111111111  HEX: 0x0FFF    DEC: 4095
    Bank1: Port A & B BIN: 0000011111111111  HEX: 0x07FF    DEC: 2047
    Bank1: Port A & B BIN: 0000001111111111  HEX: 0x03FF    DEC: 1023
    Bank1: Port A & B BIN: 0000000111111111  HEX: 0x01FF    DEC: 511
    Bank1: Port A & B BIN: 0000000011111111  HEX: 0x00FF    DEC: 255
    Bank1: Port A & B BIN: 0000000001111111  HEX: 0x007F    DEC: 127
    Bank1: Port A & B BIN: 0000000000111111  HEX: 0x003F    DEC: 63
    Bank1: Port A & B BIN: 0000000000011111  HEX: 0x001F    DEC: 31
    Bank1: Port A & B BIN: 0000000000001111  HEX: 0x000F    DEC: 15
    Bank1: Port A & B BIN: 0000000000000111  HEX: 0x0007    DEC: 7
    Bank1: Port A & B BIN: 0000000000000011  HEX: 0x0003    DEC: 3
    Bank1: Port A & B BIN: 0000000000000001  HEX: 0x0001    DEC: 1
    Bank1: Port A & B BIN: 0000000000000000  HEX: 0x0000    DEC: 0
     *
     *
     *
     */

    // Majenko MCP23S17 Library
    #include <MCP23S17.h>

    // Arduino Library SPI.h
    #include <SPI.h>

    // SPI CS/SS chipselect pin can be changed by user as desired
    const uint8_t chipSelect = 10;

    // example Arduino board pin
    uint8_t pin7 = 7;

    // Create an object for each chip
    // Bank1 is address 0. Pins A0,A1,A2 grounded.
    // Bank2 is address 1. Pin A0=+5V, A1,A2 grounded.

    MCP23S17 Bank1(&SPI, chipSelect, 0);
    MCP23S17 Bank2(&SPI, chipSelect, 1);

    void setup() {

      // Slow down the master a bit if desired
      SPI.setClockDivider(SPI_CLOCK_DIV8);

      Serial.begin(9600);

      Bank1.begin();
      Bank2.begin();

      // LED connected to Arduino pin 7 to test inter-device communication
      pinMode(pin7, OUTPUT);

      //
      // Set MCP23S17 pin modes:
      // example set one pin: chip.pinMode(0, OUTPUT); // sets chip pin 0 (Port A 0) to OUTPUT mode
      //
      // setChipPins(); // use loop to set individual pins
      // or, since this library does not have a setPortPinMode, do 8 pin loops
      setPortPins(); // example: set pins on each Port on each chip to different modes.
      //

    }

    // Set all Chip pins to desired mode
    void setChipPins() {
      // Example usage

      // Set all Bank1 pins to be OUTPUT
      for (uint8_t i = 0; i <= 15; i++)
        Bank1.pinMode(i, OUTPUT);

      // Set all Bank2 pins to be INPUT_PULLUP
      for (uint8_t i = 0; i <= 15; i++)
        //Bank2.pinMode(i, INPUT);  // unswitched pin voltages about +0.1V, switch must pull pin to +5V
        Bank2.pinMode(i, INPUT_PULLUP);  // unswitched pin voltages about +4.9V, switch must ground pin
    }

    // Set Port pins to desired mode
    void setPortPins() {
      // Example usage

      // Set all Bank1 Port A pins to OUTPUT
      for (uint8_t i = 0; i <= 7; i++)
        Bank1.pinMode(i, OUTPUT);

      // Set all Bank1 Port B pins to OUTPUT
      for (uint8_t i = 8; i <= 15; i++)
        Bank1.pinMode(i, OUTPUT);

      // Set all Bank2 Port A pins to be INPUT
      for (uint8_t i = 0; i <= 7; i++)
        Bank2.pinMode(i, INPUT);

      // Set all Bank2 Port B pins to be INPUT_PULLUP
      for (uint8_t i = 8; i <= 15; i++)
        Bank2.pinMode(i, INPUT_PULLUP);
    }

    //
    // Change LED On/Off with button push
    // 1) Switch an INPUT_PULLUP pin to ground
    // 2) Read the pin value
    // 3) Write the value to an OUTPUT pin
    // 4) Turn LED On/Off
    // Use functions digitalRead(pin) and digitalWrite(pin,value)
    //
    void RWpins() {

      Serial.print("\n -- RWpins() --"); Serial.println("");

      uint8_t b15 = 0;  // Bank2 input pin value (0 push LOW, 1 normally open HIGH) with push button switch to gnd
      uint8_t i = 15;   // Bank2 pin number
      uint8_t a4 = 0;   // Bank1 output pin value
      uint8_t j = 4;    // Bank1 pin number

      // read the switch value into b15
      b15 = Bank2.digitalRead(i);
      Serial.print("\nBank2: Switch i"); Serial.print(i); Serial.print(": ");  Serial.println(b15);

      // write the switch pin i, value b15, to the output pin j
      Bank1.digitalWrite(j, b15);

      a4 = Bank1.digitalRead(j);
      Serial.print("Bank1: Output j"); Serial.print(j); Serial.print(": ");  Serial.println(a4);

      // Turn on/off LED connected to Arduino pin 7 through resistor to ground
      digitalWrite(pin7, a4);
    }

    //
    // Read and Write Port values
    //
    void RWport() {

      Serial.print("\n -- RWport() --"); Serial.println("");

      // set the port pin modes
      setPortPins(); // all Bank1 pins are OUTPUT but set as Ports

      // clear the port pin values to 0
      uint8_t port = 0; // Port A
      uint8_t val = 0x00; // set to 0000 0000
      Bank1.writePort(port, val);
      port = 1; // Port B
      Bank1.writePort(port, val); // set to 0000 0000

      // read the port pin values
      uint8_t valueA = Bank1.readPort(0);
      Serial.print("\nBank1: Port A BIN: "); print8Bits(valueA); Serial.println("");
      uint8_t valueB = Bank1.readPort(1);
      Serial.print("Bank1: Port B BIN: "); print8Bits(valueB); Serial.println("");

      // set the port pin values
      port = 0; // Port A
      val = 0xF4; // set to 1111 0100
      Bank1.writePort(port, val);
      port = 1; // Port B
      val = 0x0B; // set to 0000 1011
      //val = 0xB0; // set to 1011 0000
      Bank1.writePort(port, val);

      // read the port pin values
      valueA = Bank1.readPort(0);
      Serial.print("\nBank1: Port A BIN: "); print8Bits(valueA);
      Serial.print("  DEC: "); Serial.println(valueA, DEC);

      valueB = Bank1.readPort(1);
      Serial.print("Bank1: Port B BIN: "); print8Bits(valueB);
      Serial.print("  DEC: "); Serial.println(valueB, DEC);
    }

    void RWlongPortValue() {

      Serial.print("\n -- RWlongPortValue() --"); Serial.println("");

      // Read the Bank1 Port pin values as a combined long value
      uint16_t valueLong = Bank1.readPort();
      Serial.print("\nBank1: Port A & B BIN: "); print16Bits(valueLong);
      Serial.print("  HEX: "); crPrintHEX(valueLong, 4);
      Serial.print("  DEC: "); Serial.println(valueLong, DEC);
    }

    void RWlongPort() {

      Serial.print("\n -- RWlongPort() --"); Serial.println("");

      // Write the Bank1 Port pin values as a combined long value
      uint16_t valueLong = 0xB942;
      Bank1.writePort(valueLong);

      // Read the Bank1 Port pin values as a combined long value
      uint16_t valueLongIn = Bank1.readPort();
      Serial.print("\nBank1: Port A & B BIN: "); print16Bits(valueLongIn);
      Serial.print("  HEX: "); crPrintHEX(valueLongIn, 4);
      Serial.print("  DEC: "); Serial.println(valueLongIn, DEC);
    }

    //
    // Cycle through OUTPUT pins with count-up count-down
    //
    void CyclePins() {

      Serial.print("\n -- CyclePins() --"); Serial.println("\n");

      // Set all Bank1 pins to be OUTPUT
      for (uint8_t i = 0; i <= 15; i++)
        Bank1.pinMode(i, OUTPUT);

      // clear Bank1 using writePort
      uint16_t valueLong = 0x0000;
      Bank1.writePort(valueLong);

      // Read the Bank1 Port pin values as a combined long value
      for (int8_t i = -1; i <= 15; i++) {
        if (i >= 0) Bank1.digitalWrite(i, 1); // i=-1 allows print of 0 data
        valueLong = Bank1.readPort(); // read 16 bits
        Serial.print("Bank1: Port A & B BIN: "); print16Bits(valueLong);
        Serial.print("  HEX: "); crPrintHEX(valueLong, 4);
        Serial.print("  DEC: "); Serial.println(valueLong, DEC);
      }

      Serial.println("");

      for (int8_t i = 15; i >= -1; i--) { // i=-1 allows print of 0 data
        // decrement after the read while reading down the values
        valueLong = Bank1.readPort(); //  read 16 bits
        Serial.print("Bank1: Port A & B BIN: "); print16Bits(valueLong);
        Serial.print("  HEX: "); crPrintHEX(valueLong, 4);
        Serial.print("  DEC: "); Serial.println(valueLong, DEC);
        Bank1.digitalWrite(i, 0);
      }
    }

    void loop() {

      // Change LED On/Off with button push
      RWpins();

      // Read and Write Port pins as a group
      RWport();

      // Read the Bank1 Port pin values as a combined long value
      RWlongPortValue();

      // Read and Write Chip 16 pins as a group
      RWlongPort();

      // Cycle through OUTPUT pins with count-up count-down
      CyclePins();

      delay(1000);

    }

    // print 8-bit byte as 8 bit binary string
    void print8Bits(uint8_t myByte) {
      for (byte mask = 0x80; mask; mask >>= 1) {
        if (mask  & myByte)
          Serial.print('1');
        else
          Serial.print('0');
      }
    }

    // print 16-bit word as 16 bit binary string
    void print16Bits(uint16_t myWord) {
      for (uint16_t mask = 0x8000; mask; mask >>= 1) {
        if (mask  & myWord)
          Serial.print('1');
        else
          Serial.print('0');
      }
    }

    //---------------------------------------------------------------------------------
    // crPrintHEX print value as hex with specified number of digits
    //---------------------------------------------------------------------------------

    void crPrintHEX(unsigned long DATA, unsigned char numChars) {
      unsigned long mask  = 0x0000000F;
      mask = mask << 4 * (numChars - 1);
      Serial.print("0x");
      for (unsigned int i = numChars; i > 0; --i) {
        Serial.print(((DATA & mask) >> (i - 1) * 4), HEX);
        mask = mask >> 4;
      }

      Serial.print("  ");
    }

  [1]: https://github.com/MajenkoLibraries/MCP23S17


body:
The MKR1000 is still pretty new and I'm having a hard time getting good information on it. I'm using the Arduino IDE but don't find any functions to sleep the MKR1000. Most libraries I encounter are for AVR chips while the MKR1000 has an ARM chip. I want to put it to sleep until an external interrupt is called. I also use the millis() function, will this function be rendered useless if it goes to sleep?

In the data sheet for the ATSAMD21 it talks about the Wait for Interrupt instruction which puts the machine to sleep but it doesn't say how to call the instruction. How can I do this in the Arduino IDE?

title: Powering Down Arduino MKR1000

Answers: 1

body:
The [rocketscream low power library][1] looks like it supports the ATSAMD21.

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


body:
I have an HC-SR04 attached to a servo. When the 90 degree reading is less than 30 cm, I want the motor to take 2 seconds to turn to 130 degrees, get a measurement on the right, and turn back to 90 degrees. My code does not seem to work. Even though I tell it to wait for 2000 ms, it skips directly to the if statement where the turning to 90 degrees is done. Here is the main code:

     #include <Servo.h>
    #define trig 22
    #define echo 24
    long duration;
    boolean turned130 = false;
    int cm50, cm, cm130;
    Servo servo;
    boolean checkRight = false;
    boolean mainPing = true;
    unsigned long counter;
    unsigned long servoTimer = millis();
    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(echo, INPUT);
    pinMode(trig, OUTPUT);
    servo.attach(12);
    servo.write(90);
    delay(2000);

    }

    void loop(){
    counter=millis();//my timer
      if(((counter-servoTimer) >= 250) && mainPing){//distance measured 4 times a second
        ping();
        cm=duration/29.1/2;
        Serial.println(cm);
        servoTimer=counter;//this if statement works fine
      }
      if((cm<30) && mainPing){

        mainPing=false;//makes the 90 degree ping and this if statement unable to run
        checkRight = true;//enables next if statement to run
        servoTimer=millis();
        servo.write(130);
        cm=30;//so that this if statement does not get called again until distance is obtained
        Serial.println("Inside less than 30 loop");//I added this for debugging, to let me know when the loop is called

      }
      if(checkRight && ((counter-servoTimer) >= 2000)){//after 2 seconds passes

        checkRight=false;
        ping();
        cm130 = duration/29.1/2;
        mainPing = true;//enable to other 2 if statements to run
        servoTimer=millis();
        Serial.println(cm130);
        servo.write(90);//turn motor back
        Serial.println("Inside other loop");//for debugging

      }

      delay(2);
      }

    void ping(){

        digitalWrite(trig, LOW);
        delayMicroseconds(2);
        digitalWrite(trig, HIGH);
        delayMicroseconds(10);
        digitalWrite(trig, LOW);
        duration = pulseIn(echo, HIGH);

    }
This is what I got in the Serial monitor:

    25//distance triggers 2nd if statement
    Inside less than 30 loop
    261
    Inside other loop
    13
    Inside less than 30 loop
    14
    Inside other loop
    14
    Inside less than 30 loop
    14
    Inside other loop
    3242
    13
    Inside less than 30 loop
    14
    Inside other loop

This all happened within milliseconds. There was no 2 second pause and the servo never turned. What is wrong with my code that prevents the motor from turning and waiting 2 seconds? The order of the Serial messages is correct, but it is happening fast.

EDIT:

When I remove the Serial messages and disconnect from the computer, it kind of works. By that, I mean it turns and waits for 2 seconds 50% of the time. Other times, the servo just shakes a little bit and stops.

Another thing I noticed is that if I leave only Serial.println(cm) message and Serial.println("Inside less than 30 loop"), this is the result that I observe.

        12
        13
        Inside less than 30 loop

        15
        3
        Inside less than 30 loop

For some reason the loop does not get triggered the first time. Is there a possibility that I have a defective Arduino Mega?

EDIT 2:

I tested the same setup on an official Arduino Uno and it did not work either. This means that I do not have a broken Arduino. Could the servo motor be broken? That won't explain the Serial messages though.

title: How come my code does not wait for a specific time before going into an if statement?

Answers: 1

body:
I added some more debugging, and I think I have your issues detected.

Amended code:

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

    #include <Servo.h>
    #define trig 22
    #define echo 24
    long duration;
    boolean turned130 = false;
    int cm50, cm, cm130;
    Servo servo;
    boolean checkRight = false;
    boolean mainPing = true;
    unsigned long counter;
    unsigned long servoTimer = millis();
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      pinMode(echo, INPUT);
      pinMode(trig, OUTPUT);
      servo.attach(12);
      servo.write(90);
      delay(2000);
    }

    void loop() {
      counter = millis(); //my timer
      if (((counter - servoTimer) >= 250) && mainPing) { //distance measured 4 times a second
        Serial.print ("Doing ping at time ");
        Serial.println (counter);
        ping();
        cm = duration / 29.1 / 2;
        Serial.println(cm);
        servoTimer = counter; //this if statement works fine
      }
      if ((cm < 30) && mainPing) {

        mainPing = false; //makes the 90 degree ping and this if statement unable to run
        checkRight = true;//enables next if statement to run
        servoTimer = millis();
        servo.write(130);
        cm = 30; //so that this if statement does not get called again until distance is obtained
        Serial.println("Inside less than 30 loop");//I added this for debugging, to let me know when the loop is called
      }
      if (checkRight && ((counter - servoTimer) >= 2000)) { //after 2 seconds passes
        Serial.print ("counter = ");
        Serial.println (counter);
        Serial.print ("servoTimer = ");
        Serial.println (servoTimer);
        checkRight = false;
        ping();
        cm130 = duration / 29.1 / 2;
        mainPing = true;//enable to other 2 if statements to run
        servoTimer = millis();
        Serial.print ("cm130 = ");
        Serial.println(cm130);
        servo.write(90);//turn motor back
        Serial.println("Inside other loop");//for debugging
      }
      delay(2);
    }

    void ping() {
      digitalWrite(trig, LOW);
      delayMicroseconds(2);
      digitalWrite(trig, HIGH);
      delayMicroseconds(10);
      digitalWrite(trig, LOW);
      duration = pulseIn(echo, HIGH);
    }

With no server (or anything) attached I get this output:

<!-- language: lang-none -->

    Doing ping at time 1999
    0
    Inside less than 30 loop
    counter = 1999
    servoTimer = 2693
    cm130 = 0
    Inside other loop

First note that `servoTimer` is somewhat higher than `counter` because the `pulseIn` function takes a while to execute (times out after 1 second allegedly, although that was less than a second).

Now we come to the problem "if" statement.

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

      if (checkRight && ((counter - servoTimer) >= 2000)) { //after 2 seconds passes

That can't be right, eh? `counter` is 1999 and `servoTimer` is 2693, and there is not 2000 difference. However you are doing the maths the other way:

<!-- language: lang-none -->

    counter - servoTimer =  1999 - 2693 = -694

Since we are using **unsigned long**, it cannot hold negative numbers so the result of the subtraction is 4294966602.

[![Unsigned long calculation][1]][1]

That is much larger than 2000, so the "if" branch is taken.

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


body: Does any one know how to use Gas Sensor module in Proteus. I wanna use Gas Sensor but I am unable to find it in Proteus. So, does anyone know any way of adding Gas Sensor Library for Proteus software. Thanks in advance.

title: Gas Sensor Library for Proteus

Answers: 1

body:
I have found the [Gas Sensor Library for Proteus][1], so I thought to share it here so that others can also get benefit out of it. They have also posted the complete method of How to use this Gas Sensor Library and have also given an example to download.

Thanks.

  [1]: http://www.theengineeringprojects.com/2016/05/gas-sensor-library-proteus.html


body:
My son and I are attempting to connect a TCS230 Color Sensor to an Arduino Nano using the tutorial at TopTechBoy.com (http://www.toptechboy.com/arduino/lesson-15-super-cool-arduino-color-sensor-project/) as guidance.

Everything seems to be working except that the conversion from pulseIn to RGB used on TopTechBoy is expecting a maximum pulse count of 102,400. Instead I am receiving pulseIn readings with a maximum of 2000.

Our Wiring

 S0  - GND
 S1  - 5V
 OE  - No Connection (Tried GND)
 GND - GND
 S2  - D8
 S3  - D7
 OUT - D4
 VCC - 5V

Our Code:

    int S2 = 8;
    int S3 = 7;
    int OUT = 4;

    void setup() {

    Serial.begin(9600);
    pinMode (S2, OUTPUT);
    pinMode (S3, OUTPUT);
    pinMode (OUT, INPUT);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      int red , green, blue;

      red = getRed();
      Serial.print("Red : "); Serial.println(red);
      Serial.println("**********************");
      Serial.println();

      blue = getBlue();
      Serial.print("Blue : "); Serial.println(blue);
      Serial.println("**********************");
      Serial.println();

      green = getGreen();
      Serial.print("Green : "); Serial.println(green);
      Serial.println("**********************");
      Serial.println();

      delay(3000);

    }

    int getRed(void){ return getColor(0, 0, 19000, 24000); }

    int getGreen(void){return getColor(1, 1, 13600, 19200);}

    int getBlue(void){return getColor (0, 1, 16400, 21600);}

    int getColor(int s2Value, int s3Value , int typicalPulseWidth, int maxPulseWidth){

      long divideForScale = typicalPulseWidth / 255 ;

      digitalWrite(S2, s2Value);
      digitalWrite(S3, s3Value);

      unsigned int pulseWidth = pulseIn(OUT,LOW);

      Serial.print("Pulse Width : "); Serial.println(pulseWidth);

      unsigned int rColor = pulseWidth / divideForScale ; //401.5686274509804
      Serial.print("Response Color - Inverted : "); Serial.println(rColor);

      rColor = 255 - rColor ;
      Serial.print("Response Color - Final : "); Serial.println(rColor);

      delay(500);

      return rColor ;

    }

The pulses appear correct, just out of scale. Red items produce short Red pulses and so on.

I tried to correct for the shorter pulses by using the Typical Output Frequency (f0) found on page 4 of the data sheet. I'm not sure if this is the right use of this frequency output spec.

http://www.unihedron.com/projects/darksky/tcs230-e33.pdf

Lowering the max possible pulses per second from 100,400 to around 20,000 gave us a little more variation between RGB values, but still the output is nothing like the expected color.

Can anybody offer some insight as to why the TCS230 pulse count is far fewer than the TTB code expects and what can I do to fix either the pulse count or the scale? Kind regards.

Output from Measuring a Blue RFID Keyfob:
    divideForScale : 74
    Pulse Width : 673
    Response Color - Inverted : 9
    Respponse Color - Final : 246
    Red : 246
    **********************

    divideForScale : 64
    Pulse Width : 376
    Response Color - Inverted : 5
    Respponse Color - Final : 250
    Blue : 250
    **********************

    divideForScale : 53
    Pulse Width : 737
    Response Color - Inverted : 13
    Respponse Color - Final : 242
    Green : 242
    **********************

title: TCS230 Low Pulse Length with Arduino

Answers: 2

body:
From the project page (a comment by Marius David) it seems some integer datatypes may not be the same on different platforms. If he is correct, you may be working with a 16 bit pulseWidth while 32 bits are needed.

Try using an `unsigned long` for the `pulseWidth` variable.

body:
Connect S0 to 5V to get 100% OUTPUT FREQUENCY SCALING.

Currently, with S0 LOW and S1 HIGH, you get 2% OUTPUT FREQUENCY SCALING. Which would explain the 50 times to low values you get (100% / 2% = 50).


body:
[![Bidirectional logic level converter][1]][1]
[1]: https://i.stack.imgur.com/NL4YV.jpg

THe product: (https://www.sparkfun.com/products/12009)

So guys, here' s a pretty simple but important question for me:
Can I convert 3.7V (li-po battery's voltage level) to 5V's (I do have arduino pro mini running on 5 volts) using 3.3v to 5v converter (picture shown above...) ??

Thanks already...

title: Can I convert 3.7V to 5V's using 3.3v to 5v converter

Answers: 1

body:
No. That is a level shifter. It uses a low voltage (3.3V) to switch a separate high voltage (5V) supply to create different logic levels.

It does not convert voltage, it merely switches.

To create 5V from 3.7V you need either a *boost converter* (inductor based circuit) or a *charge pump* converter (capacitor based circuit).


body:
Using `RCLib` ([github][1]) I'm getting this error. The trick is that the RCLib [example][2] works on it's own but does not work in my program ([github][3]).

**Serial Output "Error"**

    Pin 0 (62) you are trying to use is not supporting interrupts
    Pin 1 (63) you are trying to use is not supporting interrupts
    Pin 2 (64) you are trying to use is not supporting interrupts
    Pin 3 (65) you are trying to use is not supporting interrupts
    Pin 4 (66) you are trying to use is not supporting interrupts
    Pin 5 (67) you are trying to use is not supporting interrupts

  [1]: https://github.com/jantje/ArduinoLibraries/tree/master/RCLib
  [2]: https://github.com/jantje/ArduinoLibraries/blob/master/RCLib/Examples/Maga6ChanelsA8_A13/Maga6ChanelsA8_A13.ino
  [3]: https://github.com/jacksonkr/SwatBotSpine

Answers: 1

body:
It is quite right. Those pins aren't interrupt pins. What you want to do is make it use *PinChange interrupt* pins instead.

This can (by the look of things) be done by including the PinChangeInt.h library before including the RCLib library.


body:
I am interfacing an LCD with an Arduino. Sometimes it shows nothing after uploading the program. What should I do?

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

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

title: Arduino Mega LCD

Answers: 1

body:
An LCD will show blocks like that if it isn't initialized correctly.  You may have an intermittently-bad connection on one or more of the control lines.  [But see edit 1, below, regarding contrast adjustment.]

To diagnose intermittent connections, you could run a sketch that repeatedly initializes the LCD and then displays different sets of characters for a few seconds.  This will allow you to wiggle different pins and find out which is responsible for the bad connection.

To avoid intermittent connections, you could use a shield with soldered pins, or could get multipin shells to replace the single-pin shells of the Dupont-type connectors shown in the photograph.  Having adjacent connectors fixed in a single multipin shell results in more-stable connections.

---

*Edit 1:* As noted in a comment, blocks appearing on both lines is typical of contrast adjustment problems or missing contrast voltage.  On the other hand,  blocks appearing on just the first line is typical of incorrect  initialization, which could be caused by poor connections or by software errors.

---

Below is a sketch that repeatedly initializes the LCD and then displays different sets of characters for a few seconds each.

Note, if you don't have  the `Streaming.h` [contributed library](https://www.arduino.cc/en/Reference/Libraries) installed, you can get [`Streaming5.zip`](http://arduiniana.org/Streaming/Streaming5.zip) from [arduiniana.org](http://arduiniana.org/libraries/streaming/).

Note, if not using an I2C-interfaced LCD, change the included LCD library .h from `LiquidCrystal_I2C.h` to whatever is appropriate, and remove I2C-address-related stuff from the sketch.  If you are using an I2C-interfaced LCD on a known fixed address, remove the `lcd.setAddress(address);` and `lcd.getAddress(address);` stuff.  Those routines are not part of the usual LCD libraries; they probably can be added by subclassing `LiquidCrystal_I2C`, but on my system I added code as shown after the sketch.

---

    /* Screen-test sketch for PCF8574/PCF8574A/PCF8574T I2C LCD Backpack
    Uses library from https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads GNU General Public License, version 3 (GPL-3.0) */
    #include <Streaming.h>
    #include <Wire.h>
    #include <LCD.h>
    #include <LiquidCrystal_I2C.h>

    enum { LCDcols=16, LCDrows=2 };        // # of rows and cols on LCD
    enum { LCDaddr2=0x27, LCDaddr3=0x3F}; // For TI PCF8754 or PCF8754A
    LiquidCrystal_I2C lcd(LCDaddr2,2,1,0,4,5,6,7);

    void initLCD(byte address) {
      byte cdata[8];
      Serial << "initLCD(" << _HEX(address) << ')' << endl;
      lcd.setAddress(address);       // Set LCD I2C address
      Serial << "LCD address ... " << _HEX(lcd.getAddress()) << endl;
      // activate LCD module
      lcd.begin(LCDcols, LCDrows);
      lcd.setBacklightPin(3,POSITIVE);
      lcd.setBacklight(HIGH);
      lcd.noCursor();

      // Load custom characters
      for (int c=0; c<8; ++c) {
        unsigned int d = ((c+4)<<12 | (c|3)<<9 | (c|2)<<6 | (c|1)<<3 | c) ^ 0x5555;
        //Serial << "c=" << c << "  d=" << _HEX(d) << endl;
        for (byte k=0; k<8; ++k)
          cdata[k] = d >> k;
        lcd.createChar(c, cdata);
      }
      lcd.home ();
      lcd.print("Initialized");
      delay(1000);
    }

    void setup() {
      Serial.begin(115200);
      Serial << "Starting up" << endl;
      Wire.begin();                 // Setup to wirescan to check for 8754 addr
      Serial << "after Wire.begin()" << endl;
      TWBR = 152;  // 50 kHz, use if it works, or use slower rate
      TWBR = 158;  // 12.5 kHz, = slower rate
      TWSR |= bit (TWPS0);  // change prescaler
      Serial << "after TWBR / TWSR" << endl;
      Wire.beginTransmission (LCDaddr2);
      Serial << "after Wire.beginTransmission()" << endl;
      if (Wire.endTransmission() == 0) // Does 0x27 succeed?
        initLCD(LCDaddr2);      // Set up with 0x27 address
      else
        initLCD(LCDaddr3);      // Set up with 0x3F address
      Serial << "after initLCD()" << endl;
    }

    void show(char base, byte delt) {
      enum {MD=2000};
      byte k, ro;
      for (ro=0; ro<LCDrows; ++ro) {
        lcd.setCursor(0, ro);
        for (k=0; k<LCDcols; ++k) {
          lcd.print(base);
          base += delt;
        }
      }
      if (base==' ') {
        lcd.setCursor(1, 1);
        lcd << "LCD @" << _HEX(lcd.getAddress()) << " =" << lcd.getAddress();
      }
      delay(MD);
    }

    long p=0;
    void loop() {
      byte c;
      Serial << "Pass " << p++ << " on " << _HEX(lcd.getAddress()) << " at t=" << millis() << endl;
      lcd.home ();   // Set cursor to 0,0
      show('#', 0);   // Screen of # characters
      show(' ', 0);   // Screen of ' ' characters
      show('@', 0);   // Screen of @ characters
      show( 0,  1);   // lo specials + ' '...'/'
      for (c=' '; c < '~'; c+=16)
        show(c, 1);

      lcd.setBacklight(HIGH);
      while (Serial.available()) {
        c = Serial.read();
        if (c == '2') initLCD(LCDaddr2);
        if (c == '3') initLCD(LCDaddr3);
      }
    }

---

To add `lcd.setAddress(address);` and `lcd.getAddress(address);` routines:

 // add after void setBacklight(...); in LiquidCrystal_I2C.h
    void setAddress(uint8_t addr);
    uint8_t getAddress();

and

    // add after void setBacklight(...); in LiquidCrystal_I2C.cpp
    void LiquidCrystal_I2C::setAddress(uint8_t addr) {
      LiquidCrystal_I2C::_Addr = addr;
    }
    uint8_t LiquidCrystal_I2C::getAddress() {
      return LiquidCrystal_I2C::_Addr;
    }


body: I'm kind of curious as to why there is a 0.1uF capacitor on this Arduino Pro Mini (https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf). It seems like it would work just fine without it.

title: Why does this Arduino Pro Mini use a capacitor on the DTR reset line?

Answers: 1

body:
Most USB to serial chips set the DTR to LOW on connecting, but it keeps it LOW.

This would reset the arduino, but since the DTR never goes HIGH the Arduino will never get out of this reset state, and not run your code.

The capacitor will AC couple the signal. The the DTR goes low, the other side of the capacitor will go LOW too, but the pull-up resistor will slowly charge the capacitor, till the reset pin is HIGH again.

So it will convert a LOW transition to a LOW pulse.


body:
I have an ESP8266 module attached to an Arduino Uno that is connected to my local network. On the network, at address 192.168.1.13, I have a nodejs/express server running on port 3000. How would I go about posting an eight digit number from the Arduino to the webserver? In my current attempts the server console isn't receiving any data when using AT+CIPSEND while connected to it.

EDIT: My Code is as follows:

         #include <SoftwareSerial.h>

    const byte rxPin = 9; // Wire this to Tx Pin of ESP8266
    const byte txPin = 10; // Wire this to Rx Pin of ESP8266

    // We'll use a software serial interface to connect to ESP8266
    SoftwareSerial ESP8266 (rxPin, txPin);

    void setup() {
      Serial.begin(9600);
      ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
      delay(1000); // Let the module self-initialize
      Serial.println("Sending an AT command...");
      ESP8266.println("AT+CWMODE=1");
      delay(1000);
      ESP8266.println("AT+CWJAP=\"username\",\"pass\"");
      delay(10000);
      ESP8266.println("AT+CIPMODE=1");
      delay(1000);
      ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\test\",3000");
      delay(1000);
      GetData();

    }
    void loop() {
     while (ESP8266.available()){
         String inData = ESP8266.readStringUntil('\n');
         Serial.println("Got reponse from ESP8266: " + inData);
      }
    }
    void GetData(){
      ESP8266.println("AT+CIPSEND=4");
      ESP8266.print("test");
    }

and My output is this

      Sending an AT command...
    Got reponse from ESP8266: AT+CWMODE=1

    Got reponse from ESP8266:

    Got reponse from ESP8266: OK

    Got reponse from ESP8266: AT+CWJAP="surveillancevan4","7073199495"

    Got reponse from ESP8266: AT+CIPSEND=4

    Got reponse from ESP8266: testI

EDIT 2: I modified my code to this

        #include <SoftwareSerial.h>

    const byte rxPin = 9; // Wire this to Tx Pin of ESP8266
    const byte txPin = 10; // Wire this to Rx Pin of ESP8266
    // We'll use a software serial interface to connect to ESP8266
    SoftwareSerial ESP8266 (rxPin, txPin);

    void setup() {
      Serial.begin(9600);
      ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
      ESP8266.println("AT");
      delay(1000);
      ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\",3000");
      delay(20000);
      String request = "POST /test HTTP/1.0 \r\n";
      ESP8266.println("AT+CIPSEND=19");
      delay(5000);
      ESP8266.println(request);

    }

    void loop() {
     while (ESP8266.available()){
         String inData = ESP8266.readStringUntil('\n');
         Serial.println("Got reponse from ESP8266: " + inData);
      }
    }
and now my output claims it posted successfully, but I'm still not seeing any data in my nodejs server. Here is the output:
Got reponse from ESP8266:

    AT

    Got reponse from ESP8266:

    Got reponse from ESP8266: OK

    Got reponse from ESP8266: AT+CIPSTART="TCP","192.168.1.13",3000

    Got reponse from ESP8266: CONNECT

    Got reponse from ESP8266:

    Got reponse from ESP8266: O

    Got reponse from ESP8266: busy sytes

    Got reponse from ESP8266:

    Got reponse from ESP8266: SEND OK

I can confirm that it is connecting to my web app because when I run the code on the module without the server running it returns an error.

title: Posting data with ESP8266 module?

Answers: 1

body:
     ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\test\",3000");

That line is going to fail miserably for a number of reasons:

1. You need to provide an IP address or domain name - NOT a URL
2. Even if you could provide a URL this bit `192.168.1.13\test` would end up, after C escaping, as `92.168.1.13        est` since `\t` is a TAB character.

And then on top of all that I assume you are connecting to a HTTP server, yet you aren't sending a HTTP request, you are just sending the word "test", which the HTTP server has no hope of ever understanding.

You need to formulate and send a proper HTTP request and send it to the server. I suggest you go and look at a few tutorials and maybe look up how HTTP Servers actually operate and what the protocol looks like.


body:
I took just Arduino Uno board, connected Ethernet Shield to it and compiled Web Server example. And it works.

But it outputs:

    analog input 0 is 1023
    analog input 1 is 1023
    analog input 2 is 789
    analog input 3 is 663
    analog input 4 is 525
    analog input 5 is 449

Why so different values? Shouldn't it be zeros? Is this static electricity or what?

title: Why so different not connected analog inputs?

Answers: 1

body: Floating inputs, EMI, high input impedance and sample-and-hold capacitor. It can measure anything at this point (usually electro static charge is split between pin capacity and S&H capacitor. It can be used even for touch sense pins...


body:
I have a simple sketch here that should just blink a led once a second or so (approximately):

    boolean onOff=true;
    int count=0;

    void setup() {
      pinMode(13, OUTPUT);
     }

    void loop() {
        count++;
        delay(1);

        if (count == 316) {
        onOff=!onOff;
        digitalWrite(13, onOff);
        count=0;
        }
    }
So, if `count` is 316 it changes the state of led. It works right now, but it does not without `delay()` function or some other complex ones like `digitalWrite()` being in the `loop()` too. If i am deleting `delay()`, than led is just always on. I can feel it is smth about interrupts, but i am not sure.

----------

 What am i trying to do here is to make an alternative to `delay()` and `millis()` for my other project. One of the most needed thing for me is to make ASAP (as soon as possible) "timer", so that some code could run every 2(3-4...) iterations of loop(). delay() is bad always, and millis() uses `long` variable (which is bad for cpu time and ram), and while having problems with ram and cpu time in my project, i want smth lighter for ASAP and other not very precise timing.  So, the questions are:

 1. Why does my sketch works only with delay(), but does not work
    without it?
 2. Why does blinking sketches work with millis(), while they do not use any delay() just like my sketch.
 3. Am i a bad person for trying to make smth like an ASAP timer?:)  Is saved ram and cpu time worth of it?  Any other possible problems?
 4. Can this sketch be workable without `delay()` or other complex or ram and cpu costly functions?

Thank you.

So, the sketch up there works indeed, but here is the version that you can can observe with your eyes:

    boolean onOff=1;
    unsigned int counter=0;
    unsigned long time=0;

    void setup() {
      pinMode(13, OUTPUT);
      Serial.begin(57600);
    }

    void loop() {
       if (counter==0)  time=micros();
        counter++;
        if (counter == 0) {
            onOff= !onOff;
        digitalWrite(13, onOff);
        Serial.println(micros()-time);
        }
    }
With Serial i was checking delay between blinks, and it is 140164 mcs = 140 ms = 0.14s. But to be honest it feels slower, so please correct me if i can benchmark it in a better way.

title: Sketch does not work without delay() or other complex functions like digitalWrite()

Answers: 2

body:
As majenko answered in the comments, the blinking rate will be so fast you can not see it.
Also it is possible that without the delay the optimizer removes the whole counting. So increasing the number as proposed by majenko may not even work due to compiler optimisations.
Using a method based on counters is a very unreliable way to use timings.

Look at the blinkwithout delay example as proposed by Dirk.
It boils down to using millis() for timing. millis tells you how many millis the arduino is running.

    void loop() {
      // here is where you'd put code that needs to be running all the time.

      // check to see if it's time to blink the LED; that is, if the
      // difference between the current time and last time you blinked
      // the LED is bigger than the interval at which you want to
      // blink the LED.
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }

        // set the LED with the ledState of the variable:
        digitalWrite(ledPin, ledState);
      }
    }

body:
This sketch blinks an LED on D10 (on a Uno) at one second intervals. It does not use `delay`, `micros`, `millis` or any unsigned long variables (apart from a constant).

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

    const int STROBE_FREQ = 1000;     // sets the period in milliseconds
    const unsigned long countTo = ((float) F_CPU / 1024.0) / (1000.0 / STROBE_FREQ);

    void setup ()
      {
      // D10 to output
      bitSet (DDRB, 2);

      // Fast PWM top at OCR1A
      TCCR1A = bit (WGM10) | bit (WGM11); // fast PWM
      TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS12) | bit (CS10);   // fast PWM, prescaler of 1024
      OCR1A = countTo - 1;                 // zero relative
      OCR1B = (countTo / 2) - 1;           // 50% duty cycle
      bitSet (TCCR1A, COM1B1);   // clear OC1B on compare
      }  // end of setup

     void loop ()
       {
        // do something useful
       }

It frees up the main loop to do something useful without worrying about time taken to do the blinking.

For more details see [my page about timers](http://www.gammon.com.au/timers).


body:
I have a water counter which switches reed on each 10 liters of water. I would like to count these values with Arduino.

I wrote a program which counts changes from analog input and connected counter between `+5V` and analog input. It counts well but I am doubt I connected correctly. Because when reed is opened, then analog input is connected to nothing, while it should be connected to `GND`.

How to implement correct conversion from reed to analog or digital input?

title: How to encode resistance change (reed) for Arduino?

Answers: 1

body: A reed switch is just a button. Treat it as such. Either connect it between a digital input and ground, with a pull-up resistor (internal one would do) or between a digital input and +5V and use a pull-down resistor.


body:
I am working on a project that I am supplying with voltage an LED through a digital pin (26) and I want the LED to be switched off after 4 seconds.

I am using Arduino Mega2560 and I am programming it using Arduino's IDE version 1.6.10. I have installed the SimpleTimer library .zip method but it does not seem to function.

**Code**

    #include <SimpleTimer.h>

    SimpleTimer timer;

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

    timerId = timer.setTimeout(4000, switchOff);
    }

    void switchOff() {
      digitalWrite(26, LOW);
    }

    void loop() {
    }

The problem is that the LED stays just on (*digitalWrite(26, HIGH);*) instead of going to the *switchOff* function and turning off (*digitalWrite(26, LOW);*). I have also tried using Timer1 and Timer libraries but they also do not work. Can someone who has made any of the libraries work, provide me with some guidance?

title: Perform function after a period of time

Answers: 1

body:
You have to call `timer.run()` inside loop function.

The SimpleTimer library is more like a scheduler. You call at every so often, and it checks if there is any event that has expired.


body:
This is the multi serial example from Arduino IDE

    void setup() {
      // initialize both serial ports:
      Serial.begin(9600);
      Serial1.begin(9600);
    }

    void loop() {
      // read from port 1, send to port 0:
      if (Serial1.available()) {
      // plus do some operations
        int inByte = Serial1.read();
        Serial.write(inByte);
      }

      // read from port 0, send to port 1:
      if (Serial.available()) {
        // plus do some operations
        int inByte = Serial.read();
        Serial1.write(inByte);
      }
    }

As you can see, the loop is running multiple times doing almost nothing at most of cycles, this will eat up battery life (if it has one).

Is it possible to read when data is available without looping, just like with an interrupt.

Also, is it a good practice to run a loop all the time? Is there any way to sleep? I have seen examples like this one http://playground.arduino.cc/Learning/ArduinoSleepCode which uses some other pin to wake up. I don't want that.

title: Interrupt driven serial in Arduino Mega

Answers: 2

body:
Why do you not want to sleep the processor? If it's running at all, it doesn't matter whether it is polling the UARTs or executing something else; it will still be using power.

The first several paragraphs of the article you linked to describe putting the processor into low-power mode and reducing the power consumption further by disabling some internal hardware modules. When the UART receives a byte, the processor will wake up and continue execution from where it slept. Isn't that what you are asking for?

body:
Serial input can wake the processor from sleep, assuming it is useful for it to sleep (for example, if it is battery-powered).

[My page about power](http://www.gammon.com.au/power) shows various technicques including using serial input to wake it from sleep (see reply #8 on that page). However a disadvantage of that is, it take a few microseconds to wake from sleep - sometimes quite a few - so you are likely to lose the first byte received from serial if you are asleep.

> Also, is it a good practice to run a loop all the time?

There is no harm, except for battery consumption.


body:
I'm creating a data-logger system which logs data in SD card at a high speed of about 20000-30000 bytes per second. But the SD library in arduino currently writes data at about 4500-5000 bytes per second which is too slow.

I've read this [hack to improve the write speed][1], but I'm wondering if a more direct approach is possible, maybe by adjusting the [SPISettings][2].

  [1]: https://hackingmajenkoblog.wordpress.com/2016/03/25/fast-efficient-data-storage-on-an-arduino/
  [2]: https://www.arduino.cc/en/Reference/SPISettings

title: How to increase SD card write speed in arduino

Answers: 3

body:
Many factors would decide if you can reach this wanted speed. Only some of these.

----------

1. Your Software
-----------

The [SdFat][1] Library is faster than the standard SD Library of the Arduino IDE. It also has an easy to use compatibility function with the standard SD Library. Try it out.

2. Your Hardware
----------------
You should use a high class SD Card. As you maybe know SD Cards are sorted into performance classes. Most people in the internet recommend a SanDisk SD Card.

  [1]: https://github.com/greiman/SdFat

body:
OK. So, I tried the SDFat lib. This library is definitely better than the default SD library that comes with adruino.
But that is not how I solved my problem of low data-rate.

I followed the instruction of the author of SDFat library from [***this post***][1].

According to *fat16lib*, to increase the data rate we need to use flush() wisely. We would want to write() the data in each cycle, but we only need to flush() once every 100 cycles or so depending on how much data is being written in each cycle. Also, be sure to keep the flag in SD.open() as 'O_WRITE | O_CREAT' instead of 'FILE_WRITE'.

This sure increased the speed by a great factor. But I needed more!

Storing the data in binary ([check out this blog][2]) improved the performance even more.

My current speed is approximately 100-120 KBps (that's kilo bytes) with a class 4 SD card!

Finally, I want to thank you guys for your help.

  [1]: http://forum.arduino.cc/index.php?topic=49649.msg354701#msg354701
  [2]: https://hackingmajenkoblog.wordpress.com/2016/03/25/fast-efficient-data-storage-on-an-arduino/

body:
Avoid the handshake getting a buffer!

Use
**SD.write(buf,size);**

Hi every one, I'm working in a project with the same issue. I was following the same steps of yours and got exactly the same numbers. I've just fixed it out. The problem is the handshake when you call the `SD.write()`.

Instead:

    //for each loop, it is going to make a handshake
    while(<yourCondition>){
        SD.write(<yourValue>);
    }

Do:

    char buf[length];
    while(yourCondition){
        buf[index] = yourValue;
    }
    SD.write(buf,index);//only one handshake

In my project the first one I got **4100** bytes, and the second one using a buffer with 128 (buf[128]) I got **145408** bytes in my project. Good enough.


body: I am using Arduino Uno. I want to control my room lamp both manually and over the network, so when I switch off my lamp manually, how do I get acknowledgement over the network that lamp is off ?

title: Arduino connection confirmation

Answers: 0


body:
In my current project, I want the sensor to be continuously scanning for a value of less than 30cm. I was wondering how long of a delay I need (if any) between each call of the ping function. It currently works at 150ms between each ping call with no problem. The less the delay, the better for my project. This is the ping function:

    void ping() {
      digitalWrite(trig, LOW);
      delayMicroseconds(2);
      digitalWrite(trig, HIGH);
      delayMicroseconds(10);
      digitalWrite(trig, LOW);
      duration = pulseIn(echo, HIGH);
    }

For example, would having a delay of only 5ms be sufficient?

title: How often can I ping an HC-SR04 ultrasonic sensor?

Answers: 2

body:
> How often can I ping an HC-SR04 ultrasonic sensor?

This ping() function is vulnerable to interrupts during the pulseIn(). This implies that a delay needs to wait for queued interrupts as from, for instance, Serial output. Input interrupts may still affect the results. This function only works in very simple sketches.

Possible solutions are to 1) disable during the pulse measurement (not the wait for pulse start), 2) use a more advanced method to allow concurrent events (such as timer capture).

Cheers!

body:
[Documentation from elecfreaks.com][1] recommends 60 milliseconds between measurements. That'll cut down your time by ~60% (from your 150ms delay). It works for me.

  [1]: http://www.elecfreaks.com/244.html


body:
I am building a robot with multiple sensors, abilities etc. Since I had a bug with a HC-SR04 rotated by a servo, I experimented in a different sketch. If the distance is less than 30cm, the servo turns left and right. Since I need continuous readings of other sensors, I cannot use delays so I used millis in order to keep time. The sensor worked correctly in a different sketch, but something in the full one conflicts with it.

    #include <LiquidCrystal.h>
    #include <Wire.h>
    #include <RTClib.h>
    #include <Servo.h>
    #include <IRremote.h>

    RTC_DS1307 rtc;

    /*const int blue2 = 12;
    const int blue1 = 11;
    const int red1 = 10;
    const int red2 = 9;
    */
    Servo servo;

    byte leds[4] = {8, 7, 6, 9};

    const int STBY1=45;
    const int ain11=47;
    const int ain12=43;
    const int aPWM1=2;
    const int bin11=41;
    const int bin12=40;
    const int bPWM1=4;
    const int STBY2 = 39;
    const int ain21=33;
    const int ain22=31;
    const int aPWM2=5;
    const int bin21=35;
    const int bin22=37;
    const int bPWM2=3;

    const int piezo = 32;

    const int flamePin = A7;

    int flameState;

    const int photoResistor = A1;

    int photoState;

    const int temp = A2;

    float temperature;

    int ledAnalog;

    const int irGnd = 52;

    const int irVcc = 50;

    const int irSignal = 48;

    decode_results results;

    IRrecv irrecv(irSignal);

    boolean manualLeds = false;

    boolean ledsOn = false;

    unsigned long counter;

    unsigned long prevMillis = 0;

    int piezoInterval = 200;

    int drivingMode = 0;

    boolean playPiezo=false;

    #define trig 22
    #define echo 24
    long duration;
    boolean turned150 = false;
    int cm30, cm, cm150;
    bool checkLeft = false;
    boolean checkRight = false;
    boolean mainPing = true;
    unsigned long servoTimer = millis();

    void setup(){
      Wire.begin();
      rtc.begin();
      pinMode(piezo, OUTPUT);
    pinMode(STBY1, OUTPUT);
      pinMode(aPWM1, OUTPUT);
      pinMode(ain11, OUTPUT);
      pinMode(ain12, OUTPUT);
      pinMode(bPWM1, OUTPUT);
      pinMode(bin11, OUTPUT);
      pinMode(bin12, OUTPUT);

      pinMode(STBY2, OUTPUT);
      pinMode(aPWM2, OUTPUT);
      pinMode(ain21, OUTPUT);
      pinMode(ain22, OUTPUT);
      pinMode(bPWM2, OUTPUT);
      pinMode(bin21, OUTPUT);
      pinMode(bin22, OUTPUT);

     servo.attach(12);
     for(int i=0;i<sizeof(leds)/sizeof(leds[0]);i++){
        pinMode(leds[i], OUTPUT);
     }

      pinMode(flamePin, INPUT);
      pinMode(photoResistor, INPUT);
      pinMode(temp, INPUT);
      pinMode(irGnd, OUTPUT);
      digitalWrite(irGnd, LOW);
      pinMode(irVcc, OUTPUT);
      digitalWrite(irVcc, HIGH);
      pinMode(irSignal, INPUT);
     Serial.begin(9600);
      irrecv.enableIRIn();
      digitalWrite(STBY1, LOW);
        digitalWrite(STBY2, LOW);
    servo.write(90);
    delay(200);
    }

    void loop(){

     counter=millis();
     //Serial.print("Millis1: ");
     //Serial.println(millis());
     if(irrecv.decode(&results)){
        translateIR();
        irrecv.resume();
      }
     // Serial.print("Millis2: ");
     //Serial.println(millis());
    if(drivingMode == 1){
       if(((counter-servoTimer) >= 150) && mainPing){
        ping();
        cm=duration/29.1/2;
        Serial.println(cm);
        counter=millis();
        servoTimer=counter;
      }
      if((cm<30) && mainPing){

        mainPing=false;
        checkRight = true;
        counter=millis();
        servoTimer=millis();
        servo.write(150);
        cm=30;

      }
      if(checkRight && !checkLeft && ((counter-servoTimer) >= 170)){

        ping();
        checkLeft=true;
        cm150 = duration/29.1/2;
        counter=millis();
        servoTimer=millis();
        servo.write(50);
      }
      if(checkRight && checkLeft && ((counter-servoTimer) >= 340)){
      checkRight=false;
      checkLeft=false;
      mainPing=true;
      ping();
      cm30 = duration/29.1/2;
      counter=millis();
      servoTimer=millis();
      servo.write(90);

      }

     }

    //getTime();
    //existsFire();
    /*if(!manualLeds){
    readPhoto();
    }*/

    }

    void readPhoto(){

      photoState = analogRead(photoResistor);
      if(photoState>600){
        ledAnalog=0;
      }
      else if(photoState<300){
        ledAnalog=255;
      }
      else{
        ledAnalog = 150 - photoState/4;
      }
      for(int x = 0;x<sizeof(leds)/sizeof(leds[0]);x++){
      analogWrite(leds[x], ledAnalog);
      }

    }

    void existsFire(){
    flameState = analogRead(flamePin);
    Serial.println(flameState);
    if(flameState <= 50){
      static boolean playingBuzzer = true;
      if(counter - prevMillis > piezoInterval){

         prevMillis = counter;
         playingBuzzer=!playingBuzzer;

      }
      if(playingBuzzer){

        digitalWrite(piezo, HIGH);

      }
      else{
        digitalWrite(piezo, LOW);
      }

    }
    else if(!playPiezo){
      digitalWrite(piezo, LOW);
    }
    else if(playPiezo){
      digitalWrite(piezo, HIGH);
    }

    }

    void checkTemp(){

      temperature = ((analogRead(temp) / 1024.0 * 5.0) - .5) * 100;
      Serial.println(temperature);

    }
    void ping(){

        digitalWrite(trig, LOW);
        delayMicroseconds(2);
        digitalWrite(trig, HIGH);
        delayMicroseconds(10);
        digitalWrite(trig, LOW);
        duration = pulseIn(echo, HIGH);

    }
    void getTime(){

      DateTime now = rtc.now();

      Serial.print(now.year(), DEC);
        Serial.print('/');
        Serial.print(now.month(), DEC);
        Serial.print('/');
        Serial.print(now.day(), DEC);
        Serial.print(" ");
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.print(':');
        Serial.print(now.second(), DEC);
        Serial.println();
    }
    void forward(){
    digitalWrite(STBY1, HIGH);
    digitalWrite(ain11, HIGH);
    digitalWrite(ain12, LOW);
    analogWrite(aPWM1, 255);

    digitalWrite(bin11, LOW);
    digitalWrite(bin12, HIGH);
    analogWrite(bPWM1, 234);

    digitalWrite(STBY2, HIGH);
    digitalWrite(ain21, LOW);
    digitalWrite(ain22, HIGH);
    analogWrite(aPWM2, 255);

    digitalWrite(bin21, LOW);
    digitalWrite(bin22, HIGH);
    analogWrite(bPWM2, 234);
    }
    void backward(){

    digitalWrite(STBY1, HIGH);
    digitalWrite(ain11, LOW);
    digitalWrite(ain12, HIGH);
    analogWrite(aPWM1, 255);

    digitalWrite(bin11, HIGH);
    digitalWrite(bin12, LOW);
    analogWrite(bPWM1, 235);

    digitalWrite(STBY2, HIGH);
    digitalWrite(ain21, HIGH);
    digitalWrite(ain22, LOW);
    analogWrite(aPWM2, 255);

    digitalWrite(bin21, HIGH);
    digitalWrite(bin22, LOW);
    analogWrite(bPWM2, 235);

    }
    void left(){

    digitalWrite(STBY1, HIGH);
    digitalWrite(ain11, HIGH);
    digitalWrite(ain12, LOW);
    analogWrite(aPWM1, 255);

    digitalWrite(bin11, HIGH);
    digitalWrite(bin12, LOW);
    analogWrite(bPWM1, 255);

    digitalWrite(STBY2, HIGH);
    digitalWrite(ain21, LOW);
    digitalWrite(ain22, HIGH);
    analogWrite(aPWM2, 255);

    digitalWrite(bin21, HIGH);
    digitalWrite(bin22, LOW);
    analogWrite(bPWM2, 255);

    }
    void right(){
    digitalWrite(STBY1, HIGH);
    digitalWrite(ain11, LOW);
    digitalWrite(ain12, HIGH);
    analogWrite(aPWM1, 255);

    digitalWrite(bin11, LOW);
    digitalWrite(bin12, HIGH);
    analogWrite(bPWM1, 255);

    digitalWrite(STBY2, HIGH);
    digitalWrite(ain21, HIGH);
    digitalWrite(ain22, LOW);
    analogWrite(aPWM2, 255);

    digitalWrite(bin21, LOW);
    digitalWrite(bin22, HIGH);
    analogWrite(bPWM2, 255);

    }
    void brake(){

    digitalWrite(STBY1, LOW);
    digitalWrite(ain11, LOW);
    digitalWrite(ain12, LOW);
    analogWrite(aPWM1, 0);

    digitalWrite(bin11, LOW);
    digitalWrite(bin12, LOW);
    analogWrite(bPWM1, 0);

    digitalWrite(STBY2, LOW);
    digitalWrite(ain21, LOW);
    digitalWrite(ain22, LOW);
    analogWrite(aPWM2, 0);

    digitalWrite(bin21, LOW);
    digitalWrite(bin22, LOW);
    analogWrite(bPWM2, 0);

    }
    void translateIR(){
    //Serial.println(results.value, HEX);
    switch(results.value){
    case 0xFF02FD:
    case 0x20DF22DD:
    //stop(ok)
    if(drivingMode==0){
    brake();
    //Serial.println("brake");

    }
    break;
    case 0xFF629D:
    case 0x20DF02FD:
    //forward
    if(drivingMode==0){
    forward();
    //Serial.println("forward");
    }
    break;
    case 0x20DF827D:
    case 0xFFA857:
    //back
    if(drivingMode==0){
    backward();
    //Serial.println("back");

    }
    break;
    case 0xFF22DD:
    case 0x20DFE01F:
    //left
    if(drivingMode==0){
    left();
    //Serial.println("left");
    }
    break;
    case 0x20DF609F:
    case 0xFFC23D:
    //right
    if(drivingMode==0){
    right();
    //Serial.println("right");

    }
    break;
    case 0xFF6897:
    case 0x20DF8877:
    if(drivingMode==0){
      brake();
      drivingMode=1;
    }
    else{
      brake();
      servo.write(90);
      drivingMode=0;
    }
    //1(switch driving mode)
    break;
    case 0xFF9867:
    case 0x20DF48B7:
    //2(switch led mode)
    if(!manualLeds){
    manualLeds=true;
        for(int x = 0;x<sizeof(leds)/sizeof(leds[0]);x++){
      digitalWrite(leds[x], LOW);
      }
    }
    else{
    manualLeds=false;
    }

    break;
    case 0xFFB04F:
    case 0x20DFC837:
    if(manualLeds){
      if(!ledsOn){
        for(int x = 0;x<sizeof(leds)/sizeof(leds[0]);x++){
      digitalWrite(leds[x], HIGH);
      }

      ledsOn=true;
      }
      else{
           for(int x = 0;x<sizeof(leds)/sizeof(leds[0]);x++){
      digitalWrite(leds[x], LOW);
      }
      ledsOn=false;
      }
    }
    //3(toggle leds if mode is on)
    break;
    case 0xFF30CF:
    case 0x20DF28D7:
    //4(play sound)
    playPiezo = !playPiezo;

    }

    }

EDIT 2:

I decided to see what will happen if I start removing code. I removed most of the code that I did not need for this experiment. After the removal, the issue persisted. The sensor is still giving me 0s. This is all the code that was left after I removed stuff:

    #include <Servo.h>

    //RTC_DS1307 rtc;

    /*const int blue2 = 12;
    const int blue1 = 11;
    const int red1 = 10;
    const int red2 = 9;
    */
    Servo servo;

    unsigned long counter;

    unsigned long prevMillis = 0;

    int piezoInterval = 200;

    int drivingMode = 0;

    boolean playPiezo=false;

    #define trig 22
    #define echo 24
    long duration;
    boolean turned150 = false;
    int cm30, cm, cm150;
    bool checkLeft = false;
    boolean checkRight = false;
    boolean mainPing = true;
    unsigned long servoTimer = millis();

    void setup(){

     servo.attach(12);
    /* for(int i=0;i<sizeof(leds)/sizeof(leds[0]);i++){
        pinMode(leds[i], OUTPUT);
     }
    */
     Serial.begin(9600);

    servo.write(90);
    delay(200);
    }

    void loop(){

     counter=millis();
     //Serial.print("Millis1: ");
     //Serial.println(millis());
    /* if(irrecv.decode(&results)){
        translateIR();
        irrecv.resume();
      }*/
    //  Serial.print("Millis2: ");

    if(drivingMode == 0){
       if(((counter-servoTimer) >= 150) && mainPing){
        ping();
        cm=duration/29.1/2;
        Serial.println(cm);
        counter=millis();
        servoTimer=counter;
      }
      if((cm<30) && mainPing){

        mainPing=false;
        checkRight = true;
        counter=millis();
        servoTimer=millis();
        servo.write(150);
        cm=30;

      }
      if(checkRight && !checkLeft && ((counter-servoTimer) >= 170)){

        ping();
        checkLeft=true;
        cm150 = duration/29.1/2;
        counter=millis();
        servoTimer=millis();
        servo.write(50);
      }
      if(checkRight && checkLeft && ((counter-servoTimer) >= 340)){
      checkRight=false;
      checkLeft=false;
      mainPing=true;
      ping();
      cm30 = duration/29.1/2;
      counter=millis();
      servoTimer=millis();
      servo.write(90);

      }

     }

    //getTime();
    //existsFire();
    /*if(!manualLeds){
    readPhoto();
    }*/

    delay(2);
    }

    //}
    void ping(){

        digitalWrite(trig, LOW);
        delayMicroseconds(2);
        digitalWrite(trig, HIGH);
        delayMicroseconds(10);
        digitalWrite(trig, LOW);
        duration = pulseIn(echo, HIGH, 24000L);

    }

Maybe this means that the issue is within this remaining code. Of course I will need all of the code that I removed for the final project, but I was just trying to debug.

I made my code a lot more concise since the posted code draft, but the ultrasonic sensor still gives me 0s. I do not understand what can affect its performance as it works fine in my other sketch.

I tried connecting the sensor to an external 5 volt power source and the same thing happened. The reason for the issue is not because if my power source.

I used to have a small delay at the end of my code and I removed that in order to make it run faster. Since pulseIn is blocking for 24ms, the delays do not affect it and it should work normally. But it does not.

Also, the sensor is giving 0s not because the target is too far away. Even if I put my hand close, it still gives 0s. If I make the cm equal 400 if the duration equals 0, the cm are always 400 regardless of the distance from the sensor.

title: Why does HC-SR04 return 0s in this sketch

Answers: 3

body:
> Why does the same block of code act differently in different sketches?

There are different interrupt sources in the sketches that may affect pulseIn(). Try using a more advanced method to measure the pulse width such as Timer Capture.

Cheers!

body:
`pulseIn()` may block up to **1 second** (by default), which would happen everytime the **HC-SR04** receives no echo, which might be the case if ultrasounds do not get properly reflected on a flat surface or if the nearest echoing surface is over ~4 meters away from it.

In this situation, not only would `pulseIn` block for one second, but it would also return `0` to indicate the pin never changed level during that time (which can explain the **0cm distance** you calculated).

Since the **HC-SR04** range is maximum 4 meters, the max ultrasound distance echoed should be then less than 8 meters. Under normal atmospheric conditions, sound propagates at **~340m/s**, that means in the worst case, i.e. an obstacle found 4 meters away, the sound roundtrip should take less than **8/340s**, i.e. **~24ms** rounded up.

This shows it is pointless to have `pulseIn` wait for 1 second, where 24ms would be enough. To tell `pulseIn` to use a shorter timeout, just pass it an extra argument:

    duration = pulseIn(echo, HIGH, 24000L);

Note that timeout must be expressed in **us**.

Then, in other parts of your code, before using `duration`, you should check that it is not `0` (which means no obstacle found less than 4 meters away), for example you might consider in this case the distance is 4 meters (or anything larger).

E.g. you could replace:

    cm150 = duration/29.1/2;

with:

    cm150 = duration == 0 ? 400 : duration/29.1/2;

Since this calculation is found several times you should probably create a function for it, that would improve code maintainability and maybe code size as well.

body:
In the `setup()` function add a `setPin(echo, INPUT)` statement.

**UPDATE**

Have you checked the wiring? A loose connection of either the `trig` or `echo` pins would cause this behavior.

I know it might seem obvious, but double checking continuity between the Arduino pins and the HC-SR04 module with a basic multimeter (while your board is not powered) is not going to hurt, right?


body:
I prefer writing code in Vim, so I'd like to get a workflow going with the Arduino CLI. I used to use [`ino`](http://inotool.org), but I didn't like the restructuring of the project, which meant anyone who downloaded the code having to use `ino`.

I can build and verify using `/Applications/Arduino.app/Contents/MacOS/Arduino --verify MyProject.ino`, which pops up a new instance of the Java IDE, then exits after verifying.

While this works, and works well, it's incredibly slow. Is there any way to keep the IDE open to save the few seconds lost from the IDE starting again?

title: Is there any way to prevent Arduino CLI from closing each time?

Answers: 1

body:
> Is there any way to prevent Arduino CLI from closing each time?

I would suggest working the other way around.

1. Start the Arduino IDE and set external editor in the Preferences (once).
2. Open the sketch file(s) in the Arduino IDE and VIM.
3. Edit the sketch file(s) in VIM.
4. Move to the Arduino IDE and Verify, Upload, Monitor, etc.
5. Repeat steps 3-4.

The alternative is to use a make based build system. An example may be found in the [Cosa build system for Linux][1].

Cheers!

PS: VIM = any external editor such as GNU Emacs, TextEdit, etc.

  [1]: https://github.com/mikaelpatel/Cosa/tree/master/build/Arduino-Makefile