title: What is an ICSP pin?

text:
# Question
Title: What is an ICSP pin?
What is an ICSP pin? I have read that it is an AVR and a tiny programming header for the Arduino, but what is an AVR and what does an ICSP pin do?

# Answer
> 24 votes
ICSP stands for *In Circuit Serial Programming*, which represents one of the several methods available for programming Arduino boards. Ordinarily, an Arduino bootloader program is used to program an Arduino board, but if the bootloader is missing or damaged, ICSP can be used instead. ICSP can be used to restore a missing or damaged bootloader.

A typical Arduino ICSP header has six pins, arranged 2x3. The article Connecting the Programmer: In-Circuit Serial Programming (ICSP) at Sparkfun describes some of the functions of ICSP pins, which include MISO, MOSI, SCK, V+, Ground, and Reset.

Each ICSP pin usually is cross-connected to another Arduino pin with the same name or function. For example, MISO on an Uno or Nano's ICSP header is connected to MISO / digital pin 12; MOSI on the ISCP header is connected to MOSI / digital pin 11; and so forth. Note, MISO, MOSI, and SCK pins taken together make up most of an SPI interface.

Several Arduinos, including the Uno, have two ICSP headers. One of them is for use with the ATmega328 (or similar), and the other for use with the ATmega16U2 (or similar) chip that implements USB. When present, this allows reprogramming the USB chip.

---

AVR refers to the instruction set architecture used in a family of Atmel microcontrollers. Several Arduinos – Mega, Uno, Nano, Micro – use AVR chips. Others, like the Zero and Due, instead use ATSAM3 chips, with an ARM instruction set architecture.

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


# Question
Title: Two Arduinos get out of sync after a few seconds
I built a small PCB that has some LEDs (bare NeoPixel 5050) and an IR receiver on it. The microcontroller is an ATtiny85, and the PCB is powered by a LiPoly battery (3.7V). The circuit normally stays in ULP sleep mode until a pin change interrupt wakes the circuit. The pin change interrupt is tied to the IR receiver so when the receiver gets a signal from a remote (38kHz modulated IR burst) a lighting sequence is triggered. I have multiple of these PCBs running the exact same code (shown below). When the PCBs receive an IR signal they all start at the same time, but then after a few seconds they start to drift apart. The lighting needs to be synchronized. What is the reason for this drift and how can I eliminate it? Is it due to different battery voltages? That would be the only physical difference between any two PCBs. Thanks for your help.

```
#define IR_PIN      4
#define LIGHT_PIN   0
#define DELAY_TIME  200

#include <Adafruit_NeoPixel.h>
#define NUM_PIXELS  2
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_PIXELS, LIGHT_PIN, NEO_GRB + NEO_KHZ800);

#include "avr/interrupt.h"
#include "avr/sleep.h"

void setup() {
  pinMode(IR_PIN, INPUT);
  strip.begin();
  pixelsOff();
}

void loop() {
  sleep();

  for (int i = 0; i < 5; i++) {
    pixelsOnRed();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
    pixelsOnGreen();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
  }

  for (int i = 0; i < 5; i++) {
    pixelsOnBlue();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
    pixelsOnRed();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
  }

  for (int i = 0; i < 5; i++) {
    pixelsOnGreen();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
    pixelsOnRed();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
  }
}

void pixelsOff() {
  strip.setPixelColor(0, 0, 0, 0);
  strip.setPixelColor(1, 0, 0, 0);
  strip.show();
}

void pixelsOnRed() {
  strip.setPixelColor(0, 255, 0, 0);
  strip.setPixelColor(1, 255, 0, 0);
  strip.show();
}

void pixelsOnGreen() {
  strip.setPixelColor(0, 0, 255, 0);
  strip.setPixelColor(1, 0, 255, 0);
  strip.show();
}

void pixelsOnBlue() {
  strip.setPixelColor(0, 0, 0, 255);
  strip.setPixelColor(1, 0, 0, 255);
  strip.show();
}

ISR(PCINT0_vect)
{
    //This is not needed for the current sketch
}

void sleep() {
    GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
    PCMSK |= _BV(PCINT4);                   // Use PB3 as interrupt pin
    ADCSRA &= ~_BV(ADEN);                   // ADC off
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

    sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
    sei();                                  // Enable interrupts
    sleep_cpu();                            // sleep

    cli();                                  // Disable interrupts
    PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
    sleep_disable();                        // Clear SE bit
    ADCSRA |= _BV(ADEN);                    // ADC on

    sei();                                  // Enable interrupts
}

```

# Answer
> 1 votes
> What is the reason for this drift and how can I eliminate it?

two solutions:

1) try using crystal oscillators;

2) try driving on arduino with the other arduino's clock output.

# Answer
> 1 votes
*Assuming internal RC oscillator:*

In the datasheet:

> By default, the Internal RC Oscillator provides an approximate 8.0 MHz clock. **Though voltage and temperature dependent,** this clock can be very accurately calibrated by the user. See “Calibrated Internal RC Oscillator Accuracy” on page 164 and “Internal Oscillator Speed” on page 192 for more details. The device is shipped with the CKDIV8 Fuse programmed. See “System Clock Prescaler” on page 31 for more details

And page 192 shows a graph of frequency vs voltage.

On 164 it says:

> It is possible to manually calibrate the internal oscillator to be more accurate than default factory calibration. **Please note that the oscillator frequency depends on temperature and voltage. Voltage** and temperature characteristics can be found in Figure 22-40 on page 193 and Figure 22-41 on page 193.

So yes, conclusive evidence there that the voltage will affect the frequency.

# Answer
> 0 votes
Other answers have noted that the internal RC oscillator's frequency is voltage and temperature dependent. If you have good control over voltage and temperature, consider manually or automatically calibrating the clocks of your several ATtiny85's.

Absent that control, consider adding crystals or ceramic resonators to your circuits, or set up a synchronization protocol using IR. For example, if your IR transmitter is programmable, have it send a synchronization character as often as necessary to adequately synchronize the lights. If your IR transmitter is not programmable, add an IR LED and driver to one or more of your ATtiny85's, and send synchronization characters at regular intervals.

---
Tags: led, attiny, rgb-led, sleep
---


# Question
Title: Arduino Uno, HM-10 Bluetooth Module, Not Discoverable
In short, I've hooked up an HM-10 to digital pins 10 and 11 on my Uno (required because TX/RX (0/1) can't be used whilst a serial connection is present). The Bluetooth module is a Sunfounder HM-10 which comes with a data sheet. I'm successfully communicating with the HM-10 and I've written a modified version of serial comms tutorial code provided so it stores the reads up in a buffer before outputting them which works fine, I can set all properties on the HM-10 using this method.

The delays were necessary as it seems the clock cycle can't 'keep up' - bytes go missing when reading/writing, so if I attempt to write by just using `Serial.read()` in `loop()` alone then not all of it is read/written.

Here's the code.

```
#include <SoftwareSerial.h>

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

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Goodnight moon!");

  delay(500);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.print("Wake up wake up wake up wake up wake up! Wake up wake up wake up wake up wake up!");
}

void loop() // run over and over
{
  if (mySerial.available()) {
    String s = "";
    char c;
    while((c = mySerial.read()) != -1) {
      s += c;
      delay(10);
    }

    Serial.println("Received: " + s);
  }

  if (Serial.available()) {
    String s = "";
    char c;
    while((c = Serial.read()) != -1) {
      s += c;
      delay(10);
    }

    delay(10);

    Serial.println("Sent: " + s);

    mySerial.print(s);
  }
}

```

This allows me to show input and output as follows:

```
Sent: AT+ADDR?
Received: OK+ADDR:F4B85EB42D64
Sent: AT+ADVI?
Received: OK+Get:0
Sent: AT+ALLO?
Received: OK+Get:0
Sent: AT+BATT?
Received: OK+Get:077

```

So good so far. Here's what I can't figure out from the data sheet. How do I make the bluetooth module discoverable on, say, my Mac or from my iPhone? I've tested setting `AT+ROLE0` or `AT+ROLE1` followed by `AT+RESET` and also set `AT+NAME` so I know what to expect, yet I can't discover the module.

Also to note, the status LED is flashing as per the specification as an unconnected status (500ms high, 500ms low) which indicates `AT+PIO10` is setup. `AT+ADTY?` is set to 0 which allows it to be advertising, responds to scanning and connectable.

I'm likely missing something quite obvious. Any ideas?

# Answer
Ah, I jumped the gun. Just found out Mac/iPhone can't scan for BLE devices, so I downloaded a BLE scanning app and once I set AT+ROLE0 and AT+RESET it appeared.

So, the answer is you need a BLE scanning application.
> 2 votes

# Answer
Thanks for your answer! In another thread, I found a free iOS bluetooth scanning app called LightBlue Explorer (https://itunes.apple.com/au/app/lightblue-explorer-bluetooth/id557428110?mt=8) which also lets you read/write to the device. Super handy. Adding that here for the next person who encounters this thread and wants a rec for a scanning app.
> 2 votes

---
Tags: bluetooth
---


title: HC-05 emit data without pairing

text:
# Question
Title: HC-05 emit data without pairing
Is it possible to emit data from an arduino connected to a hc-05 Bluetooth module without pairing it to another device? i.e. imagine that I want to send a Bluetooth signal as if it was a information spot. Then whoever who gets the signal can read it.

# Answer
> 2 votes
No. The HC-05 has to be paired. It runs on Bluetooth 2.x which requires pairing. What you want is BLE (or Bluetooth 4.x) which has various "beacon" facilities.

---
Tags: arduino-nano, bluetooth, hc-05
---


# Question
Title: How to set Alarms on the DS3231 easily so the Nano doesn't have to go to sleep with delay statements?
I want my solar array sun tracker to shut down at night then move full east in the morning to catch the first rays.

I know the DS3231 can set alarms but it is not clear from its documentation how to do it with the normal library.

Delay statements are the way I have it periodically check for when to take readings, but I really want it to be able to respond to radio-remote control commands, which don't work during delays.

Q: Is there an easier way?

# Answer
> 2 votes
Here it is:

https://github.com/sleemanj/DS3231\_Simple

Example: https://github.com/sleemanj/DS3231\_Simple/blob/master/examples/z2\_Alarms/Alarm/Alarm.ino

This is what I was looking for.

My system needs to be able to respond to radio remote commands while asleep, and the long delay() statements were preventing that.

These alarms solve the problem.

---
Tags: rtc, ds3231-alarms
---


# Question
Title: Write your own program to control Arduino Uno
Is it possible to write a program to control the Arduino Uno, without using the Arduino IDE?

# Answer
You can program the Arduino hardware without using the Arduino IDE. Using *avr-gcc* and a handful of other tools, including *make* and *avrdude*, you can compile and download to the target Aduino hardware. You can even dispense with the Arduino bootloader, and program the hardware using the common ICSP interface. To do this, you need a hardware programmer, but you can make another Arduino into one very easily. Using this method frees up the space used by the bootloader for your own code. Naturally, you use the editor of your choice. For a bit of a taste, have a look at the Adafruit page on programming a trinket (technically not an Arduino, but the methods still apply).
> 2 votes

# Answer
I assume you mean the Arduino IDE?

Yes there are many options, for example plugins for Eclipse or Microsoft Visual Studio.

This link show others like:

* CodeBender
* Electron
* Stino
* GEdit
* Komodo

Personally use normally the default Arduino IDE, but I don't like the fact you can use just a few files before it does not fit In the top bar, so than I use the Visual Studio plugin VisualMicro.
> 1 votes

# Answer
Most of the time I wrote code for arduino on codeblocks.

The other times on sublime text.

So the answer is yes.
> 1 votes

---
Tags: programming, arduino-ide, ide
---


title: String to persistent memory (EEPROM?)

text:
# Question
Title: String to persistent memory (EEPROM?)
I am creating a server node that I want to be able to save the wifi SSID and the password into persistent memory so that when it starts ups it can connect to the network. I have looked for several hours and found just a few bits of information. One bit I found here http://playground.arduino.cc/Code/EEPROMWriteAnything

```
#include <EEPROM.h>
#include <Arduino.h>  // for type definitions

template <class T> int EEPROM_writeAnything(int ee, const T& value) {
    const byte* p = (const byte*)(const void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          EEPROM.write(ee++, *p++);
    return i;
}

template <class T> int EEPROM_readAnything(int ee, T& value) {
    byte* p = (byte*)(void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          *p++ = EEPROM.read(ee++);
    return i;
}

```

This code will not store String values to the EEPROM. So as I thought I would ask for advice from the Stack Exchange geniuses.

Thanks!

# Answer
> 2 votes
EEPROM library has two functions `put` and `get` , which can help you store character array of any size, not exceeding the size of internal EEPROM size of Arduino. Please see the examples provided in the link above.

Here is a sample code to get you going.

```
int address = 10;
char arrayToStore[20];                    // Must be greater than the length of string.
String testString = "hello there";

testString.toCharArray(arrayToStore, testString.length()+1);  // Convert string to array.

EEPROM.put(address, arrayToStore);                 // To store data
EEPROM.get(address, arrayToStore);                 // To read data

```

---
Tags: esp8266, eeprom, memory-usage, flash
---


# Question
Title: Can I make delayMicroseconds more accurate?
I'm trying to bit bang DMX data and that requires 4us pulses. Not having much luck with the results I'm checking to see how good the Arduino is at delaying... Seems to be pretty terrible at it.

Here's a quick little test I did:

```
unsigned long ptime;

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

void loop() {
  ptime = micros();
  delayMicroseconds(4);
  Serial.println(micros() - ptime);

  delay(1000); //just to keep the serial monitor from going nuts
}

```

And the results:

> 8 4 8 4 4 4 4 4 8 8 8 8 4 8 8 4 4 8 4 4 4 8 8 8 4 8 4

I was kinda shocked at just how bad it's accuracy is. It's double the time I wanted to delay, but it's not even consistent to where I could just divide by 2!

Is there anything I can do to get correct, consistent results?

# Answer
As explained in the previous answers, your actual *problem* is not the accuracy of `delayMicroseconds()`, but rather the resolution of `micros()`.

However, to answer your actual *question*, there is a more accurate alternative to `delayMicroseconds()`: the function `_delay_us()` from the AVR-libc is cycle-accurate and, for example

```
_delay_us(1.125);

```

does exactly what it says. The main caveat is that the argument has to be a compile-time constant. You have to `#include <util/delay.h>` in order to have access to this function.

Note also that you have to block the interrupts if you want any kind of accurate delay.

**Edit**: As an example, if I were to generate a 4 µs pulse on PD2 (pin 19 on the Mega), I would proceed as follows. First, notice that the following code

```
noInterrupts();
PORTD |= _BV(PD2);   // PD2 HIGH
PORTD &= ~_BV(PD2);  // PD2 LOW
interrupts();

```

makes a 0.125 µs long pulse (2 CPU cycles), because that's the time it takes to execute the instruction that sets the port `LOW`. Then, just add the missing time in a delay:

```
noInterrupts();
PORTD |= _BV(PD2);   // PD2 HIGH
_delay_us(3.875);
PORTD &= ~_BV(PD2);  // PD2 LOW
interrupts();

```

and you have a cycle-accurate pulse width. It is worth noting that this cannot be achieved with `digitalWrite()`, as a call to this function takes about 5 µs.
> 8 votes

# Answer
Your test results are misleading. `delayMicroseconds()` actually delays fairly precisely (for delays of more than 2 or 3 microseconds). You can examine its source code in file /usr/share/arduino/hardware/arduino/cores/arduino/wiring.c (on a Linux system; or on some similar path on other systems).

However, the resolution of `micros()` is four microseconds. (See, eg, the garretlab page about `micros()`.) Hence, you will never see a reading *between* 4 microseconds and 8 microseconds. The actual delay might be just a few cycles over 4 microseconds, but your code will report it as 8.

Try doing 10 or 20 `delayMicroseconds(4);` calls in a row (by duplicating the code, not by using a loop) and then report the result of `micros()`.
> 4 votes

# Answer
> I'm checking to see how good the Arduino is at delaying... Seems to be pretty terrible at it.

`micros()` has a well-documented resolution of 4 µs.

You could improve the resolution by changing the prescaler for Timer 0 (of course that throws out the figures, but you can compensate for that).

Alternatively use Timer 1 or Timer 2 with a prescaler of 1, which gives you a resolution of 62.5 ns.

---

> ```
>  Serial.begin(9600);
>
> ```

That's going to be slow anyway.

---

> 8 4 8 4 4 4 4 4 8 8 8 8 4 8 8 4 4 8 4 4 4 8 8 8 4 8 4

Your output is exactly consistent with the 4 µs resolution of `micros()` coupled with the fact that sometimes you would get two "ticks" and sometimes one, depending on exactly when you started the timing.

---

Your code is an interesting example of measurement error. `delayMicroseconds(4);` will delay for close to 4 µs. However your attempts to measure it are at fault.

Also, if an interrupt occurs then it will stretch the interval a bit. You need to turn interrupts off if you want an exact delay.
> 3 votes

# Answer
When measured with an oscilloscope, I found that:

`delayMicroseconds(0)` = `delayMicroseconds(1)` = 4 μs real delay.

So, if you want a 35 μs delay you need:

```
delayMicroseconds(31);

```
> 2 votes

# Answer
> Is there anything I can do to get correct, consistent results?

The Arduino implementation is quite generic thus may not be as effective in some applications. There are a few ways for short delays, each with its own shortfalls.

1. Use nop. Each is one instruction so 16th of a us.
2. Use tcnt0 directly. Each is 4us as the prescaler is set to 64. You can change the prescaker to achieve 16th us resolution.
3. Use ticks, you can implement a clone of systick and use it as basis of the delay. It offers finer resolution plus accuracy.

edit:

I used the following block to time the various approaches:

```
time0=TCNT0;
delay4us();             //65
//t0delayus(4*16);          //77
//_delay_us(4);             //65
//delayMicroseconds(4);     //45
time1=TCNT0 - time0;        //64 expected

```

before that, I had reset the timer0 prescaler to 1:1 so each TCNT0 tick is 1/16th of a microsecond.

1. delay4us() is built up from NOP(); it produced a delay of 65 ticks, or just over 4us;
2. t0delayus() is built up from timer0 delays. it produced a delay of 77 ticks; slightly worse than delay4us()
3. \_delay\_us() is a gcc-avr function. performance on par with delay4us();
4. delayMicroseconds() produced a delay of 45 ticks. the way arduino implemented its timing functions, it tends to under-count, unless in an environment with other interrupts.

hope it helps.
> 2 votes

---
Tags: arduino-mega, timers, time
---


# Question
Title: Confusion receiving I2C data from magnetic sensor
So, I've found the address of my device using a I2C device scanner. I then looked up the datasheet for a magnetic sensor I am trying to grab data from.

I'm now trying to communicate with the device by following the 'Example Measurement' section in the data sheet.

Here is my code so far...

```
#include <Wire.h>
#define address 0b110000 // find the actual address, it is at 0x30, which is 0b00110000

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

void loop() {
  int x, y, z;

  Wire.requestFrom(0b00110000, 1); // START condition?, starts with a 0 to indicate a WRITE request
  if(Wire.available() > 0) {
    Serial.println("1");
    Wire.read();
  }
  Serial.println(Wire.read());
  Wire.write(0b00000111);
  if(Wire.available() > 0) {
    Serial.println("2");
    Wire.read();
  }
  Wire.write(0b00000001);
  if(Wire.available() > 0) {
    Serial.println("3");
    Wire.read();
  }
  Wire.requestFrom(0b00110000, 1); // write request
  if(Wire.available() > 0) {
    Serial.println("4");
    Wire.read();
  }
  Wire.write(0b00000110);
  if(Wire.available() > 0) {
    Serial.println("5");
    Wire.read();
  }
  Wire.requestFrom(0b10110000, 1); // READ request
  if(Wire.available() > 0) {
    Serial.println("6");
    Wire.read();
  }
  // not sure what to do for the 7th cycle???
  // am I even doing the previous correct?
  Wire.endTransmission(address);
  delay(1000);
}

```

The numbers in each of the if statements represent the cycle within the 'Example Measurement' section of the datasheet, I'm never able to read data from the device and I am sure that I am doing something wrong.

I appreciate any help! This is my first time ever trying to understand I2C, and I've just been staring at this datasheet for too long without getting anywhere.

# Answer
This is how you send a byte to your slave:

```
  Wire.beginTransmission(SLAVE_ADDRESS);
  Wire.write(someByteValue);
  Wire.endTransmission();

```

You must sandwich the writes between a beginTransmission/endTransmission. Output buffer is 32 bytes long, so keep things short.

Wire.write() doesn't write; just put thing in an output buffer, waiting for your endTransmission().

If you need an answer (said, a byte), first you said how many bytes you want and then read them:

```
  byte pin;
  Wire.requestFrom(SLAVE_ADDRESS, 1);
  if (Wire.available() == 1) {
    pin = Wire.read();
  }

```

Your are Wire.read()ing, but you are not capturing the return value!

Disclaimer: after requestFrom, you have to be prepared to wait for the data (it may be not inmediatly available). Also, data may arrive in chunks.
> 1 votes

---
Tags: i2c
---


# Question
Title: Use MQ2 Sensor with Arduino Uno without breadboard?
I want to make a small and compact gas sensor using the Arduino Uno and MQ2 sensor. However all sites list a breadboard as a requirement.

Now, the MQ2 has A0, D0, GND, VCC, pins and the Uno also has A0, GND, 3.3V and 5V connectors.

So can I use Male to Female Jumper Wires to directly connect these? I am not using anything else like LEDs or speakers.

My code keeps the inbuilt LED ON when smoke level is LOW and blinks when the Level is HIGH. Also will I need any resistor for it?

# Answer
> 1 votes
This is point-to-point wiring, a technique loved by high-end audio amplifier fans:

# Answer
> 0 votes
Usually I don't think at the UNO as "small and compact"; I usually prefer to use a barebone atmega or an arduino pro mini / nano as alternatives (nano has inbuilt usb, pro mini doesn't). But anyway...

The SeeedStudio MQ2 has four pins, but no D0 pin; it has Vcc, GND and A0 and a NC pin (which means do not connect this pin).

So... Yes, The sensor is 5V powered and has an analog out interface, so you should connect the A0 pin to any analog input on the arduino (A0..A7); you are not forced to use A0.

Be careful that the sensor uses 800mW of power (160mA at 5V) in the pre-heating, so you are not advised to use it form a battery source

# Answer
> 0 votes
Yes, you can use male to female jumper wires to directly connect them. Breadboard is not a requirement. Also, you don't need any resistors.

# Answer
> 0 votes
You can connect it exactly like this. I'm using female-female jumper wires and have soldered pins onto the UNO clone to enable me to do this.

Pins on sensor from left to right A0 - D0 - GND - VCC

You can also find the wiring diagram on-line for a barebones sensor if you've not got the sensor module.

here MQ2- Sensor Information

You can either use the D0 output pin to turn on an LED in the presence of gas / smoke or you can use the A0 to report a gas / smoke level.

The code in my other reply is for the analogue reporting of the sensor value. The Digital output is either on or off and the potentiometer on the back of the sensor will adjust the point at which the D0 pin report a High output level, if it's not set right then the D0 pin won't actually output a voltage.

# Answer
> 0 votes
MQ2 flammable gas and smoke sensor detects the concentrations of combustible gas in the air and ouputs its reading as an analog voltage. The sensor can measure concentrations of flammable gas of 300 to 10,000 ppm.

The sensor can operate at temperatures from -20 to 50°C and consumes less than 150 mA at 5 V.

Connecting five volts across the heating (H) pins keeps the sensor hot enough to function correctly. Connecting five volts at either the A or B pins causes the sensor to emit an analog voltage on the other pins.

A resistive load between the output pins and ground sets the sensitivity of the detector. Please note that the picture in the datasheet for the top configuration is wrong. Both configurations have the same pinout consistent with the bottom configuration.

The resistive load should be calibrated for your particular application using the equations in the datasheet, but a good starting value for the resistor is 20 kΩ.

DataSheet PDF Here

```
    * Smoke/Gas Sensor Module project
     * tutorial url: http://osoyoo.com/?p=671
     */
    void setup()
    {
        Serial.begin(9600);
    }

    void loop()
    {
        int val;
        val=analogRead(0);
        Serial.println(val,DEC);
        delay(100);

}

```

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


# Question
Title: Micro servo is not working with Arduino UNO
I am new to Arduino and trying to do some basic tasks. I want a micro servo to rotate but it's not working, only slightly virbating when I launch a sketch. Below on the photos is how it is all assembled: I have a jumpwires connected to GND, 5V and #8 ports just as in the tutorial. I use micro servo SG-90 and Funduino UNO. Does anybody have any ideas what might the problem be? Here is also the sketch.

```
#include <Servo.h>

Servo servo;

void setup() {
  // put your setup code here, to run once:
servo.attach(8);
}

void loop() {
   // put your main code here, to run repeatedly:
servo.write(0);
delay(2000);
servo.write(90);
delay(2000);
}

```

# Answer
> 2 votes
You should not power a servo from a USB port.

However, your most glaring problem is that you have entirely mis-wired the connections, such that no wire is going to the correct place.

Servo connections are in the order of `Ground` \- `Power` \- `Signal`, usually with a dark color for ground and a redder one for power. Connector shells aren't standardized between brands, but within one there may be keying to prevent reverse installation.

It would appear that on your servo, `ground` is brown, `power` red, and `signal` orange.

Pull out all three wires and start over; also you'd do well to use a dark color for the ground, as you appear to have mixed up the power and ground as well as the signal.

---
Tags: arduino-uno, servo
---


# Question
Title: How can I define integer inputs to a function and get array as an output?
I am trying to write a function that takes integer values as an input and gives an array as an output. I have tried the following code but it doesn't show the output result in the serial monitor:

```
int *phi (int cur,int vol,int t) {
  int z[4];
  z[0]=1;
  z[1]=cur;
  z[2]=vol;
  z[3]=t;
//z=cur+vol+t;
  return z;
}

void setup() {
  // put your setup code here, to run once:

}

void loop() {

int result;
result=phi(1,2,5);
Serial.begin(9600);
Serial.print(result);

}

```

# Answer
> 3 votes
Defining the array in phi() returns a pointer to unassigned memory - it is no longer reserved once phi() returns. The next function call or interrupt (which you have no control over) will likely clobber the data.

A better choice would be to define `z` in the caller (loop() in this case) as an uninitialized array and pass it to phi() to fill and return. This is the more usual case, as it:

* avoids using globals,
* permits multiple calls to the function without clobbering previously returned data (you would pass different arrays in this case), and
* it avoids statically defined arrays that may not be needed after the caller returns, in a memory-starved environment (this may not be applicable if loop() is the caller).

In short, it gives the calling function the greatest flexibility, while committing the least amount of memory.

# Answer
> 2 votes
It appears you have created an array which only has scope with in the method "phi".

In practical terms, the array "z" is a local variable declared inside of the method and, as such, will likely end up in temporary RAM. When the method has completed, the RAM reserved for that method's local variables is released and is available for other purposes.

To fix this you could make "z" a static or you could give "z" global scope.

---
Tags: arduino-uno
---


title: AtTiny44 and AtTiny 85 communication

text:
# Question
Title: AtTiny44 and AtTiny 85 communication
I'm working on a project where I use two microcontrollers: an AtTiny44 (20MHz ext clock) and an AtTiny85 (8MHz internal).

What I'm trying to achieve is an I2C communication between the 85 and the 44, with the 44 acting as master and the 85 as slave, then transmit the data read from both of them to a PC with FDTI cable using softwareSerial.

I started with writing the AtTiny85 code:

```
   #include <TinyWireS.h>
   #define ADC3 A3

   void setup() {
      TinyWireS.begin(I2C_SLAVE_ADDRESS); // join i2c network
      TinyWireS.onRequest(requestEvent);
      pinMode(4,OUTPUT);
      digitalWrite(4,HIGH);
      pinMode(ADC3,INPUT_PULLUP);
   }

   void loop() {
      // This needs to be here
      TinyWireS_stop_check();
   }

   // Gets called when the ATtiny receives an i2c request
   void requestEvent() {
     int val=analogRead(ADC3);
     byte valLow = val & 0xff;
     byte valHigh = (val >> 8);
     TinyWireS.send(valHigh);
     TinyWireS.send(valLow);
   }

```

With this I am able to send the data read from an adc (A3 pin) to an Arduino as 2 bytes

The Arduino code:

```
  #include <Wire.h>

  int check=0;

  void setup() {
     Wire.begin();        // join i2c bus (address optional for master)
     Serial.begin(9600);  // start serial for output
  }

  void loop() {
      Wire.requestFrom(8, 2);    // request 2 bytes from slave device #8

      while (Wire.available()&&check<2) { // slave may send less than
                                          // requested
        int c = Wire.read(); // receive a byte as int
        check++;
        int d = Wire.read();
        check++;
        int number = d | c << 8; //convert two bytes as int
        Serial.println(number);
     }
     check=0;
     delay(500);
   }

```

Maybe the `check` variable is useless, but it's not a problem, because I'm getting the right reading on serial monitor.

I then moved to the AtTiny44; I have an onboard thermistor, and I need to print on softwareSerial the value read from this and the value read from the AtTiny85 board.

This is the code, using TinyWireM:

```
  #include <TinyWireM.h>
  #include <USI_TWI_Master.h>
  #include <SoftwareSerial.h>

  SoftwareSerial mySerial(0, 1); // RX, TX

  int adc = 2;
  int check=0;

  void setup() {
    pinMode(1, OUTPUT);
    pinMode(0, INPUT);
    pinMode(4,INPUT_PULLUP);
    pinMode(6,INPUT_PULLUP);
    pinMode(7, OUTPUT);
    pinMode(adc, INPUT);
    mySerial.begin(9600);
    TinyWireM.begin();        // join i2c bus (address optional for master)
    while (!mySerial) {
      ;
    }
    mySerial.println("Serial comm started");
    digitalWrite(7, HIGH);
    delay(1000);
    digitalWrite(7, LOW);
 }

 void loop() {
   mySerial.println((int)analogRead(adc));
   TinyWireM.requestFrom(8, 2);    // request 2 bytes from slave device #8
   while (TinyWireM.available()&&check<2) { // slave may send less than
                                            // requested
   digitalWrite(7, HIGH);
   int c = TinyWireM.receive(); // receive a byte as character
   check++;
   int d = TinyWireM.receive();
   check++;
   int number = d | c << 8;
   mySerial.println(number);
   }
 check=0;
 delay(500);
 }

```

The softwareSerial is working good (I get to write the ADC data from the 44) but I can't find where the problem on I2C is (on console monitor `mySerial.println(number)` sends out 0).

What I excluded so far: connections error, clock skew (the clocks are distant between them), pull-up on I2c bus (they are high in both devices)

# Answer
> the 85 as slave

writing a slave, especially an i2c slave, isn't for the faint of heart. typically you use a state machine to help handle that.

one great example is the one presented by nxp in old LPC210x datasheet. AVRs share the same i2c hardware so it is immensely portable to the avr.
> -1 votes

---
Tags: serial, i2c, softwareserial, attiny, attiny85
---


title: How do I read a sub-degree angle?

text:
# Question
Title: How do I read a sub-degree angle?
I need to measure (and record changes over a short time) the angle of a lever at a sub-degree resolution (The fulcrum can be the sensor) using an Arduino.

I've looked at rotary encoders, but even those with no detents have about 24 pulses per rotation. I need to measure only across a 90 degree arc. 24 pulses per rotation is 15 degrees per pulse. Which I guess results in a measurable resolution of 7.5 degrees!

I could add gears to increase the turns on the encoder, but that would increase the force required to move the lever.

Is there an option I'm not thinking of?

# Answer
> 2 votes
> I've looked at rotary encoders, but even those with no detents have about 24 pulses per rotation.

It sounds like you have been looking at encoders intended for user input controls.

**Optical Rotary Encoders** for machinery applications are readily available with up to several thousand pulses per revolution. Prices vary depending on if the wheel is glass or plastic, mounting options, brand, etc.

Do be aware that especially at the high resolutions, getting the encoder disk mounted perfectly concentric to the shaft being measured in important. You would either need to buy a a wheel which already has a bushing of the same diameter as your shaft, have access to a lathe, or have something custom made. (This is probably a case where a 3d printer is not accurate enough)

Also keep in mind that encoder wheels are often specified in cycles per revolution; with the typical two channel read head and quadrature decoding, there will be four times as many distinct state transitions. So a mere 300 CPR wheel would give you 1200 counts per revolution.

# Answer
> 2 votes
Try a spirit level (also called bubble level) app on your phone or tablet. It can get to sub-degree accuracy, but it is relative and not absolute accuracy. If that is good enough for you, then you could buy a modern accurate **accelerometer** and average the values.
It might even be possible to have more than one accelerometer for more accuracy.

Good quality (calibrated) digital spirit levels are very accurate. They use a accelerometer.

It will measure the angle with the earth gravity, and it is sensitive for vibrations.

There are more ways to measure the angle, but it depends on the mechanical construction of the lever. For example a **IR distance sensor** for short distances at the end of the lever. Maybe a magnet and **hall sensor**. There are probably more ways to measure the angle.

# Answer
> -1 votes
> Is there an option I'm not thinking of?

a ruler would be the simplest solution.

a capacitive pad could sense it as well.

a lever + a linear encoder.

...

---
Tags: rotary-encoder
---


# Question
Title: 65 hall effect sensors as switches to be used as a keyboard with a teensy
I'm trying to wire up a silly little keyboard using hall effect sensors and magnets in a glove. The idea being only I can use the keyboard since I'll have the glove.

The sensors are 3 pin, (vcc, gnd, and an output that sends 5v out when a magnetic field is present. I don't have anywhere near enough pins on the teensy for all the sensors. Could I just use several port expanders? Are there issues with using 4 or 5 at once? How many keys could be pressed at a time?

Is there a better option than all those expanders?

Also I know that this keyboard will be ugly and completely impractible to use regularly, but I thought it would fun to show off.

# Answer
\[**Completely rewritten answer**\]
That seems fun. But why 65 keys ? with 64 keys it is easier.

You have to test the sensitivity of the hall switches with the magnets to know how far apart the keys must be. Perhaps they only work with strong magnets or perhaps a number of them are activated when the glove is near.

With hall switches, there are 65 digital signals from the sensors.
The most common way to create more digital inputs is to use shift registers. For example with the 74HC165. Nick Gammon has the best tutorial of the 74HC165 with daisy-chain. There is also an example is with the CD4021 and the ShiftIn function, but the 74HC165 is mostly used.
The shift registers can be daisy-chained, they are made for that.

Your AH1807 has a open-drain output. That means you need 65 pullup resistors.
It is not possible to connect all the outputs and turn them on one by one, since it requires 150ms to wake up.

Another option is using multiplexers. It can be used for analog and for digital signals. For example with four 16-to-1 multiplexers you can create 64 inputs going to 4 pins. The best multiplexer tutorial is once again written by Nick Gammon.

With four analog multiplexers of 16-to-1 you would require only 4 pullup resistors after the multiplexer. I think it is better to use a resistor per hall sensor (65 pullup resistors).

When using reed switches (those tiny glass tubes, used in house alarms), they can be set in a matrix/grid with rows and columns and the Keypad library. For example 10\*7 requires 17 pins. The Keypad library allows that multiple keys are pressed at the same time.
> 2 votes

---
Tags: teensy, keyboard
---


title: Basic makefile for avr-gcc

text:
# Question
Title: Basic makefile for avr-gcc
I would like to make a makefile for compiling c programs for the arduino. I am somewhat familiar with make but have never used it with avr-gcc. What is the simplest way I could put the commands below in a makefile?

```
$ avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o led.o led.c
$ avr-gcc -mmcu=atmega328p led.o -o led
$ avr-objcopy -O ihex -R .eeprom led led.hex
$ avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:led.hex

```

# Answer
It's no different to working with Make and any other form of GCC. Just set your CC variable and CFLAGS variable accordingly and work as per normal.

For instance, I just knocked this one up:

```
CC=avr-gcc
OBJCOPY=avr-objcopy

CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

led.hex: led.elf
    ${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

led.elf: led.o
    ${CC} -o led.elf led.o

install: led.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:led.hex

```

That's saying that any automatic C compilation will be done with avr-gcc and the flags specified in CFLAGS. It will by default make the hex file using OBJCOPY, which is set to the avr one, which relies on the file led.elf - so to get that file it runs the led.elf target, which links the object file led.o with the default libraries using whatever was set in CC. To do that it needs led.o, and it makes that automatically using the program specified in CC and the flags in CFLAGS. You can then optionally to `make install` which will run `avrdude` to install the hex file into the chip.

You can make it even more generic so you can copy it in to other projects and make the minimum changes necessary:

```
BIN=led
OBJS=led.o test.o

CC=avr-gcc
OBJCOPY=avr-objcopy
CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

${BIN}.hex: ${BIN}.elf
    ${OBJCOPY} -O ihex -R .eeprom $< $@

${BIN}.elf: ${OBJS}
    ${CC} -o $@ $^

install: ${BIN}.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:$<

clean:
    rm -f ${BIN}.elf ${BIN}.hex ${OBJS}

```

That uses "automatic variables" and simple name replacement. `BIN` contains the "base" of your binary files, `OBJS` contains the list of object files. $@ is the name of the current target, $\< is the name of the first prerequisite, and $^ is the list of all the prerequisites. Just change `BIN` and `OBJS` to suit. As a bonus I have thrown in `make clean` to remove the compiled files and just leave you with the source.
> 7 votes

# Answer
The accepted answer is great as it has given me a valuable lesson in all kinds of debugging tools (avr-objdump -D has become a close friend). Namely, the line:

`${OBJCOPY} -O ihex -R .eeprom $< $@`

is missing the architecture flag and should read

${OBJCOPY} **-mmcu=atmega328p** -O ihex -R .eeprom $\< $@

Without the -mmcu architecture flag, avr-gcc guesses we are compiling for 8515 architecture (definitely not) and it produces the .elf file without initial instructions for initializing, i.e. without instructions to call the "main" function etc.

This results in confusing behavior as any simple program (e.g. blink) with only the "main" function works perfectly, but if you define another function before or after the "main", it runs that function and never calls "main" or it restarts all the time etc.

I am also not a particular fan of avoiding the verification of correct MCU type and uploaded program, so I'd advocate not to use -F and -V and use -v instead.

So, the improved answer could be:

```
PKG=led
BIN=${PKG}
OBJS=${PKG}.o
MCU=atmega328p

CC=avr-gcc
OBJCOPY=avr-objcopy
CFLAGS=-Os -DF_CPU=16000000UL -mmcu=${MCU} -Wall
PORT=/dev/ttyACM0

${BIN}.hex: ${BIN}.elf
        ${OBJCOPY} -O ihex $< $@

${BIN}.elf: ${OBJS}
        ${CC} -mmcu=${MCU} -o $@ $^

install: ${BIN}.hex
        avrdude -v -c arduino -p ${MCU} -P ${PORT} -b 115200 -U flash:w:$<

clean:
        rm -f ${BIN}.elf ${BIN}.hex ${OBJS}

```
> 5 votes

---
Tags: arduino-uno, atmega328, c, avr, compile
---


# Question
Title: Arduino does not make any sound when connected to laptop?
When I connect my Arduino through USB to my laptop, it does not make any sound like something is connected but green light is on. And port option in the Arduino IDE remains grayed out. I might have burned my Arduino, maybe? Please help.

# Answer
The Arduino will not make a sound, but probably you refer to the sound Windows makes when a USB device is connected?

Try (except for the tips already given by JRobert)

* different USB port
* reinstall Arduino IDE
* disable/enable or reinstall driver in Control panel/hardware/system/USB devices
> 2 votes

# Answer
There are a number of possible scenarios as to what is wrong:

1. The USB cable is a power only cable and has no data lines. However, this is unlikely because, whilst power-only USB cables are common with mobile phones (i.e. USB to Micro USB), a *full on* USB-A to USB-B cable, which is what the Uno uses, *normally* do not come in a power-only configuration.
2. The port is damaged on the laptop. This is unlikely, but it worth checking by connecting a keyboard or mouse to the same port, to see if data is transferred
3. You have no driver installed. This is the most likely scenario. Normally the Arduino will trigger a driver to be automatically installed. However, in the case of the cheap Chinese clones, which use the CH340G chip, then the CH340 driver will need to be installed, if you are using Windows. Check the Device Manager in Windows to see if you Uno is recognised when connected, or whether is is shown as an "Unknown Device". A quick google should provide you with the correct driver for the CH340G. Please note that, if you are using Linux, then no driver is required, see Majenko's answer to Safe place to download CH340G drivers from.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: LCD5110 - How to make Direct Draw via 2D-array of boolean?
How to draw 2D-array directly on LCD 5110 (PCD8544)?

I have tried libraries like AdaFruit and several others.

But I need draw there via pixel 2D-array, something like this:

```
bool picture[48][84] = {
 {0,1,0,0, ... to 84 elements},
 {1,0,1,0,0, ...},
 ... to 48 elements
};

```

I haven't used charset table or geometry figures drawing library functions. Simplest and smallest drawing by pixel - 0 - not draw, 1 - draw pixel.

The "picture bitmap" will generate on the mini-pc board via Python and send to Arduino, which will draw it as "video card".

What is the simplest way to draw pixel in any site of the display without using powerful libraries?

Something about this:

```
// Send boolean bitmap 48x84 to LCD 5110
// Rows
for (int i=0; i<48; i++) {
 // Columns
 for (int j=0; j<84; j++) {
  // PIN 5 is Din on the 5110 module
  digitalWrite(5, picture[i][j]);
 }
}

```

# Answer
For a start the Arduino Uno is incapable of storing that array in RAM. You're using twice as much memory for that array as the Arduino has in total. You will have to place it in PROGMEM and use the right functions to access it.

Secondly, you have to use a special library to control the display properly. That library will contain functions to draw on the screen. So your function to draw it would look something (though not exactly) like this:

```
const bool picture[] PROGMEM = {
    1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0,
    ... etc ... ... 4032 numbers in total ...
};

for (int i=0; i<48; i++) {
    for (int j=0; j<84; j++) {
        lcd.setPixel(j, i, pgm_read_byte_near(picture + (i * 84 + j));
    }
}

```

Refer to the manual for the library for the actual function to run and how to configure and set up the LCD screen.
> 1 votes

# Answer
```
// PIN 5 is Din on the 5110 module
digitalWrite(5, picture[i][j]);

```

with that kind of code, I would suggest that you spend a little bit more time on understanding the libraries you are trying to use, or the datasheet if you aren't using any libraries and ask more directed questions.

embedded engineering is one that ties software with hardware and it is not possible for you to understand software without understanding, very well, the hardware first.
> 0 votes

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


# Question
Title: How to read response from server using an Ethernet shield?
I want to control a relay by reading values from MySQL. I'm using an Arduino and an Ethernet shield. So far, I can get the response from server and get the value. I just need the value `10110110`, but I get a response in the serial monitor like this:

```
HTTP/1.1 200 OK
Date: Sun, 02 Jul 2017 07:53:29 GMT
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By: PHP/5.3.1
Content-Length: 13
Content-Type: text/html

<10110110>

```

How to remove this long response and get the value `10110110`?

# Answer
> 1 votes
There are, obviously, a great number of ways that this can be achieved. The simple brute force way would be to have a series of `if` statements, looking for a sequence of eight consecutive `0`s and/or `1`s, and loop through the string containing the response.

Or you could loop through the response, using `strcmp()`, similar to what is described here: how to do like a grep in a sketch?

However, a more intelligent method would be to use pattern matching and regular expressions.

From New regular expression library released, Nick has provided a Regexp library. It uses Lua for the expression syntax, see string.find, for more details.

I am still playing with this code, but your sketch would need something like this:

```
#include <Regexp.h>
void setup ()
{
  Serial.begin (115200);
  Serial.println ();

  unsigned int index = 0;
  char buf [100];

  MatchState ms;
  ms.Target ("HTTP/1.1 200 OK\
Date: Sun, 02 Jul 2017 07:53:29 GMT\
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
X-Powered-By: PHP/5.3.1\
Content-Length: 13\
Content-Type: text/html\
\
\
<10110110>");  // what to search

  while (true){
    char result = ms.Match ("^<([01][01][01][01][01][01][01][01])", 0);  // look for an eight bit binary digit
    if (result == REGEXP_MATCHED)
    {
      Serial.println ("-----");
      Serial.print ("Matched on: ");
      Serial.println (ms.GetMatch (buf));
      Serial.println ("Captures:");
      for (int j = 0; j < ms.level; j++)
         Serial.println (ms.GetCapture (buf, j));
      // move past matching string
      index = ms.MatchStart + ms.MatchLength;
    }  // end of match
    else
      break;  // no match or regexp error

  } // end of while

}  // end of setup

void loop () {}

```

This code assumes that you are looking for a line beginning with `<` and captures an eight digit binary thereafter - as determined by the expression within the inner `()`, in the line:

```
    char result = ms.Match ("^<([01][01][01][01][01][01][01][01])", 0);  // look for an eight bit binary digit

```

So, it *should* output:

```
-----
Matched on: <10110110
Captures: 10110110
-----

```

Obviously, instead of just outputting the captured binary digits to the serial monitor, you need to save them for your relay control.

---

For neatness, you could replace

```
 ms.Target ("HTTP/1.1 200 OK\
Date: Sun, 02 Jul 2017 07:53:29 GMT\
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
X-Powered-By: PHP/5.3.1\
Content-Length: 13\
Content-Type: text/html\
\
\
<10110110>");  // what to search

```

with

```
  char * str = "HTTP/1.1 200 OK\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
    X-Powered-By: PHP/5.3.1\
    Content-Length: 13\
    Content-Type: text/html\
    \
    \
    <10110110>";

  ms.Target (str);

```

Note the use of the backslashes at the ends of the lines. I've included them here, in order to get the test sketch to compile. You probably will not need them as you would be receiving the response from the server, and not providing an example string for testing.

---

Here is a *working* version, along with multiple test strings (`input_str`) and example match strings (`match_str`):

```
#include <Regexp.h>
void setup ()
{
  Serial.begin (9600);
//  Serial.begin (115200);
  Serial.println ();

  unsigned int index = 0;
  char buf [100];

// Simple test pair
//  char * input_str = "RGB:123";
//  char * match_str = "(%a)";

// Simulated MySQL responses
// Most basic
//  char * input_str = "<10110110>";
// Over two lines
//  char * input_str = "http\\n<10110110>";
// Full response
  char * input_str = "HTTP/1.1 200 OK\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
    X-Powered-By: PHP/5.3.1\
    Content-Length: 13\
    Content-Type: text/html\
    \
    \
    <10110110>";
// Full response with newlines
//  char * input_str = "HTTP/1.1 200 OK\\n\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\\n\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\\n\
    X-Powered-By: PHP/5.3.1\\n\
    Content-Length: 13\\n\
    Content-Type: text/html\\n\
    \\n\
    \\n\
    <10110110>";
// Shorter version of full MySQL response with newlines
//  char * input_str = "Content-Type: text/html\\n\
    \\n\
    \\n\
    <10110110>";
// Shorter version of full MySQL response with newlines with no preceeding spaces
//  char * input_str = "Content-Type: text/html\\n\
\\n\
\\n\
<10110110>";

// Match strings for MySQL response, containing an eight bit binary number
// Match at beginning of line
//  char * match_str = "^<([01][01][01][01][01][01][01][01])";
// Match at beginning of line with multiple newline characters
  char * match_str = "[\n]*<([01][01][01][01][01][01][01][01])";
// Match at beginning of line with zero or one newline characters
//  char * match_str = "[\n]?<([01][01][01][01][01][01][01][01])";
// Match at anywhere
//  char * match_str = "<([01][01][01][01][01][01][01][01])";

  MatchState ms;

  while (true){
    char result = ms.Match (match_str, 0);

    if (result == REGEXP_MATCHED)
    {
      Serial.println ("-----");
      Serial.print ("Matched on: ");
      Serial.println (ms.GetMatch (buf));
      Serial.println ("Captures:");
      for (int j = 0; j < ms.level; j++)
         Serial.println (ms.GetCapture (buf, j));
      // move past matching string
      index = ms.MatchStart + ms.MatchLength;
    }  // end of match
    else
      break;  // no match or regexp error

  } // end of while

}  // end of setup

void loop () {}

```

For the `match_str` line,

```
char * match_str = "[\n]*<([01][01][01][01][01][01][01][01])";

```

you may or may not need the caret (`^`) to match at the start of the line, and the `[\n]*` or `[\n]?`. See which combination works for you.

---
Tags: arduino-uno, ethernet
---


title: Is this (loose) capacitor critical?

text:
# Question
Title: Is this (loose) capacitor critical?
I have a Arduino Mega where a capacitor is 'broken off' ... I originally posted the question in the Electronics forum (Question).

One of the answers was that the capacitor is not critical. Can anyone confirm it (and consequences by not fixing it at all)? I didn't dare to turn on the Mega because of the broken capacitor.

It looks like this:

# Answer
If the voltage regulator is a MC33269 as in the official Arduino Mega 2560, then you need that capacitor, or else the MC33269 might start to oscillate. Search in the datasheet of the MC33269 for the paragraph with: "The MC33269 requires an external output capacitor for stability". The board will probably still work without it, but if it does indeed start to oscillate, then it can cause trouble. This is only when powered via the power barrel jack or the VIN pin.

That capacitor does not do a lot when the Arduino Mega is powered via the USB cable. You can use it without any problem when powered via the USB.

According to the photo, you can solder it back into place. They wrote enough about that in the EESE section. Give it a try, but don't create a shortcut with too much solder.
> 1 votes

---
Tags: arduino-mega
---


title: Upload original firmware to HID Arduino

text:
# Question
Title: Upload original firmware to HID Arduino
I recently was playing around with Arduino and using dfu-programmer reflashed ATMega16u2 to make the computer think it was a keyboard device.

Well, I wish to put the original Arduino firmware back on, but now dfu-programmer says the device is not present.

The Arduino is listed under `/dev/hidraw5` on Ubuntu. Typing `lsusb` gives the following output for Arduino keyboard:

```
Bus 004 Device 008: ID 03eb:2042 Atmel Corp. LUFA Keyboard Demo Application

```

I tried erasing with the command:

```
sudo dfu-programmer atmega16u2:4,8 erase

```

and got

```
dfu-programmer: no device present.

```

Is there a way to target `/dev/hidraw5` using dfu-programmer? Many thanks.

# Answer
Very sorry! But I actually figured this out on my own. I needed to reset by briefly bridging the reset pin with ground near the USB connector. Then typed

```
sudo dfu-programmer atmega16u2 erase

```

and I'm happy again.
> 1 votes

---
Tags: firmware
---


title: Reverting Arduino Environment on OS X

text:
# Question
Title: Reverting Arduino Environment on OS X
I am using Arduino environment 1.6.17 on OS X, 10.12.2. In this version, all of the core avr library stuff is located in ~/Library/Arduino15.

I was told by a vendor that in order for their program to compile properly, I needed to compile it under 1.6.4 of the Arduino environment. I dowloaded that version and compiled the program again. I could tell though, by the compiler messages, that while the IDE may be version 1.6.4, the program was still compiling with version 1.6.17 tools and avr libraries. Is there anyway to change that so I can get it to actually compile with all tools and libs from 1.6.4?

# Answer
I didn't try the total removal of the environment and then a re-installation as JRobert suggested, because I didn't really want to nuke my current environment. But his post did inspire me to try and run the 1.6.4 environment from another user account that had never run any Arduino stuff before. This seemed functionally equivalent to his or her suggestion. That seemed to work. Although, I still have a feeling that there is a more convenient solution out there.
> 1 votes

# Answer
Try removing the Arduino app with AppCleaner or a similar application remover. AppCleaner should find any related files not contained within the app. Let it remove them. Then reinstall Arduino 1.6.4.
> 0 votes

# Answer
When you run a recent-ish version of the Arduino IDE, it installs stuff in `~/Library/Arduino15`, unless it already exists. So when you installed 1.6.4, it saw the `~/Library/Arduino15` folder and proceeded without installing its own version of the tools.

The only way to have your 1.6.4 running alongside a newer version is to have copies of the `~/Library/Arduino15` folder, by renaming them when appropriate.
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: How can I alter my program to read PWM signals from Arduino Mega?
I am new to programming and Arduinos but I've decided to give a go for a project. I'm after a code that will read PWM signals from a RC receiver (Specifically aileron and throttle) and output this as 4 PWM signals to drive two H Bridges (Right motor forward/reverse and left motor forward/reverse).

This is my code that isn't working.

```
unsigned long timer[3];
byte last_channel[2];
int throttle;
int aileron;

void setup() {
pinMode(8, OUTPUT);//Right motor fowards
pinMode(9, OUTPUT);//Right motor reverse
pinMode(10, OUTPUT);//left motor fowards
pinMode(11, OUTPUT);//left motor reverse

PCICR |= (1 << PCIE0);  //This enables pin change intterupt enabler

PCMSK0 |= (1 << PCINT0); // This tells the mask register
which pins will cause an intterupt (Pin 2)

PCMSK0 |= (1 << PCINT1); // (Pin 3)

Serial.begin(9600); //Sets the data rate in bits per second
}

void loop() {

}
ISR(PCINT0_vect) {

timer[0] = micros(); // registers intterupt time

//Throttle_Channel----------------------------------------------------------

if(last_channel[0] == 0 && PINB & B00000001 ) { // This checks if pin has
changed from low to high

last_channel[0] = 1;

timer[1] = timer[0];
}

else if(last_channel[0] == 1 && !(PINB & B00000001)){

last_channel[0] = 0;

throttle = timer[0] - timer[1]; //calculates the change in time and sets to

input[0]
//--------------------------------------------------------------------------
}
//Aileron_Channel-----------------------------------------------------------

if(last_channel[1] == 0 && PINB & B00000010 ) { // This checks if pin has

changed from low to high

last_channel[1] = 1;

timer[2] = timer[0];
}

else if(last_channel[0] == 1 && !(PINB & B00000010)){ //This checks if pin  has

changed from high to low

last_channel[1] = 0;

aileron = timer[0] - timer[2]; //calculates the change in time and sets to i

input[0]
//--------------------------------------------------------------------------
}

//Calculations to put output in correct form--------------------------------
int throttle_pwm = (throttle - 1500) / 1000;

int aileron_pwm = (aileron - 1500) / 1000;

int v = (0.5 - abs(aileron_pwm)) * (throttle_pwm / 0.5) + throttle_pwm;

int w = (0.5 - abs(throttle_pwm)) * (aileron_pwm / 0.5) + aileron_pwm;

int lm = v + (w/2) * 255;

int rm = v - (w/2) * 255;
//--------------------------------------------------------------------------

if (lm > 0 && rm > 0){

analogWrite(8,rm);

analogWrite(9,0);

analogWrite(10,lm);

analogWrite(11,0);
}

else if (lm > 0 && rm <= 0){

analogWrite(8,0);

analogWrite(9,abs(rm));

analogWrite(10,lm);

analogWrite(11,0);
}

else if (lm <= 0 && rm > 0){

analogWrite(8,rm);

analogWrite(9,0);

analogWrite(10,0);

analogWrite(11,abs(lm));

}

else if (lm <= 0 && rm <= 0){

analogWrite(8,0);

analogWrite(9,abs(rm));

analogWrite(10,0);

analogWrite(11,abs(lm));

//--------------------------------------------------------------------------
}
}

```

It compiles fine but I've tried measure PWM at the four output and it doesn't work. If anyone could offer advice or guidance it would be greatly appreciated.

# Answer
> 1 votes
It looks like the code in the ISR is slow and it may compute incorrect results.

It is slow because of using floating point arithmetic in `throttle_pwm` and `aileron_pwm` calculations. It may be so slow that the trailing edge of a PWM pulse occurs while the leading edge still is being processed. This will delay trailing edge processing, and mis-measurement of pulse lengths.

The main thing to do to reduce the amount of code executed in the ISR is separate the input measuring phase from the output actuating phase. You could compute pulse widths and store them in volatile variables for a loop in main to pick up and use in `analogWrite()` statements there.

---

Note, in 16-bit `int` arithmetic, the value of expression `(t-1500)/1000` is 0 for 500 \< t \< 2500. Because `throttle` and `aileron` are supposed to be RC pulse lengths in the range 1000 to 2000 μs, your `throttle_pwm` and `aileron_pwm` will be zero. That means you can replace the following code,

```
int throttle_pwm = (throttle - 1500) / 1000;
int aileron_pwm = (aileron - 1500) / 1000;
int v = (0.5 - abs(aileron_pwm)) * (throttle_pwm / 0.5) + throttle_pwm;
int w = (0.5 - abs(throttle_pwm)) * (aileron_pwm / 0.5) + aileron_pwm;
int lm = v + (w/2) * 255;
int rm = v - (w/2) * 255;

```

with this code:

```
int throttle_pwm=0, aileron_pwm=0, v=0, w=0, lm=0, rm=0;

```

which should save you several milliseconds of computation! Also, having `lm` and `rm` as constant zeroes means that you don't need all those lengthy and laborious `if` and `else` blocks. You can replace those 24 lines of stuff with just the following:

```
analogWrite(8,0);
analogWrite(9,0);
analogWrite(10,0);
analogWrite(11,0);

```

---

Slightly more seriously, it looks like you intended for your arithmetic like `(throttle - 1500) / 1000`, etc. to determine whether to raise or lower the throttle, etc. Instead of doing that time-consuming division, just say:

```
int throttle_pwm = throttle > 1500 ? 1 : -1;  // or whatever values you meant to have
int aileron_pwm = aileron > 1500 ? 1 : -1;    // ditto

```

Instead of all those 24 lines of stuff, just say:

```
analogWrite(8,  (rm>0) * Level);
analogWrite(9,  (rm<=0)* Level);
analogWrite(10, (lm>0) * Level);
analogWrite(11, (lm<=0)* Level);

```

where `Level` is some level you want to set the control to. Note, an expression like `(rm>0)` has a value 1 when it is true and and 0 when it is false. So when `rm>0`, you have, in effect, `analogWrite(8,Level);` and `analogWrite(9,0);`.

If instead you end up with a calculation where `lm` and `rm` are actually usable PWM levels, ie numbers from 0 to 255, you could instead say:

```
analogWrite(8,   (rm>0) * rm);
analogWrite(9,  -(rm<=0)* rm);
analogWrite(10,  (lm>0) * lm);
analogWrite(11, -(lm<=0)* lm);

```

or could say:

```
analogWrite(8,  rm>0  ?  rm : 0);
analogWrite(9,  rm<=0 ? -rm : 0);
analogWrite(10, lm>0  ?  lm : 0);
analogWrite(11, lm<=0 ? -lm : 0);

```

---

Also see my answer to the question Read RC receiver channels using Interrupt instead of PulseIn and see my answer to the question Arduino read PWM duty cycle value with input (analog / digital).

# Answer
> 0 votes
See my page about interrupts. Data to be shared between an ISR and the main code should be declared `volatile` which yours isn't.

---

Also see:

https://www.arduino.cc/en/Reference/softwareSerial

> Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

It's not really clear from your post which pins you are using for the encoder, but you mention pins 2 and 3:

> ```
> PCMSK0 |= (1 << PCINT0); // (Pin 2)
> PCMSK0 |= (1 << PCINT1); // (Pin 3)
>
> ```

Pins 2 and 3 on the board are not PCINT0 and PCINT1. Also they are not in the list of supported pin-change interrupt pins.

You might be better off using **external** interrupts (see my page above). External interrupts are supported on pin 2 and 3. However your code needs to change a bit.

# Answer
> 0 votes
If you are trying to read a PWM signal, you should try using the pulseIn function, which reads the length of a pulse signal.

---
Tags: arduino-mega, pwm, h-bridge
---


# Question
Title: Additional boards manager option is missing from Arduino IDE
I am new to Arduino. For the project I am trying to do, I want to install the ESP8266 extension. But the additional boards manager URL option is missing from the Arduino IDE. What should I do to add the extension?

# Answer
> 9 votes
You need to download and install a recent version of the Arduino IDE from:

http://www.arduino.cc/en/Main/Software

When you install the Arduino IDE using `apt-get` you get a very outdated and non-standard version, which does not have the Boards Manager feature. The reason for this is that the license documentation of the Arduino IDE does not currently meet the required standards for the package manager:

https://github.com/arduino/Arduino/pull/2703

# Answer
> 1 votes
the URL is the following and the 1.8.2 IDE accepted it: http://arduino.esp8266.com/stable/package\_esp8266com\_index.json

Good luck, endre

P.s.: I found the answer/URL here: No Response to AT commands

# Answer
> 0 votes
You stated in the comments that you are using version 1.0.5. This is a very old version. Go through you computer and make sure you uninstalled any old versions, then try to reinstall the ide.

Make sure you download from arduino.cc, the official location to download the software.

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


title: Recording and playback sound

text:
# Question
Title: Recording and playback sound
I'm working in an art project, is some kind of loop between contact microphones and walkie talkies. I want to create some kind of noisy feedback.

I'm putting one walkie-talkie inside of a bottle, and in front of the speaker/microphone from the walkie I want to put another contact microphone attached to an Arduino, and record the sounds of the walkie talkie and played with some delay in some buzzer in front of another contact microphone attached to an amp with three speakers. To sum up, I have like 3 parts linked between them, the first one the walkie, the second one with an Arduino and the third one a simple mic whith an amp and three speakers.

Only the second part will be working with the Arduino and I want it to record sound and play it simultaneously with some delay. I worked with a friend with some servo motors and music shields and I've been doing some research. I found 3 very interesting projects one is this, that it's practically what I want to do Space Replaybut there's so little information about it, and the other two are Arduino Audio Input and Arduino Audio Output So, my questions are:

* If I use a music shield I don't need a DAC or/and an amp? or only an amp if my speakers are too loud?
* In the project Space Replay they only use this music shield so with only one music shield I can record and play music simultaneously? or I need two music shields?
* That Adafruit Wave Shield is only for Arduino uno, but it will be better or easier to work with DUE or Arduino Mega and another music shields or making my own circuits like in the instructables Arduino Audio Input and Output?

I don't care too much about the quality of the audio, as I said the purpose is make some noise. The only thing is I want to create some kind of echo, or some kind of cannon, between the first sound of the walkie and the others pick up sounds.

Any other comment or advice will be much appreciated and welcomed. Thanks

# Answer
Try using this shield from Adafruit. I believe it can record and play audio, and they have versions with and without amps.

I do not know about near-simultaneous playback, so read up a bit before buying.
> -1 votes

---
Tags: arduino-uno, arduino-mega, arduino-due, shields, sound
---


title: Making a 7-hour timer-based relay

text:
# Question
Title: Making a 7-hour timer-based relay
I want to make a very small 7-hour timer circuit that can turn on a relay after 7 hours. I am trying to make the first prototype with an Arduino Nano but I can't understand how to program it for such purpose. So please help me out.

Once I make a prototype in Arduino then I was thinking to make a small one using an ATtiny13. Can I use an ATtiny13 for such purpose?

# Answer
> 2 votes
The question is whether its a one shot triggering ON the relay after 7 hours and thereafter you always leave it ON or its some periodic process where every 7 hours, you want the relay to trigger ON and OFF alternatively. Presuming the latter, this can be done in 2 ways:

1) Configure a hardware timer interrupt to call a small function every second and increment a variable within that function. So after 1 hour your variables value must be 3600, therefore after 7 hours it will be 25,200. Once the variable is equal to 25200, you can ON the relay and reset the variable to 0. Factors such as the number of hardware timers and its resolution differs from one MCU to another.

2) Use a Real Time Clock like the DS1307 for this purpose and save you hardware timers for performing some other time critical operations.

Hope this helps!.

# Answer
> 1 votes
> cant understand how to program it for such purpose so please help me out

it is fairly easy to approach such questions:

1) you can program any?

2) can you program this mcu to blink an led?

3) can you program this mcu to do short time counting?

4) can you program this mcu to do long time counting?

what you help helps you the most depends on your answers to those questions.

---
Tags: timers, relay, attiny13
---


# Question
Title: I have to reload Sketch every time I start my Yun
I am new to Arduino and IoT. I got my hands on a Yun and loaded a simple sketch to subscribe to a topic. I am receiving messages (I have set up a PHP script and broker on a server, which takes care of the messages) and can turn ON and OFF LED, L13. But when I disconnect the Yun from my PC and connect it again (to power it up), it stops receiving messages. I have to load the sketch again to make it work. Here is my code:

```
#include <spi.h>
#include <pubsubclient.h>
#include <yunclient.h>

byte server[] = { 192, 168, 1, 196 };
int port = 1883;
char* pubTopic = "fromYun";
char* subTopic = "sensor/light";

void callback(char* topic, byte* payload, unsigned int length) {
  //convert byte to char
  payload[length] = '\0';
  String strPayload = String((char*)payload);
  // handle message arrived
  if(strPayload == "ON") {
    digitalWrite(13, HIGH);
  } else if(strPayload == "OFF") {
    digitalWrite(13, LOW);
  }
}

YunClient yun;
PubSubClient mqtt(server, port, callback, yun);

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  Bridge.begin();
  if (mqtt.connect("arduinoClient")) {
    mqtt.publish(pubTopic,"hello world!");
    mqtt.subscribe(subTopic);
  }
}

void loop() {
  mqtt.loop();
}

```

Am I missing something?

I referred to this post and PubSubClient -\> mqtt\_basic.ino for making this ketch.

I don't understand what `mqtt.connect("arduinoClient")` is. I mean, what is this string "arduinoClient"? In one sketch on GitHub I saw it as "yun"...

Any help will be appreciated. Thanks in advance!

EDIT: I am using Mosquitto MQTT.

# Answer
> 0 votes
Please explain which messages? Serial port messages or MQTT messages?

The mqtt.connect name "arduinoClient" is the ID name. It depends on the server what the parameters should be. For some servers it can be an empty string and the second parameter should be the account name, and a third parameter for the password/key.

When you upload a sketch, the OpenWrt part is already running. Perhaps there is a problem with `Bridge.begin`. Try to wait 90 seconds before calling `Bridge.begin`. If a 90-second delay makes it work, lower it to 5 seconds, and keep it at 5 seconds.

Perhaps you can use (blinking) LEDs to indicate that the code has finished the `Bridge.begin` or to indicate an error.

When you solve this problem, there will be other problems. Have you updated to the newest firmware for the OpenWrt part? The Arduino Yún might only work with a very simple and small sketch. Don't try to add too many things that use the Bridge. The OpenWrt/linux part is reliable, you can run linux scripts there. The ATmega32U4 part is just like an Arduino Leonardo and is also reliable. It is the combination and the Bridge that causes a never ending chain of problems.

What about the Raspberry Pi? That is reliable. Have you thought about the ESP8266 or ESP32 in Arduino compatible mode? Adafruit has an MQTT server for users, and the Adafruit Feather M0 WiFi seems a very nice board. Anything but the Yún.

My best advice for you is to grab a hammer and destroy the Yún and forget about it. It will make your life so much easier.

(*I just noticed that this is a very old question, sorry, but my answer is still valid*).

---
Tags: arduino-yun, uploading, sketch
---


# Question
Title: Need help with my code for my project using an Arduino Uno and Processing
I am using an Arduino Uno for my project. I use 4 digital inputs and they will be triggered by 4 different relays. I would like to save the data in a \*.csv file in the format below.

For example, if any of the inputs goes high, it will save a station ID, date, time it goes ON (starts). But once the input goes low, it will save the time it goes OFF (stops) on the same line.

Kindly help to advise if my code is correct because I get too many errors when I run it.

Example table in .csv file:

```
Date        Oven Station    Time Start     Time Stop
3/7/2017       Oven_P1_1       11:58       16:00
3/7/2017       Oven_P1_2        7:30       11:00
3/7/2017       Oven_P5_1       14:10       20:00
4/7/2017       Oven_P5_2        01:20      7:30
4/7/2017       Oven_P5_1        2:40       8:45
4/7/2017       Oven_P1_2        08:05      12:00
4/7/2017       Oven_P1_1        09:12      13:10

```

```
import processing.serial.*;

int Oven_P1_1 = 8;
int Oven_P1_2 = 9;
int Oven_P5_1 = 10;
int Oven_P5_2 = 11;
float Ovenvals [] = {0,0,0,0};

Serial myPort;
String val;
Table table;

String filename;

void setup() {
  String portName = Serial.list()[5];
  myPort = new Serial(this, portName, 9600);
  table = new Table();
  table.addColumn("id");
  table.addColumn("year");
  table.addColumn("month");
  table.addColumn("day");
  table.addColumn("hour");
  table.addColumn("minute");
  table.addColumn("second");
  table.addColumn("Oven_P1_1");
  table.addColumn("Oven_P1_2");
  table.addColumn("Oven_P5_1");
  table.addColumn("Oven_P5_2");
}

void serialEvent(Serial myPort) {
  val = myPort.readStringUntil('\n');
  if (val != null) {
    val = trim(val);
    println(val);
    float Ovenvals[] =float(split(val, ','));
    TableRow newRow = table.addRow();
    newRow.setInt("id", table.lastRowIndex());
    newRow.setInt("year", year());
    newRow.setInt("month", month());
    newRow.setInt("day", day());
    newRow.setInt("hour", hour());
    newRow.setInt("minute", minute());
    newRow.setInt("second", second());
    newRow.setInt("Oven_P1_1", ovenVals[0]);
    newRow.setInt("Oven_P1_2", ovenVals[1]);
    newRow.setInt("Oven_P5_1", ovenVals[2]);
    newRow.setInt("Oven_P5_2", ovenVals[3]);
    {
      saveTable(table, "data/OvenStatus.csv");
    }
  }
}

void draw() {
  OvenVal[0] = digitalRead(Oven_P1_1);
  OvenVal[1] = digitalRead(Oven_P1_2);
  OvenVal[3] = digitalRead(Oven_P5_1);
  OvenVal[4] = digitalRead(Oven_P5_2);
  Serial.print(OvenVal[0]);
  Serial.print(",");
  Serial.print(OvenVal[1]);
  Serial.print(",");
  Serial.print(OvenVal[2]);
  Serial.print(",");
  Serial.print(OvenVal[3]);
  Serial.print(",");
  delay(100);
}

```

# Answer
> 1 votes
You asked for (emphasis mine):

> \[...\] But once the input goes low, it will save the time OFF (stop) **on the same line**.

That's hard. What if several other inputs have gone HIGH in the meanwhile? You will have to somehow rewind part of the file, then add the stop time, the add again the subsequent lines...

You probably do not want to do all this on an Arduino. Especially considering that the Arduino has no concept of file, unless you add an SD card and the appropriate library. And it has no concept of time of day, unless you add an RTC and the appropriate library. I would suggest you go the easy path:

* have the Arduino tell your computer through the Serial port whenever one of those inputs changes state
* write a program in your computer (with processing or whatever) that reads this information and formats it the way you want.

For the first part, I suggest the following:

```
/*
 * Tell us when some pins change state.
 */

const int CHANNELS = 4;
const uint8_t pins[CHANNELS] = {8, 9, 10, 11};

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

void loop()
{
    static int states[CHANNELS];
    for (int i = 0; i < CHANNELS; i++) {
        int state = digitalRead(pins[i]);
        if (state != states[i]) {  // input changed state
            Serial.print("channel ");
            Serial.print(i);
            Serial.print(" going ");
            Serial.println(state ? "HIGH" : "LOW");
            states[i] = state;  // record new state
        }
    }
}

```

The output will be something like

```
channel 2 going HIGH
channel 1 going HIGH
channel 2 going LOW
...

```

For the second part, well, that's not an Arduino-related question anymore!

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


# Question
Title: Purpose of this resistor in Arduino Nano schematic
I was looking at the Arduino Nano's schematic and noticed a resistor that seems to be pointless (RP2C on this picture).  Also there is numbers 6 and 3 on it, does it mean that resistor is connected to pins 6 and 3 on FT232 or to the same pins on Atmega328?

# Answer
> 0 votes
It's an unused element of resistor array RP2. Both ends are grounded in order to reduce noise.

# Answer
> 3 votes
The resistor is one of 4 resistors that make up an SMD resistor array, RP2. It is seen on the board here:

The resistor array works like this:

The resistor on this array is spare, so both terminals are grounded.

---
Tags: arduino-nano, resistor
---


# Question
Title: Is there anything special about Arduinos?
I've been using the stm32f4 discovery up until now but I've heard Arduinos are easier to use. While looking for an Arduino Genuino Uno Rev3 board, I was told to get a knock off instead.

Is there any real difference between Arduino boards and other knock off micros with similar specs? I really just want to get a feel for what it's like using an 'easier' micro. It doesn't need to be extra special.

# Answer
Arduino have "standardized connectorss" for witch are many shields created. Also many manufacturers marks anything vaguely in power range of 5V as "for Arduino", because Arduino is so popular. And that is main reason, that Arduino is so popular. (This and that it came in the righ time with equipement targeting to be easy for beginners and a lot of educational materials).

I am using Arduino just because I start with it and bought a lot of AVR based boards and chips, but I may switch to STM for higher computing power, more pins and better equipement.

And the Arduino IDE is easy for beginners (and popular between them), because it have nearly nothing in it and it can compile+upload code to Arduino with just 2 buttons. (But it is like notepad with few more buttons - if you are a little more advanced you will run away for better editor/IDE/whatever at all cost. I use Vim + Make to create and run Arduino code and avoid the IDE totally, many do that too.)

So if you are used to STM32F4 kit, it would be big step back for you and it would satisfy you only if you need something cheap for work, where your STM is total overkill.
> 0 votes

# Answer
This is Google Trend of Arduino (blue) versus four other boards: STM32 (red), Teensy (green), MSP430 (yellow) and PIC32 (magenta).

That means lot of people using Arduino, making hardware and software, writing blogs, answering questions. That's the biggest plus of Arduino.
> 2 votes

# Answer
I think the reason why people say Arduino is **easier** to use is because it has a nice IDE and code upload is rarely troublesome.

Especially, the IDE allows the user to code hardware related functions with simplified functions.

For example, when coding an Arduino Sketch, the user doesn't really have to bother about registers.

The Arduino family are based on Atmel chips, so when it comes to raw hardware performance, Arduino performances are identical to Atmel chips.

If you are familiar with what you have(STM32F4) and don't want to make things easier but rather challenging, you don't have to move to Arduino.

Of course, if you want a simple & fast prototyping, nothing beats Arduino. (\<- my personal opinion)
> 1 votes

---
Tags: arduino-uno
---


title: Read and store data with the usb

text:
# Question
Title: Read and store data with the usb
Hi i am new to Arduino and I want to know if it is possible to read the data from a sensor that it is connected to the Arduino, I am using the Arduino mega 2560, which is already working, as I have a LED which change color depending on the detection of the object and then store it in a file as txt or another normal extension.

# Answer
> 0 votes
I don't have experience with Processing, but probably that is what you need. It communicates through USB and with the CreateWriter function, you can create a text file.

More about Processing can be found at Processing

Also another thread at Electronics stack exchange might help:

Related question

Alternatives (also mentioned in the above thread):

* Use serial port directly with a terminal application on the PC
* Use an SD card inside the Arduino to log

# Answer
> 0 votes
From what I understand from your question, you want to store the data displayed in the Serial monitor to a text file or something similar. As the Arduino itself cannot do this task, I used "GoBetwino" to save my data from an Arduino into a text file, from where you can export the data into Excel if you want charts and graphs. The process is fairly easy and described properly in their user manual. https://playground.arduino.cc/Interfacing/GoBetwino

---
Tags: usb, atmega2560, makefile
---


title: Arduino chip family

text:
# Question
Title: Arduino chip family
This is a very basic question but I cannot find answer for this. I have a couple of Arduino Nano boards lying with me. With keen scrutinizing I found that a few chips on board where numbered as Atmega 328P-AU 1645 and some were numbered Atmega 328P-AU 1644. Can somebody please tell me the difference the number after AU makes ? I know the difference between an AU and PU chip.

# Answer
> 2 votes
Looks to me like a date code: YYWW, where YY are the last two digits of the year and WW is the ISO week number.

---
Tags: arduino-nano
---


# Question
Title: My Arduino Ethernet shield is not working
Actually I'm using a W5100 Hanrun HR911105A 16/02 Ethernet shield with an Arduino Uno (original).

I tried this code from the examples:

```
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};
IPAddress ip(192, 168, 1, 177);
IPAddress myDns(192,168,1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
// telnet defaults to port 23
EthernetServer server(23);
boolean gotAMessage = false;
// whether or not you got a message from the client yet

void setup() {
  Serial.begin(9600);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // start the Ethernet connection:
  Serial.println("Trying to get an IP address using DHCP");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // initialize the Ethernet device not using DHCP:
    Ethernet.begin(mac, ip, myDns, gateway, subnet);
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  ip = Ethernet.localIP();
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(ip[thisByte], DEC);
    Serial.print(".");
  }
  Serial.println();
  // start listening for clients
  server.begin();
}

void loop() {
  // wait for a new client:
  EthernetClient client = server.available();
  // when the client sends the first byte, say hello:
  if (client) {
    if (!gotAMessage) {
      Serial.println("We have a new client");
      client.println("Hello, client!");
      gotAMessage = true;
    }
    // read the bytes incoming from the client:
    char thisChar = client.read();
    // echo the bytes back to the client:
    server.write(thisChar);
    // echo the bytes to the server as well:
    Serial.print(thisChar);
    Ethernet.maintain();
  }
}

```

That code prints the following on the serial monitor:

```
Trying to get an IP address using DHCP
Failed to configure Ethernet using DHCP
My IP address: 192.168.1.177.

```

So what is the problem? Why it is not connecting? I tried all the ethernet examples, but not one works. I don't know, maybe the problem is that I don't have a sticker of MAC address on the shield and I'm using the MAC address of the examples. Or maybe I'm writing the IP address wrong? Here is the data from the network connection details.

```
Connection-specific DNS Suffix: zte.com.cn
Description: Intel(R) Dual Band Wireless-AC 3165
Physical Address: 72-57-C5-BC-66-07
DHCP Enabled: Yes
IPv4 Address: 192.168.1.2
IPv4 Subnet Mask: 255.255.255.0
IPv4 Default Gateway: 192.168.1.1
IPv4 DHCP Server: 192.168.1.1
IPv4 DNS Server: 192.168.1.1
IPv4 WINS Server:
NetBIOS over Tcpip Enabled: Yes
Link-local IPv6 Address: fe80::b523:b9f2:b43c:6a8a%14
IPv6 Default Gateway:
IPv6 DNS Server:

```

My router is a ZTE model ZXHNH108N.

# Answer
If your Arduino can not get an IP address, it could be because there is a problem with your code, your shield or your network.

There doesn't seem to be a problem with your code from a quick glance, so let's look at the network.

1. The cable. Are you using the right sort of cable? You should be using a Cat5e straight through cable. Cat5e is the type of cable for Ethernet, if it is plugged into the router and you didn't make it yourself, it is probably either a CAT5e or CAT6 cable, so it will be OK. There are two types of cable and they are almost impossible to tell apart, the normal sort is a "straight through" cable, which means the Transmit and Receive pins at one end go to the Transmit and Receive pins at the other end. The other sort is a "crossed" cable where the Transmit goes to the Receive, this is for connecting a computer to a computer. Since you are plugging to a router you should have a straight cable, if in doubt test it with a working device, ie plug it into your PC.
2. DHCP - I see from your PC output DHCP is enabled on 192.168.1.1 and I guess this is your router. A DHCP server needs to know what addresses it can give out to devices, these addresses are called "the DHCP pool". If you have no more free addresses in the pool then you can't connect anymore devices. It sounds like you haven't restricted your pool, but it might be worth logging onto your router and seeing if you can see what addresses are in the pool or range.
3. MAC Filtering - For security some routers only allow certain MAC addresses to connect to the router and request a DHCP address. If you have it turned on then add your MAC address to the white list. If you don't have it turned on, don't worry.
4. Speed - I suspect that your shield has a maximum speed of 10MBs. Most modern networking equipment only supports 100/1000MBs so the shield just won't work with your router. Your router should have the numbers near the wired sockets to confirm or deny this.

If none of that works the you are going to need to see if you can read the data from the shield and see if you can work out what is going wrong. You will need a network snooper like WireShark and a *HUB*. An Ethernet switch will not work, it must be an Ethernet Hub, because switches don't rebroadcast the data on all ports. If your PC has two network cards you could set it up as a 'bridge' and you can snoop on the data as it passes across the bridge.

Sorry if some of these terms are confusing, but you should be able to Google them and get a better explanation than I can give you in the space here.

One final thought: are you running the Arduino from a battery? If so it might be worth using a mains supply, because the battery might not be able to support the Ethernet transmissions.
> 3 votes

---
Tags: arduino-uno, ethernet, networking, ethernet-shield
---


title: Arduino UNO UART coding in pure C

text:
# Question
Title: Arduino UNO UART coding in pure C
Below is a simple `USART` code for `ARDUINO` written in `Pure C`. But due to uknown(in reference to me) reasons, the code is not provicing desired output.

Can someone point out the error in the code. I cannot use the `Arduino` built in function `Serial.begin` as i need to use USART receive `interrupts`.

```
#include <avr/io.h>
#define F_CPU 16000000
#define BAUD 9600
#include<util/setbaud.h>

void UART_Init();

void setup()
{
    UART_Init();
}

void loop()
{
    UART_Transmit('c');
}

void UART_Init()
{
   UBRR0H = UBRRH_VALUE;
   UBRR0L = UBRRL_VALUE;
   UCSR0B = (1<<RXEN0) | (1<<TXEN0);
   UCSR0C = (3<<UCSZ00);
}

void UART_Transmit(unsigned char data)
{
    while(!(UCSR0A & (1<<UDRE0)));
    UDR0 = data;
}

```

# Answer
> 0 votes
Finally I figured it out.

The `UBRR0` calculation was the mistake

For making the code work for baud rate 9600, we need to set the equation as:

> UBRR0 = (F\_CPU / 4 / baud - 1) / 2;

and also double the USART speed by setting :

> UCSR0A = (1\<\< U2X0)

I hope someone will find this information helpful.

# Answer
> 0 votes
> UBRR0 = (F\_CPU / 4 / baud - 1) / 2;

you probably want to check the datasheet for that.

One way to code it is to change it based on the U2X bit, like this:

```
UxBRR=F_UART / ((UxCSRA & (1<<U2X0))?8:16) / baud - 1;          //generate baud rate register

```

So the user can change the U2X bit freely and the software will take care of it.

there is one set of uart polling and interrupt-driven routines that I use: https://github.com/dannyf00/My-MCU-Library/tree/master/UART/UARTISR/ATMega328p

they have the same user interface so can be exchanged freely.

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


title: what is aref(analog reference)

text:
# Question
Title: what is aref(analog reference)
what is the analog reference, I know that it can be used as a voltage reference, but not exactly what it is all about please someone help.

# Answer
> 3 votes
It is the reference voltage against which all other analog voltages (analog inputs) are measured against.

By default it is the same as the chip supply voltage (5V on most Arduino boards), so the analog inputs can measure between 0 and 5V.

If you connect the AREF pin to a lower voltage, say to the 3.3V pin (for convenience) and set the analog reference to EXTERNAL, you can then measure between 0 and 3.3V.

This is good if you are measuring a smaller voltage and want to get as much resolution in the analog reading. If you leave it at 5V and are measuring only up to, say, 3.3V, you're wasting all the analog reading values between 3.3V and 5V that could go to getting you more sensitivity.

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


# Question
Title: Arduino digital pin reading string numbers
Using for example 433MHz RF Receiver modules, they are connected to a digital input pin with interrupt. Looking at the most basic meaning of digital readings (e.g. 1/0, on/off, HIGH/LOW), how does the Arduino convert the signal readings to a number/string?

From my limited understanding, I'm assuming it has something to do with the (external) libraries, or it might just be that my understanding about digital readings are too limited.

# Answer
From the official Arduino site, See DigitalWrite :

If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.

The exact definitions can be found here for reading a signal: Constants

When reading or writing to a digital pin there are only two possible values a pin can take/be-set-to: HIGH and LOW.

**HIGH**

The meaning of HIGH (in reference to a pin) is somewhat different depending on whether a pin is set to an INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (Atmega) will report HIGH if:

-a voltage greater than 3.0V is present at the pin (5V boards); -a voltage greater than 2.0V is present at the pin (3.3V boards);

A pin may also be configured as an INPUT with pinMode(), and subsequently made HIGH with digitalWrite(). This will enable the internal 20K pullup resistors, which will pull up the input pin to a HIGH reading unless it is pulled LOW by external circuitry. This is how INPUT\_PULLUP works and is described below in more detail.

When a pin is configured to OUTPUT with pinMode(), and set to HIGH with digitalWrite(), the pin is at: -5 volts (5V boards); -3.3 volts (3.3V boards);

In this state it can source current, e.g. light an LED that is connected through a series resistor to ground.

**LOW**

The meaning of LOW also has a different meaning depending on whether a pin is set to INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (Atmega) will report LOW if:

-a voltage less than 1.5V is present at the pin (5V boards);

-a voltage less than 1.0V (Approx) is present at the pin (3.3V boards);

When a pin is configured to OUTPUT with pinMode(), and set to LOW with digitalWrite(), the pin is at 0 volts (both 5V and 3.3V boards). In this state it can sink current, e.g. light an LED that is connected through a series resistor to +5 volts (or +3.3 volts).

Probably, HIGH is 1, LOW is 0, and ON is 1, OFF is 0. Than 1 is mapped to 5V or 3.3V depending on the Arduino and 0 is mapped to 0V. These mappings and the definitions of HIGH/LOW/ON/OFF are in the Arduino libraries.
> 1 votes

# Answer
A digital pin can only tell you if a signal is HIGH or LOW at any instant in time. That itself isn't enough to transfer data (as in a stream of 1 and 0) since it's just the state at that moment.

To transfer data you need to introduce the extra parameter of *time*. That is, the amount of time a pin is HIGH or LOW and when exactly it changes.

UART data works this way. Both ends of the connection agree on a certain time for each "bit" of data (*symbol*) and read or set the pin at the agreed rate. That is the *baud rate* of the connection. Without that pre-arranged agreement on the time there is no way one end can know what the other is saying.

Other methods involve looking not at the current state of the pin but instead looking at how and when it changes from HIGH to LOW or LOW to HIGH. One example of this is *Manchester Coding* which encodes the different bits 0 and 1 as different sequences of transitions between HIGH and LOW or LOW and HIGH.

A third method, which is what SPI and I2C use, is to employ another pin to indicate to the receiver when it should look at the pin - this is sending the *clock* to the receiver.

Fourth, you get the way IR remote controls work. These use different length pulses of HIGH/LOW to indicate a 1 or a 0. A long HIGH and short LOW could be a 1, and a short HIGH and long LOW could be a 0.
> 0 votes

---
Tags: interrupt, digital-in
---