# Question
Title: Read information from Twitch's API and execute actions depending on the output
i'm trying to create a display that notifies me when someone goes live on twitch. I need to acess the API and check if the 'stream' object is null or not. Then, perform an action depending on this.

The address to the API is http://api.twitch.tv/kraken/streams/pedrinholuizf

What can I do? I'm using an Arduino Leonardo with the Ethernet Shield.

# Answer
> 2 votes
Break your problem into small steps and try to identify the success criteria for each step. So you might:

1. Try to set up the Ethernet shield and get it to respond to a ping on your local network.
2. Try to connect to a site outside of your network.
3. See if you can find some examples of using the Twitch API.
4. Try to replicate one of the simple examples.
5. See if you can get the Stream object that you want.
6. See if you can read the value of the object.

If you have a plan and try to follow it you'll be able to tell us what you've been doing and where you got stuck / confused. That is likely to get you better answers – both because we can be more specific and also because we can see that you're "carrying your weight" as we work on the problem.

---
Tags: ethernet
---


# Question
Title: Read RFID Card Number in Processing over Serial
I have successfully setup up a RFID reader with Arduino Uno and EM-18 Card Reader Module.

Its program for Arduino is below:

```
int count = 0; // count = 0

char input[12];                                         // character array of size 12

boolean flag = 0;                                       // flag =0

void setup()
{
   Serial.begin(9600);                                  // begin serial port with baud rate 9600bps
}

void loop()
{
   if(Serial.available())

{

count = 0;

while(Serial.available() && count < 12)          // Read 12 characters and store them in input array

{
input[count] = Serial.read();
count++;
delay(5);
}

//Serial.print("Card ID - ");

Serial.print(input);      // Print RFID tag number

}

}

```

But when try to read the code over serial in the program for locking/unlocking mouse in Processing the values of strings don't match. Hence the mouse doesn't get unlocked.

The program for processing is as below:

```
import processing.serial.*;
import java.awt.AWTException;
import java.awt.Robot;

Robot robot;
boolean locked = false;
Serial port;
void setup()
{
  println(Serial.list()); //Prints available ports

  port = new Serial(this, Serial.list()[36], 9600); //Chooses the first available port
  try
  {
    robot = new Robot(); //Creates robot
  }
  catch (AWTException e)
  {
    e.printStackTrace();
  }
}

void draw()
{
  if (locked == true) robot.mouseMove(0, 0); //If locked, moves mouse to top left corner
  while (port.available() > 0)
  {
    String input = port.readString();
    //println(input);
    if (input.equals("11006F26DC84") == true) locked = false; //If it read my card it will unloack.
  }
}

void keyPressed ()
{
  if (key == 'l')
  {
    locked = true; //Locks it
  }

  if (key == 'u')
  {
    locked = false; //Unlocks it
  }

  if (key == ESC)
  {
    key = 0; //Disables escape as quit
  }
}

```

Please point the incorrect syntax and suggest correct one.

# Answer
`input` has to be 13 characters in size; you forgot to include a byte for the null-terminator. Then right before `Serial.print(input)`, you write `input[12] = 0`. Also the argument to `string.equals()` should be a String as well; you must write the statement like this: `input.equals(String("11006F26DC84"));`
> 1 votes

---
Tags: arduino-uno, rfid, processing-lang
---


# Question
Title: Atlas Scientific pH project - serialEvent3 problems
I am trying to get this pH project working and I've noticed that the serialEvent3 never sets the boolean value sensor\_string\_complete to true. I am not sure if it is actually capturing the values from the probe. What I want is for every loop through it should grab a pH value and that is not happening right now. Most times through the loop the serial3 port is not providing any values. Here is my code:

```
String sensorstring = "";
boolean sensor_string_complete = false;
float pH;

void setup() {
  Serial.begin(38400);
  Serial3.begin(38400); // pH stamp
}

void serialEvent3() {                                 //if the hardware       serial port_3 receives a char
  sensorstring = Serial3.readStringUntil(13);         //read the string until we see a <CR>
  sensor_string_complete = true;                      //set the flag used to tell if we have received a completed string from the PC
}

void loop() {
  getPh();
  if (sensor_string_complete == true) readph();
}

void getPh() {
  Serial.println("we are here");
  Serial3.print("r");
  Serial3.print(13);
}

void readph(){
  Serial.println("read ph here");
  if (isdigit(sensorstring[0])) {
    pH = sensorstring.toFloat();
    Serial.println(pH);
  }
  else{
    Serial.println(sensorstring);
  }

  sensorstring = "";
  sensor_string_complete = false;
}

```

This returns values such as we are here we are here we are here read ph here 7.0 we are here read ph here 7.0 we are here we are here we are here read ph here 7.0

I want this to return these values every loop. I expect to see: We are here read ph here 7.0 We are here read ph here 7.0

Any help on this would be great. Thanks so much!

# Answer
> 3 votes
On a typical Arduino, the delay between `loop()` ending and `loop()` running again is a few microseconds. `Serial.println()` in `getPh()` is interrupt-driven so that call too takes only a few microseconds. Writing two bytes with `Serial3.print()` at 38400 bps will take about half a millisecond. In short, there is plenty of time for `loop()` to run several times before `serialEvent3()` sets `sensor_string_complete`.

To call `getPh()` once and `readph()` once per `loop()`, instead of

```
if (sensor_string_complete == true) readph();

```

say

```
while (!sensor_string_complete) {}
readph();

```

This will stall the loop while the pH sensor takes and reports a reading.

Note, in `getPh()` instead of using two separate `Serial3.print()` statements, you can just say `Serial3.print("r\r")`.

---
Tags: serial, arduino-mega
---


# Question
Title: Arduino Due: Interrupt-based ADC hangs processing
I am trying to build an oscilloscope using an Arduino Due and an LCD. I have the LCD running perfectly and started working on using the ADC peripheral to sample signals. Here's what I have so far:

```
#define SAMPLE_BUFFER_SIZE 800
volatile int sample_buffer[SAMPLE_BUFFER_SIZE];
volatile bool sample_buffer_full = 0;
volatile int sample_buffer_idx = 0;

void adcm_init() {
    pmc_enable_periph_clk(ID_ADC); // To use peripheral, we must enable clock distributon to it
    adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST); // initialize, set maximum posibble speed
    adc_disable_interrupt(ADC, 0xFFFFFFFF);
    adc_set_resolution(ADC, ADC_12_BITS);
    adc_configure_power_save(ADC, 0, 0); // Disable sleep
    adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1); // Set timings - standard values
    adc_set_bias_current(ADC, 1); // Bias current - maximum performance over current consumption
    adc_stop_sequencer(ADC); // not using it
    adc_disable_tag(ADC); // it has to do with sequencer, not using it
    adc_disable_ts(ADC); // deisable temperature sensor
    adc_disable_channel_differential_input(ADC, ADC_CHANNEL_7);
    adc_configure_trigger(ADC, ADC_TRIG_SW, 1); // triggering from software, freerunning mode
    adc_disable_all_channel(ADC);
    adc_enable_channel(ADC, ADC_CHANNEL_7); // just one channel enabled
    adc_enable_interrupt(ADC, ADC_IER_DRDY);            // Data Ready Interrupt Enable
    NVIC_EnableIRQ(ADC_IRQn);
    adc_start(ADC);
}

void ADC_Handler(void)  {
    if (!sample_buffer_full) {

        if ((adc_get_status(ADC) & ADC_ISR_DRDY) == ADC_ISR_DRDY) {

            sample_buffer[sample_buffer_idx] = adc_get_latest_value(ADC);
            sample_buffer_idx++;

            if (sample_buffer_idx == SAMPLE_BUFFER_SIZE) {
                sample_buffer_full = 1;
                sample_buffer_idx = 0;
            }
        }
    }
}

void setup()
{
    adcm_init();
    Serial.begin(115200);
}

void loop() {
    Serial.print("Loop\n");
    if (sample_buffer_full) {
        for (int i = 0; i < SAMPLE_BUFFER_SIZE; i++) {
            Serial.print(sample_buffer[i]);
            Serial.print(" ");
        }
        Serial.print("\n");
        sample_buffer_full = 0;
    }
}

```

This was copied and slightly modified from somewhere on the internet (can't remember where, though). I have also studied the docs and this code seems to make perfect sense and it should work.

The idea is for the sampling to be interrupt-based. However, if I set the ADC to freerunning mode and enable interrupts, it just gives up and stops working.

What I mean by that is: on my serial monitor, after pressing reset, all I see are 2 lines saying "Loop" and it just stops there. Normally it should print "Loop" indefinitely, and also print ADC values from time to time.

If I disable interrupts, "Loop" is printed indefinitely, but of course no values are shown. If I disable free-running mode, "Loop" is printed and no values are shown unless the buffer size is 1, in which case the same value is printed over and over (as expected, in that case the interrupt runs only once, right at the beginning).

The CPU clock freq. is 84Mhz, I'm going for the fastest I can get out of the ADC, so a sample is taken (and an interrupt is fired) every 1Mhz. That means 84 clock cycles per interrupt. Don't know for sure if that is enough for the rest of the program to work, but my gut tells me that's not a problem. Besides, I tried with a lower ADC clock value and it still didn't work.

Any ideas? I'm really at a loss here...

# Answer
> 4 votes
In your interrupt handler, `ADC_Handler()`, you set `sample_buffer_full` when the buffer is full. ~~I don't see anywhere in the code where `sample_buffer_full` ever gets reset (cleared) once it's been set.~~

While `sample_buffer_full` is set, it disables the body of the interrupt handler – ie, the handler's structure is

```
if (!sample_buffer_full) { ...body of handler... }

```

– and in particular, prevents `adc_get_latest_value(ADC);` from occurring. The source code of `adc_get_latest_value();` is like

```
uint32_t adc_get_latest_value(const Adc *p_adc) {
  return p_adc->ADC_LCDR;
}

```

which accesses the ADC data register. According to section 43.6.4 *Conversion Results* on page 1322 of the data sheet, Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A\_Datasheet.pdf,

> The channel EOC bit in the Status Register (ADC\_SR) is set and the DRDY is set. In the case of a connected PDC channel, DRDY rising triggers a data transfer request. In any case, either EOC and DRDY can trigger an interrupt.
>
> Reading one of the ADC\_CDR registers clears the corresponding EOC bit. Reading ADC\_LCDR clears the DRDY bit and EOC bit corresponding to the last converted channel.

It appears to me that your code enables interrupts, fills a buffer, sets `sample_buffer_full`, then spins in `ADC_Handler()`. That is, repeatedly executes `ADC_Handler()` without clearing the EOC bit.

Note, for oscilloscope applications with a Due, I suggest using DMA buffers instead of one interrupt per conversion. See thread #137635, *speed of analogRead*, in forum.arduino.cc for DMA code to read one or two analog channels on a Due at one sample per microsecond. Also see edaboard.com/thread283843 and forum.arduino.cc #186169

*Edit note:* Although `sample_buffer_full` does get reset, that reset happens after a time-consuming for-loop. Whether it takes some hundreds of microseconds or a few milliseconds, the for-loop is enough of a delay that at least one more conversion and interrupt will occur before `sample_buffer_full` gets cleared. One unhandled conversion is enough to lock up the interrupt handler. Here are some alternative approaches to consider:

• Use a circular buffer, and never stop filling it. This is ok if you are only interested in the most recent data, rather than a complete waveform record.

• Set or reset `sample_buffer_full` as now; and remove the initial if test from the handler. Instead, put an `if` before `sample_buffer_idx++;`, to not increment if the buffer is full.

• Turn off ADC's freerun mode. This is a reasonable thing to do when not taking data.

• Turn off ADC's interrupt when not taking data. Also reasonable.

• Use multiple buffers. Reasonable, but by itself doesn't avoid the problem.

• Read the latest value every time the handler executes \[for example, say `int datum = adc_get_latest_value(ADC);` as the first statement in the handler\] and then only store that value in certain cases. An easy and effective way to avoid problem.

---
Tags: arduino-due, interrupt, adc, analog-sampling
---


# Question
Title: Transistor slows motor instead of turning it off
I'm new to electrical engineering and I am currently trying to make a motor turn on for one second, turn off for one second, and repeat.

I'm using an Arduino Uno's `digitalWrite()` feature to activate a transistor, allowing the external 9V battery to turn on the motor.

Although everything is responding, instead of the motor turning on and off like I want it to, it spins fast for a second, then spins slower for a second. I would like the motor to stop completely, but cannot figure out how to do that.

Here's the schematic of my circuit:

simulate this circuit – Schematic created using CircuitLab

**Code:**

```
void setup(){
  pinMode(9, OUTPUT);
}

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

```

Why isn't the motor completely turning off?

# Answer
I can't make much sense of your diagram- but this is the correct way to do it:

simulate this circuit – Schematic created using CircuitLab

R1 is low enough that the base gets 10-15mA of drive, sufficient for a few hundred mA of motor current. D1 protects the transistor Q1 when it turns off (from the motor inductance). The emitter of the NPN transistor should be grounded and then the collector will either be near ground or at the 9V level depending on whether it is off or on.

You may have damaged the transistor you are using (due to breaking it down in reverse across the E-B junction) so I would suggest proceeding with a new one. You didn't mention it, but it probably got quite warm.
> 6 votes

# Answer
There are multiple things wrong with your drawn schematic:

* The ground symbol is not wrong but really misleading.
* You forgot to add a flyback diode.
* You wired the load the wrong way: the load is placed between the collector and VCC, not between emitter and GND.
* The base resistor is way too high.
> 3 votes

---
Tags: motor
---


title: c expected ; before ) token

text:
# Question
Title: c expected ; before ) token
```
void GravaFicheiros(CONFERENCIA *co)
{

    int i, ii, iii;

    FILE *fp;

    fp = fopen("grabameisso", "wt");

    fprintf (fp, "%s\n", co->nomeconf);

    int k = NSessoes(co);
    fprintf (fp, "%d\n", k);

    for (i = 0; i < k; i++)
    {

        fprintf (fp, "%s\n%d\n%d\n", co->sessoes[i].tema, co->sessoes[i].hora, co->sessoes[i].auditorio);

        int a = NArtigos(co, i);

        fprintf (fp, "%d\n", a);

        for (ii = 0; ii < a; ii++)
        {

            fprintf (fp, "%s\n", co->sessoes[i].artigos[ii].titulo);

            int aa = NAutores(co, i, ii);

            fprintf (fp, "%d\n", aa);

            for (iii = 0; iii < aa, iii++)
            {

                fprintf (fp, "%s\n%d\n", co->sessoes[i].artigos[ii].autores[iii].nome, co->sessoes[i].artigos[ii].autores[iii].idade);
            }
        }
    }

    fclose(fp);
    return;

```

# Answer
> 3 votes
Although you didn't ask a specific question I assume you want to know why there was an error in your code.

One of your for loops is missing a semi-colon.

> ```
> for (iii = 0; iii < aa, iii++) //this line gives the error
>
> ```

Should be:

```
 for (iii = 0; iii < aa; iii++) //the comma should be a semi-colon

```

When it says ; expected before token ). It means quite literally that there is a ; missing before a ).

---
Tags: c++, c
---


# Question
Title: How to add the Wiring S board to Arduino IDE v.1.6.2?
My Arduino Uno is running out of memory to support my script (yes, I've tried several ways of optimize it already: PROGMEM, EEPROM, no Strings, and so on), so I would like to upload my script to my Wiring S board.

However, instead of "porting" all libraries to Wiring, I would like to compile my script in Arduino IDE and upload it to my Wiring S. It used to be "easy" in Arduino v.1.0.x. because somwhere I got a Wiring folder (containing, among other things, a boards.txt file) and copied it to Arduino's `hardware` folder getting the Wiring S board listed in Arduino IDE.

Since Arduino 1.5 the specification for adding other boards changed. I'd say it's more complex now. I simply cannot understand most of the new specification (yes, I'm new into electronics), so I haven't been able to add my Wiring S board.

Running my script in Arduino 1.0.x doesn't seem to be an option, since it throws lots of errors (although the script compiles in Arduino 1.6.2).

Do you have any experience adding other boards (like Wiring S) to Arduino IDE? Could you please give me some hint?

# Answer
> 1 votes
There are two things I do; I use the Serial.print(F("string/n")); which prints the data from flash rather then copying it to ram. Keep as many of your variables local as possible, that will save ram. This is done by defining then in the function, the added advantage nothing outside the function can change them.

Global and Static variables are the first things loaded into SRAM. They push the start of the heap upward toward the stack and they will occupy this space for all eternity.

Variables created in functions, are dynamically allocated objects and data. Unlike Global and Static variables, these variables can be de-allocated to free up space at function exit. But Every function call creates a stack frame that makes the stack grow toward the heap. This data is usable within the function, but the space is 100% reclaimed when the function exits!

---
Tags: arduino-uno, sketch, sketch-size
---


# Question
Title: How to change SIM908 GPS location coordinates format?
I am using the SIM908 module to get GPS position.

The SIM908 sends the latitude and longitude in the `ddmm.mmmm` format, but major online services for GPS location (for example, Google Earth) use the `dd.dddd` format.

So, how can I modify my code to convert coordinates from the SIM908 to `dd.dddd` format?

This is the SIM908 GSM Library Code that I am using:

```
#include "gps.h"
char GPSGSM::getBattInf(char *str_perc, char *str_vol)
{
     char ret_val=0;
     char *p_char;
     char *p_char1;

     gsm.SimpleWriteln("AT+CBC");
     gsm.WaitResp(5000, 100, "OK");
     if(gsm.IsStringReceived("+CBC"))
          ret_val=1;

     //BCL
     p_char = strchr((char *)(gsm.comm_buf),',');
     p_char1 = p_char+1;  //we are on the first char of BCS
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_perc, (char *)(p_char1));

     //Voltage
     p_char++;
     p_char1 = strchr((char *)(p_char), '\r');
     if (p_char1 != NULL) {
          *p_char1 = 0;
     }
     strcpy(str_vol, (char *)(p_char));
     return ret_val;
}

char GPSGSM::getBattTVol(char *str_vol)
{
     char *p_char;
     char *p_char1;
     char ret_val=0;

     gsm.SimpleWriteln("AT+CBTE?");
     gsm.WaitResp(5000, 100, "OK");
     if(gsm.IsStringReceived("+CBTE"))
          ret_val=1;

     //BCL
     p_char = strchr((char *)(gsm.comm_buf),':');
     p_char1 = p_char+2;  //we are on the first char of BCS
     p_char = strchr((char *)(p_char1), '\r');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_vol, (char *)(p_char1));
     return ret_val;
}

char GPSGSM::attachGPS()
{
     if(AT_RESP_ERR_DIF_RESP == gsm.SendATCmdWaitResp("AT+CGPSPWR=1", 500, 100, "OK", 5))
          return 0;
     if(AT_RESP_ERR_DIF_RESP == gsm.SendATCmdWaitResp("AT+CGPSRST=1", 500, 100, "OK", 5))
          return 0;
     return 1;
}

char GPSGSM::deattachGPS()
{
     if(AT_RESP_ERR_DIF_RESP == gsm.SendATCmdWaitResp("AT+CGPSPWR=0", 500, 100, "OK", 5))
          return 0;
     return 1;
}

char GPSGSM::getStat()
{
     char ret_val=-1;
     gsm.SimpleWriteln("AT+CGPSSTATUS?");
     gsm.WaitResp(5000, 100, "OK");
     if(gsm.IsStringReceived("Unknown")||gsm.IsStringReceived("unknown"))
          ret_val=0;
     else if(gsm.IsStringReceived("Not"))
          ret_val=1;
     else if(gsm.IsStringReceived("2D")||gsm.IsStringReceived("2d"))
          ret_val=2;
     else if(gsm.IsStringReceived("3D")||gsm.IsStringReceived("3d"))
          ret_val=3;
     return ret_val;
}

char GPSGSM::getPar(char *str_long, char *str_lat, char *str_alt, char *str_time, char *str_speed )
{
     char ret_val=0;
     char *p_char;
     char *p_char1;
     gsm.SimpleWriteln("AT+CGPSINF=0");
     gsm.WaitResp(5000, 100, "OK");
     if(gsm.IsStringReceived("OK"))
          ret_val=1;

     //longitude
     p_char = strchr((char *)(gsm.comm_buf),',');
     p_char1 = p_char+1;  //we are on the first char of longitude
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_long, (char *)(p_char1));

     // latitude
     p_char++;
     p_char1 = strchr((char *)(p_char), ',');
     if (p_char1 != NULL) {
          *p_char1 = 0;
     }
     strcpy(str_lat, (char *)(p_char));

     // altitude
     p_char1++;
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_alt, (char *)(p_char1));

     // UTC time
     p_char++;
     p_char1 = strchr((char *)(p_char), ',');
     if (p_char1 != NULL) {
          *p_char1 = 0;
     }
     strcpy(str_time, (char *)(p_char));

     // TTFF
     p_char1++;
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }

     // num
     p_char++;
     p_char1 = strchr((char *)(p_char), ',');
     if (p_char1 != NULL) {
          *p_char1 = 0;
     }

     // speed
     p_char1++;
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_speed, (char *)(p_char1));

     return ret_val;
}

void parseTime(char *field, int *time)
{
     ////////////////Time////////////
     char tmp[4];
     tmp[2]=0; // Init tmp and null terminate
     tmp[0] = field[8];
     tmp[1] = field[9];
     time[0] = atoi(tmp); // Hours
     tmp[0] = field[10];
     tmp[1] = field[11];
     time[1] = atoi(tmp); // Minutes
     tmp[0] = field[12];
     tmp[1] = field[13];
     time[2] = atoi(tmp); // Seconds
     /////////////Date///////////////
     tmp[0] = field[0];
     tmp[1] = field[1];
     tmp[2] = field[2];
     tmp[3] = field[3];
     tmp[4]=0; // Init tmp and null terminate
     time[3] = atoi(tmp); // year
     tmp[0] = field[4];
     tmp[1] = field[5];
     tmp[2]=0; // Init tmp and null terminate
     time[4] = atoi(tmp); // month
     tmp[0] = field[6];
     tmp[1] = field[7];
     tmp[2]=0; // Init tmp and null terminate
     time[5] = atoi(tmp); // day
}

// Read the latitude in decimal format from a GGA string
double convertLat(char* latString)
{
     double latitude = atof(latString);                                    // convert to a double (precise)
     int deg = (int) latitude / 100;                               // extract the number of degrees
     double min = latitude - (100 * deg);                  // work out the number of minutes
     latitude = deg + (double) min/60.0;                   // convert to decimal format
     return latitude;
}

// Read the longitude in decimal format from a GGA string
double convertLong(char* longString)
{
     double longitude = atof(longString);                                  // convert to a double
     int deg = (int) longitude / 100;                              // extract the number of degrees
     double min = longitude - (100 * deg);                 // work out the number of minutes
     longitude = deg + (double) min/60.00;                 // convert to decimal format
     return longitude;
}

```

# Answer
This could be a general programming question. The only thing specific to Arduino here is that you may want a solution that minimizes the use of memory and avoids floating point operations.

Here is a memory-friendly solution that reformats the string *in place*, i.e. it overwrites the original string. In many cases this is appropriate, as it is unlikely that you need the original string later, but you have to make sure it fits your application. It works by first moving a few characters around in order to have the format "dd.mmmmm", then parsing the minutes and converting to fractional degrees, then writing that in ASCII.

It should be noted that the only reason for dropping the last digit in the minutes field is to avoid 32-bit operations. I compiled for an Uno and checked the generated assembly: it uses only four bytes of RAM, in the stack.

```
// Convert the format of a latitude from "ddmm.mmmm" to "dd.dddd".
// The string is converted in place.
void convertLat(char* s)
{
    // Convert ddmm.mmmm to dd.mmmmm
    s[4] = s[3];  // move minutes
    s[3] = s[2];  // move tens of minutes
    s[2] = '.';   // put decimal point
    s[8] = '\0';  // drop last digit

    // Compute fractional degrees.
    uint16_t fraction = atoi(s + 3);  // unit = 1e-3 arcmin
    fraction /= 6;                    // unit = 1e-4 deg

    // Write in ASCII, right to left.
    s[7] = '\0';
    for (int i = 6; i > 2; i--) {
        s[i] = fraction % 10 + '0';
        fraction /= 10;
    }
}

```

You can use this same function to convert a longitude from "dddmm.mmmm" to "ddd.dddd" by just skipping the first character:

```
static inline void convertLon(char* s)
{
    convertLat(s + 1);
}

```

---

**Addendum**: To answer Lipsyor comment, it is possible to have the latitude in units of 1e-6 deg by using 32-bit arithmetic:

```
// Convert the format of a latitude from "ddmm.mmmm" to "dd.dddddd".
// The string is converted in place.
void convertLat(char* s)
{
    // Convert ddmm.mmmm to dd.mmmmmm
    s[4] = s[3];  // move minutes
    s[3] = s[2];  // move tens of minutes
    s[2] = '.';   // put decimal point

    // Compute fractional degrees.
    uint32_t fraction = atol(s + 3);     // unit = 1e-4 arcmin
    fraction = (fraction * 10 + 3) / 6;  // unit = 1e-6 deg

    // Write in ASCII, right to left.
    for (int i = 8; i > 2; i--) {
        s[i] = fraction % 10 + '0';
        fraction /= 10;
    }
}

```

The `+ 3` in the computation is only to round to nearest. Dropping this term should not make any significant difference.
> 2 votes

---
Tags: arduino-uno, gps, tinygps
---


title: ESP8266 is not responding

text:
# Question
Title: ESP8266 is not responding
I have ESP8266, FTD232 UART, Linux mint 17.3 OS, Arduino IDE 1.6.7,

Following are the connections:

```
External Power source  ESP8266
  3.3 V                  VCC
  GND                    GND
  3.3 V                  CHPD
  3.3 V                  GPIO0

FTD232 UART  ESP8266
    RX         TX
    TX         RX

```

Plus FTD232 GND and Power Source GND are connected to make sure that there is a common reference.

I open the Arduino IDE and select Generic ESP 8266 board.

Open Serial Monitor:

AT command, no response..?

I have tried lots of different things found from web, even a new ESP8266, but no response.

Can anybody provide help...?

# Answer
The ESP8266-01 will boot and show some boot up messages at baud rate 76800 before switching to the default configured baud rate of 9600 or 115200.

Try setting the baud rate to 76800 and reset the ESP8266 to see if you can see the boot up messages first to determine if your circuit is working. You might see something like this:

> ets Jan 8 2013,rst cause:4, boot mode:(3,7)
> 1 votes

# Answer
1.What firmware ? AT commands do not work in nodeMcu firmware. Usually the AT firmware work to 115200 bps.

2.If your FTD232 works at 5V, you will need resistor between Arduino TX and ESP RX. ESP8266 only works at 3.3V.

3.Try esplorer - is a very nice tool to test ESP8266: http://esp8266.ru/esplorer/
> 1 votes

---
Tags: esp8266
---


title: SoftwareSerial library

text:
# Question
Title: SoftwareSerial library
How do I rectify this error? Clearly it says there is some error in the library, so how do I correct it?

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:1: error: expected unqualified-id before 'if'

# Answer
As you haven't shown the code that produces the error when it's compiled, I can't say for sure what the problem is. However, here are links to three instances of the same error:

*error: expected unqualified-id before 'if'* on stackoverflow

*Arduino: error: expected unqualified-id before 'if' (using ping sensor)*, also on stackoverflow

*error: expected unqualified-id before 'if'* on arduino.cc.

In each case, the problem was due to executable code (as opposed to declarations) appearing outside of a function. You may have put some executable statements outside of `loop()` or `setup()`, etc.
> 1 votes

# Answer
Your copy of the SoftwareSerial library has become corrupted. Why is anyone's guess: maybe your hard drive is dying?

Replacing the file with a good copy will solve the problem. The simplest way to do that is to reinstall the IDE.
> 0 votes

---
Tags: softwareserial
---


title: Trouble with large numbers

text:
# Question
Title: Trouble with large numbers
Probably something stupid, but I can't figure out how to work with these large numbers, then cast the result (which will be small) to an integer. I keep getting negative numbers, which I think means I'm overflowing somewhere.

```
int freq = 440;
int len = 256;
long timer = 2000000.0 / (freq * len);
int roundedTimer = int(timer);

```

I should get 18, but I'm getting -108...

# Answer
`freq * long`, since they are both integers, are calculated as integers.

`440*256=112640` \- in binary that is `1 1011 1000 0000 0000` and trimmed to 16 bits becomes `1011 1000 0000 0000` which is `-18432` and that is where the heart of your problem is. Unless you explicitly say otherwise the Arduino's compiler does all calculations (except floating point) as 16-bit signed integers.

By casting the values to `long` it forces the compiler to 'overflow' the 16-bit limit and use a 32-bit limit instead:

```
long timer = 2000000 / ((long)freq * (long)len);

```

Another alternative is to define `freq` and `len` to be `long` from the outset instead of `int`.
> 3 votes

---
Tags: data-type, mathematics
---


title: Calculate OCR2A from audio frequency

text:
# Question
Title: Calculate OCR2A from audio frequency
I'm working on a Arduino-based synthesizer using this tutorial, specifically using a wavetable and 1-bit DAC. I understand that the value for OCR2A register sets the frequency, but how do I calculate the value?

I've seen this list of notes which is great, but I want arbitrary frequencies in Hz...

Here's the code I'm working from:

```
#include <avr/interrupt.h>

// sinewave parameters
#define FREQ 18
#define PI2 6.283185    // 2*PI saves calculation later
#define AMP 127         // scaling factor for sine wave
#define OFFSET 128      // offset shifts wave to all >0 values

#define LENGTH 256      // length of the wave lookup table
byte wave[LENGTH];      // wavetable

void setup() {

  // populate wavetable
  for (int i = 0; i < LENGTH; i++) {
    float v = (AMP * sin((PI2 / LENGTH) * i));
    wave[i] = int(v + OFFSET);
  }

  // set timer1 for 8-bit fast PWM output
  pinMode(9, OUTPUT);       // make timer’s PWM pin an output
  TCCR1B = (1 << CS10);     // set prescaler to full 16MHz
  TCCR1A |= (1 << COM1A1);  // pin low when TCNT1=OCR1A
  TCCR1A |= (1 << WGM10);   // use 8-bit fast PWM mode
  TCCR1B |= (1 << WGM12);

  // set up timer2 to call ISR
  TCCR2A = 0;             // no options in control register A
  TCCR2B = (1 << CS21);   // set prescaler to divide by 8
  TIMSK2 = (1 << OCIE2A); // call ISR when TCNT2 = OCRA2
  OCR2A = FREQ;           // set frequency of generated wave
  sei();                  // enable interrupts to generate waveform!
}

void loop() {
  // nothing to do here!
}

// called every time TCNT2 = OCR2A
ISR (TIMER2_COMPA_vect) {   // called when TCNT2 == OCR2A
  static byte index = 0;    // points to each table entry
  OCR1AL = wave[index++];   // update the PWM output
  asm("NOP; NOP");          // fine tuning
  TCNT2 = 6;                // timing to compensate for ISR run time
}

```

# Answer
> 4 votes
The equation to calculate it is given in the first article you linked:

The 2MHz value comes from the factor of 8 prescale on the 16MHz clock and 256 is the size of the lookup table specified by your `LENGTH` define. If you start from a frequency you want to synthesize, just use the above equation to solve for the necessary value of OCR2A. Note that since you have to input integer values to OCR2A, you can't really achieve *arbitrary* frequencies, but you're certainly not locked in to the values given in the supplemental musical note PDF you reference.

So, to solve for OCR2A:

```
OCR2A = TCNT2_rate / (desiredFreq * wavetableLength);

```

---
Tags: audio
---


# Question
Title: Arduino declaring class in h and cpp file Undefined Reference
I am trying to compile my project, but unfortunately get errors.

I created class and separated implementation and declaration (cpp file and h file)

Here they are

**sensor.h**

```
#ifndef SENSOR_H
#define SENSOR_H
#include <stdint.h>
#include "Arduino.h"
// Sensor types
enum SensorType {
  ANY_SENSOR,
  UNKNOWN_SENSOR,
  WATER_SENSOR,
  TEMPERATURE_SENSOR,
  VIBRATION_SENSOR,
  INTERCOM_SENSOR,
  HUMIDITY_SENSOR,
  PIR_SENSOR,
  SOUND_SENSOR,
  LIGHT_SENSOR
};
class Sensor {
  public:
  // Variables declaration
    uint32_t sensorId;
    SensorType sensorType;
    float currentValue;
    bool isEnabled;
    float criticalLowerLevel;
    float criticalUpperLevel;
   // Methods declaration
    Sensor();
    Sensor(uint32_t id,SensorType type,long currentValue,bool isEnabled,long lower,long upper);
    String toString();
    bool isCriticalLevelRised() {
      return (this->currentValue >= this->criticalUpperLevel || this->currentValue <= this->criticalLowerLevel);
    };
    void enable(bool enable);
    void toggle();
    static String convertSensorTypeToString(SensorType sensorType);
};

#endif

```

And cpp file

```
#include "sensor.h"
Sensor::Sensor()
{
  this->sensorId = 0;
  this->sensorType = UNKNOWN_SENSOR;
  this->currentValue = 0;
  this->isEnabled = false;
  this->criticalLowerLevel = 0;
  this->criticalUpperLevel = 0;
}
Sensor::Sensor(uint32_t id,SensorType type,long currentValue,bool isEnabled,long lower,long upper) {
  this->sensorId = id;
  this->sensorType = type;
  this->currentValue = currentValue;
  this->isEnabled = isEnabled;
  this->criticalLowerLevel = lower;
  this->criticalUpperLevel = upper;
}
void Sensor::enable(bool enable) {
   this->isEnabled = enable;
}
void Sensor::toggle() {
  this->enable(!this->isEnabled);
}
String Sensor::toString()
{
  String response = "";
  response += F("Sensor id is ");
  response += this->sensorId;
  response += '\n';
  response += F("Sensor type is ");
  response += convertSensorTypeToString(this->sensorType);
  response += '\n';
  response += F("Sensor current value is ");
  response += this->currentValue;
  response += '\n';
  response += F("Sensor isEnabled is ");
  response += this->isEnabled;
  response += '\n';
  response += F("Sensor criticalLowerLevel is ");
  response += this->criticalLowerLevel;
  response += '\n';
  response += F("Sensor criticalLowerLevel is ");
  response += this->criticalUpperLevel;
  response += '\n';
  return response;
}
String Sensor::convertSensorTypeToString(SensorType sensorType) {
  switch (sensorType) {
    case UNKNOWN_SENSOR:
      return F("UNKNOWN SENSOR");
    case ANY_SENSOR:
      return F("ANY_SENSOR");
    case WATER_SENSOR:
      return F("WATER_SENSOR");
    case TEMPERATURE_SENSOR:
      return F("TEMPERATURE_SENSOR");
    case VIBRATION_SENSOR:
      return F("VIBRATION_SENSOR");
    case HUMIDITY_SENSOR:
      return F("HUMIDITY_SENSOR");
    case PIR_SENSOR:
      return F("PIR_SENSOR");
    case SOUND_SENSOR:
      return F("SOUND_SENSOR");
    case LIGHT_SENSOR:
      return F("LIGHT_SENSOR");
    default:
      return F("UNKNOWN TYPE");
  }
}

```

And I got following errors

```
ketch/NodeIntercom.ino.cpp.o: In function `sendSensorMessageToMaster(RF24Mesh*, SensorDataMessage*, char, unsigned int, bool)':
/home/iron/Arduino/What'sHappening/NetworkMaster/additional_functions.h:48: undefined reference to `Sensor::toString()'
sketch/NodeIntercom.ino.cpp.o: In function `handleSetSensorDataRequest(RF24NetworkHeader*)':
/home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:97: undefined reference to `Sensor::toggle()'
/home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:89: undefined reference to `Sensor::enable(bool)'
sketch/NodeIntercom.ino.cpp.o: In function `SensorDataMessage':
/home/iron/Arduino/What'sHappening/NetworkMaster/common.h:40: undefined reference to `Sensor::Sensor()'
sketch/NodeIntercom.ino.cpp.o: In function `__static_initialization_and_destruction_0':
/home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:35: undefined reference to `Sensor::Sensor(unsigned long, SensorType, long, bool, long, long)'
collect2: error: ld returned 1 exit status

```

What I am doing wrong ? Please help.

**EDIT**

Yes main sketch compiles perfectly where this files are located.

But I don't want to duplicate common files in my all my arduino sketches withing the project, they are the same for whole project. Here my files location

```
--ArduinoProjects
---NodeIntercom
----NodeIntercom.ino
---MasterNode
----MasterNode.ino
----sensor.h
----sensor.cpp
----common.h

```

So this files are only located in MasterNode directory

And I tried to include them like this

```
#include "/home/iron/Arduino/What'sHappening/NetworkMaster/common.h"
#include "/home/iron/Arduino/What'sHappening/NetworkMaster/additional_functions.h"

```

And in common.h I include sensor.h Also tried to include directly, but still the same

But headers files included as above works perfectly.

What is the right way to solve this problem, I don't want to duplicate this class in each folder whenever I change it.

If there is no way, maybe create symbolic link (I am using linux) ?

**PARTIAL SOLUTION**

Just use symbolic links in the sketch directory and this works perfectly

# Answer
The Arduino build preprocessing cannot locate the sensor source and header files if they are located in another sketch directory. The files needs to be moved to separate directory if shared (as a library).

```
--Sketchbook
---NodeIntercom
----NodeIntercom.ino
---MasterNode
----MasterNode.ino
---libraries
----Sensor
-----Sensor.h
-----Sensor.cpp

```

The Sensor header is included with

```
#include <Sensor.h>

```

in the sketches that needs to use it.
> 3 votes

# Answer
There is nothing wrong with that class and its code (as far as I can tell) - it compiles perfectly fine.

What is probably wrong is that the IDE isn't picking up the code and compiling it in to your project.

Is this class part of the sketch, or is it a separate library that you are writing? If the latter you have to ensure that the IDE knows about it, and it can only look for it when you load the IDE, so if you haven't restarted the IDE since creating the library you must do that so it can find the new library.
> 2 votes

---
Tags: arduino-uno, c++, arduino-ide, class, ino
---


# Question
Title: Problem with a digital potentiometer application
I am a beginner when it comes to electronics, coding and things like that (this is practically the first time I have done anything like this), so when building an application that is supposed to vibrate a vibration motor with a strength based on the distance measurement made by the ultrasonic rangefinder, I bumped up with a problem.

The MCP 41010 digital potentiometer seems to let electricity through only when it is given a SPI.transfer(128). Any other number stops the flow of electricity completely.

I have tried some addresses such as 00, 0x00, 0x01 and 0x04 to replace the 0 and the result was the same. With addresses 0x11 and 0x08 the digital potentiometer didn't react at all.

In addition to the code I have here I have tried just copy-pasting some of the tutorials I found from the internet, for example this one Digital Potentiometer not fading LED without really understanding the commands formats thing all that well. With that code I got a vibration that didn't seem to fade in or fade out at all, so the problem remains (I lack a way to properly test that though).

So... what am I doing wrong and how to fix it?

Thank you!

Many tutorials were used when making the code.

```
#include <SPI.h>

int vcc = 2; // attach pin 2 to vcc
int trig = 3; // attach pin 3 to Trig
int echo = 4; // attach pin 4 to Echo
int gnd = 5; // attach pin 5 to GND

int shortest = 250;
int longest = 12000;

int CS = 10; // for digi pot

void setup() {

  SPI.begin ();
  pinMode (vcc,OUTPUT);
  pinMode (gnd,OUTPUT);
  pinMode (CS, OUTPUT); // for digi pot
  // initialize serial communication:
  Serial.begin(9600);

}

void loop()
{
  digitalWrite(vcc, HIGH);
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(trig, OUTPUT);
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(5);
  digitalWrite(trig, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echo,INPUT);
  duration = pulseIn(echo, HIGH);

  if (duration > 200 && duration < 220)
  // Limiting out an unwanted, randomly appearing distance measurement
  // made useless by later code though
    {
     Serial.print("Error ");
     Serial.print(duration);
     Serial.print("\n");

     return;
    }

   // Compressing the result of the distance measurement into the scale of 0 - 128
  if (duration < shortest) duration = shortest;
  if (duration > longest) duration = longest;
  duration = (1.0f-((float)(duration - shortest) / (float)(longest - shortest))) * 128;

  digitalWrite(CS, LOW);
  SPI.transfer(0); // 0x01 and 0x04 seem to "work" too. With 0x11 and 0x08 no voltage goes through
  SPI.transfer(duration); // sending a number from 0 to 128 to the digital potentiometer
  digitalWrite(CS, HIGH);

  Serial.print(duration); // printing the result of the measurement and calculations
  Serial.print("\n");

  delay(100);
}

```

# Answer
> 3 votes
Digital potentiometers are not a good choice for controlling the speed of a motor. They are designed only for very low current applications - things like setting offset points for op-amps and things like that - things where you would use a small trimmer pot rather than a large power *rheostat*.

Instead you should be controlling the motor using PWM and a transistor (here is a good tutorial).

But to help you understand the digital potentiometer and so you can work with it better:

Step one is always to read the datasheet. That details the SPI communication protocol for you so you can know what numbers mean what.

In this case the protocol is made up of two bytes - a command byte and a data byte.

The command byte is made up like this:

As you can see it's in two parts - a command and a potentiometer selector. So to set the resistance of potentiometer 0 you would need to craft a command byte that had the write command and the code for potentiometer 0. That would be `0b00010001` or 0x11 in hex. So your transaction would look like:

```
digitalWrite(CS, LOW);
SPI.transfer(0x11);
SPI.transfer(duration);
digitalWrite(CS, HIGH);

```

Another important part of the datasheet is the electrical characteristics. That is a table that tells you the minimum, typical and/or maximum values for different parameters. One important one here is the *wiper current* which it states as being allowed between -1mA and +1mA. That is the maximum current you are allowed to draw through the digital potentiometer before you risk damaging it. That is why it's not good for powering things like motors, no matter how small.

---
Tags: potentiometer
---


title: Analog Pins are sensing Values

text:
# Question
Title: Analog Pins are sensing Values
I used the example code AnalogReadSerial and tried it on all analog pins from A0 to A7. None of the analog pins were connected to anything so I expectedy to get 0 in the serial monitor. But as it turns out, I was wrong. Only pin A7 shows 0 to 19 values on the serial monitor. The rest have values ranging from 100 to 300 for pins A2, A3, A4, A5 and A6. The worst performers are A1 and A0 with values from 921 to 1023 showing on the serial monitor. What is the cause of this and how will I fix it?

# Answer
The ADC is multiplexed across the pins, and will carry a small charge from pin to pin. If you want them to be zero, tie them to ground.

This answer, https://arduino.stackexchange.com/a/575/6628 , suggests pulling them to ground for higher accuracy.
> 1 votes

# Answer
This is normal, as the unconnected pin may float from GND to VCC. You may enable internal pull-up (to VCC). This is normal for all high-z inputs. If you read digital port you'll see that it floats too. Sometimes you can change digital I/O input value just by waving your hand above the board.

For that reason we always tie high-z inputs to something. You can leave it floating - it won't damage anything, but the value obtained from free-floating input is useless.
> 3 votes

---
Tags: analogread
---


title: PID tuning help

text:
# Question
Title: PID tuning help
I'm currently working on a self-balancing robot with an Arduino Uno and a 10DOF ADXL345 sensor. Everything is going fine until I got to this PID tuning part. I've read about it several times but I'm unable to get the desired results. Can somebody give a detailed guide on PID tuning? Thank you.

# Answer
Maybe you can help yourself with this tutorial for PID line follower robot. I successfully tuned my PID for line following and had some success with PID for wall following with sonar.
> 1 votes

# Answer
In real life there is no set equation to find the PID values. At best you'll get close with equations and then need to tune the parameters.

For anyone into PID loops have a read of this. I've found it to be excellent.

My advice is to:

* only use P
* set I & D to 0
* get it and good as you can by trial and error
* add I and trial it too

D is for experts really and may cause weird/undesirable jitter.
> 1 votes

---
Tags: robotics
---


# Question
Title: Arduino Nano, ICSP header and 595 Shift register
I'm trying to control a 4-digit 7 segment display with an Arduino Nano, but I'm getting something wrong. I'm using the ICSP header to interface with a 74HC595 Shift Register which is then connected to the display. I've tested and retested the connections and everything seems to be alright, however the shift register doesn't have the desired output, and I notice it only shifs one single bit when I press the reset button on the arduino board.

```
74HC595   |    A. Nano
DS     <-----> MOSI (ICSP)
SH_CP  <-----> SCK (ICSP)
ST_CP  <-----> D6
MR     <-----> 5V (ICSP)
OE     <-----> GND (ICSP)
VDD    <-----> 5V (ICSP)
GND    <-----> GND (ICSP)

```

My code:

```
//pin connected to STCP
const int latchPin = 6;
//pin connected to SHCP
const int clockPin = 17;
//pin connected to DS (MOSI)
const int dataPin = 11;

byte val=0;

void setup() {
  // put your setup code here, to run once:
  //SPI pins are output
  pinMode(latchPin,OUTPUT);
  pinMode(clockPin,OUTPUT);
  pinMode(dataPin,OUTPUT);

  pinMode(3,OUTPUT);
  updateRegister(0);

}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(3,HIGH);
  for (int i=0; i<8; i++) {
    updateRegister();
    delay(500);
  }

}

void updateRegister() {
  //pull latch low to write new bits to the register
  digitalWrite(latchPin,LOW);
  //shift out the data
  shiftOut(dataPin,clockPin,LSBFIRST,val);
  //pull latch pin high so that the leds light up
  digitalWrite(latchPin,HIGH);
}

```

# Answer
> 1 votes
`const int clockPin = 17;`

I'm pretty sure that should be 13, not 17.

# Answer
> 3 votes
It is extremely confusing to have a variable `val` and then use `_val` in your function but then:

```
  shiftOut(dataPin,clockPin,LSBFIRST,val);

```

As James pointed out, you are not sending the value passed to the function, to the shift register.

Also this is just going to give you a boolean:

```
 updateRegister(!i);

```

Why take "not i" there?

---

I suggest you use SPI and not muck around with shiftOut. I have a page about the 595 chip including example code. eg.

```
#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

byte c;
void loop ()
{
  c++;
  digitalWrite (LATCH, LOW);
  SPI.transfer (c);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop

```

# Answer
> 1 votes
Do you need to add the _ to the shiftOut(dataPin,clockPin,LSBFIRST,val); ?

---
Tags: c++, arduino-nano, spi, shift-register, icsp
---


# Question
Title: Problem with connecting ESP8266 to arduino
I have:

Problem: I see SoftAP and can connect to it. But I can't send AT-commands to ESP8266 from Arduino. I use Arduino app v.1.6.5 for send command to ESP8266 via Arduino. But I don't get answer. And ESP8266 doesn't blinking.

I use this scheme:

Please, help me. I'm trying to fix this is very time consuming.

# Answer
I had the same problem. I used `SoftwareSerial` library, so you should set baud rate as 115200 for communication with esp8266. It might look like this:

```
#include <SoftwareSerial.h>

SoftwareSerial esp8266(2,3);

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

```

It helped in my case.
> 1 votes

# Answer
I had the same problem. I solved it doing the following:

Connect Arduino TX to a voltage divider (to get 3,3V) and then to TX on ESP8266 Connect Arduino RX to RX on ESP8266

It should work!.

Please read the information on this link http://rancidbacon.com/files/kiwicon8/ESP8266\_WiFi\_Module\_Quick\_Start\_Guide\_v\_1.0.4.pdf
> 0 votes

# Answer
You must need to add another power supply, which will give to the wifi module not just the correct voltage (3v) but the mA that it need. / other thing you may need to do is connect the ground of Arduino to Ground of the power supply. For me works good.

the connections would be like this

1. esp TX \> arduino dpin 10
2. esp RX \> arduino dpin 11
3. esp CH \> to VCC 3V
4. esp RST \> to pushbutton connected to gnd
5. esp GpIO 0 \> none
6. esp GpIO 2 \> none
7. esp VCC \> power supply 3v
8. esp GND \> power supply gnd
> 0 votes

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


title: Arduino can't multiply?

text:
# Question
Title: Arduino can't multiply?
I have a value I'm taking from a sensor module, which is 2500 when the sensor is facing a light source. This reads to my code and can be saved perfectly fine. When I try to find the weighted average of a set of values (2500\*1000+2500\*2000+2500\*3000 etc), the Arduino comes out with very weird answers. For example

2500\*1000=9632

If I just compute 2500\*1000 on its own, the answer still comes out the same! The results come out negative if I use int so I switched to using double (just in case the values created were too big), this stops producing negatives as expected but the result is still like it is above.. I have no idea why.. any ideas?

# Answer
2500 * 1000 = 9632 is exactly what you expect with 16-bit integers. You should use long integers instead:

```
2500L * 1000L == 2500000L

```

Floats work also, but are more expensive:

```
2500.0 * 1000.0 == 2500000.0

```

although I do not recommend testing for exact equality of floats (it works here because these numbers are exactly representable).
> 4 votes

---
Tags: arduino-uno, c
---


# Question
Title: Both red and blue led of ESP8266 stays on
I've connected ESP8266 to Arduino UNO. After a getting a huge trouble I successfully managed to run some AT commands. I have also tested AP mode.

Then I got some trouble with software serial communication with Arduino and decided to change baud-rate to 9600 (previously it was 115200).

I used `AT+IPR=9600` command to change it.

After that blue led of esp stays on and not taking AT commands any more, but output some gibberish to serial monitor with few ascii text like below:

```
ets Jan  8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x40100000, len 1396, room 16
tail 4
chksum 0x89
load 0x3ffe8000, len 776, room 4
tail 4
chksum 0xe8
load 0x3ffe8308, len 540, room 4
tail 8
chksum 0xc0
csum 0xc0

2nd boot version : 1.4(b1)
SPI Speed      : 40MHz
SPI Mode       : DIO
SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

```

Note: I know it consumes a lot power tried external 3.3V power supply and voltage divider for rx pin.

Any help would be appreciated.

# Answer
If you have too, you can find the firmware for the ESP8266 here and re-flash it.

There's some good info here about the instruction set.

With respect to your issue of the blue (traffic) light staying on, I can't imagine that the baud command would have caused an issue. Perhaps you need to double check your circuit and make sure that the Rx pin of the ESP8266 is not being held high.

What happens with only 3.3V and GND connected to the ESP8266?

Also the output you're getting is similar to the output from “AT+GMR”. Are you sending it that in a loop by chance?
> 4 votes

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


# Question
Title: What is the relation between Arduino's clock and possible VGA resolution?
I have seen it said over and over (in different places) that in order to achieve 640x480 resolution out to a DB15 VGA connection, the arduino would need to be clocked at 25Mhz or that at half resolution it would need to be clocked at 12.5Mhz.

What is the relation between resolution and internal clock? I would expect that so long we can feed the signal fast enough that would be enough.

# Answer
> 5 votes
I doubt if that would be fast enough. See my thread about connecting to a VGA monitor.

Borrowing from that page, so as to not make a link-only answer ...

---

For 640x480 pixels of active video you have something like this:

---

## Vertical Sync

Let's start with the vertical sync pulses. In fact, we'll show how all the timing data can be derived from three figures:

* The screen refresh rate (eg. 60 Hz)
* The screen resolution (eg. 640 x 480)

So what is the refresh rate? It's the rate at which the entire screen is redrawn. If you ever looked at Windows screen resolution you probably saw something like this:

That's the refresh rate: 60 Hz (60 times a second). This figure was probably originally chosen because it is the mains frequency in the USA, so that would minimize the artifact of mains hum bars appearing on the screen, in the days of CRT monitors.

The other figure of interest is the screen resolution.

In our case we are going for the minimum we can (640 x 480) and seeing where those figures lead us.

Starting with the refresh rate, a 60 Hz refresh rate will require a "vertical sync" pulse 60 times a second, or a period of 1/60 (16.66 ms).

---

## Generating vertical sync pulses

This code in my VGA output sketch generates the vertical sync pulses:

```
  // Timer 1 - vertical sync pulses
  pinMode (vSyncPin, OUTPUT);
  Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE);
  OCR1A = 259;  // 16666 / 64 uS = 260 (less one)
  OCR1B = 0;    // 64 / 64 uS = 1 (less one)

```

The clock period is 62.5 ns (1/16000000). By applying a prescaler of 1024 the timer counts up once every 64 µs. So to get a period of 1/60 of a second (16666 µs) we need to count up to 260 (16666 / 64 = 260). Since the timer counts are zero-relative we set OCR1A to count up to 259. This sets the frequency of Timer 1.

Then we need to set the pulse width by putting the correct value in OCR1B. We want a pulse width of two lines. One line is 1 / 60 / 525, namely 31.7 µs. So two lines would be 63.4 µs. This is close enough to exactly one timer count (64 µs). So OCR1B is set to zero (being zero-relative, making it zero gives a count of 1).

Timer 1 is configured to "clear B on compare" which effectively means that it toggles the output pin (D10 on the Uno) so it is high for the duty cycle width (64 µs) and low the rest of the time. If you wanted the opposite sync pulse polarity, change CLEAR\_B\_ON\_COMPARE to SET\_B\_ON\_COMPARE.

The timer is also set up to generate an interrupt, which is used to tell the code that we are starting another vertical cycle, by setting the line count to zero:

```
ISR (TIMER1_OVF_vect)
  {
  vLine = 0;
  messageLine = 0;
  backPorchLinesToGo = verticalBackPorchLines;
  } // end of TIMER1_OVF_vect

```

---

## Horizontal sync

Horizontal sync pulses tell the monitor when to start drawing each line.

To calculate the horizontal sync frequency we need to divide the overall frame rate (60 Hz) by the number of total lines (525 if you count the sync pulse itself, and the front and back porches).

In other words:

```
 (1/60) / 525 * 1e6 = 31.74 µs

```

We also need to know the sync pulse width. That is documented to be 96 pixels, so we need to know the width of one pixel. That would be the figure above, divided by 800 (being the total screen width including the sync pulse, and front and back porches).

Thus that is:

```
((1/60) / 525 * 1e9) / 800 = 39.68  ns
1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz

```

So our pixel width is 39.68 ns and the pixel clock is 25.2 mHz.

The horizontal sync pulse width is 96 pixels, so we want a pulse of:

```
96 * 39.68 ns = 3.8 µs

```

---

## Generating horizontal sync pulses

Now we are ready to set up the timer for the horizontal sync pulses:

```
  // Timer 2 - horizontal sync pulses
  pinMode (hSyncPin, OUTPUT);
  Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE);
  OCR2A = 63;   // 32 / 0.5 µs = 64 (less one)
  OCR2B = 7;    // 4 / 0.5 µs = 8 (less one)

```

The clock period is 62.5 ns (1/16000000). By applying a prescaler of 8 the timer counts up once every 0.5 µs. So to get a period of 32 µs we need to count up to 64 (32 / 0.5 = 64). Since the timer counts are zero-relative we set OCR2A to count up to 63. This sets the frequency of Timer 2.

Then we need to set the pulse width by putting the correct value in OCR2B. We want a pulse width of 96 pixels (3.8 µs). So OCR2B is set to 7 (being zero-relative, making it 7 gives a count of 8, which is 4 / 0.5).

Again, if you wanted the opposite sync pulse polarity, change CLEAR\_B\_ON\_COMPARE to SET\_B\_ON\_COMPARE.

The timer is also set up to generate an interrupt, which has the sole purpose of waking the processor up from sleep, so it can draw each line with exactly the same delay after the pulse. If it wasn't asleep, there would be a variation of two to three clock cycles (since an interrupt cannot occur during a single instruction) and this gives very bad-looking "jitter" on the screen.

```
ISR (TIMER2_OVF_vect)
  {
  } // end of TIMER2_OVF_vect

```

---

## Pixel data

Now things get tricky ...

Let's see how long we have to draw 640 pixels:

```
((1/60) / 525 * 1e9) / 800  * 640 = 25396.82 ns (25.39 µs)

```

It just can't be done on this processor. The clock period itself is only 62.5 ns, so there is no way we can output a pixel every 39.68 ns (that is: 25396.82 / 640 = 39.68).

The fastest way we can get bits "out the door" is using the SPI hardware. That can run at a maximum clock rate of twice the system clock, that is, one pixel every 125 ns. So we will have to settle for having the pixels 4 times as wide. A horizontal resolution therefore of 160 pixels. Since we will display 8-pixel characters, that gives us 20 characters per line.

---

## Summary

Even at 25 MHz processor speed (which exceeds its spec) you won't be able to clock out pixels fast enough for 640 pixel width (since the fastest SPI speed is half the processor clock speed).

---

> I would expect that so long we can feed the signal fast enough that would be enough.

That's the tricky bit. To output data you have to do more than merely send it. You have to read it from memory, so it would take a least a couple of clock cycles to do that.

---

## Example of working at that resolution

A screen shot of my sketch in action (160 characters wide - 640 pixels and 30 characters high - 480 pixels, which is 16 pixels each as they were "doubled" in height to make them look in proportion). The font data was 8x8 pixels, and thus they appear as 16x16 on the screen.

---

> So does that mean that there really isn't a direct relation between clock speed and resolution? Other than, the clock must be faster than this

To work even at that speed the processor speed needs to be a multiple of the VGA clock, or close enough for the monitor to accept. (Looking at my figures the pixel rate is not in fact a multiple of 39.68 ns, so I am guessing that my monitor was able to adjust).

You could get better results by having a system clock which was an exact multiple of 39.68 ns (around 25 MHz - precisely 25.201613 MHz) - which is what you suggested in the question. However that just gives more accurate timing, you would still get similar resolution to what I show here.

So yes, to work on more monitors you should have a direct relation between clock speed and resolution.

I seem to have a 25.175 MHz crystal in my parts drawer, so perhaps I experimented with this a while back. Of course, you have to recalculate the other timings if you use that, and the processor is running out of spec.

---
Tags: oscillator-clock
---


title: Branching Bus for Sensor

text:
# Question
Title: Branching Bus for Sensor
I am looking to setup a system where I have a master Arduino polling a number of sensors.

The way I am thinking is hooking the master TX line to the sensors RX line(and the opposite for the other line)

Questions

1. How long can the lines be?
2. Can the lines branch?

# Answer
> 2 votes
I have a page about connecting Arduinos using RS485. You can connect multiple devices up like this:

That has a reasonable range, 20 metres or more.

---

On that page I describe a *Rolling-master system* where each device takes turns to be the master and transmit information to the other devices. It also manages some devices not responding.

This screenshot shows the various devices "talking" during their timeslot:

In that particular case there were 3 devices active out of 4 configured.

---

> I have a master ardunio polling a number of sensors.

I'm assuming in my answer that you have an Arduino at each sensor point (you could use a cheap ATtiny85 or something). That would be needed to run the rolling master code.

# Answer
> 0 votes
How many sensors and what kind are they? What Arduino do you have?

Basically you could use 1 Arduino Output per sensor if you have enough, or you are going to need to use a multiplex technique via additional electronic components.

The only other solution would be to use communication (I2C/Serial/etc) to receiving nodes at the sensor.

---
Tags: serial
---


# Question
Title: ArduinoMEGA: 64 digital inputs cause random digitalRead values
I have 64 hall effect sensors (magnetic field sensors) (DRV5023AJQLPG) connected to an Arduino MEGA 2560. For that, I use 48 digital pins and 16 analog pins as digital input pins. The program in the Arduino continuously reads out those 64 digital input pins (in a for-loop) and sends out a serial byte, to a laptop via a usb cable, whenever one of those input pins changes between LOW and HIGH. I also use the ATmega2560’s internal pullup resistors to prevent irregular readouts of the input pins when the sensor is not giving a 0v output (i.e. when it isn’t measuring a strong enough magnetic field).

Everything is working fine when I only physically connect up to 16 of the sensors. The laptop then only receives bytes that correctly tell when a sensor measures a state-change.

However, when I start connecting more of those 64 sensors, then the laptop starts receiving irregular streams of bytes, erroneously suggesting that all the connected sensors measure changing magnetic fields (HIGH and LOW readouts).

I can think of two reasons why these irregular readouts occur: 1. Either, the ATmeag2560’s internal pullup resistors arent working as I think they should. 2. Or, the arduino board and \>16 hall effect sensors combined are pulling to much current.

1. **Pullup resistors not working?** When testing with only 16 sensors connected, it is a stable, properly working setup. When I explicitly *don’t* use the pullup resistors in the program then the setup *does* start behaving irregular, also with just 16 sensors. So the internal pullup resistors seem to be properly activated by the program.
2. **Arduino + 64 sensors draw to much current?** Besides powering the Arduino board and sensors via the usb cable (providing 500mA), I’ve also tried external power sources that provide 1 or 2A. I’ve also powered the Arduino board via an external 5v, +1A voltage regulator, bypassing the Arduino’s onboard voltage regulator. This all doesn’t seem to make a difference in the system’s irregular behaviour. When measuring those setup’s current usage (with amperage meter) it didn’t go above **250mA**.

Calculating the combined current usage (using datasheet info), I came to this:

```
- sensor operating current:             2,7 mA
- sensor output current when in ‘active’ state:     0,25 mA
- TOTAL current of 64 sensors   (3mA*64=)       192 mA
- Arduino MEGA current (approx)             150 mA
- TOTAL current of 64 sensors + Arduino MEGA:       **342 mA**

```

So, both the calculated and measured current usage seem within the range of what can be handled by mentioned power sources.

I’m kinda stuck now. Can anyone suggest anything that might cause this problem? Or point to incorrect thinking of me? Thanks for any responses.

---

'Schematic' (only showing first 8 sensors connected. The ArduinoMEGA is connected to a computer via a usb cable with disabled power line):

Top-side: the hall effect sensors and Vcc an GND rails:

Bottom-side: ArduinoMEGA + the 64 red sensor output lines to the input pins:

Below is the Arduino code:

```
/*
Arduino to Pd protocol

 Placing or removing a chess piece sends only one byte.
 There’s no other serial data being communicated.

 event:                     byte value:
 placing a chess piece on a square:     0-63
 removing a chess piece from a square:          64-127

 ArduinoMEGA pin to byte value mapping:
  byte      pin
  0     6
  1     7
  2     8
  3     9
  …
  46        52
  47        53

  48        A0 (analog 0)
  49        A1
  50        A2
  …
  62        A14
  63        A15

*/

byte prevSquares[64];  // array that holds previous readouts
byte i;                // variable used in for-loops
byte sensorValue;      // variable temp storing of digitalread

void setup() {
  Serial.begin(9600);
  for (i = 0; i < 64 ; i++) {
    pinMode(i+6, INPUT_PULLUP);  // activate pullup resistor
  }
  for (i = 0; i < 64 ; i++) {
    prevSquares[i] = digitalRead(i+6);
  }
}

void loop() {
  for (i = 0; i < 64 ; i++) {
    sensorValue = digitalRead(i+6);
    if (sensorValue != prevSquares[i]) {
      // chess piece was placed or removed from square
      if (sensorValue == 0) {
        // chess piece was placed
        // send serial byte (0-63):
        Serial.write(i);
      }
      else {
        // chess piece was removed
        // send serial byte (64-127):
        Serial.write(i + 64);
      }
      //update prevSquares array:
      prevSquares[i] = sensorValue;
    }
  }
}

```

# Answer
After seeing your schematic, I think the general problem here is that you need to more closely read and follow the datasheet for this part. A lot of times, when you are hobbling a project together at a small scale there are a lot of things you can ignore and get away with, but as you scale up, all the rounded corners start to add up. In this case, you can get away with 16, but once you start adding too more, it becomes too much. Let's go over a few:

**Pull up resistors**

Like I mentioned in the comments, relying on the internal pull ups is probably not a good idea. In my personal experience, they are only really good for adding a quick button input for debugging purposes. I'm not sure specifically what would cause issues only after 16 sensors. It could be that collectively internal pullups are subject to a different and lower current limit, but I'm not familiar enough with the internal architecture of the ATMega2560 to do more than just speculate.

Whatever the case, the best practice here would be to use separate external pull up resistors, within the specifications of the datasheet. (See equation 1 on page 13 of the datasheet.)

**Decoupling Capacitor**

Per the datasheet, page 17:

> A 0.01-µF (minimum) ceramic capacitor rated for VCC must be placed as close to the DRV5023 device as possible.

This capacitor is referred to as C1 in the datasheet figures and is required. This type of capacitor is called a decoupling capacitor, and one of the things it does is provide a local energy storage, so that when the sensor starts pulling a little extra current, it doesn't have to wait for the regulator to respond, it has some local energy already.

Your schematic indicates a single 1uF capacitor on the output of the voltage regulator, however, there are no capacitors for the sensors. The one capacitor is only for output filtering for the regulator, and will not satisfy any decoupling needs of the sensor.

**Filtering Capacitor**

Referred to as C2 in the datasheet, this an optional capacitor to filter out high frequency noise. This isn't needed in most cases, in fact, per the datasheet, page 13:

> Most applications do no require this C2 filtering capacitor.

However, your project might not fall into "most applications" and there are a few things specifically that worry me.

1. You have long wires that are basically acting as antennas that will capture any nearby noise.
2. You have long power lines running parallel to your signal lines which can cause stray inductance which leads to other interesting things. (With the thickness of the plywood separating them, this might not be an issue, but it is something to be aware of).

I would definitely try the first two ideas above to begin with, and only pursue this as a last resort. The only way to know for sure if this is something you need is to stick an oscilloscope on the line and see how noisy it is, but that is not something you probably have handy.

**Other Concerns**

I'm just a little bit worried about voltage drop. Depending on the gauge of wire used, with all the sensors connected, at the end of a strand you might have a non-negligible voltage drop.

With that many wires running together into the Mega, there might be cross talk problems.

Another common problem with scaling up is that there is a higher probability of having faulty components. This is especially with this part which per the datasheet indicates that is particularly sensitive to ESD. It could be that there is a dead sensor that has failed in such a way that it is causing problems for the other sensors. Maybe go through and test all 64 sensors, 8~16 at a time to make sure that separately they all work, and that the issue only occurs when all of them are connected.

**Other Ideas**

Many other comments on the question have suggested a multiplexer and/or multiplexing and I will just briefly echo that here. Multiplexers are typically used in situations where you don't have enough pins and you want to split a single pin to multiple other pins. While that isn't an issue here with the Mega (it appears you have enough pins to do what you are wanting to do), there are other benefits that can be derived from multiplexing this.

For example, one thing you could do is split up the board into 8 - 2 x 4 chunks and then have a multiplexer (such as a 4051 or a 74151) local to each chunk. Then you would have just 8 short wires going into the multiplexer, as opposed to having long antenna-like wires heading to the Mega. This could improve overall signal integrity.
> 3 votes

---
Tags: arduino-mega, sensors, current, digital-in, pull-up
---


title: arduino pro mini downloading?

text:
# Question
Title: arduino pro mini downloading?
I purchased the arduino pro mini atmega328 and equipped it with FTDI breakout board with USB, a battery charging board, Wireless transmitter and a wireless receiver. I'm assuming they can all be connected. My question is, how do I download programs to the arduino board? And where might I find specific programs to download?

# Answer
> 4 votes
The Arduino Pro Mini has a row of connections at the small end that align with the connections on the USB-to-Serial board you have. They are marked GND - VCC - RXI - TXI and should be in the same order as the connector on the FTDI board. I think that the pin marked GRN on the Arduino will align with the connector marked DTR on the USB-to-Serial board, but please make sure that VCC aligns with 5V!

With the FTDI board plugged into the Arduino, you can plug your computer into the FTDI board's USB port and when you run the Arduino IDE programming tool, that USB port should say that it's connected to a serial port. Pick the "Arduino Pro or Pro Mini" as your board, then pick your processor (most likely the "ATmega328 (5V, 16MHz)" and finally your port (that serial port you found).

Now when you upload your Arduino program to the Arduino, it will know the board your have and the port to use.

As for programs to use, start simple and get the onboard LED to blink. From there, you'll have the basics down for creating a program and getting it to the Arduino. You'll find tons of example programs (called sketches in Arduino land) that will help you connect all your fun wireless gizmos!

As noted above - Google is your friend. There are many places to go for examples and help. Start with some of the commercial sites like Adafruit and SparkFun. Their staff really supports the Arduino community with how-to videos, libraries, examples, etc.

---
Tags: wireless
---


title: mthread and multiple header files

text:
# Question
Title: mthread and multiple header files
I'm using mthreads (https://github.com/jlamothe/mthread) for my arduino. But now as the project is getting bigger, it would make sense to break it up in several files.

I successfully outsourced already a part which is not threaded. But somehow I cannot make up my mind how to use mthread in conjunction with several header files.

here is what I got:

main: call header:

```
#include "tcan.h"

```

tcan.h:

```
#ifndef tcan_h
#define tcan_h

#include "Arduino.h"

class tcan : public Thread {
  public: tcan();
  protected: bool loop();
  private:
};
#endif

```

tcan.cpp

```
#include "Arduino.h"
#include "tcan.h"
#include <mcp_can.h>

bool tcan::loop() {
  // lala
  return true;
}

```

but I get an error when compiling:

> tcan.h:6:28: error: expected class-name before '{' token class tcan : public Thread {

Thanks in advance

# Answer
The compiler error is due to that the compiler does not know what Thread is.

> tcan.h:6:28: error: expected class-name before '{' token class tcan : public Thread {

The issue is that the header file is not complete. **A good practice is to include all header files that are needed to read the header file.** As *Thread* is defined in *mthread.h* the *tcan.h* file should be:

```
#ifndef tcan_h
#define tcan_h

#include <mthread.h>

class tcan : public Thread {
public: tcan();
protected: bool loop();
private:
};
#endif

```

Cheers!
> 1 votes

---
Tags: threads
---


# Question
Title: Use command line to upload hex code to teensy.ex
I need a command line implementation for uploading code to Teensy-LC through Windows 8.1 operating system I know Paul has not released support for command line for Teensy-LC yet but i would like to know if any work has been done by anybody else in this regard.

I asked this and this. But all these solutions include

> sending the hex file to the user.
>
> Asking him to open Teensy.exe
>
> Asking him to upload the hex file into Teensy.ex
>
> Asking him to run teensy\_reboot.exe

So is it possible to create an installer of a sort for this purpose which eliminates the user performing all these operations separately and a guided installer simply with Next-\>Next which does the entire job.

But I suppose that since Command Line installer is not available for windows I don't know if this is possible for impossible.

So if there is any way I can achieve an installer UI for Teensy-LC bootloader that would be perfect

**Other viable option** If not that is it possible to make the entire process happen with the person not having direct access to the hex file. Like sending a packaged installer or something I am not sure how this would happen but if there is any possible way please help me out

# Answer
This is starting to drift off topic for this site, but the best solution for making an automated programming utility for the Teensy on Windows, short of writing one yourself, would be to use some kind of UI automation framework to automate the process described in my earlier answer. My favorite one that I have used in the past is AutoIt. It has tools to inspect applications so that you can programmatically click buttons and fill out fields. There are even ways of having it run programs without them being visible to the user. There are plenty of tutorials on the web on how to use AutoIt so I would suggest googling for that. If you have further questions on how to do that, they would be more appropriate on a site other than Arduino.SE.
> 1 votes

---
Tags: uploading, bootloader, teensy, command-line
---


# Question
Title: Can Android phone can be used instead of( or with) Arduino as controller?
I am Android application developer and I want to modify regular toy RC car which can be controlled by Android phone. I want to use 2 Android phones: 1 as remote controller, 1 as controller in RC car. I want to use sensors like GPS, Mobile network, Wifi in RC car in RC car side. I want to know: can I use Android phone as controller in RC car. I am thinking about 2 options:

1. phone as controller (without arduino) - this option would be the best
2. if phone cannot give commands maybe with arduino, while using phone's sensors like gps, mobile network, wifi, bluetooth

Is this possible? If yes, what tools I should use to connect?

# Answer
> 1 votes
You cannot directly control your RC car using and Android phone if you are talking about a normal RC car. If you have an RC car that can be already connected via bluetooth this is another story.

So for normal RC car you would need to have:

AndroidPhone -\> Network -\> AndroidPhone -\> SerialInterface -\> Arduino -\> RC

---
Tags: arduino-nano, remote-control, android
---


# Question
Title: How to emulate an RFID tag with the RC522
Is it possible to emulate an RFID tag with the RC522? (Spec sheet: nxp MFRC522.pdf)
I want the RC522 to act like a NTAG213 nxp.com/documents/data\_sheet/NTAG213\_215\_216.pdf and to be read/write by other readers/writers.
Are there libraries for that purpose?

# Answer
No. Looking at the datasheet, card emulation is not a feature provided by the RC522.

Another popular chip, the PN532, does seem to indicate support for that feature, however, looking at the most popular library for this chip from Adafruit, it does not implement this feature. Another library from Seeed, does seem to implement it, but it looks rather limited as to which cards can be emulated, and the library itself hasn't been updated in a while.
> 2 votes

---
Tags: rfid
---


# Question
Title: Powering Motor doesnt work from Digital Pin, but works on 5V power
I am building a little car project, and I have come across an issue that has made me go mental. I have a single motor (3V-5V), that on direct 3.3V & 5V output works fine. However, when I connect this to a digital port, it for some reason doesn't power. Of course, I first thought it was not supplying correct power, so I got myself a voltage meter and tried that. 3.3V outputs, well 3.3V, all fine. The digital port outputs 4-5V (when it is coded to). So here is my question: Why aren't my motors powering/turning?

# Answer
Power is made up of two values, not one. Besides the voltage there is the current (P=VI), and it's the current you are lacking.

A motor needs a large amount of current to start turning (called the *stall current*) and a digital I/O pin can only supply a relatively small amount (absolute maximum 40mA, recommended maximum 25mA). The power pins though can supply many hundreds of mA.

You should never try and power a motor directly from an I/O pin since you risk damaging the I/O pin. Instead you should use the I/O pin to control an NPN transistor or N-channel FET, which is then used to switch the power (actually the ground connection) to the motor from one of the power pins.

Here is a good tutorial: http://www.circuitstoday.com/pwm-generation-and-control-using-arduino
> 3 votes

---
Tags: power, motor, digital
---


title: Bluetooth connection and RX ,TX

text:
# Question
Title: Bluetooth connection and RX ,TX
I have connected a RN-42 bluetooth (TX-D0, RX-D1, VCC-5V, GND\_GND) to arduino.The problem is that when I run this code ,nothing happens it just upload to infinite or it doesn't. I am checking with tera term. Is there a problem with the connection of the pins? Also when I pair my android phone to the bluetooth it says paired on the phone but the blue light of the bluetooth doesn't switch on, like it's not connected.

```
  #include <SoftwareSerial.h>// import the serial library
   SoftwareSerial Genotronex(1, 0); // TX,RX
   int ledpin=13; // led on D13 will show blink on / off
   int BluetoothData; // the data given from Computer

  void setup() {
  // put your setup code here, to run once:
   Genotronex.begin(9600);
   Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
   pinMode(ledpin,OUTPUT);
  }

  void loop() {
    // put your main code here, to run repeatedly:
  if (Genotronex.available()){
     BluetoothData=Genotronex.read();
   if(BluetoothData=='1'){   // if number 1 pressed ....
  digitalWrite(ledpin,1);
  Genotronex.println("LED  On D13 ON ! ");
   }
  if (BluetoothData=='0'){// if number 0 pressed ....
   digitalWrite(ledpin,0);
   Genotronex.println("LED  On D13 Off ! ");
   }
}
   delay(100);// prepare for next data ...
 }

```

# Answer
> 1 votes
As commenter by RSM

The issue you are facing is because you are using pins **0** and **1**

These are used by the arduino for uart.

So for starters please use any pin other that **0** and **1**. But if you insist that you do need to use these pins, then you don't need softwareserial you can use the default serial itself, but you will need to disconnect the bluetooth while programming.

# Answer
> 0 votes
If you use RX, and TX in default pin then it is not necessary that you should *include SoftwareSerial* library.

# Answer
> 0 votes
The simplest solution to this is to just unplug the Bluetooth module from the TX and RX ports and click to upload. Your sketch will be uploaded and you can plug the pins back. For a permanent solution use the digital pins aside 1 and 0 because they are the same pins your computer uses to upload your sketch to the Arduino board.

# Answer
> -1 votes
Try taking off the bluetooth module, this will allow communication with the computer, not the bluetooth module. I had the same problems with my hc-06, and have not solved the ladder yet.

---
Tags: arduino-uno, bluetooth
---


# Question
Title: How to switch on 32A/240VAC with Arduino?
I have an air conditioner switch rated at 32A/240V AC - how do I turn this on using Arduino and Relay.

I'm based in India and I am unable to find a relay switch rated higher than this.

I don't want to try anything that results in a fire hazard. My aim is to switch on the AC with my mobile phone. I'm using Arduino Uno with a 2.4GHz transceiver for communication.

# Answer
Just go with a solid state relay: you can search on ebay for SSR-40DA (240V, 40A, from China around 4$) or, better, SSR-100DA (240V, 100A, from China around 6$). For 32A you should definitely mount it on an heatsink (they sell quite a lot of them on ebay).

The main advantage of that kind of SSR is that you can command them directly from the arduino. No transistors, no limiting resistors, just connect the ground and the pin and you are done.

With a relay my arduino halted often (probably because of the 5V-12V boost, but it was necessary to drive the 12V relay). In the end I switched to an SSR and... Works like a charm. And since it is quite cheap I suggest you to use it.
> 0 votes

# Answer
> I don't want to try anything that results in a fire hazard.

That's a good idea.

Besides those toy relays there are real ones: 440 V AC * 63 A (Around there, you can find smaller ones too)

BTW: Don't rely on what's printed on the relay itself, with cheap Arduino relay modules. 230V and some current need proper handling by the PCB board as well (size and distance of the copper tracks on the scondary side)

If you want a solution that could be certified (or certifiable) as "safe" there probably won't be an Arduino involved or being built by anyone asking questions like you do ;( (sorry)
> 3 votes

# Answer
The simple answer is: you need to find a relay rated high enough for the voltage and current. There's no way you can make a small relay handle a large current, and relays cannot be joined together to share the load.

If a relay is not available in your country (and I seriously doubt that - you're probably just looking in the wrong places - instead of looking for things on Amazon or eBay try looking at proper industrial electronics suppliers) then you would have to come up with something more creative.

How about designing and building a small electro-mechanical system that physically changes the position of the existing switch for you? Solenoids to press the right bits of the switch, or motors to turn the right bit round, etc.
> 2 votes

# Answer
What about staying with small relay and just add a contactor? The relay will deal with the low current 230v to drive the contactor and the contactor would deal with the high current.
> 2 votes

---
Tags: arduino-uno, relay
---


title: Arduino uno not writing to file

text:
# Question
Title: Arduino uno not writing to file
I'd like the arduino to write to a file whenever an ajax call is made. The ajax works, but it doesn't write to the file. All other code inside the ajax handler does execute.

```
void handle_ajax() {
    int startUrlIndex = HTTP_req.indexOf("button");
    int endUrlIndex = HTTP_req.indexOf(" HTTP");
    String url = HTTP_req.substring(startUrlIndex, endUrlIndex);
    int startButtonIndex = url.indexOf("device-") + 7;// 7 is length of device-, I really just want the number.
    int endButtonIndex = url.indexOf("&");
    String button = url.substring(startButtonIndex, endButtonIndex);
    int startStateIndex = url.indexOf("state=") + 6; // 6 is length of state=, I really just want the number.
    String state = url.substring(startStateIndex);
    int device = button.toInt();
    int newState = state.toInt();
    dim_light(device, newState * 12);
    write_config("", "text");
}

bool write_config(String line, String text) {
    configFile = SD.open("config.ini", FILE_WRITE);

    if (configFile) {
        configFile.write("Dipshit");
    }

    configFile.close();
    Serial.println("Works.");
    return true;
}

```

# Answer
You have run out of RAM. Consider moving string literals into flash with thr `F()` macro.
> 0 votes

---
Tags: arduino-uno, programming, sd-card
---


title: Bad LCD? Bad microcontroller? Or what?

text:
# Question
Title: Bad LCD? Bad microcontroller? Or what?
So I recently bought an Arduino along with an LCD module and two extra ATmega328P-PU ICs. Yesterday it was working just fine then I disconnected everything and reconnected it and this happened.

What could possibly go wrong?

Setup:

with microcontroller that came with the board:

# Answer
> 1 votes
> So i recently bought an arduino along with lcd module and 2 extra atmega328p-pu ,yesterday it was working just fine then i disconnect everything and reconnect it and this happen, what could possibly go wrong ?

I hope you understand how difficult it is for anyone to help with this type of question.

My quick answer is "follow the schematics and reconnect the wires correctly" and "double check all wires".

From the picture it looks like you need to adjust the LCD contrast and reduce the back-light. Please see typical schematics for this.

Another rule-of-thumb is to use wire colors in a meaningful way. For instance, black for GND, red for VCC, yellow for data, blue for control, green for clock, etc.

Cheers!

# Answer
> 1 votes
These 16x2 LCDs are fairly sensitive about their power requirements.

As a first step, I would check the VCC and GND wires are well connected, and closely connected on the breadboard near the LCD.

If your LCD display shows rubbish characters, check the 4 data lines are connected in the correct order.

Also it looks like the contrast is at minimum (or LED backlight at maximum). It could just be the photo, but best check both of these.

---
Tags: arduino-uno, lcd
---


title: Bluetooth Trancievers for arduinos

text:
# Question
Title: Bluetooth Trancievers for arduinos
Would it be possible to use to of these on two separate arduino's, to send and receive information? I am having difficulties understanding the chinese-english descriptions and haven't seen any documentation on doing this. There would be no phone involved. There would only be two arduino's with a Bluetooth module on each of them sending and receiving data from each other.

# Answer
> 2 votes
The boards in your link look funny. Typical boards like this include the "bluetooth circuit" which piggy-backs onto that board, and is soldered at all those little pads.

Have a look at say, the HC-05 board ~ https://www.google.com.au/search?q=hc05+bluetooth+module&tbm=isch

It's easy to see the part that's missing from the one in your link.

For these HC-05 boards, it's possible to pair two together. They need to be configured as "Master" and "Slave" though. Some bluetooth boards can do slave-mode only, so be careful before you purchase.

---
Tags: bluetooth, arduino-nano, hardware
---


# Question
Title: What is the Proper Voltage to supply an enough Current to the Arduino
I'm just confused about the supply that I should use in driving my arduino. Is it okay to use a 3.7V with a 1000mAh to supply it?

I will be using a Lilypad Arduino.

Your replies would be a big help to me.

Cheers!

# Answer
The Technical Specs say that 2.7-5.5V DC is ok so you should be good at 3.7V DC.

Remember though: Power consumption = Current x Voltage

So check that your power supply has enough current available. The current amount used will depend on how many pins you are using. The maximum each digital pin may use is 40mA. 1A (1000mA) will be plenty but mAh (milliampere hours) sounds like a battery specification.

Also, a word from the wise is that some cheap power supplies can be bad (little spikes and dips). If you are having trouble with strange issues it can be a good idea to check the power is ok.
> 1 votes

---
Tags: arduino-mega, battery, current
---


# Question
Title: How to avoid delays in the loop() function?
vI have this functions in my loop() and it publishes temperature reading to Ubidots(an IoT cloud service) using the #include library but it seems it returns a boolean and so the loop is delayed until a true or false value is return and this takes a while there by slowing down my loop() function and other functions in it. Is there a way I can call this function without it having to slow the loop?

```
#include <math.h>
#include <Wire.h>
#include <Servo.h>
#include <WiFi.h>
#include <Ubidots.h>
#include "rgb_lcd.h"
#include "Timer.h"
//#include <SoftwareSerial.h>

//SoftwareSerial mySerial(11, 10); // RX, TX

char ssid[] = "ROSTALECOM_6916";                                                 //your network SSID (name)
char pass[] = "6PTDFYJD";                                                         //your network password (use for WPA, or use as key for WEP)
String api = "875c4a17d995ce4977bdfc1ace55233fd0591c7ce";                             //your API Key number
String idvari = "567d623a762542205cbc517f";                                          //the number of the Ubidots variable
String ctext = "{\"color\":\"blue\",\"status\":\"active\"}";
Ubidots ubiclient(api);                                                             //with that you call the api with the prefix ubiclient

byte p5[8] = {
  0x1F,
  0x1F,
  0x1F,
  0x1F,
  0x1F,
  0x1F,
  0x1F,
  0x1F
  };

int a;
int temperature;
int B=3975;                  //B value of the thermistor
float resistance;

String readString;
int val;
int hum = 70.35;
unsigned char base = 10;

//Temperature Limits
int maxTemp = 29;
int minTemp = 28.5;

//Declarations
rgb_lcd lcd;
Servo winServo;

//Ubidots timer
Timer t;

void setup()
{
    //Loading character
    lcd.createChar(0, p5);

Serial1.begin(9600);
Serial.begin(9600);
winServo.attach(3);
lcd.begin(16, 2);
//mySerial.begin(9600);

//Start Screen
lcd.print("--SmartGarden--");
for (int i = 0; i < 16; i++)
{
        // scroll one position left:
        lcd.setCursor(i, 1);
        lcd.write((uint8_t)0);
        delay(400);
 }
lcd.clear();
lcd.print("Connecting...");
//connect to  wifi network
boolean response;
int status = WL_IDLE_STATUS;
response = ubiclient.WifiCon(ssid, pass, status, api);
Serial.println(response);

//
t.every(1000, sendToUbi);

}

void readTemp()
{
   a=analogRead(0);
   resistance=(float)(1023-a)*10000/a;
   temperature=1/(log(resistance/10000)/B+1/298.15)-273.15;

   //Send temperature via Bluetooth
   Serial.print(temperature);

   //print temperature to LCD
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Tmp:");
   lcd.print(temperature);
   //print humidity to LCD
   lcd.setCursor(8,0);
   lcd.print("Hm:");
   lcd.print("50");

   delay(1000);

}
void writeServo()
 {
  if (val != 0)
  {
  //val = map(val, 0, 1023, 0, 180);
  winServo.write(val);
  delay(100);
  }
 }

 void sendToUbi()
 {
 ubiclient.save_value(idvari, String(temperature));                                                  //this function is to post to ubidots and return True or False depending on the connection status
 Serial.println("The sensor value " + String(temperature) + " was sent to Ubidots");                //print the sensor value
 }

void timerMax()
{
  for (int i = 0; i < 60; i++)
  {

   }
   winServo.write(180);
 }

void loop()
{
  //read temperature
  readTemp();

  //Update ubidots timer
   t.update();

  while (Serial1.available()) {
    delay(3);
    char c = Serial1.read();
    readString += c;
  }
  if (readString.length() >0)
    {
      Serial.println(readString);
      delay(15);

       val = readString.toInt();
       if (val != 0)
       {
       //val = map(val, 0, 1023, 0, 180);
        winServo.write(val);
       delay(100);
       readString = "";
       }
       //writeServo();

    if (readString == "1")
       {
        digitalWrite(13, HIGH);
       }
     if (readString == "0")
       {
        digitalWrite(13, LOW);
       }
     readString = "";
  }

  if (temperature >= maxTemp)
  {
    timerMax();

  }

}

```

# Answer
> 2 votes
> How to avoid delays in the loop() function?

The question is why all the delays? Is there some logic missing? What are you trying to design?

Using delays is often a sign of an attempt to synchronize with external events. Wait for additional input, etc.

Let us walk through some of them:

```
void readTemp()
{
   ...
  delay(1000);
}

```

What is this about? The function does read an analog input BUT then there is a lot of output to Serial and LCD and last this delay. Why?

```
void writeServo()
{
  ...
 delay(100);
}

```

Again the same pattern. Now for your question "delays in the loop()".

```
void loop()
{
   readTemp(); // hidden 1000 ms delay

  while (Serial1.available()) {
    delay(3);
    ...
  }
  if (readString.length() >0)
  {
     ...
     delay(15);
     ...
     if (val != 0)
     {
       winServo.write(val);  // Possible hidden 100 ms delay
       delay(100);
       ...
     }
     ...
}

```

Consider using some logic instead of the delays. There seem to be a common pattern you are using.

# Answer
> 1 votes
As short reply and a general note, there is the millis() function that will be faster than a `delay()`. It returns the number of milliseconds since the Arduino board began running the current program. You use maths to check if you've waited long enough.

Like this:

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

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

    // do something after the waiting interval here

   }

```

Edit: One should also be aware of Interrupts, but be warned they must be used correctly.

---
Tags: arduino-uno, arduino-mega, arduino-ide, library
---