# Question
Title: Is Sparkfun's MicroView OLED Arduino module a shield?
I'm getting confused by the Arduino terminologies: shield, breakout, module.

Is this MicroView an Arduino compatible shield that will plug into Arduino's or Adafruit's Uno?

# Answer
> 1 votes
No, MicroView is not an Arduino shield, so you can't plug that into any Arduino. Arduino Uno and MicroView are developed based on Atmega328 controller. So it is 100% code compatible with Arduino Uno, means the code that runs on an Arduino Uno will also be able to run on the MicroView.

---
Tags: arduino-uno, shields, display
---


title: arduino ethernet run php from sd card

text:
# Question
Title: arduino ethernet run php from sd card
I am just interested, but I would like to run a webpage with php on my arduino ethernet. I would like to be able to store my webpage on the sd card as well.
does anyone know of a library that would let me do this?

# Answer
Loading a file off an sdcard and displaying it on port 80 isn't hard. Just check out the 'Ethernet' library and the 'SD' library.

I don't want to discourage you too much about the PHP part, but you won't be able to load the official PHP interpreter onto the Arduino. Simply not enough memory available.

However, if you just want to have dynamic website such as display variables or output from sensors, then you could write your own code interpreter for dynamic web pages that would fit in the memory of an Arduino, just think a bit smaller in scope as far as what it can handle. Maybe you'll end up writing a new library for dynamic webpages for Arduino sensor data.

If you really need to run a PHP interpreter then you can try something like a Rapsberry Pi and hook it up to the Arduino for sensor input using the I2C protocol.
> 1 votes

# Answer
Thats not possible, only if you write yourself a PHP interpreter, which I suspect won't fit inside an Arduino.

You might be able to create your own interpreter for simple Get and POST requests, but bear in mind that HTTP, and even TCP are very sophisticated protocols to run on an AVR. You might want stick with simple things, preferentially with small messages as you also have very little RAM on those MCUs.
> 0 votes

---
Tags: library, ethernet, web-server
---


# Question
Title: How do I connect components to the Arduino with a motorshield?
How would I connect components to the Arduino with this motor shield?

Thanks :)

# Answer
> 0 votes
If you are up for a little soldering, look into stackable Arduino headers. (Feel free to shop around for those, adafruit was just the first result.) You could then use male jumpers and a breadboard to connect anything that fits in a breadboard.

Just be careful to avoid pins that the shield is already using.

---
Tags: arduino-uno, arduino-motor-shield
---


# Question
Title: Getting "Undefined reference to vtable for {classname}
I have a large collection of libraries that compile correctly but won't link. I am using Visual Micro for Visual Studio 2015. Here is the complete collection of error messages:

```
CommandPattern3.cpp.o:In function `DualMotorRomeo
DualMotorRomeo.h:undefined reference to `vtable for DualMotorRomeo
DualMotorRomeo.h:undefined reference to `vtable for DualMotorRomeo
CommandPattern3.cpp.o:In function `__static_initialization_and_destruction_0
CommandPattern3.ino:undefined reference to `DualMotorRomeo  ~DualMotorRomeo()
collect2.exe*:error: ld returned 1 exit status

Error compiling for board Arduino/Genuino Mega w/ ATmega2560 (Mega 2560)

```

I have been through the code with a fine toothed comb, but cannot see what references are undefined.

Is there some Windows 10 utility that can examine the vTables and help me find what is missing?

The code base is too large to post, but I can provide a ZIP file with all the code in it for anyone willing to help.

# Answer
> 1 votes
I don't have the header file for `DualMotorRomeo`, but the linker is saying that a destructor has been declared (`~DualMotorRomeo()`) in the class header, but no destructor has been defined. If you didn't write `DualMotorRomeo` then the library needs to be updated.

Until then, simply add the following to one of your source files:

```
DualMotorRomeo::~DualMotorRomeo() {
} // DualMotorRomeo::~DualMotorRomeo()

```

That will also fix the `vtable` linker errors - the `vtable` will be included in the compiled file with this declared in it.

---
Tags: arduino-mega, compiler
---


# Question
Title: Arduino Pro Mini interrupts timer not working
i am trying to make an arduino pro mini sd card serial logger.The arduino should log the data that comes over the uart and write it to an sd card and if it is no data on the serial for 25 seconds to save automatically the data into the file.Each file are named diffrent every time they are saved(for example datalog0.txt, datalog1.txt and so on).I am creating also at the start of the sketch an config(config.txt) file where the number of the file present of the sd are stored and if the file already exist than a new one will be created, this option works good.Now, after the 25 seconds past and it is no more data over the serial the arduino dont close the datalog.txt file , so the next data will be saved in the same file, this is the problem i have, even in the config file the file number will be increased.I will attach the sketch and expect patient from you, ai am still newbie.I forgot to mention that it was working good for some time but not anymore, the only thing i did was to upload the bootloader from ide and since than is not working anymore.

Regards.

```
//#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>
#include <SoftwareSerial.h>

            int i;
            int incomingByte = 0;
//int data[512];
            File myFile;
            unsigned char bytes,flag_again;
            unsigned int fileNo,timer_count;
            String s_fileNo,filename,filename_master;
            char comanda;

            void Timer1_InIt()
        {
            TCCR1A = 0;
            TCCR1B = 0;
            TCNT1  = 0;
            OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
            TCCR1B |= (1 << WGM12);
                TCCR1B |= (1 << CS12) | (1 << CS10);
                //TIMSK1 |= (1 << OCIE1A);
            }

ISR(TIMER1_COMPA_vect)
{
    timer_count++;
    if(timer_count > 25)
    {
        timer_count = 0;
        TIMSK1 &= ~(1 << OCIE1A);
        myFile.close();
        fileNo++;
        myFile = SD.open("config.txt",FILE_WRITE);
        myFile.seek(0);
        myFile.print(fileNo);
        myFile.close();
        //software_Reset() ;    //reset the sketch
    }
}
SoftwareSerial mySerial(4, 5); // RX, TX

void setup()
{
    cli();
    Timer1_InIt();
    sei();

    mySerial.begin(9600);
    Serial.begin(10752,SERIAL_8E2);
    //mySerial.print("Initializing SD card...");

    if (!SD.begin(10))
    {
        //mySerial.println("initialization failed!");
        return;
    }
    Serial.println("initialization done.");

    myFile = SD.open("config.txt",FILE_READ);
// mySerial.println("Config file created");
    if(!myFile.available())
        bytes = 0;
    else
    {
        bytes = myFile.available();
        for(i = 0; i< bytes ; i++)
            s_fileNo += (char)myFile.read();
    }
    myFile.close();
    fileNo = s_fileNo.toInt();
// mySerial.print("file no:");
    //mySerial.println(fileNo);

    filename = "datalog";
    filename += fileNo;
    filename += ".txt";

    myFile = SD.open(filename,FILE_WRITE);
    if (myFile)
    {
        //mySerial.print(filename);
        //mySerial.println(" File Open...");
    }
}

void loop()
{

    if(!myFile)
        myFile = SD.open(filename, FILE_WRITE);

    while(Serial.available())
    {
        incomingByte = Serial.read();
        /*if(incomingByte == 0 || incomingByte < 15 )
        {
          Serial.print('0');
          myFile.print(0,HEX);
        }*/
        //mySerial.println(incomingByte,HEX);
        myFile.println(incomingByte,HEX);
        // myFile.println(incomingByte);
        timer_count = 0;
        flag_again = 1;
    }
    if(!Serial.available() && flag_again)
    {
        TIMSK1 |= (1 << OCIE1A);
        flag_again = 0;
    }

}

```

# Answer
> 1 votes
In untested (pseudo-)code

```
unsigned long lastSerialInput = millis();

void loop()
{

    if(!myFile)
        myFile = SD.open(filename, FILE_WRITE);

    while(Serial.available())
    {
        incomingByte = Serial.read();
        myFile.println(incomingByte,HEX);

        lastSerialInput = millis();
    }

    // check for 25 seconds of inactivity
    if( myFile && (millis()-lastSerialInput > 25000 )
    {
        myFile.close();
        fileNo++;
        filename = "datalog";
        filename += fileNo;
        filename += ".txt";

        //save new fileNo to config.txt (though I'd personally find the file with the largest number in setup instead of relying on a config.txt file)
    }

}

```

---
Tags: arduino-pro-mini
---


title: Missing Libraries make no sense

text:
# Question
Title: Missing Libraries make no sense
I've never much issue importing a library to my master sketchbook location, restarting Arduino, then using the library examples. Today is a different story:

1. I'm loading RCLib which is part of this ArduinoLibraries family
2. RCLib requires PinChangeInt

So everything is in my sketchbook location right? `Arduino > Preferences > Sketchbook Location`

Still I'm getting compiler errors about missing libraries:

```
/Users/Jackson/Documents/Arduino/ArduinoLibraries-master/RCLib/Examples/Maga6ChanelsA8_A13/Maga6ChanelsA8_A13.ino:7:86: fatal error: PinChangeInt.h: No such file or directory
 #include "PinChangeInt.h"

```

I've even tried `#include <PinChangeInt.h>` Which makes more sense since this is a system library.

**What is going on here?**

The sketch I'm trying to run:

```
/**This is an example of using the RCLib with a mega and pinchangeint
 * This example isprovided as is by Jantje
 * Congratualtions, constructive feedback and I like it can be send to eclipse@baeyens.it
 **/

#define NUM_RC_CHANNELS 6 //You need to specify how many pins you want to use
#include "PinChangeInt.h"  //If you need pinchangeint you need to include this header
const uint8_t RC_Channel_Pin[NUM_RC_CHANNELS]={
  A8,A9,A10,A11,A12,A13};//Here I specify I want to listen to pins A8 to A13 of my mega

uint16_t RC_Channel_Value[NUM_RC_CHANNELS]; //This variable will contain the values read from the RC signal
#include "RCLib.h" //This include needs all declarations above. Do not try to move it up or it won't compile

```

*Arduino v1.6.9 | OSX 10.11.4*

# Answer
> 2 votes
I had downloaded PinChangeInterrupt through Arduino

Sketch \> Include Library \> Manage Libraries... \> *Filter your search...* \> PinChangeInterrupt \> Install

I thought this is all I needed but I was wrong. This differs from the popular PinChangeInt library. Ultimately the file names where slightly different which is why my file was showing as missing. I found this out by manually looking at the file names in the library I was trying to used and comparing them against my includes.

---
Tags: library, osx
---


title: Arduino due + mcp2551

text:
# Question
Title: Arduino due + mcp2551
I am currently using an atmega328 along with the mcp 2515 and the 2551 for CAN communication in my systems.

However, I've now decided to upgrade to the arduino due for my operations. Can anybody tell me if the arduino due along with it's inbuilt CAN controller be used with the mcp2551 transciever to operate CAN successfully.

If not, can somebody also tell me if there are other alternatives I should look into. Thanks :)

# Answer
The biggest trouble you are going to find is the voltage levels. The MCP2551 works at 5V and your MCU is 3.3V. I personally don't have experience with this MCUs, but some STM32 MCUs are 5V tolerant on some pins, including the CAN\_TX and Can\_RX and it's fine to use a 5V Transceiver like the MCP2551.

Anyway, you still can replace the CAN Transceiver with one that has a built in level shifter, like one of the following:

* MCP2562
* ATA6561
* SN65HVD256
* NCV7351D13

I've used all the above, except the TI one, and they all talk nicely between each other. Some have different features, like silence or advanced sleeping modes.

Cheers
> 1 votes

---
Tags: arduino-due, can-bus
---


# Question
Title: Do I need resistors or capacitors on this relay?
I'm using my Arduino to control a relay switch, which has an extension cord attached to it (see photo).

The relay is connected to the Arduino via pin 9, which is set to `pinMode(9, OUTPUT);`

Do I need any resistors or capacitors or diodes attached to this? Almost feels *too* simple, given I'm running AC power through the relay. But maybe no?

It definitely *works*, but I want to make sure I'm not going to burn something out (or down).

# Answer
> 2 votes
Yes, that is too simple.

The Arduino's IO pin is not designed to directly drive a relay. It needs to go through a transistor first, and you must include a diode to absorb the back-EMF generated by the collapsing magnetic field.

Google for "Arduino Relay" and you will find hundreds of thousands of examples.

In short, the circuit you need to create is this:

---
Tags: relay, electronics, switch
---


title: How to detect cancelled download?

text:
# Question
Title: How to detect cancelled download?
I have a server with files that may be downloaded.

How do I go about detecting when a download is cancelled by a client?

The function that handles reading files for download:

```
void readFile()
{

EthernetClient client = server.available();

// Open file for Reading.
SdFile webFile;
webFile.open(&root, &MyBuffer[1], O_READ);
if (!webFile.isOpen()) error("readFile");

do   // @ adafruit_support_rick's do-while loop
{
    int count = 0;
    char buffers[BUFSIZE];
    bool done = false;

    while ((!done) && (count < BUFSIZE) && (webFile.available()))
    {
        char c = webFile.read();
        if (0 > c)
        done = true;
        else
        buffers[count++] = c;
        delayMicroseconds(1000);
    }

    if (count)
    client.write( buffers, count);

} while (webFile.available());

webFile.close();

fileDownload = 0;  //File download has finished; allow logging since download has completed

delay(500);

MyBuffer[0] = '\0';

}

```

# Answer
> 1 votes
Well, assuming cancelling a download == incomplete download == client disconnected before server was done, you could create a flag like this at the top of the function:

```
bool dload_cancel = false;

```

Change the `IF` block, below the innermost `WHILE` loop, to this:

```
if (count){
  if (client.connected())
    client.write( buffers, count);
  else {
    dloadCancel = true;
    break;
  }
}

```

The flag will be set once your server checks and discovers that the client has been disconnected. You can check the state of the flag outside the `DO-WHILE` block to know if the download was completed or not.

```
if (dloadCancel){
  // client was disconnected; download did not complete
}

```

`dloadCancel` is also a better indicator of a completed download than your `fileDownload` flag.

You should also know that this:

```
if (0 > c)
    done = true;

```

is redundant. Its already taken care of by `webFile.available()`.

---
Tags: arduino-mega, programming
---


# Question
Title: VGAX library only allows 4 colors, library or hardware limitation?
I'm working with VGA DSUB-15 output, however VGAX only allows for 4 colors. I'm using an Arduino Nano that uses an 8-bit atmel chip, and I've seen many 8-bit computers of which have a *bit* more than 4 colors.

# Answer
It's a memory limitation. The ATmega328 has 2 KB of RAM, and a 120x60 framebuffer at two bits per pixel (four colors) uses 1.8 KB. There's no room for more.
> 3 votes

# Answer
Are you using the Arduino to directly drive the VGA, or are you using a shield. If you're directly driving the display, I think the limitation is on the Arduino because with only 2kb or RAM, you can't really store all the pixel data. And the duino is also generating the high frequency vsync and hsync signals.
> 1 votes

# Answer
The VGA interface uses full analog signals for Red, Green an Blue video. There is no limit to the color levels in the VGA standard.

However, it is not unusual to find that minimalist implementations of VGA in microcontroller products use Digital to Analog Converter (DAC) techniques with a limited number of bits of resolution. For example, using two bits of resolution for Red and Blue, and three bits of resolution for Green so that the pixel information will fit into an 8-bit byte, etc.
> 0 votes

---
Tags: arduino-nano
---


# Question
Title: How do you change the state of an image on a TFT display when the associated pin changes state?
I just recently resolved my problem on getting images to load on to my TFT display via the SD card. Thanks to UTFT\_SdRaw!!! it's by far the easiest to use. For a novice like me, its been a real feat. Now translating the code, I am trying to turn on and off the image when the pin state changes:

Example: When pin A2 on my MEGA goes high (+5vdc) I want my SD to spool up and load an image so here is my code snipit:

\****myFiles.load(20, 55, 130, 130, "Power Medium.raw");\****

So now when the pin state changes back to low (0vdc), how do I remove the image without clearing the entire screen? The image seems to stay frozen instead of disappearing when the pin voltage falls away.

Any ideas? I am stumped. Thanks in advance for any comments and suggestions that may help me over the hump.

# Answer
> 1 votes
It's quite silmple: just draw a box over the image the same colour as the background.

Either that or draw a different image over the top of the existing image.

---
Tags: programming, display
---


# Question
Title: Neopixel Painter - Need to change few lines. Not sure where to start
My name is Maria and I'm learning programing in high school. I'm working on a birthday present for my mom, want to make a mood light. Using light painter, a neopixel strip, and an arduino.

https://github.com/adafruit/NeoPixel\_Painter

I found the part, which reads the bmp line by line a very innovative way to make custom animations.

But some tweaks are needed. (I've tried to make them, believe me, oh I've tried.) So, i was wondering if i can ask someone a favor and teach me how to modify the code (like, comment on parts that been changed.)

Basically, what I want to be changed is, to loop the current bmp until 'next' button is pressed, rather than hold the trigger. Also, I'm not sure if the code try to save power, but it can be disabled since it will run from a power supply.

Here is the part that makes you hold the trigger button (i think)

```
  for(;;) {
    while(!(TIFR1 & _BV(TOV1)));               // Wait for Timer1 overflow
    TIFR1 |= _BV(TOV1);                        // Clear overflow bit

    show();                                    // Display current line
    if(stopFlag) break;                        // Break when done

    if(++block >= nBlocks) {                   // Past last block?
      if(digitalRead(TRIGGER) == HIGH) {       // Trigger released?
        memset(sdBuf, 0, N_LEDS * 3);          // LEDs off on next pass
        stopFlag = true;                       // Stop playback on next pass
        continue;
      }                                        // Else trigger still held
      block = 0;                               // Loop back to start
    }
    card.readBlock(block + firstBlock, sdBuf); // Load next pixel row
  }

```

And the complete code: https://github.com/adafruit/NeoPixel\_Painter/blob/master/NeoPixel\_Painter.ino

Anyway, Since I'm talking to an experts right now, I have this idea to remote control the code! from another arduino!

My, probably retarded idea is, to run an IR remote code on a second arduion, than when it receives a signal, send a simulated button press to the first ardu playing the bmp! Is that even possible? Just wondering.

Cheers Maria

# Answer
> 0 votes
I think you need something like this.

```
  for(;;) {
    while(!(TIFR1 & _BV(TOV1)));               // Wait for Timer1 overflow
    TIFR1 |= _BV(TOV1);                        // Clear overflow bit

    show();                                    // Display current line

    if(++block >= nBlocks) {                   // Past last block?
      block = 0;                               // Loop back to start
    }

    if(digitalRead(NEXT_PIN_OR_SOMETHING) == LOW) {       // Next button pressed
      break; // Break out of for-loop
    }

    card.readBlock(block + firstBlock, sdBuf); // Load next pixel row
  }

```

---
Tags: arduino-uno, neopixel
---


# Question
Title: How to convert char[] to int with fail\success control?
this is more like C question, but i failed to google this.

i expect a command parameter in char\[\], but there may be no argument passed at all, so i need to try to parse this char\[\] to int and if there is garbage instead of a number, notify user.

i also need to be able to parse negative (with -sign char) numbers from char\[\].

how can i do this? thanks.

# Answer
> 0 votes
It isn't doable, reliably, with the given specs. If the array has garbage in it, it won't necessarily fail to parse as an int. That said, you can try to parse as an int with atoi() or sscanf(), as suggested in the comments, and report that it *did or did not parse*, but not necessarily whether it is valid in some respect.

If you're in control of the array, zero its first element. Then if you get back a non-empty string, at least you'll know some command parameter had been placed in it.

---
Tags: programming, c
---


title: Servo Speed Changer with Buttons

text:
# Question
Title: Servo Speed Changer with Buttons
ok so yesterday i was in trouble with the buttons, with help from you i got over it and everything worked fine with the 1st speed of the servo, then i added the other 2 speeds and it looks like it all messed up... the buttons don\`t respond as they should and the servo moves very weirdly. Here is the code:

```
const int button1Pin = 2;
const int button2Pin = 3;
const int ledPin1 = 13;
const int ledPin2 = 12;
const int ledPin3 = 11;
#include <Servo.h>
Servo servo1;

int x = 0;
int button1State = 0;
int lastButton1State = 0;
int button2State = 0;
int lastButton2State = 0;

void setup() {
  servo1.attach(9);
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
    int position;
    button1State = digitalRead(button1Pin);
    button2State = digitalRead(button2Pin);

      if (button1State != lastButton1State)
     {
        if (button1State == HIGH)
          {
            x++;
            Serial.println("on1");
            Serial.print("number of button Pushes:  ");
            Serial.println(x);
          }
        else
          {
            Serial.println("off1");
          }
     }

    if (button2State != lastButton2State)
      {
        if (button2State == HIGH)
          {
            x--;
            Serial.println("on2");
            Serial.print("number of button Pushes:  ");
            Serial.println(x);
          }
        else
          {
            Serial.println("off2");
          }
       }
          delay(1000);

lastButton1State = button1State;
lastButton2State = button2State;

  if(x == 1)
    {
      digitalWrite(ledPin1, HIGH);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
        for(position = 0; position < 360; position += 2)
          {
            servo1.write(position);
            delay(20);
          }
    }
   else if (x == 2)
    {
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, LOW);
        for(position = 0; position <360; position += 5)
          {
            servo1.write(position);
            delay(20);
          }
    }
   else
    {
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, HIGH);
        for(position = 0; position < 360; position += 10)
          {
            servo1.write(position);
            delay(20);
          }
    }
}

```

# Answer
> 1 votes
There may be better ways to mitigate button bounce. Check this link for a discussion on button bounce and example code to work around this problem. In your code, it appears you can not press your buttons faster than once a second.

Determine if the servos you are using are capable of the range you are demanding. Some servos only travel from 0 degrees to 180 degrees. Your code is asking the servo to travel from 0 degrees to 360 degrees. Also, it is unlikely that any normal servo can travel this far. Most servos use a potentiometer as a feed back sensor. And most potentiometers can only be turned to something less than 1 full revolution.

It is likely you have not given the servos enough time to move to the zero degree position at the start of each of your 3 loops. Understand that normal servos can not make complete revolutions. They need to stay within their designed limit of rotation. If you want to start over at 0 degrees you need to allow the servos time to rotate back in reverse to the 0 degree position.

Consider your last loop. You are asking the servo to move from 0 degrees to 360 degrees in 10 degree steps. You are allowing 20ms per step. That means the servo will be demanded to move almost a complete revolution in (((360 / 10) * 0.020 = 0.72 seconds) less than a second. Some but not all servos can move that fast.

---
Tags: arduino-uno, programming, servo, button, debounce
---


title: Arduino uno unexpected void loop stop

text:
# Question
Title: Arduino uno unexpected void loop stop
I have a trouble with following, few lines code. For some reason after few seconds Arduino uno stops responding into void loop section of code. I tried to remove serial communication, all print and println without any success. Is the problem comming from MMA\_7455.h?

```
#include <MMA_7455.h>
#include <Servo.h>

int servoPin = 9;
int servoAngle = 0;

Servo servo;

MMA_7455 accel = MMA_7455();
char yVal;
char yVal_bkp;

void setup() {
    servo.attach(servoPin);
    accel.initSensitivity(2);
    accel.calibrateOffset(1.0, 26.0, -69.0);
}

void loop() {
    yVal = accel.readAxis('y'); //Read out the 'y' Axis

    if(yVal_bkp != yVal + 2 || yVal_bkp != yVal -2)
    {
        servo.write(90 + yVal);
        yVal_bkp = yVal;
    }
}

```

P.S. Servo is normal G90

# Answer
> 1 votes
Have you checked that MMA\_7455 can handle this many reads?
I had sensors that stop working because I asked to often for feedback.
As the servo needs a 20ms to adjust its location I would add a delay(20) to the loop.

---
Tags: arduino-uno, servo, accelerometer
---


title: What does 16u and 128u mean?

text:
# Question
Title: What does 16u and 128u mean?
The below is a snippet of a code for operating SI4455 Rf module with Arduino. I have some doubts which I'd like to seek some help in clearing.

```
byte numOfBytes = *pSetPropCmd++;

    if (numOfBytes > 16u) // What does this 16u mean?
    {
        /* Initial configuration of Si4x55 */
        if (SI4455_CMD_ID_WRITE_TX_FIFO == *pSetPropCmd)
        {
            if (numOfBytes > 128u) // What does this 128u mean?
            {
                /* Number of command bytes exceeds maximal allowable length */
                return SI4455_COMMAND_ERROR;
            }

            /* Load array to the device */
            pSetPropCmd++;
            WriteEZConfigArray(numOfBytes - 1, pSetPropCmd);

            /* Point to the next command */
            pSetPropCmd += numOfBytes - 1;

            /* Continue command interpreter */
            continue;
        }

```

In the above snippet, what does 16u and 128u mean?. I think its meaning u for unsigned, but still not clear as what does 16u and 128u mean.

Rgds VD

# Answer
> 0 votes
It means that it is a unsigned value. Because the compiler checks for signed and unsigned in the same operation this is used (amongst others) to avoid warnings.

This is explained on stackoverflow here https://stackoverflow.com/questions/14844119/define-foo-1u-2u-4u-what-does-1u-and-2u-mean

---
Tags: arduino-uno, c, data-type
---


# Question
Title: Sending data via SoftwareSerial results in garbled reception
My overall goal is to have an Arduino Uno with an Ethernet Shield send a short (5-character) string via a SoftwareSerial connection and a UDP packet when I press a button.

The device which is receiving the serial message is fixed at 9600 baud, no parity, one stop bit.

For the purposes of debugging my serial problem I have removed the Ethernet Shield. I mention it above only so that potential responders understand my intended final hardware configuration.

I am using a USB/serial adaptor and Kermit to check the serial output.

```
C-Kermit>show communications

Communications Parameters:
 Line: /dev/ttyUSB0, speed: 9600, mode: local, modem: none
 Parity: none, stop-bits: 1 (8N1)
 Duplex: full, flow: none, handshake: none
 Carrier-watch: off, close-on-disconnect: off
 Lockfile: /var/lock/LCK..ttyUSB0
 Terminal bytesize: 8, escape character: 28 (^\)

```

My first job on receiving garbled characters was to test my test rig. I connected the predecessor device and was able to receive the expected characters. (It cannot send the UDP packet, which is why it is being replaced.)

One button on the original device sends "X0401", exactly as expected:

```
$ od -b oldserial⋅
0000000 000 130 060 064 060 061
0000006

```

Another button on the original device sends "X0402" (which I expected) and also a whole bunch of nuls, which I didn't expect:

```
$ od -b oldserial⋅
0000000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000
0000020 000 000 000 000 000 130 060 064 060 062
0000032

```

In any event, it seems that the terminal is actually receiving 8N1 data at 9600, so I can trust what it shows me.

I was going kind of nuts trying to figure out what was the problem, because nothing I sent from the Arduino came through properly. Then I stumbled on a suggestion that 'U' made a good test character because an ASCII 'U' is 0123 or 01010101. Indeed, I am able to send sequences of arbitrary length and so long as they contain only the 'U' caracter, they come through correctly.

(I've got three buttons and three different sets of messages, so my tests tend to run in sets of three attempts.)

Next step is to reintroduce a little bit of variety and see what comes through:

Here I send "UUUUU", "UUEUU", and then "UUQUU". 'E' and 'Q' were chosen because they are each just one bit different from 'U'.

What I saw when I sent the first message was:

```
UUUUU

```

Then sent the second:

```
UUUUUUU]UU

```

Then the third:

```
UUUUUUU]UUUUWUU

```

Kermit was also storing the session to a log file, which looked like this:

```
$ od -b serialUsequesnce⋅
0000000 125 125 125 125 125
0000005
$ od -b serialUsequesnce⋅
0000000 125 125 125 125 125 125 125 135 125 125
0000012
$ od -b serialUsequesnce⋅
0000000 125 125 125 125 125 125 125 135 125 125 125 125 127 125 125
0000017

```

Somehow, 'E' (0105) turned into 0135 and 'Q' (0121) turned into 0127. In each case, a sequence of three 0 bits were turned into 011, while no 1 bits were changed.

Sending:

```
UUAUU

```

Got me:

```
$ od -b serialUsequesnce2⋅
0000000 000 125 125 137 125 125
0000006

```

The five consecutive 0 bits in 01000001 were turned into 01111 to give me 01011111 or 0137

Longer strings get weirder.⋅

Test strings of:

```
UU0123456789UU
UUABCDEFGUU

```

Got me:

```
$ od -b serialUsequesnce3
0000000 125 125 326 266 226 166 126 066 026 366 215 125 125 000
0000016
$ od -b serialUsequesnce4
0000000 125 125 137 257 335 325 315 305 125 125 001
0000013

```

Now I'm seeing not just bits being replaced, but I'm getting fewer characters than I'm sending.

Since I wasn't getting good data from my SoftwareSerial port, I thought I would listen in on the USB traffic, which is also set to 9600 baud.

This text from the Arduino monitor:

```
UUAUU
Start button pressed
UU0123456789UU
Stop button pressed
UUABCDEFGUU
Light button pressed

```

Came through as this:

```
$ od -b serialUSB
0000000 125 125 137 125 125 171 275 165 324 332 027 277 073 025 027 027
0000020 041 043 277 037 031 031 065 067 345 353 000
0000033
$ od -b serialUSB2
0000000 125 125 326 266 226 166 126 066 026 366 215 125 125 345 353 131
0000020 027 041 037 277 073 025 027 027 041 043 277 037 031 031 065 067
0000040 345 353 000
0000043
$ od -b serialUSB3
0000000 125 125 137 257 335 325 315 305 125 125 225 353 147 055 061 057
0000020 027 277 073 025 027 027 041 043 277 037 031 031 065 067 345 353
0000040 000
0000041

```

I'm guessing that I'm doing something wrong with the hardware, but my serial connector simply has pin 5 connected to ground and pin 2 connected to digital 6 (or 2 when watching USB traffic).

I'm powering the Arduino Uno via its USB connection. When I checked the voltage at Vin and the adjacent ground, I got 4.51 volts.

```
/*
Listens on three buttons:
 - Start
 - Stop
 - Lights

Sends serial messages to a Color Kinetics iPlayer 2
9600 baud, 8 data bits, no parity, 1 stop bit
Commands are
 - X0100 Lights Off
 - X0288 Lights at half
 - X02FF Lights at full
 - X0401 Set Show #1

Created 2016-07-13
by David H. Silber
(Cribbing extensively from the Arduino examples.)
*/

#include <SPI.h>         // needed for Arduino versions later than 0018

#include <SoftwareSerial.h>
SoftwareSerial softSerial( 5, 6 ); // RX, TX

const int noButton = 100;
const int startButton = 2;
const int stopButton = 3;
const int lightButton = 4;
bool startTriggered = false;
bool stopTriggered = false;
bool lightTriggered = false;
int lastTriggered = noButton;
unsigned long lastButtonTime = 0;

const char startSerial[] = "UUUUU";
const char stopSerial[]  = "UUEUU";
const char lightSerial[] = "UUQUU";

void setup() {
  // initialize the pushbutton pin as an input:
  pinMode(startButton, INPUT);
  pinMode(stopButton, INPUT);
  pinMode(lightButton, INPUT);

  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Starting");  // prints hello with ending line break⋅

  // set the data rate for the SoftwareSerial port
  softSerial.begin(9600);
  delay( 1000 );
}

void loop() {
  // read the state of the pushbutton value:
  startTriggered = ( HIGH == digitalRead(startButton) );
  stopTriggered = ( HIGH == digitalRead(stopButton) );
  lightTriggered = ( HIGH == digitalRead(lightButton) );

  if ( startTriggered && (startButton != lastTriggered) ) {
    action( "Start button pressed", startSerial );

    lastTriggered = startButton;
    startTriggered = false;
  }

  if ( stopTriggered && (stopButton != lastTriggered) ) {
    action( "Stop button pressed", stopSerial );

    lastTriggered = stopButton;
    stopTriggered = false;
    }

  if ( lightTriggered && (lightButton != lastTriggered) ) {
    action( "Light button pressed", lightSerial );

    lastTriggered = lightButton;
    lightTriggered = false;
  }

  buttonTimeout();
}

void action( const char usbMessage[], const char serialMessage[] ) {
    Serial.println( serialMessage);⋅
    Serial.println( usbMessage);⋅

    softSerial.write( serialMessage );

    lastButtonTime = millis();
}

void buttonTimeout() {
  if ( millis() - lastButtonTime > 2000 ) {
    lastTriggered = noButton;
  }
}

```

# Answer
> 1 votes
A friend came and visited me with his oscilloscope and we determined that the 'serial' output from the Arduino was not actually RS-232. It was only an accident that any data came through at all.

I think my answer will be to add https://www.arduino.cc/en/Main/ArduinoBoardSerial or something like it.

One of our realizations was that we needed to level shift the output, searching on "arduino serial level shifter" led me to http://forum.arduino.cc/index.php?topic=18689.0 which in turn led us to the MAX232 chip and boards that provide it.

It would be a good thing if there were some mention in the Arduino documentation that the 'serial' connection one would get from it was not actually RS-232.

---
Tags: serial, softwareserial, code-review
---


title: calling a timer when a button is pushed

text:
# Question
Title: calling a timer when a button is pushed
I'm trying to call a function to keep an LED on for a certain amount of time. The function is called when the button is pushed but the LED stays on. I used the same code in the void loop before moving it into a function and it worked.

```
const int ledPin2 = 2;
const int buttonPin7 = 7;
const unsigned long onTime = 1000;
unsigned long previousMillis = 0;

//
void timer(){
    unsigned long currentMillis = millis();
    digitalWrite(ledPin2, HIGH);

    if (currentMillis - previousMillis >= onTime){
        digitalWrite(ledPin2, LOW);
        previousMillis = millis();
    }
}

void setup(){
    Serial.begin(9600);
    pinMode(ledPin2, OUTPUT);
    pinMode(buttonPin7, INPUT);
}

void loop(){
    int buttonState = digitalRead(buttonPin7);
    if (buttonState == HIGH) timer();
}

```

# Answer
When your code:

```
if (currentMillis - previousMillis >= onTime){
    digitalWrite(ledPin2, LOW);
    previousMillis = millis();
}

```

was in the loop, it was executed multiple times, so when `if (currentMillis - previousMillis >= onTime)` eventually became true, it would set ledPin2 LOW again. Now that you moved it to the `timer` funtion, it only gets executed once (and `if (currentMillis - previousMillis >= onTime)` never gets a chance to become true).

You need to introduce a loop in the `timer` function. It also looks like you have your `currentMillis` / `previousMillis` messed up. I think you are looking for something like this:

```
void timer(){

    unsigned long previousMillis = millis();
    unsigned long currentMillis = millis();
    digitalWrite(ledPin2, HIGH);

    while((currentMillis - previousMillis) < onTime) {
        // wait for a bit
        sleep(10);
        // update currentMillis
        currentMillis = millis();
    }

    digitalWrite(ledPin2, LOW);
}

```
> 2 votes

# Answer
Your code says

```
if (buttonState == HIGH) timer();

```

So... what will it do if `buttonstate` is `LOW`? Sorry, but the answer is "nothing". You don't have any code to tell it what to do when the button is in the opposite state.

What you should do is check the button, and if it's pressed (whether that's `HIGH` or `LOW` depends on your circuit), then light the LED and start the timer (assign to `previousMillis`).

Then, *regardless of the state of the button*, check to see if `currentMillis - previousMillis >= onTime`. If it is, then turn off the LED.
> 1 votes

---
Tags: timers
---


# Question
Title: Custom ATMega 2560 board won't execute Arduino code
I have a custom PCB with an ATMega 2560 microcontroller on it. To test if the ATMega was working properly, I uploaded the following code:

```
void setup() {
  Serial.begin(9600);
  Serial.println("Test setup");
  pinMode(6, OUTPUT);
  pinMode(30, OUTPUT);
  pinMode(31, OUTPUT);
  pinMode(32, OUTPUT);
}

void loop() {
  digitalWrite(6, HIGH);
  digitalWrite(30, HIGH);
  digitalWrite(31, LOW);
  digitalWrite(32, HIGH);
}

```

The mentioned ports are connected to LEDs, 6 to an external LED and 30, 31 and 32 to LEDs on the PCB. Each connected in series with a 220 Ohm resistor.

The board is setup like this:

When uploading I am using a Arduino UNO as ISP and after uploading the Arduino IDE says 'Done uploading' without any errors, but the board is not showing any sign of executing the code. I have checked that VCC is 5V and RESET is HIGH after uploading. The text "Test setup" is also not shown on the serial monitor.

Does anybody have a clue why the board is not working?

Thanks on forehand.

# Answer
> 0 votes
When using an empty ATMega2560 you need to change the fuse settings, otherwise it will just upload your code but it won't execute. This tutorial explains it very clearly: Programming ATMega 2560 with Arduino UNO

---
Tags: arduino-mega
---


# Question
Title: Constantly read analog in in SWITCH/CASE setup
I'm writing a program with three different cases. Case one an LED is off, in another it is on and in the last case the brightness is controlled by a potentiometer. Each case works as I press the button. The issue I am having is with the third case. The potentiometer is read only once and the LED is set accordingly. I would like the LED to be adjusted continuously until the button is pushed again and the case is switched to off. I used the Serial.print to see the valves read from the potentiometer. I verified its only read once on each cycle through the different cases. I also changed from a SWITCH/CASE to If statements and it only reads the potentiometer once.

*CODE HAS BEEN UPDATED*

```
//-------------------------------------------------------
// BUTTON AND POT - TEST
// KNOWN ISSUE - POT ONLY TAKES ON READING
// vonderasche
// 7/28/2016
//-------------------------------------------------------

const int BUTTON_PIN = 9;
const int LED_PIN = 3;
const unsigned long DEBOUNCE_TIME = 50;

int val = 0;
int pot = 0;

int state = 0;

void setup()
{
    pinMode(BUTTON_PIN, INPUT_PULLUP);
    pinMode(LED_PIN, OUTPUT);
    Serial.begin(9600);
}

bool button_press()
{
    static bool last_state;
    static unsigned long last_state_change;
    unsigned long now = millis();

    if (now - last_state_change < DEBOUNCE_TIME)
        return false;

    bool state = digitalRead(BUTTON_PIN);
    if (state != last_state) last_state_change = now;
    bool press = last_state && !state;
    last_state = state;
    return press;
}

void loop()
{

    unsigned long now = millis();
    static enum { OFF, ON, POT } state;

    if (button_press()) switch (state) {
    case OFF:
        analogWrite(LED_PIN, 255);
        state = ON;
        Serial.println(state);
        break;
    case ON:
        analogWrite(LED_PIN, 0);
        state = POT;
        Serial.println(state);
        break;
    case POT:
        Serial.println(state);
        int Mode = button_press();
        while (val < 1023) {
            val = (analogRead(pot) / 4);
            analogWrite(LED_PIN, val);
            Serial.println(val);
            state = OFF;
            break;
        }
    }
}

```

# Answer
The problem is that it will only go through the POT case once, if you want it to repeatedly read the potentiometer, and then change the LED brightness, you would have to put the case in a loop.

So, you might do something like this:

```
case POT:
int Mode = digitalRead(BUTTONPIN);
while(Mode == LOW) {
    val = (analogRead(pot) / 4);
        analogWrite(LED_PIN, val);
        Serial.println(val);
        state = OFF;
        break;
        Mode = digitalRead(BUTTONPIN);
    }
}

```

If you want to use the debounce, do something like this:

```
static enum { OFF, ON, POT } state;
unsigned long now = millis();
int x = 0;

while (x == 0) {
    switch (state) {
    case OFF:
        analogWrite(LED_PIN, 255);
        if (button_press()) {
        state = ON;
        }
        break;
    case ON:
        analogWrite(LED_PIN, 0);
        if (button_press()) {
        state = POT;
        }
        break;
    case POT:
        val = (analogRead(pot) / 4);
        analogWrite(LED_PIN, val);
        Serial.println(val);
        if (button_press()) {
        state = OFF;
        }
        break;
    }
}

```

This should work. What it's doing is basically just going through this while loop over and over and over again, and whenever the button is pressed, THEN it will switch state, but otherwise, it'l just do the same state again and again. This way the potentiometer will work AND the debounce.
> 0 votes

---
Tags: potentiometer, switch
---


# Question
Title: Any disadvantages on using Particle Photon over an Arduino?
It seems to me like Photon is 'winning' on the price front and ease of programming and of course the cheap wifi connection.

I realize the cloud portion (even the local cloud server) could be considered a disadvantage, but what about things like ability to drive dc/stepper motors or some exotic sensor? Perhaps not enough analog and/or digital pins? etc..

One disadvantage I can think of is the lack of resources whereas the Arduino has a ton of references online with working with all kinds of motors and sensors.

# Answer
> 4 votes
**Photon advantages:**

The photon has cloud compatibility and wifi access. The Arduino doesn't without a separate shield.

A photon about 1/4 the size of an Arduino UNO

Photon is much cheaper than arduinos

**Arduino UNO advantages:**

Arduino UNO has 5 volt AND 3.3 volt while Photon has only 3.3 volt

Arduino has many resources while Photons don't since Photons are fairly new

Arduinos don't need any wifi to work while Photons need to be connected to wifi and the cloud to flash code (Although there is a way to flash over USB cable, it is HIGHLY complicated with need of the terminal and DFU-UTIL installed.)

UNO has 5 analog, 13 digital ports while Photon has only 5 analog, 7 digital

UNOs have female pins, so no breadboards are necessary for small, simple projects. Photons have male pins, and they need to be plugged into a breadboard or soldered.

*Personally, I have both an UNO and a photon. Photons are useful for small and more compact projects, while Arduinos are for projects on a bigger scale. Unless you specifically need access to the cloud or access to WIFI, I would suggest buying the Arduino. Good luck!*

---
Tags: arduino-uno
---


# Question
Title: How to use Aiduino module to connect to computer network?
I have 4 usb Hard Drives and I just want to connect them to computer network directly without a traditional computer. Is there an any module with 4 usb ports and one RJ45 port. The module should able to connect drives to network as NAS (Network Area Storage) or other mounting possibility.

# Answer
An Arduino is completely incapable of doing such a difficult task. It's literally impossible because the processor isn't strong enough, it has no built in network capabilities that support NAS, it has no USB software built in, and so on and so on.

But you *can* use a Raspberry Pi. They are cheap for their capabilities, they do require quite some programming to get it to work but there's a huge community that has guides for everything. Best of luck :)
> 3 votes

---
Tags: arduino-mega, arduino-ide, arduino-nano, hardware, networking
---


# Question
Title: Follow up question to Calling a timer when a button is pushed
I have changed the code with some help here. There are two buttons each one is set to turn on a LED. When the LED turns on it is timed and when the time is up it turns off. The problem I am having is that only one LED can be on at a time even though I am not using the delay() and I am using millis() to keep track of time. So if I press button one the first LED will turn on. Even if I press button two at this time the second LED wont turn on until the first one turns off.

```
const int ledPin2 = 2;
const int ledPin3 = 3;
const int buttonPin6 = 6;
const int buttonPin7 = 7;

const unsigned long onTime = 10000;
unsigned long previousMillis = 0;

void timer() {

unsigned long previousMillis = millis();
unsigned long currentMillis = millis();
digitalWrite(ledPin2, HIGH);

while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

digitalWrite(ledPin2, LOW);
}

void timer2() {

unsigned long previousMillis = millis();
unsigned long currentMillis = millis();
digitalWrite(ledPin3, HIGH);

while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

digitalWrite(ledPin3, LOW);
}

void setup() {
Serial.begin(9600);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(buttonPin6, INPUT);
pinMode(buttonPin7, INPUT);

}

void loop() {

int buttonState2 = digitalRead(buttonPin6);
if (buttonState2 == HIGH) timer2();

int buttonState = digitalRead(buttonPin7);
if (buttonState == HIGH) timer();

}

```

# Answer
As jogco says, you are (effectively) using a delay in your timer function, by doing this:

```
while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

```

What you want is to remember the time each LED was switched on, and each every time through the loop check if the required time has passed. Something like this:

```
const int ledPin2 = 2;
const int ledPin3 = 3;
const int buttonPin6 = 6;
const int buttonPin7 = 7;

const unsigned long onTime = 10000;
unsigned long led1_start = 0;
unsigned long led2_start = 0;
boolean led1_on = false;
boolean led2_on = false;

void timerOn(int led) {

    switch(led) {
        case 1:
            led1_start = millis();
            digitalWrite(ledPin2, HIGH);
            led1_on = true;
            break;
        case 2:
            led2_start = millis();
            digitalWrite(ledPin3, HIGH);
            led2_on = true;
            break;
    }
}

void timerOff(int led) {

    switch(led) {
        case 1:
            digitalWrite(ledPin2, LOW);
            led1_on = false;
            break;
        case 2:
            digitalWrite(ledPin3, LOW);
            led2_on = false;
            break;
    }
}

boolean checkTime(unsigned long startTime) {
      return ((startTime + onTime) >= millis());
}

void setup() {
    Serial.begin(9600);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
    pinMode(buttonPin6, INPUT);
    pinMode(buttonPin7, INPUT);
}

void loop() {

    int buttonState2 = digitalRead(buttonPin6);
    if (buttonState2 == HIGH) timerOn(2);

    int buttonState = digitalRead(buttonPin7);
    if (buttonState == HIGH) timerOn(1);

    if (led1_on) {
        if (checkTime(led1_start)) timerOff(1);
    }

    if (led2_on) {
        if (checkTime(led2_start)) timerOff(2);
    }

}

```

In fact I would look at arrays for the pin numbers and status/time variables, to make it more reusable...

```
int ledPins[2] = {2, 3};
int ledStart[2] = {0, 0};
int buttonPins[2] = {6, 7};

```

... and the like
> 3 votes

# Answer
Yes, it is because in timer() and timer2() you busy-loop with while until the condition is not met. Hence, when buttonState2 is HIGH, your code will execute timer2() until the condition of the while loop is not met. You are effectively doing a delay.
> 3 votes

---
Tags: timers
---


# Question
Title: Can I make so when I press a button on my Arduino Uno board, it will press a key on my computer?
I looked up the question before, but they only gave answers for boards that are not the Uno. Is there any way to make it so when I press a button on my board, it registers as a key press on my computer? I'm trying to make a flight controller for PC sims.

Thanks!

# Answer
> 3 votes
Not without extra software on your computer side.

However if you use Arduino Micro, you can emulate keyboard and/or mouse directly.

# Answer
> 0 votes
You'll need something on the Arduino that sends an event to your PC whenever the button is pressed. The easiest version of this would be the Serial channel over USB.

Second, you'll need a program running on your PC that receives that Serial message and generates your desired keyboard and mouse events.

In Windows, you can generate system wide keyboard and mouse events fairly easily using the Windows API. This would allow you to click a mouse, or keyboard button when inside of most programs written in Windows. https://msdn.microsoft.com/en-us/library/ms171548(v=vs.110).aspx

That said, you can have problems sending spoofed events to video games that don't use standard Windows forms. You might find this answer helpful from StackOverflow - https://stackoverflow.com/questions/7320424/c-win32-simulate-keypress-with-directinput

# Answer
> 0 votes
EDIT: check @JohnBurger 's comment. THIS is NOT good for the UNO.

You can connect your Arduino as a keyboard to the computer. There is a Keyboard Arduino library you can use. Here is a reference: KeyboardWrite

For example this line of code will react just like you pressed A on your keyboard:

```
Keyboard.write(65);

```

# Answer
> 0 votes
You can do USB HID device on any AVR or Arduino chip without USB hardware interface by bitbanging on any 2 DIO:

https://www.obdev.at/products/vusb/index.html

Supports 4 endpoints (like 2 mouse and 2 keyboard, if makes sense :). Sure no additional software or driver is needed on OS side (default drivers shall be ok if correct VID/PID specified).

**EDIT:**

Seems 2 endpoints are required for USB HID keyboard. If remaining 2 is enough for USB HID joystick, it could be useful for flight sim.

---
Tags: arduino-uno, button, keyboard
---


# Question
Title: ir sender detecting receiver and display
I am in a pickle and want to know if you can help me. I have an IR sensor and receiver and want a program that makes a light bulb flash or detect whenever the IR receiver is in range. So whenever the IR sender detects the receiver, it should print "detect". This will be done using the Arduino program. And it is an Arduino Nano I am using.

These are the things I use:

http://www.dx.com/p/keyestudio-digital-ir-receiver-module-for-arduino-black-429206#.V5gcpzYko-U

http://www.dx.com/p/38khz-ir-infrared-transmitter-module-for-arduino-135040#.V5gcpjYko-U

How should this program look like? Anyone have the code for this?

Never mind the LED blinking, I just want the program to know whenever the receiver is detected and probably display it somehow. My plan is to send the number of times the transmitter detects the receiver to an Android app in the end.

# Answer
You can't.

IR is a one-way protocol. The transmitter has no way of knowing whether a receiver is in range; it's literally just an LED that emits infrared instead of visible light.
> 2 votes

# Answer
Assuming you got receiver and transmitter mixed up, then its simple. Otherwise, its not as simple. As @duskwuff points out, simple IR is one-way. The Transmitter here is just an IR Led. That's it. The Receiver is a Remote Control type IR Receiver, looks for a 38khz modulated IR signal, and removes the 38khz carrier wave, passing on the data to be read by the other end.

For a IR beacon type setup, in either simple or two way mode, you'd need two micro controllers.

Simple:

* Microcontroller A is the Transmitter. All it does is repeatedly send out an IR modulated code. The Arduino IRLib library can do this.
* Microcontroller B is the Receiver. It looks for that specific code, and if found, does X, which could be print to serial, or send over bluetooth to a phone.

Complex, both receive and send:

* **Microcontroller A is the main part**. It sends a code then switches to receive mode for X seconds. If it receives a confirmation or its own code back, it tells the phone/pc it has been found or flashes a different LED.
* Microcontroller B is **a beacon/repeater**. It waits to receive the code above, then switches to transmit mode, and sends the same code or a different code back. That's all it does. A Basic IR Remote Control Repeater.

This tutorial at Adafruit explains it all, with code examples.
> 1 votes

---
Tags: ir
---


# Question
Title: Why is there a need to ground a circuit?
Please tell me why I have to connect one of the wires of arduino gnd to the gnd of a relay or a bluetooth module?

# Answer
> 1 votes
If you are constructing a complex circuits or connecting many boards and sensors together, you really need to provide a common ground for all the devices.

The main reason is here we are dealing voltage and different circuits operate at different voltages. It is important to understand that voltage is the potential difference between two points in the circuit. This value is relative to the circuit itself since every circuit has its own ground (GND) pin. What this means is there is no absolute potential difference for a complex circuits. Hence, it is important to establish a common ground such that all potential difference can be measured from a common GND pin.

For instance, consider you have an arduino (operates at 5V) connected to motor controllers or relays (operates at 12V) and there are no common ground established between them. This will mess up the signals from arduino to motor controllers or relays. The output signals coming from the arduino may not be 5V but lower. Therefore, it is not detected by the motor controllers/relays.

I hope this helps.

# Answer
> 5 votes
Electric circuits need to be closed. The hydraulic analogy might help you in this sense: suppose you have a garden fountain and want to recycle its water; if you want water to *circulate* by means of a pump, you need a way to put the water back in the pump. That's what the ground connection is for.

Sometimes you have closed circuits using other wires, and a ground connection (or a shorter, direct ground connection) might be required to keep at bay the effect of EMI (electro-magnetic interference). For example, this is the output of an Arduino Nano sensed by connecting only the tip of the oscillocope probe to pin 13.

And this is the same output when I connected the ground tip to Arduino's GND (actually to the USB frame):

---
Tags: arduino-uno
---


# Question
Title: Reading digital port with pullup via Firmata
I've got a weird issue, probably something I'm missing but have no clue what.

Got some simple float sensors connected to D2 - D5 on a Nano. Need internal pull-up to eliminate a floating value. Wrote this little sketch to test things:

```
pinMode(2, INPUT_PULLUP);
int sensorVal = digitalRead(2);
Serial.println(sensorVal);

pinMode(3, INPUT_PULLUP);
int sensorVal = digitalRead(3);
Serial.println(sensorVal);

```

There's one sensor connected reading HIGH and one reading LOW. This works as expected (displays 1010101010...).

Now I've got this connected to my Raspberry Pi via Bluetooth (BT shield connected to RX/TX) and using Firmata to communicate with the Nano. Code (C#):

```
_arduino.pinMode(2, PinMode.PULLUP);
PinState result2 = _arduino.digitalRead(2);

_arduino.pinMode(3, PinMode.PULLUP);
PinState result3 = _arduino.digitalRead(3);

Debug.WriteLine($"Result pin 2: {result2} and pin 3: {result3}");

```

This always gives me two pinstates of LOW, even though I'm absolutely sure it should be reading HIGH as my test sketch is outputting the correct value. This driving me nuts. The Firmata sketch I've got loaded on the Arduino is this one: https://github.com/jsiegmund/submerged/blob/master/src/Arduino%20Sketches/SubmergedCabinetModule/SubmergedCabinetModule.ino. Also tried the latest available version from the firmata repo, doesn't solve the issue. As I've got the BlueTooth shield connected to RX/TX (and wasn't able to change that) I cannot use the serial monitor to provide more debug info. Should anyone know how to change that, would also be appreciated.

Btw for other things, Firmata is working just fine. So the communication itself shouldn't be the issue I think.

# Answer
Never mind, I found out what the problem is. The Firmata SDK (Remote Wiring) for Windows just completely ignores the PULLUP pin mode. There are PR (https://github.com/ms-iot/remote-wiring/pull/102) which fixes this, now it's working just fine.
> 1 votes

---
Tags: arduino-nano, pull-up, firmata
---


# Question
Title: Please explain this adafruit image for connecting a DS1307 RTC
https://learn.adafruit.com/assets/3813

I understand that `analog 4` and `5` are `SDA/SLC`, isn't the picture also showing `5v` and `GND` being plugged into two analog pins? Does that work?

I have it wired up to the actual `5v` and `GND`, but it would be convieniet to be able to stack the RTC like they show in the picture

# Answer
It's written in the tutorial

> If you set analog pin 3 (digital 17) to an OUTPUT and HIGH and analog pin 2 (digital 16) to an OUTPUT and LOW you can power the RTC directly from the pins!
> 3 votes

---
Tags: arduino-uno, rtc
---


# Question
Title: Best way to read CSV from SD card and store values by date
I am starting a project in Arduino and I need to read data from an CSV stored in an SD card. The data is stored as the following:

id, value, date

What I want to do is read the file, filter by date and then store the values by id. Each id will correspond to different values from that same date.

Is it possible to do something like this?

Thank you very much for your advice.

# Answer
I highly suggest checking out this YouTube video (https://www.youtube.com/watch?v=5v5A3j7Rrco), especially around 21:30. It goes over in detail to do exactly what you are asking for, mainly the headings with IDs for each data point. At the end of the day you are going to need something that looks similar to this:

```
float id = 0; //used to provide a numbered ID to each data point

void setup(){
//initialize all your once-run variables and such
}

void loop(){
  //Write Log File Header
  File logFile = SD.open("NAME.csv", FILE_WRITE);

  if (logFile){
    logFile.println(", , , ,"); //Just a leading blank line, incase there was previous data

    String header = "ID, Time, Light, Temp"; //These will be the headers for your excel file, CHANGE "" to whatevr headers you would like to use
    logFile.println(header);
    logFile.close();
    Serial.println(header);
  }

  else {
    Serial.println("Couldn't open log file");
  }
}
}

```

This is all code that I currently use to do the exact same thing as you, and its a small edit from what Jeremy Blum does in the YouTube video I just linked you too. This is how the header files will look on an excel sheet, I took a screenshot of an actual file I have created using this method:
> 1 votes

---
Tags: sd-card
---


title: Arduino sketch unexpected behaviour

text:
# Question
Title: Arduino sketch unexpected behaviour
I am currently in a arduino project to read some parameters from another microcontroller serially and the arduino is supposed to transmit these serially to dweet.io cloud. I use SIM900 modem for this. But my problem is that if i put some data to the variables, then the post to the cloud becomes unsuccessfull. Without any data in all parameters, the code runs fine.

Please find the code

```
char code[4] = {'\0'}, voltage[4] = {'\0'}, current[4] = {'\0'}, mcurrent[4] = {'\0'}, acurrent[4] = {'\0'}, power[4] = {'\0'}, pf[4] = {'\0'}, freq[4] = {'\0'}, temp[4] = {'\0'};
const char APN[18] = "bsnlnet";
byte dtype = 0;

#include <avr/pgmspace.h>

void read_comp() {
    byte flag = 0, index = 0, l = 0;
    char c;
    char readings[8] = {'\0'};
    dtype = 0;

    do {
        while (Serial.available() && l == 0) {
            c = Serial.read();
            delay(20);

            if (c == '\n') {
                l = 1;
                break;
            } else {
                readings[index] = c;
                index++;
            }
        }

        readings[index] = '\0';
        index = 0;
        l = 0;

        if (readings[0] == 'v' || readings[0] == 'V') {             //check if received reading is voltage
            dtype = 1;
            flag = 1;

            if (readings[1] == 'o') {
                flag = 100;
            }
        } else if (readings[0] == 'c' || readings[0] == 'C') {  //check if received reading is current
            dtype = 2;
            flag = 1;

            if (readings[1] == 'u') {
                flag = 100;
            }
        } else if (flag == 1 && readings[1] == 'o') {
            dtype = 9;
            flag = 100;
        } else if (readings[0] == 'm' || readings[0] == 'M') {
            dtype = 3;
            flag = 1;

            if (readings[1] == 'c' && flag == 1) {
                flag = 100;
            }
        } else if (readings[0] == 'a' || readings[0] == 'A') {
            dtype = 4;
            flag = 1;

            if (readings[1] == 'c') {
                flag = 100;
            }
        } else if (readings[0] == 'p' || readings[0] == 'P') {
            flag = 1;

            if (readings[1] == 'o') {
                flag = 100;
                dtype = 5;
            } else if (readings[1] == 'f' || readings[1] == 'F') {
                flag = 100;
                dtype = 6;
            }
        } else if (readings[0] == 'f' || readings[0] == 'F') {
            dtype = 7;
            flag = 1;

            if (readings[1] == 'r') {
                flag = 100;
            }
        } else if (readings[0] == 't' || readings[0] == 'T') {
            dtype = 8;
            flag = 1;

            if (readings[1] == 'e') {
                flag = 100;
            }
        }

        if (flag == 100) {
            switch (dtype) {
                case 1:
                    voltage[0] = readings[3];
                    voltage[1] = readings[4];
                    voltage[2] = readings[5];
                    voltage[3] = readings[6];
                    voltage[4] = '\0';
                    flag = 0;
                    break;

                case 2:
                    current[0] = readings[3];
                    current[1] = readings[4];
                    current[2] = readings[5];
                    current[3] = readings[6];
                    current[4] = '\0';
                    flag = 0;
                    break;

                case 3:
                    mcurrent[0] = readings[3];
                    mcurrent[1] = readings[4];
                    mcurrent[2] = readings[5];
                    mcurrent[3] = readings[3];
                    mcurrent[4] = '\0';
                    flag = 0;
                    break;

                case 4:
                    acurrent[0] = readings[3];
                    acurrent[1] = readings[4];
                    acurrent[2] = readings[5];
                    acurrent[3] = readings[6];
                    acurrent[4] = '\0';
                    flag = 0;
                    break;

                case 5:
                    power[0] = readings[3];
                    power[1] = readings[4];
                    power[2] = readings[5];
                    power[3] = readings[6];
                    power[4] = '\0';
                    flag = 0;
                    break;

                case 6:
                    pf[0] = readings[3];
                    pf[1] = readings[4];
                    pf[2] = readings[5];
                    pf[3] = readings[6];
                    pf[4] = '\0';
                    flag = 0;
                    break;

                case 7:
                    freq[0] = readings[3];
                    freq[1] = readings[4];
                    freq[2] = readings[5];
                    freq[3] = readings[6];
                    freq[4] = '\0';
                    flag = 0;
                    break;

                case 8:
                    temp[0] = readings[3];
                    temp[1] = readings[4];
                    temp[2] = readings[5];
                    temp[3] = readings[6];
                    temp[4] = '\0';
                    flag = 0;
                    break;

                case 9:
                    code[0] = readings[3];
                    code[1] = readings[4];
                    code[2] = readings[5];
                    code[3] = readings[6];
                    code[4] = '\0';
                    dtype = 10;
                    flag = 0;
                    break;
            }
        }
    } while (dtype != 10);
}

void modem_initialization(void) {
    char rec_data, r;
    byte network_status = 0 ;//network_status initialized as zero
    byte status_check = 0 ;//status_check initialized as zero
    byte Serial3_cnt = 0;//Serial3_cnt initialized as zero
    byte ok_flag = 0; //ok_flag initialized as zero
    byte count = 0; //count initialized as zero
    clear_rx_buffer();

    while (Serial3_cnt < 4) { // repeat entire loop until Serial3_cnt less than 5
        switch (Serial3_cnt) {
            case 0:
                clear_rx_buffer();//clearing receiving buffer
                Serial3.println(F("AT"));// Attention command to wake up Serial3 modem
                delay(1000);
                break;

            case 1:
                clear_rx_buffer();//clearing receiving buffer
                Serial3.println(F("ATE0"));//Command for disable echo
                delay(1000);
                break;

            /*case 2: clear_rx_buffer();//clearing receiving buffer
                   // Serial3.println("ATV0");// Command for numeric response after this '0'(zero) will be recieved instead of "OK"
                    delay(1000);
                    break;*/
            case 2:
                clear_rx_buffer();//clearing receiving buffer
                Serial3.println(F("AT&W"));// Command TO SAVE SETTINGS
                delay(1000);
                break;

            case 3:
                Serial3_cnt = 4;// exit from the loop
                break;

            default :
                break;
        }

        while (Serial3.available() > 0) {
            rec_data = Serial3.read();

            if (rec_data == 'O') { // 'o' is recieved
                ok_flag = 1;
            } else if (ok_flag == 1 && rec_data == 'K') { // 'K' is recieved
                Serial3_cnt ++;
                ok_flag = 0;
            } else if (rec_data == '0') { // '0'(zero) is recieved (numeric response)
                Serial3_cnt ++;
                ok_flag = 0;
            } else if (rec_data == '+') { // '+' is recieved message
                clear_rx_buffer();

                if (Serial3_cnt > 0) {
                    Serial3_cnt --;
                }
            }
        }
    }

    Serial3_cnt = 0;
    ok_flag = 0;

    while (network_status == 0) { //wait for PIN READY
        if (status_check == 0) {
            delay(1000);
            status_check = 1 ;
            clear_rx_buffer();
            Serial3.println(F("AT+CPIN?")); //checkin PIN return ready(+CPIN: READY) with a valid simcard otherwise error
        }

        while (Serial3.available() > 0) {
            rec_data = Serial3.read();

            if (rec_data == '+' && status_check == 1) { // '+' is recieved
                status_check = 2 ;
            } else if (rec_data == 'C' && status_check == 2) { // 'C' is recieved
                status_check = 3 ;
            } else if (rec_data == 'P' && status_check == 3) { // 'P' is recieved
                status_check = 4 ;
            } else if (rec_data == 'I' && status_check == 4) { // 'I' is recieved
                status_check = 5 ;
            } else if (rec_data == 'N' && status_check == 5) { // 'N' is recieved
                status_check = 6 ;
            } else if (rec_data == ':' && status_check == 6) { // ':' is recieved
                status_check = 7 ;
            } else if (rec_data == ' ' && status_check == 7) { // ' ' is recieved
                status_check = 8 ;
            } else if (rec_data == 'R' && status_check == 8) { // 'R' is recieved
                status_check = 9 ;
            } else if (rec_data == 'E' && status_check == 9) { // 'E' is recieved
                status_check = 10 ;
            } else if (rec_data == 'A' && status_check == 10) { // 'A' is recieved
                status_check = 11 ;
            } else if (rec_data == 'D' && status_check == 11) { // 'D' is recieved
                status_check = 12 ;
            } else if (rec_data == 'Y' && status_check == 12) { // 'Y' is recieved
                status_check = 13 ;
            } else if (rec_data == 0X0D && status_check == 13) { //Carriage return
                status_check = 14 ;
            } else if (rec_data == 0X0A && status_check == 14) { //Line Feed
                status_check = 15 ;
            } else if (rec_data == 'O' && status_check == 15) { // '0' is recieved
                status_check = 16;
            } else if (rec_data == 'K' && status_check == 16) {
                clear_rx_buffer();
                status_check = 0 ;
                network_status = 1; //goto next step
            } else if (rec_data != 'R' && status_check == 8) { //+CPIN: NOT READY
                clear_rx_buffer();
                status_check = 0 ;
                network_status = 0; //repeat current step
            } else if (rec_data == 'M' && status_check == 3) { // in case of any message
                clear_rx_buffer();
                status_check = 0 ;
                network_status = 0; //repeat current step
            }
        }
    }

    while (network_status == 1) { //wait for SIM network registration
        if (status_check == 0) {
            delay(1000);
            status_check = 1 ;
            clear_rx_buffer();
            Serial3.println(F("AT+CREG?")); //checking for SIM card registration ,if registerd "+CREG: 0,1" will receive
        }

        while (Serial3.available() > 0) {
            rec_data = Serial3.read();

            if (rec_data == '+' && status_check == 1) { // '+' is recieved
                status_check = 2 ;
            } else if (rec_data == 'C' && status_check == 2) { // 'C' is recieved
                status_check = 3 ;
            } else if (rec_data == 'R' && status_check == 3) { // 'R' is recieved
                status_check = 4 ;
            } else if (rec_data == 'E' && status_check == 4) { // 'E' is recieved
                status_check = 5 ;
            } else if (rec_data == 'G' && status_check == 5) { // 'G' is recieved
                status_check = 6 ;
            } else if (rec_data == ':' && status_check == 6) { // ':' is recieved
                status_check = 7 ;
            } else if (rec_data == ' ' && status_check == 7) { // ' ' is recieved
                status_check = 8 ;
            } else if (rec_data == '0' && status_check == 8) { // '0' is recieved
                status_check = 9 ;
            } else if (rec_data == ',' && status_check == 9) { // ',' is recieved
                status_check = 10 ;
            } else if (rec_data == '1' && status_check == 10) { // '1' is recieved
                status_check = 11 ;
            } else if (rec_data == 0X0D && status_check == 11) { //Carriage return
                status_check = 12 ;
            } else if (rec_data == 0X0A && status_check == 12) { //Line Feed
                status_check = 12 ;
            } else if (rec_data == 'O' && status_check == 12) { // '0' is recieved
                status_check = 13;
            } else if (rec_data == 'K' && status_check == 13) {
                clear_rx_buffer();
                status_check = 0 ;
                network_status = 2; //goto next step
            } else if (rec_data != '1' && status_check == 10) { // +CREG: 0,2 not registered
                clear_rx_buffer();
                status_check = 0 ;
                network_status = 1; //repeat current step
            } else if (rec_data == 'M' && status_check == 3) { // in case of any message
                clear_rx_buffer();
                status_check = 0 ;
                network_status = 1; //repeat current step
            }
        }
    }

    Serial3_cnt = 0;

    while (Serial3_cnt < 4) { // repeat entire loop until Serial3_cnt less than 4
        switch (Serial3_cnt) {
            case 0:
                clear_rx_buffer();//clearing receiving buffer
                Serial3.println(F("AT+CMGF=1"));// Attention command to wake up Serial3 modem
                delay(1000);
                break;

            case 1:
                clear_rx_buffer();//clearing receiving buffer
                Serial3.println(F("AT+CNMI=2,1,0,0,0"));//Command to configure new message indication
                delay(1000);
                break;

            case 2:
                clear_rx_buffer();//clearing receiving buffer
                Serial3.println(F("AT+CMGD=1,4"));// Command to delete all received messages
                delay(1000);
                break;

            case 3:
                Serial3_cnt = 4;// exit from the loop
                break;

            default :
                break;
        }

        while (Serial3.available() > 0) {
            rec_data = Serial3.read();

            if (rec_data == 'O') { // '0'(zero) is recieved (numeric response)
                rec_data = Serial3.read();

                if (rec_data == 'K') {
                    Serial3_cnt ++;
                }
            } else if (rec_data == '+') { // '+' recieved ,before "AT+CIICR" command,may be any message
                clear_rx_buffer();

                if (Serial3_cnt > 0) {
                    Serial3_cnt --;
                }
            } else if (rec_data == 'E' && Serial3_cnt > 2) { // '4' recieved (error),in gprs initialisation commands
                clear_rx_buffer();
                Serial3_cnt = 4;
            }
        }
    }

    Serial3_cnt = 0;
}

void clear_rx_buffer(void) {
    Serial3.flush();
}

void gprs_init() {
    byte st = 1, i = 0, response = 0;
    char r[10];

    while (st <= 9) {
        delay(1000);
        clear_rx_buffer();

        switch (st) {
            case 1:
                Serial3.println(F("AT+CGATT?"));
                break;

            case 2:
                Serial3.println(F("AT+CIPSHUT"));
                break;

            case 3:
                Serial3.println(F("AT+CIPMUX=0"));
                break;

            case 4:
                response = cmd1_check(1);
                break;

            case 5:
                Serial3.println(F("AT+CIICR"));
                delay(1000);
                break;

            case 6:
                Serial3.println(F("AT+CIFSR"));
                break;

            case 7:
                response = cmd1_check(2);
                delay(2200);
                clear_rx_buffer();
                break;

            case 8:
                Serial3.println(F("AT+CIPSEND"));
                break;

            case 9:
                Serial3_send();
                ++st;
                break;
        }

        if (st == 10) {
            clear_rx_buffer();
        }

        delay(1000);

        while (Serial3.available() && st < 9 && st != 7 && st != 4) {
            r[i] = Serial3.read();
            i++;
        }

        i = 0;

        if (strstr(r, "ALREADY") != NULL) {
            Serial3.println("AT+CIPSHUT");
            delay(50);
            clear_rx_buffer();
            st = 2;
            r[0] = '\0';
        }

        if (strstr(r, "OK") != NULL || strstr(r, "+CGATT") != NULL || (strstr(r, ".") != NULL && st == 6) || strstr(r, ">") != NULL) {
            st++;
        } else if (strstr(r, "ERR") != NULL) {
            break;
        } else if (response == 1 && (st == 7 || st == 4)) {
            st++;
            response = 0;
        }
    }
}

char cmd1_check(short int o) {
    byte timout1 = 10500, m1, p1 = 0, resp1 = 0;
    char response1[25] = {'\0'};
    m1 = millis();
    clear_rx_buffer();

    if (o == 1) {
        Serial3.print(F("AT+CSTT="));
        Serial3.print('"');
        Serial3.print(APN);
        Serial3.print('"');
        Serial3.print(',');
        Serial3.print('"');
        Serial3.print('"');
        Serial3.print(',');
        Serial3.print('"');
        Serial3.println('"');
        delay(3000);
    } else if (o == 2) {
        Serial3.print(F("AT+CIPSTART="));
        Serial3.print('"');
        Serial3.print(F("TCP"));
        Serial3.print('"');
        Serial3.print(',');
        Serial3.print('"');
        Serial3.print(F("dweet.io"));
        Serial3.print('"');
        Serial3.print(',');
        Serial3.println(80);
        delay(2000);
    }

    do {
        p1 = 0;

        while (Serial3.available()) {
            response1[p1] = Serial3.read();
            p1++;
            delay(20);
        }

        if (strstr(response1, "OK") != NULL && o == 1) {
            resp1 = 1;
        } else if (strstr(response1, "ERR") != NULL) {
            resp1 = 2;
        } else if (strstr(response1, "CONNECT OK") != NULL && o == 2) {
            resp1 = 1;
        }
    } while ((millis() - m1) <= timout1 && resp1 == 0);

    return (resp1);
}

void Serial3_send() {
    Serial3.print("POST /dweet/for/");
    Serial3.print("mythingname");
    Serial3.print("?vo=");
    Serial3.print(voltage);
    Serial3.print("&cu=");
    Serial3.print(current);
    Serial3.print("&Mc=");
    Serial3.print(mcurrent);
    Serial3.print("&Ac=");
    Serial3.print(acurrent);
    Serial3.print("&Po=");
    Serial3.print(power);
    Serial3.print("&PF=");
    Serial3.print(pf);
    Serial3.print("&fr=");
    Serial3.print(freq);
    Serial3.print("&Te=");
    Serial3.print(temp);
    Serial3.println(" HTTP/1.1");
    Serial3.println("connection: keep-alive");
    Serial3.println();
    Serial3.println();
    Serial3.write(26);
    Serial3.println();
    delay(10000);
    Serial3.println("AT+CIPSHUT");
    delay(50);
}

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

void loop() {
    dtype = 0;
    read_comp();
    gprs_init();
}

```

# Answer
This **looks like** you are constructing the data to be sent as **GET** parameters (i.e as part of the querystring), whereas I believe dweet.io expects them as part of the **POST** body - as seen here.

There seem to be many people struggling to successfully send HTTP POSTs with a SIM900, but I think this answer outlines the correct sequence to make it work.
> 2 votes

---
Tags: gsm, memory
---


title: Solar Power Inside a Car

text:
# Question
Title: Solar Power Inside a Car
I plan on making an Arduino project for reminding a parent to take a child from a car. In order to power the project I though on using a solar panel. Since I can't rely on having solar power all the time I'll need to use rechargeable batteries and charge them with the solar panel.

The problem is that from reading about the subject it is clear that it can be dangerous as far as battery go up in flame in some cases, especially due to high heat.

My car can get into very high temperature when parked outside so this scenario is very likely to happen.

Can someone please direct me to reading materials about using solar power in a very safe way?

# Answer
Firstly, solar panels inside a car is pretty pointless. Solar panels need to be in direct sunlight to be effective. Having them inside a car means they're not going to be in direct sunlight, so they're not going to be able to generate anywhere near enough power - unless they are massive, in which case where is the child going to sit? Yes, you could put them on the roof, but that would be silly.

The whole concept of solar panels for this project is completely wrong.

The car has a big battery and an in-built generator. Use them. There is absolutely no reason for you to have your own batteries as well. Yes, you could charge your own batteries from the car's battery, but that just introduces extra losses and wastefulness.

The only possible benefit of having your own batteries is it will safeguard the car's battery when the engine isn't running. It would then be impossible for your project to flatten the car's battery. But if you design your project properly that wouldn't be a problem anyway.

Some things you seem to be missing with your project:

1. The car has power you can use. It's throughout the car. No need to provide your own external power source.
2. The car has an "accessory" signal that is only turned on when the ignition is on. It's used by things like the radio etc so that when you turn the car's ignition off the radio turns off. No need for vibration sensors or anything to know if the car is running, it can tell you directly.
3. Cars generally have "seat occupied" sensors in them that couple with the seatbelts to know if a passenger hasn't got their seatbelt on and warn the driver (in most jurisdictions it's the responsibility of the driver to ensure all passengers have their seatbelts on).

If you really must charge batteries there are certain safety aspects you really must take into account. Your charge circuit must be able to manage the battery charging 100% safely. You have mentioned heat, and that is a very very important thing to manage. A decent battery manager chip will include an input for a thermistor. That is used as one of the multiple methods of charge termination (there's dv/dt (change in voltage over time), dT/dt (change in temperature over time), etc). It also serves as an over-heat safety cutout. Ensure that the charge circuit you use not only provides a thermistor input but also has the ability to cut off charging in the case of an overheat situation.

You also need to consider over-voltage. A car's 12V supply isn't 12V. It can get as high as 16V sometimes, and noise from the ignition can cause regular spikes as high as 70V or more. Automotive electronics have to be able to withstand those spikes, and that means your charge circuit has to be able to withstand those spikes. Buffering the 12V through a proper 5V (cigarette lighter USB charger) regulator will remove that noise and make your circuit easier to work with.

So you need to think more carefully about just what it is you want to achieve and how that is going to fit into an automotive situation.
> 1 votes

---
Tags: power, solar, heat
---


title: Arduino-like ethernet only board?

text:
# Question
Title: Arduino-like ethernet only board?
I don't think USB chip is more expensive than Ethernet chip. So, I expect there should exist a board like Arduino, but where USB is removed in favour of Ethernet.

Are there such boards?

# Answer
> 2 votes
Yes, there's the Arduino Ethernet. Available from Sparkfun for example

# Answer
> 0 votes
It is highly unlikely you will ever find an "Ethernet only" board. There are plenty of boards that have both Ethernet and USB, but one without USB? I doubt it.

To make an Ethernet only board you would first need to create a bootloader with built-in support for the Ethernet port as well as a way of configuring that port to suit your network. Than kind of program would be rather large and take up a fair proportion of the flash memory, leaving you with much less room for your own program.

And as you have rightly noticed, USB chips (especially the dreaded CH340G, the bane of my life) are so cheap now, so why *wouldn't* you include one on your board?

So you get boards with both USB *and* Ethernet, and you install the software (generally) through USB which doesn't need any special configuration or complex software to get it to work.

Some boards provide "OTA" (Over The Air) updates, such as the ESP8266, but these generally require the OTA software first installing via the USB (or UART) connection to allow it to communicate on your network and accept OTA firmware. Others, such as the Arduino Yun, use multiple MCUs to provide remote programming. In the case of the Yun you get a "host" microcontroller which is considerably more powerful than the AVR microcontroller that it is programming, which always strikes me as a little pointless.

So no, I doubt that anyone would ever want to make an Ethernet only board.

---
Tags: ethernet
---


# Question
Title: On UNO, when serial.print to UART pin 11, nothing comes out of pin 11
The problem: Message prints only to the Arduino IDE's **Tools \> Serial Monitor**, not coming out of TX pin 11. Question, please how to get Arduino Uno or Mega to send data out of pin 11?

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(12, 13); // RX, TX pins on Arduino
void setup() {
  Serial.begin(9600);
}
void loop() {
  Serial.print("This is a test\n\n");
  delay(1000);
}

```

# Answer
> 3 votes
Of course it's only coming out on the serial monitor - you are printing it to the hardware UART which comes out on the serial monitor.

You have created a SoftwareSerial object which you are then completely ignoring and then using the HardwareSerial UART object instead, which is on pins 0/1.

If you want to use a SoftwareSerial object you should actually *use* the SoftwareSerial object.

Replace all the references to `Serial` with `mySerial` instead.

---
Tags: arduino-uno, softwareserial
---


title: Arduino and A4988

text:
# Question
Title: Arduino and A4988
I am new in the Arduino area.
What is necessary to control motors through Arduinos.

1. What is the difference between A4988 and the Arduino motor shield?
2. Is one A4988 needed for each stepper motor?
3. Or is one A4988 enough for all motors?

# Answer
> 1 votes
An A4988 can control a single motor and supply up to 35V at 1.5A. An Arduino motor shield can drive 2 DC Motors or 1 stepper motor at up to 12V and 4A/2A.

An A4988 needs mounting. A motor shield drops straight in.

There are other options, including getting the ICs and doing it your self. I have a motor shield which drives 4 DC motors or 2 Stepper motors that I got off eBay.

# Answer
> 1 votes
The A4988 is a bipolar stepper driver. It is designed specifically to drive a single bipolar (4-wire) stepper motor. It consists of a pair of H-bridges and some extra drive logic to provide a simple GPIO interface.

The motor shield, in contrast, uses the L298D motor driver chip. This provides, as well, two H-bridges like the A4988. However it just gives you direct control of those H-bridges without a simple stepper-oriented interface. So it is up to you to provide the correct control signals to effectively emulate the A4988's outputs.

Both chips can interface with exactly one bipolar stepper motor. The A4988 can *only* interface with a stepper motor. The L298D can *also* be used with other types of motor (though of course not at the same time as a bipolar stepper).

---
Tags: arduino-uno
---


# Question
Title: mqtt library which support softwareSerial on arduino uno with ESP8266
I am using ESP8266 and Arduino with `SoftwareSerial`. My requirement is to use MQTT protocol with it. So I am using an MQTT library named `pubSubClient` but the problem is it doesn't support `SoftwareSerial`. Could anyone tell me how can I use MQTT protocol with it?

```
#include
#include
SoftwareSerial esp(2, 3); // RX, TX
PubSubClient client(esp);

```

The error I get is: `no matching function for call to 'PubSubClient::PubSubClient(SoftwareSerial&)`

# Answer
In order to use the ESP8266 WiFi module with `pubSubCient`, you need a library that interfaces with the module with the usual AT commands, while presenting an Arduino `Client` interface on the surface. A while back, I found this library after a great deal of searching. It supports `SoftwareSerial` as well as `HardwareSerial` objects. Its ESP8266 interface provides the standard `Client` methods of `write()`, `read()`, `connected()`, etc. There are some issues, of course, but its the best I've found so far. You can pass the created `Client` object to the `pubSubClient` constructor and you're good to go.
> 1 votes

# Answer
Not sure what you're trying to do - but thought I would offer this since I just spend some time on getting my esp8266 to act as a wifi shield for my arduino. Basically I wanted to subscribe to an mqtt channel and send the payload to my arduino. So the esp8266 connected to a broker, upon reading a message, it would simply write it via serial to the arduino (I used software serial on the arduino side so I could use the standard serial for debugging). If it helps, check out http://mganis.blogspot.com for the details

--Matt
> 0 votes

---
Tags: arduino-uno, esp8266, softwareserial
---


title: Arduino wait for change in value

text:
# Question
Title: Arduino wait for change in value
I am currently working on a project that involves steering wheels, and I would like a way for Arduino to wait for a change in value. A potentiometer is used and I would like a program to run (say, like lights blinking ) until there is a change in value of the potentiometer ( like an increase in 300).

Thanks in advance.

**EDIT** I realized that I did not give enough information about what I want, so here is the actual task I am trying to achieve :

The lights goes on when :

Button is pressed

The lights goes off when :

The button is pressed again

*or*

Another button is pressed

*or*

Potentiometer increases **or** (only one of it) decreases by 300

Plus I didn't mention that the value of the potentiometer will be constantly changing so the old value for the potentiometer should be the one right after the button press.

Soooo sorry for the inconvenience caused. ( I am really bad at programming)

# Answer
```
int oldValue;
void setup()
{
    oldValue = analogRead(A1);
}

void loop()
{
    int value = analogRead(A1);
    while( abs(value-oldValue)<300 )
        delay(1);
    oldValue = value;

    // start blinking lights here, as the value has changed by at least 300

}

```
> 1 votes

# Answer
A change in value is nothing more than that. A change between a value *then* and the value *now*.

All you need to do is remember what the value used to be, and compare it with what the value is now. If the two have changed, and the change is big enough, then you do something.

And of course you have to remember that "now" will be "then" "next time".
> 0 votes

# Answer
Figured it out in the end. Although my solution doesn't exactly fit what I wanted but it works in this case. I used the FMS Majenko mentioned like this : Wait for potentiometer value to go beyond a certain value, then wait for it to come back to the value. If that happens then the lights stop blinking. Thanks guys( this is quite different from what I initially wanted but it is enough for what it is meant to do)
> 0 votes

---
Tags: potentiometer
---


title: Server checkbox not working properly

text:
# Question
Title: Server checkbox not working properly
I am trying to make an arduino alarm clock to which you can send alarm clock times over the web. This is the HTML code

```
 <input type="checkbox" name="alarm1" id="alarm1">1</button>

```

It's sending the HTTP correctly but the rest of the code insists that the alarms are always on.

```
      if (_server.arg("alarm1") = "on") {
      alarm1 = true;
      Serial.println("Alarm 1 is set");
  }
  else {
      alarm1 = false;
      Serial.println("Alarm 1 is inactive");
  }

```

# Answer
The alarm is always on because you are setting it to be always on. You code should say:

```
 if (_server.arg("alarm1") == "on") {

```
> 2 votes

---
Tags: esp8266, web-server
---


title: Size of String array

text:
# Question
Title: Size of String array
I am trying to find out the size of an array like this:

```
    String days[3] = { "Mon", "Tue", "Wed" };
Serial.printf("Size of array: %2d\n", sizeof(days));
for (int i = 0; i < sizeof(days); i++) {
    Serial.print(days[i]);
}

```

The result of the code above is 36 which is incorrect.

Do I have any other options considering that I don't know the size of the array to begin with?

# Answer
No, the result is correct, you're just interpreting it incorrectly. If you want the number of elements in a statically-allocated array use:

```
sizeof(somearray) / sizeof(somearray[0])

```
> 1 votes

---
Tags: esp8266, string, array
---