# Question
Title: AC meter By ADC timer interrupt from Nick Gammon
I want to read ADC from the pin A0 and A1. I have written in this code, however.

I took this code came from Nick Gammon

Thank You //////////////////////////////////////////////////////////////////////////////

this is code

```
const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

// ADC complete ISR
ISR (ADC_vect)
  {
  if (resultNumber >= MAX_RESULTS)
    ADCSRA = 0;  // turn off ADC
  else
    results [resultNumber++] = ADC;
  }  // end of ADC_vect

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);  // WTF?
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

  // wait for buffer to fill
  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
    Serial.println (results [i]);

  }  // end of setup

void loop () { }

```

# Answer
> 1 votes
In the code you posted the first line is:

> ```
> const byte adcPin = 0;  // A0
>
> ```

To read from A1 the change is simple:

```
const byte adcPin = 1;  // A1

```

---

> i am sorry i come from thailand

Whatever country you are from does not excuse from you posting the same question many, many times.

I suggest you read the datasheet:

ATmega48A-48PA-88A-88PA-168A-168PA-328-328P\_datasheet

Scroll down to **24.9.1 ADMUX – ADC Multiplexer Selection Register**

# Answer
> 0 votes
You can read two analog channels like this:

```
int first_reading = analogRead(A0);
int second_reading = analogRead(A1);

```

If this does not fit your purpose, then your question was not asked properly: rewrite it and clearly state your requirements. Explain why the simple solution does not work for you.

If this *does* work for you, then stop (for now) reading advanced tutorials, like the one where you found your code, and focus on the very basics: the Arduino examples in the 01.Basics section, then the 03.Analog section.

# Answer
> 0 votes
```
constexpr byte  adc_mux_setting = bit(REFS0) | bit(ADLAR); // Left alligment for ADC result, so ADCH contains 8b result.

volatile uint16_t         sum_u = 0;
volatile uint16_t         sum_i = 0;
volatile uint8_t   resultNumber = 0;

// ADC complete ISR
ISR (ADC_vect) {
    if (resultNumber & 1) {
        sum_u += ADCH-(sum_u>>8);                  // 8bit resolution, something like floating average
    } else {
        sum_i += ADCH-(sum_i>>8);                  // 8bit resolution, something like floating average
    }
    ADMUX  = adc_mux_setting | (++resultNumber&1); // Expecting pins A0 and A1 (otherwise offset must be added)

    TIFR1 |= bit(OCF1B);                           // clear the flag otherwise it never starts ADC conversion (not without ISR)
                                                   // it's here because I don't want to ADC starts conversion before switching channel
}

void setup () {
    Serial.begin(115200);
    Serial.println("Start");

    // reset Timer 1
    TCCR1A  = 0;
    TCCR1B  = bit(CS11) | bit(WGM12);              // CTC, prescaler of 8
    TCNT1   = 0;
    //TIMSK1 = bit (OCIE1B);                       // it doesn't work without clearing OCF1B
    OCR1A   = 80;                                  // it never reaches 80 so it never sets interrupt flag
    OCR1B   = 79;                                  // 40 uS - sampling frequency 25kHz for both (15kHz for each)

    ADCSRA  = bit(ADEN)  | bit(ADIE) | bit (ADIF); // turn ADC on, want      interrupt on completion
    ADCSRA |= bit(ADPS2);                          // Prescaler of 16
    ADMUX   = adc_mux_setting;                     // A0 goes first
    ADCSRB  = bit(ADTS0) | bit(ADTS2);             // Timer/Counter1 Compare Match B
    ADCSRA |= bit(ADATE);                          // turn on automatic triggering
}

void loop () {
    if (resultNumber == 0) {                       // print results after 128 measures for both channels
        Serial.print(sum_u);
        Serial.print(' ');
        Serial.println(sum_i);
        while (resultNumber == 0);                 // I want to print it only once per iteration
    }
}

```

---
Tags: interrupt, atmega328, analogread, adc, analog-sampling
---


# Question
Title: Is it possible to pass HIGH and LOW values as parameter in a function?
I've created the following function:

```
void runMotor(int _dir, int _step, int wait){
  digitalWrite(_dir, HIGH);
  for (int x = 0; x < 3200; x++) {
    digitalWrite(_step, HIGH);
    delayMicroseconds(wait);
    digitalWrite(_step, LOW);
    delayMicroseconds(wait);
  }

```

In the first line inside the function I used the value `HIGH` as a fixed value. I would like to know if there's a way to pass the values `HIGH` and `LOW` as a parameter in this function. Is it possible?

Or should I just create a new function to rotate my step motor to the other side?

# Answer
`digitalWrite` expects the pin and value to be `uint8_t` type. So you can certainly pass LOW or HIGH to functions.

For example:

```
void runMotor(int _dir, int _step, int wait, uint8_t value){
  digitalWrite(_dir, value);

```
> 4 votes

---
Tags: code-optimization
---


title: Returning an int array from a function

text:
# Question
Title: Returning an int array from a function
I have a function that needs to return 3 int values. I currently use an array declared in the global scope and I ask the function to write into them. Is there a way to make a function return an array?

Here is what I want to do:

```
int function()
{

int array[3];

array[0] = 19;  //these are just random numbers

array[1] = 7;

array[2] = 69;

return array[]; //is this possible??

}

```

# Answer
> 6 votes
> I have a function that needs to return 3 int values.

In the interests of completeness I'll suggest another method. Let's assume that you really need 3 values and not 300.

```
void foo (int & a, int & b, int & c)
{
  a = 19;  //these are just random numbers
  b = 7;
  c = 69;
}

void setup() {
  Serial.begin (115200);
  int x, y, z;
  foo (x, y, z);
  Serial.println (x);
  Serial.println (y);
  Serial.println (z);
}

void loop() {
}

```

This conceivably will use less memory because the compiler may be able to optimize all 3 values into registers. In fact in that specific example, it has optimized away the entire function call:

```
000000be <setup>:
  public:
    inline HardwareSerial(
      volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
      volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
      volatile uint8_t *ucsrc, volatile uint8_t *udr);
    void begin(unsigned long baud) { begin(baud, SERIAL_8N1); }
  be:   26 e0           ldi r18, 0x06   ; 6
  c0:   40 e0           ldi r20, 0x00   ; 0
  c2:   52 ec           ldi r21, 0xC2   ; 194
  c4:   61 e0           ldi r22, 0x01   ; 1
  c6:   70 e0           ldi r23, 0x00   ; 0
  c8:   82 e2           ldi r24, 0x22   ; 34
  ca:   91 e0           ldi r25, 0x01   ; 1
  cc:   0e 94 64 01     call    0x2c8   ; 0x2c8 <_ZN14HardwareSerial5beginEmh>
  d0:   4a e0           ldi r20, 0x0A   ; 10
  d2:   50 e0           ldi r21, 0x00   ; 0
  d4:   63 e1           ldi r22, 0x13   ; 19  <---------- x
  d6:   70 e0           ldi r23, 0x00   ; 0
  d8:   82 e2           ldi r24, 0x22   ; 34
  da:   91 e0           ldi r25, 0x01   ; 1
  dc:   0e 94 4d 03     call    0x69a   ; 0x69a <_ZN5Print7printlnEii>
  e0:   4a e0           ldi r20, 0x0A   ; 10
  e2:   50 e0           ldi r21, 0x00   ; 0
  e4:   67 e0           ldi r22, 0x07   ; 7   <---------- y
  e6:   70 e0           ldi r23, 0x00   ; 0
  e8:   82 e2           ldi r24, 0x22   ; 34
  ea:   91 e0           ldi r25, 0x01   ; 1
  ec:   0e 94 4d 03     call    0x69a   ; 0x69a <_ZN5Print7printlnEii>
  f0:   4a e0           ldi r20, 0x0A   ; 10
  f2:   50 e0           ldi r21, 0x00   ; 0
  f4:   65 e4           ldi r22, 0x45   ; 69  <---------- z
  f6:   70 e0           ldi r23, 0x00   ; 0
  f8:   82 e2           ldi r24, 0x22   ; 34
  fa:   91 e0           ldi r25, 0x01   ; 1
  fc:   0c 94 4d 03     jmp 0x69a   ; 0x69a <_ZN5Print7printlnEii>

00000100 <loop>:
 100:   08 95           ret

```

# Answer
> 13 votes
There are several ways to achieve what you want:

## The way that does not work

Did you try to compile the code you gave in the question? Then you probably noticed it does not compile. I tried and got: “error: expected primary-expression before ‘\]’ token”, meaning the compiler expected `return array[some_index];`.

## The way that almost works

Remove the brackets and just return `array`:

```
int *function()
{
    int array[3];
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

```

This may work, or not, depending on the surrounding code, on how the optimizer processes your program, and on how lucky you are when you test it. It is called “undefined behaviour” and is something you should always avoid.

Here is what happens: in C (and C++) you cannot return an array. The identifier `array` “decays” to a pointer pointing at its first element. Then `return array` is essentially equivalent to `return &array[0]`. The problem is that, since the array is allocated in the function's stack frame, it ceases to exist when the function returns, thus the caller gets a pointer to an area of memory that is not allocated anymore. Likely memory corruption ahead. The compiler warned me when I tried to do that: “warning: address of local variable ‘array’ returned”. It's a very serious warning that should never be ignored.

## The simplest fix: make the array static

As suggested by Chris Stratton in a comment, you can make the array static, so it will be allocated for the whole life of the program:

```
int *function()
{
    static int array[3];
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

```

The only catch is that the function is now not *reentrant*, meaning that every time you call it it will clobber the same array it returned on the previous calls. Depending on your use case, this may not be an issue, but it's something you need to be aware of.

## Have the caller manage the allocation

A safer (reentrant) way is to have the caller provide the memory needed for the array. This is a very common method in C, and is suggested both by Harper Shelby's answer and Chris Stratton's comment:

```
int *function(int array[3])
{
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

```

The caller can allocate in static memory, or in it's own stack frame, or on the heap... but you do not care, the allocation is the caller's problem now.

A couple of things to note here:

* The prototype is equivalent to `int *function(int *array)`: the function receives only a pointer. Writing `array[3]` instead of `*array` has the sole effect of *documenting* that the function expects the pointer to point to somewhere with room for 3 values. You could document that in a comment instead.
* The function could return `void`, since the caller presumably knows the address it is giving you. Returning that same address is just for convenience, as it can help you chain calls like `another_function(function(array))`.

## Return the array in a struct

One may wonder: why can't we return an array in the first place. I do not know for sure why the authors of the language made this choice, but one possible explanation is that it is expensive to return a big array by value, as it involves copying the whole of it. Now, if your array is *really* only three ints, then that argument does not apply, and you may reasonably want to really return the whole array by value. This can be done by embedding it inside a struct:

```
// Struct definition.
struct Array3 {
    int array[3];
};

Array3 function()
{
    Array3 a;
    a.array[0] = 19;
    a.array[1] = 7;
    a.array[2] = 69;
    return a;
}

```

# Answer
> 1 votes
There are 2 ways to do what you want in C. One relies on the function caller managing memory, the other on the "library" code managing the memory. If you go with the caller-managed memory, your function accepts a buffer and fills it. For "library" managed memory, you provide additional functions to allocate and release the buffer that the caller then calls

If you want to use C++ idioms, you can make a class (possibly static) that allocates the memory and provides access to the data.

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


# Question
Title: How to connect Flora 2 and nRF8001 BLE Breakout
I'm trying to get the nRF8001 BLE Breakout polling properly on Flora but Adafruit's tutorial and everything I've read and hunted around but I'm new to Arduino and not really sure how the Adafruit\_BLE\_UART library is handling I/O on the various pins. I'd appreciate it if anyone knows the proper pin configuration to get this working. I'm not in a position where I can easily change out to a better BLE device for my Flora.

So it's clear I have

* SCK connected to SCK.
* MISO to MISO, I've also tried it in D12 with the same outcome.
* MOSI in MOSI, there's no D11 on this board so I couldn't try that.
* REQ in D10.
* RDY in SDA, which is supposed to correspond to D2 (besides SCL I don't think there are any other interrupt pins).
* RST in D9, also tried it in the Reset SPI, doesn't seem to make any difference.

In short I'm using all the appropriate SPI pins and two of the data pins mentioned in the BLE tutorial, and I've tried a couple other configurations without much success.

And it appears to be powered properly.

using `echoDemo`, `getState` always returns the disconnected opcode. Polling apparently does nothing, `setDeviceName` does not set a name. I think either MISO or MOSI or both are the problem here. I can blink the LED, and other peripherals are working okay. (Crossposted to Adafruit forums.)

Some code:

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

// Connect CLK/MISO/MOSI to hardware SPI
// e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 2
#define ADAFRUITBLE_RST 9

Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

void setup(void) {
  Serial.begin(9600);
  while(!Serial); // Leonardo/Micro should wait for serial init
  Serial.println(F("Adafruit Bluefruit Low Energy nRF8001 Print echo demo"));
  BTLEserial.setDeviceName("NEWNAME"); /* 7 characters max! */
  BTLEserial.begin();
}
aci_evt_opcode_t laststatus = {5};

void loop() {
  // Tell the nRF8001 to do whatever it should be working on.
  BTLEserial.pollACI();
  // Ask what is our current status
  aci_evt_opcode_t status = BTLEserial.getState();
  Serial.println(laststatus);
  Serial.println(status);
  Serial.println(ACI_EVT_DEVICE_STARTED);
  Serial.println(ACI_EVT_CONNECTED);
  Serial.println(ACI_EVT_DISCONNECTED);
  delay(1000);
  // If the status changed....
  if (status != laststatus) {
    // print it out!
    if (status == ACI_EVT_DEVICE_STARTED) {
        Serial.println(F("* Advertising started"));
    }
    if (status == ACI_EVT_CONNECTED) {
        Serial.println(F("* Connected!"));
    }
    if (status == ACI_EVT_DISCONNECTED) {
        Serial.println(F("* Disconnected or advertising timed out"));
    }
    // OK set the last status change to this one
    laststatus = status;
  }
}

```

# Answer
> 1 votes
The SPI bus can be accessed using a 6 pin header located next to the embedded processor. Look at the embedded image below. Locate the 6 pin header just to the right of the processor. Note the white dot indicating pin1 of the header. Now look at the bottom of the embedded image to see the definitions of the 6 pins. MISO, MOSI and several other SPI signals are listed.

---
Tags: bluetooth, adafruit
---


# Question
Title: upload real time ultrasonic sensor data to pubnub using arduino and esp8266
I want to upload the real time data of ultrasonic sensor attached to my Arduino Uno and I have been using esp8266 module for the WiFi connection.

I want to upload to PubNub but I don't know how to start writing the code for PubNub and where do I have to write the code.

I have the code working on my Arduino using the ultrasonic sensor in C++ language, printing the readings on the serial monitor. However, the code will be definitely changed in order to upload the sensor readings to PubNub.

On PubNub the most used SDK is JavaScript and I'm not very familiar to it. For C++ the most used SDK is Posix but it seems way more difficult more than JavaScript. So how I have to translate the code from C++ to JavaScript to get it published on PubNub?

Sorry, I am completely new to this stuff therefore I don't know much about it.

# Answer
The PubNub website has a link to an Arduino library:

https://github.com/pubnub/arduino

Although it doesn't have specific support for the ESP8266 per se, it does support the Arduino Ethernet Shield, Arduino Wifi Shield and Arduino Wifi101 Shield, so I would imagine it wouldn't be hard to adapt the code.

Be aware that for the Arduino Uno, the SRAM will be fairly limited, where as the ESP8266 contains 96 KB of DRAM.
> 1 votes

---
Tags: sensors, esp8266, web-service
---


# Question
Title: Serial available doesn't work right after upload
I have 2 programs to test serial communication, an simple arduino program that echoes whatever is on the serial port and a python program that writes to the serial port and prints the reply.

I'm having an issue where whenever I upload the arduino program and try to run the python code the arduino code wouldn't detect serial available on the first run. I would have to either

* open and close serial monitor before I run python program
* run the python program, quit, and run it again

and it would continue to work until I re-upload the arduino then the same thing happens. Does anyone know what is the issue? This is on Ubuntu.

arduino

```
String str;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(115200);
}

void loop() {
  if (Serial.available()) {
      str = Serial.readStringUntil('\n');     // Read the serial input
      Serial.println(str);             // sends ascii code

  }
}

```

Python

```
import serial

ser = serial.Serial('/dev/ttyACM1', 115200)

for i in range(0,4):
    str = "test string\n"
    ser.write(str)
    print ser.readline()

```

# Answer
> 1 votes
This fails due to the typical auto-reset-on-open serial port configuration interacting with a problematic assumption made by the PC code.

The first issue means that it will typically take a few seconds between when the port is opened (unless the port is configured *not* to manipulate modem control signals on open) and when the usual bootloader times out, yields to the custom sketch loaded in the Arduino, and the latter becomes able to accept input and potentially respond.

The second issue is with the PC side code:

```
for i in range(0,4):
    str = "test string\n"
    ser.write(str)
    print ser.readline()

```

Assuming that `import serial` refers to pySerial, then because you did not specify a timeout when opening the port, the `ser.readline()` is an eternally **blocking read**. To quote the documentation:

> Be carefully when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received.

If we look at what happens with your python program and a typical serial port configuration where modem status lines change on open, then the first thing your program does is implicitly reset the Arduino. Next, it writes "test string\n" - but because of the reset, it writes this at the bootloader, not the sketch which is not running yet. Finally your program eternally waits for a newline terminated reply - which it will never receive, because your sketch will not send that until it receives something from the PC, which will not send anything else until it receives the newline terminated response to its first message.

**Your programs are thus stuck in a "no, after you" deadlock.**

There are many potential ways to work around this. For example, you might open the port with a timeout, wait a few seconds, and conduct this test write and attempt to read a reasonable number of times, but declare an error to the user if success is not achieved in ten or so seconds of those attempts.

Note also that the sketch may start running midway through transmission of the test string, so you will have to handle the possibility of a message with the beginning missing, either by declaring an error or discarding it and waiting for a subsequent intact one.

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


# Question
Title: Serial communication doesn't work right after upload
I'm trying to communicate between a program on the Arduino Uno and a program on the PC via USB. I got it more or less working. Only problem is that it doesn't work when I run my PC program the **first time after I upload** the Arduino code via the Arduino IDE (version 2:1.0.5+dfsg2-4). It has some strange behaviour. Of course I could do some workaround, but I hope someone knows what the cause of this problem is and if there is a nice way to solve it.

This program should send back every byte it receives:

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

void loop () {
    if (Serial.available()) {
        Serial.write(Serial.read());
    }
}

```

This program sends the bytes 0 to 255 to the Arduino twice and outputs every byte it receives. It is written in Scala and uses the Java RXTX library for serial communication. I'm using Debian Linux.

```
import gnu.io.CommPortIdentifier
import gnu.io.SerialPort

object SerialTest extends App
{
    val portId = CommPortIdentifier.getPortIdentifier("/dev/ttyACM0")
    val port = portId.open(getClass.getName, 0).asInstanceOf[SerialPort]
    port.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE)

    val in = port.getInputStream
    val out = port.getOutputStream

    for (i <- 0 until 512) out.write(i)

    while (true) print(in.read + " ")
}

```

Instead of the 512 bytes it should receive, only around the last 44 bytes are received. Also, the first bytes the program receives are usually wrong. When I run the program for a second time, I get the desired result.

```
  Try 1: 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  Try 2: 186 58 93 157 221 29 151 167 183 199 215 231 247 7 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  Try 3: 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  Try 4: 221 29 151 167 183 199 215 231 247 7 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
Desired: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

```

If I let the program wait for 2 seconds anywhere between `val portId = ...` and writing to the output stream, it works. But there is be a better way, right?

(related question)

# Answer
The first time you open the serial port on the PC the Uno resets and enters the bootloader. Two seconds later your sketch starts running.

By then you have already sent a load of your data to the Uno which it ignores because it's not valid bootloader commands.

When your program exits it leaves the port in an different state (RXTX is crap and doesn't clean up after itself when you terminate a program). That state includes the DTR signal being disabled.

With the DTR signal disabled the Uno doesn't reset when you open the port. Thus when you run your program a second time the sketch is already running and everything works fine.

You can toggle the control of the DTR signal in Linux by setting or clearing the `hupcl` flag on the tty:

```
Disable DTR control:
$ stty -F /dev/ttyACM0 -hupcl

Enable DTR control:
$ stty -F /dev/ttyACM0 hupcl

```
> 1 votes

---
Tags: serial, java
---


# Question
Title: Switch between ntc resistor sensors time based for other device
We have a heating system that uses an ntc resistor to measure water temperature. I would like to replace that ntc resistor by a fixed one (low enough to disable heating) temporary on a 5 minute schedule, or any other.

It's to prevent the warm water using up all the heat and not leaving any for the central heating of the building. We got fooled by the contractor and a proper upgrade would now cost several thousands, so we just want to trick the system. ;p

The arduino is not supposed to measure anything, just to connect one of the two resistors to the heating system.

Is an arduino the right choice for that? If yes, which model? What extra elements would I need? Transistors? Relays? They shouldn't have too much own resistance to not influence the measuring of the heating system when the NTC is connected.

Just a simple connection of the extra resistor would work too because the resulting resistance would be lower and still indicate "water is hot enough" to the heating system.

Any help is welcome, even if it is not arduino based.

# Answer
It sounds like what you want is a small SPDT relay (maybe a *reed* relay).

simulate this circuit – Schematic created using CircuitLab

Turn on the GPIO, the MOSFET (or NPN BJT if you choose - increase R1 if you do) turns on, which energises the relay. The relay then switches between the NTC and the resistor being connected into the circuit.
> 1 votes

---
Tags: resistor, switch
---


title: Expected } at the end of input

text:
# Question
Title: Expected } at the end of input
I am getting the error in my title when I try to compile the following code:

```
#define char incomingByte; //Defines incomingByte
#define char sendBack = K;
#define char ?;
#define pollTime;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}

void loop() {
for(Serial.available() > 0;)  { //Gets you the number of bytes that are available to be read from the serial port.
pollTime = delayMicroseconds(200); // Sets a poll time of 200 microseconds.
incomingByte  = Serial.read();
if(incomingByte = ?) {
Serial.print(sendBack);
  }
 }
}

```

# Answer
> 3 votes
Your code is completely wrong in almost every respect.

---

```
#define char incomingByte; //Defines incomingByte

```

That line means that the compiler will substitute `incomingByte;` whenever it sees `char`.

---

```
#define char sendBack = K;

```

Now it will substitute `sendBack = K;` when it sees `char`.

---

```
#define char ?;

```

Now it will substitute `?;` when it sees `char`.

---

```
#define pollTime;

```

I don't know what you are thinking here. If you are trying to *declare* a variable you have to give a type, like this:

```
int pollTime;

```

---

```
bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}
void loop() {

```

Those lines are OK.

---

```
for(Serial.available() > 0;)  { //Gets you the number of bytes that are available to be read from the serial port.

```

You don't want the semicolon there. A `for` loop is not written like that. You possibly mean `while`, ie.

```
while(Serial.available() > 0)

```

---

```
pollTime = delayMicroseconds(200); // Sets a poll time of 200 microseconds.

```

That is doing nothing of the sort. It is delaying 200 µs, it isn't setting anything.

---

```
incomingByte  = Serial.read();

```

That line is OK, assuming you declared `incomingByte` like this, and not the way you did:

```
char incomingByte;

```

---

```
if(incomingByte = ?) {

```

That needs to be in single quotes, as you are comparing a character. Also you compare with `==` not `=` ie.

```
if(incomingByte == '?') {

```

---

```
Serial.print(sendBack);

```

It looks from your earlier code you mean:

```
Serial.print('K');

```

---

```
  }
 }
}

```

These lines look OK.

---

I suggest you read a beginners page about C programming. This is just pure guesswork what you are doing here. For one thing, read up on how `#define` works. Here is one page: https://www.techonthenet.com/c\_language/constants/create\_define.php. And another: http://www.cprogramming.com/reference/preprocessor/define.html

# Answer
> 0 votes
\[UPDATE\]

Try this:

```
int question = 63; //in the ascii table, ? is 63

void setup() {
  Serial.begin(9600); //set baud rate.
}

void loop() {
  if (Serial.available())  { //Gets you the number of bytes that are available to be read from the serial port.
    if (Serial.read() == question) {
      Serial.println("OK");
    }
  }
}

```

---
Tags: arduino-uno
---


title: Compiles but doesn't print anything

text:
# Question
Title: Compiles but doesn't print anything
Here is my code. It is suppose to read a couple of sensors and print them out in the serial monitor. Any help please? Note that I'm new to object orientated programming.

```
/* The Blue Box

   Project description:
   Arduino black box flight data recorder
   This projects acts like a little homemade black box. It records data of a flying object.

   Details about the code:
   Altitude is calculated in meters above sea level.
   Records: day of the week, year, month, day, hour, minute, second, time from activation, yaw, pitch, roll, altitude, temperature

   This code is subject to a lot of ameliorations.

   By: xxx
   Date: 2016/08/28

   Extra credits:

   GY-521 library:
   I2Cdev device library code is placed under the MIT license
   Copyright (c) 2012 Jeff Rowberg
   https://github.com/jrowberg/i2cdevlib

   MPL3115A2 library
   Adafruit Industries
   https://github.com/adafruit/Adafruit_MPL3115A2_Library

   SD card library
   Code from example by Tom Igoe
   Included in the Arduino IDE itself

   DS3231 library
   Rinky-Dink Electronics
   http://www.rinkydinkelectronics.com/library.php?id=73
*/

#include <SPI.h>                        //include the SPI library
#include <SD.h>                         //include the SD card library
#include <Wire.h>                       //include I2C library
#include "I2Cdev.h"                     //include another I2C library
#include "Wire.h"                       //include another I2C library (yes, again)
#include "MPU6050_6Axis_MotionApps20.h" //include the MPU6050 library
#include "SparkFunMPL3115A2.h"          //include the MPL3115A2 library
#include <DS3231.h>                     //include the DS3231 library

//==================================================

#define testtest                    //*** COMMENT THIS LINE BEFORE UPLOADING OFFICIAL CODE TO FINAL PROJECT ***

#define chipSelect 10               //pin for the CS/SS
#define led 2                       //led and/or buzzer

volatile bool mpuInterrupt = false; //some random bool

bool ledState = false;              //state of the led and/or buzzer
bool dmpReady = false;              //state of the mpu6050

int yprInt[3];                      //gyro data in a integer because the extra precision of the float is total bullshit
int altitude;                       //altitude above takeoff point in meters
int altitudeCalibration;            //calibration for the altimeter
int temperature;                    //temperature in degrees Celcius

float counter = 0;                  //time counter, a somewhat internal clock that starts when the module starts dataloging

uint8_t mpuIntStatus;               //holds actual interrupt status byte from MPU
uint8_t devStatus;                  //return status after each device operation
uint8_t fifoBuffer[64];             //FIFO storage buffer

uint16_t packetSize;                //expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;                 //count of all bytes currently in FIFO

String day;                         //day of the week
String ymd;                         //date: year,month,day
String hms;                         //time: hour,minute,second

MPU6050 mpu;                        //change mpu's adress
Quaternion q;                       //quaternion container
VectorFloat gravity;                //gravity vector

MPL3115A2 myPressure;               //MPL3115A2 object declaration as myPressure
DS3231  rtc(A0, A1);                //DS3231 object declaration as

void dmpDataReady() {
  mpuInterrupt = true;
}

class MainLoop
{

    unsigned long previousMillis;

  public:
    MainLoop()
    {
      rtc.begin();            //start DS3231

      Wire.begin();
      myPressure.begin();                                         //start MPL3115A2 communication
      myPressure.setModeAltimeter();
      myPressure.setOversampleRate(7);
      myPressure.enableEventFlags();
      altitudeCalibration = myPressure.readAltitude();            //read altitude

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE

      TWBR = 24;
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE

      Fastwire::setup(400, true);
#endif

      mpu.initialize();
      devStatus = mpu.dmpInitialize();
      mpu.setXGyroOffset(0);
      mpu.setYGyroOffset(0);
      mpu.setZGyroOffset(0);
      mpu.setZAccelOffset(0);

      if (devStatus == 0)
      {
        mpu.setDMPEnabled(true);
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
      }

#ifdef testtest

      Serial.begin(115200); //start serial communication
#endif

#ifndef testtest

      if (SD.begin()); ();       //sd card
#endif

    }

    void go(  )
    {
      unsigned long currentMillis = millis();

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE

      TWBR = 24;

#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE

      Fastwire::setup(400, true);
#endif

      mpu.initialize();
      devStatus = mpu.dmpInitialize();
      mpu.setXGyroOffset(0);
      mpu.setYGyroOffset(0);
      mpu.setZGyroOffset(0);
      mpu.setZAccelOffset(0);

      if (devStatus == 0)
      {
        mpu.setDMPEnabled(true);
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
      }

      else
      {
        return;
      }

      altitude = myPressure.readAltitude() - altitudeCalibration; //read altitude
      temperature = myPressure.readTemp();                        //read temperature

      day = rtc.getDOWStr();  //get day of the week
      ymd = rtc.getDateStr(); //get day, month, year
      hms = rtc.getTimeStr(); //get hour, minutes, seconds

#ifdef testtest

      Serial.print(day);
      Serial.print(" ");
      Serial.print(ymd);
      Serial.print(" -- ");
      Serial.print(hms);
      Serial.print(", ");
      Serial.print(counter);
      Serial.print(", ");
      Serial.print(yprInt[0]);
      Serial.print(", ");
      Serial.print(yprInt[1]);
      Serial.print(", ");
      Serial.print(yprInt[2]);
      Serial.print(", ");
      Serial.print(altitude);
      Serial.print(" ,");
      Serial.print(temperature);
      Serial.println();
#endif

#ifndef testtest

      if (altitude > 1) //if the device is higher then 1m, then we sstart recording everything
      {
        File dataFile = SD.open("datalog.txt", FILE_WRITE);

        if (dataFile)
        {
          dataFile.print(day);
          dataFile.print(" ");
          dataFile.print(ymd);
          dataFile.print(" -- ");
          dataFile.print(hms);
          dataFile.print(", ");
          dataFile.print(counter);
          dataFile.print(", ");
          dataFile.print(yprInt[0]);
          dataFile.print(", ");
          dataFile.print(yprInt[1]);
          dataFile.print(", ");
          dataFile.print(yprInt[2]);
          dataFile.print(", ");
          dataFile.print(altitude);
          dataFile.print(" ,");
          dataFile.print(temperature);
          dataFile.println();
          dataFile.close();
        }
      }
#endif

      counter = counter + 0.5;

    }
};

MainLoop main;

void setup() {
}

void loop()  {
  main.go();
}

```

# Answer
Move all that code out of the constructor and put it in a `.begin()` method to call from `setup()`. You are calling functions before the chip has been initialized and things are being undone.

It is only safe to use a constructor to initialize a few variables and the like. Simply because the call sequence is:

1. Constructors
2. System Init
3. Setup
4. Repeat forever:
5. -\> Loop

System Init configures the timers, peripherals, IO pins, etc. Things which need to be done *before* the code in your constructor.
> 2 votes

# Answer
> mind giving a small example. I'm really not familiar with class and constructors

Here is an example of trying to do things in the constructor:

```
class foo
{
  public:
  foo () // constructor
    {
    Serial.begin (115200);
    Serial.println ("Hello, world.");
    }
}; // end of class foo

foo bar;  // make an instance of foo

void setup() { }
void loop() { }

```

On my setup that prints "Hel" and nothing else.

---

Now if we change things around it works:

```
class foo
{
  public:
  void begin ()
    {
    Serial.begin (115200);
    Serial.println ("Hello, world.");
    }
}; // end of class foo

foo bar;  // make an instance of foo

void setup()
  {
  bar.begin ();
  }

void loop() { }

```

Now we are doing things in the right order. "Under the hood" the `main` function provided by the IDE initializes the hardware (by calling `init`) and then calls `setup`. Now we can call the `begin` function in our class.

---

It would have worked if we created the class instance inside `setup` because that is after `init` is called, like this:

```
class foo
{
  public:
  foo () // constructor
    {
    Serial.begin (115200);
    Serial.println ("Hello, world.");
    }
}; // end of class foo

void setup()
  {
  foo bar;  // make an instance of foo
  }

void loop() { }

```

However now `bar` is not a global variable.

---

What is sometimes done is to make a function to return an instance of the class, which creates it the first time it is called, like this:

```
class foo
{
  public:
  foo () // constructor
    {
    Serial.println (F("Hello, world."));
    }
  void doSomething ()
    {
    Serial.println (F("Doing something"));
    }
}; // end of class foo

foo & getFoo ()
  {
  static foo myBar;  // make an instance of foo
  return myBar;
  }  // end of getFoo

void setup()
  {
  Serial.begin (115200);
  Serial.println (F("Program starting."));

  foo & bar = getFoo ();
  bar.doSomething ();
  }  // end of setup

void loop()
  {
  foo & bar = getFoo ();
  bar.doSomething ();
  delay (500);
  }  // end of loop

```

Now the function `getFoo` returns a *reference* to the instance of foo created as a static variable inside it. Thus, *the first time it is called*, the instance is created. Subsequent times just return the same instance.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Can I use L293D driver as ESC for arduino controlled quadcopter
I recently thought that it would be fun to build an arduino quadcopter.

As I did some research I realized that the common L293D motor drivers aren't ever used.

Why is this? Could I still use them in my project?

# Answer
> 3 votes
Bipolar bridge drivers like the L293D, L298, etc have extremely high losses. They are long out of date and a poor choice compared to modern FET chips even for surface vehicles, let alone something that needs a good power to weight ratio for flight. Typically if you made a small robot with one and some AA cells, you'd have to have an extra cell in the pack just to cover the losses of the L293D. An aircraft (and especially a vertical lift one) cannot afford that waste. Also the wasted energy shows up as heat (though I suppose you could position the chip in the propwash).

Actual quadcopters use MOSFET drivers, typically discrete ones carefully selected for a low RDSon at a low enough threshold voltage to fully turn on when driven by an MCU output. Either just one N FET per motor for unidirectional control of brushed motors, or H bridges made of an N FET and either a P FET or else an N FETs with special high side driver circuitry for bidirectional control of brushed motors, or similarly as a half-bridge for each of the three leads of a brushless motor. The MOSFETs may be found either on the main board in a single board quadcopter, or else they may be packaged in modular speed controllers separated from it.

But providing current to drive the motors is the easy part - sequencing brushless motor commutation, and stabilizing a flight platform are the hard parts.

In that regard, an Arduino is a very poor choice as a flight controller. A literal one means carrying around a lot of extra mass and connectors that aren't really fitting. A work-alike on a custom board is possible, but most of the open source projects that started that way have long since moved on to other MCUs with more capability. You do still see ATmega8's within brushless motor drivers though.

---
Tags: motor
---


# Question
Title: Error Uploading Arduino Sketch to Arduino Pro Mini
I got an error "stk500\_getsync() not in sync resp=0x00" when I tried to update an Arduino Pro Mini with an FTDI Basic Breakout 5V/3.3V - Micro USB. Maybe someone has instructions on how to resolve this issue. I use the last version of Arduino IDE. All standard stuff like drivers, ports installed and configured.

I have communication with controller and I receive answers from it, but when I try to flash the firmware I get that error.

# Answer
> 0 votes
It's your COM port or your board selection.

I often use the Pro Mini and an Uno and when I forget to change either the COM port or the board to which I have to upload the sketch to, that error message happens.

---
Tags: arduino-ide, arduino-pro-mini
---


# Question
Title: Powering a 12v lock with batteries, via WiFi, and with low energy consumption
I'm a complete newbie in anything related to electronics, software or hardware; yet with a couple of friends we're going ahead with an interesting project related to automation through wireless devices: more or less IoT but involving electric locks.

The case scenario: there's a room without any power outlets. It has a regular door. **We want to be able to open this door through the internet, with a lock that lies inside the room, on the other side of the door**; all this, given we:

* Can't make any modifications to the door's structure.
* Can't drill or make holes or whatever so as to get a power cable to the inside of the room.
* But **we can** glue certain pieces behind the door, this is, inside the room that hasn't any power outlets.

We've planned, so far, to use an Arduino Uno; enhance it with WiFi features (i.e. a module or shield) so as to bypass the limitation of not being able to connect an ethernet cable; and glue a solenoid or lock to the inside of the doors, so that it acts as a second lock that can only be unlocked through the internet, accessed via Arduino.

**Our ideal scenario would be opening this door remotely, from our home, even if this door is a hundred blocks away. If someone wants to get in, they should ask for our permission, as we don't control the built-in handle, but we do control a latch fixed on the inside.**

All this setup should be powered with a long-lasting battery: we can't plug anything, and we can't risk getting our batteries depleted fast, because we'll never be able to open the door once again. We need these batteries to last long enough so as to be able to change them in a prudent time window; a back-up battery system should also work well.

Standard solenoid locks are 12v. Arduino powers 5v devices, not 12v ones, as far as my understanding goes.

We should open this door only 5 times a day. That's it; the remaining time in between, the whole device setup can well stay 'dormant', in low-energy consumption mode, only to 'wake up' when we give the order: "Arduino, please tell the solenoid to open".

We haven't specified which battery we would use; ideally, the most cost-efficient option. If it lasts 3 months and costs, say, 20 dollars -- well, we would love that.

I've done this really inaccurate, schematic drawing to illustrate our idea and research. I know there's many details missing but I wanted to prove our point:

(The Arduino should be positioned on the wall and not on the door! My bad.)

I hope I'm clear enough up to now.

The questions, then, are:

I've done some research, and I've seen that Arduino can be enhanced so that it consumes the minimum possible energy so as to remain 'aware', but not in full-power mode, which in our case would be unnecessary.

1. So, can we make Arduino *super efficient* in terms of power consumption, even if we attach WiFi functions, which, as far as I'm concerned, really takes on battery life? So that we can make Arduino run for months before replacing the battery?
2. Arduino can send only 5v; but the solenoid powers on 12v; then, getting a second battery to power our solenoid sounds straightforward, except that as far as my knowledge goes, this battery should last next to nothing (maybe I'm wrong here). And we want it to last for months -- if not, our door will remain sealed forever! Can I make the solenoid dependant on the Arduino, so that it's part of the "almost-no-battery-consumption" scheme, and battery lasts, as I would really like, some months? We would be talking of only one battery to power the whole set-up, instead of two that I guess that we'll need.

I'm a newbie, but can't Arduino power 12v through a relay or a transistor? Can't post links.

To clarify: Getting two batteries for our complete setup (one for the Arduino, one for the solenoid), if these two batteries both last, is not a problem; but it would be catastrophic to make a battery last long enough while the other depletes in 48 hours. The solenoid needs to get electricity a modest 5 times a day; that's why I believe we can make it super efficient.

With our friends, we've so far programmed Arduino to open a solenoid from the Internet. The solenoid we've used was 220v because we had it in stock; it won't be what we need for our project. It was just a trial. On top of this, the Arduino has no WiFi module, just an Ethernet shield.

There's a remaining problem to solve, which is: what would happen if the Arduino fails? The door would be sealed 'forever'. We'll tackle that issue afterwards.

**TL;DR:** we'd love to open a lock via WiFi: the lock and Arduino should run solely on batteries that last more than 48 hours: a couple of months would be ideal! Can we work this out?

Thank you very much for your help, opinions, and time. I hope my question is up to the standards.

# Answer
> 1 votes
\[I'm coming in late but since this question got reposted, here goes:\]

If this not to be just a Proof of Concept, but to be actually installed, you really have to address the several points of failure (Arduino, Arduino power, solenoid, solenoid power) that could lock you out of the room forever ("ever" being the time needed to fetch and apply destructive tools :).

Assuming it's a POC, here are a few more ideas:

1. You need 12v for the solenoid. You can take your 5v from the same source using an efficient regulator. Advantage: one fewer point of failure (power source), and the Arduino could monitor the 12v source and send an alert if/when it starts to sag (which would only be useful if there's some head-room between its charged voltage and the minimum needed to drive the solenoid).
2. If you use Bluetooth LE on the Arduino instead of WiFi, but place another Arduino outside the door, somewhere with power (locked into the wall, the ceiling, or an adjacent room), the outer Arduino with "unlimited" power could talk BTLE to the inside Arduino. Advantage: Lower power consumption by the inside Arduino (unless step 1. makes it unnecessary). Disadvantage: More equipment (second Arduino); more complex system has additional ways to fail, though not necessarily to lock you out; possible additional point of vulnerability to intrusion.
3. Is that a steel door? If not, an inductive charging coil on the inside of it might let you temporarily apply an inductive charger from outside to provide power - or charge a small battery or even a capacitor - enough to unlock the door. Advantage: One less point of failure (loss of 12v). Disadvantage: More equipment; applicability depends on door material and thickness.

# Answer
> -1 votes
This is not the place to answer all the questions and design options that you have, but, to give you a starting point, you need to look at very low power arduino-compatible boards.

My suggestion is to use an ESP8266 module which can be programmed as an Arduino (have a look at here). The module is quite low power, and it may run for some days with AA batteries. You can use a 12V power source for both the module and the solenoid (you need a voltage regulator). The solenoid will only be activated when needed, so the rest of the time it won't consume any power.

The whole project is not a simple one. I would definitely suggest you to go step by step.

Good luck.

# Answer
> -1 votes
As far as the 12V motor is concerned, you can construct a decent H-bridge to shift polarity. I am assuming you are using a linear actuator or servo. Use a mechanical relay with 2 channels. Wire GND to NO1 and NO2, VCC (12V) to NC1 and NC2, and pull VOUT to motor from COM1 and COM2 - IIRC - and in your code track state of when each channel is on or off... It will short out if both relay channels are ON simultaneously, so that must not be possible.

Mechanical relays are slower to switch than transistors (can haul 230VAC/30VDC/10A with no voltage drop), but if you want a transistor H-bridge use the rather old TIP120 NPN Darlington (0.6-0.7V voltage drop per transistor), or MOSFETs. At least the TIP120s require heatsinking for \>=0.5A, but can drive 5-6A upto 60V, which is plenty.

As far as the wifi bit goes, I don't have enough experience. I would use a GET request to a web server/page and read what state the lock should be in at short intervals... no more than 5 seconds. A simple '1' or '0' in a text file will do. To output state, heartbeat (is the Arduino OK right now, or is something wrong?) and other stuff from the Arduino, use POST requests. You should use a simple database for this... PostgreSQL is my favourite, but you may want something simpler.

If you need precise timekeeping for events like open at 9.00 am, use a DS3231. Be careful to conserve SRAM, the Uno has only 2KB. There are guides on arduino.cc to help you with that (PROGMEM for immutable variables and the F macro for static strings). This is a good method, hope it helps.

---
Tags: wifi, battery, home-automation
---


# Question
Title: How to improve date-time control from RTC?
I want to run cameras at a remote site from external batteries as long as possible. I need power-miser Arduino to switch battery power on/off at set intervals (e.g. 5 min) during daytime only. I am a beginner with Arduino and electronics.

Have set up 'breadboard' arduino with mosfet module for switching the power supply and RTC module, both from Freetronics (http://www.freetronics.com.au/collections/modules/products/real-time-clock-rtc-module#.V-i-S8knuPs). Following their recommendation I'm using RTC library here: http://rweather.github.io/arduinolibs/index.html

I need to refine the crude hour-based script below. Weatherley library returns separate objects e.g date.day, time.hour etc. Is there a simple way to convert to date-time object? Then calculate sunrise and sunset times based on latitude?

```
  #include <JeeLib.h> //  power saving library
  ISR(WDT_vect) { Sleepy::watchdogEvent(); } // Setup jeelip watchdog
  #include <SoftI2C.h> // rweather lib for RTC module
  #include <DS3232RTC.h> //rweather lib for RTC module
  SoftI2C i2c(A4, A5); // assign pins to SDA and SCL
  DS3232RTC rtc(i2c);
  RTCTime time;
  int gatePin = 12;   //  mosfet Gate connected to digital pin
  int startHour = 6; // want to replace with sunrise time
  int endHour = 19; // want to replace with sunset time

void setup()
{
 pinMode(gatePin, OUTPUT);   //  output pin for mosfet module
}

void loop()
{ // main loop starts here
  rtc.readTime(&time);  //get current time
  if (time.hour >= startHour && time.hour < endHour) // check daytime
  {   // if condition begins here
      while(time.hour < endHour ) // daytime operating period

      {   //  while loop (day) begins here
      digitalWrite(gatePin, HIGH);   // turn on gate for power supply
      Serial.flush(); //needed before sleepy
      Sleepy::loseSomeTime(30000); // low power wait
      digitalWrite(gatePin, LOW);    // turn off gate for power supply
      Serial.flush(); // needed before sleepy
      for (int i=0; i <= 3; i++){
        Sleepy::loseSomeTime(65000); // low power wait
        } // end for loop
      rtc.readTime(&time);
      } // end while loop (day)
      } //  if condition (daytime) ends here
else
  { // else condition (night time) starts here
    while (time.hour >= endHour || time.hour < startHour )
    { // while loop (night) begins here
    for (int i=0; i <= 59; i++){
    Serial.flush(); // needed before sleepy
    Sleepy::loseSomeTime(65000); // low power wait
    } // end for loop
    rtc.readTime(&time);
    } // while loop (night) ends here
// need to refine timing else hour-long wait periods can run past the end of night period
  } // else condition (night) ends here
} //  main loop ends here

```

I will be very grateful for advice, many thanks in advance!

EDIT: Part of my original question could be answered - see below about time-date format *without* using RTC. Issues with RTC appear harder than I expected. I think they will need a new question later.

# Answer
> 3 votes
> Is there a simple way to convert to date-time object?

Not with this library. But you can find other libraries supporting the DS3232 which work with the Arduino Time library\[\]. This time library provides both the date and time in a single object, either:

* a `time_t`, which is just the number of seconds elapsed since a standard “epoch”
* a `tmElements_t` struct, which has the date and time broken into separate elements (year, month, day, hour...).

> Then calculate sunrise and sunset times based on latitude?

There are quite a few algorithms describes on the Web for that. The more accurate ones are also the more complex.

> `#include <SoftI2C.h>`

Doesn't your Arduino have a hardware I2C port? That would be more efficient than software emulation.

> `Serial.flush(); //needed before sleepy`

It's only needed if you are actually using the serial port.

**Edit**: I saw on your other question that you have been bitten by an incompatibility between the Arduino Time library and the file `time.h` from avr-libc. Now I just noticed that avr-libc includes the functions `sun_rise()` and `sun_set()` that you may find handy. Not sure they will play well with the Arduino time libraries though. One possible incompatibility is the fact that they use different epochs for defining `time_t` (year 1970 v.s. 2000).

# Answer
> 2 votes
I hope I am allowed to summarise progress. Edgar Bonet's answer above pointed me in the right direction regarding date-time format and I want to 'accept' that answer, although it did not resolve my difficulties with RTC. I need to ask a new question about RTC later.

Using the Time library Edgar Bonet recommended, I managed to set and change date-time format, and calculate duration between date-time instances. I hope my example below could perhaps be useful for other beginners. If anyone has suggestions to improve this example, please add them.

```
    #include <TimeLib.h> // https://github.com/PaulStoffregen/Time
    time_t tstart;

    void setup()  {
    Serial.begin(9600);
    // assume no RTC available therefore set date-time in this sketch
    // when serial monitor opens, date-time will be set as follows
    setTime(8,30,0,17,10,2016); // (hr,min,sec,day,mnth,yr);
    tstart = now();
    Serial.print("Started at: ");
    digitalClockDisplay();
    Serial.println();
    }

    void loop(){
    Serial.println("Waiting...");
    delay(20000 + random(500, 5000) );
    Serial.println();
    time_t tnow = now();
    Serial.print("Now it is: ");
    digitalClockDisplay();
    time_t duration = tnow - tstart;
    Serial.print("Duration since start: ");
    showDuration(duration);
    Serial.println();
    Serial.println();
    }

    // function to print current date-time
    // modified from example in TimeLib
    void digitalClockDisplay(){
      Serial.print("Date: ");
      Serial.print(day());
      Serial.print("-");
      Serial.print(month());
      Serial.print("-");
      Serial.print(year());
      Serial.print("  Time: ");
      Serial.print(hour());
      printDigits(minute());
      printDigits(second());
      Serial.println();
    }
    // utility function from TimeLib
    // to print leading zeros
    void printDigits(int digits){
      Serial.print(":");
      if(digits < 10)
        Serial.print('0');
      Serial.print(digits);
    }

    // function from example TimeRTCLog
    void showDuration(time_t duration){
    // prints the duration in days, hours, minutes and seconds
      if(duration >= SECS_PER_DAY){
         Serial.print(duration / SECS_PER_DAY);
         Serial.print(" day(s) ");
         duration = duration % SECS_PER_DAY;
      }
      if(duration >= SECS_PER_HOUR){
         Serial.print(duration / SECS_PER_HOUR);
         Serial.print(" hour(s) ");
         duration = duration % SECS_PER_HOUR;
      }
      if(duration >= SECS_PER_MIN){
         Serial.print(duration / SECS_PER_MIN);
         Serial.print(" minute(s) ");
         duration = duration % SECS_PER_MIN;
      }
      Serial.print(duration);
      Serial.print(" second(s) ");
    }

```

---
Tags: time, rtc
---


# Question
Title: LED and Switch Compolation Error Arduino 101
I'm getting an error on line 9 for some reason, (digitalWrite(Sender, HIGH);), and I just cant figure out why. My goal is to have two sets of flashing patterns, one for each switch state. I don't know how important this is but I'm using an Arduino 101. This is also my first day programming so the answer could be staring me right in the nose, (in fact, I would prefer that haha). Thank you for your time!

```
// Starting this by declairing intigers
int Sender = 2; // Switch Out on pin two
int LedG = 10; // LED Green out on pin ten
int LedR = 11; // LED Red out on pin eleven
int Reader = 12;  // Switch Input on pin twelve
//configuring I/O
pinMode(Sender = OUTPUT); // Setting pin two to output
pinMode(Reader = INPUT); // Making pin 12 set to read switch data
digitalWrite(Sender, HIGH); //Making pin two hot
//main loop
void loop() {
  if (digitalRead (Reader) == HIGH) { // if Switch input is reading on than do pattern A
    digitalWrite(LedG, HIGH); //turning on green led
    delay(50); //delay next instruction
    digitalWrite(LedG, LOW); //turn green led off
    digitalWrite(LedR, HIGH); //turn red led on
    delay(50); //delay next instruction
    digitalWrite(LedR, LOW); //turn red led off
  }
  else { //if switch input is readion off than play pattern b
    digitalWrite(LedR, HIGH); //turn red led on
    delay(1000); //delay next instruction
    digitalWrite(LedR, LOW); //turn red led off
    digitalWrite(LedG, HIGH); //turning on green led
    delay(1000); //delay next instruction
    digitalWrite(LedG, LOW); //turn green led off
  }
}

```

# Answer
> 3 votes
I notice that your pinMode function calls are not quite correct:

```
pinMode(Sender = OUTPUT); // Setting pin two to output
pinMode(Reader = INPUT); // Making pin 12 set to read switch data

```

Should be:

```
pinMode(Sender, OUTPUT); // Setting pin two to output
pinMode(Reader, INPUT); // Making pin 12 set to read switch data

```

Refer to https://www.arduino.cc/en/Reference/PinMode for more information.

And the whole section where you configure your I/O should be wrapped inside the `setup()` function.

```
//configuring I/O
void setup()
{
    pinMode(Sender, OUTPUT); // Setting pin two to output
    pinMode(Reader, INPUT); // Making pin 12 set to read switch data
    digitalWrite(Sender, HIGH); //Making pin two hot
}

```

---
Tags: programming, c++, led, switch
---


# Question
Title: Enable free fall detection using Arduino
I'm trying to get an arduino board to detect simple free fall condtions. Currently, I have a 9DOF sensor (https://learn.sparkfun.com/tutorials/lsm9ds0-hookup-guide) and am able to get the raw data from the sensor.

However I am unsure what to do from here onwards. From what I manage to gather, there is an alternative sensor ADXL345 accelerometer that has an inbuilt free fall component. I have tried modfying the code in such a way that it will work with the sensor I am using but to no avail.

The free fall detection does not need to be extremely accurate/precise considering there are many fall/jerk patterns. It is just for a proof of concept for a project of mine. With that in mind, any suggestions on how to proceed will be greatly appreciated (or if I should just get the ADXL345 accelerometer).

Thank you.

# Answer
> 4 votes
Sitting an accelerometer flatly on a bench will produce a value of 1G in one of the 3 axes.

Free fall of an accelerometer (assuming you haven't reached terminal velocity) should read near zero on all 3 axes.

I am not aware of a mode you can set for this, but if you check the values of the 3 axes and all are close to zero, you are probably in a free fall condition.

# Answer
> 0 votes
Take the root sum squared \[sqrt(acc\_x^2 + acc\_y^2 + acc\_z^2)\] of your accelerometer readings. This is your total acceleration vector. Then write a function that triggers the free fall variable when that equation is less than or equal to a certain threshold near to zero (the value itself depends on your accelerometer).

Your gyro and magnetometer will not help as they relate to the attitude (facing direction) and rotational speed of your thing, not the linear motion. Test and play with the threshold and you will get the most accurate result possible.

---
Tags: accelerometer
---


# Question
Title: Formula for current through shift register
Hi

I am programmer that just started learning electronics and Arduino. I built this simple circuit on Autodesk Circuits earlier. Originally I used 220 ohm resistors. Then when I ran the simulation and turned on more than 4 of the leds the simulator warned that I exceeded the max current for the shift register.

I then upgraded to 560 ohm resistors which solved the problem.

What I would like to know is how can I calculate the current through the shift register for each n-number of leds I turn on? That way I can calculate the right resistor that I need before I burn out my electronics.

Thanks for the help on this.

# Answer
It's just N×IL+IQ where N is the number of LEDs, IL is the current through each LED and IQ is the current the shift register needs to operate (*quiescent* current).

The current through each LED is just (VIN \- VLED) ÷ R, where VIN is 5V, VLED is the forward voltage drop of the LED, and R is the value of your resistor.

So you can combine it to be a single formula, if all your LEDs are the same and your resistors are the same, to:

IT = N × ((VIN \- VLED) ÷ R) + IQ
> 0 votes

---
Tags: arduino-uno, current, resistor, shift-register
---


title: Expected declaration before } token

text:
# Question
Title: Expected declaration before } token
Below is my code. The idea is it is supposed to wait for the ? character, print K, and turn on the LED. If it does not detect ? then it should keep waiting.

Below is my code:

```
incomingByte = Serial.read();
sendBack = K;
int pollTime = 200;

int ledPin = 9;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}

void loop() {
while(Serial.available())  {
  if(Serial.read == '?')  {
  Serial.print(sendBack);
  pinMode(9,OUTPUT);
  else  {
   delayMicroseconds(pollTime);
  }
}
}
}

```

# Answer
> 0 votes
Try this:

```
void setup() {
  Serial.begin(9600); //set baud rate.
  pinMode(9, OUTPUT);
}

void loop() {
  if (Serial.available())  { //Gets you the number of bytes that are available to be read from the serial port.
    if (Serial.read() == '?') {
      Serial.println("OK");
      digitalWrite(9, HIGH);
      delay(1000);
    }
  }
  else
  {
    digitalWrite(9, LOW);
  }
}

```

---
Tags: arduino-uno
---


# Question
Title: MATLAB - Read from 2 SPI inputs synchronously
I am using the MATLAB Arduino Support Package to create a setup where I can read force data from a load cell and positional data from an incremental encoder - then plot them on MATLAB. It must be done at the same time in order to produce a material stress-strain curve.

I am thinking of using the SPI Device functions to do this.

Can the data from the load cell and encoder be read synchronously?

# Answer
Yes and No. Synchronously in development slang means step-by-step execution. Asyncronously mean by some event.

Arduino has only one core. Even if you use interrupt, Arduino can only execute one command at once.

Best way for you I guess would be read both on Arduino and combine into single value to read at once. Just reading both with readDigitalPin would give huge latency.
> 2 votes

# Answer
Truly parallel sampling is rarely needed. Especially if you can separate the triggering (latching) of a reading in the peripheral from the act of subsequently transferring the latched value over SPI, it is likely you can merely trigger both in quick turn and then read them out in slightly slower turn.

But if you *truly* need simultaneous reading, then you will need a workaround. The ATmega used in classic Arduinos only has one hardware SPI engine. But you can also implement a software or "bit bang" SPI master using arbitrary digital I/O pins.

Typically this is done with single-bit GPIO operations, but if you place the critical SPI signals for both chips (probably SCLK, the others are usually only sampled at changes in that) on distinct pins of the same GPIO port, then you can use whole port operations at raw AVR level (below the Arduino API level) to drive them at effectively the same time.

To make this work, you would do the following:

1) For each SPI peripheral, figure out exactly at what transition of what part of what access sampling occurs. Make sure to include any internal setup or latency within the chip in the determination.

2) Start the access to whichever peripheral takes longer using port-wide operations which preserve the status of bits not related to this peripheral.

3) Add the access to the peripheral which takes less setup before the sampling instant by starting to include the bits connected to that in the values to be changed in the port wide GPIO operation.

4) Use a similar port-wide operation to trigger the critical sampling operation for both devices at the same time

5) Continue with whatever followup each device needs, and stop updating its pins when no more operations are needed by that device.

Do be aware that some SPI devices, particularly those which are ADC's or having ADC type behavior internally, can be quite sensitive to jitter or timing variation in the clock edges. You may want to look at using an interrupt or even a hardware counter/time or the SPI peripheral to generate the SCLK edges, and operate the other signals with interrupt driven software slaved to that.

Again, in most cases true parallelism will not be needed. But if it is needed methods such as this can achieve it at the cost of intricate software.
> 1 votes

---
Tags: arduino-uno, matlab
---


title: How do I clear sim800L buffer?

text:
# Question
Title: How do I clear sim800L buffer?
Let's say that I've tried sending an SMS directly from serial monitor or any kind of terminal. For whatever reason (syntax error, etc), my attempt fails. Now, I try sending it again, but this time by code (as seen on this site):

```
#include <SoftwareSerial.h>

//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 8

//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7

//Create software serial object to communicate with SIM800
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup() {
  //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(9600);
  delay(1000);

  Serial.println("Setup Complete!");
  Serial.println("Sending SMS...");

  //Set SMS format to ASCII
  serialSIM800.write("AT+CMGF=1\r\n");
  delay(1000);

  //Send new SMS command and message number
  serialSIM800.write("AT+CMGS=\"07194XXXXX\"\r\n");
  delay(1000);

  //Send SMS content
  serialSIM800.write("TEST");
  delay(1000);

  //Send Ctrl+Z / ESC to denote SMS message is complete
  serialSIM800.write((char)26);
  delay(1000);

  Serial.println("SMS Sent!");
}

void loop() {
}

```

The code sends not only the SMS within the code ("TEST"), but also the unwanted junk / remains of the previously unsuccessful sending attempt.

**Is there a way to clear the module's buffer before sending a new message?**

I guess I could restart the module before sending messages, but I was wondering whether there's a cleaner solution.

P.S. I apologize for the slightly misleading and irrelevant tags, but I can not use the nonexistent sim800L, which would be better suited for my question.

# Answer
According to the SIM800 AT Command Set you can terminate the sending of an SMS part way through by sending `ESC` (character 27).

So you can begin your sketch by first sending a number of `ESC` to ensure that any pre-existing text input for an earlier SMS is abandoned.

```
serialSIM800.write(27);
serialSIM800.write(27);
serialSIM800.write(27);

```

Only one should be needed, but it is best to repeat it a couple of times in case the first one isn't taken. You should then do a `CR/LF` to make sure it's ready for the next command.

```
serialSIM800.print("\r\n");

```

However, your method of controlling the modem is crude at best and not particularly reliable. The modem sends back responses from all the commands you send it. You should be reading in those responses and checking that the commands you sent actually worked. That way you can know if a command hasn't been accepted because it is in SMS reading mode (no response within 1 second, say), and you can force an escape.
> 0 votes

---
Tags: arduino-nano, gsm
---


# Question
Title: Are there any online data analysis websites for arduino IoT projects?
I am planning on making a system where multiple arduinos monitor the conditions of certain type of plant. (Each arduino monitors its own plant, but the plants are of the same species). Each plant would have a different placement in the yard(varies the light). The plants are watered as normal, without an exact amount of water. The arduinos would measure light, temperature, and soil water content. Each would send it to the cloud. My question is: Is their a cloud service that can analyze and "find" the best conditions(amount of water,light,temperature,etc) for type a plant, based on how healthy the plants are?(The health of the plants would be entered in manually by the person using the system). (Sorry if my question doesn't make sense, please ask me any questions you have ,Thanks.)

# Answer
> 2 votes
To send data to cloud you will need an internet shield and given that the individual plants are far apart, you will need a wifi shield for each plant that you want to monitor most likely the yun shield. Now for online services, there are a few like Temboo, Pushingbox, Initial State, Cayenne, Xively. Each of them works differently and you will need to choose which best suit you.

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


title: Arduino project list: What do I need?

text:
# Question
Title: Arduino project list: What do I need?
Being new to Arduino I would like to know if I can build a project on this platform.

I want to connect Arduino to a few car parking sensors, a video camera and a mobile phone. The preferred language is JavaScript.

* Is it something feasible?
* Are there JavaScript libraries that can help with automation?
* What version of Arduino should I use? Arduino UNO or something else?

Thanks, George

# Answer
Arduino is in C/C++/a bit of Java Script. That's the normal IDE language so no you can't change it. Even other compiler mostly use one of the many C languages.

Car parking sensor question anwsered here.

For the hardware, use an UNO Rev3. It's the latest and most expandable board. It's also cheaper then others and easy to use.
> -1 votes

---
Tags: arduino-uno
---


title: Running Pthreads (POSIX) on an Arduino

text:
# Question
Title: Running Pthreads (POSIX) on an Arduino
So I have a project where I need to run pthreads (coded in C) on an Arduino Uno. I've written and compiled the code and the output is what we need when I use a C compiler. But I'm having trouble running it on the board. I've installed the Pthreads library in the libraries folder of the Arduino, but it still gives me erroneous errors.

I'm jumbling back and forth without finding a solution, can anyone give me any tips? It's become so annoying that I'm thinking of buying a Pi.

Any help is much appreciated.

Edit: let me rephrase: the professor wants us to implement pthreads on an Arduino or Pi. I didn't decide pthreads is the solution, it is the requirement.

# Answer
> 2 votes
> I need to run pthreads ...

You probably don't *need* to run pthreads. This sounds like an X-Y problem.

What you are probably saying is "I need to do multiple things at once" (such as flashing LEDs whilst taking ADC readings, or play sounds at the same time as moving a vehicle forwards).

You could get better answers if you described the project (X) and not your proposed solution (Y) which you think is pthreads.

I have a web page about How to do multiple things at once ... like cook bacon and eggs which goes into this sort of thing in some detail.

Some example code from that page which blinks different LEDs at different rates is:

```
// Which pins are connected to which LED
const byte greenLED = 12;
const byte redLED = 13;

// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long greenLEDinterval = 500;
const unsigned long redLEDinterval = 1000;

// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer;
unsigned long redLEDtimer;

void setup ()
  {
  pinMode (greenLED, OUTPUT);
  pinMode (redLED, OUTPUT);
  greenLEDtimer = millis ();
  redLEDtimer = millis ();
  }  // end of setup

void toggleGreenLED ()
  {
   if (digitalRead (greenLED) == LOW)
      digitalWrite (greenLED, HIGH);
   else
      digitalWrite (greenLED, LOW);

  // remember when we toggled it
  greenLEDtimer = millis ();
  }  // end of toggleGreenLED

void toggleRedLED ()
  {
   if (digitalRead (redLED) == LOW)
      digitalWrite (redLED, HIGH);
   else
      digitalWrite (redLED, LOW);

  // remember when we toggled it
  redLEDtimer = millis ();
  }  // end of toggleRedLED

void loop ()
  {

  // Handling the blink of one LED.
  if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleGreenLED ();

  // The other LED is controlled the same way. Repeat for more LEDs
  if ( (millis () - redLEDtimer) >= redLEDinterval)
    toggleRedLED ();

/* Other code that needs to execute goes here.
   It will be called many thousand times per second because the above code
   does not wait for the LED blink interval to finish. */

}  // end of loop

```

---

> It's become so annoying that I'm thinking of buying a Pi.

Sure you can do that. You can buy a Mac or a Windows PC. You can buy 5 Arduinos. But if you want to learn how to do multiple things on an Arduino you can learn how to manage a "state machine" and do it all on $5 of hardware.

---

As an example of what *can* be done see this post about a retro arcade game called Toorum's Quest written by Petri Häkkinen and run on an Atmega328P (same chip as in the Arduino Uno).

Hardware and screenshots:

In his code (which I compiled using the Arduino IDE to test it) he has:

* Multiple sprites on a TV screen with a resolution of 104x80 with 256 colors.
* Sprites are multiplexed so you can have as many as you want on the screen.
* He moves them around according to game logic
* He plays music and sound effects at the same time
* He reads from a game controller

---
Tags: arduino-uno
---


# Question
Title: Can LilyPad Main Board interface with a sensor via UART?
Is the LilyPad Arduino Main Board physically capable of interfacing with, let's say, a LeddarTech LeddarOne Optical Rangefinder, which has a 3.3v UART interface? I understand that the LilyPad has a serial interface, but I wouldn't be sure if it was meant to handle more than just transferring code.

# Answer
Yes you can.

Lilypad \<\> Other device using UART

Rx \< Tx

Tx \> Rx

Note that you cannot use 5V with the lilypad if you do this. If you do want to use 5V with the Arduino, then you'll have to put a voltage divider between the Tx and Rx (other wise you might fry the other UART device using 3.3V.

Also, when you upload the code FROM your computer TO your Lilypad, you have to connect all other UART device connected to the Lilypad. Connecting other devices to the Tx and Rx of the Lilypad while uploading a code to it might cause lag or bugs.

Hope I anwsered your question!
> 1 votes

---
Tags: serial, sensors, uart
---


title: Most memory efficient way to program

text:
# Question
Title: Most memory efficient way to program
I currently know 3 ways to do a program. Which one of them is the most memory friendly. Note that the example code is simple (blinking a led) and the final code will be VERY VERY complex. Also, the way I code is not the best, so suggest any suggestions in the way to write things or where to put them please.

1- All in the loop. The most basic way of programming.

```
const int led = 2;
const int interval = 500;
bool ledState = false;

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

void loop() {
  ledState = !ledState;
  digitalWrite(led, ledState);
  delay(interval);
}

```

2- Functions. Similar to the loop but a little neither. Can be splitted into many tabs.

```
const int led = 2;
const int interval = 500;
bool ledState = false;

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

void loop() {
  blinkLed();
}

void blinkLed()
{
  ledState = !ledState;
  digitalWrite(led, ledState);
  delay(interval);
}

```

Then finnaly, objects. The most supreme of them all (and the one that I know the least). I like objects and classes because multitasking with it is much easier. It is more flexible too. Code taken from here.

```
class Flasher
{
  // Class Member Variables
  // These are initialized at startup
  int ledPin;      // the number of the LED pin
  long OnTime;     // milliseconds of on-time
  long OffTime;    // milliseconds of off-time

  // These maintain the current state
  int ledState;                 // ledState used to set the LED
  unsigned long previousMillis;   // will store last time LED was updated

  // Constructor - creates a Flasher
  // and initializes the member variables and state
  public:
  Flasher(int pin, long on, long off)
  {
  ledPin = pin;
  pinMode(ledPin, OUTPUT);

  OnTime = on;
  OffTime = off;

  ledState = LOW;
  previousMillis = 0;
  }

  void Update()
  {
    // check to see if it's time to change the state of the LED
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
      ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;   // Remember the time
      digitalWrite(ledPin, ledState);   // Update the actual LED
    }
  }
};

Flasher led(2, 500, 500);

void setup()
{
}

void loop()
{
  led.Update();
}

```

So, which is the best out of those 3.

# Answer
That is an incredibly hard question to give a definitive answer to.

In general using OO consumes more memory, but that is the price you pay for greater flexibility and ease of use. The difference is usually minor though. Variables within an object take the same amount of space as variables outside an object. It's just the overhead of instantiating the object itself that adds to the memory usage, and that can be quite small, depending of course on what the object does.

Calling functions increases memory use on the stack. Every time you call a function the return address and a number of the internal CPU registers, along with some of the parameters, get placed on the stack. The deeper your function calls go the bigger the stack gets. But that is all temporary - as you leave the functions the stack shrinks again.

However, this is where it gets more complex:

The compiler performs optimizations. One of them is to consider functions for *inlining*. This replaces the function call with the content of the function that is being called. It makes for a slightly larger program, but it's a program that runs faster and uses less stack.

In your first two examples, because there is only one call to the `blinkLed()` function, the compiler will see that as a good candidate for using inline. So your first and second programs may well both end up exactly the same.

There are times, as well, where variables that you declare don't actually ever exist. For instance, if you use a couple of temporary variables to do a few calculations in a function and then return the result the compiler may instead just use CPU registers to store the temporary values instead of allocating variable space in memory.

So it is very hard to say "this is better" or "that is better". Instead you should pay more attention to how and where you declare and use your variables.

In general there are two rules:

1. Keep your variables the smallest size possible for the contents (use 8 bit variables instead of `int` for storing smaller numbers).
2. Keep the scope of variables as small as possible.

The latter is often overlooked. The scope of a variable is the block (delimited by `{` and `}` for example) where the variable is declared. Anything inside that block, including sub-blocks, can see the variable. By keeping the variable in as small a scope as possible you increase the chances that the compiler will choose to use CPU registers instead of allocating memory. For example:

```
int i;

for (i = 0; i < 1000; i++) {
    .... do something ....
}

.... other things ....

for (i = 30; i < 2000; i++) {
    .... do something else ....
}

```

That is pretty much guaranteed to allocate memory for `i`. However:

```
for (int i = 0; i < 1000; i++) {
    .... do something ....
}

.... other things ....

for (int i = 30; i < 2000; i++) {
    .... do something else ....
}

```

With that method the variable `i` will only exist within the first loop, after which it disappears. It is then recreated as an entirely new variable for the second loop. It doesn't need to stay in memory in between. The compiler may just place it in internal registers, or it may reuse the same block of memory, etc.

Also by keeping scope as small as possible you increase the ability of the compiler to re-use the same bits of memory for different purposes. 10 integers in different scopes doesn't mean 20 bytes of memory - it may mean just 2 bytes for all 10 integers.

So as you can see managing memory effectively can be a bit of a black art at times.
> 8 votes

# Answer
There are very good observations about coding with limited resources in this book:

https://www.amazon.com/Programming-Arduino-Next-Steps-Sketches/dp/0071830251

It covers the items you ask about and more besides, including some brought up in the comments.

As others indicate- there are some 'best' practices to consider but often the most efficient method is context-dependent.
> 1 votes

---
Tags: c++, arduino-ide, c, memory-usage, memory
---


# Question
Title: Can a timer be used in both CTC and (fast) PWM mode simultaneously?
I would like to generate a sequence of pulses of varying lengths in the range of 0-100us, so that from the start of one pulse to the start of the next there is a delay of 100us. I have set up timer0 in CTC mode to trigger an interrupt every 100us.

In this interrupt, I would like to turn the appropriate pin high, read the length of the current pulse from an array, and then configure the timer in such a away that it turns the pin off as soon as the pulse length has elapsed (I am hoping that this is possible without using an interrupt for turning off the pin). It seems that the PWM functionality can do what I want, if I use the second output compare register.

In any case this seems possible using a secondary timer in PWM mode, but I'd like to know whether the same is possible using only a single timer. From what I've seen in the datasheets the answer seems no, but perhaps I am missing something.

Can a timer be used in both CTC (with output compare register A) and PWM modes (with output compare register B)?

# Answer
> 2 votes
As noted in previous answer, CTC and PWM are distinct modes, and only one mode can be selected at any given moment.

However, your problem description sounds like mode 14 on timer 1 will serve. That's a Fast PWM mode that uses ICR1 as TOP. OCR1A or OCR1B can be used for output compare, depending whether you want to output on OC1A or OC1B. OC1A is PB1, or digital pin 9 on ATmega328 systems, and OC1B is PB2, or digital pin 10.

On a 16 MHz system, you would put 1600 in ICR1, so there would be an Overflow Interrupt every 100 μs. At each Overflow Interrupt you would put the currently desired pulse-length into OCR1A or OCR1B. This will work so long as your Overflow ISR takes fewer cycles than any desired pulse length.

You would set COM1A1/COM1B1 and COM1A0/COM1B0 to 1, 0, because Table 16-3 for this combination says, “Clear OC1A/OC1B on Compare Match, set OC1A/OC1B at BOTTOM (non-inverting mode).” \[Or see §16.9.3 (“Fast PWM Mode”) of the 2015 '328 spec, which says: “In non-inverting Compare Output mode, the Output Compare (OC1x) is cleared on the compare match between TCNT1 and OCR1x, and set at BOTTOM.”\]

# Answer
> 3 votes
Technically no. CTC and PWM are distinct modes of operation.

*However*, more advanced PWM modes, specifically mode 7 for 8-bit timers and modes 14 and 15 for 16-bit timers, allow specifying an arbitrary timer duration in OCRxA or ICRx while still allowing PWM operation using the other output compares.

---
Tags: pwm, atmega328, timers
---


title: Error in the arduino code

text:
# Question
Title: Error in the arduino code
This is my arduino code for interfacing with an ESP8266:

```
#include <ESP8266WiFi.h>

int incomingByte;
String value;
char a;
int flag=0;
String valueserial;
int valueint;

const char* ssid     = "NIDHI";
const char* password = "nidhi123";

String data;

void setup() {
  Serial.begin(9600);
  delay(6000);
  data = "";
  valueserial = "";

//
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 //
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);

    Serial.print(".");

  }
  //
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
//
}

void loop() {
  flag = 0;
  delay(5000);
  valueserial = "";
  // Use WiFiClient class to create TCP connections
  WiFiClient client;
String url = "/display.php";

if (Serial.available() > 0){
    while (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();
                valueserial += char(incomingByte);
              }
    if (incomingByte == '\n') {
      Serial.print("Value:");
      Serial.println(valueserial.toInt());
      Serial.print("String: ");
      Serial.println(valueserial);
      // clear the string for new input:
    }
    //valueint = Serial.parseInt();
    data = "?value=" + String(valueserial.toInt());

    url += data;
    delay(100);
    flag = 1;
}

if (client.connect("www.soil.pixub.com",80) && flag==1) { // REPLACE WITH YOUR SERVER ADDRESS
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
    "Host: soil.pixub.com\r\n" +
    "Connection: close\r\n\r\n");
    Serial.println("!!!!DATA POSTED!!!!");
   }

       //valueserial += '\0';
  //valueserial = Serial.read();
//
Serial.println(data);
//
  if (client.connected()) {
    client.stop();  // DISCONNECT FROM THE SERVER
  }
//
  Serial.println();
  Serial.println("closing connection");
//
}

```

And i am getting the following errors

```
Arduino: 1.6.12 (Windows 10), Board: "Arduino/Genuino Uno"

In file included from C:\Users\Akshay\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFi.h:33:0,

                 from C:\Users\Akshay\Downloads\esp8266code\esp8266code.ino:3:

C:\Users\Akshay\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory

 #include <queue.h>

                   ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

# Answer
> 2 votes
The ESP8266WiFi library is meant to be used when programming an ESP8266 using the Arduino environment. In Arduino lingo: It's supposed to be used with a ESP8266 Board.

It's -not- meant to be used with a 'Arduino/Genuino Uno' board, which is what you are trying to do. This is why it fails.

What you want to use is the ESP8266wifi library, which is used with a ESP8266 connected to a Arduino, and flashed with AT firmware.

And yes, it's confusing, there are two very similar libraries:

# Answer
> 0 votes
The file queue.h is either missing or is not in the expected location (correctly installed). Make sure you have your SDK and Libraries correctly installed and up-to-date. In an extreme case, you might consider reinstalling both to make sure the build environment is correct.

---
Tags: esp8266
---


# Question
Title: How to get real time data from ardunio board using NodeJS and send to my remote server without the wifi module?
As the question, How to get real time data from ardunio board using NodeJS and send to my remote server without the wifi module.how to do this without any hardware.

# Answer
It is pretty easy to send data with the help of NodeJS. Here i attach the code.

```
var request = require('request');
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;

var serialPort = new SerialPort("COM5", {
  baudrate: 9600,
  parser: serialport.parsers.readline("\n")
});

serialPort.on("open", function () {
  console.log('open');
  serialPort.on('data', function(data) {
    console.log(data);
  });
});

serialPort.on('data', sendSerialData);

function sendSerialData(data) {
 request({
  uri: "http://127.0.0.1/write_data.php?value="+data,
 method: "GET",
  timeout: 10000,
   followRedirect: true,
   maxRedirects: 10
}, function(error, response, body) {
   console.log(body);
});

}

```
> 0 votes

---
Tags: arduino-uno
---