title: DHT11 and Pulse sensor incompatibility?

text:
# Question
Title: DHT11 and Pulse sensor incompatibility?
I am working on an IoT project to send data acquired from DHT11 and PulseSensor to a website. I can send the data properly when I use each of sensors alone but when I write a wrapper to use both sensors simultaneously, DHT11 returns check-sum error. PulseSensor uses interrupt based on TIMER2 , whenever I remove interruptSetup(); from setup block the problem is solved but obviously the PulseSensor does not work in this case. I searched inside the DHT11 library, as far as I could understand it does not use any Timer or interrupt to make a conflict with PulseSensor requirements. This project use to serial port to communicate with PC for debugging and another one to communicate with ESP8266. Please help me in finding a solution for this problem. Or guide me to websites that Arduino gurus track more :)

```
#include <SoftwareSerial.h>
#include <stdlib.h>
#include <dht.h>

dht DHT;
//DHT11 PIN
#define DHT11_PIN 5
// LED
int ledPin = 13;

// Heart_Sensor_Variables
int pulsePin = 0;                 // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 10;                // pin to blink led at each beat

// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

//ISR variables
volatile int rate[10];                    // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;          // used to determine pulse timing
volatile unsigned long lastBeatTime = 0;           // used to find IBI
volatile int P =512;                      // used to find peak in pulse wave, seeded
volatile int T = 512;                     // used to find trough in pulse wave, seeded
volatile int thresh = 525;                // used to find instant moment of heart beat, seeded
volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

//function Prototypes
void interruptSetup(void);

//Thingspeak API key
String apiKey = "REMOVED FOR SECURITY REASONS";

// connect 11 to TX of Serial USB
// connect 12 to RX of serial USB
SoftwareSerial ser(11, 12); // RX, TX

// this runs once
void setup() {
  // initialize the digital pin as an output.
  pinMode(ledPin, OUTPUT);

  // enable debug serial
  Serial.begin(57600);
  // enable software serial
  ser.begin(57600);
  // reset ESP8266
  Serial.println("AT+RST");

  // sets up to read Pulse Sensor signal every 2mS
   interruptSetup();
}

// the loop
void loop() {
  // blink LED on board
  digitalWrite(ledPin, HIGH);
  delay(200);
  digitalWrite(ledPin, LOW);

//Read DH11 Data
  int chk = DHT.read11(DHT11_PIN);

// DISPLAY DATA
switch(chk) {
  case 0: ser.println("OK"); break;
  case -1: ser.println("Checksum error!"); break;
}

  ser.print(DHT.humidity, 1);
  ser.print(",\t");
  ser.println(DHT.temperature, 1);

if (QS == true){     // A Heartbeat Was Found
  ser.println("BPM and IBI have been Determined");
  ser.println(BPM, 1);
  ser.println(IBI, 1);

                       // BPM and IBI have been Determined
                       // Quantified Self "QS" true when arduino finds a heartbeat
        digitalWrite(blinkPin,HIGH);     // Blink LED, we got a beat.

        QS = false;                      // reset the Quantified Self flag for next time
  }

  // TCP connection
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += "184.106.153.149"; // api.thingspeak.com
  cmd += "\",80";
  Serial.println(cmd);
  delay(1000);

  if(Serial.find("Error")){
    ser.println("AT+CIPSTART error");
    return;
  }

  // prepare GET string
  String getStr = "GET /update?api_key=";
  getStr += apiKey;
  getStr +="&field1=";
  getStr += String(DHT.humidity);
  getStr +="&field2=";
  getStr += String(DHT.temperature);
  getStr +="&field3=";
  getStr += String(BPM);
  getStr +="&field4=";
  getStr += String(IBI);
  getStr += "\r\n\r\n";

  // send data length
  cmd = "AT+CIPSEND=";
  cmd += String(getStr.length());
  Serial.println(cmd);
 delay(500);
  if(Serial.find(">")){
    Serial.print(getStr);
  }
  else{
    Serial.println("AT+CIPCLOSE");
    // alert user
    ser.println("AT+CIPCLOSE");
  }

  // thingspeak needs 15 sec delay between updates
  delay(16000);
}

void interruptSetup(){
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

// THIS IS THE TIMER 2 INTERRUPT SERVICE ROUTINE.
// Timer 2 makes sure that we take a reading every 2 miliseconds
ISR(TIMER2_COMPA_vect){                         // triggered when Timer2 counts to 124
  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // keep track of the time in mS with this variable
  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise

    //  find the peak and trough of the pulse wave
  if(Signal < thresh && N > (IBI/5)*3){       // avoid dichrotic noise by waiting 3/5 of last IBI
    if (Signal < T){                        // T is the trough
      T = Signal;                         // keep track of lowest point in pulse wave
    }
  }

  if(Signal > thresh && Signal > P){          // thresh condition helps avoid noise
    P = Signal;                             // P is the peak
  }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250){                                   // avoid high frequency noise
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) ){
      Pulse = true;                               // set the Pulse flag when we think there is a pulse
      digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED
      IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
      lastBeatTime = sampleCounter;               // keep track of time for next pulse

      if(secondBeat){                        // if this is the second beat, if secondBeat == TRUE
        secondBeat = false;                  // clear secondBeat flag
        for(int i=0; i<=9; i++){             // seed the running total to get a realisitic BPM at startup
          rate[i] = IBI;
        }
      }

      if(firstBeat){                         // if it's the first time we found a beat, if firstBeat == TRUE
        firstBeat = false;                   // clear firstBeat flag
        secondBeat = true;                   // set the second beat flag
        sei();                               // enable interrupts again
        return;                              // IBI value is unreliable so discard it
      }

      // keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // clear the runningTotal variable

      for(int i=0; i<=8; i++){                // shift data in the rate array
        rate[i] = rate[i+1];                  // and drop the oldest IBI value
        runningTotal += rate[i];              // add up the 9 oldest IBI values
      }

      rate[9] = IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // add the latest IBI to runningTotal
      runningTotal /= 10;                     // average the last 10 IBI values
      BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!
      QS = true;                              // set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (Signal < thresh && Pulse == true){   // when the values are going down, the beat is over
   digitalWrite(blinkPin,LOW);            // turn off pin 13 LED
    Pulse = false;                         // reset the Pulse flag so we can do it again
    amp = P - T;                           // get amplitude of the pulse wave
    thresh = amp/2 + T;                    // set thresh at 50% of the amplitude
    P = thresh;                            // reset these for next time
    T = thresh;
  }

  if (N > 2500){                           // if 2.5 seconds go by without a beat
    thresh = 512;                          // set thresh default
    P = 512;                               // set P default
    T = 512;                               // set T default
    lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
    firstBeat = true;                      // set these to avoid noise
    secondBeat = false;                    // when we get the heartbeat back
  }

  sei();                                   // enable interrupts when youre done!
}// end isr

```

# Answer
The DHT requires some precise timing on its one-wire interface e.g. a \>40us HIGH pulse == 1, while a \<40us HIGH pulse == 0. Your DHT library doesnt use interrupts directly but it does use `micros()` which is based on regular interrupts, which are disabled automatically when you are within the TIMER2 ISR (no need for your explicit `cli()` and `sei()`, by the way). If you waste too much time in your ISR, you'll miss bits/pulses on the DHT line and obtain incorrect data, hence your checksum error.

The simplest solution I can think of is to disable the TIMER2 interrupt before the `read11()` call and enable it again after. I dont have much experience with AVR interrupts but I think this small change should do it:

```
#define TIM2_EN() (TIMSK2 = 0x02)
#define TIM2_DIS() (TIMSK2 = 0x00)

// your code as usual

void loop(){
  // ...as before...

  TIM2_DIS(); //Enable TIMER2 Interrupt

  //Read DH11 Data
  int chk = DHT.read11(DHT11_PIN);

  TIM2_EN(); //Disable TIMER2 Interrupt

 //...as before...
}

// your code as before

```
> 0 votes

# Answer
```
// THIS IS THE TIMER 2 INTERRUPT SERVICE ROUTINE.
// Timer 2 makes sure that we take a reading every 2 miliseconds
ISR(TIMER2_COMPA_vect){                         // triggered when Timer2 counts to 124
  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor

```

Interrupts are automatically disabled in an ISR.

Don't do lengthy things in an ISR (like analogRead). That takes 104 µs when an ISR should take only a few µs.
> 0 votes

---
Tags: sensors, interrupt, timers, temperature-sensor
---


# Question
Title: Digit LED has single input, multiple outputs for each segment. Concerns about "sinking" 5v supply into digital pins
The model name is 5161BS

Pins 3/8 are input and the rest are output for each individual segment.

I have connected pin 3 to the 5v pin on the Arduino, and the rest to individual digital pins.

With a simple sketch with the pins set to mode output, all segments are lit.

My concern is that the way I am turning off each segment is by setting the output pin to high.

Meaning

```
5v pin --> LED <-- Digital pin

```

Is this dangerous to have two voltage sources going in the same direction? Is there another way to do this?

# Answer
This is called a common-anode LED. The anodes (+ side) are shared. They probably dedicate two pins (3 and 8) to share the current to the anodes.

Connecting the common anode to +5V is fine. However you *should have* current-limiting resistors between each of the other pins (the cathodes) and the Arduino digital pin. Otherwise you are getting the Arduino to try to "sink" its own 5V supply through a digital pin, which far exceeds its rating. You will probably damage the output driver MOSFETs and they will stop working. Plus the excessive current will damage the LEDs as well.

See the LED resistor calculator. Something like a 330 ohm resistor, in series with *each* of the cathodes, should be adequate.

Now, setting the digital pins to output will "sink" 10 mA or thereabouts from +5V, through the LED (which lights up) and through the digital pin to ground.

You control what "number" you see on the LED by turning off the appropriate pins, to make the segments light up.

Also see The care and feeding of LEDs.
> 1 votes

# Answer
The device you have is a common anode display. This means that the anodes (+ve terminals) of all the LEDs are connected to one common pin (well, 2 pins actually, pin 3 and 8 are connected internally) . Their cathodes (-ve terminals) are what make up the remaining pins. Now, to light up any LED, you need 5 V at its anode and GND at its cathode. You have connected 5 V to pin 3, which stands for the common anode of every LED, so all that is left for any LED to turn on, is for you to connect GND to its corresponding cathode. So when you made all the remaining pins (the cathodes) OUTPUT, by default the Nano sets those pins to a logic LOW (or GND) value, so ALL the LEDs got lit up. Each LED now has `5 - 0 = 5 V` across its terminals and is forward-biased.

However, when you write HIGH to any cathode, the potential difference across the associated LED/segment is now zero, because that LED has 5 V at its anode (pin 3/8) and 5 V at its cathode (as a result of writing HIGH), and `5 - 5 = 0 V` so it is reverse-biased (at least 2 V or thereabouts is needed for a red LED to become forward-biased) and so the segment turns off. And this is how you control which segment is on at any time: You write a LOW to a cathode to turn on the associated segment, and write HIGH to turn it off. It sounds counter-intuitive but it follows if you think about it. Regarding your question, there's no damage being done to anything; the minimum voltage across the LED is 0 V (well below its maximum peak inverse voltage), while the maximum voltage across the LED is around 2 V, if you use the **highly recommended** current-limiting resistors (220/330 ohms is good) in series between each cathode and its Arduino digital pin.

Without any resistors, you will be drawing a lot of current through each pin, in total, a lot more than the Nano can safely supply. Use resistors that limit the current through each LED to 10-20mA.
> 2 votes

---
Tags: led, arduino-nano
---


# Question
Title: 434 RF Transmitter and Receiver for distance measurement problem
As a student I'm working on a project where we use 434 MHz RF Transmitter and receiver pairs for distance measurement. I know that this technology is not a good choice for this, but we have to deal with this problem due to external constraints.

Here is the receiver: RF Link Receiver - 4800bps (434MHz).

I did a little bit of research how these receivers works, but I found it a bit overwhelming to understand them bit by bit.

We want to use the signal strength for distance measurement. So we tried sending pulses of signals from one transmitter to a receiver. If the amplitude of the signal received is higher than a certain value (let's say 3V), it sends back a signal (let's call it trigger signal) in the gap between the two pulses.

The problem is that that these signals seems to affect each other even though they are not in the same time (so it's not superposition that we are talking about). When there is a signal sent back, the next pulse will be lower, which results in false distance measurement.

The whole difficulty is (to me it seems) that we are not using these signals to send data, we are using it for distance measurement. My idea is that we are using too long pulses and the AC coupling in the receiver doesn't tolerate it, but again, I don't have enough electrical knowledge to safely say that.

I know this is not descriptive, but I don't know how to make it more descriptive, so I'm happy to answer more questions on demand.

# Answer
It is very likely you have an AGC problem. Try to slow down the measurement. The sender shall send data not often than once per second.

This idea is not fully perfect for doing a distance measurement. It measures incoming power strength - affected by walls, reflection, AGC of the receiver, and a lot more. If you have a scope, measure the waveform on the pin 3 of the module (linear out). It is not a constant voltage, I am afraid, so you need some sort of averaging too.

A tricky way to get along even if you have an AGC is to measure how long the AGC needs to settle. The AGC works as follows: it detects the signal, and within some time (say, 2ms) it will change the amplification so that the signal will look having the full amplitude.

* compare on a two channel scope the signal pulse driving the transmitter
* and the signal on the pin 3 of the receiver module

If you are lucky, you'll see that actually pin3 or pin2 output is delayed a bit compared to the transmitter driving pulse. The delay depends on the power of the incoming signal to the receiver, which depends on the distance.

I was able to make an acceptable distance sensor from a standard AGC enabled IR receiver using the principles above.
> 1 votes

---
Tags: arduino-uno, electronics, rf
---


# Question
Title: DS18B20 Temperature Sensor return as float function returning null 50% of the time
I just got an DS18B20 Temperature sensor and am trying to modify the example code to use a function instead. Below is my `getTemp` function. It's working but returning results with a 0 value part of the time for example:

> Temperature = 72.39
> Temperature = 0.00

If I add `Serial.print(fahrenheit);` within the function I am always provided with the correct temperature. I though this may have to do with needing a delay but adding `delay(5000);` in my loop didn't help.

I'm assuming it's something simple I'm not understanding about how `floats` return.

```
#include <OneWire.h>

// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library

OneWire  ds(2);  // on pin 10 (a 4.7K resistor is necessary)

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

float getTemp(char tScale) {
  byte i;
  byte present = 0;
  byte type_s = 0;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    ds.reset_search();
    delay(250);
    return false;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();

  }

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  if (tScale == 'C') {
    return celsius;
  }
  else if (tScale == 'F') {
    return fahrenheit;
  }

}
void loop(void) {
    Serial.print("Temperature = ");
    Serial.println( getTemp( 'F' ) );

}

```

Edit: Interesting enough, adding an `if` statement to the loop fixes this, however. I'd still like to understand what is going on:

```
void loop(void) {
  if ( getTemp( 'F' ) == 0 ){
    Serial.print( "Temperature = " );
    Serial.println( getTemp( 'F' ) );
  }
}

```

# Answer
> 1 votes
You have intermittent communication problems.

Your address search occasionally fails and `getTemp()` returns false. In C++ (and many other languages) false will be implicitly cast to `(int) 0`, `(float) 0.0f`, and so on.

Your `getTemp()` function also is difficult to debug because the multiple return statements have different meaning.

After the `delay(250);` you do a `return false;` in order to skip the rest.

In the example at https://www.pjrc.com/teensy/td\_libs\_OneWire.html the meaning of the `return` statement(s) is different. There the return happens within the `void loop()` function, where it simply means to interrupt the current execution (without returning a value) and continue with the next loop.

While it is generally okay to have multiple `return`, it can sometimes be problematic and I recommend to avoid it.

If you want to clean this up while still preserving the ability to detect a fault, you have a couple of options (order from most to least recommended):

* do the setup/checking in a different function (and only call the second one if the first one succeeded), i.e. `if (isReady()) { Serial.println(getTemp()); }`
* set a separate error variable, i.e. `error = true; return 0;` (and then check `error` later)
* define a 'default' value that you interpret as an error (and never expect to be a temperature), i.e. `return NAN; // not a number`

---
Tags: arduino-uno, temperature-sensor, float, ds18b20
---


# Question
Title: Is there a semi-permanent way to attach wires to the Nano?
At least for prototyping, is there a semi-permanent way to attach wires to the Nano posts?

And yes, usually the Nano is hanging in free space by its wires (yes I know, quick and dirty, should be using something cleaner, even for prototypes). So I'm hoping for the best of both worlds, sturdy "enough" to stay attached, yet possible to remove and switch around. Having no luck finding such advice on the internet, perhaps searching for the wrong terms.

**EDIT:** I neglected one important point, each wire is attached individually just like the SparkFun wires with the female header as mentioned in @TheDoctor's answer below.

# Answer
There are jumper wires that have a female header on one end and a male header on the other. Example: https://www.sparkfun.com/products/9140

You could also attatch several wired to a strip of breakaway female headers, such as https://www.sparkfun.com/products/115
> 6 votes

# Answer
A wire wrap tool can work well for this - the wrappings tend to be fairly secure if done right, though the wire itself can break if stressed.
> 2 votes

# Answer
The *entire* premise behind Gravitech's design of the Arduino Nano was for it to be plugged into a **breadboard**. If done so, then none of the pins are left *dangling*. From Arduino's webpage for the Nano:

> The Arduino Nano is a small, complete, and *breadboard-friendly* board based on the ATmega328 (Arduino Nano 3.x) or ATmega168 (Arduino Nano 2.x). It has more or less the same functionality of the Arduino Duemilanove, but in a different package. It lacks only a DC power jack, and works with a Mini-B USB cable instead of a standard one. The Nano was designed and is being produced by Gravitech.

From Gravitech's webpage for the Nano:

> Arduino Nano is a surface mount *breadboard* embedded version with integrated USB. It is a smallest, complete, and *breadboard friendly*.
>
> ...
>
> Nano’s got the *breadboard-ability* of the Boarduino and the Mini+USB with smaller footprint than either, so users have more *breadboard* space.

If you have a Nano in such a *dangling* state, then you are using the wrong sort of Arduino board for the wrong purpose.

Obviously a Nano will work just fine when *loose* on a surface, i.e. not plugged into a breadboard, but that is not what it was intended for, and maybe you should employ an UNO in its place.

However, if you have to use your Nano without a breadboard, then in addition to the wire wrapping, wires with female DuPont connectors, or female header strips, you could just solder wires to the holes in the nano board, if you do not already have header pins already soldered in to them.
> 2 votes

# Answer
Here's what I use, repeatedly, successfully. It fits the Nano headers, and gives you screw terminals for proto work.
> 2 votes

---
Tags: arduino-nano, prototype, wires
---


title: Attach headers to servo wires?

text:
# Question
Title: Attach headers to servo wires?
I have these 3 wires coming from a servo motor. They're very thin and flimsy and despise staying in a breadboard.

Is it possible to add headers to these wires to make them easier to put in a breadboard? (Like the attached image) And if so, where would one procure such a thing?

# Answer
What I do in situations like that is get some of those breadboard hookup wires, like you have in your second photo, cut them in the middle (giving yourself two wires, each with a bare end, and a end with a plug on them).

Strip the bare end, and then solder it to the servo motor wires. Before commencing soldering, slip some heat-shrink tubing onto the wire. Once the wires are soldered together, move the heat-shrink tubing over the join and shrink it (with a hair-dryer, or heat gun).

You now have a plug for your breadboard which is designed to be mechanically strong, and the heat-shrink tubing over the join protects it from being flexed too much.

You could put some thicker heat-shrink over all three wires, to give additional stability.
> 3 votes

# Answer
I have bought a crimping tool. With the correct dice and crimps and crimp holders you get a professional finish. The crimps and crimp holders themselves are cheap (buy in multiples of 100) but the crimping tool and dice are expensive. It takes some practise before you make "high quality good contacting crimp" connections. You need to crimp in such a way that the strength comes from the connection between the wire insulation and the crimp and not loose electrical contact.

Also it is not so easy to find the "correct" crimps and crimp holders.
So this is only an option if you are willing to invest in your hobby (or you know someone who has ;-) )

If it is a DIY job I would go with nick solution.
> 0 votes

---
Tags: electronics, wires
---


title: Baud rate Arduino/Linux

text:
# Question
Title: Baud rate Arduino/Linux
I'm trying to communicate some numbers between a Linux program and my Ardunino Uno. To this end I wrote a C++ program which somehow contains:

```
#include <stdio.h>

int a,b;
a = 1;
b = 2000;

File* serial = fopen("/dev/ttyACM0","w");
fprintf(serial,"%d,%d\n",a,b);
fclose(serial);

```

Now out of standards I guess, the baud rate is 9600 bit/s. If I use `stty -F /dev/ttyACM0 115200` I can change the baude rate of that port to 115200 bit/s. However the communication does not work anymore. My arduino program waiting for `number,number` does not show any action to the same code as before. Oh, and in the Arduino program of course I changed the code to `serial.begin(115200);`.

How can I change the baude rate in such a setup? If it is a concern, I'm using Ubuntu and an Arduino Uno.

# Answer
Actually, I tried it again with exactly the same settings and it worked. It seems, as if Linux uses the settings of ssty, when referring to the "file" of a serial connection.

Thanks anyway!
> 0 votes

# Answer
Setting baud rates in a C program isn't a trivial task. You need to use the low-level `open()` instead of `fopen()` and act on the returned file descriptor with `ioctl()` or `tcsetattr() / tcgetattr()`. The former method allows the setting of non-standard baud rates while the latter only allows specific baud rates to be used.

I wrote a C++ class to deal with it all for me a while back. You are welcome to examine the methodology and/or steal whatever bits of it you like to use in your own program.
> 3 votes

---
Tags: serial, linux, baud-rate, rs232
---


title: Particle-like wifi configuration

text:
# Question
Title: Particle-like wifi configuration
Can anybody tell me how the Particle (Photon/Core) WiFi *setup* works?

I am looking to mimic this WiFi configuration format for my own device.

The basic steps are as follows:

1. Power device on; put in "listening mode" if not already active;
2. Connect smartphone to the wireless network that you want to connect your device to;
3. Open the Tinker/Spark/whatever-it's-called App on your smartphone; choose "Add New Device";
4. Enter wireless password;
5. Wait for device to be discovered by the App; device is now connected to WiFi.

How is the information (SSID, password) transferred from the smartphone to the device?

Thanks in advance.

# Answer
> 2 votes
The Particle Photon is a replacement for the Spark Core module. This module was exploiting the Texas Instrument CC3000 chip. It was this chip that handle the very simple and convenient Wi-Fi configuration of the Spark Core. Texas Instrument named this method : SimpleLink.

The Particle Photon is now using a different module than the Core : a Broadcom BCM43362 instead of the CC3000. It's seems to work in a similar manner even if I was not able to find any information on it.

I've found on the George Howkins Depletion Region blog multiple articles that explain how the CC3000 SimpleLink works.

All the posts : http://depletionregion.blogspot.fr/search?q=smart+config

---
Tags: wifi
---


# Question
Title: How do I learn C? (was Computer project)
Can you help me writing a code for this question guys?? You have an Arduino Uno with 8 LEDs connected to digital pins 2 to 9. Create an array of 8 elements. Fill it with random numbers between 2 and 9 (all inclusive) Write a program which determines the greatest number among them. Save this number in a variable named max. Print this number on serial monitor. Blink the LED connected to this number. Let the delay time be 0.5 second.

Note that the random function may result in duplicate numbers generated. For example, the generated array may be {3,4, 4, 7,6, 2,5,7}

The maximum number will be 7.Since it occurred twice in the array, then you should blink it twice ^\_^ It the maximum number occured 3 times in the array, then you should blink it 3 times, and so for any number of occurrences

I have written this so far but I'm sure it's all wrong

```
int pins[8]={2, 3, 4, 5, 6, 7, 8,9};

void setup()
{
   pinMode(pins[8], OUTPUT);
}

void loop()
{
    x=random(0, 8);
    digitalWrite(pins[x], HIGH);
    delay(1000)
    digitalWrite(pins[x], LOW);
    delay(1000)
}

```

# Answer
> 2 votes
First hint: pinMode() only applies to one pin at a time. You'll need to execute it 8 times to intialize 8 I/O pins' modes.

Second hint: As @ChrisStratton tried to suggest, generate the random number set first; then "figure out" (set some variables in memory that will tell you) what do with the terminal output and the digital I/Os; then do each of those things. It helps to partition a larger problem into smaller ones.

Update: Considering your updated title, *How do I learn C?*, and since the question reads like a homework assignment, aren't you already taking a class in C or C++? If so, how do you find it lacking, i.e., what additional resources or direction would be most helpful to you? There are a number of good books on the C language, and one of those would be a good place to start. If you don't already have a favorite one, you can't go wrong with *The C Programming Language*, by Brian Kernighan & Dennis Ritchie, the authors/designers of the C language and its early compilers. It is book on the C language, not on programming per-se, so if you are new to programming as well, a programming tutorial would be an excellent additional choice (sorry I don't have one to recommend).

Secondly, beat up on the example programs that come with the ArduinoIDE: click the "Open" button \[uparrow icon on the IDE toolbar; not the File | Open menu\] and you'll see a menu of your current sketches and, below the break, categories of example programs. Pick one of the examples, read it and try to understand what it does and why it is written the way it is. Then tweak the ###p out of it - both to understand how make it behave differently, and to **break** it. You'll learn a lot by a) interpreting error messages from the compiler, and b) finding and fixing your mistakes. If you're not breaking your programs at least twice as often as you're succeeding, you're not trying hard enough!

---
Tags: programming, code-optimization, array
---


# Question
Title: I need help purchasing components for my Arduino project
I am a newbie on this hardware stuff. I need help on purchasing the components

**Brief description of my project**

I need a device that would remotely detect weight or pressure when somebody push on it and send the info to the webserver or websockets. The device could be located up to 300 ft.

After doing some research on it I learned that I need, arduino uno as the device main platform, xbee for wireless communication with the web, xbee shield for the xbee and Force sensitive resistor sensor to detect small weight or pressure.

**Question**

*First am I correct above mentioned components would solve what I am trying to do? If not what am I missing? Anything I mis-stated?*

*I have learned that there are stuff like xbee explorer, Arduino stackable headers, break-away headers, and breadboard. Do I really need these?*

*In the future I want to be able do other experiments with the board like use ultrasonic sensor with it or infrared sensor to detect objects. Will I need to buy anything specific to make these sensors compatible with the board or they are all standard?*

Basically I want to buy everything I need in one shot. Thank you in advance. Any help will be appreciated.

# Answer
> 0 votes
I would rather go with ESP8266. You can program that from the Arduino IDE. You don't need anything else than a programming cable (an USB-UART adapter), and you can connect the force sensor to the analog input with one pullup resistor.

There is a similar idea with one button here: https://www.hackster.io/noelportugal/esp8266-ifttt-easy-button-888a87

You can build your own force sensor: http://www.todayifoundout.com/index.php/2010/01/how-to-make-a-ridiculously-cheap-analog-pressure-sensor/

If you don't really need to measure the force, there are much easier solutions to detect weight of a person. These give a simple contact once pressed, and can be used like a button (see the first link in my answer). http://learning.media.mit.edu/projects/gogo/documents/making%20sensors.html#Paper and Aluminum foil.

It is not really possible to buy everything as one batch :) I would say you need:

I suggest you to find an ESP8266 based tutorial, Adafruit has a lot of those, and then you'll have an understanding about the tools and components needed.

If you buy some Arduino, consider buying the ones using 32u4 chip, such as Arduino Leonardo or Arduino Micro. The 32u4 chip has more memory, and more performance than the original Arduino Uno, plus it can work as an USB mouse or an USB keyboard too.

For infra (do you mean a PIR which detects humans, or a reflective sensor?) you have quite a lot of possibilities. In case of using ESP8266 directly, check that the sensors work on 3.3V. Some stuff works on 5V, others on 3.3V. You can interface them easily, but this is just another extra thing to cover, so better go with a dedicated 3.3V sensor.

Ultrasonic sensors are coming also in a lot of varieties. Do you need something ridiculously cheap? A sensor with a short range? A sensor with a longer range? I think you have to set up your goal first.

The Leonardo and Uno and Micro boards work both with 5V and 3.3V sensors. Driving these sensors are quite standard, you need to power them with two wires, and have one wire which goes from 0V to 5V (or vice versa) when something is detected. Ultrasonic sensors vary: there are sensors with one analog output, giving a voltage between 0V and 5V propoprtional to the distance. However most of ultrasonic sensors are simple as the ultrasonic principles: they have one input what you drive, and will give one output of the recived echo signal. In this case you have to measure the time elapsed between the drive signal and the echo, which depends on the distance of the object from the sensor.

---
Tags: arduino-uno, arduino-mega, xbee
---


title: BLE SPI Module with ATtiny85

text:
# Question
Title: BLE SPI Module with ATtiny85
Adafruit carries a number of Bluetooth LE 4.0 modules in their store, notably the SPI (https://www.adafruit.com/products/2633) and UART (https://www.adafruit.com/product/2479) version. I have used the NRF24L01 module with ATtiny85 via SPI to transmit data in the past, and this uses 3 pins. I used the following setup to do so: https://www.hackster.io/arjun/nrf24l01-with-attiny85-3-pins-74a1f2.

My previous system consisted of ATtiny85s communicating with a receiver (Bluefruit Feather) via NRF24L01 radios. As the receiver got data, it sent it to an iPhone app that I wrote. Now, I would like to cut out this receiver and BLE straight to the iPhone, which supports multiple peripheral connections.

However, unlike the RF24 library, the Adafruit BLE SPI library needs the actual SPI library to compile correctly, which for some reason the RF24 library (this version: http://tmrh20.github.io/RF24/) doesn't. I don't quite get how the RF24 library can compile fine without the SPI library when targeting the ATtiny85 - Is there some way to get this to work similar to the RF24 library?

Alternatively, I think there is a way to do software UART on ATtiny85, which I know nothing about, so if there truly is no way to do SPI is UART possible?

I realize that this is a question best asked to Adafruit, which I have done, but I thought I'd post it here and see if anyone can help.

Thanks, Alex

# Answer
I find the ATTiny85 working well with software serial port. Serial UART (or in fact any of the protocols like I2C or SPI) are just bit banging - and you can do that pretty well in software. Of course, having a hardware support makes things easier and faster, but there is nothing badly wrong with a software uart either. Except that you have to continuously check if there is some data arrives.

I was using software serial on Adafruit Trinket (ATTiny85) in various projects to talk to a Bluetooth 2.1 module, and it worked pretty well.

Here http://arduining.com/category/trinket-projects/ they use the same approach to talk to an ESP8266.

You may wish to look for the SoftwareSerial lib for Trinket, or in certain cases you may want to go for the SendOnlySoftwareSerial lib (send only, but smaller code footprint).

Also a hardware based serial lib is available: https://blog.adafruit.com/2013/09/30/hardware-serial-library-for-the-trinket/
> 0 votes

---
Tags: bluetooth, attiny, spi, adafruit
---


title: Arduino minimal power usage

text:
# Question
Title: Arduino minimal power usage
I know there is a lot on this subject on the net but i cant seem to be able to join the dots together. I am trying to make sensor system than can run for as long as possible if not indefinitely using an Arduino, and also to do so very cheaply. I have a £1 Arduino Nano clone that is running with sensor and alarm fine, but currently its runs off USB power from PC.

I have followed this guide to minimize power usage code side: https://www.openhomeautomation.net/arduino-battery/

And I have read that the Vin pin needs at least 7 volts to work properly, so 2 volts would be wasted in heat making a 5V level.

I have a 3.7V lithium cell 4300mAh so I thought I would need a step up boost module.

But it looks like the Nano can run using 3V. But the 3.3V rail is apparently made for external sensors, assuming I want a mixture of cheap/simple and high efficiency. Can i just hook a 3.7 lipo into the 5V rail of the Nano and a 5V solar panel (with diode) up to same point? Will this kill my Nano? If not, is it worth stepping the 3.7V down to the minimum the Nano can run with?

Underclocking is not an issue, it essentially wakes up every hour reads 5 sensors and if all is well (99% of the time) goes back to sleep for an hour. Linear voltage regulators seem to burn the excess voltage as heat. And then what will happen when the battery dies off and is no longer 3.7 volts? And if my solar panel is around 5V in good light, if its partly shaded and only has 3.5 volts for example it would not charge my lipo to 100% capacity. Should I step up DC/DC boost the panel voltage to charge my cell.

Guidance please.

# Answer
> 4 votes
I have to agree with @Olin Lathrop about the fact that Arduinos are not really tuned for your goals.

I am doing microcontroller projects for like 20 years, and I found the nanowatt PIC microcontrollers offering the best price/performance/tricks ratio if you need to have something running on batteries for a seriously long time (and has not too much to calculate). There we're talking about nanoamperes in sleep, and there are a lot more tricks you can consider.

You have chosen Arduino for a valid set of good reasons. But which Arduino please? They come with different CPUs and hardware!

If you go with Uno:

* power your board directly by batteries, e.g. 3xAA batteries at the 5V pin to bypass power loss on the 5 V regulator (you can also give a try to feed power via the USB socket if you feel that more convenient)
* remove the 3.3 V regulator (assume you don't need 3.3 V)
* sleep a lot and sleep well, listen to @Nick Gammon and check his page about power saving

Then comes the minor tricks:

* do not let any pin float. Before going to sleep, put all inputs to output. I.e. if you have a button input, change port direction to output and set to 0. (assuming that you don't need the button in sleep)
* turn off not only all internal peripherals, but also external ones. For example, things like I2C temperature sensors may have remarkable 0.5 mA sleep current. The easiest thing is to power those from a port pin, and set the port to 0 before going to sleep.
* turn off all pullups (and all inputs to outputs), don't forget the I2C as well. Although the bus will be idle, there is a serious leakage current (serious means microamperes, and you wanna go to the nanoampere range, right?)

Then if you want to go really to the hard parts:

And the final steps:

* I would check the electrolytic capacitors on the power rails, e.g. C2. These also have a leakage.
* Although Arduino does not have suppressor diodes to protect anything from any voltage spikes, I have to emphasize that single high capacity unipolar and bipolar suppressor diodes may have a leakage current of 1 uA.

Note about underclocking: this is not necessarily a wise thing to do. It is true that on slower speed the CPU consumes less. However at slower speed the CPU has to stay awake much longer to perform the same tasks.

* I found that if you need to perform some complex calculations (not just reading some sensors) it may make sense to switch to a higher CPU speed, and do the calculation in less time and go back to sleep more efficient.
* On the other hand, if your CPU is awake just to wait for some sensor readings and just burning cycles while waiting, a slower CPU speed is more beneficial.

# Answer
> 7 votes
I have a project along those lines. I am reading temperature, humidity, and light level and logging it, with a timestamp, to an SD card.

Schematic (click for larger image):

Photo:

It was designed with low power in mind. It runs from 3 x AA batteries which I think I have only changed once since I made it (in August 2013).

Also see my page about power saving.

I don't see any problem with running it directly from 3.7V - you would need to slow the processor down to 8 MHz (which I did anyway in that project).

The code (available here) compiles under the Arduino IDE.

# Answer
> 6 votes
Arduinos are for rapidly getting something going without having to know much about the underlying electronics and microcontroller. As a result, some design tradeoffs were made for you, generally optimized for development simplicity.

You now have a different primary concern, which is low power consumption. If that is truly important, then you have to design the system with that goal up front. This means starting with the bare microcontroller, designing the electronics around it carefully to minimize power, and designing the firmware architecture to minimize high-power cycles and maximize sleep time.

You are asking where to strap the big engine on a Honda Civic to make a high performance racing car. You can make a Civic higher performance, but to get really high performance you have to start with that goal from the beginning.

---
Tags: power, arduino-nano
---


title: Using AVR Timer Within an ISR

text:
# Question
Title: Using AVR Timer Within an ISR
I'm trying to create an ISR which operates for 15 seconds when a particular button is pressed. I'm attempting to use the AVR functions on my Arduino Uno to start counting when it enters the ISR, then quit the loop when it reaches 15 seconds.

I'm having difficulty reasoning out where the counter is actually stored that I want to use for my while loop.

Here is my code so far:

```
#define button_pin 2
#define duration 15
#define osc_in 0

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

const float convert = 5.0/1023.0;

void setup() {

  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  attachInterrupt(digitalPinToInterrupt(button_pin), button_interrupt, CHANGE);

  sei();

  pinMode(button_pin, INPUT);
  Serial.begin(9600);
}

void loop() {
    //int channel1 = analogRead(osc_in);

//while (millis() < 10000)
  //Serial.println(millis());
  //Serial.println(channel1 * convert);
  //channel2 = channel1;
}

void button_interrupt(){
  //(# timer counts + 1) = (target time) / (timer resolution)
  //int timer_counts = duration/(pow(6.4, -5));
  //int dur = 234374;
  OCR1A = 234374;
  TCCR1B |= (1 << CS10);

  while (????????){
    int channel1 = analogRead(osc_in);
    Serial.println(channel1 * convert);
  }
}

```

# Answer
Don't do delays inside an ISR. Don't do serial prints inside an ISR. Read this.

You need to redesign. The ISR can set a flag, that you then test in `loop`. Do the delay in `loop`.
> 1 votes

---
Tags: arduino-uno, avr, isr
---


# Question
Title: What will happen if I supply greater than 1.1V to analogue inputs if analogReference set to INTERNAL?
I am reading a 50Hz AC voltage using the analogue inputs.

If I set the analogReference() to INTERNAL, meaning 1.1V on the Arduino Uno, what will happen if a voltage greater than 1.1V is supplied to the pin? Will the board be damaged? If not, what value will the ADC give?

# Answer
You will read 1023.

The limit of the voltage is not the reference voltage but the chip supply voltage - so 5v on a 5v board.
> 3 votes

---
Tags: analogread, adc
---


title: Problem with ATtiny85 and RF modules

text:
# Question
Title: Problem with ATtiny85 and RF modules
I am doing a project on a ATtiny85 which involves using 433MHz RF modules. Whenever I want to compile any sketch using the Manchester library I always get these errors : "Manchester library doesnt support your microcontroller". Could anyone help me solving this?

# Answer
> 1 votes
Somehow I got it working. I don't know the cause of the problem but in order to fix it I had to Arduino 1.0 IDE; use this ATtiny support and this Manchester library. Thank you all for your help.

# Answer
> 0 votes
If you are using arduino IDE, only limited functions are supported for the ATtiny85, and if that library requires some of the function from the IDE (Probably Serial), then it will not work. There are few solutions: 1, use an atmega Chip; 2, get another library; 3, write your own code.

---
Tags: attiny
---


# Question
Title: Can't compile my library because "String does not name a type"
I am writing a small library to move some code out of the arduino sketch and make it reusable. Problem is that it does not compile since "String does not name a type".

This is my code (reduced):

myESP.h:

```
#ifndef MYESP_H
#define MYESP_H

#include "Arduino.h"

#include <String>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>

class myESP {
    private:
        const char* _ssid;
        const char* _password;
        const char* _host;
    public:
        myESP();
        myESP(char * ssid, char * pwd, char * host);
        String macToStr(const uint8_t* mac);
        String doGet(String data, String sensor, int duration);
};
#endif

```

myESP.cpp:

```
#include <String>

#include "Arduino.h"
#include "myESP.h"

myESP::myESP() {}

myESP::myESP(char * ssid, char * pwd, char * host) {
    _host = host;
    _password = pwd;
    _ssid = ssid;
}

myESP::String macToStr(const uint8_t* mac) {
}

myESP::String doGet(String data, String sensor, int duration) {

}

```

When i try to compile it, I get the following:

> /Users/lbedogni/Documents/Arduino/libraries/myESP/myESP.cpp:14:1: error: 'String' in 'class myESP' does not name a type myESP::String macToStr(const uint8\_t\* mac) {
>
> /Users/lbedogni/Documents/Arduino/libraries/myESP/myESP.cpp:22:1: error: 'String' in 'class myESP' does not name a type myESP::String doGet(String data, String sensor, int duration) {

I have tried to change the order of the imports, change libraries, but still it does not compile.

Any idea?

# Answer
Your syntax is wrong in myESP.cpp. Change this:

```
myESP::String macToStr(const uint8_t* mac) {
}

myESP::String doGet(String data, String sensor, int duration) {

}

```

to this:

```
String myESP::macToStr(const uint8_t* mac) {
}

String myESP::doGet(String data, String sensor, int duration) {

}

```

The return type is `String` and the function implementation should be prefixed with the class name `myESP::`. Obviously, you also need to fill in the body of the implementation or you'll get more errors because you don't actually return anything.
> 2 votes

---
Tags: library, esp8266
---


# Question
Title: Arduino onboard LED pin number as a constant
To use the onboard LED on an Arduino one usually has to know the pin number (13 in most cases), but is there a constant in the Arduino IDE one can use as well?

So is it possible to use something like `int LED = ONBOARDLED;` instead of using `int LED = 13;`?

# Answer
> `#define LED_BUILTIN 13`

(source)
> 4 votes

# Answer
Try `LED_BUILTIN`:

```
pins_arduino.h:static const uint8_t LED_BUILTIN = 13;

```
> 4 votes

---
Tags: led, arduino-ide, arduino-due
---


title: Serial Monitor Suddenly Doesn't Work

text:
# Question
Title: Serial Monitor Suddenly Doesn't Work
I have had this problem a few times, it seems the Arduino IDE and the serial monitor is incredibly unstable, unless it's user error but judging from the fact that I hadn't even touched anything before it broke, I would say it's not me.

It was working the night before but this morning it just wouldn't print anything to the serial monitor from my code, however if I start one of the communication example codes like the ASCII example, it prints fine...I'm using the arduino uno, but I have a couple of dues too, so I tried the script on the due and it printed fine to the serial monitor.

Here is my code, could someone check my code and see if they can print to the serial monitor or not?

```
/*
   Pins:

   RTC:
   5V to VCC
   GND to GDN
   A4 to SDA
   A5 to SLC
*/

#include <Wire.h>
#include "RTClib.h"

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

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

//Words     //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
char* w[] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Thirty", "Forty", "Fifty", "Keeg Jo And Mat 2016", "", " ", "Good",
             //28       //29         //30       //31     //32    //33  //34       //35    //36       //37  //38
             "Morning", "Afternoon", "Evening", "It Is", "Past", "To", "Quarter", "Half", "O'Clock", "AM", "PM"
            };

//End Words

int timeType = 0;
int _hour = 0;

int dayInput = 0;
int hourInput = 0;
int minuteInput = 0;

int iDay = 0;
int iHour = 0;
int iMinute = 0;

void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(57600);
  pinMode(11, INPUT);//Minutes
  pinMode(12, INPUT);//Hours
  pinMode(13, INPUT);//Day

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    //rtc.adjust(DateTime(2016, 3, 11, 10, 51, 0));
  }

  //rtc.adjust(DateTime(2016, 3, 11, 1, 0, 50));
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}

void loop () {
  DateTime now = rtc.now();

  minuteInput = digitalRead(11);
  hourInput = digitalRead(12);
  dayInput = digitalRead(13);

  if (minuteInput == HIGH) {
    Serial.println("Minute");
  } else if (hourInput == HIGH) {
    Serial.println("Hour");
  } else if (dayInput == HIGH) {
    Serial.println("Day");
  }

  Line();

  if (now.minute() == 0) {
    timeType = 0;
  } else if (now.minute() > 0 && now.minute() <= 20) {
    timeType = 1;
  } else if (now.minute() > 20 && now.minute() < 50 && now.minute() != 30 && now.minute() != 45) {
    timeType = 0;
  } else if (now.minute() >= 50 && now.minute() < 60) {
    timeType = 2;
  } else if (now.minute() == 30) {
    timeType = 3;
  } else if (now.minute() == 45) {
    timeType = 4;
  }

  ps("Time Type: ");
  pi(timeType);

  Line();
  Line();

  //Greeting
  p(27);
  Space();
  if (now.hour() >= 0 && now.hour() < 12) {
    p(28);
  } else if (now.hour() >= 12 && now.hour() < 18) {
    p(29);
  } else if (now.hour() >= 18 && now.hour() < 24) {
    p(30);
  }

  Line();
  Line();

  //Time (It Is) Time Type 0
  if (timeType == 0) {
    Itis();
    hours(0);
    Space();
    _minutes();
    OClock();
  }

  //Time (Past) Time Type 1
  if (timeType == 1) {
    Itis();
    _minutes();
    Past();
    hours(0);
    OClock();
  }

  //Time (To) Time Type 2
  if (timeType == 2) {
    Itis();
    _minutes();
    To();
    hours(0);
    OClock();
  }

  //Time (Half Past) Time Type 3
  if (timeType == 3) {
    Itis();
    p(35);
    Past();
    hours(0);
  }

  //Time (Quarter To) Time Type 4
  if (timeType == 4) {
    Itis();
    p(34);
    To();
    hours(1);
  }

  //AM/PM
  AMPM();

  Line();
  Line();

  //Day
  //Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
  ps(daysOfTheWeek[now.dayOfTheWeek()]);

  Line();
  Line();

  pl(24);

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

  delay(1000);

}

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

void Line() {
  pl(25);
}

void Itis() {
  p(31);
  Space();
}

void Past() {
  Space();
  p(32);
  Space();
}

void To() {
  Space();
  p(33);
  Space();
}

void Space() {
  p(26);
}

void OClock() {
  DateTime now = rtc.now();
  if (now.minute() == 0 || now.minute() == 60) {
    Space();
    p(36);
  }
}

void AMPM() {
  Space();

  DateTime now = rtc.now();

  bool am = false;

  if (now.hour() > 12) {
    am = false;
  } else {
    am = true;
  }

  if (am) {
    p(37);
  } else {
    p(38);
  }
}

void p(int i) {
  Serial.print(w[i]);
}

void pl(int i) {
  Serial.println(w[i]);
}

void ps(char* i) {
  Serial.print(i);
}

void pi(int i) {
  Serial.print(i);
}

void _minutes() {
  DateTime now = rtc.now();
  int minutes = 0;

  if (timeType == 2) {
    minutes = 60 - now.minute();
  } else {
    minutes = now.minute();
  }

  int i = minutes;

  if (i <= 20 && i != 0) {
    p(i);
  } else if (i > 20 && i < 30) {
    p(20);
    Space();
    p(i - 20);
  } else if (i > 30 && i < 40) {
    p(21);
    Space();
    p(i - 30);
  } else if (i > 40 && i < 50 && i != 45) {
    p(22);
    Space();
    p(i - 40);
  } else if (i > 50 && i < 60) {
    p(23);
    Space();
    p(i - 50);
  } else if (i == 30) {
    p(35);
  } else if (i == 40) {
    p(22);
  } else if (i == 50) {
    p(23);
  }

}

void hours(int m) {
  DateTime now = rtc.now();

  if (now.hour() > 12) {
    _hour = now.hour() - 12;
  } else {
    _hour = now.hour();
  }

  _hour = _hour + m;

  p(_hour);
}

```

# Answer
```
  //rtc.adjust(DateTime(2016, 3, 11, 1, 0, 50));
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

```

Every time you reset the Arduino, the RTC clock will be set back to the date/time you compiled the sketch. Surely you don't want that?

---

The serial monitor is not at all unstable, as you agree when you try a different sketch. Therefore your sketch has a bug, which you need to find.

One possible issue is hardware. The default Wire library will hang if communications are lost when doing a read. Can you describe your clock hardware? Is it a chip you soldered yourself? A board? If so, which one? Do you have pull-up resistors on SDA/SCL?

There is an alternate I2C library that you could try.

---

Your method of printing is certainly unusual. You call, for example:

```
Line ();

```

When you could just as easily (and a lot more readably) call:

```
Serial.println ();

```

Similarly for `Space` and so on.

---

Still, despite the very hard-to-read code, I can't see any loops that might cause printing to fail. I suggest you comment out the calls to `rtc.now()` and test it. If it works, that confirms you have a clock issue, not a printing issue.

I note that you have multiple calls to:

```
DateTime now = rtc.now();

```

... sprinkled throughout your code. Surely you only need to read the time once, per loop?

Put the `now` variable outside loop, and call it once only, like this:

```
DateTime now;

void loop () {
  now = rtc.now();

```

Then remove the other calls to `rtc.now()`.

---

I found when I tested (without a RTC connected) that it did indeed hang. But that was the `rtc.now()` call failing. If you comment that out, it prints fine.

eg.

```
Minute

Time Type: 0

Good Morning

It Is Six Twenty Eight AM

Keeg Jo And Mat 2016
--------------------------------------------------
--------------------------------------------------
Minute

Time Type: 0

Good Morning

It Is Six Twenty Eight AM

Keeg Jo And Mat 2016
--------------------------------------------------
--------------------------------------------------

```

That shows it is definitely a clock issue, not a serial printing issue.
> 1 votes

---
Tags: arduino-uno, serial, c++
---


# Question
Title: Is this method to a String from a function going to cause memory corruption?
I'd like to define a function such that I return a string and a boolean indicating whether the result is valid. Like this:

```
bool getStringOrTimeout(String *s) {
  ...
  if (timed_out) {
    return false;
  } else {
    *s = String(<some value>);
    return true;
  }
}

```

Is this going to cause a memory problem because the string is allocated on the stack and deallocated when it leaves scope, or is this okay?

# Answer
You are better off passing the string by reference, like this:

```
bool getStringOrTimeout(String & s)
{
  if (timed_out)
    return false;
  s = "foo";
  return true;

}

```

That means the *caller's* string will be modified. And you no longer need to pass down a pointer to a string.
> 1 votes

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


title: Problem: "stray '#' in program"

text:
# Question
Title: Problem: "stray '#' in program"
I got a sketch from the internet (http://www.instructables.com/id/How-to-build-an-8x8x8-LED-cube-and-control-it-with/) for controlling the display of an 8x8x8 LED cube. The program won't compile and the error says "stray '#' in program". I looked it up on google but nothing appears to be relevant. Here's a part of the code. (The error occurs at the `baseColor = color(#222222);` line)

```
int rectX, rectY;      // Position of square button
int ROWX, ROWY;
int rectSizeX = 80;     // Width of rect
int rectSizeY = 20;     // Height of rect
int circleSize = 20;   // Diameter of circle
color rectColor, circleColorOff, circleColorOn, baseColor;
color rectHighlight, circleHighlight;
color circleCurrentColor;
color rectCurrentColor;
boolean rectOver = false;

// State of LEDs
boolean[][] circleOn;

// Position of LED buttons
int[][] circlePos;

// Mouse Over LED buttons?
boolean [][] circleOver;

int delayedby = 50;

void setup() {
 //number of rows and columns
 ROWX= 8;
 ROWY= 8;

 size((ROWX*40+10), (ROWY*44+30));
 noStroke();
 frameRate(10);
 smooth();
 rectX = ROWX*20-30;
 rectY = ROWY*44+5;

 // Colors
 rectColor = color(#FF0000);
 rectHighlight = color(#FFFF00);
 circleColorOff = color(#444444);
 circleColorOn = color(#ff0000);
 circleHighlight = color(#CCFF00);
 baseColor = color(#222222);
 circleCurrentColor = circleColorOff;
 rectCurrentColor = rectColor;

circleOn = new boolean[ROWX][ROWY];
for(int i=0; i<=(ROWY-1); i++) {
 for(int j=0; j<=(ROWX-1); j++) {
   circleOn[j][i] = false;
    }
}
circlePos = new int[2][(ROWX*ROWY+1)];

// X Posistions
for(int i=0; i<(ROWX*ROWY-(ROWX-1)); i=i+ROWX) {
int Xpos = 25;
  for(int ii=0; ii<ROWX; ii++) {
     circlePos[0][i+ii] = Xpos;
     Xpos += 40;
  }
}

// Y Positions
int Ypos = 40;
 for(int i=0; i<(ROWX*ROWY-(ROWX-1)); i+=ROWX) {
  for(int ii=0; ii<ROWX; ii++) {
     circlePos[1][i+ii] = Ypos;
  }
        Ypos += 40;
 }

circleOver = new boolean[ROWX][ROWY];
for(int i=0; i<=(ROWY-1); i++) {
 for(int j=0; j<=(ROWX-1); j++) {
   circleOver[j][i] = false;
 }
}
}

```

It turns out that the code was compiled in the earlier beta versions of the Arduino IDE, and now I don't know what I need to do for it to be compiled by my 1.6.5 version.

# Answer
> 3 votes
From the Instructable you linked:

> matrix8x8.pde is a program in Processing to build your own displays.

You downloaded the **Processing** code, not the **Arduino** code. See above that:

> cube8x8x8.pde is the *Arduino code*.

So basically you are compiling the wrong code. Go back and re-read that page.

---
Tags: sketch, ide
---


# Question
Title: Understanding the contents of a library in C
So this is a question not just about the #include but most all includes you find while programming in C.

So I understand a library is prewritten code and when you include that library are you able to used certain function that are included in that library.

What I have always wanted to know is: where can you find the "instruction set", in C, for these libraries?

How can I find out what commands are available for me to use with this library?

hope this makes sense.

thank you everyone.

# Answer
> 2 votes
> What I have always wanted to know is: where can you find the "instruction set", inc C, for these libraries?

The libraries are usually found in the `libraries` sub-folder under your sketchbook folder (wherever that is). There is also another `libraries` folder inside the IDE install folder for the "official libraries".

> How can I find out what commands are available for me to use with this library?

Usually the library documents them in one way or another. Try looking inside the `.h` file used by the library to see what functions are exposed.

---
Tags: programming, library, c, atmega328
---


# Question
Title: What are the components of a Xively HTTP PUT request to send to my SIM800 GPRS module?
I have an Elecrow GPRS shield which I want to use to post temperatures from 3 x DS18B20s to Xively. The example code is a mystery to me. You can find in full at this link: http://www.elecrow.com/wiki/index.php?title=GPRS/GSM\_Shield\_v1.0#A\_Simple\_Source\_Code\_Example

The relevant function is here:

```
///send2Pachube()///
///this function is to send the sensor data to the pachube, you can see the new value in the pachube after execute this function///
void Send2Pachube()
{
mySerial.println("AT+CGATT?");
delay(100);

ShowSerialData();

mySerial.println("AT+CSTT=\"CMNET\"");//start task and setting the APN,
delay(1000);

ShowSerialData();

mySerial.println("AT+CIICR");//bring up wireless connection
delay(300);

ShowSerialData();

mySerial.println("AT+CIFSR");//get local IP adress
delay(2000);

ShowSerialData();

mySerial.println("AT+CIPSPRT=0");
delay(3000);

ShowSerialData();

mySerial.println("AT+CIPSTART=\"tcp\",\"api.cosm.com\",\"8081\"");//start up the connection
delay(2000);

ShowSerialData();

mySerial.println("AT+CIPSEND");//begin send data to remote server
delay(4000);
ShowSerialData();
String humidity = "1031";//these 4 line code are imitate the real sensor data, because the demo did't add other sensor, so using 4 string variable to replace.
String moisture = "1242";//you can replace these four variable to the real sensor data in your project
String temperature = "30";//
String barometer = "60.56";//
mySerial.print("\"method\": \"put\",\"resource\": \"/feeds/43634/\",\"params\"");//here is the feed you apply from pachube
delay(500);
ShowSerialData();
mySerial.print(": ,\"headers\": \"X-PachubeApiKey\":");//in here, you should replace your pachubeapikey
delay(500);
ShowSerialData();
mySerial.print(" \"_cXwr5LE8qW4a296O-cDwOUvfddFer5pGmaRigPsiO0");//pachubeapikey
delay(500);
ShowSerialData();
mySerial.print("jEB9OjK-W6vej56j9ItaSlIac-hgbQjxExuveD95yc8BttXc");//pachubeapikey
delay(500);
ShowSerialData();
mySerial.print("Z7_seZqLVjeCOmNbEXUva45t6FL8AxOcuNSsQS\",\"body\":");
delay(500);
ShowSerialData();
mySerial.print(" \"version\": \"1.0.0\",\"datastreams\": ");
delay(500);
ShowSerialData();
mySerial.println("[\"id\": \"01\",\"current_value\": \"" + barometer + "\",");
delay(500);
ShowSerialData();
mySerial.println("\"id\": \"02\",\"current_value\": \"" + humidity + "\",");
delay(500);
ShowSerialData();
mySerial.println("\"id\": \"03\",\"current_value\": \"" + moisture + "\",");
delay(500);
ShowSerialData();
mySerial.println("\"id\": \"04\",\"current_value\": \"" + temperature + "\"],\"token\": \"lee\"");

delay(500);
ShowSerialData();

mySerial.println((char)26);//sending
delay(5000);//waitting for reply, important! the time is base on the condition of internet
mySerial.println();

ShowSerialData();

mySerial.println("AT+CIPCLOSE");//close the connection
delay(100);
ShowSerialData();

}
void ShowSerialData()
{
while(mySerial.available()!=0)
Serial.write(mySerial.read());
}

```

Note that although this is called "send2Pachube" it uses the Cosm API, which still works. The section following the line

```
mySerial.println("AT+CIPSEND");

```

is where the HTTP gets formulated. I've assembled the string in the example code and it looks odd. The API key goes on about four times longer than it should. I'm not sure what all those colons are doing in there, are they a String operator? Can anyone give me an example of an HTTP PUT request for Cosm or Xively that illustrates how this string should be assembled? Thanks

# Answer
I've got a working solution to this issue. Here's the values you can edit and the function:

```
String FEED = "YOUR_FEED";
String KEY = "YOUR_API_KEY";
String DATASTREAM1 = "YOUR_DATASTREAM1_NAME";
Int VALUE1 = YOUR_VALUE1;
String DATASTREAM2 = "YOUR_DATASTREAM2_NAME";
Int VALUE2 = YOUR_VALUE2;

void send2Cosm()
{
mySerial.println("AT+CGATT?");
delay(100);
ShowSerialData();
mySerial.println("AT+CSTT=\"CMNET\"");//start task and setting the APN,
delay(1000);
ShowSerialData();
mySerial.println("AT+CIICR");//bring up wireless connection
delay(300);
ShowSerialData();
mySerial.println("AT+CIFSR");//get local IP adress
delay(2000);
ShowSerialData();
mySerial.println("AT+CIPSPRT=0");
delay(3000);
ShowSerialData();
mySerial.println("AT+CIPSTART=\"tcp\",\"api.cosm.com\",\"8081\"");//start up the connection
delay(2000);
ShowSerialData();
mySerial.println("AT+CIPSEND");//begin send data to remote server
delay(4000);
ShowSerialData();

mySerial.print("{\"method\": \"put\",\"resource\": \"/feeds/" + FEED + "/\",\"params\"");
delay(500);
ShowSerialData();
mySerial.print(": {},\"headers\": {\"X-ApiKey\":");
delay(500);
ShowSerialData();
mySerial.print("\"" + KEY + "\"},\"body\":");
delay(500);
ShowSerialData();
mySerial.print(" {\"version\": \"1.0.0\",\"datastreams\":");
delay(500);
ShowSerialData();
mySerial.print("[{\"id\": \"" + DATASTREAM1 + "\",\"current_value\": \"");
mySerial.print(VALUE1);
delay(500);
ShowSerialData();
mySerial.print("\"},{\"id\": \"" + DATASTREAM2 + "\",\"current_value\": \"");
mySerial.print(VALUE2);
delay(500);
ShowSerialData();
mySerial.println("\"}]}}");
delay(500);
ShowSerialData();

mySerial.println((char)26); //sending = ctrl+z
delay(5000);//waitting for reply, important! the time is base on the condition of internet
mySerial.println();

ShowSerialData();

mySerial.println("AT+CIPCLOSE");//close the connection
delay(100);
ShowSerialData();

}

void ShowSerialData()
{
while(mySerial.available()!=0)
Serial.write(mySerial.read());
}

```

To answer part of my question: no, the colons aren't a String operator, they're part of the HTML. Here's an example of the formed URL that gets sent:

```
{"method": "put","resource": "/feeds/YOUR_FEED/","params": {},"headers": {"X-ApiKey":"YOUR_API"},"body": {"version": "1.0.0","datastreams":[{"id": "DATASTREAM1","current_value": "VALUE1"},{"id": "DATASTREAM2","current_value": "VALUE2"}]}}

```

This code updates my feed but after several hours the updates stop. I'm still troubleshooting this new problem so I'm not 100% sure that this code is good. I will post back if the problem's in here.
> 0 votes

---
Tags: gsm
---


title: Send commands to Arduino from the WEB

text:
# Question
Title: Send commands to Arduino from the WEB
I need to send Arduino some instructions from the web. Basically I would have a web app with a few buttons, and when I press them they send an instruction to Arduino to move for example a motor or turn a lamp. This has to function remotely, so not locally.

I'm using an Arduino Yùn.

How should I do this? Websocket? How? Thanks!

# Answer
> 1 votes
It becomes lots easier if you see the yun as a linux computer with a arduino connected over serial.
Then the question becomes: what is the best way to send commands over the internet to a (linux) computer.
Answer: there are so many ways because there is no best way.
What are the main key drivers: Your linux computer needs to be reachable from the internet. That means opening your local network(firewall). The firewall is there for a reason. Do you have the skills to open your firewall and still be safe? If so you can run a service (lots of options) and reach your yun from anywhere on the internet. Just as you do locally.

If not you will need to go to a polling system. You use a server which is on the internet and send you request to that server. Your yun polls that server to get the messages you send.

There is a third option: If you can open your firewall from the internet, and you are the only user of the service and you very rarely need the service you can temporarily open the firewall when you need it .

# Answer
> 0 votes
Another option, if you can be limited to controlling your device from a mobile app, is blynk.cc. They provide mobile apps for Android and iOS, that let you build a control panel via drag-and-drop, and embedded platform libraries for Arduino, standalone ESP8266, RPi, and others, that talk both ways between the app and your embedded device, as well as between devices.

The embedded devices and the mobile apps communicate as clients to their servers (or to your server, if you choose to host the open-source server code) so you don't have to open any ports on your router or firewall.

You won't have the full freedom (or requirement!) of designing custom web-pages; but OTOH, you can be up and running with their example code in a few minutes.

I have a couple of room-temperature monitors on my desk that can report the temperature (plus history) to me anywhere I can get a web connection. I put two buttons on my panel to turn on, or blink, 2 LEDs on the board. With my feet up on the hearth I control the LEDs. There are slider-controls that can talk to the PWM ports as well. All the capabilities you need are there, at least to get started.

# Answer
> 0 votes
The simplest way to do this would be to host a webpage with the buttons on the Yùn itself, like for example this here. There are loads of examples for stuff like this out there.

To access it "remotely" - I presume you mean from anywhere on the internet - you would have to forward a port from your home router to the Yùn, like this. This will make the Yùn accessible from the internet. You only have to know your outside address (Google: "Find my IP") and then you can access your arduino from all over the world.

---
Tags: arduino-yun, web-server, remote-control, web-service, web
---


# Question
Title: Arduino metronome - Change time signature on button press
```
/**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 12;
int buttonState = 0;
int bpm = 120;
/**************************************/
void setup()
{
  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {
    pinMode(thisPin, OUTPUT); //initialize thisPin as an output
    pinMode(6, INPUT);

  }
  pinMode(keyPin, INPUT);
}

/****************************************/
void loop()
{

  //iterate over the pins
  //turn the led on from lowest to the highest

  if (digitalRead(keyPin) == HIGH && ts == 2) {
    ts = 3;
    delay(2000);
  }

  else if (digitalRead(keyPin) == HIGH && ts == 3) {
    ts = 4;
    delay(2000);
  }

  else if (digitalRead(keyPin) == HIGH && ts == 4)
  {
    ts = 2;
    delay(2000);
  }

  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {

    bpm = pulseIn(6, HIGH);

    pinMode(13, OUTPUT);
    if (ts > 4)
    {
      if (count > 3)
        for (int a = 4; a <= ts; a++) {
          digitalWrite(a - 3, HIGH);
        }

    }
    else
      digitalWrite(thisPin, HIGH);

    if (count == 1)
      tone(13, 1500, 100);
    else
      tone(13, 1000, 100);

    delay(bpm - 52);
    pinMode(13, INPUT);
    digitalWrite(thisPin, LOW);

    count++;
    if (count > ts)
      count = 1;

  }

}

```

I am trying to make a metronome using Arduino Uno, with 4 LEDs, each LED is a beat. I want to change the time signature every time I press the pushbutton, so that there are different number of beats per measure, but when I do press the button, it runs the code for 2 and 3 beats per measure once, and then goes back to its default, 4 beats per measure.

Sometimes, it even changes without pressing the button, randomly. I am using a 220 ohm resister instead of 10, as 10 starts much more randomly than the 220.

# Answer
You must have resistors in series with the LEDs. See The care and feeding of LEDs. 330 ohms in series with each LED would be about right in your situation.

With no resistors you are drawing far too much current from the output pins. That would drop the voltage and the processor would reset. Thus it goes back to the default of 4 beats per measure.

It also damages both the processor and the LEDs.

You can tell if the processor resets by putting extra code into `setup`. For example, after setting the pins to outputs:

```
 for (int i = 0; i < 10; i++)
    {
    digitalWrite (3, HIGH);
    delay (200);
    digitalWrite (3, LOW);
    delay (200);
    }

```

If you see pin 3 flashing 10 times, you know the processor has reset.

---

I think your problem now is that you have a floating input for the switch. When I tried your sketch, with a couple of modifications, it worked fine.

My code:

```
/**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 12;
int buttonState = 0;
int bpm = 120;
/**************************************/
void setup()
{
  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {
    pinMode(thisPin, OUTPUT); //initialize thisPin as an output
    pinMode(6, INPUT);
  }
  pinMode(keyPin, INPUT_PULLUP);
}

/****************************************/
void loop()
{

  //iterate over the pins
  //turn the led on from lowest to the highest

  if (digitalRead(keyPin) == LOW && ts == 2) {
    ts = 3;
    delay(2000);
  }

  else if (digitalRead(keyPin) == LOW && ts == 3) {
    ts = 4;
    delay(2000);
  }

  else if (digitalRead(keyPin) == LOW && ts == 4)
  {
    ts = 2;
    delay(2000);
  }

  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {

    bpm = pulseIn(6, HIGH);
    //bpm = 1000;

    pinMode(speaker, OUTPUT);
    if (ts > 4)
    {
      if (count > 3)
        for (int a = 4; a <= ts; a++) {
          digitalWrite(a - 3, HIGH);
        }
    }
    else
      digitalWrite(thisPin, HIGH);

    if (count == 1)
      tone(speaker, 1500, 100);
    else
      tone(speaker, 1000, 100);

    unsigned long now = millis ();
    while (millis () - now < (bpm - 52))
      {
      // quit delay if switch pressed
      if (digitalRead(keyPin) == LOW)
        break;
      }

    pinMode(speaker, INPUT);
    digitalWrite(thisPin, LOW);

    count++;
    if (count > ts)
      count = 1;

  } // end of for each pin

} // end of loop

```

Note that the input from the switch is now INPUT\_PULLUP which means it is pulled HIGH by an internal resistor. Thus, the tests are now for `== LOW` rather than `== HIGH`.

Also, instead of a delay for the timing of the metronome, I changed it to testing `millis()` and seeing if time is up. Otherwise you have to hold the switch down for the entire time that a cycle repeats.
> 1 votes

---
Tags: arduino-uno, c++, button
---


title: Timer to control 1.5V clock

text:
# Question
Title: Timer to control 1.5V clock
I want to make either an alarm clock or countdown timer whose alarm is loud enough to notice, but soft enough to not wake me up when asleep. My idea is to use the sound of an analog clock that I have - powered by a single AA 1.5V battery. I like this sound. So, I'd like to create an alarm or a timer that can turn on the power to this analog clock for a few minutes at least. Ideally, it would be something I could use daily for a couple hours without replacing the timer/alarm battery too often.

I've looked at these programmable relay timers: http://www.amazon.com/dp/B00P0TZ5CY/ but the voltage seems kindof overkill.

I've also considered an arduino board, but I'd like to be able to set the time on the device without plugging it into a computer.

I'm a developer, so I could do arduino programming if needed, but I don't know much about circuitry & hardware. I've also never done an arduino project, so I'm starting from 101.

Any ideas where I could start? The timer I mentioned above would be perfect if it didn't require 12V power. My knowledge is limited, so maybe that's less of a big deal than I think.

# Answer
I suggest a simple setup (similar to my temperature and humidity sensor but less complex).

You can run from 3 x AA batteries, and have an RTC clock to keep track of the time. You can use a MOSFET to turn on your analog clock when required.

The processor can be asleep most of the time, using the watchdog timer to wake up and check the time from the RTC. Don't use an Arduino "board" unless you are running from a wall-wart because the voltage regulator, USB interface, and power LED, will consume too much power.
> 1 votes

---
Tags: timers, relay
---


# Question
Title: I am planning to do a periodic table with Arduino's help but I have a few questions
I'm doing that for my school project, but I have few questions before I purchase the components.

First of all, let me explain how it will work:

There will be 4x20 LCD, an Arduino and probably two potentiometers (due to the potentiometer's sensitivity). When the user turns the potentiometers, the program adds the first potentiometer's value to the other potentiometer's value, because of sensitivity issues. Then the program checks which element corresponds to the two potentiometers' values.

After that, the program shows that element's information in the LCD (like its name, symbol, neutron number, proton number, valence electrons, ...).

Questions:

* There are around 118 elements in the periodic table. I'm not an expert with programming, but this means there will be 118 `if ... else if ...` statements. I can shorten the inside of the `if` statement by function, but there will be still 118 `if` statements. I'm afraid it will be over the memory (sketch size limit) limit of the Arduino. How can I shorten the code?
* Should I buy a Mega or will a Uno be enough?
* Will there be any problems if I connect a 5V Arduino pin to both potentiometers and 4x20 backlight? If not, how can I fix this? I don't want to use any other power source except Arduino.

# Answer
Expanding an answer from my comment on your question:

First thing is to define a struct that holds all the data you want to store and display for one element:

```
struct Element {
    char symbol[3];
    char name[16];
    float mass;
    char electronic_state[9];
    // etc...
};

```

Do not store the atomic number, as it will be deduced from the index on the array you will build. Each string in this struct (symbol, name...) should be big enough to store the longest possible string, including the final NULL terminator. The compiler will help you here: if you do not allocate enough room, it will later say something like “*error: initializer-string for array of chars is too long*”.

It is obviously somewhat inefficient to allocate each string the maximum possible length. I suggest you do this for the sake of simplicity, and because I do not think you should be short on flash, even on an Uno. If you really end up being short on flash, then I suggest you seriously consider jwpat7's answer. It is somewhat complicated, but likely to be significantly more efficient than mine in terms of flash usage.

Second step is to write down the periodic table as a PROGMEM array:

```
const Element periodic_table[] PROGMEM = {
    // symbol  name    mass      electronic state
    {"H",  "Hydrogen", 1.008,    "1s1"     },
    {"He", "Helium",   4.002602, "1s2"     },
    {"Li", "Lithium",  6.94,     "[He] 2s1"},
    // etc...
};
const size_t table_length = sizeof periodic_table / sizeof *periodic_table;

```

Then your program will only have to browse through this table in order to get the needed information. The only tricky part here is that you will have to copy the data to RAM before using it, for example with something like:

```
Element elt;  // element in RAM
memcpy_P(&elt, &periodic_table[i], sizeof elt);

```

I do not have an LCD, so I wrote a test program that simply dumps the table through the serial port:

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

void loop()
{
    Serial.println(F("Z  Symbol  Name  Atomic mass  El. state"));
    Serial.println(F("---------------------------------------"));
    for (size_t i = 0; i < table_length; i++) {
        Element elt;  // element in RAM
        memcpy_P(&elt, &periodic_table[i], sizeof elt);
        Serial.print(i+1);  // Z = i+1
        Serial.print(F("    "));
        Serial.print(elt.symbol);
        Serial.print(F("     "));
        Serial.print(elt.name);
        Serial.print(F("  "));
        Serial.print(elt.mass);
        Serial.print(F("  "));
        Serial.println(elt.electronic_state);
    }
    Serial.println();
    delay(1000);
}

```

This program only takes 4480 bytes of flash. This means I could expand the table to 118 elements and over 200 bytes of data per element before running out of flash on an Uno.
> 1 votes

# Answer
You probably don't need a Mega for this, but think about it as a long term investment if you want to keep messing around with the Arduino/move on to bigger projects.

Unfortunately, typing all the code out will be quite tedious. But you can make separate arrays for strings of all the element names:

https://stackoverflow.com/questions/1088622/how-do-i-create-an-array-of-strings-in-c

And you can make corresponding arrays for all of the numerical data.

Then you take the signal, do some math to figure out how you can use the signal to obtain an integer from 1-118, write that into an integer (say i), and then write name\[i\], symbol\[i\], neutnum\[i\], and so on to the LED screen.

The hardest part will be doing math so that the transition between two elements in terms of turning the potentiometer feels natural.

Note that if your math somehow generates 200, then name\[200\] will most likely write random values from memory to your LED screen. I think. If your LED screen is displaying nonsense, then that is what you should look at/debug first.
> 1 votes

# Answer
Rather than manually putting all of the periodic-table data into a program in just the right form (which would be quite tedious), you could use a program on your software development computer to read periodic-table data files and create the corresponding C-program data structures.

The python program shown below gives an example of that approach. (It contains a data table in a list of tuples, ie doesn't read data; but data like that in the tuples *can* be read from a file, or with a bit of programming, from a spreadsheet of periodic-table data.)

The python program opens file `datatables.data.c` for output, then it writes C statements into that file, which subsequently can be added into a sketch, `datatables.ino`, as shown later.

# Python program, `densconmelt.py`:

```
#!/usr/bin/python
# From data as shown in slide 19 of 39 at
# http://www.slideshare.net/bravetiger1964/lecture-11-metals-and-its-alloys-their-crystalline-structure-and-properties

# Physical Properties of several Metals and Alloys.
#   Metal or Alloy
#     Density (kg/m3)
#       Thermal conductivity W/(m*K) (t=20 C)
#         Melting point (Tm) (C)
adtm = [
    ('Aluminum', '2712', '204', '659'),
    ('Aluminum alloys', '7700-8700', '120-180', '462-671'),
    ('Brass-casting', '8400-8700',  '',  '990-1025'),
    ('Red Brass',     '8746', '159', '1027'),
    ('Yellow Brass',  '8470', '115', '930'),
    ('Bronze - lead', '7700-8700', '',  '850-1000'),
    ('Copper', '8930', '385', '1083'),
    ('Gold', '19320',  '318', '1063'),
    ('Pure iron',     '6800-7800', '72', '1530'),
    ('Cast Iron',     '7850', '', 'Gray 1370, Malleable 1360, White 1370'),
    ('Wrought Iron',  '7750', '58', '1450'),
    ('Lead',  '11340', '35.3', '327'),
    ('Nickel', '8800', '89', '1453'),
    ('Silver', '10490', '406', '961'),
    ('Solder 50/50 Pb/Sn', '8885', '', ''),
    ('Non-alloyed and low-alloy steel', '7850', '53.6', '1480'),
    ('Stainless Steel', '7480-8000', '12.11-45.0', '1430-1500'),
    ('Tin',  '7280', '63', '232'),
    ('Zinc', '7135', '115', '419')
    ]

locs = []
# To track current offset into datatext, and longest single string part
used = longy = 0
with open('datatables.data.c', 'w') as fo:
    fo.write('#ifdef ADDTABLE  // Disallows separate compile\n')
    fo.write('const char datatext[] PROGMEM = \n  ')
    for i in adtm:
        #a, d, t, m = i
        #print '{:20} {:12} {:12} {:12}'.format(a, d, t, m)
        for x in i:
            locs.append(used)
            used += len(x)+1
            longy = max(longy, len(x)+1)
            fo.write('"{}\\0" '.format(x))
        fo.write('\n  ')
    fo.write(';\nconst int offsets[] = {')
    for o in locs:
        fo.write(' {},'.format(o))
    fo.write(' {}{};\n'.format(used, '}'))
    fo.write('enum {} LONGSTR={}, ITEMS={}{};\n'.format('{', longy, len(adtm), '}'))
    fo.write('char buffy[LONGSTR];\n')
    fo.write('#endif\n')

```

Note, the out-commented lines

```
        #a, d, t, m = i
        #print '{:20} {:12} {:12} {:12}'.format(a, d, t, m)

```

would be an appropriate place to modify the python program so it prints out how the lines will look when displayed on the 4x20 LCD. Rather than repeatedly downloading files to your Uno or Mega just to fix lines that are a little too long, or misaligned, etc., you could make the python program show the display appearance in the same loop where it generates data structures to be included in the Arduino sketch.

Note, if you aren't familiar with the `with` construct, see the *With Statement* section of pythonforbeginners.com's Reading and Writing Files in Python page.

# What the Python program generates:

Some lines from the file generated by `densconmelt.py` are shown below, interspersed with comments about what those lines do. Later, the whole of the file `datatables.data.c` is shown.

```
#ifdef ADDTABLE  // Disallows separate compile

```

That line is a preprocessor statement to keep `datatables.data.c` from being compiled alone. During compilations, the Arduino IDE will copy `datatables.ino` and `datatables.data.c` into a temporary work directory and will compile each of them. However, the body of `datatables.data.c` won't compile correctly alone (outside the sketch), so is guarded from causing compile errors by surrounding it with `#ifdef ... #endif` lines.

```
const char datatext[] PROGMEM =

```

That line tells the C compiler to store the value of `datatext[]` into program memory. It also says the value and content of `datatext` are constant, and `datatext` is an array of characters.

```
  "Aluminum\0" "2712\0" "204\0" "659\0"
  "Aluminum alloys\0" "7700-8700\0" "120-180\0" "462-671\0"
  "Brass-casting\0" "8400-8700\0" "\0" "990-1025\0"
...
  "Tin\0" "7280\0" "63\0" "232\0"
  "Zinc\0" "7135\0" "115\0" "419\0"
  ;

```

Those lines each give the name of a metal or alloy, its density, its thermal conductivity, and its melting point. Values are strings instead of numbers, so ranges and missing values can be handled. Note that by rules of C, strings with no operators between them concatenate together. For example, the line `"Tin\0" "7280\0" "63\0" "232\0"` is equivalent to the line `"Tin\07280\063\0232\0"`. Note, each `\0` is a null character at the end of a substring. If space were short, one could leave out all the `\0`s and compute string lengths as differences of adjacent entries in `offsets[]`.

```
const int offsets[] = { 0, 9, 14, ... 524, 528, 533, 538, 542, 546};

```

That line tells where each substring begins, within the big string `datatext`. This method of storing offsets and substrings takes 12 bytes per item, ie 4·2 bytes for 4 `int` values plus 4 bytes for null characters. There are half a dozen ways to reduce the overhead to 5 to 10 bytes per item, but the most effective simple change would be to put `offsets[]` in PROGMEM. In addition, one might change some fields from strings to integers or floats, which would not need null separators or offset values if placed at fixed offsets at the front of an item's record.

```
enum { LONGSTR=38, ITEMS=19};
char buffy[LONGSTR];
#endif

```

Those lines create two constants, LONGSTR and ITEMS, telling the length of the longest substring and the number of items; allocate a buffer, as long as the longest substring; and close the guarding `#ifdef ... #endif`.

# `datatables.data.c`, shown whole:

```
#ifdef ADDTABLE  // Disallows separate compile
const char datatext[] PROGMEM =
  "Aluminum\0" "2712\0" "204\0" "659\0"
  "Aluminum alloys\0" "7700-8700\0" "120-180\0" "462-671\0"
  "Brass-casting\0" "8400-8700\0" "\0" "990-1025\0"
  "Red Brass\0" "8746\0" "159\0" "1027\0"
  "Yellow Brass\0" "8470\0" "115\0" "930\0"
  "Bronze - lead\0" "7700-8700\0" "\0" "850-1000\0"
  "Copper\0" "8930\0" "385\0" "1083\0"
  "Gold\0" "19320\0" "318\0" "1063\0"
  "Pure iron\0" "6800-7800\0" "72\0" "1530\0"
  "Cast Iron\0" "7850\0" "\0" "Gray 1370, Malleable 1360, White 1370\0"
  "Wrought Iron\0" "7750\0" "58\0" "1450\0"
  "Lead\0" "11340\0" "35.3\0" "327\0"
  "Nickel\0" "8800\0" "89\0" "1453\0"
  "Silver\0" "10490\0" "406\0" "961\0"
  "Solder 50/50 Pb/Sn\0" "8885\0" "\0" "\0"
  "Non-alloyed and low-alloy steel\0" "7850\0" "53.6\0" "1480\0"
  "Stainless Steel\0" "7480-8000\0" "12.11-45.0\0" "1430-1500\0"
  "Tin\0" "7280\0" "63\0" "232\0"
  "Zinc\0" "7135\0" "115\0" "419\0"
  ;
const int offsets[] = { 0, 9, 14, 18, 22, 38, 48, 56, 64, 78, 88, 89, 98, 108, 113, 117, 122, 135, 140, 144, 148, 162, 172, 173, 182, 189, 194, 198, 203, 208, 214, 218, 223, 233, 243, 246, 251, 261, 266, 267, 305, 318, 323, 326, 331, 336, 342, 347, 351, 358, 363, 366, 371, 378, 384, 388, 392, 411, 416, 417, 418, 450, 455, 460, 465, 481, 491, 502, 512, 516, 521, 524, 528, 533, 538, 542, 546};
enum { LONGSTR=38, ITEMS=19};
char buffy[LONGSTR];
#endif

```

# Sketch to get item data from program memory and display it:

We've used `densconmelt.py` to generate `datatables.data.c` as above, and now will show a sketch that gets an item's data out of program memory and displays it, whenever the sketch receives an item number via Serial input.

```
// Sketch that accepts a number via serial input, and responds with
// two lines of data via serial output.  The reply-data consists of an
// Alloy name on the first line, and Density, Thermal conductivity,
// and Melting point on the next line.

// See http://arduiniana.org/libraries/streaming/ for Streaming library
#include <Streaming.h>
// This sets up datatext in PROGMEM; offsets[]; buffy; LONGSTR; ITEMS
#define ADDTABLE
#include "./datatables.data.c"

void setup() {
  Serial.begin(115200);         // init serial port
}

void loop() {
  Serial << "Please enter item number from 1 to " << _DEC(ITEMS) << ": ";
  int item = 0;
  while (1) {
    while (!Serial.available()) {}; // Wait for a character
    int c = Serial.read();
    if (c == '\n') break;
    item = 10*item + c - '0';
  }
  if (item < 1 || item > ITEMS) {
    Serial << item << endl << item << " is out of range -- try again.\n";
    return;
  }
  // Display specified item's title on first line
  strcpy_P(buffy, datatext + offsets[item*4-4]);
  Serial << item << endl << "Item #" << item << ", " << buffy << endl;
  // Show other data items on next line
  strcpy_P(buffy, datatext + offsets[item*4-3]);
  Serial << "Density " << buffy;
  strcpy_P(buffy, datatext + offsets[item*4-2]);
  Serial << "   Thermal cond. " << buffy;
  strcpy_P(buffy, datatext + offsets[item*4-1]);
  Serial << "   Melt@ " << buffy << " C" << endl << endl;
}

```

Note, for a description of `strcpy_P()` arguments, see nongnu.org's **avr/pgmspace.h : Program Space Utilities** page.

See arduino.cc's PROGMEM page for a cursory overview of PROGMEM.

See avrfreaks.net's GCC and the PROGMEM Attribute page for detailed coverage of PROGMEM, and see Nick Gammon's Putting constant data into program memory (PROGMEM) page as well.

# Example of program output, as in Serial Monitor box:

Following is an example of program output as shown in the Serial Monitor box after I typed several numbers into the input line and pressed enter after each. (Note, at the bottom of the Serial Monitor box, set Line Ending to `Newline` and data rate to 115200 bps.)

```
Please enter item number from 1 to 19: 18
Item #18, Tin
Density 7280   Thermal cond. 63   Melt@ 232 C

Please enter item number from 1 to 19: 19
Item #19, Zinc
Density 7135   Thermal cond. 115   Melt@ 419 C

Please enter item number from 1 to 19: 20
20 is out of range -- try again.
Please enter item number from 1 to 19: -2220
-2220 is out of range -- try again.
Please enter item number from 1 to 19: 2
Item #2, Aluminum alloys
Density 7700-8700   Thermal cond. 120-180   Melt@ 462-671 C

Please enter item number from 1 to 19: 0
0 is out of range -- try again.
Please enter item number from 1 to 19: 5
Item #5, Yellow Brass
Density 8470   Thermal cond. 115   Melt@ 930 C

Please enter item number from 1 to 19:

```

The sketch echoes the user-input item number twice, so it appears at the end of each input solicitation as well as in line labels like “Item #5, Yellow Brass”.
> 1 votes

# Answer
i think you might have to buy a mega(probably more expensive!)

i also fear someone putting countless nights into coding (preferably on pc for me, because 1: sketch is only available as an ancient version on raspberrypi. & 2: easier transfer of code.)
> 0 votes

---
Tags: arduino-mega, lcd, potentiometer, sketch-size
---