# Question
Title: C Serial Communication Code is unreliable
This going to be a difficult to debug problem but I hope some ppl here have C knowledge and idea what's going on. Given an arduino nano which is controlled by a C program from WRT54G.

Here is the relevant part of the arduino code:

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

 int integerValue=0;

                              // Max value is 65535
char incomingByte;

void loop() {
  if (Serial.available() > 0) {   // something came across serial
    integerValue = 0;         // throw away previous integerValue
    while(1) {            // force into a loop until 'n' is received
      incomingByte = Serial.read();
      if (incomingByte == '\n') break;   // exit the while(1), we're done receiving
      if (incomingByte == -1) continue;  // if no characters are in the buffer read() returns -1
      integerValue *= 10;  // shift left 1 decimal place
      // convert ASCII to integer, add, and shift left 1 decimal place
      integerValue = ((incomingByte - 48) + integerValue);

    }
   Serial.print("Command: ");
   Serial.println(integerValue);

  }
}

```

Pretty straight forward (it converts serial received ascii chars to numeric format), arduino receives a simple integer and it runs a function. For example 1-\> turn on relay1. This work's reliably for sure because I can just do:

```
echo "1" > /dev/tts/1

```

from the terminal.

Now here is the relevant part of the C code:

```
    int serialport_read_until(int fd, char* buf, char until, int buf_max, int timeout)
    {
        char b[1];  // read expects an array, so we give it a 1-byte array
        int i=0;
        do {
            int n = read(fd, b, 1);  // read a char at a time
            if( n==-1) return -1;    // couldn't read
            if( n==0 ) {
                usleep( 1 * 1000 );  // wait 1 msec try again
                timeout--;
                continue;
            }
    #ifdef SERIALPORTDEBUG
            printf("serialport_read_until: i=%d, n=%d b='%c'\n",i,n,b[0]); // debug
    #endif
            buf[i] = b[0];
            i++;
        } while( b[0] != until && i < buf_max && timeout>0 );

        buf[i] = 0;  // null terminate the string
        return 0;
    }

    /* Only use integer commands */
    int serialport_write(int fd, int comm_no)
    {
        char command[6];

        sprintf(command,"%d\n",comm_no);
        printf("Sending Command:%s",command);

        int len = strlen(command);
        int n = write(fd, command, len);
        if( n!=len )
            return -1;
        return 0;
    }

void *ardu_handler(void *fdfd)
{
  int fd = *(int*)fdfd;
  char buf[256];
  char getback[10];

  while (1)
   {
     memset(buf, 0, sizeof(buf));
     serialport_read_until(fd, buf, '\n', 256, 5);
     fprintf(stderr, "Received: %s\n", buf);
   }
}

```

Then a C thread will be started with the ardu\_handler which in this case doesn't do anything else just print's back the response from the ardu.

What's happening is when I send a command I start getting back infinite amount of commands (up until I close the C app and start it again) and to make it worse it is even inconsistent.

For example:

```
Command: 62143
Command: 7891
Command: 3216
Command: 11287
...
runs forever.

```

What I asking myself is whether these *responses* coming out from the arduino or they are just coming out from the bogous C program... It's not possible to connect to see what's coming out on the serial port unfortunately until this program holds the port open.

Although I run the C code on mips this was doing the same thing back on x86 PC with an arduino uno (sometimes it is stable but then it falls into this unstable state and floods the serial port). It was unreliable and I would like to make it reliable.

# Answer
I recommend you change the type of `incomingByte` to `int`, like was advised in the comments. Also, your null-termination is occurring past the end of `buf`; change the condition in the `while` statement to `i < buf_max - 1`, so that one byte is left for the `null`. Also use parentheses to separate those conditions, in the unlikely event there's some issue of precedence.
> 1 votes

---
Tags: serial, arduino-nano
---


title: ACS712 sensor reading for AC current

text:
# Question
Title: ACS712 sensor reading for AC current
I'm trying to track down a clearly/simply articulated piece of code to take a reading from the ACS712 current sensor (link to download PDF data sheet).

I understand that these sensors are noisy, and that reading AC current is quite different to DC current.

After looking at a range of examples in a variety of forums etc., I've based the following on http://henrysbench.capnfatz.com/henrys-bench/acs712-arduino-ac-current-tutorial/

```
void ac_read() {
  int rVal = 0;
  int maxVal = 0;
  int minVal = 1023;
  int sampleDuration = 100; // 100ms

  uint32_t startTime = millis();
  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0);
    if (rVal > maxVal)
      maxVal = rVal;

    if (rVal < minVal)
      minVal = rVal;
  }

  // Subtract min from max to determine the peak to peak range
  // 1023 = the max value we'll get on the input (1024, zero indexed)
  // 5.0 = 5v total on adc input
  double volt = ((maxVal - minVal) * (5.0/1023.0));

  // div by 2 is to calculate RMS from peak to peak
  // 0.35355 is factor to calculate RMS from peak to peak
  // see http://www.learningaboutelectronics.com/Articles/Voltage-rms-calculator.php
  double voltRMS = volt * 0.35355;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = voltRMS
  double ampsRMS = (voltRMS * 1000)/100;
  Serial.println(ampsRMS);
}

```

I unfortunately don't have sufficient test equipment at present to validate this, but I'm getting a value of around 8.9 for a 2300W device, which afaict is roughly accurate (based on this calculator http://www.rapidtables.com/calc/electric/Watt\_to\_Amp\_Calculator.htm).

Is anyone able to confirm the above makes sense/is logical/sane? Is there anything obviously incorrect?

# Answer
> 4 votes
Measuring the peak-to-peak current and scaling the result will get you an answer which will at least go up and down with the magnitude of your average AC current, so yes it is NOT incorrect. As you suggested it will be sensitive to noise from the sensor - in fact as you are taking the highest and lowest single readings the noise will always cause the measurement to be higher than actual.

However, I think you could do better. Given that the code is already having to take many samples (basically as fast as it can) for 100mS (which will sample 5 cycles of the waveform if it is 50Hz and 6 if it is 60Hz, depending on where you are in the world), then you could actually do the maths to measure the RMS value and by basing this on all of the signal the effect of the noise will be reduced.

You need to know the ADC reading when there is no current `rZero` (which should be around 511 but could be off a bit due to offset errors) - you could measure this with nothing connected to calibrate the sensor, or take a long term average even with the AC signal present.

As the henrysbench tutorial points out it is important that the Arduino samples the signal at a high enough frequency (say 1000Hz - hence 100 samples for your 100mS sample duration)- the count of the number of times that the while loop executes `sampleCount` will confirm if this still the case even with the extra computation time of this code.

Also if you increase the sample time please be careful that the `unsigned long rSquaredSum` can't overflow, but I would avoid use of doubles within the while loop as they will definitely slow it down a LOT.

```
void ac_read() {
  int rVal = 0;
  int sampleDuration = 100;       // 100ms
  int sampleCount = 0;
  unsigned long rSquaredSum = 0;
  int rZero = 511;                // For illustrative purposes only - should be measured to calibrate sensor.

  uint32_t startTime = millis();  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0) - rZero;
    rSquaredSum += rVal * rVal;
    sampleCount++;
  }

  double voltRMS = 5.0 * sqrt(rSquaredSum / sampleCount) / 1024.0;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = 10 * voltRMS
  double ampsRMS = voltRMS * 10.0;
  Serial.println(ampsRMS);
}

```

---
Tags: sensors, current, electricity
---


# Question
Title: What is the Maximum Current an Arduino can Supply?
I was wondering how much my Arduino I/O pin can output when it is set at **Output** and is at **High**.

I am using an **Arduino Uno R3**.

Thanks in Advanced.

# Answer
40.0mA.

The Arduino UNO Digital IO pins are connected directly to the IO pins on the ATMEGA328P processor.

From page 299 of the data sheet for that processor...

Note that there is also a total current limit for all output pins combined, and that the voltage starts to drop as the current goes up.
> 6 votes

---
Tags: current, input
---


title: Store String using F() Macro

text:
# Question
Title: Store String using F() Macro
I'm new to the Arduino and do not quite understand the `F()` macro yet.

In my code, I have a `String`, and as I want to transfer it via WebServer, I need to write it to the answer.

Somehow I need to convert the `String`, to fit it into the `fastrprintln()` function.

```
String weather_json = getWeatherData();
char weather[2048];
weather_json.toCharArray(weather,2048);
client.fastrprintln(F(weather));

```

Do you have any idea for me?

# Answer
The Arduino core macro F() takes a string literal and forces the compiler to put it in program memory. This reduces the amount of SRAM needed as the string is not copied to a data memory buffer. Special functions are required to access the data stored in program memory. The Arduino core hides a lot of the typical usages such as:

```
Serial.println(F("Hello world"));

```

Further details of the low level access program memory access may be found in the AVR GCC libc documentation. The F() macro is defined as:

```
class __FlashStringHelper;
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper*>(PSTR(string_literal)))

```

The FlashStringHelper class is used to help the compiler recognize this type of string literal when passed to Arduino functions. Below are some examples:

```
// String constructor with program memory string literal
String::String(const __FlashStringHelper *str);

// Print (Serial, etc) of program memory string literal
size_t Print::print(const __FlashStringHelper *);
size_t Print::println(const __FlashStringHelper *);

```

You should not use the Arduino core F() macro with anything other than a string literal.
> 11 votes

---
Tags: memory-usage
---


# Question
Title: Modbus master arduino code is throwing weird errors on upload
I am using the following https://code.google.com/p/simple-modbus/ arduino master library code. In order to communicate with my industrial drive.

All seems right but I am getting some weird errors. I am using the arduino master code as it is. With just the difference in modbus\_construct.

Here is the error I am getting

```
 This report would have more information with
 "Show verbose output during compilation"

enabled in File > Preferences.
Arduino: 1.0.6 (Windows 7), Board: "Arduino Uno"
In file included from SimpleModbusMasterArduino.ino:29:

C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:131: error: expected ',' or '...' before numeric constant
In file included from C:\Program Files\Arduino\hardware\arduino\cores\arduino/HardwareSerial.h:28,
                 from C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:215,
                 from SimpleModbusMasterArduino.ino:29:
C:\Program Files\Arduino\hardware\arduino\cores\arduino/Stream.h:57: error: expected ',' or '...' before numeric constant
In file included from SimpleModbusMasterArduino.ino:29:
C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:222: error: expected ',' or '...' before numeric constant
SimpleModbusMasterArduino:37: error: 'Packet' does not name a type
SimpleModbusMasterArduino.ino: In function 'void setup()':
SimpleModbusMasterArduino:45: error: 'packets' was not declared in this scope
SimpleModbusMasterArduino:45: error: 'READ_HOLDING_REGISTERS' was not declared in this scope
SimpleModbusMasterArduino:45: error: 'modbus_construct' was not declared in this scope

```

SimpleModbusMasterArduino:49: error: 'modbus\_configure' was not declared in this scope SimpleModbusMasterArduino.ino: In function 'void loop()': SimpleModbusMasterArduino:56: error: 'modbus\_update' was not declared in this scope

Here is my code:

```
#include <SimpleModbusMaster.h>

/*
   The example will use packet1 to read a register from address 0 (the adc ch0 value)
   from the arduino slave (id=1). It will then use this value to adjust the brightness
   of an led on pin 9 using PWM.
   It will then use packet2 to write a register (its own adc ch0 value) to address 1
   on the arduino slave (id=1) adjusting the brightness of an led on pin 9 using PWM.
*/

//////////////////// Port information ///////////////////
#define baud 115200
#define timeout 1000
#define polling 200 // the scan rate
#define retry_count 10

// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 2
#define LED 13

// The total amount of available memory on the master to store data
#define TOTAL_NO_OF_REGISTERS 8
#define TOTAL_NO_OF_CONSTANTS 1

// This is the easiest way to create new packets
// Add as many as you want. TOTAL_NO_OF_PACKETS
// is automatically updated.
enum
{
  PACKET1,
  //PACKET2,
  TOTAL_NO_OF_PACKETS // leave this last entry
};

// Create an array of Packets to be configured
Packet packets[TOTAL_NO_OF_PACKETS];

// Masters register array
unsigned int regs[TOTAL_NO_OF_REGISTERS];

void setup()
{
  // Initialize each packet
  modbus_construct(&packets[PACKET1], 1, READ_HOLDING_REGISTERS, 0x3000, 8, 0);
  //modbus_construct(&packets[PACKET2], 2, READ_HOLDING_REGISTERS, 0x3000, 8, 16);

  // Initialize the Modbus Finite State Machine
  modbus_configure(&Serial, baud, SERIAL_8N2, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);

  pinMode(LED, OUTPUT);
}

void loop()
{
  modbus_update();
  Serial.println(regs[0]);
  //regs[0] = analogRead(0); // update data to be written to arduino slave

  //analogWrite(LED, regs[0]>>2); // constrain adc value from the arduino slave to 255
}

```

# Answer
> 1 votes
Your issue is that you define constants, such as `timeout`, which are widely used in Arduino library as parameter names. After preprocessing your definitions, correct code in "Arduino.h" such as

```
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout);

```

becomes

```
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long 1000);

```

No wonder the latter line fails to compile.

You will need to find unique names for your defines, or use constant variables instead.

---
Tags: rs485, modbus
---


# Question
Title: W5100 Ethernet shield DHCP fails with a Switch
we are using Arduino W5100 Ethernet shield. The code is to try DHCP first and if that fails, then try the static IP. we do the Ethernet Initialization and stop every time. The library is Arduino Ethernet library.

1. when we try with a wireless router, everything works and we are able to contact our web server.
2. Now the wireless router is connected to a switch. switch \<======\> router \<=====\> W5100

if we try to send data using the switch directly, DHCP fails, whereas a laptop using the same cable works.

Question is, even Arduino Library has DHCP functionality, why should a laptop work where the shield is failing? The network and topology and rules should be same for both the laptop and W5100 shield. Anything we can do to debug this issue more?

Edit1 : - Switch which we are using is L3 in nature.

Below is the code which we are using at present.

```
    while(1) {

        KDEBUG("wait 10 seconds...\r\n");
        // wait 10 seconds
        for(loop = 10; loop > 0 ; loop--) {
            wait_millis(1000);
        }

        KDEBUG("Try transmitting data on ethernet...\r\n");
        transmit_data();

    }

    return 0 ;

}

void wait_millis(uint16_t num) {

    for(; num > 0 ; num-- ) {
        _delay_ms(1) ;
    }

}

// transmit data using Ethernet
static uint8_t transmit_data() {

    char request[256];
    uint8_t status = 0  ;

    // reset counter
    counter = (counter > 254) ? 0 : counter ;

    memset(&request[0], 0 , sizeof(request));
    memset(&bencode[0], 0 , sizeof(bencode));

    wait_millis(5000);
    // try DHCP
    if (Ethernet.begin(mac_address) == 0) {
        KDEBUG("Failed to configure Ethernet using DHCP \r\n");
        // use static IP. no return code.
        Ethernet.begin(mac_address, ip_address);

    } else {
        KDEBUG(" Got lease from DHCP \r\n");
    }

    // wait for ethernet to initialize:
    wait_millis(5000);

    // we got a connection?
    status = client.connect(server, port) ;
    KDEBUGF("ethernet client  status= %d \r\n", status);
    if(!status) {
        goto quit ;
    }

        KDEBUG("connected \n");
    // create an HTTP request
    strcat(request, "GET /api/gl868.php?data=");
    strcat(request,bencode);
    // 12 chars
    strcat(request," HTTP/1.1 \r\n");
    // 25 chars
    strcat(request,"Host: ");
    strcat(request,server);
    strcat(request," \r\n");

    // send GET request
    client.println(request);
    _delay_ms(1);
    client.println() ;

    wait_millis(1000);
    client.stop();
    wait_millis(1000);

    if(client.connected()) {
        client.stop();
    }

    return 1 ;

quit:

    wait_millis(100);
    if(client.connected()) {
        client.stop();
    }

    return 0 ;

}

```

# Answer
> 1 votes
A certain way to debug this is to use `tcpdump` to capture network packets from both Arduino and your laptop and check the differences. I would start by looking for `DHCPDISCOVER` packet that Arduino should be sending.

A simpler way would be to check DHCP server logs to see how the communication looks like from server's perspective. Here, you should be looking for lines which have the MAC address of your Arduino shield. The success of this approach will depend of the verbosity of the DHCP server you're using.

# Answer
> 1 votes
If I understand your connection...

* Device over wifi to router works.
* Wired, via a switch to router does not?

DHCP is clearly switched on for WLAN, is it switched on for LAN?

Personally I always use fixed IP for such projects, with a default value that can be reset so that I can always find my device. I change the IP (and/or MAC) via a serial monitor.

---
Tags: ethernet, networking
---


# Question
Title: Power Supply Problem with Arduino Yún: Using a long USB cable
I want to use an Arduino Yún as a kind of outdoor weather station. I want to supply the power for the Yún with a 5V USB-Charger. Using a normal USB cable everything works fine. But as the weather station shall be far from the next power socket, I made the USB cable about 10 meters longer. Now the Yún does not power up any more.

Has anybody an idea why?

Should I use a 12 V power supply and a 7805 power converter instead?

# Answer
> 4 votes
The USB specification limits the length of a cable between two devices to 5 meters. When you make a longer cable, you're going out of spec, which means it is not guaranteed to work anymore.

Since you're only supplying power, the issue is (as you have guessed) the voltage drop in the cable. However, the voltage drop will depend on how much current Arduino is consuming at any given moment. Supplying it with a higher voltage without a converter is dangerous, because it will lead to overvoltage you won't be able to control.

I'd suggest trying better cables first: thicker and stiffer cables have thicker wires, and may have less voltage drop. You can also make your own cable (provided you can solder) using only two thick wires for power.

The ultimate solution, like you said yourself, is to deliver higher voltage over the wire (12V would do) and install a power converted (12V to 5V) near your Arduino. That way, the voltage drop in 5V line will be small, and the voltage drop in 10m 12V line will be compensated by the converter. Actually, the intermediate voltage may be higher: you can simply drop a mains line (220V or whatever you have) to your weather station and place the same USB charger near the Arduino.

---
Tags: power, arduino-yun, usb
---


# Question
Title: Not sure if logic analyzer shows an error or perhaps just a 'relay bounce'
I have an Arduino controlling a relay. I was taking a look at the timings using a logic analyzer and at the onset of the relay switching, it quickly switches again.

This seems to be occurring randomly and I thought it could be highlighting a problem with my code but I wondered if it might just be a 'relay bounce' due to the speed of the switch. I've attached an image below. Any feedback is greatly appreciated. Thanks.

# Answer
> 2 votes
According to your plot, the pulse length is 50 microseconds. Typical mechanical relay switching time is 10 milliseconds, which is 200 times longer. It's next to impossible that the pulse is due to your software powering the relay back on for a moment, since the relay simply could not react to such a short input pulse.

So yeah, it's just a bounce. You can safely ignore it in most cases, unless you're counting events or doing something similar. In the latter case, there are both hardware and software debouncing techniques, which share the basic idea of a low-pass filter.

---
Tags: relay
---


title: ESP8266 Returns 'invalid' - Cause 4

text:
# Question
Title: ESP8266 Returns 'invalid' - Cause 4
I have tried to get the Ai-Thinker ESP8266 working at all. If you hook it up to an Uno you have garbage returned no matter what the baud rate is. Tried softwareSerial on D3 and D4 (switching pins doesn't help) and over D0 and D1 with no sketch (to send AT commands directly to the device because softwareSerial wasn't working).

I'm using a logic converter from 5v to 3.3v to handle the voltage correctly.

I also know for a fact you can do that. I've done it a bunch with Bluetooth. HC-05.

NOTE: Pins in the wrong order won't return anything, in order to get garbage it needs to be wired correctly.

I also have a FTDI module that functions as another passthrough unit for this. It has a jumper for 3.3v to 5v and will stay on 3.3v as these units are unable to handle 5v.

I used PuTTY in order to view the boot information of this chip. On boot it returns this information.

So here's my issue.

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

wdt reset
load 0x40100000, len 816, room 16
tail 0
chksum 0x8d
load 0x3ffe8000, len 788, room 8
tail 12
chksum 0xcf
ho 0 tail 12 room 4
load 0x3ffe8314, len 288, room 12
tail 4
chksum 0xcf
csum 0xcf

2nd boot version : 1.2
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size : 4Mbit
jump to run user1

sd▒C▒
Ai-Thinker Technology Co. Ltd.

invalid

```

At the end of the day this invalid line means that the wifi information (from what I understand) is corrupted. It also refreshes this information over and over and WILL NOT accept AT commands so I can't seem to chase it down.

I am afraid that by attempting to update it if this kind of issue happens it will be bricked.

Both of these modules are opened today and I have tested another 8266 with similar results.

Any help would be appreciated.

# Answer
> 1 votes
Alright so I figured it out. Thanks to user Butters for pointing me in the right direction.

The Arduino Uno DOES NOT have enough power to handle the ESP8266 itself. It needs a power source using a 5v to 3v stepdown chip. The 3v3 rail doesn't handle it by itself.

# Answer
> -1 votes
I don't know what this "invalid" means I am getting this on every boot but my device is working fine. I have tested downloading webpages and it's working. So maybe just ignore this. use cutecom it works there, didn't work in minicom maybe because of carriage return absent.

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


# Question
Title: Nothing is working even though every thing is right & it is new?
I have bought a new 'SunFounder Arduino uno R3' and started learning, the first lesson was 'Blinking LED' of course.

I have done it all, connected Jumper-Wires and the Sensor and the LED light, I wrote the code:

```
const int ledPin = 9;
void setup()
{
   pinMode(ledPin,OUTPUT);
}
void loop()
{
   digitalWrite(ledPin,HIGH);
   delay(500);
   digitalWrite(ledPin,LOW);
   delay(500);
}

```

BUT NOTHING HAPPENS !!!, I checked out every thing over and over, it just does not work ??? Every thing is well about the board and the UNO R3 it is new. I have checked the code and the connections and checked the Device Manager to know that the serial port of the arduino is 'COM3'... I dont know what is wrong with it ?!!

# Answer
> 2 votes
In these cases it helps to break down the problem in pieces.

If the internal LED on pin 13 blinks with your code it means that the software side is OK so far (code, Arduino type, compiling, uploading etc), so I suggest looking at the physical side of things.

Do you have a multimeter available? If so, connect it between pin 13 and ground and it should show you if the output works.

Finally, is the LED working? When you connect it between 5V and GND (with a resistor!) it should light up.

---
Tags: arduino-uno
---


# Question
Title: Module and library for self healing large sensor network
I have to build a wireless sensor network with arduinos on my project. It does not need to be a mesh network, but it needs to have self healing capabilities.

I would like to use something cheaper than XBees. I tried the NRF24L01 with maniacbug's, TMRh20's and MySensors' libraries. However they aren't solving the problem and I'm wasting a ton of time trying to figure out how to make them work.

Another thing, I need a lot of repeater nodes between the base and the sensors because the office is 2 km far from the monitoring area and some of these libraries have a limitation of 5 level deep network, so I'd have max 4 repeaters between the base and sensor, which is bad.

And the last, my project is going to be fine with 15 sensors for now, but it'll have 500-1000 nodes in a couple of months and most of these libraries assign 8 bit addresses (256 nodes), which does not cover that amount of nodes.

What do you suggest?

# Answer
A few thoughts:

1. For ~$20 per unit, the 1mW Digimesh modules will take care of reliable mesh networking plus provide a high degree of configurability and scalability. Depending on the budget for your sensor nodes this might be better than "wasting a ton of time" messing with bare-bones hardware and third party code.
2. Constrain the mesh network within the "monitoring area" and set up dedicated point-to-point links (with higher power and directional antennae) between it and your office. Set up two or three if you want redundancy.
3. If you can't afford better hardware but have time to spare, consider reading up on mesh protocols and implementing one you think best fits your project. Many of them are reasonably simple if you are not pushing for maximum efficiency or performance.
> 2 votes

---
Tags: sensors, arduino-nano, nrf24l01+, rf, networking
---


title: Automatic/manual door lock with servo

text:
# Question
Title: Automatic/manual door lock with servo
I'm building an automatic door lock, which is moved by a servo ( this one ). However, I want to still make it possible to open the lock manually, but it's not possible if the servo is attached to the lock mechanism.

Do you have ideas on how to go around this problem?

Here's a diagram of the lock mechanism

# Answer
> 1 votes
So it's actually the worm gear that is causing your problem, since that can't be reverse driven by the cogs.

The simplest option, I think, would be to have the middle cog normally separated from the worm gear and only re-engage it when you need to drive the mechanism with the servo. You could maybe use a second servo to move it into the right place, or maybe a solenoid, or something along those lines. Have it slide along a short track or slot with a spring to ensure it disengages when the solenoid is released.

---
Tags: servo
---


# Question
Title: How has Arduino been used in the classroom?
I remember seeing Primo, this robot that is based on Arduino and serves to teach kids to program. My interest in the platform comes from there, but it is always nice to learn about other cool applications.

What other applications are there that utilise Arduino for K-12 education?

# Answer
I've used Sparki from Arcbotics as a robotics platform. It's uses Arduino Sketch to program and a modified Arduino IDE.

Sensors for line following , edge detection, distance and light level sensing are built in. Also the creators are focused on education so the material and projects are teaching oriented.

The Community seems pretty active and engaged too so the material should build over time.
> 2 votes

# Answer
We have been using Arduino's to teach basic microcontroller concepts in classes focused on environmental monitoring & instrumentation, rather than just electronics:

An Arduino UNO based Datalogger for the Classroom

The IDE abstracts away enough of the low level details that you can get students into programming quickly, while still exposing them to enough of hardware side of things. I am not sure what other platform would let us take true beginners so far, so quickly.
> 1 votes

---
Tags: project
---


# Question
Title: Compute yaw from magnetometer and accelerometer
I use an Arduino and a 9 DOF sensor (gyroscope, accelerometer and magnetometer) and I'm trying to use the pitch, roll and yaw that the sensor gives me to rotate an object in unity.

I managed to correctly compute pitch and roll (the z and x axis in unity) from the accelerometer but it seems that I can't get the Yaw right. By that I mean that when I rotate my sensor pitch or roll it rotates my yaw too, in a weird way.

---

*Code in the arduino to get the heading*

```
void getHeading(void)
{
  heading=180*atan2(Mxyz[0],Mxyz[1])/PI;
  if(heading <0) heading +=360;
}

void getTiltHeading(void)
{
  //float pitch = asin(-Axyz[0]);
  //float roll = asin(Axyz[1]/cos(pitch));
  float pitch = atan( Axyz[0] / sqrt( Axyz[1] * Axyz[1] + Axyz[2] * Axyz[2] ) );
  float roll = atan( Axyz[1] / sqrt(Axyz[0] * Axyz[0] + Axyz[2] * Axyz[2]));

  float xh = Mxyz[0] * cos(pitch) + Mxyz[2] * sin(pitch);
  float yh = Mxyz[0] * sin(roll) * sin(pitch) + Mxyz[1] * cos(roll) - Mxyz[2] * sin(roll) * cos(pitch);
  float zh = -Mxyz[0] * cos(roll) * sin(pitch) + Mxyz[1] * sin(roll) + Mxyz[2] * cos(roll) * cos(pitch);
  tiltheading = 180 * atan2(yh, xh)/PI;
  if(yh<0)    tiltheading +=360;
}

```

*Pitch and roll*

```
    float _Pitch  = (float)(180 / Math.PI * Math.Atan( m_ResultX / Math.Sqrt( m_ResultY * m_ResultY + m_ResultZ * m_ResultZ ) ) );
    float _Roll = (float)(180 / Math.PI * Math.Atan(m_ResultY / Math.Sqrt(m_ResultX * m_ResultX + m_ResultZ * m_ResultZ)));
    float _Yaw = (float)(m_TiltHeadingResult);

```

Don't hesitate to ask for details.

# Answer
> 3 votes
I don't know how all your sensor's axis are lined up, but it looks like you should level the magnetometer readings by rotating them by `-pitch` and `-roll` to get back to the global reference frame, instead of rotating the magnetometer readings by the positive angles.

However, The pitch and roll angles in the code are both relative the horizon, not a set of euler angles that define a rotation between two states; because of this, they do not compose to rotate the magnetometer back into the global xy frame like I assume the equations are trying to do. The code is also only using `atan` for pitch and roll instead of `atan2`, so their range is only 180 degrees.

You need to make sure the rotation matrix you multiply your magnetometer reading by is based on the same conventions as the equations you use to get pitch and roll from the accelerometer, and that it cancels the observed rotation.

To do this correctly, I recommend you read into euler angles. You might also try searching around for a good library that handles 9-DOF sensor fusion for you.

---
Tags: sensors, algorithm
---


title: Arduino recieving binary

text:
# Question
Title: Arduino recieving binary
I was wondering if Arduino digital pin can receive binary data. For example, I might want one Arduino to send another Arduino a binary code. If the code is `01` it would turn a red led on, if it was `11` it would turn green on, etc. I would like to do this so that I don't have to use a lot of digital pins. Is this possible with Arduino or not?

# Answer
Pretty much anything is possible.

There is a method known as *bit banging* which toggles a generic IO pin to create a protocol, and read changes on another generic IO pin to read in the data of a protocol.

The trick is in creating a protocol.

Fortunately that has all been done for you - the SoftwareSerial library. It will create a bit banged version of the RS232 serial protocol using any combination of IO pins to transfer data between devices.
> 2 votes

# Answer
As Majenko says, it is easily possible to implement using bit banging. Assuming that you want to write your own protocol, you need to distinguish between the end of one data packet and the start of another. This could be done by having all of the packets the same length (as in your example with length 2) or using a form of Huffman coding where only the external nodes of the state tree are results so you know when a full packet has been received.

Using a standard serial or I2C protocol would also work. With serial you would be able to communicate via a serial emulator on a USB port so you could test with a computer.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How would I use Arduino microcontroller separately?
I'm learning Arduino. I use Arduino Uno board with ATMEGA328-PU. I tried basic codes like LED blink, control of DC motor etc. Arduino board is used only when we program microcontroller, right? I mean, when we finish programming it, we can use microcontroller separately? If it can be used separately, we must have some "external" circuit as replacement for Arduino board, which allow us to use microcontroller in specific application. What type of circuit is used? I'm new in this field so don't blame me because of amateur questions.

# Answer
> 4 votes
Assuming you are going to upload the program into the ATmega328 on the Arduino, then take the ATmega328 out of the socket, and use it in your circuit, then a simple answer is to search for "minimal Arduino circuit"

An example returned by that search is "From Arduino to a Microcontroller on a Breadboard".

It lists:

* a 16 MHz crystal,
* a 10k resistor, and
* two 18 to 22 picofarad (ceramic) capacitors

That is enough to run the chip at the same speed as the Arduino, *and* the code used on the Arduino to initialise its clock will work unchanged.

This should run okay directly from a battery supply of about 4.5V or 4.8V, or a good 5V power supply.

A better circuit, which runs at the same 16MHz speed as the Arduino is 'Shrimp It'. That shows a similar minimal circuit and a better 'protected' circuit which has a more reliable approach for its power supply. This is all you need to run off a 4.5V (e.g. 3 1.5V) battery power supply.

However, if you don't care about running at 16MHz, you could ditch the crystal and capacitors, and use the internal 8MHz oscillator, that will need the code to be slightly different. For example, the 8MHz clock is 1/2 the speed of the Arduino's standard 16MHz, so code like `delay()` will take 2ms instead of 1ms.

Further, the RESET button can be set up so it doesn't need the 10k pullup.

So, with some software changes (search the web for details), an ATmega328 could be used with **no** external components.

Alternatively, you might want to use a better power supply, for example a voltage regulator with the circuit of the protected 'Shrimp It', *and* be able to load the program onto the ATmega while on its board.

There are products which bundle that 'standard' set of parts (voltage regulator, plugs and sockets and protected 'Shrimp It' running exactly like an Arduino at 16MHz) with a very compact PCB. They are able to plug directly into a breadboard, and so can be used with veroboard/stripboard (or a PCB) to make the rest of the circuit.

One is a kit called 'Boarduino'from adafruit. That web site gives some details to sow how to do this yourself. It is a convenient-to-use version of the 'Shrimp It', on a compact PCB.

An alternative kit is the "Really Bare Bones Board (RBBB) kit". However it is available as the PCB only, which is the "Really Bare Bones board (RBBB)", though the same supplier as the RRRB kit.

Neither Boarduino nor RRRB has on-board USB upload circuit. However, you can use your Arduino to do that, for example "Using an Arduino as an AVR ISP (In-System Programmer)". Or you could buy a USB to UART cable.

# Answer
> 2 votes
Look at the schematics and see which bits you don't need. Leave those out and what's left is what your require. You then would need to design a circuit board for these parts.

Now, who *should* we blame for your amateur questions? ;^)

# Answer
> 2 votes
There are two approaches to this. One is to simply use the Arduino Uno board in your final product! However, if you're making a large number of boards, it may be more cost efficient to develop a custom board with only the features you need. It may be nothing more than a few GPIO pins and a power regulator!

Another thing which can be important in these final products, no matter what board you are using, is that you can permanently burn your program into memory so that it always starts up when power is applied.

# Answer
> 1 votes
> Arduino board is used only when we program microcontroller, right?

Not necessarily. The Arduino board is useful not only for programming, but because it provides required peripheral circuitry such as power regulation, USB-serial interface, convenient headers, and a crystal.

However, it is perfectly fine to use the Arduino board to program your ATmega328 and then take it out and use it in another circuit.

> If it can be used separately, we must have some "external" circuit as replacement for Arduino board, which allow us to use microcontroller in specific application. What type of circuit is used?

All the ATmega328 really needs is a stable power supply. If you're alright running it at 8MHz, you don't need an crystal. If you don't need in-circuit programming, you don't need an ISP connection or any USB-serial stuff.

For more powerful microcontrollers, you might require clock generation circuitry, multiple power rails, debug/programming connections, etc.

# Answer
> 1 votes
See this page on how to put an ATMega329 chip on a breadboard and have it run. I think this will explain things: https://www.arduino.cc/en/Main/Standalone

---
Tags: atmega328
---


title: Print to console

text:
# Question
Title: Print to console
I am trying to get the string ("Enter an Integer : ") to print to the serial, then have the user enter a string of numbers which is then converted to an array of chars then ints.

The problem is the string will not display on the serial monitor when opened, and when the numbers are entered by the user, and the conversion is done I need the string to be displayed again. So when the user inputs a number and presses enter it should be the end of that conversion, and prompt a new one.

Code below:

```
int convert(void) {
  while (Serial.available() > 0) {
    char ch = Serial.read();
    if (ch >= '0' && ch <= '9' || ch == '-') {
      // Collect digits, only works if minus is first.
      strValue[index] = ch;
      index++;
    } else {
      strValue[index] = '\0';
      blinkRate = atoi(strValue);
      Serial.println(blinkRate);
      Serial.print("Enter integer : ");
      index = 0;
    }
  }
}

```

# Answer
> 2 votes
The biggest problem I see is that when your `convert()` function is called, if the user hasn't already typed something, then `Serial.available()` is going to return 0 (zero) and the `while` statement will never get executed.

Second, your `print` statement that prints the prompt to the console will only get called *after* you have already read a string from the user.

Third, you're trying to reinvent the wheel by writing your own function to read a string from the serial input. I suggest you use `ReadStringUntil()`.

# Answer
> 1 votes
The problem is, the Arduino serial monitor is way too crude to understand what you're trying to do. Using a real terminal emulator (Teraterm for example) will probably give you better results (but you will also need to echo back the characters typed so you can see what you're typing) - either that or don't try and do things "in-line" like a prompt, instead print a message including the line feed (i.e., use `println()` instead of `print()`) so that the serial monitor can output a new line with the message text in it.

# Answer
> 1 votes
It seems likely to me that you have not configured your serial monitor to send a newline. See the bottom line of the Serial Monitor.

If it is set to "no line ending" then when you send the line, you get the line only and no newline.

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


# Question
Title: Why can't the new Arduino IDE 1.6.7 compile extern "C"?
Consider:

I having a problem in compiling in extern "C" code in the Arduino IDE 1.6.7 which I don't have on version 1.6.5.

The error is:

> error: conflicts with new declaration with 'C' linkage

It is complaining about the lines containing `loop()` and `start_timer(void);`.

This is my code:

```
#ifdef __cplusplus
extern "C" {
#endif

void start_timer(void);

#ifdef __cplusplus
}
#endif

void start_timer(void)
{
    Serial.println("2");
    Serial.begin(9600);
    delay(2000);
}

void setup()
{
    start_timer();
    Serial.println("4");
}

void loop()
{
    Serial.println("1");
    delay(2000);
}

```

# Answer
I can't reproduce your problem still. See this:

---

However if you are having problems (and frankly I expected you to) then you should read this:

How to avoid the quirks of the IDE sketch file pre-preprocessing

How the IDE organizes things

---

I can reproduce your problem in IDE 1.6.5 (not 1.6.7). The code generated by the IDE preprocessor is this:

```
#line 1 "sketch_jan11a.ino"
#ifdef __cplusplus
#include "Arduino.h"
void start_timer(void);
void setup();
void loop();
#line 2
extern "C" {
#endif

void start_timer(void);

#ifdef __cplusplus
}
#endif

void start_timer(void)
{
    Serial.println("2");
    Serial.begin(9600);
    delay(2000);
}

void setup()
{
    start_timer();
    Serial.println("4");
}

void loop()
{
    Serial.println("1");
    delay(2000);
}

```

You can see that in the automatic function prototype generation that the IDE "helpfully" generates for you, it puts the prototype for `start_timer` outside the extern "C" declaration. Thus one function prototype has a declaration in C++ format, and the other in C format.

Why are you even doing this? I presume this is a small example of a larger problem.

If you follow the suggestions in my link How to avoid the quirks of the IDE sketch file pre-preprocessing \- *did you read that?* \- the problem goes away, because .cpp files in IDE tabs are not subjected to this extra processing.
> 4 votes

# Answer
The compiler is telling you that there is a conflict between the *two* definitions of start\_timer().

The normal usage of extern "C" is in a header file for functions that are accessed from both C and C++. This actually has to do with how C++ handles names and overloading. Using extern "C" will use normal C name handling and C++ name mangling is turned off (together with overloading, etc).

Please see https://stackoverflow.com/questions/31349865/compiler-error-for-conflicting-variable-declarations-conflicts-with-new-declar.
> 1 votes

---
Tags: programming, c++, arduino-ide
---


# Question
Title: Why I cannot change array values even if a statement is successfully called? TFT Touch Screen
```
#include <Adafruit_GFX.h>    // Core graphics library
#include "LGDP4535.h" // Hardware-specific library
#include <zTouchScreen.h>
#define BOXSIZE   40
// Assign human-readable names to some common 16-bit color values:
#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

LGDP4535 tft; // Using the shield, all control and data lines are fixed

#define YP A3  // must be an analog pin, use "An" notation!
#define XM A2  // must be an analog pin, use "An" notation!
#define YM 9   // can be a digital pin
#define XP 8   // can be a digital pin

// You need to calibrate to fit your LCD
#define TS_MINX 930
#define TS_MINY 903
#define TS_MAXX 142
#define TS_MAXY 117

#define PENRADIUS 3
#define MINPRESSURE 10
#define MAXPRESSURE 1000

int matrix[2][3]; // Initial Declaration
int array[3]

TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

// array = start with 1 but the variable read start with 0
String ButtonAction[9]={"a", "b", "c", "d", "e", "f", "g", "h", "i"};
boolean ActiveMenu=true;

void setup(void) {
   Serial.begin(9600);
   tft.reset();
   tft.begin();
   ts.InitVariable(3, 240, 320, TS_MINX, TS_MAXX, TS_MINY, TS_MAXY, MINPRESSURE, MAXPRESSURE);
   tft.fillScreen(BLACK);
   DrawIt(CYAN, "draw");
   DrawIt(BLACK, "text");
}

void loop() {//SOME OTHER STUFF}

unsigned long DrawIt(uint16_t color, String CurrentAction) {

  int timedcycle=0;

  if (CurrentAction == "text") {
     int matrix[2][3]={{25,150,265},{45,100,155}};
     int array[3]={3,3,3};

     tft.setRotation(3);
     tft.setTextColor(BLACK);
     tft.setTextSize(1);

     Serial.println("Text Columns");
  }

  else if (CurrentAction == "draw") {
    int matrix[2][3]={{260,140,20},{40,150,95}};
    int array[3]={3,3,3};
  }

  Serial.println(CurrentAction);

  for(int j=0; j<3; j++) {
     for(int i=0; i<array[j]; i++) {

       if (CurrentAction == "draw") {

         if (timedcycle == 7) {
           tft.fillCircle(100, 160, 15, WHITE);
         }
         else {
           tft.fillRect(matrix[1][j], matrix[0][i], 20,40, color);
         }

       }
       else if (CurrentAction == "text") {
         if (timedcycle == 4) {
           true;
           //tft.fillCircle(100, 160, 15, WHITE);
         }
         else {
           tft.setCursor(matrix[0][j], matrix[1][i]);
           tft.println(ButtonAction[timedcycle]);
         }

       }
     timedcycle++;
     }
  }
}

```

So as you can see I'm trying to draw some things in a TFT Touch Screen. Everything seems to be working but no matter what I do I can't change the array value.

If I initialize the array variable with a predetermined value it won't change even if the statement is called correctly. I can see that it runs over serial but the array still doesn't change.

I suppose there's something wrong but I can't pinpoint what it is! Thanks in advance!

# Answer
It's because you are defining a *new* array every time, not modifying the existing one.

```
int matrix[2][3]={{25,150,265},{45,100,155}};

```

That line doesn't assign new values to the existing `matrix` array, instead it creates a new array called `matrix` which only exists within the current scope - that is, within the `{...}` defined by the `if` that it is within.

Instead you either need to assign values directly to the existing matrix array on a slice-by-slice basis (you cannot use `{...}` to assign them in bulk):

```
matrix[0][0] = 25;
matrix[0][1] = 150;
... etc ...

```

Alternatively, since the values are static, you can pre-define the different matrices in the global scope and then switch between them. This can be done with the right kind of pointer. For instance:

```
int textMatrix[2][3] = {{260,140,20},{40,150,95}};
int (*matrix)[3];

void whateverTheFunctionIs() {
    if (whatever...) {
        matrix = textMatrix;
    }
}

```

In that example `matrix` is a pointer to an array of pointers, which is basically what a 2D array is internally. It starts off by not being assigned to anything at all - it's just "dangling in the breeze". When the `if` in your function is triggered the address that the `matrix` pointer points to is changed to that of the `textMatrix` 2D array, so any access to `matrix[x][y]` will be identical to accesses to `textMatrix[x][y]`.
> 2 votes

---
Tags: arduino-uno, array
---


# Question
Title: Arduino + ESP8266 - poll file from a server?
I really need all the help I can get... It's been a week now and I'm still not able to solve the problem.

I have text file on a server. The whole address is www.example.com/test.txt I want to read the file using a GET request every 3-5 secs and parse it for further actions. But the arduino codes that I've tried till now use software serial and it keeps misbehaving. Sometimes it skips a few serial-print commands and loops back sometimes it reads the file 3-4 times and then hangs. Basically I'm getting the response only a few times but then it stops working properly.

I want to solve this...I need a working arduino code to work with ESP8266 so that I can successfully poll a text file from server without any problems.

Here is my current code -

```
 #include<SoftwareSerial.h>

    #define led 13
    SoftwareSerial esp(11, 12);
    String domain = "www.example.com";
    String request = "GET /test.txt HTTP/1.0\r\n\r\n";

    void SerialDo(String command, float time, bool debug) {
      delay(100);
      esp.print(command);

      int i = millis();
      while (millis() - i < (time * 1000)) {
        while ( (esp.available())) {
          if (debug) {
            Serial.print((char)esp.read());
          }
        }
      }

      Serial.flush();
    }

    void setup() {
      // put your setup code here, to run once:
      digitalWrite(led, OUTPUT);
      Serial.begin(9600);
      esp.begin(9600);
      esp.setTimeout(3000);
      digitalWrite(led, LOW);
      Serial.println("Hello");
      //delay(2000);
      SerialDo("AT+RST\r\n", 5, true);
      Serial.flush();
      SerialDo("AT+CWMODE=1\r\n", 0.5, true);

      delay(1000);
      //SerialDo("AT+CWLAP\r\n", 5, true);
      SerialDo("AT+CWJAP=\"Sherlock\",\"Watson@11\"\r\n", 10, true);
      SerialDo("AT+CIPMUX=0\r\n", 0.5, true);

    }

    void loop() {

      delay(1000);
      Serial.print("loop\r\n");

      SerialDo("AT+CIPMUX=0\r\n", 0.5, true);
      SerialDo("AT+CIPSTART=\"TCP\",\"" + domain + "\",80\r\n", 1.5, true);
      esp.flush();

      esp.print("AT+CIPSEND=" + String(request.length()) + "\r\n");
      delay(100);
      esp.print(request);

      String t = "";
      int i = millis();
      while (millis() - i < 1500) {
        while ((esp.available() > 0)) {
          if (true) {
            char c = (char)esp.read();
            t += c;
            Serial.print(c);
          }
        }
      }

      esp.print("AT+CIPCLOSE\r\n");

      if (t.indexOf("hello world") > -1) {
        digitalWrite(led, !digitalRead(led));
      }
  }

```

# Answer
> 1 votes
It seems that you're trying to do the same thing:

> https://www.youtube.com/watch?v=q02f4sPghSo

Maybe it will help, I'm tryin' to do that (a POST), only that I don't have the server on a text file.

# Answer
> 0 votes
You aren't implementing the timeouts well and I don't see the point of this `if`:

```
if (true) {
   char c = (char)esp.read();
   t += c;
   Serial.print(c);
}

```

It will always be executed. You have allotted 1500 ms to the whole process of reading the whole file, whether the ESP is done or not. Inside the loop, you are calling Serial.print(), as well as concatenating chars to a string, which takes a significant portion of the 1.5 secs. Get rid of the Serial.print() and use the timeout this way:

```
unsigned long lastRead = millis();
while (millis() - lastRead < 1500) {
    while (esp.available() {
        t += (char)esp.read();
        lastRead = millis();
    }
}
Serial.print(t);

```

Storing the value of `millis()` with an `int` isn't a good idea since after about 33 seconds, it'll overflow. The code above will ensure that the last time a character was read is always stored in `lastRead`; the end result is that no character is available from the ESP after a continuous 1500ms, we conclude that there's nothing more to be read or some error has occurred. Repeat this for the loop in `SerialDo` as well. The `setTimeout` in your setup() is also unneeded, in this case; you didn't call any `SoftwareSerial` method that makes use of it, so remove the line. Also if your server supports HTTP 1.1, then try this request:

```
    String request = "GET /test.txt HTTP/1.1\r\nHost: www.example.com\r\n\r\n"

```

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


# Question
Title: SIM900 Shield read only sms headers without text
I enable messages about new SMS

```
AT+CNMI=2,2,0,0,0

OK

```

and when received sms, output like this.

```
+CMT: "+79XXXXXXXXX","1","15/09/23,01:34:03+24"
Test

```

But when I read message, output only before `<CR><LF>` I don't see text of message.

```
AT+CMGR=1

+CMGR: "REC READ","+79XXXXXXXXX","1","15/09/23,00:34:17+24"

AT+CMGL="ALL"

+CMGL: 1,"REC READ","+79XXXXXXXXX","1","15/09/23,00:34:17+24"
+CMGL: 2,"REC READ","+79XXXXXXXXX","1","15/09/23,01:34:03+24"

```

I use following (via SoftwareSerial) code for test this. `SMSGSM.GetSMS` and `SMSGSM.GetAuthorizedSMS` of GSM GPRS GPS Shield Library receive only phone number without sms text.

I use this shield:

```
AT+GSV

SIMCOM_Ltd
SIMCOM_SIM900
Revision:1137B05SIM900M64_ST_ENHAN

```

# Answer
> 1 votes
This is most likely a case of overrun SoftwareSerial buffer. You are reading too slowly from the modem, especially with the `Serial.print()`s in your code. You should look for SoftwareSerial.h in `C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial` if you're using Win 8 and above. Or just search your PC for it. Look for this line:

```
    #define _SS_MAX_RX_BUFF 64

```

Change 64 to 256 and save. If it solves your problem, try reducing 256 to 128 to see if it still works. The greater the size of the buffer, the lesser the amount of memory available to the rest of your program.

You could also try this, to interact with the module:

```
#include <SoftwareSerial.h>

SoftwareSerial SIM900(7,8);

void setup() {
  Serial.begin(19200);
  SIM900.begin(19200);
}

void loop() {
  // put your main code here, to run repeatedly:
  while (Serial.available() > 0){
    SIM900.write(Serial.read());
  }
  while (SIM900.available() > 0){
    Serial.write(SIM900.read());
  }
}

```

It does the same thing as your code and doesn't require adjusting buffer size, though I still recommend you make the change if you will use other sketches.

# Answer
> 0 votes
Could you confirm that any of the commands sent over your `SoftwareSerial` are responding?

You probably need to add a `"\n"` (new line) at the end of your messages or just use `println()`.

Also, add your code to the question so we can be of better assistance.

---
Tags: serial, gsm, softwareserial
---


title: SIM300cz AT command returns -1

text:
# Question
Title: SIM300cz AT command returns -1
I connected SIM300cz module's GSM board with Arduino Mega. The GSM board has the pins VCC, GND, RXD, TXD, GND, RI, DTR, STATUS, PWKEY and GND. I connected the GNDs with Arduino's GND, VCC to Arduinos 5V (took power from Arduino), RXD to pin 5, TXD to pin 6 (because of using software serial) and PWKEY to pin 53. My code is as follows:

```
#include<SoftwareSerial.h>
SoftwareSerial GPRS(5, 6);

int inputPinTempSensor = 0;
float tempCelsius = 0 ;
float thresholdTemp = 45;

void setup()
{
  GPRS.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);  // the Serial port of Arduino baud rate.
  pinMode(53, OUTPUT);
  digitalWrite(53, HIGH);
  delay(100);
}

void loop() {
  GPRS.print("AT+CREG/r");
  Serial.print(GPRS.read());
  delay(2000);
}

```

The AT command response should be something like "ok" but it's returning -1 for every loop waiting 2 seconds. Why and what could be the solution?

**Edit:**

Sorry for the mistakes. I was trying different ways with carriage return and new line characters to make it work. Now the code is:

```
#include<SoftwareSerial.h>
SoftwareSerial GPRS(5, 6);

void setup()
{
  GPRS.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);  // the Serial port of Arduino baud rate.
  pinMode(53, OUTPUT);
  digitalWrite(53, HIGH);
  delay(2000);
  GPRS.println("AT+CREG");
}

void loop() {
  while(GPRS.available()){
    Serial.print(GPRS.read());
  }
}

```

Now it gives no responses at all. Actually after buying the module I was trying with these examples and they were not working either. So, I thought to test if the AT commands were working properly. I could be a problem with my wiring too.

# Answer
I think there are 2 mistakes in your code:

First, you should ensure that the 3AT3 commands are termintaed by a new line character:

```
GPRS.print("AT+CREG/r");

```

should be changed into:

```
GPRS.println("AT+CREG/r");

```

or:

```
GPRS.print("AT+CREG/r\n");

```

Nite that I am not sure why you added `/r` at the end of the AT command, is that supposed to be part of the command? If your intention was to force a new line, then you meant `\r` not `/r`, which is not really a new line character but a carriage return (that might be interpreted the same by yur GSM module, but not necessarily).

The the second mistake in your code, is directly calling `GPRS.read()` **without** first waiting for a character to be available; in this situation, `GPRS.read()` will always return `-1` as a specific value meaning "no available character to read".

So you should change your code to something like:

```
// 1st wait for a character to be available
while (!GPRS.available()) {
}
// Then read all available characters and log them to Serial
while (GPRS.available()) {
    Serial.print(GPRS.read());
}

```
> 1 votes

# Answer
The correct AT command is `AT+CREG?\r`. A delay of at least 500ms is also advised after every command, though a timeout loop would be better. Since you didn't send any other commands, the modem will have no further responses for you and the Arduino will return -1 to any Serial.read()s, indicating there's nothing to be read.
> 1 votes

---
Tags: arduino-mega, gsm
---


# Question
Title: Arduino and reading from multiple USB connections
I'm sending up a high-altitude balloon with an onboard Mighty Ohm Geiger Counter and some other sensors, all of which will be managed by an R Pi B+. I'll collect and store the data with the R Pi; all of that's fine.

In order to track and recover it, I'm using the HABDuino shield on an Arduino. It uses the APRS system and sends back short messages, giving the altitude, internal temp, my callsign, and coordinates. I'd like to add the Geiger counter's data to that, but I'll need to get it from the R Pi.

Currently, I'm using an FTDI Friend to connect the Gieger counter to the R Pi, and getting the data from the serial port. I see here that I can connect the Arduino and Pi vai USB, but... since there's already a USB connection to the Gieger counter, will there be a conflict? Is that something that I can work around?

Thanks for the help!

# Answer
> 0 votes
The FTDI should be showing up as `/dev/ttyUSB0` on the Pi.

If you connect an Arduino as well it will show up as `/dev/ttyACM0`.

If you don't have enough USB sockets then just add a USB hub.

---
Tags: arduino-uno
---


# Question
Title: Correct solution for "multiple definition of" compile error
I'm in the process of trying to take this demo sketch and extract the necessary bits into a modular library that can be included in other sketches.

Here's where I'm at so far.

Here's the test sketch that I'm including it in.

However, when I try to compile it right now, I'm getting...

```
libraries/Adafruit_CC3000_Dynamodb/sha256.cpp.o: In function `Sha256Class::init()':
/home/me/sketchbook/libraries/Adafruit_CC3000_Dynamodb/sha256.cpp:33: multiple definition of `Sha256Class::init()'
sketch/sha256.cpp.o:sketch/sha256.cpp:33: first defined here

```

I've been programming for years in other languages, but I'm not all that experienced in C. I'm sure I'm doing something completely stupid, but I can't figure out what it is.

I'm also aware that this code still needs a lot of cleanup work in general. Right now I'm just trying to work toward a basic MVP that works so that I start gradually cleaning things up and making it more OOP one step at a time.

# Answer
> 2 votes
You have an old copy of the sha256 files lingering in the build folder. These will have been output at some point in the past and never been cleaned up since they have been deleted from the IDE.

It is probably a bug in the IDE that doesn't remove the old files.

Restarting the IDE will cure the problem and allow you to compile.

---
Tags: c
---


# Question
Title: UART error can not compile on Arduino Yun (ATmega32u4)
This code is used for communication between the Glediator interface and a NeoPixel Matrix, but I receive an error saying 'UCSR0A' is not defined within the scope.

```
UCSR0A |= (1<<U2X0);
UCSR0B |= (1<<RXEN0)  | (1<<TXEN0) | (1<<RXCIE0);
UCSR0C |= (1<<UCSZ01) | (1<<UCSZ00)             ;
UBRR0H = 0;
UBRR0L = 1; //Baud Rate 1 MBit (at F_CPU = 16MHz)

```

Any feedback is appreciated.

# Answer
Those register names are for a different chip (maybe the ATMega328P of the Uno).

Instead you need to use the *right* register names. Start by reading the datasheet for the ATMega32U4. You might find that the register names are UCSR1A etc, or UCSRA or something like that instead of UCSR0A.
> 1 votes

# Answer
You should be able to use Serial1 to access the USART. But...

> Note that on the Yún, the Serial class refers to USB (CDC) communication; for TTL serial on pins 0 and 1, use the Serial1 class. The hardware serials of the ATmega32U4 and the AR9331 on the Yún are connected together and are used to communicate between the two processors. As is common in Linux systems, on the serial port of the AR9331 is exposed the console for access to the system, this means that you can access to the programs and tools offered by Linux from your sketch\[1\].

Please see below references for further details:

1. https://www.arduino.cc/en/Main/ArduinoBoardYun
2. https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/variants/yun/pins\_arduino.h#L40
3. https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/variants/leonardo/pins\_arduino.h#L363
> 0 votes

# Answer
So what I did was changing the codes by replacing the '0' from the other chipset to the '1' on the Atmega32u4

```
UCSR1A |= (1<<U2X1);
UCSR1B |= (1<<RXEN1)  | (1<<TXEN1) | (1<<RXCIE1);
UCSR1C |= (1<<UCSZ11) | (1<<UCSZ10)             ;
UBRR1H = 0;
UBRR1L = 1; //Baud Rate 1 MBit (at F_CPU = 16MHz)

ISR(USART_RX_vect)
{
  unsigned char b;
  b=UDR1;
...

```

I think that this is the problem that causes freeze when I Open Serial. Any advice? Thanks In advance
> 0 votes

---
Tags: compile, uart, baud-rate
---


# Question
Title: Arduino loading variables from an SD card
Hello I have made a small game using and Arduino Uno and a Nokia 5110 screen. I use bitmaps to draw the images onto the screen. The problem is that bitmaps take up a lot of space and I can only use up to three bitmaps before running out of space. Is it possible to use an SD card to store the bitmaps on and have a method in the Arduino code to load a bitmap at a certain time, like when a button is pushed?

# Answer
Typically a bitmap for the Nokia 5110 (PCD8544) requires 504 bytes of memory (48\*84/8). A bitmap as a initiated global variable will be stored in program memory, transfered to data memory on startup and then to the device (when drawn). Three bitmaps will use up 1.5 Kbyte. This is the limit for the Arduino Uno as an additional bitmap will require all data memory.

The first trick that can be used is to define the bitmaps in program memory with the attribute PROGMEM and when needed transfer to a buffer (504 byte) in data memory (and then to the device).

```
void *  memcpy_P (void *, const void *, size_t)

```

The second trick is to transfer the bitmap directly from the program memory to the device. This may be supported by the library. If not the bitmap draw function will need to be updated to explicitly read program memory.

The upper limit for the bitmaps is now the size of the program memory (30 Kbyte, 60 bitmaps).

Cheers!
> 0 votes

# Answer
Yes, it is possible, but is it practical?

There's basically two ways of doing it:

1. Load the entire bitmap into RAM for displaying multiple times
2. Display the bitmap direct from the SD card.

As the Uno only has 2KiB of RAM that rather limits the size of bitmap that can be loaded into it. As you currently can have 3 bitmaps in flash (max 32KiB) I will assume they are considerably bigger than 2KiB each, so loading them into RAM is not really going to be doable on the Uno.

So the second option - drawing it direct from the SD card - is really the only practical way. The problem with that is reading from the SD card is considerably slower than reading from the internal Flash. That means that your screen updates could be really slow, which would seriously impact the playability of your game.

All that happens when you draw a bitmap normally is that a loop iterates through the data and interprets each bit of each byte as a pixel being on or off and sets the relevant pixel to be on or off on the screen. Instead of reading data from flash you just read bytes from the SD card and interpret them in exactly the same way. If you take a look at the bitmap drawing routine in your LCD library you will see how simple it is - replacing the Flash access with SD card reading should be a simple enough matter to implement in your own copy of the routine.

A much better option would be to use a more powerful Arduino - one that has considerably more flash, such as the Mega2560.
> 0 votes

---
Tags: arduino-uno
---


title: Pinout for Leonardo USB

text:
# Question
Title: Pinout for Leonardo USB
According to the docs, the Arduino Leonardo uses digital pins 0 and 1 for the USB D- and D+ lines. However, which is which? e.g. is D0=D+ or is D1=D+?

To save space in a very tight project, I want to wire USB directly to these pins instead of using the USB plug, however, I can't find any resource that explains which pin goes to which USB line.

# Answer
The USB does not go to pins 0 and 1. The UART goes to pins 0 and 1 - that is a totally different interface.

The USB is connected to dedicated USB pins on the chip. If you look at the Leonardo schematic you can see it is pins 3 and 4 on the chip. Note that that is not pins D3 and D4 on the board, but the third and fourth pins anti-clockwise from the "pin 1" dot on the main chip.
> 5 votes

# Answer
As shown in the ATmega32U4 datasheet, D- and D+ connect to pins 3 and 4 respectively ***of the MCU***. But you don't want to wire directly to the chip unless you know what you are doing since the chip does not include the USB termination resistors. Follow the schematics given in the datasheet when connecting to the USB pins of the MCU.
> 3 votes

---
Tags: usb, arduino-leonardo
---


# Question
Title: Hardware to measure velocity via string/wire attatchment? beginner
This is a broad question but I want advice on what type of hardware I should look for to make a device that could measure the velocity of an object attached via a string/wire to some sort of rotary wheel.

The purpose of this is to attach it to a barbell and measure mean-velocity for weightlifting atheletes.

I'm a software engineer by trade but know nothing about hardware. I will obviously need to start with simple projects to learn, but I would like to know which hardware I should lean towards buying, so I don't have to re-buy anything?

# Answer
You can use a dog lead (or replace it with a fishing line). I made one my self. I used a rotary encoder and a dog lead, an Arduino board Paralax, and Excel.

It will use interrupts. Once the wire is triggered, the Arduino will send to Excel time and distance traveled. Once the weight goes down distance and time will be printed too, however distance will run in a minus direction. Later just press one button in Excel and each set of lifts will appear on the desktop. I can see my lift speed, power generated, distance travelled and so on.
> 1 votes

# Answer
This is an example of the optical encoder. You want to use interrupt detection, rather than polling. Or maybe even an HW counter. That's all you really need.

I am using 4 of them for a car.

I am in the process of refactoring the code, but you could already have a look at the driver & example I wrote for ChibiOS, here.
> 1 votes

---
Tags: accelerometer
---


# Question
Title: How to upload Arduino sketches to Atmel chips
I am new in this Arduino coding world and I was trying to make a project. I normally used Arduino Unos all the time, but I was facing a problem and that is that the Arduino Uno has only 13 digital pins and 6 analog pins, and some of my friends advise me to use an Arduino Mega, but that costs too much, some to my friends also tell me that I could use only a Atmel chip, which will save money.

But the problem is that I can not burn these chips without a burner. I see online that Arduino Uno has Arduino ISP options also that will allow you to bootload or upload Arduino sketches to those kind of chips, but I have been trying for over 3 months and I cannot figure out how to do that

At present I am working with the ATmega8 chip.

This is my problem:

Using stk500v1 but the problem is not resolved

# Answer
First thing you need to do in this situation is to crank up the verbosity level on the invocation of `avrdude`. You do this by adding one or more `-v` flags to the command line. With `-v -v -v -v`, you get maximum verbosity.

From your two logs, it appears that the initial handshake with the microcontroller was successful (which would indicate that your connections were good), but then the signature reading turns out quite badly. This is a rather unusual combination which makes me wonder whether you may have misidentified what microcontroller you have.
> 1 votes

---
Tags: arduino-uno, sketch, bootloader, avr, atmel-studio
---


title: Update code over Ethernet?

text:
# Question
Title: Update code over Ethernet?
I've got an Arduino faithfully monitoring our sewer lift pump. It talks to the world over Ethernet (with PoE). I'm wondering if there is any way to load new code over the Ethernet as well. Any ideas if this could be done?

I imagine that using the boot loader might be out of the question, but perhaps it would be possible to upload a new system image – perhaps onto an SD card – and then use a modified boot loader to discover the new image and copy it into place.

# Answer
A bootloader to network-boot might be too large to leave enough code space for your application. Your second suggestion sounds more workable - to collect & verify the entire new image in secondary storage first, then call a storage-to-flash boot loader. You really don't want to start loading an image that then suffers damage in transit, or to have the link go down mid-download. The likely only way out of that is a site-visit. Saving first lets you confirm the integrity of the new image before you start over-writing any of the old one.
> 1 votes

---
Tags: ethernet
---


# Question
Title: Why can I power an SD card reader from a digital pin?
I'm trying to understand the power requirements of an SD card. I have a cheap breakout board from eBay that includes built-in level shifters, so I can plug it in directly to my Arduino. I provide power from one of the digital pins, and it works. This doesn't make sense to me, as I thought an SD card reader should draw upwards of 50-100 mA, well over the capacity of an individual digital pin on the Arduino. However, at least one SD card manufacturer does this as well, so I'm not making this up.

I have checked, and the data is written no problem. I have connected an ammeter between the Arduino and the SD reader, and it never jumps above 3 mA? The only problem I have is when I switch from using the USB cable (connected to my computer) for power to a battery pack, the SD card starts acting erratically. Which makes sense, if it's not getting enough current.

What I'm wondering is why it *ever* works when connected to a digital output pin? Clearly I'm missing something important.

Edit: The reason why I thought they required a lot of current: I've seen comments like this on a number of tutorials:

> One is that they are strictly 3.3V devices and the power draw when writing to the card can be fairly high, up to 100mA (or more)!

Edit2: @dlu answer lead me to investigate the voltage I was sending to the SD card reader, which turns out to have been the problem. I was supplying the Vin pin with 5.2V, which was regulated down to 4V, presumably too low for the 5V-3.3V step-down at the SD card. Moving the battery power to the 5V pin corrected this. This also introduces some new risk, as the board is now receiving unregulated power. But that is another problem.

Edit3: And finally, answering my original question: I found a note on the Adafruit product page for a similar breakout that indicates:

> Onboard 5v-\>3v regulator provides 150mA for power-hungry cards

So despite only drawing 3mA of current from the Arduino pin, the actual SD card is supplied with \> 100mA from the regulator.

# Answer
It seems that you've verified that the power requirements are within the range of a digital pin. Is there a reason why you thought they would be higher?

So, it sounds like the real question is "why does the SD card work with USB power, but not with battery power?" The first thing that occurs to me is that the battery is not providing sufficient voltage. What kind of battery are you using and where do you connect it to the Arduino?

Almost any battery that you use will be able to provide sufficient current for a 3 mA load, but the voltage may not be adequate – especially if you are running a marginal battery (voltage wise) through the onboard regulator.
> 1 votes

# Answer
I just tested a SD card in an adapter (with level shifters). Without any activity the SD card is only drawing around 0.5 mA. So that is in the capability of an output pin.

Doing a directory list appears to use a maximum of 7 mA, so that is OK.

Writing a file used a maximum of **54.3 mA**, which is exceeding the absolute maximum ratings for an output pin (40 mA - recommended only 20 mA for continuous current).

Now you may say that "it works" but the question is: for how long? Exceeding absolute maximum ratings is a path to damaging your processor.

If you want to turn the SD card on and off from time to time, to reduce power, I suggest you arrange to switch the 5V line (and not use a digital output). For example from this page about a low-power temperature sensor I have this schematic:

The MOSFET there switches a 5V line on and off under program control.

That particular design includes a SD card, and that particular gadget has been working for a couple of years now.

Photo of hardware:
> 2 votes

---
Tags: power, sd-card
---


title: Do I need a lot of Arduinos?

text:
# Question
Title: Do I need a lot of Arduinos?
I would like to make a smart home using Arduino. My system must be wireless. I want to control power outlets and lamps and I want to be able to turn off and on power outlets and lamps wirelessly, using my android app, using nRF24L01.

Do I need an Arduino for each power outlet and lamp? Do I need to put an Arduino, nRF24L01 and relay inside each power outlet and lamp?

# Answer
> 2 votes
You might also consider using ESP8266 + relay combinations, instead of Pro Mini + nRF24L01 + relay sets. An Arduino IDE setup is available to support C code on ESP8266 systems (,,).

Note: As a consequence of its higher clock speed and larger RAM size (80 MHz or 160 MHz clock, and 80 KB DRAM, vs Mini's 16 MHz clock and 2 KB SRAM) a typical ESP8266 board uses more power than a Pro Mini + nRF24L01 does. According to nrqm.ca/nrf24l01, the nRF24L01 draws around 11 or 12 mA when sending or receiving, and 22 μA in low-power standby mode. According to wiki.iteadstudio.com/ESP8266\_Serial\_WIFI\_Module, an ESP8266 draws ~ 60 mA receiving and 135–215 mA sending. (That current range covers a power output range of 5.5 dBm. It probably supports a much bigger communication area than nRF24L01 does.) Of course, if all your installations have mains power available, the power requirements might not matter much to you. Note, ESP8266 boards typically run on 3.3 V power instead of 5 V power.

As far as cost goes, at the moment Pro Mini clones cost about $2.15 each. nRF24L01's run about $0.90. ESP8266 modules are $2–$3 depending on model and level of module (,). You might save a few dollars on your whole system using ESP8266's, but the smaller-sized electronics they provide probably is more important.

# Answer
> 2 votes
One arduino can control multiple relays. Beyond that, how many you need will depend on the details of your project.

Once you have a working example, you can build it using less expensive alternatives than regular Arduino boards.

---
Tags: arduino-uno
---


# Question
Title: Few questions related to programming microcontrollers
I'm learning "Arduino" (I don't have previous knowledge of microcontrollers). I have few questions:

1. What is the difference between programming a microcontroller in C and programming in "Arduino?"
2. Is it a good idea for beginners to start programming microcontrollers in Arduino and then start learning to program in C?
3. I have Arduino Uno with an Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board? What are differences between various microcontrollers which can be used with this board?
4. If a microcontroller is already programmed, can we download the program from it to a PC and edit it in Arduino IDE? Or it is like a .exe on a PC, once compiled we can't get source, all we can do is reverse engineer?

That's it :)

# Answer
1. The Arduino IDE uses C++ primarily, which it preprocesses in order to make compilable. But you can still for the most part use C in the Arduino IDE and it will just work as normal; there's nothing requiring you to use C++ or the Arduino libraries (or even the Arduino IDE) for most tasks.
2. Not touching this one. And in the end it doesn't matter terribly since they're very close.
3. Any of the ATmegaXX8 or ATmega8 chips will fit the socket. Note that they will require separate cores if you're using the IDE. And you can use any chip without the board in the IDE as long as you can find a core for it.
4. Not if you use a traditional compiled language to program it. If you use a VM then you conceivably could, but you'd have the source on your system regardless.
> 4 votes

# Answer
1. Nothing really. The Arduino language is C++, a super-set of C. It contains a library of routines which are automatically included and linked, as well as a small amount of pre-processing to hide some of the pitfalls of C (e.g., automatically adding function prototypes for all functions to the top of your program so function ordering isn't something you now need to think about). Other than that, it is just C++, which is C with bells.
2. If you learn the Arduino language you are learning C. If you learn C first then it gives you a good grounding in how to program the Arduino. Either way, by the time you have written your first Arduino program, you will be programming in C.
3. There are a number of chips by Atmel that will work. You need, besides the "core" that Ignacio mentions, a board definition which defines what pins do what and what chip is in use. You also need a bootloader for that specific chip and some way to install that bootloader into the chip. There are tutorials on how to do that for commonly used chips - more uncommon ones may not have a bootloader readily available.
4. When you program for the Arduino you are compiling the software. That is turning the source code first into object code and then linking the object code into an executable format - almost exactly the same as a .EXE on Windows. There is nothing you can do to "undo" that, only disassemble the raw instructions into assembly language and try to interpret what it is doing, which with assembly is a bit of a black art since it can be somewhat cryptic.
> 1 votes

# Answer
> What is difference between programming microcontroller in C and programming in Arduino?

The difference is that the Arduino core includes a set of functions and classes (C++) to make Arduino boards easier to program.

> Is it good idea for beginners to start programming microcontrollers in Arduino and then start learning programming in C?

The whole idea with Arduino is to make it much easier to start embedded programming in C and/or C++.

> I have Arduino Uno board Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board? What are differenes between various microcontrollers which are used with this board?

None. This is the controller for that board (though there are "smaller" versions).

> If microcontroller is already programmed, can we download program from it to PC and edit it in Arduino IDE? Or it is like .exe on PC, once compiled we can't get source, only we can do is Reverse Eng.?

This you will have to explain better. Sounds like something bad and you should avoid that (or at least do not ask people to help you do a bad thing).
> 1 votes

# Answer
> What is the difference between programming a microcontroller in C and programming in "Arduino?"

The default language is C++, but you can program in C. Thus the difference is "not much".

> Is it a good idea for beginners to start programming microcontrollers in Arduino and then start learning to program in C?

Ah, if you program the Arduino you will be learning C. So "goodness" doesn't really enter into it.

> I have Arduino Uno with an Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board?

You could conceivably remove the chip and replace it with an Atmega168P. I'm not sure why you would want to.

> What are differences between various microcontrollers which can be used with this board?

RAM, program memory (flash) size, and EEPROM size.

> If a microcontroller is already programmed, can we download the program from it to a PC and edit it in Arduino IDE? Or it is like a .exe on a PC, once compiled we can't get source, all we can do is reverse engineer?

No. Like a PC, you can't get the source back. The compiler is a good, highly optimized one. The generated code won't look like the source.
> 1 votes

---
Tags: c
---


# Question
Title: Why does Ethernet.begin() require a MAC address when WiFi.begin() doesn't?
I am working on an Arduino application which is dependant on a certain library. This library uses the `Ethernet` class for network communications, but ideally, I would like it to be wireless (I have both an Ethernet and WiFi shield available for testing).

When working on replacing the `Ethernet` functionality of the library with the corresponding `WiFi` functionality, I noticed that the `Ethernet.begin()` function requires a MAC address while the `WiFi.begin()` doesn't (it instead accepts SSID and password, among a couple of other things).

As both come shipped with a MAC address sticker on them, I couldn't really figure out why this is the case (and if I need to supply the MAC address found on the WiFi shield in some other fashion).

Why is this the case?

# Answer
> 1 votes
The flip answer would be "because it doesn't need it…"

I think what is going on is that older Ethernet shields did not have a MAC address and it was necessary for the code to set one (and I would guess that on at least some of them you can still set the MAC address, overriding the one that is on the sticker).

WiFi cards, I would guess, are newer and the MAC address is always there, so there is no need to require you to assign it.

---
Tags: wifi, ethernet
---


title: Waiting for an AT command to complete

text:
# Question
Title: Waiting for an AT command to complete
I'm looking for a way to wait for a response from an AT command to return OK or CONNECTED or whatever the command returns when it's true.

I can check if the serial is available, but that means I have to manually guess what time between commands to give them time to connect or start.

Function:

```
void ModemCommand(String command) {
  //Send command to modem
  mySerial.println(command);
  Serial.println(command);
  delay(100);
  while (!mySerial.available()) {
    //Wait for Response from modem
    Serial.println(F("No response yet"));
    delay(1000);
  }
  while (mySerial.available()) {
    Serial.write(mySerial.read());
    //Print response from modem
  }
  Serial.println("");
  //Linefeed after reponse
  delay(10);
}

```

Code example:

```
ModemCommand(F("ATE0"));
//Turn on echo
ModemCommand(F("AT+CFUN=1"));
//Turn modem functions on
waitSec(8,F("turning on Modem functions"));
ModemCommand(F("AT+CGREG?"));
//GSM attached?
ModemCommand(F("AT+CSQ"));
//Signal Quality
ModemCommand(F("AT+CSTT=\"internet\""));
//Set APN
ModemCommand(F("AT+CIICR"));
//Connect to APN GPRS
waitSec(8,F("connecting to APN GPRS"));
ModemCommand(F("AT+CIFSR"));
//Get IP

```

Does anybody know how to do this?

# Answer
> 1 votes
The most you can do is define a certain amount of time between received characters, after which you can decide that there's nothing more to be read from the modem. Of course, the time taken for processing is longer for certain commands (and some provide no response at all, until you've completed entering their payload, like TCPSEND, in which case you should simply use `mySerial.write()` to send said payload, and not your function), but once a response is ready and its first character is available, a timeout of 1 second between characters should be sufficient, for any reasonable baud rate. Something like this:

```
#define TIMEOUT 1000

void modem_command(String command){
  mySerial.println(command);
  Serial.println(command);
  while (mySerial.available() == 0);  // wait for first char

  unsigned long lastRead = millis();   // last time a char was available
  while (millis() - lastRead < TIMEOUT){
    while (mySerial.available()){
      Serial.write(mySerial.read());
      lastRead = millis();   // update the lastRead timestamp
    }
  }
  // No need for extra line feed since most responses contain them anyways
}

```

Of course, you can always alter `TIMEOUT` based on your findings.

# Answer
> 1 votes
You would need to create a buffer which will populate over each loop so you dont block the main loop while waiting the all string.

When you get the string or your buffer is full, just check whatever is the response, and based on that you can make your decision.

---
Tags: serial, c++, arduino-pro-mini
---


# Question
Title: Can I set an Arduino pin as input and output?
When I used to program PICs, there was a way to set the pins to input and output, at the same time. Can this be done on the Arduino? I see the pinmode documentation, but nothing about being an IO port.

# Answer
No there is no function that lets you set all the pins to either input or output at the same time, but it wouldn't take much to write one.

No, you can't set an Arduino's pin as bidirectional. If you are running out of pins look at IO expanders or multiple Arduinos.

Hope that helps, if not please feel free to clarify what it is you would like to know and we'll try and help.
> 3 votes

---
Tags: arduino-uno, pins
---


# Question
Title: Arduino IDE not handling library code correctly?
The author of the PinChangeInt library and the EnableInterrupt library states at github:

> When the PinChangeInt was in a .h and .cpp file, the Arduino IDE tried to compile it twice. I have a technique that you can use- #define LIBCALL\_ENABLEINTERRUPT - that if you put it ahead of your #include in all files but the sketch, then you should be able to use the library without conflicts. If you know how to make it work in another way- remember, this is a library and will not compile in the same directory as the sketch and any other .h/.cpp/.ino files- then I'm all ears.

I came there, because both libraries failed to build with linker errors due to double definitions. So far so good. I split the PinChangeInt library in .h and .cpp myself and it compiled flawlessly. I did not try to split the other library yet because it looks like much work to me.

So now my question(s): Is GreyGnome right with his statement, that library code gets compiled twice when split in code and headers? And if so, what are the consequences? Memory waste? Runtime errors? What about the many other (working) libraries exhibiting separate code and header files?

# Answer
Header files are parsed by the preprocessor and the compiler wherever they are included.

There's nothing weird about that. One can avoid multiple inclusions by using header guards. That's pretty standard too.

I have not looked at the library, but, for example, a typical error is to *not* declare variables as extern in the header and instead leave the real declaration in the header, which will lead to multiple instances, possibly clashing at link time. Variables that are part of the library API should be declared as extern in the header and the real declaration should be done only in the .C/.CPP file.

Interrupts are an even more special case: the AVR gcc relies on very specific names to identify interrupt handlers and each of them can be present at most once. So there are even more chances for having linker problems, if not declared correctly.
> 1 votes

# Answer
To elaborate on your comment ~

An easy way to prevent multiple definitions from re-inclusion of the same header file is to ensure it's only defining things once.

e.g. my\_header.h

```
#ifndef __MY_HEADER_H__
#define __MY_HEADER_H__

// some header code.

#endif //#ifndef __MY_HEADER_H__

```

When the header is *first* compiled, the definition of `__MY_HEADER_H__` gets created by the compiler due to the 2nd line of the file. On subsequent compiles, which are caused by including the same header in more files, the 1st line '#ifndef' conditional skips everything down to the '#endif'.

When you write (or split) C / C++ code, it's common to wrap the class and function definitions (which go in the .h header file) in these compilation control blocks, and then the .c/.cpp file only gets the function bodies.

e.g.: my\_rgb.h ~

```
#ifndef __MY_RGB_H__
#define __MY_RGB_H__

#include <stdint.h>

uint32_t packRGB(uint8_t r, uint8_t g, uint8_t b);

class RGB
{
public:
    RGB(uint8_t r, uint8_t g, uint8_t b);

    void toGreyscale();

private:
    uint8_t red;
    uint8_t green;
    uint8_t blue;
};

#endif //#ifndef __MY_RGB_H__

```

and my\_rgb.cpp

```
#include "my_rgb.h"

// Note: this would typically be a member function
// but is separate to show a standalone function definition.
uint32_t packRGB(uint8_t r, uint8_t g, uint8_t b)
{
    uint32_t packed;

    packed = (r << 24) | (r << 16) | b;

    return packed;
}

RGB:RGB(uint8_t r, uint8_t g, uint8_t b)
{
    red = r;
    green = g;
    blue = b;
}

void RGB::toGreyscale()
{
    uint8_t grey = 0.2126 * (float)r + 0.7152 * (float)g + 0.0722 * (float)b;
    r = g = b = grey;
}

```

Including the header file multiple times will give "redefinition" errors at **compile time**. Including the same function multiple times will give double definitions at **link time**.

If you stick to this method of laying out .h and .c/.cpp files you will never have a problem with multiple definitions on your own files. (Unless you re-define a library function by accident, etc.)

Of course it's ok (and quite common) to define short little functions in the header/.h file too. (The compiler typically generates these as inline code though.) I'm not trying to explain the complete workings of headers & .C files, just presenting you a method which will *always* prevent multiple definition problems.
> 0 votes

---
Tags: arduino-ide, library
---


# Question
Title: ESP8266 (connected to Arduino) only works when plugged into USB power
The Wi-Fi connects when the Arduino is powered by my computer and a serial console is connected, but not if I plug into an outlet.

**UPDATE**

It seems this is a power issue. I am powering the esp8266 from the Redboard 3.3v line that is only rated for 150mA. I will be switching to the 5v line with a 1A regulator.

I also switched to 9600 baud for communicating with the esp8266, added retries around all of esp8266 commands, and added reconnect logic in case the esp8266 reboots. With the changes, it works okay even with the underpowered 150mA line.

It's still a mystery to me why it works so well when connected to my Macbook.

# Answer
> 1 votes
It sounds like your power supply is inadequate to the task.

The ESP8266 is notoriously finicky about having a noise free power supply capable of delivering a lot of instantaneous power. If you are using a wallwart style supply it should promise at least 1A and more is better. Even though the actual use is more like 250 mA.

---
Tags: esp8266
---


title: NRF24L01 Connection Not Working

text:
# Question
Title: NRF24L01 Connection Not Working
I have an ATTiny85 connected to an NRF24L01+ module using this wiring diagram: diagram. The ATTiny85 periodically goes in and out of sleep to send some value to a receiver, an Arduino Uno. If the ATTiny is running off the Arduino power supply (3.3v), everything works correctly. When I run the ATTiny off of a separate CR2032 coin cell that delivers around 3v, the Arduino never receives any data. I have a status LED hooked up to the ATTiny to ensure that the ATTiny is waking correctly, which it is. Here's the code for both:

**EDIT**: Connecting it to an external 3.3v not from the Uno makes everything work - why wouldn't the coin cell's voltage work? I think everything is rated below 2.8v, the CR2032 minimum.

**ATTiny Code**

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

// Routines to set and claer bits (used in the sleep code)
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

#define CE_PIN 3
#define CSN_PIN 3 //Since we are using 3 pin configuration we will use same pin for both CE and CSN

#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

byte address[11] = "SimpleNode";
unsigned long payload = 0;

void setup() {
  radio.begin(); // Start up the radio
  radio.setAutoAck(1); // Ensure autoACK is enabled
  radio.setRetries(15,15); // Max delay between retries & number of retries
  radio.openWritingPipe(address); // Write to device address 'SimpleNode'
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);
  delay(500);
  digitalWrite(4, LOW);
  delay(500);
  digitalWrite(4, HIGH);
  delay(500);
  digitalWrite(4, LOW);
  delay(500);
  digitalWrite(4, HIGH);
  delay(500);
  digitalWrite(4, LOW);
  delay(1000);
  setup_watchdog(6);
}

volatile int watchdog_counter = 0;

ISR(WDT_vect) {
  watchdog_counter++;
}

void loop()
{
  sleep_mode(); //Go to sleep!

  if(watchdog_counter >= 5)
  {
    digitalWrite(4, HIGH);
    watchdog_counter = 0;
    payload = 123456;
    radio.write( &payload, sizeof(unsigned long) ); //Send data to 'Receiver' ever second
    delay(1000);
    digitalWrite(4, LOW);
  }
}

//Sleep ATTiny85

void system_sleep() {

  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System actually sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out

  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON

}

// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
void setup_watchdog(int ii) {

  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

```

**Receiver Code**

```
#define CE_PIN 7
#define CSN_PIN 8

#include <SPI.h>
#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

byte address[11] = "SimpleNode";
unsigned long payload = 0;

void setup() {
  while (!Serial);
  Serial.begin(115200);
  radio.begin(); // Start up the radio
  radio.setAutoAck(1); // Ensure autoACK is enabled
  radio.setRetries(15,15); // Max delay between retries & number of retries
  radio.openReadingPipe(1, address); // Write to device address 'SimpleNode'
  radio.startListening();
  Serial.println("Did Setup");

}

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

    radio.read( &payload, sizeof(unsigned long) );
    if(payload != 0){
        Serial.print("Got Payload ");
        Serial.println(payload);
    }
  }
}

```

Is the problem here that the ATTiny and Uno need to be turned on at the same time to establish a connection, or is it something to do with the battery, or something else entirely? Any help would be appreciated.

# Answer
I was just researching the exact question and I have some bad news.

The ORIGINAL nrf24l01+ alone use around 10-12 ma in transmitting, but unoriginal might even draw more. (https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss\_Preliminary\_Product\_Specification\_v1\_0.pdf)

Nevertheless a standard CR2032 battery is simply not made to supply more than a few milliamps at the best, leaving your nrf24L01+ lacking enough current.

There is something called shockburst which can lower your consumption considerably at the cost of range - but if it will succeed in transmitting with one CR2032 I'm not sure about.

Edit: If you add a capacitor you need to cover at least a 10ma drain for around 15ms (turn on - send - turn of immediately), that will require a minimum of a 200µF capacitor at 3V to be able to deliver the current while keeping above 2.0v.
> 1 votes

---
Tags: arduino-uno, attiny, nrf24l01+, wireless, sleep
---