# Question
Title: Trying to explain strange behavior when attempting to do a digitalWrite to A7 on a pro mini?
I found out the hard way today that pins `A6` and `A7` can't be used as digital outputs, but what actually happens when you try to read/write them?

**Some backstory:** I soldered some headers onto a pro mini and I wanted to test all the pins to make sure they worked. I wrote a test program that looped through all the digital pins once a second and toggled their state by doing `digitalWrite(pin, !digitalRead(pin);`. I then added a second loop that went through pins `A0` through `A7` and toggled them using the same method. After adding this loop the built in LED on pin 13 no longer toggled on and off every second. Instead, it would just flicker on very briefly. At first I assumed there was something wrong with my loops (like an off by one) that was causing the strange issue, so I completely rewrote things to use a single loop that iterated over all the pins. The resulting code should have been effectively equivalent to the original code, but now pin 13's LED was toggling properly again.

After much experimenting, I was able to whittle it down to the following test program to demonstrate the strangeness:

```
#define WORKS_CORRECTLY 1

int pins[] = {13, A7};
#define SIZE (sizeof(pins) / sizeof(int))

void setup()
{
#if WORKS_CORRECTLY
    for(int i = 0; i < SIZE; i++)
        pinMode(pins[i], OUTPUT);
#else
        pinMode(pins[0], OUTPUT);
        pinMode(pins[1], OUTPUT);
#endif
}

void loop()
{
    for(int i = 0; i < SIZE; i++)
    {
        int pin = pins[i];
        int pinVal = digitalRead(pin);
        digitalWrite(pin, !pinVal);
    }

    delay(1000);
}

```

With `WORKS_CORRECTLY` defined as `1` the LED on pin 13 toggles state every second like one would expect. With it defined as `0`, however, it just flickers on very briefly every second. This is very perplexing.

Ultimately the answer is to not try to do a `digitalWrite` to `A7` (or `A6`), but I'd like to understand why the behavior changes based on seemingly irrelevant differences.

# Answer
You are calling `digitalWrite` and `digitalRead` with argument `A7`.

According to the file pins\_arduino.h, `A7` is defined as 21.

Now, the two functions are defined in file wiring\_digital.c, and the most important part is that both of them use this code to understand which register and bit to use:

```
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);

```

Those two are not functions, but macros defined in the Arduino.h file:

```
#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )
#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )

```

This means that the positions are stored into two arrays, and each pin data is an offset from the beginning of the array itself. This means that the pin 0 is located on register digital\_pin\_to\_port\_PGM\[0\] (i.e. port D) and is in position digital\_pin\_to\_bit\_mask\_PGM\[0\] (so bit 0).

Now, what about pin A7? It is in index 21. But look at the file pins\_arduino.h:

```
const uint8_t PROGMEM digital_pin_to_port_PGM[] = {
    PD, /* 0 */
    PD,
    PD,
    PD,
    PD,
    PD,
    PD,
    PD,
    PB, /* 8 */
    PB,
    PB,
    PB,
    PB,
    PB,
    PC, /* 14 */
    PC,
    PC,
    PC,
    PC,
    PC,
};

```

The array has only 20 entries! This means that A6 and A7 are NOT mapped. When you call the function with A7, you are going beyond the array limits.

This means that this leads to an unexpected behavior. In THIS particular case you are getting

```
PORT: _BV(1) = 2 which is equal to PB in Arduino.h
BIT: NOT_ON_TIMER = 0

```

So when you read from bit A7 you will check for

```
*portInputRegister(port) & bit
*portInputRegister(PB) & 0 => 0 for every value

```

so it always reads a LOW.

When you write any value to it, you will apply this code:

```
if (val == LOW) {
    *out &= ~bit;
} else {
    *out |= bit;
}

```

`bit` is always 0, so if you write a `LOW` value you will write a `HIGH` on ALL bits connected to port B, otherwise you will write a `LOW` on all of them.

Different is the access to A6: the port will be mapped to 0, which is translated to NOT\_A\_PORT when detecting the register. This will try to read and write from/to register #0, which I admit I do not know what means. According to the ATMEGA328P register map it is reserved, so better not to use it.

Short answer: never try to use values which are not supposed to be used, otherwise you will incur in strange behaviors
> 3 votes

# Answer
> pins A6 and A7 can't be used as digital outputs.

that shows the importance of reading the datasheet (and the schematic): there is no port / pins associated ADC6/A6 and ADC7/A7 on the chip. Absolutely no way of writing to / reading from those pins digitally.

None whatsoever.
> 0 votes

---
Tags: pins, arduino-pro-mini, digital
---


# Question
Title: Trouble connecting Arduino Pro Mini (Atmega328, 3.3V) to nRF24L01 over SPI, receiving all 0 values when I use radio.printDetails();
I am trying to connect my Arduino Pro Mini 3.3V to an nRF24L01 transceiver and cannot see what I am doing wrong. I've checked my wiring a million times because the problem hints there is an invalid or no connection between the Arduino and the transceiver. I have the following pin connections:

> Arduino --------------- nRF24L01
>
> --GND ------------------- GND
>
> --VCC ------------------- VCC
>
> ---D9 --------------------- CE
>
> --D10 -------------------- CSN
>
> --D13 -------------------- SCK
>
> --D11 -------------------- MOSI
>
> --D12 -------------------- MISO

I am using the following sketch

```
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"

RF24 radio(9, 10);

const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0C2LL };     //Addresses to send/receive

void setup()
{
  printf_begin();
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15, 15);
  radio.openReadingPipe(1, pipes[0]);
  radio.printDetails();
  radio.stopListening();
}

void loop()
{
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));

  delay(1000);
}

```

I have no clue where I am going wrong. This setup works well on my Uno, however I cannot replicate it on the Arduino Pro Mini. Can anyone tell me if I am doing something super wrong that would prevent this from working? I'm all out of ideas. Appreciate any help in advanced!

**Update**:

I forgot to copy and paste the output from `printDetails()`:

```
STATUS  = 0x00
RX_DR=0
TX_DS=0
MAX_RT=0
RX_P_NO=0
TX_FULL=0
RX_ADDR_P0-1    = 0x0000000000 0x0000000000
RX_ADDR_P2-5    = 0x00 0x00 0x00 0x00
TX_ADDR = 0x0000000000
RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA   = 0x00
EN_RXADDR   = 0x00
RF_CH   = 0x00
RF_SETUP    = 0x00
CONFIG  = 0x00
DYNPD/FEATURE   = 0x00 0x00
Data Rate   = 1MBPS
Model   = nRF24L01
CRC Length  = Disabled
PA Power = PA_MIN

```

# Answer
Whenever you get an *all zeros* output from the `printDetails()` function you can bet you are having a communication issue between the Arduino and the nRF24 module.

Start by checking your connections.

Check your connections again, using a multimeter to ensure continuity.

Check your connections again (no, I'm not joking).

Finally add a capacitor (anything between 1uF and 100uF will do) between the `VCC` and `GND` pins of your nRF24 module: those modules are pretty sensitive to voltage fluctuations and they are subject to current consumption spikes at startup.

Pair that with a possibly not state of the art voltage regulator (especially on cheap Arduino clones) and you end up with a non responding nRF24 module: the capacitor will provide the extra juice whenever it's required by the radio module.

This is such a common problem that I started soldering the capacitors directly onto the modules to save breadboard space!
> 1 votes

---
Tags: arduino-pro-mini, nrf24l01+
---


title: Custom source directory

text:
# Question
Title: Custom source directory
How do you specify a custom location for your sketch?

I want my code to be located in a `src` folder, but when I try to compile my `main.ino`, `arduino` complains `"The file main.ino needs to be inside a sketch folder named "main".` How do I disable this arbitrary restriction?

# Answer
I found I could accomplish this using the arduino-builder tool. I created this simple bash script to do the compilation:

```
#!/bin/bash
CURRENT_DIR=`pwd`
mkdir -p $CURRENT_DIR/.build
arduino-builder -compile -hardware /usr/share/arduino/hardware -tools /usr/share/arduino/hardware/tools -tools /usr/share/arduino/tools-builder -libraries $CURRENT_DIR/lib -fqbn arduino:avr:uno -build-path $CURRENT_DIR/.build $CURRENT_DIR/src/main.ino

```
> 1 votes

# Answer
You can't. It's a feature of Processing, on which the Arduino IDE is based.
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: Will M2.5 screws fit the holes in the Arduino Uno?
I'm developing a sump pump monitor/alarm setup that will include an Arduino Uno as well as a Raspberry Pi. Both boards will be mounted to a piece of wood. The Arduino is designed to take M3 screws, but the Pi is designed to take M2.5 screws. The difference in these two screw sizes is 0.5mm (2.4mm M2.5 vs 2.9mm M3). Is this going to be close enough to be able to use the smaller M2.5 screws for both? Due to cost reasons, I want to avoid having to purchase two different sizes of screws and standoffs.

# Answer
> 1 votes
With the screw holes for the Arduino being the larger screw holes, the 2.9mm screws would fit, but would probably need a nut and/or a washer to properly secure things. In the end if you intend to be doing more work with Arduinos and Pis in the future that require screwing things together then just go and get proper screw sizes, you won't regret it.

---
Tags: arduino-uno, raspberrypi
---


title: Getting a fixed sampling rate

text:
# Question
Title: Getting a fixed sampling rate
Ultimately I will move to a generic smart phone for this project. I'm trying to read 4 analog inputs from my arduino with a fixed 1kHz sampling frequency. I managed to set it to read at 1kHz as you can see from this link. The issue is that after running several times, I kept testing the frequency by logging the time vector (produced by arduino to the serial terminal) into Excel and calculating the frequency using the equation: f=1/(t2-t1)

I did this to the entire column and I noticed that I got a changing frequency. The difference is very big as it ranges from 780 to 1kHz. I need a fixed sampling rate because we will be applying some digital signal processing on the obtained results which obviously requires a sampling frequency. My code to send the data is the following:

```
#define INTERVAL_LENGTH_US 1000UL

unsigned long previousMicros;
#define FASTADC 1
int recValue;
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
double t = 0;

void setup() {
  int start ;
  int i ;

#if FASTADC
  // set prescale to 16
  sbi(ADCSRA, ADPS2) ;
  cbi(ADCSRA, ADPS1) ;
  cbi(ADCSRA, ADPS0) ;
#endif

  Serial.begin(115200) ;
}

void loop()
{
  unsigned long currentMicros = micros();

  if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
  {
    previousMicros += INTERVAL_LENGTH_US;

    int val_a0 = analogRead(A0);
    int val_a1 = analogRead(A1);
    int val_a2 = analogRead(A2);
    int val_a3 = analogRead(A3);

    Serial.print(((double)currentMicros) / 1000000UL, 5 ); // 1 is the number of decimals to print
    Serial.print('\t');

    Serial.print(val_a0);
    Serial.print(',');

    Serial.print(val_a1);
    Serial.print(',');

    Serial.print(val_a2);
    Serial.print(',');

    Serial.println(val_a3);

  }
}

```

Ps. I'm using Arduino Leonardo, What's the right way to achieve this?

EDIT: Thank you all for responding, As you wanted to see my data, here is a screenshot of the results after I applied Jwpat7's suggestion:

The yello shaded column is the frequency calculated, the first and 2nd columns represent T1 and T1 (T2 is just T1 shifted upward for easier calculation). You may notice the Matlab section, this is because I'm trying to plot the data in Matlab and use it to do the digital signal processing after transmission. The plotting will be real time (I'll the data in txt files for later processing). the bottom potion of the figure shows the frequency after a while....as you can see it's decreasing!

Thanks

# Answer
> 3 votes
You can speed your code up slightly by sending a raw microseconds reading, rather than divided by 1000000. Floating arithmetic on typical Arduino devices can be quite slow. Also, the time to complete a divide is data dependent, so may occasionally but not always delay the next reading; that is, the division may contribute to jitter as well as overall slowness.

Another source of jitter is polling via `loop()` rather than *within* loop \[see below\]. However, this probably adds only a few microseconds of jitter.

To test if too-slow serial transmission is the problem, you could comment out all the serial printing and substitute `Serial.println(currentMicros)`. (Or print the low two bytes of `currentMicros`.)

---

**Polling within `loop()`:** You could replace

```
currentMicros = micros();
if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
  {  ...  }

```

with

```
while (micros() - previousMicros < INTERVAL_LENGTH_US) ;
currentMicros = micros();
...

```

This would tighten up the busy-wait loop and reduce jitter slightly.

If small changes as suggested above don't resolve the problem, you might need to use timer-based interrupts interrupt flags to schedule trigger ADC reads (as suggested in comments) and/or create a circular data buffer to make data collection timing less dependent upon data transmisssion timing.

The **ADC Auto Trigger Source Selections** table in the ATmega32U4 datasheet shows the ADTS bit settings to select various ADC trigger sources, which include Free Running, Analog Comparator, External Interrupt Request 0, and various Compare/Overflow/Capture events on Timer/Counter0, 1, and 4. Your ADC conversion-complete interrupt handler would need to read the ADC, store the reading, set a volatile flag to tell `loop()` which reading is ready, and set the ADC input selection to the next channel.

---

*Edit 2:* **Where the code spends its time:** In the version that busy-waits until the next time-mark arrives, and then takes four ADC readings, the process sits and waits for the ADC to complete. With a standard prescale factor of 128 and 104 μs per conversion, about 416 microseconds are spent waiting on ADC completion. If FASTADC is set and prescale is 16, giving 13 μs per conversion, then only 52 μs is spent in that waiting. In brief: use of a standard prescale factor will probably use up too much time if the polling method is used. But if readings are timer-interrupt triggered and ADC-ready-interrupt stored, a standard prescale factor is ok.

**Serial transmission rate estimates:** As noted in Edgar Bonet's answer, 115200 bps isn't fast enough to support 1000 Ascii-data serial transmissions per second. If working at 100% throughput, that data rate allows only 115 bits per transmission, or 11.5 characters, which typically is not enough for the data you are sending. Additionally, sending the time in Ascii adds another digit to the transmission length at the 10 second and 100 second marks, which may account for the observed slowdown in the "Test ARDUINO" scenario. (The slowdown in the Matlab case may be due to rapidly-growing memory use by Matlab; possibly try less-accurate plotting, or narrower plots, or a specialized graphing program.)

Edgar Bonet's code sidesteps this problem by transmitting data from a fixed-length (8 byte) buffer in binary, hence the 80000 bps figure he mentions (8 bytes times 10 bits per serially-transmitted byte times 1000 readings per second). Since ADC readings are timer-triggered, there probably is no real need to transmit a clock time with each reading, but resynchronization (in case of lost bytes) might need to be added somehow. Possibly one could send a 9-byte packet at each transmission; the extra byte would allow use of a protocol to support error-detection, resynchronization, periodic clock readings, and packet counts.

# Answer
> 2 votes
Expanding on my previous comments...

The only reliable way to get jitter-free ADC readings is to trigger the ADC from a timer event. I wrote the following program to demonstrate the approach on an Arduino Uno, as I don't have a Leonardo. The program configures the Timer 1 to set it's overflow flag every 250 µs, and the ADC to start a conversion on every rising edge of that flag. When the conversion is done (104 µs after it started), the ADC ISR fires. It's job is to retrieve the conversion result and set the analog multiplexer for the next channel, switching round-robin through channels 0 – 3.

```
volatile int adc_readings[4];
volatile bool fresh_readings;

// Used only to clear the interrupt flag.
EMPTY_INTERRUPT(TIMER1_OVF_vect);

ISR(ADC_vect)
{
    static int buffered_readings[3];
    static uint8_t channel;

    if (channel == 3) {

        // "Export" the 4 readings at once.
        adc_readings[0] = buffered_readings[0];
        adc_readings[1] = buffered_readings[1];
        adc_readings[2] = buffered_readings[2];
        adc_readings[3] = ADC;
        fresh_readings = true;
    } else {

        // Buffer the current reading.
        buffered_readings[channel] = ADC;
    }

    // Move to next channel.
    channel = (channel + 1) % 4;
    ADMUX = _BV(REFS0)  // reference = Vcc
          | channel;
}

void setup()
{
    Serial.begin(115200);
    Serial.write("================");

    // Configure the ADC.
    ADMUX  = _BV(REFS0)   // reference = Vcc
           | 0;           // channel = ADC0
    ADCSRA = _BV(ADEN)    // enable
           | _BV(ADSC)    // start first conversion
           | _BV(ADPS0)   // prescaler = 128
           | _BV(ADPS1)   // ...ditto
           | _BV(ADPS2);  // ...ditto
    ADCSRB = _BV(ADTS1)   // trigger source = Timer 1 overflow
           | _BV(ADTS2);  // ...ditto

    // Wait for and discard the first conversion.
    loop_until_bit_is_set(ADCSRA, ADIF);

    // Configure Timer 1 to overflow every 250 us.
    TCCR1A = _BV(WGM11);  // fast PWM mode, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ...ditto
           | _BV(WGM13)   // ...ditto
           | _BV(CS11);   // clock at F_CPU/8
    TIMSK1 = _BV(TOIE1);  // enable overflow interrupt
    ICR1   = 500 - 1;     // period = 500 * 8 CPU cycles

    // Set the ADC to auto-trigger mode.
    ADCSRA |= _BV(ADATE)  // enable auto-trigger
            | _BV(ADIF)   // clear interrupt flag
            | _BV(ADIE);  // enable interrupt
}

void loop()
{
    if (fresh_readings) {
        Serial.write((uint8_t *) adc_readings, sizeof adc_readings);
        fresh_readings = false;
    }
}

```

A few comments:

* The Timer 1 overflow interrupt is used only to clear the timer interrupt flag. The flag has to be cleared because the ADC is triggered only on it's rising edges. Alternatively, that flag could be cleared inside the ADC ISR.
* I choose to deliver the readings by batches of 4 (one reading per channel), thus the buffering inside the ADC ISR. The choice is arbitrary: you can, if you wish, transmit the readings as they come, as suggested in jwpat's answer.
* The very first ADC reading is manually started and discarded. The only reason for this is that it takes longer (200 µs instead of 104).
* The readings are transmitted in binary form at 115.2 kb/s. The effective data rate is 80 kb/s. ASCII would not be possible at this sampling rate.
* The `loop()` function must never take more than 1 ms to execute, otherwise there is a risk of it reading the `adc_readings` array while the ADC ISR is updating it, which would lead to corrupt data. Protecting the access to `adc_readings` inside a `cli()`/`sei()` pair would not significantly ease the timing constraint, as a long `loop()` execution would still carry the risk of loosing data points.

From a cursory look at the ATmega32u4 datasheet it would seem it's Timer 1 is identical to the one of the ATmega328P powering the Uno, save for an extra PWM channel. The ADC, however, is slightly different, but similar enough to make porting fairly straightforward. At least the setting of `ADMUX` would be different.

# Answer
> 1 votes
What you have here is a classic case of the measurement of something changing what is measured.

I guessed when I saw your question that the time taken to transmit all that serial data would be longer than 1 ms. If you really were transmitting at 115200 baud then it would take 2.6 ms to send the 30-odd bytes you are sending (30 * 1/11520). Since you are using a Leonardo you get USB speeds which is faster but not infinitely fast.

I could reproduce your figures when I tested.

However if I comment out the two lines that send the time:

```
//    Serial.print(((double)currentMicros) / 1000000UL, 5 ); // 1 is the number of decimals to print
//    Serial.print('\t');

```

And also measure separately by toggling pin 13:

```
  if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
  {
    previousMicros += INTERVAL_LENGTH_US;
    digitalWrite (13, !digitalRead (13));

```

Then I found that pin 13 toggled at exactly once per millisecond.

(edit) Close enough. See screenshot of logic analyser (0.996 ms):

That is only 4 µs out - within error range for the processor clock.

Uncommenting the timing code I found that for a short time I still got 1 ms per iteration, but it then dropped down to around 1.04 ms (ie. 960 Hz). I am guessing that some USB buffer, somewhere, is filling up and not being emptied as fast as you would like.

Here is the screenshot of the code which sends the time (1.0366 ms):

Notice how simply sending the number of microseconds has increased the time between toggling the pin?

---

It is helpful to have extra hardware to hand to measure things like this. Using the processor that you are trying to time, to send its own timing information is fraught with problems.

---
Tags: arduino-leonardo
---


# Question
Title: How to set limits in Arduino of pin x to remain in high state?
I am working on this thermostat, which has a predefined int that sets pin high and low. But now I want to give it a particular range on which the pin 7 stays high, let's say from 24°C to 26°C, because I don't want my relay clicking every second.

```
const int sensor=A1; // Assigning analog pin A1 to variable 'sensor'
int relay=7;
float tempc;  //variable to store temperature in degree Celsius
float vout;  //temporary variable to hold sensor reading

void setup() {
    pinMode(sensor,INPUT); // Configuring pin A1 as input
    Serial.begin(9600);
}

void loop() {
    vout=analogRead(sensor);
    vout=(vout*500)/1023;
    tempc=vout; // Storing value in Degree Celsius
    vout=analogRead(sensor);
    vout=(vout*500)/1023;
    tempc=vout; // Storing value in Degree Celsius
    Serial.print("temprature in C is ");
    Serial.print(tempc);
    Serial.println();
    delay(2000);
    if (tempc <24) {
      digitalWrite(7,HIGH);
      Serial.print("heating is on as " );
    } else {
      digitalWrite(7,LOW);
      Serial.print("heating is off as ");
    }

```

# Answer
> 1 votes
Your question is not very clear, but I assume, like Mark Smith, that you want your thermostat to be hysteretic between 24°C and 26°C. The algorithm is as follows:

* If the heater is OFF and you get a temperature reading below 24°C, then you switch it ON.
* If the heater is ON and you get a reading above 26°C, then you switch it OFF.
* In any other case, you leave the heater alone: it will stay in whatever state you have previously set it.

Translated to C++:

```
// Pinout.
const uint8_t sensor = A1;  // temperature sensor
const uint8_t heater = 7;   // heater connected through a relay

void setup()
{
    pinMode(sensor, INPUT);
    pinMode(heater, OUTPUT);
    Serial.begin(9600);
}

void loop()
{
    static bool heaterOn;
    float temperature = 500.0 / 1024 * analogRead(sensor);

    // Switch ON if the temperature drops below 24 Celsius.
    if (!heaterOn && temperature < 24) {
        Serial.println(F("Switching the heater ON."));
        digitalWrite(heater, HIGH);
        heaterOn = true;
    }

    // Switch OFF if the temperature rises above 26 Celsius.
    else if (heaterOn && temperature > 26) {
        Serial.println(F("Switching the heater OFF."));
        digitalWrite(heater, LOW);
        heaterOn = false;
    }
}

```

---
Tags: arduino-uno
---


# Question
Title: Can't send HTTP request using ESP8266 and Arduino Uno
I have an Arduino Uno and for Wifi an ESP8266.

My ESP8266 Firmware is

```
AT+GMR

AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04

```

---

```
baund = 115200,
 Both NL & CR

```

Server -- www.linysoft.com

The URL I want to send is either: `http://www.linysoft.com/arduino/?light=off` OR `http://www.linysoft.com/arduino/?light=on`.

Depending on to the link I send the result should be either ==\> on or ==\> off on the page `http://www.linysoft.com/arduino/light.json`.

Now I want to send an HTTP request (Weblink - `http://www.linysoft.com/arduino/?light=on`) so it can write according to that link "on" in the `light.json` page.

The AT command I am sending (my wifi module is connected to my wifi automatically):

```
WIFI CONNECTED
WIFI GOT IP

AT+CWMODE=1

OK

AT+CIPMUX=1

OK

AT+CIPSTART=0,"TCP","www.linysoft.com",80

0,CONNECT

OK

AT+CIPSEND=0,200

OK
>

```

Here I am getting a problem after this \> I can't send `**GET /arduino/?light=on**`. I also tried `GET /arduino/?light=on HTTP/1.0\r\n`.

After putting this line in the textbox, I press the Enter button or Send Button, but nothing happens.

It is stuck here \> for some time. And then it shows me:

```
OK
> 0,CLOSED

```

Pin Connection

```
ARDUINO UNO        ESP8266
RX  -------------->  TX
TX  --------------> RX
VCC--------------> 3.3
CH_PD ----------> 3.3
GND -------------> GND

```

# Answer
linysoft.com is a virtual host. Just try going to http://100.42.56.28/ and see that the connection is reset.

So after the `GET /arduino/?light=on`, you have to also send `Host: www.linysoft.com` (on the next line).
> 1 votes

# Answer
The domain is missing. Try this instead:

```
GET http://www.linysoft.com/arduino/?light=on HTTP/1.0\r\n\r\n

```

Cheers!

Ref. http://contractorwolf.com/esp8266-wifi-arduino-micro/
> 1 votes

# Answer
Just found out a POST wouldn't work. Try this GET request to turn on the light.

```
    GET /arduino/?light=on HTTP/1.1\r\nHost: www.linysoft.com\r\n\r\n

```

Then you can get the status of the LED by GETting light.json like this:

```
    GET /arduino/light.json HTTP/1.1\r\nHost: www.linysoft.com\r\n\r\n

```
> 0 votes

# Answer
I was having same problem and this one solved the problem that after you get a '\>' sign then write

GET http://linysoft.com/arduino?light=on HTTP/1.0\r\n\r\n(or if you are directly writing this on serial monitor then press enter key twice and then wait for somemoment like 2-3 sec in this case dont put \r\n\r\n)

If this didnt worked then try GET http://linysoft.com/arduino/?light=on HTTP/1.0\r\n\r\n

But in this I guess you need to specify arduino.php or arduino.html whichever type you have and too you have to take care the cipsend should be the byte no of get request excluding \r\n\r\n and add 4 to it because we are too sending \r\n\r\n these are 4 character

I hope this will surely work for you
> 0 votes

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


# Question
Title: decomposition long number to byte and recomposition With FRAM
I'm using Adafruit FRAM for my little project and have some trouble with recomposition of LONG Variable , right now the recomposition on INTEGER it's fine. Where I'm wrong with recomposition of LONG number? Thank's for reply :D

```
#include <SPI.h>
#include "Adafruit_FRAM_SPI.h"

/* Example code for the Adafruit SPI FRAM breakout */
uint8_t FRAM_CS = 10;

//Adafruit_FRAM_SPI fram = Adafruit_FRAM_SPI(FRAM_CS);  // use hardware SPI

uint8_t FRAM_SCK = 13;
uint8_t FRAM_MISO = 12;
uint8_t FRAM_MOSI = 11;
//Or use software SPI, any pins!
Adafruit_FRAM_SPI fram = Adafruit_FRAM_SPI(FRAM_SCK, FRAM_MISO, FRAM_MOSI, FRAM_CS);

uint16_t          addr = 0;

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
#define Serial SerialUSB
#endif

void setup(void) {
#ifndef ESP8266
  while (!Serial);     // will pause Zero, Leonardo, etc until serial console opens
#endif

  Serial.begin(9600);

  if (fram.begin()) {
    Serial.println("Found SPI FRAM");
  } else {
    Serial.println("No SPI FRAM found ... check your connections\r\n");
    while (1);
  }
  int interoDaScrivere = 12345;
  long longDaScrivere = 123456789;
  byte a1 = 0;
  byte a2 = 0;
  byte intPt0 = 0;
  byte intPt1 = 0;
  byte longPt1 = 0;
  byte longPt2 = 0;
  byte longPt3 = 0;
  byte longPt4 = 0;
  a1 = byte(interoDaScrivere);        // si scompone l'intero in 2 byte
  a2 = byte( interoDaScrivere >> 8);
  //decomposition Long

  byte b1 = (longDaScrivere);
  byte b2 = (longDaScrivere >> 8);
  byte b3 = (longDaScrivere >> 16);
  byte b4 = (longDaScrivere >> 24);

  //--------------

  // Read the first byte
  uint8_t test = fram.read8(0x0);
  Serial.print("Restarted "); Serial.print(test); Serial.println(" times");

  // Test write ++
  fram.writeEnable(true);
  fram.write8(0x0, test + 1);
  fram.writeEnable(false);
  /*
    fram.writeEnable(true);
    fram.write(0x1, (uint8_t *)"FTW!", 5);
    fram.writeEnable(false);
  */

  fram.writeEnable(true);
  fram.write8(1, a1);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(2, a2);
  fram.writeEnable(false);

  fram.writeEnable(true);
  fram.write8(3, b1);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(4, b2);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(5, b3);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(6, b4);
  fram.writeEnable(false);

  //ricomposizione INT
  int interoRicomposto = 0;
  intPt0 = fram.read8(1);
  intPt1 = fram.read8(2);
  //INT RECOMPOSITION
  interoRicomposto =  ((intPt1 << 8) | intPt0);
  // ricomposizione LONG
  long longRicomposto = 0;
  longPt1 = fram.read8(3);
  longPt2 = fram.read8(4);
  longPt3 = fram.read8(5);
  longPt4 = fram.read8(6);
 //LONG RECOMPOSITION
  longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24));

  Serial.print("A1 F0 ");
  Serial.print(a1);
  Serial.print(" ");
  Serial.println(intPt0);
  Serial.print("A2  F1 ");
  Serial.print(a2);
  Serial.print(" ");
  Serial.println(intPt1);
  Serial.println(interoRicomposto);

  Serial.print("b1 LongPt1 ");
  Serial.print(b1);
  Serial.print(" ");
  Serial.println(longPt1);
  Serial.print("b2 LongPt2 ");
  Serial.print(b2);
  Serial.print(" ");
  Serial.println(longPt2);
  Serial.print("b3 LongPt3 ");
  Serial.print(b3);
  Serial.print(" ");
  Serial.println(longPt3);;
  Serial.print("b4 LongPt4 ");
  Serial.print(b4);
  Serial.print(" ");
  Serial.println(longPt4);

  Serial.println(longRicomposto);

}

void loop(void) {

}

```

# Answer
> 1 votes
There is one very obvious error in your code: You are writing the `long` number LSB (least significant byte) first: the LSB goes at address 3 of the FRAM, while the MSB (most significant byte) goes at address 6. You reconstruct the number with

```
longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24));

```

which puts `longPt1` (contents of address 3) as the most significant byte. Thus you are swapping all the bytes around.

Then there is a more subtle error. `longPt1` is a `byte`. According to the C++ promotion rules, it is implicitly promoted to `int` before any arithmetic or logical operation. But since an `int` is 16-bits, you are shifting *all the bits out* when you do `longPt1 << 24`. You should cast the numbers to a 32-bit type before shifting, as follows:

```
long longRicomposto = (uint32_t) longPt1 <<  0
                    | (uint32_t) longPt2 <<  8
                    | (uint32_t) longPt3 << 16
                    | (uint32_t) longPt4 << 24;

```

Note that I am casting to an *unsigned* type. Shifting a 1 into the bit sign of an integer is undefined behavior in C++: the shift must be done with an unsigned type, *then*, if needed, cast to a signed type.

# Answer
> 1 votes
There is actual a member function in the Adafruit\_FRAM\_SPI library that solves all of this. There is no need for all this shifting.

```
int interoDaScrivere = 12345;
long longDaScrivere = 123456789;

fram.write(1, (const uint8_t*) &interoDaScrivere, sizeof(interoDaScrivere));
fram.write(3, (const uint8_t*) &longDaScrivere, sizeof(longDaScrivere));

```

And

```
fram.read(1, (uint8_t*) &interoDaScrivere, sizeof(interoDaScrivere));
fram.read(3, (uint8_t*) &longDaScrivere, sizeof(longDaScrivere));

```

Cheers!

PS: Might need to adjust depending on the number of bytes/bits and address.

# Answer
> 0 votes
Let's cut out all the rubbish from your code and just look at the relevant lines:

```
byte b1 = (longDaScrivere);
byte b2 = (longDaScrivere >> 8);
byte b3 = (longDaScrivere >> 16);
byte b4 = (longDaScrivere >> 24);

fram.write8(3, b1);
fram.write8(4, b2);
fram.write8(5, b3);
fram.write8(6, b4);

longPt1 = fram.read8(3);
longPt2 = fram.read8(4);
longPt3 = fram.read8(5);
longPt4 = fram.read8(6);

longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24));

```

If we now compress it even more by removing the fram stuff and just assigning direct from b? to the equivalent longPt? you can see even better what is happening:

```
byte b1 = (longDaScrivere);
byte b2 = (longDaScrivere >> 8);
byte b3 = (longDaScrivere >> 16);
byte b4 = (longDaScrivere >> 24);

longPt1 = b1;
longPt2 = b2;
longPt3 = b3;
longPt4 = b4;

longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24));

```

Now if we remove the b? variables completely and just assign direct to longPt? we get:

```
longPt1 = (longDaScrivere);
longPt2 = (longDaScrivere >> 8);
longPt3 = (longDaScrivere >> 16);
longPt4 = (longDaScrivere >> 24);

longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24));

```

And if we then split the last line up so it looks more like the first block:

```
longPt1 = (longDaScrivere);
longPt2 = (longDaScrivere >> 8);
longPt3 = (longDaScrivere >> 16);
longPt4 = (longDaScrivere >> 24);

longRicomposto  = (longPt4 << 0);
longRicomposto |= (longPt3 << 8);
longRicomposto |= (longPt2 << 16);
longRicomposto |= (longPt1 << 24);

```

Hopefully from that it is now clear where you have gone wrong.

You take the lowest 8 bits `(longDaScrivere)` and shift them 24 places to the left (`(longPt1 << 24)`), and apply that to the recombined long.

In effect, you start with 4 bytes `ABCD` and reverse them through bit shifting - 0 goes to 24, 8 to 16, 16 to 8 and 24 to 0, to end up with `DCBA`.

---
Tags: variables, eeprom
---


# Question
Title: Using multiple HC-SR04: sharing trigger pin and interference between HC-SR04
If I have four HC-SR04 detectors, can they share the same trigger pin on the Arduino? This would reduce the number of pins needed from eight to five.

Even if they can share the same trigger, maybe this doesn't make sense because the emitted signal from one HC-SR04 will give a false reading to the others. If this will occur, how much time should the sketch pause before triggering/reading the next HC-SR04?

Thanks.

# Answer
No, you can't really share the same trigger pin, for the reasons you have already worked out. You can, though, share the same echo pin, since you know which HC-SR04 has been activated by the trigger.

To do that you will need a "wired or" circuit. The simplest method is a diode per ECHO signal and a pull-down resistor:

simulate this circuit – Schematic created using CircuitLab
> 2 votes

---
Tags: arduino-uno, hc-sr04
---


# Question
Title: Can I connect to a DALI network as a master node using an Arduino?
I have googled a lot, and mostly every website you can link me I have already explored, some are outdated and don't work, others aren't clear in their documentation, and use equipment too expensive to run the risk of buying it and it not working.

https://github.com/edinburghhacklab/dali

https://github.com/sde1000/python-dali

https://github.com/krzychb/DimSwitch/blob/master/extras/pictures/PHILIPS-HF-REGULATOR-TOUCH-a-DALI%2018-58w-T8-%201-a-2-LAMPS.pdf

http://microcontrollershop.com/product\_info.php?products\_id=5384

Moreover, like any free protocol, you have to pay to access the DALI standard.

What can I do to control a network of connected DALI dimmable ballasts?

# Answer
I have made a simple DALI controller with Arduino Nano. Maybe it will be useful for you. Look here: Simple DALI Controller
> 1 votes

---
Tags: can-bus, modbus, home-automation, automatization
---


# Question
Title: How to connect an industrial sensor to Arduino Uno?
I want to use a sensor to read pressure in rooms. But sensor like MPX series isn't capable to read air pressure change under 100 Pa. So I want to use industrial sensor like Dwyer 607 Series, and dont have a clue how to connect it to arduino. Anyone can help? Thanks :) Fyi, this is the manual instruction for the sensor http://www.dwyer-inst.com/PDF\_files/E\_76\_low.pdf

# Answer
That uses the industry standard 4-20mA current loop system. For that you really need a special chip to interface it.

You can buy shields that interface to 4-20mA current loops.
> 1 votes

---
Tags: arduino-uno, sensors
---


# Question
Title: Using Arduino libraries with ARM based microcontroller
A week ago I started messing with LoRa. I got my STM32L151 IM880A kit.

Company that provided SX1272 LoRa modem chip (used in kit), provided some libraries, but lots of functionalities are still not implemented and is still not suitable for use in multi P2P aplications.

After googling I came across Libelium company which used SX1272 chip in their products design and they provided useful set of libraries that provides lots of functionalities and also implements some sort of LoRa frame protocol stack ideal for use in P2P applications.

The problem is that I'm using STM32 in my project and Libelium libraries are written for Arduino. So I was wondering if there is a smart way to port Arduino libraries so I could use them in my STM32 Keil projects, since the libraries seems huge.

Tips, hints, links would be appreciated (I don't have experience in using Arduino and I'm not familiar with Arduino library structure).

# Answer
Every time I work on a project I use arduino libraries and port them to my micro controller. I used sublime text editor with multiple selection and editing(ctrl-d). Then I copy the arduino code to both sublime and my uC IDE then compile it in the IDE, scroll up to the first undefined function and add its definition to the code or modify it using sublime multiple editing and selecting (like digital read and write was in my opinion useless). After that update the file in your IDE and compile again.

You would do that till you have finished and it would take some time.
> 1 votes

# Answer
> So I was wondering if there is a smart way to port Arduino libraries so I could use them in my STM32 Keil projects, since the libraries seems huge.

Yes. the STM32 port of arduino uses GCC, which isn't that different MDK or ADS - I have ported quite a few from back and forth from GCC \<-\> MDK, and one from GCC to ADS. If the code is well written, in many times all you need to do is to change the isr-related code pieces (a few names) and hit the recompile.
> 0 votes

---
Tags: library
---


# Question
Title: Am I able to connect an anti static wrist strap to the ground pin on the Arduino uno?
So you have the pin on the arduino uno which is ground, are you able to use a jumper wire to send the ground source out the other end of the wire to the alligator clip for the antistatic wrist strap?

# Answer
I was about to write that I wouldn't do that, but in view of the post I linked to \- I am changing my mind.

The point to the wrist strap it to have you, and the thing you are touching, at the same potential (whatever that is relative to the known Universe). Now if you connected the strap to the earth on your power point, that would not achieve anything unless your Arduino was **also** grounded (eg. via a USB cable).

So using the ground wire on the Arduino sounds sensible enough. Personally I don't usually do that, however if I have moved around (and might have shuffled over some carpet, etc.) I always touch some metal part to ground myself (for example, a metal switch on a lab power supply) and discharge any static that might have built up by moving around on the floor.
> 1 votes

---
Tags: arduino-uno, voltage-level, safety
---


# Question
Title: WS2812B strip stopped responding to control
I have a WS2812B LED strip (A clone of the Adafruit one I assume, it's from China via eBay) of 60 LEDs. When I got it, it was all fine - I could load the FastLED examples and they would work perfectly. I then tried to write something more custom, which didn't work for whatever reason. Upon re-loading the FastLED examples, I now get absolutely nothing from the strip.

It's being powered by an ATX computer power supply with ample amperage on 5V, and when I remove and then re-add the power connectors the strip does flash, indicating it's getting power and is capable of lighting up. It just feels like something I have done has caused it to enter a state where it won't respond to control.

I've also made sure my sketches are making it to the arduino by loading the inbuilt LED blink sketch, which works, then trying to switch back to a FastLED example which does nothing.

I'm kind of lost as to what could be wrong here.

# Answer
Did you follow the Adafruit NeoPixels best practices guide?

You may have zapped the first NeoPixel in the group. You should be able to, fairly easily, bypass that. Each NeoPixel has to "reshape" the data for the next one along, so if you damage the first one, no data will reach the others.

I strongly suggest you follow the guidelines in the link, including the capacitor and resistor.
> 1 votes

---
Tags: led, arduino-leonardo
---


# Question
Title: How to connect to pins when using I2C LCD shield?
How are pins used with this shield? The tutorial says that the header pins are inserted into the Arduino but the guide says they are not used for signals. Is there any way of using the other pins?

Update:

# Answer
What it means is although all pins from the Arduino are connected only A4, A5 5V and Gnd are actually used by the shield. I think that these 4 pins are shared with other shields and all the rest of the pins are available for shields to either share or use exclusively.

So, if you have this shield and an Ethernet shield, which needs exclusive access to pins d7, d8 and d9 then you would be to use both shields at the same time.
> 1 votes

---
Tags: lcd, shields
---


title: Bluetooth signal returns 0

text:
# Question
Title: Bluetooth signal returns 0
I have started programming Arduino in the last month. Now I'm working with a bluetooth module. But when I send some data from the Android device to the Arduino, it stays for a very short time and after that immediately it becomes `0`.

Why does it become `0`? And how can I get rid of that problem?

Here is my code:

```
int x,y;

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  if(Serial.available()>0)
  {
    x=Serial.parseInt();
    y=Serial.parseInt();
    Serial.print("x:");
    Serial.print(x);
    Serial.print("\n");
    Serial.print("y:");
    Serial.print(y);
    Serial.print("\n");
  }
  else
  {
    ;
  }
}

```

and here is the result:

# Answer
`Serial.parseInt()` has a timeout. If something arrives on the serial, or is left over from a previous transmission and hasn't been read yet, `Serial.parseInt()` will start looking for a number to parse. When that fails it times out (and so does the second one immediately after it). When that timeout occurs `parseInt()` just returns 0.

IMHO the Arduino serial parsing routines are very poorly written and should be avoided. I have some tips on how to properly read serial here.
> 1 votes

---
Tags: serial, bluetooth
---


# Question
Title: How do functions outside of void loop work?
I am used to Arduino sketches with a `void setup()` part that runs once, and a `void loop()` part that keeps looping. What happens when you have void functions outside of the main `void loop()`? Will these all keep looping in parallel or do they run one after the other? Or do certain void functions only run once certain criteria has been met (like a while loop)?

For example in the code below, when will the `void receiveData(int byteCount)` and the `void sendData()` functions run?

```
//I2C_test

//This code demonstrates communication via an I2C bus between a raspberry pi and an arduino.
//When the Raspberry pi (master) sends data to the Arduino (slave), the Arduino uses this
//data to control a motor. After the Arduino has recieved data from the master, it then collects
//data from the external environment via a sensor and sends this data back to the Raspberry pi.

#include <Wire.h>
int number = 0; //Declare variables
int val = 0;

void setup() {
  //Anything between the curly brackets runs once when the arduino is turned on or reset
  pinMode(0, INPUT);
  //Set pin 0 as input and 3 as output
  pinMode(3, OUTPUT);
  Serial.begin(9600);
  //Set the data rate for serial transmission at 9600bps
  Wire.begin(0x04);
  //Initiate the Wire library, join the Arduino as a slave, and specify its 7 bit slave address
  Wire.onReceive(receiveData);
  //Define callbacks for i2c communication
  Wire.onRequest(sendData);
}

void loop() {
  //The code between the curly brackets keeps repeating
  delay(100);
}

void receiveData(int byteCount) {
  while(Wire.available()) {
    number = Wire.read();
    //Set the variable "number" to the data sent by the master
    analogWrite(3, number);
    //Write this number to pin 3 (PWM). This controls the motor speed
  }
  val = analogRead(0);
  //Read the voltage on pin 0 (connected to the sensor). Map input voltages between 0 and 5 volts into integer values between 0 and 1023
}

void sendData() {
  Wire.write(val);
  //Send the data read from the sensor to the master.
}

```

# Answer
> 11 votes
The `setup()` and `loop()` functions are unusual because they are called automatically for you by the Arduino code. No other functions behave this way.

Generally speaking, a function will never run unless you explicitly call it yourself (e.g. from within `setup()` or `loop()`), or instruct another part of the program to call it. (There are other ways to execute functions, but that usually involves some very advanced tinkering which is best avoided.)

For example, `pinMode()` is a function just like any other. It only runs when you actually put something like `pinMode(3, INPUT)` in your code. At that point, it runs once, finishes, and then the calling function carries on from where it left off (they never run in parallel).

The example code you've posted is quite interesting. Look at these lines in `setup()`:

```
Wire.onReceive(receiveData);
Wire.onRequest(sendData);

```

These lines are telling the `Wire` object to call `receiveData()` and `sendData()` in response to I2C events. It does this by passing function pointers which are stored and used by `Wire`.

I'd recommend searching for information about **C/C++ function pointers** online if you want to learn more about this. You may also be interested to explore Arduino's `attachInterrupt()` function.

# Answer
> 3 votes
Is it not that case that `setup()` is called once and `loop()` is called repeatedly? i.e. that there is an **unseen** `main()` which might look like this:

```
void main(){
  setup();
  while(True){
    loop();
  }
}

```

Apologies as I'm just looking into the Arduino and have almost no C/C++ experience; I'm trying to get a handle on this `loop()` situation myself.

# Answer
> 3 votes
I can't comment on Dee's response. The actual code that is executed in the main loop is here:

```
    int main(void) {
    init();
    initVariant();

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }
    return 0;
}

```

And yes, `setup()` gets called once and `loop()` is being called repeatedly (together with some serial stuff).

# Answer
> 1 votes
It works as normal function, it must be called to make sense. loop()/setup() are called from a main() function which is compiled from Arduino directory and linked in. receiveData/sendData are to called from your program which root is in loop/setup functions.

---
Tags: arduino-uno, i2c
---


title: Use TFT LCD with Uno and Wi-Fi shield

text:
# Question
Title: Use TFT LCD with Uno and Wi-Fi shield
I need to work with Arduino Uno, LCD and Wi-Fi shield.

I was wondering whether I can use the LCD in the link, 2.2" TFT Display - Test the Display with the Uno and Wi-Fi shield - and how to search for them?

# Answer
Start by checking which pins are used by the shields and if there is any conflicts. Check the shield schematics and example libraries.

If there are any conflicts, check if the shields has any jumpers that may be used to change the pin configuration.

Cheers!
> 1 votes

# Answer
Yes the arduino Uno will work with that LCD display and can work with wifi shield at same time too.
> 0 votes

# Answer
Providing they're I2C shields, it is possible to use both at the same time, you may have to write your own modifications to allow this however as each shields library may assume it is the sole connected shield.
> 0 votes

---
Tags: lcd, wifi
---


title: Arduino stacking wifi and gsm shield

text:
# Question
Title: Arduino stacking wifi and gsm shield
I'm fairly new to this and I need some help before I buy anything...

If I understand correctly I can buy an arduino, couple of shields and just stack them one onto another if they are compatible...

I'll be doing some work with an arduino and I would need both WiFi and GSM shields but I'm not sure if they're compatible... On the arduino.cc I saw that they both use pin 7 (GSM as modem reset and WiFi as "handshake")

Is there any way I can use both of the shields even though they use the same pin?

Thanks

# Answer
You can still use both of them although you'll need to buy another piece to make it work.

This is called the Go-Between Shield and it basically lets you re-route a pin to a different one. You will need to change the pin number in your code to the one you re-assign that signal to but it will still work.

The signals you listed that go on that pin are very incompatible, as in if you try to do it, you'll have problems. Every time your Wifi shield will try to connect to something, your GSM shield will reset.
> 1 votes

# Answer
If you will be using Wi-Fi, instead of buying a Wi-Fi shield and a GSM shield, simply buy an Arduino Yún (which will substitute the Arduino and WiFi shield) and connect the GSM shield to it.

From How to use the Arduino GSM shield with Arduino Leonardo, Arduino Yun, and Arduino Mega, it shows you how to connect the Arduino Yún with a GSM shield and to use them without any problem with the help of jumper.
> 1 votes

---
Tags: wifi, gsm
---


# Question
Title: Error: request for member 'RGB' in 'redLed' , which is of non-class type 'int'
My 10 year old received great gift from older brother (Crate Creations) and I am trying write the program and getting this error. It looks to me that I matched the required code word for word symbol for symbol but I just can't figure out what I did wrong:

```
void loop () {

  for (float x = 0; x < PI; x = x + 0.00001) {
    RGB[0] = power * abs(sin(x * (CommonMathVariable)));
    RGB[1] = power * abs(sin((x + PI/3) * (CommonMathVariable)));
    RGB[2] = power * abs(sin((x + (2 * PI) / 3) * (CommonMathVariable)));
    ambientLight = analogRead(ldrPin);
    if (ambientLight > 600) {

    analogWrite (redLed.RGB[0]);
    analogWrite (greenLed.RGB[1];
    analogWrite (blueLed.RGB[2];

  }

```

I get this error:

```
request for member 'RGB' in 'redLed' , which is of non-class type 'int'

```

# Answer
Probably you didn't spot commas:

```
    analogWrite (redLed,   RGB[0]);
    analogWrite (greenLed, RGB[1]);
    analogWrite (blueLed,  RGB[2]);

```

The function `analogWrite` takes two arguments, separated by commas. You were missing some brackets as well.
> 3 votes

---
Tags: programming
---


title: DS18B20 and Arduino - Internall Pull-Up

text:
# Question
Title: DS18B20 and Arduino - Internall Pull-Up
Can this DS18B20 sensor be used with Arduino internal pull-up or it require exactly 4.7k pull-up resistor?

# Answer
> 1 votes
The Arduino internal pull-up is something like 50k. That is a lot different from 4.7k. You would probably find that the pull-up is not strong enough to get clean pulses from the device. Also if you are using it in one-wire (parasitic) mode notice this from the datasheet:

> To assure that the DS18B20 has sufficient supply current, it is necessary to provide a strong pullup on the 1-Wire bus whenever temperature conversions are taking place or data is being copied from the scratchpad to EEPROM.

Notice the words 'strong pullup'. The internal pullup is not strong.

# Answer
> 0 votes
If the datasheet specifies a 4.7kΩ resistor then a 4.7kΩ resistor is what you need.

---
Tags: arduino-uno, sensors, arduino-nano, temperature-sensor
---


title: Weird characters at the end of LCD

text:
# Question
Title: Weird characters at the end of LCD
I have written a simple sketch that displays temperature and humidity on a 16x2 LCD. Here's its output:

Temp: 28▒▒
Humidity: 68▒▒

The library I used for DHT11 sensor is not from Adafruit. This is the sketch:

```
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#include<dht.h>

#define DHT11_PIN 12
#define I2C_ADDR       0x3F
#define BACKLIGHT_PIN  3
#define En_pin         2
#define Rw_pin         1
#define Rs_pin         0
#define D4_pin         4
#define D5_pin         5
#define D6_pin         6
#define D7_pin         7
#define SCL_PIN        12
#define SDO_PIN        11

dht DHT;
LiquidCrystal_I2C  lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin);

void setup() {
  pinMode(SCL_PIN, OUTPUT);
  pinMode(SDO_PIN, INPUT);
  lcd.begin (16, 2);
  lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.home ();
}

void loop() {
  lcd.setCursor(0, 0);
  int chk = DHT.read11(DHT11_PIN);
  lcd.print("Temp: ");
  lcd.println(DHT.temperature,0);
  lcd.setCursor(0, 1);
  lcd.print("Humidity: ");
  lcd.println(DHT.humidity,0);
  delay(2000);
}

```

# Answer
The function `println` usually appends a carriage-return and linefeed to what it prints. It wouldn't surprise me if those two extra characters are its attempt to "render" that.

Try replacing `println` with `print` and see what happens.
> 2 votes

---
Tags: arduino-nano, lcd, temperature-sensor
---


title: Why is the stack pointer out of range?

text:
# Question
Title: Why is the stack pointer out of range?
I have a function that dumps the contents of the arduino's ram, and it works, but I still dont understand why it says my stack pointer is at 0x08C9 If the ram of the arduino is 2kb, or 2048 bytes, shouldent the max addressable size be 0x0800?

```
RAM: SP->0x08C9 HP->0x0371 FREE:1368

```

And the code:

```
void printAddress(uint16_t val)
{
  Serial.print(F("0x"));
  if(val < 16)
{
 Serial.print(F("0"));
}
if(val < 256)
 {
  Serial.print(F("0"));
}
if(val < 4096)
{
  Serial.print(F("0"));
}
Serial.print(val,HEX);
}

void setup(){
Serial.begin(115200);
//0x0800 2048
uint8_t *heapptr, *stackptr;
stackptr = (uint8_t *)malloc(4);        // use stackptr temporarily
heapptr = stackptr;                     // save value of heap pointer
free(stackptr);                         // free up the memory again (sets stackptr to 0)
stackptr =  (uint8_t *)(SP);            // save value of stack pointer

Serial.print(F("RAM: SP->"));
printAddress(stackptr);
Serial.print(F(" HP->"));
printAddress(heapptr);//(int)&__heap_start);
Serial.print(F(" FREE:"));
Serial.print(stackptr - heapptr);
Serial.println();
}

```

As a note, Comments are not mine.

# Answer
> 1 votes
Sure... if the RAM started at address 0, which it doesn't.

According to the datasheet the RAM starts at address 0x0100, below which are all the SFRs:

# Answer
> 0 votes
> free up the memory again (sets stackptr to 0)

Freeing memory alters the **heap**, not the stack. In any case the heap is not like the stack, it is a piece of memory from which memory is allocated, not necessarily contiguously. If you were to allocate A B C from the heap, and then delete B, the heap pointer would be untouched, because it would now have a gap: A ... C

> shouldn't the max addressable size be 0x0800?

As Majenko pointed out, RAM starts past the "internal registers" of the processor, so the maximum RAM would be 0x8FF in this particular case.

---
Tags: arduino-uno
---


title: Serial Port greyed out Ubuntu 16.04

text:
# Question
Title: Serial Port greyed out Ubuntu 16.04
I am running Ubuntu Mate 16.04 LTS, with an Arduino Uno R3 clone. I am having the dreaded serial port graying out problem, and have not found a solution for fixing it. Currently, The serial port will grey out sometimes, and sometimes it will be not grayed out, and I can see that I have selected ttyUSB0. Usually when it is not grayed out, uploading a sketch will not work, and I get the error like it is grayed out:

> avrdude: ser\_open(): can't open device "/dev/ttyUSB0": No such file or directory An error occurred while uploading the sketch

```
chmod a+rw /dev/ttyUSB0

```

doesn't solve the issue, with log out included

```
gpasswd -a aaron dialout

```

doesn't solve the issue, with log out included

I searched preferences.txt and serial.debug rate is set to 9600

I have tried entering preferences.txt and deleting all of the serial entries. They are recreated the same after deletion, and this doesn't solve anything.

I tried running as sudo, doesn't work.

I tried solving this originally on Arduino IDE 1.0, didn't work.

I have upgraded to Arduino IDE 1.6.10, still not working.

running lsusb in terminal yields this while Arduino is plugged in:

```
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0a5c:21e6 Broadcom Corp. BCM20702 Bluetooth 4.0 [ThinkPad]
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

```

Checking var/log/syslog after plugging in Arduino:

> kernel: \[42043.787178\] usb 3-2: new full-speed USB device number 109 using xhci\_hcd
>
> kernel: \[42043.916241\] usb 3-2: New USB device found, idVendor=1a86, idProduct=7523
>
> kernel: \[42043.916249\] usb 3-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
>
> kernel: \[42043.916253\] usb 3-2: Product: USB2.0-Serial
>
> kernel: \[42043.916964\] ch341 3-2:1.0: ch341-uart converter detected
>
> kernel: \[42043.918199\] usb 3-2: ch341-uart converter now attached to ttyUSB0
>
> mtp-probe: checking bus 3, device 109: "/sys/devices/pci0000:00/0000:00:14.0 /usb3/3-2"
>
> mtp-probe: bus: 3, device: 109 was not an MTP device

Ran to add to dialout group, then logged out

```
sudo usermod -a -G dialout aaron

```

No solution. So it looks like Arduino board is not being recognized. Not sure what to try next. It is important that I have uploaded sketches before, but am not sure if there is a pattern to when it does not work. It does not work 95% of the time.

Thanks for the help!

# Answer
I have the same problem, I believe that the problem is related to the 4.x kernel, since I have already tried another distribution with the kernel mermo and the problem persists. Using a windows virtual machine as guest works, which excludes communications and hardware issues.
> 1 votes

---
Tags: arduino-uno, serial
---


# Question
Title: How to interpret the data from GPS GY-NEO6MV2 using Arduino Uno?
I am trying to get GPS data from my GY-NEO6MV2, but the results are not readable with SoftwareSerial or other libraries. I have used the following code that has worked for others on the net, but I don't get any results from it. The GPS data appears perfectly in the serial monitor, but the interfaces such as SoftwareSerial fail to receive it. Instead, I receive a bunch of `-1`s. Here is the code:

```
#include "SoftwareSerial.h"

// Constants
#define txPin 1      //tx pin in GPS connection
#define rxPin 2      //rx pin in GPS connection

// Set up the GPS serial port
SoftwareSerial gps = SoftwareSerial(rxPin, txPin);
// Variables
byte byteGPS = 0;
int i = 0;
int state = 0;
char dataGPG[100] = "";
char *pch;
char *GGA[15];
int sat = 0;
void setup() {
  //setup for Serial Port
  Serial.begin(9600);
  Serial.flush();
  //setup for GPS Serial Port
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  gps.begin(4800);
  gps.flush();
  //setup satellites signal
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  // Turn off the led until a satellite signal
}

void loop() {
  gps.flush();
  Serial.flush();
  Serial.println("Waiting GPS data...");
  // Prepare all for reading GPS Serial Port
  memset(dataGPG, 0, sizeof(dataGPG)); // Remove previous readings
  byteGPS = 0; // Remove data
  byteGPS = gps.read(); // Read the byte that is in the GPS serial port
  delay(1000);
  // Find the desired string
  while (byteGPS != '$') {
    byteGPS = gps.read();
   /******* Here I just get -1 *************/
  }
  // Save the string in an array
  i = 1;
  dataGPG[0] = '$';
  while (byteGPS != '*' ) {
    byteGPS = gps.read();
    dataGPG[i] = byteGPS;
    i++;
  }
  dataGPG[i] = '\0';
  string(); // Call to the function that manipulates our string
}

/*
  This function will allow us to identify the data we need to get the longitude, latitude ...
*/

void string() {
  i = 0;
  memset(GGA, 0, sizeof(GGA)); // Remove previous readings
  pch = strtok (dataGPG, ",");
  // Analyze the saved interval in pch to see if it the needed string
  if (strcmp(pch, "$GPGGA") == 0) {
    while (pch != NULL) {
      pch = strtok (NULL, ",");
      GGA[i] = pch;
      i++;
    }
    plot(GGA, "$GPGGA");
    // Call to the function that is going to display the data
  }
}

/*
  This function organize the gps data received for printing in the serial monitor.
*/

void plot(char **GGAPrint, char *trama) {
  state = atoi(GGAPrint[5]);
  sat = atoi(GGAPrint[6]);
  if (trama == "$GPGGA" && state == 1) {
    digitalWrite(13, HIGH);
    // Then there are satellites, the LED switch ON
    Serial.println("");
    Serial.println("----------------------------------------------");
    Serial.print("UTC Hour -> ");
    Serial.println(GGAPrint[0]);
    Serial.print("Latitude -> ");
    Serial.print(GGAPrint[1]);
    Serial.println(GGAPrint[2]);
    Serial.print("Longitude -> ");
    Serial.print(GGAPrint[3]);
    Serial.println(GGAPrint[4]);
    Serial.print("GPS quality: 0=null; 1=GPS fixed -> ");
    Serial.println(GGAPrint[5]);
    Serial.print("Number of satellites -> ");
    Serial.println(sat);
    Serial.print("Horizontal Dilution of Precision -> ");
    Serial.println(GGAPrint[7]);
    Serial.print("Antenna altitude -> ");
    Serial.print(GGAPrint[8]);
    Serial.println(GGAPrint[9]);
    Serial.print("Geoid Separation -> ");
    Serial.print(GGAPrint[10]);
    Serial.println(GGAPrint[11]);
    Serial.println("----------------------------------------------");
    Serial.println("");
  } else {
    // If no satellite connection
    digitalWrite(13, LOW); // Turn off the LED
    Serial.println("");
    Serial.println("-----------------------------");
    Serial.print("|--- Satellites Used -->");
    Serial.print(sat);
    Serial.println(" |");
    Serial.println("|----Waiting location----|");
    Serial.println("-----------------------------");
    Serial.println("");
  }
}

```

The result wasn't correct and I only saw this sentence:

> Waiting GPS data...

---

I updated the code by adding `gps.available()` and `delay(2)` before every `gps.read()` and it worked. I still don't know why, but this worked:

```
#include "SoftwareSerial.h"

// Constants
#define txPin 2      //tx pin in GPS connection
#define rxPin 3      //rx pin in GPS connection
char gps_data[200];

SoftwareSerial gps = SoftwareSerial(rxPin, txPin);
char byteGPS = 0;

void setup() {
  Serial.begin(9600);
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  gps.begin(9600);
}

void loop() {

  byteGPS = '0'; // Remove data
  memset(gps_data, '\0', 200);

  while (gps.available())
  {
    while (gps.available())
    {
      byteGPS = gps.read(); // Read the char that is in the GPS serial port
      if (byteGPS == '$') break;
    }
    int i=0;
    while (gps.available())  // Available3
    {
      delay(1);
      gps_data[i++] = byteGPS;
      byteGPS = gps.read();
      if ((byteGPS == '\n')) break;
    }
    if (i > 1)
    {
      delay(1);
      parse_gps_data();
    }
  }
}

```

The code in `parse_gps_data()` parses the data from gps. It works fine.

# Answer
Your sketch has many problems:

* The `flush` method waits for everything you have *written* to go out. You haven't *written* anything to the GPS or `Serial`, so there's no reason to flush the output. And you don't need to call it at the beginning of `loop`.
* Calling `delay` is the surest way to lose GPS characters. Never use `delay` in a GPS sketch.
* You are calling `read` without calling `available` first. Because you called `delay`, there are *probably* chars available, but not necessarily, and they will not be a complete sentence. This explains the partial NMEA data in your question.
* You are printing too much in the `plot` routine. After 64 characters are printed (actually *queued* for printing), the `Serial.print` call must wait for some characters to be sent (making room in the output buffer). At 9600, each character takes 1ms to be sent. During that time, the GPS device is still sending characters. Eventually, the input buffer overflows and GPS characters are lost. When properly structured (see below), there is barely enough time to print all those messages.
* You have connected the GPS to pins 1 & 2, but pins 0 & 1 are the HardwareSerial pins (Rx & Tx), dedicated to `Serial` . They are conflicting with each other, and may interfere with uploading new sketches via USB.
* You do not have good satellite reception, according to the GPS data fragments you show. Check the antenna, get near a window, or go outside. It may take 10 minutes before a "fix" is acquired.
* You are using `SoftwareSerial` for the GPS port. `SoftwareSerial` is very inefficient, because it disables interrupts for long periods of time. At 4800, the Arduino is dedicated to receiving each char for 2ms, an *eternity* for a 16MHz processor. This will interfere with other parts of the sketch or other libraries. This answer gives several alternatives, like `AltSoftSerial`, on different pins.

### Solutions:

First, you have to get the hardware connections corrected. The NEO-6M is a 3.3V device, so you shouldn't connect it directly to the 5V Arduino. You *could* connect just the GPS TX to the Arduino, but you may not receive data reliably. Connecting an Arduino transmit pin to the GPS RX could damage the GPS module, as it is only rated for 3.6V **MAX**. It is best to "level-shift" between the two devices. You can use a few discrete parts (resistors + a diode, or resistors + FETs) or a level-shifting module. I recommend the latter, because they are cheap, and they also work for high-speed interfaces like SPI.

When you have level-shifting ready to add, move the GPS RX & TX connections to Arduino pin 9 (to GPS RX) and 8 (to GPS TX). This will let you use `AltSoftSerial` instead of `SoftwareSerial`. If you configure the NEO-6M to run at 9600 (that is the default), you could use NeoSWSerial on any two pins (besides 0 & 1 !!!). I'm not sure why your NEO-6M is running at 4800, unless you used the u-center utility to configure it permanently.

Finally, I would suggest trying my NeoGPS library. It is smaller, faster and more accurate than all other libraries, and it includes distance and bearing calculations that you might eventually need.

The Installation instructions guide you through several examples, after which you should try NMEAloc. NeoGPS also has a diagnostic program, and lots of tips on the Troubleshooting page. You can download it from the Arduino IDE Library Manager, under the menu **Sketch -\> Include Library -\> Manage Libraries**.

After going through those first examples, you should be ready to try your own sketch. Here is your sketch, modified to use NeoGPS and either `AltSoftSerial`, `NeoSWSerial`, or the built-in `Serial1` on a Mega2560, Leo or Due:

```
// Set up the GPS serial port (pick *one* of these choices)

//#include <AltSoftSerial.h>
//AltSoftSerial gps_port; // always 8 & 9 on an UNO

//#include <NeoSWSerial.h>
//#define rxPin 2
//#define txPin 3
//NeoSWSerial gps_port( rxPin, txPin );

#define gps_port Serial1  // for a Mega2560, Leo or Due

// Variables
#include <NMEAGPS.h>
NMEAGPS gps;
gps_fix fix;

#ifndef NMEAGPS_PARSE_GGA
  #error You must uncomment NMEAGPS_PARSE_GGA in NMEAGPS_cfg.h!
#endif

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

  gps_port.begin(4800); // 9600 is the default for NEO-6M

  //setup satellites signal
  pinMode(13, OUTPUT);

  // Turn off the led until a satellite signal
  digitalWrite(13, LOW);

  Serial.println( F("Waiting GPS data...") );
}

void loop() {
  while (gps.available( gps_port )) {
    fix = gps.read();  // a new fix structure has been parsed
    plot();
  }
}

/*
  This function organize the gps data received for printing in the serial monitor.
*/

void plot() {

  if (fix.valid.location) {
  // or if (fix.valid.status && (fix.status >= gps_fix::STATUS_STD)) {

    digitalWrite(13, HIGH); // Then there are satellites, the LED switch ON

    Serial.println();
    Serial.println( F("----------------------------------------------") );
    Serial.print  ( F("UTC Hour -> ") );
    if (fix.valid.time)
      Serial.println( fix.dateTime.hours );
    Serial.print  ( F("Latitude -> ") );
    Serial.println( fix.latitude(), 6 );
    Serial.print  ( F("Longitude -> ") );
    Serial.println( fix.longitude(), 6 );
    Serial.print  ( F("GPS status: 0=NONE; 1=EST, 2=TIME, 3=STD, 4=DGPS -> ") );
    if (fix.valid.status)
      Serial.print( fix.status );
    Serial.println();
    Serial.print  ( F("Number of satellites -> ") );
    if (fix.valid.satellites)
      Serial.print( fix.satellites );
    Serial.println();

    #ifdef GPS_FIX_HDOP
      Serial.print  ( F("Horizontal Dilution of Precision (x1000) -> ") );
      if (fix.valid.hdop)
        Serial.print( fix.hdop );
      Serial.println();
    #else
      #error You must uncomment GPS_FIX_HDOP in GPSfix_cfg.h!
    #endif

    Serial.print  ( F("Antenna altitude (m) -> ") );
    if (fix.valid.altitude)
      Serial.print  ( fix.altitude(), 2 );
    Serial.println();

    #ifdef GPS_FIX_GEOID_HEIGHT
      Serial.print  ( F("Geoid Separation (m) -> ") );
      if (fix.valid.geoidHeight)
        Serial.print  ( fix.geoidHeight(), 2 );
      Serial.println();
    #else
      #error You must uncomment GPS_FIX_GEOID_HEIGHT in GPSfix_cfg.h!
    #endif

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

  } else {
    // If no satellite connection
    digitalWrite(13, LOW); // Turn off the LED

    Serial.println();
    Serial.println( F("-----------------------------") );
    Serial.print  ( F("|--- Status -->") );
    if (fix.valid.status)
      Serial.print  ( fix.status );
    Serial.println();
    Serial.println( F(" |") );
    Serial.println( F("|----Waiting location----|") );
    Serial.println( F("-----------------------------") );
    Serial.println();
  }
}

```

Note: Using `#if` statements, it verifies the configurations in NMEAGPS\_cfg.h and GPSfix\_cfg.h. The Geoid Height field is not enabled in the default NeoGPS configuration.
> 2 votes

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


# Question
Title: What happens if device sends data to arduino over serial port (UART) and arduino is unable to read it
Suppose delay(10000) function is executed, so Arduino cannot do any other work.

> During this time if the other device sends the data to arduino what will happen ?

# Answer
> 2 votes
Depending on the memory available, between 16 and 256 bytes will be stored in a ring buffer. Any bytes that arrive after that will be just thrown away.

The reception code in the core is:

```
void HardwareSerial::_rx_complete_irq(void)
{
  if (bit_is_clear(*_ucsra, UPE0)) {
    // No Parity error, read byte and store it in the buffer if there is
    // room
    unsigned char c = *_udr;
    rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;

    // if we should be storing the received character into the location
    // just before the tail (meaning that the head would advance to the
    // current location of the tail), we're about to overflow the buffer
    // and so we don't write the character or advance the head.
    if (i != _rx_buffer_tail) {
      _rx_buffer[_rx_buffer_head] = c;
      _rx_buffer_head = i;
    }
  } else {
    // Parity error, read byte but discard it
    *_udr;
  };
}

```

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


# Question
Title: Java NetBeans sending value and receiving value from Arduino
This is my Java code to send a value to Arduino and a receiving value from Arduino. Can anyone tell where I made a mistake? I am able to send the value but can't receive a value from Arduino.

```
package hell;

import com.panamahitek.ArduinoException;
import com.panamahitek.PanamaHitek_Arduino;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class led extends javax.swing.JFrame
{
    PanamaHitek_Arduino Arduino  = new PanamaHitek_Arduino();
    private BufferedReader input;
    SerialPort serialPort;

    public led(){
        initComponents();
        try {
            Arduino.arduinoTX("com3", 115200);
        }
        catch (ArduinoException ex) {
            Logger.getLogger(led.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    public synchronized void serialEvent(SerialPortEvent oEvent)
    {
        System.out.println("lol 31");
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                System.out.println("lol 1.1");
                Scanner s = new Scanner(serialPort.getInputStream());
                int mes =Integer.parseInt( s.nextLine());
                System.out.println(mes);
                System.out.println("lol 1");
            } catch (Exception e) {
                System.err.println(e.toString());
                System.out.println("Syncronice ");
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            Arduino.sendByte(0);
        }
        catch(Exception ex){
            Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
        }
        System.out.println("led is off");
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            Arduino.sendByte(1);
        }
        catch(Exception ex){
            Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
        }
        System.out.println("led is on");
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new led().setVisible(true);
            }
        });
    }

    private javax.swing.JButton jButton1;

    try{
        Arduino.sendByte(1);
    }
    catch(Exception ex){
        Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
    }

    System.out.println("led is on");

    private javax.swing.JButton jButton2;
}

```

Here is my Arduino code, which receives a value from Java and prints it accordingly:

```
int val = 0;
int led = 8;

void setup() {
  Serial.begin(112500);
  pinMode(led, OUTPUT);
}

void loop() {
  if (Serial.available()>0) {
    val = Serial.parseInt();
    if(val == 1) {
      //Switch on the LED, if the received value is 1.
      digitalWrite(led, HIGH);
      Serial.println("Succesfully received.");
    } else if(val == 0) {
      //Switch off the LED, if the received value is 1.
      digitalWrite(led, LOW);
    }
  }
}

```

EDIT: There is no problem to controlling arduino via Java code, the problem is that I can't received message from Arduino to display in a Java.

# Answer
> 1 votes
You are writing a number as a single byte and expect it as a string on the other end.

Replace

```
val = Serial.parseInt();

```

with

```
val = Serial.read();

```

---
Tags: arduino-uno, serial, programming, java
---


# Question
Title: What is the difference between a 3 pin and 4 pin ultrasonic range sensor?
I am following a tutorial that uses an arduino and ultrasonic range sensor, it calls for a 3 pin module (Paralax 28015-ND) and I have a 4 pin module (http://www.electroschematics.com/wp-content/uploads/2013/07/HCSR04-datasheet-version-1.pdf). The 3 pin seems to have one signal pin (both input and output) and the 4 pin has two separate signal pins (a trigger and echo). How would I need to change the code and wiring if I am using the 4 pin? Here is the code from the tutorial:

```
     /* Ping))) Sensor

   This sketch reads a PING))) ultrasonic rangefinder and returns the
   distance to the closest object in range. To do this, it sends a pulse
   to the sensor to initiate a reading, then listens for a pulse
   to return.  The length of the returning pulse is proportional to
   the distance of the object from the sensor.

   The circuit:
    * +V connection of the PING))) attached to +5V
    * GND connection of the PING))) attached to ground
    * SIG connection of the PING))) attached to digital pin 7

   http://www.arduino.cc/en/Tutorial/Ping

   created 3 Nov 2008
   by David A. Mellis
   modified 30 Aug 2011
   by Tom Igoe
   modified again 02 Apr 2016
   by Randy Sarafan

   This example code is in the public domain.

 */

// this constant won't change.  It's the pin number
// of the sensor's output:
const int pingPin = 4;

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

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

  // 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(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, 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(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

```

# Answer
It's simple enough... instead of:

```
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

```

You would have

```
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);

```

(of course you have to define `echoPin` to be whatever pin you choose to connect `ECHO` to).

And to save processing time you can have all your `pinMode()` calls in setup since there is no need to change mode on the fly any more.
> 0 votes

---
Tags: sensors, code-review
---


# Question
Title: Connect my Arduinos to central server, despite different IP adresses
Community,

A team of friends just built, with an Arduino UNO, a system where one can open a door lock from the internet. The Arduino UNO has an Ethernet Module (ENC28J60). When the command prompts, the Arduino will let a solenoid receive 5v, which will open it and, therefore, open the door.

The novel thing is, this door-opening-arduino connects via the Internet to a central server, a webpage that 'centralizes' the door-opening process. So, in a certain URL, we'll get a screen which goes:

All these doors are in remote locations, connected to very different routers. Some of these routers will go **192.168.1.1**, whereas others will go with the **0.1** ending.

So far, my friend has hard-coded the internal IP address 192.168.1.143 for identifying the Arduino, so, he's given up on DHCP. Afterwards, he's chosen port 6560 to be the open port and connect the door to the Internet. (VPN is not a option).

So the public IP address and port 6560 are our way in into the door. This info is shared with his webpage, where commands can be given: 'open it'.

But with these hard-coding of the 1.143 IP and the router's different default addresses, we've had trouble. You know what I mean: sometimes, the whole code must be changed for our Arduino to connect to the router. Not even close to 'plug-n-play'.

My questions seems natural: how can we ensure the Arduino connects each time to the router, without any problems? Most devices just connect: an IP camera in these routers will connect, and will never care which IP address the router has given it. If the router resets, things will be fine, and connection will restart.

So, why not DHCP? As far as my understanding goes, a problem my friend mentioned that would happen if he chose to use DHCP would be the communication between his Arduino and his online server: 'how can I know which IP I should speak with in order to open the door? By choosing the .143, I know which would should be'. Another problem comes in with port forwarding. Apparently, by choosing the .143 and then using port 6560, we ensure that we can access via the Internet, because there's a standarized procedure: 'please open port 6560 for this IP'.

This is a bit cumbersome. Most devices just don't work this way. We want to be able to just plug it in, let our Arduino and the router get any IP, and by just opening port 6560, we're in. Pretty simple.

How can we ensure that:

* Our Arduino **just connects to the router**, and
* that **communication between our Arduino and the centralized server just flows**?

*Another friend suggested configuring each router so that a device with a certain MAC address (our Arduino) gets* this IP\* *and* this port forwarding. *But what if the default address is 192.168.0.1 (instead of 1.1), for example? wouldn't we be facing a problem?*

We're seeking a kind of plug-n-play thing, like most access control systems work. Hardware's ok, it's connection the thing that bugs us.

Any suggestions, advice, or plain responses are really welcome. I think we're just a step away from our commit, which is creating a reliable connection for these doors. It may be just a line of code, or a config trick. Thank you for your time.

**(you'll soon notice we're not that savvy on routing and switching, so If we got our premises completely wrong, don't hesitate to correct us)**

# Answer
Your problem is two-fold, and neither are easy for an Arduino to overcome.

First you have the problem that the router's internet-facing IP address is (unless you have a special arrangement with your ISP) liable to change at any time. You need to keep your sever up to date at all times with what that IP address is, and the only real way of doing that is for the router, or something behind the router, to connect with your server so it can update its IP address.

Secondly you have the port forwarding. The router has to know where to forward the port to. That means that either the IP address of the Arduino has to be static, or the Arduino has to somehow tell the router to do the port forwarding. The simplest method is just to allocate a static IP address as you have done. The alternative is to use UPnP to instruct the router "I need you to forward this port through to me" - assuming the router understands UPnP. The hardest part of that though is getting the Arduino to speak UPnP. I am not aware of any UPnP libraries for the Arduino.

So keep the static IP address for the Arduino, it is simplest. One thing to note with manually allocating an IP address though is that it is vitally important you allocate it *outside* the IP address range of the DHCP server. Otherwise it is possible that the DHCP server could then allocate the IP address to someone else, and you'd then get a conflict. Most routers allow you to choose the range of IP addresses so you may want to go in and check that the DHCP server isn't able to clobber the IP address you have chosen.

To help solve the first problem some routers provide a "DDNS" (Dynamic DNS) facility, whereby they will periodically connect to a DDNS service to update a DNS record with the public IP address of the router. Not all provide it and those that do usually only provide access to a couple of DDNS services, so check your router to see if it does support it and if there is a suitable one for your needs there. If there is you can configure that and then, instead of connecting to the IP address of your router for issuing commands you instead connect to the DDNS domain name allocated to your router.

However, there is one much simpler option that solves all the problems in one go: reverse the communications.

Instead of the server connecting to the router to forward the port through to the Arduino to issue a command, it is far simpler (though I will admit not as responsive) for the Arduino, from whatever IP address it happens to be on, to just connect to the server itself and ask it for any pending commands.

If you have the ability to run your own software on the server you could even create your own small TCP server which the Arduino connects permanently to. The server can then send commands down that TCP connection just as if you were working with an Arduino directly connected by serial.

In both those situations it doesn't matter what IP address your router is on. You don't need to do any port forwarding. The Arduino can be on any IP address on your network.

And further more you have more security - no one could connect to your Arduino through the internet and cause havoc.
> 1 votes

# Answer
I would use socket.io for this. Here is a goos presentation on this:

http://www.robojay.us/wp-content/uploads/2016/08/NRB-socket-io.pdf
> 0 votes

---
Tags: arduino-uno, ethernet, web-server
---


title: How do I accelerate a stepper motor?

text:
# Question
Title: How do I accelerate a stepper motor?
I have a 24BYJ48 stepper motor, and my main problem is that I cannot make it rotate quickly. I've understood that in order to achieve a high speed I must start at a low speed and carefully accelerate the motor to higher speeds.

I'm not quite sure how this acceleration ought to be done, though. My idea is to execute the control sequences with an initially long delay, and then decrease the delay between each time I change the sequence for the motor wires.

Below is the code I have written. When I run it, the motor accelerates for a little while, but then all of a sudden it just stops and makes a high pitched noise.

# Answer
> 2 votes
The basic technique is as you have tried to program. The time between stepper pulses if shortened to cause acceleration and lengthened to slow down. A real solution typically uses an "S" curve type acceleration profile that starts out with a slow ramp up to the acceleration rate and then as it nears the target rotational speed it slows the acceleration rate back down.

In your case you may be getting to the point where you have increased the acceleration rate too much and the motor cannot respond to it.

# Answer
> 2 votes
There are several things going on here....

1. If the load is purely inertial and small (~ equal to the rotor inertia), acceleration typical takes only a few steps. No need to drag it out. Try some different delays after the first step.
2. If you have a torque load (you are pushing something), at some point, during acceleration, the currents in the winding will be too small to generate the required torque. As the speed increases, the currents will decay, due to the motor back-EMF and inductance (which is very significant).
3. Sometimes, at particular speeds, step motors exhibit a dynamic instability. That is, they start hunting...faster, slower, faster, slower, etc. until the motor "stalls". The resistance seen by the motor, looking back into the drive circuit, is the key factor here. At high speeds, the current regulator runs out of voltage and the effective resistance drops...leading to instability.

So, do some experimentation!!!

---
Tags: motor
---


title: Avrdude fails at specific baudrates

text:
# Question
Title: Avrdude fails at specific baudrates
I'm seeing something very strange. If I run:

```
ard-reset-arduino /dev/ttyACM0;
/usr/share/arduino/hardware/tools/avr/bin/avrdude -C/usr/share/arduino/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:`pwd`/.build/main.ino.hex:i;

```

Avrdude uploads my sketch to an Arduino Uno just fine. However, if I change the buadrate to 57600, it fails with the error:

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

```

I've tried manually pressing the Arduino's reset button just before I upload, but there's no change.

Why is this happening? If I change it back to 115200 baud, it uploads fine...even though the sketch itself initializes the serial port to 57600.

# Answer
> 1 votes
Arduino bootloaders doesn't have any baud rate detection and baud rate is fixed (for the different boards there might be different baud rates)

Only Leonardo (and others with native USB) are almost idependent on baud rate except for 1200bauds used as "reset". (However it runs at maximum speed that the MCU can handle)

# Answer
> 3 votes
> If I change it back to 115200 baud, it uploads fine...even though the sketch itself initializes the serial port to 57600.

The bootloader is a piece of code designed to work at a specific baud rate. As KIIV said in his answer only the USB-based Arduinos would be relatively immune to changing the rate.

What your own code does, after being uploaded, is completely irrelevant.

> Avrdude fails at specific baudrates

Your title really should be: "Avrdude only **works** at one baudrate (the one it was designed to use for a specific board)"

---
Tags: arduino-uno, serial, avrdude, baud-rate
---


# Question
Title: Arduino Nano nRF24L01+ DFPlayer Mini SPI Problem
I'm working with an Arduino Nano board clone (CH340) on wireless control of DFPlayer Mini, transceiver sending a Struct variable with MachinePrefix (just in case), sound type (I have more folders by type of machines) and number of sounds.

The transceiver works fine, but the receiver doesn't. If I upload data into the Arduino, the DFPlayer plays the first song once (row 43 - myDFPlayer.play(1)), but after nRF24 init is not working.

After nRF24 init I'm still receiving data in valid format and range. If I comment out the nRF24 part, the DFPlayer is working, but together not. I read about working two devices on one SPI bus but I don't understand what's wrong. I think the problem is the same MOSI pin. In my opinion it should work but did not.

Any suggestions?

**Here is the code of receiver:**

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

RF24 myRadio (8, 9); // CE, CS
byte addresses[][6] = {"Sx001"};

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

struct dataStruct {
  short machinePrefix;
  short soundType;
  short soundNumber;
} dataReceived;

void setup() {
  mySoftwareSerial.begin(9600);
  Serial.begin(115200);
  delay(1000);
  Serial.println(F("RF24+dfplayermini-recever"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));
  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }

  Serial.println(F("DFPlayer Mini online."));
  myDFPlayer.setTimeOut(500);
  myDFPlayer.volume(5);  //Set volume value. From 0 to 30
  myDFPlayer.play(1);  //Play the first mp3
  //----------------------------
  delay(1000);
  myRadio.begin();  // Start up the physical nRF24L01 Radio
  myRadio.setChannel(108);  // Above most Wifi Channels
  // Set the PA Level low to prevent power supply related issues since this is a
  // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  myRadio.setPALevel(RF24_PA_MAX);
  myRadio.setDataRate(RF24_250KBPS);
  //  myRadio.setPALevel(RF24_PA_MAX);  // Uncomment for more power
  myRadio.openReadingPipe(1, addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now)
  myRadio.startListening();
  Serial.println(F("RF24 online."));
}//--(end setup )---

void loop() {  /****** LOOP ******/
  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }
  if (myRadio.available()) { // Check for incoming data from transmitter
    while (myRadio.available()) { // While there is data ready
      myRadio.read( &dataReceived, sizeof(dataReceived) ); // Get the data payload
    }
    Serial.println("loop");
    myDFPlayer.loop(3);
    if (dataReceived.machinePrefix == 11001) {
      Serial.println("same device prefix");
      int playingData = dataReceived.soundNumber;
      if (myDFPlayer.available()) {
        Serial.println("player available");
        Serial.println(myDFPlayer.readType());
        Serial.println(myDFPlayer.read());
      }
      myDFPlayer.play(2);
    }
    Serial.println(dataReceived.machinePrefix);
    Serial.println(dataReceived.soundType);
    Serial.println(dataReceived.soundNumber);
    Serial.println("-----------------------------");
  } //END Radio available
}//--(end main loop )---

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

```

# Answer
When using SPI, pin 10 should never be used as an INPUT. Otherwise the Atmega can go into SPI Slave mode. But you use pin 10 as the RX pin.

Just swap pin 9 and 10, and update your code accordingly.
> 2 votes

---
Tags: arduino-nano, spi, nrf24l01+
---