# Question
Title: Serial communication between Arduino and Java NetBeans
I am new to this serial communication between Arduino and Java NetBeans. I am doing some small project and I need to get data from external EEPROM 24LC256 which is connected to Arduino UNO and pass it to the Java NetBeans platform not the Eclipse. So far I am using RXTX driver to communicate with Arduino in Java and easily get the data from serial monitor of Arduino IDE.

So can anyone help me, on how can I serially communicate with this external EEPROM using Java?

```
import gnu.io.*;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;

public class last extends javax.swing.JFrame implements SerialPortEventListener  {
    SerialPort serialPort;
    private static final String PORT_NAMES[] = {
        "COM3", // Windows
    };
    private BufferedReader input;
    private OutputStream output;   /** The output stream to the port */
    private static final int TIME_OUT = 2000; /** Milliseconds to block while waiting for port open */
    private static final int DATA_RATE = 9600;  /** Default bits per second for COM port. */
    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        while (portEnum.hasMoreElements()) {   //First, Find an instance of serial port as set in PORT_NAMES.
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
            System.out.println("Could not find COM port.");
            return;
        }
        try {          // open serial port, and use class name for the appName.
            serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
            serialPort.setSerialPortParams(DATA_RATE,  // set port parameters
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));   // open the streams
            output = serialPort.getOutputStream();
            serialPort.addEventListener(this);   // add event listeners
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            System.err.println(e.toString());
        }}

    /**
     * This should be called when you stop using the port.
     * This will prevent port locking on platforms like Linux.
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }}

    /**
     * Handle an event on the serial port. Read the data and print it.
     */
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                String inputLine=input.readLine();
                System.out.println("the state of the led is  "+inputLine);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    public static void main(String[] args) throws Exception {
        last main = new last();
        main.initialize();
        Thread t = new Thread() {
            public void run() { //the following line will keep this app alive for 1000 seconds,
                //waiting for events to occur and responding to them (printing incoming messages to console).
                try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
            }
        };
        t.start();
        System.out.println("Started");
    }
}

```

This is the code in Java NetBeans.

# Answer
> 2 votes
Your EEPROM has I2C interface, so first you shall program Arduino to access it: An I2C EEPROM Class for Arduino

Then implement some kind of communication protocol over serial, to send commands instructing Arduino to read/write from EEPROM. For example, with following commands:

* for writing `write:<address>,<count>,<data_as_hex_string>`
* for reading `read:<address>,<count>`
* response for reading: `<address>,<count>,<data_as_hex_string>`

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


title: Issues with analog microphone readings

text:
# Question
Title: Issues with analog microphone readings
I'm having issues with sampling audio with a microphone and NodeMCU v3. I realize this is the Arduino section so if NodeMCU running the Arduino IDE is not meant for this forum, let me know.

The problem: I am sampling audio for an sound reactive RGB LED strip with the NodeMCU v3. When I use USB power from my computer, everything works well. If I power the NodeMCU from a 7805 linear regulator (5v) to Vin, it works fine. "Silent" conditions hang around 0 volts and audio levels show up clearly. When I power the NodeMCU with a 3.3v switching regulator (with the microphone grounded on the NodeMCU and VCC coming from the 3v3 pin) this is where the problem starts. If I have the LED strip unconnected, it detects the sound find (although my "silent" conditions hover more around .1 volts but for my purposes that wouldn't be an issue).

The problem is powering the board and subsequent microphone from the switching regulator with the lights connected I get very erratic voltage readings that are all over the place. You might be asking why not just use the linear regulator then? Well, even at 12 volts the (12v-5v)\*(a few hundred mA) is a decent amount of heat to dissipate but sure I could get a heat sink and control it, but the end goal for this project is to power my 10m strip, which is 24 volts, and the linear regulator would have to dissipate (24v-5v) * (a few hundred mA). I really do not think this is sustainable, which is why I got the switching regulator in the first place.

I was told that these switching regulators do not play nicely with microphones. Even with the LED strip unconnected it wasn't as consistent as USB or linear regulator power but it still worked perfectly fine.

Could anybody explain why this issue arises and hopefully a way to fix it? Are there tricks I can use to limit whatever interference is occurring? Should I give up on trying to make the switching regulator work? Would capacitors/resistors solve this?

I really would prefer to use the switching regulator for efficiency reasons. My second option wouldn't be the linear regulator, it would be powering the Node from a wall adapter and USB cable to be honest. This is getting quite frustrating. One problem's fix causes another, but I suppose that's how things go sometimes.

I am including a diagram of my setup. Please note the linear regulator should actually be a switching regulator and the board I am using is not the Huzzah, it's the NodeMCU v3.

Components:

* NodeMCU v3
* Adafruit Electret Mic (won't let me post more links... it's the adj. gain one)
* Switching Regulator
* N Type Mosfets
* RGB LED strip (currently a 5 meter 12 volt 5050 leds, future: 10 meter 24 volt)

If there is something that will solve my issue, I am not worried that it costs $5 versus the linear regulator being

I would really really appreciate any help in solving this issue, this is pretty much the last part of a pretty big and feature-rich controller.

Hopefully I have included as much information as is needed.

Thank you and feel free to ask any questions!

# Answer
The problems mentioned probably result from electrical interference, and as such might be better addressed in Electronics Stackexchange. But here is a quick overview of how to ameliorate the problem: add shielding and filtering.

For shielding, add a housing or braided-wire cable sleeves. To shield against electrical fields, the housing should be conductive and have no openings larger than the wavelength of the electrical interference you wish to suppress. To shield against magnetic fields, it should be made of a ferromagnetic material. You should have a housing around the switching supply, and can also add housings around any sensitive amplifier circuits.

For filtering, you can add an output filter with a few thousand microfarads of capacitance. For better filtering, use several large capacitors, with a choke (inductor) to connect each capacitor to the next. Add ferrite beads on each of the wires out of the power supply. Besides the large capacitors, add a couple of small ones, eg 0.01 and 0.1 μF before the chain of large filter capacitors, ie, close to the output terminals of the switching supply. Small capacitors generally have smaller self-inductance and can be more effective than large ones at suppressing high frequency hash. The big capacitors effectively smooth out lower frequency ripple but if they have much self-inductance may fail to suppress high frequencies.
> 0 votes

---
Tags: arduino-ide, led, audio, nodemcu, mosfet
---


# Question
Title: error: too few arguments to function 'char* itoa(int, char*, int)' byte blockcontent= itoa(order); ^ In file include
I have this statement in my Arduino code :

```
 byte blockcontent [16] = itoa(order);

```

and it gives me an error saying: "Too few arguments to function 'char*itoa(int,char*,int)'. Even though I've looked for the documentation of itoa function and I found that it accepts one input argument. Can anyone help me fix this error?

# Answer
itoa requires a minimum of 2 arguments.

Reference: http://www.nongnu.org/avr-libc/user-manual/group\__avr\__stdlib.html#gaa571de9e773dde59b0550a5ca4bd2f00
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How do I lock out a push button input with a selectable delay?
I have a program i am working on where a relay is turned on -\> waits a delay -\> then turns off after either one of two things happen: 1) A set timer is reached OR 2) someone pushes a push button to trigger it.

Right now 90% of my code is working and i am stuck on how i go about "locking out" the push button from triggering the relay, for a select-able amount of delay time.

The timer portion of the code, with select-able times, is working. Depending on what analog 1 see's, it will trigger the relay appropriately after the selected time.

I tried to implement this same approach for the lock out timer, using analog 2 , to determine how long of a delay. I used a variable i called LOK to either read the button if it is unlocked (LOK = 0) or if it is locked (LOK =1) to wait the allotted delay time before unlocking and allowing the button to be read again.

I've tried all sorta of things and it still isn't functioning right. Maybe there is a better or simpler way to do this but I've racked my brain, and key word searching isn't helping.

Code below - please forgive random comments. I've been chopping up and moving things around i haven't edited any comments , so some may be from other snippets of codes from other projects.

```
int DUMP = 2; // Pin connected to big dump relay
int BUTTON = 3; // Pin connected to manual dump push button.
int BUTTONlight = 4; // Pin connected to push button light.

int BUTstate; // Current reading from BUTTON pin
int lastBUTstate = LOW; // Previous reading from BUTTON pin

long lastDebounce = 0; // Last time output was changed
long Delay = 50; // Debounce Time

unsigned long DUMPTIME;
unsigned long LOT;

unsigned long prevTIME;

int a=0;
int d=0;

int LOK = 0;

void setup()
{
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);

  pinMode (BUTTON, INPUT);
  pinMode (BUTTONlight, OUTPUT);
  pinMode (DUMP, OUTPUT);

  digitalWrite(DUMP, HIGH);
  delay(10000);
  digitalWrite(DUMP, LOW);
  digitalWrite(BUTTONlight, HIGH);
}

int readTselector(int pin)
// returns the button number pressed, or zero for none pressed
// int pin is the analog pin number to read
{
  int b,c = 1;
  c=analogRead(pin); // get the analog value
  if (c>1000)
  {
    b=0; // buttons have not been pressed
  }
  else
    if (c<1000 && c>600)
    {
      b=1; // button 1 pressed
    }
    else
      if (c<520 && c>400)
      {
        b=2; // button 2 pressed
      }
      else
        if (c>100 && c<400)
        {
          b=3; // button 3 pressed
        }
        else
          if (c<100)
          {
            b=4; // button 4 pressed
          }
  return b;
  }

void loop()
{
  int DUMPTIME = DTselect();
  int LOT = LOselect();

  int reading = digitalRead(BUTTON);

  unsigned long currTIME = millis();

  if ((currTIME - prevTIME) >= DUMPTIME) // Count to 2 minutes
   {
     LOK = 1;
     digitalWrite(BUTTONlight, LOW);
     digitalWrite(DUMP, HIGH);
     delay(10000);
     digitalWrite(DUMP, LOW);
     prevTIME = currTIME;
   }

  if (reading != lastBUTstate)
  {
    lastDebounce = millis();
  }

  if (LOK == 1)
  {
    delay(LOT);
    digitalWrite(BUTTONlight, HIGH);
    LOK = 0;

  }
  if ((millis() - lastDebounce) > Delay && LOK == 0)
  {
    BUTstate = reading;
  }

  if (BUTstate == HIGH)
  {
    digitalWrite(BUTTONlight, LOW);
    digitalWrite(DUMP, HIGH);
    delay(10000);
    digitalWrite(DUMP, LOW);
    prevTIME = currTIME;
  }
  lastBUTstate = reading;
}

int DTselect()
{
  a=readTselector(1);
  if (a==0) // no buttons pressed
  {
    DUMPTIME = 210000;
  }
  else
    if (a==1) // someone pressed a button!
    {
      DUMPTIME = 180000;
    }
    else
     if (a==2) // someone pressed a button!
     {
       DUMPTIME = 150000;
     }
     else
      if (a==3) // someone pressed a button!
      {
        DUMPTIME = 120000;
      }
     else
       if (a==4) // someone pressed a button!
       {
         DUMPTIME = 90000;
       }
  return DUMPTIME;
 }

int LOselect()
{
  d=readTselector(2);
  if (d==0) // no buttons pressed
  {
    delay(20000);
  }
  else
    if (d==1) // someone pressed a button!
    {
      delay(15000);
    }
    else
     if (d==2) // someone pressed a button!
     {
       delay(10000);
     }
     else
      if (d==3) // someone pressed a button!
      {
        delay(5000);
      }
      else
       if (d==4) // someone pressed a button!
       {
         delay(0);
       }
 }

```

# Answer
> 1 votes
I took your code and did a bit of an edit. You had some useless variables and you where redefining DUMPTIME and LOT in a wierd way. I also define some of your constants as #define's because thats the way you should always do it.

```
#define DUMP 2          // Pin connected to big dump relay
#define BUTTON 3        // Pin connected to manual dump push button.
#define BUTTONlight 4   // Pin connected to push button light.
#define DELAY 50        // Debounce Time

int BUTstate;           // Current reading from BUTTON pin
int lastBUTstate = LOW; // Previous reading from BUTTON pin

long lastDebounce = 0;  // Last time output was changed

unsigned long DUMPTIME;
unsigned long LOT;
unsigned long prevTIME;

int LOK = 0;

int readTselector(int pin)
// returns the button number pressed, or zero for none pressed
// int pin is the analog pin number to read
{
    int c = analogRead(pin); // get the analog value
    if (c > 1000){
        return 0; // buttons have not been pressed
    }
    else if (c<1000 && c>600){
        return 1; // button 1 pressed
    }
    else if (c<520 && c>400){
        return 2; // button 2 pressed
    }
    else if (c>100 && c<400){
        return 3; // button 3 pressed
    }
    else if (c<100){
        return 4; // button 4 pressed
    }
    else return 0; // just in case
    }

long DTselect()
{
    switch(readTselector(1)){
        case 0: return 210000; // no buttons pressed
            break;
        case 1: return 180000; // someone pressed a button!
            break;
        case 2: return 150000;
            break;
        case 3: return 120000;
            break;
        case 4: return 90000;
            break;
        default: return 210000; // default
            break;
    }
 }

int LOselect()
{
  switch( readTselector(2) ){
        case 0:  return 20000; // no buttons pressed
            break;
        case 1:  return 15000; // someone pressed a button!
            break;
        case 2:  return 10000;
            break;
        case 3:  return 5000;
            break;
        case 4:  return 0;
            break;
        default: return 20000; // default
            break;
    }
 }

void setup()
{
    pinMode(A1, INPUT);
    pinMode(A2, INPUT);

    pinMode (BUTTON, INPUT);
    pinMode (BUTTONlight, OUTPUT);
    pinMode (DUMP, OUTPUT);

    digitalWrite(DUMP, HIGH);
    delay(10000);
    digitalWrite(DUMP, LOW);
    digitalWrite(BUTTONlight, HIGH);
}

void loop()
{
    DUMPTIME = DTselect();
    LOT = LOselect();

    int reading = digitalRead(BUTTON);

    unsigned long currTIME = millis();

    if ((currTIME - prevTIME) >= DUMPTIME){// Count to 2 minutes
        LOK = 1;
        digitalWrite(BUTTONlight, LOW);
        digitalWrite(DUMP, HIGH);
        delay(10000);
        digitalWrite(DUMP, LOW);
        prevTIME = currTIME;
    }

    if (reading != lastBUTstate){
        lastDebounce = millis();
    }

    if (LOK){
        delay(LOT);
        digitalWrite(BUTTONlight, HIGH);
        LOK = 0;
    }

    if ((millis() - lastDebounce) > DELAY && !LOK){
        BUTstate = reading;
    }

    if (BUTstate == HIGH){
        digitalWrite(BUTTONlight, LOW);
        digitalWrite(DUMP, HIGH);
        delay(10000);
        digitalWrite(DUMP, LOW);
        prevTIME = currTIME;
    }
    lastBUTstate = reading;
}

```

A different version with a BUTflag variable to keep track of the button press and release. I have not dealt with the DUMPTIME variable but hopefully this will give you an idea of how to use flags so the logic doesn't fail.

```
#define DUMP 2          // Pin connected to big dump relay
#define BUTTON 3        // Pin connected to manual dump push button.
#define BUTTONlight 4   // Pin connected to push button light.
#define DELAY 50        // Debounce Time

int BUTstate;           // Current reading from BUTTON pin
int BUTflag = 0;
int go = 0;
long lastDebounce = 0;  // Last time output was changed

unsigned long DUMPTIME;
unsigned long LOT;
unsigned long prevTIME;

int LOK = 0;

int readTselector(int pin)
// returns the button number pressed, or zero for none pressed
// int pin is the analog pin number to read
{
    int c = analogRead(pin); // get the analog value
    if (c > 1000){
        return 0; // buttons have not been pressed
    }
    else if (c<1000 && c>600){
        return 1; // button 1 pressed
    }
    else if (c<520 && c>400){
        return 2; // button 2 pressed
    }
    else if (c>100 && c<400){
        return 3; // button 3 pressed
    }
    else if (c<100){
        return 4; // button 4 pressed
    }
    else return 0; // just in case
    }

long DTselect()
{
    switch(readTselector(1)){
        case 0: return 210000; // no buttons pressed
            break;
        case 1: return 180000; // someone pressed a button!
            break;
        case 2: return 150000;
            break;
        case 3: return 120000;
            break;
        case 4: return 90000;
            break;
        default: return 210000; // default
            break;
    }
 }

int LOselect()
{
  switch( readTselector(2) ){
        case 0:  return 20000; // no buttons pressed
            break;
        case 1:  return 15000; // someone pressed a button!
            break;
        case 2:  return 10000;
            break;
        case 3:  return 5000;
            break;
        case 4:  return 0;
            break;
        default: return 20000; // default
            break;
    }
 }

void setup()
{
    pinMode(A1, INPUT);
    pinMode(A2, INPUT);

    pinMode (BUTTON, INPUT);
    pinMode (BUTTONlight, OUTPUT);
    pinMode (DUMP, OUTPUT);

    digitalWrite(DUMP, HIGH);
    delay(10000);
    digitalWrite(DUMP, LOW);
    digitalWrite(BUTTONlight, HIGH);
}

void loop()
{
    DUMPTIME = DTselect();
    LOT = LOselect();

    BUTstate = digitalRead(BUTTON);

    unsigned long currTIME = millis();
/*
    if ((currTIME - prevTIME) >= DUMPTIME && !LOK){
        LOK = 1;
        digitalWrite(BUTTONlight, LOW);
        digitalWrite(DUMP, HIGH);
        delay(10000);
        digitalWrite(DUMP, LOW);
        prevTIME = currTIME;
    }
    else */
    if (LOK){
        delay(LOT);
        digitalWrite(BUTTONlight, HIGH);
        LOK = 0;
    }
    else if(!LOK){
        if(!go && BUTstate && !BUTflag){
            lastDebounce = millis();
            BUTflag = 1;
        }
        else if (!go && BUTstate && BUTflag==1 && (millis() - lastDebounce) > DELAY){
            BUTflag = 2;
        }
        else if (!go && !BUTstate && BUTflag==2){
            BUTflag = 0;
            go = 1;
        }
        else if (go){
            digitalWrite(BUTTONlight, LOW);
            digitalWrite(DUMP, HIGH);
            delay(10000);
            digitalWrite(DUMP, LOW);
            prevTIME = currTIME;
            go = 0;
            LOK = 1;
        }
    }
}

```

---
Tags: button
---


title: Measuring ADC sample rate - Arduino DUE

text:
# Question
Title: Measuring ADC sample rate - Arduino DUE
I want to measure the conversion rate of an arduino DUE. I know I could just take it from the datasheet but I need to measure it because I am running the ADC in free running mode. Hints are welcome, I really don't know where to start.

# Answer
> 1 votes
I think using an interrupt controlled measurement might provide the best results for you.

Note: you might get more complete feedback using the Arduino forum.

In general the process would look like this:

1. Set up an interrupt vector for the ADC peripheral (in this case support for ID37).
2. Setup ADC registers (res, clock etc)
3. Set up a timer to time the conversion.
4. Create Active flag and Timer variables for processing inbound timer values.
5. Start timer and ADC conversion.
6. Loop waiting for active flag to set (it gets set in the ISR), when detected do average or store timer values, then clear active flag.

This methodology times each individual conversion using a high speed timer, which could mean a lot of values to process. You could equally not time each conversion, but simply set up say a 1 second timer, and count the total number of conversions in 1 second for your particular ADC configuration.

Peripheral ISR

1. Waiting for Interrupt.
2. In peripheral ISR, read and store timer value, reset timer, set active flag
3. Return from ISR

# Answer
> 0 votes
To expand on Jack Creasey's answer, timestamping the samples as they are taken is the most direct way to do it. If you have a block of N samples, the average sample period is simply

$$\frac{Time\_{last} - Time\_{first}}{N - 1}$$

(Note that there are N-1 time intervals between N samples.)

If you want the sample rate, just invert the expression:

$$\frac{N - 1}{Time\_{last} - Time\_{first}}$$

---

However, you can also infer the sample rate from a known signal. For example, you can feed a tone signal into the ADC and count the number of samples between some well-defined feature of the waveform, such as rising zero crossings. If you count N samples, then the sample rate is N times the tone frequency. Averaging over multiple cycles of the tone will give you a more precise measurement.

---
Tags: adc
---


# Question
Title: Storing latitude and longitude floats as chars with specified precision
I am receiving lat and long data from a GPS and want to store these numbers in the middle of a sequence of chars.

E.g. lat = -23.123456

long = 135.123456

I am after something like "Your coordinates are -23.123456,135.123456" as an array of chars.

I have tried:

```
float latitude = -23.123456;
float longitude = 135.123456;

String one = "Your coordinates are ";
String two = ","
String message = one + latitude + two + longitude;

// Convert String to char array
int str_len = message.length() + 1;
char textmessage[str_len];
message.toCharArray(textmessage,str_len);

Serial.println(textmessage);

```

but the result is: Your coordinates are -023.12,0135.12

How can I correct this?

Thanks in advance!

# Answer
When formatting serial output is a concern, it's worthwhile to download and use the `Streaming.h` contributed library that adds some “syntactic sugar” to Arduino C. That is, at compile time it converts C++-like `<<` Serial stream operators to `Serial.print` statements, without increasing code size. If you don't have `Streaming.h` installed, you can get `Streaming5.zip` from arduiniana.org.

At present, `Streaming.h` doesn't support `setw()` and `setfill()`, which in ordinary C++ set a field width and a fill character.

However, it does support four base-conversion specifiers, \_HEX, \_DEC, \_OCT, and \_BIN; a \_FLOAT function with number of decimal places specified; and `endl`.

Thus, to print “Your coordinates are -23.123456, 135.123456” one would write:

```
Serial << "Your coordinates are " << _FLOAT(latitude,6) << ", " << _FLOAT(longitude,6) << endl;

```

Note that unlike the `String` class, use of `Streaming.h` does not entail any dynamic memory management – everything it does happens at compile time – and it does not increase code size – it translates stream-style operations into ordinary `.print()` and `.println()` calls. It should result in somewhat smaller, faster, and more-robust code, by avoidance of `String`. Use of dynamic memory on small-memory embedded systems can be problematic, and this avoids those problems.

---

*Edit 1a:* As Chris Stratton points out, Arduino floats don't support 9-digit precision. I think Arduino floating-point arithmetic is intended to comply with IEEE 754, which sets out standards to be used on modern computers that support floating-point arithmetic.

In the binary32 format used to implement IEEE 754 single-precision binary floating-point, significand precision is 24 bits. That equates to about 7.22 decimal digits (ie, 24\*log₁₀(2)), so for simple calculations, 7-digit accuracy is realistic, more than that is not.

---

*\[Part of\] Edit 1b:* In the larger scheme of things perhaps there's no need to create and save a formatted string like that. It is not useful for computing – the float values are better for that. It is not needed for communication – another streaming write can be done.

---

*Edit 2 \[replaces most of 1b\]:* Streaming.h doesn't build any strings, but just delivers the text of its `<<`-arguments character-by-character to a stream. However, a PString class at arduiniana can build strings from stream inputs, as in the following example code.

```
#include <Streaming.h>
#include <PString.h>

char buffer[28];
PString pstr(buffer, sizeof(buffer));

void setup() {
  Serial.begin(115200);
  pstr.begin();     // Empty the buffer
}

void loop() {
  int first=50, second=100;
  pstr.begin();     // Empty the buffer
  pstr << 'X' << first << 'Y' << second << 'T';
  pstr += " hihi ";
  pstr << millis() << endl;
  Serial << pstr;
  delay(1000);
}

```

Here's what some of its output to Serial looks like:

```
X50Y100T hihi 263198
X50Y100T hihi 264199
X50Y100T hihi 265199
X50Y100T hihi 266201
X50Y100T hihi 267201
X50Y100T hihi 268201

```

What the sample of code does is first initialize a string buffer, then build part of a character string using streaming operator `<<`, then part of it using concatenation, then some more with `<<`, then print the string. Note that the strings involved here are in fixed buffers, rather than dynamically allocated buffers like the String class uses.
> 1 votes

---
Tags: arduino-uno, string, gps, array, float
---


# Question
Title: How do I squeeze code to fit onto an ATTiny
I am using an ATTiny85 for the first time and at compile I receive the following errors

```
Arduino: 1.6.11 (Windows 10), Board: "Digispark (Default - 16.5mhz)"

C:\Users\Steve\AppData\Local\Temp\build129e80c0e73568918bca55047472d138.tmp/Smoke_Auto-ATtiny.ino.ino.elf section `.text' will not fit in region `text'

c:/program files (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.9.2/../../../../avr/bin/ld.exe: region `text' overflowed by 562 bytes

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Digispark (Default - 16.5mhz).

```

The chip is

```
Atmel 1344
Tiny85
20SF

```

I think what is happening is that my code is too big for the board. Am I right?

Assuming so, ignoring any obvious programming errors (I can't debug for this board until I can upload :P ) how can I squeeze code like this onto an ATTiny? I am not looking for someone to rewrite it for me, I am more interested in learning where there is any obvious bloat - I suspect the IR library (IRremote Version 2.0.1 June, 2015 by Ken Shirriff : 11Kb)

FWIW this is a project to convert a manually operated smoke machine into an automatic one and be able to manipulate the smoke time and delay via a remote. It works on a Mega, proof of concept complete, I want to shrink the board to fit into the mouse-sized controller if that is possible.

```
#include <IRremote.h>

long smokeTimeInit = 5000;  // initial smoke time
long smokeWaitInit = 60000;  // initial interval between smoke

long smokeIncrement = 1000; // timer increment value
long delayIncrement = 5000; // timer increment value

unsigned long previousMillis = 0; // this is our stored time
unsigned long currentMillis;  //where we keep count of time

const int smokeOnPin = 2;  // output to relay
int smokeStopped = false; // flag to stop smoke
const int LED = 0;
const long RECV_PIN = 1;  // input from IR receiver

IRrecv irrecv(RECV_PIN);

decode_results results;

long  smokeTime = smokeTimeInit;
long  smokeWait = smokeWaitInit;

void setup() {
  pinMode(smokeOnPin, OUTPUT);
  pinMode(LED, OUTPUT);

  irrecv.enableIRIn(); // Start the receiver

  digitalWrite(smokeOnPin, LOW);  // start with the smoke on
  digitalWrite(LED, HIGH);

}

void loop() {
  if (irrecv.decode(&results)) {

    switch(results.value){
      case 284157975 :
      //more smoke time
        smokeTime = smokeTime + smokeIncrement;
        smokeStopped = false; // smoke on

      break;
      case 284104935 :
      //less smoke time
        if(smokeTime > smokeIncrement){ // don't let the smoke time become less than the increment value i.e. negative
          smokeTime = smokeTime - smokeIncrement;
        }
        else{
          smokeTime = 1000;
        }
        smokeStopped = false;

      break;
      case 284125335 :
      //reduce interval
        if(smokeWait > delayIncrement){
          smokeWait = smokeWait - delayIncrement;
        }
        else{
          smokeWait = 1000;
        }
        smokeStopped = false;  // smoke on

      break;
      case 284141655 :
      // increase interval
        smokeWait = smokeWait + delayIncrement;
        smokeStopped = false;  // smoke on

      break;
      case 284140125 :
      // reset to initial time values
        smokeTime = smokeTimeInit;
        smokeWait = smokeWaitInit;
        smokeStopped = false;  // smoke on

      break;
      case 284148285 :
      // reset but with shorter smoke time
        smokeTime = 1000;
        smokeWait = 60000;
        smokeStopped = false;  // smoke on

      break;
      case 284123805 :
      // reset with short smoke and shorter interval
        smokeTime = 2000;
        smokeWait = 30000;
        smokeStopped = false;  // smoke on

      break;
      case 284131965 :
      // stop
        smokeStopped = true;
      break;

    }

    irrecv.resume();
  }
currentMillis = millis();

if(smokeStopped){  // don't even do this if smoke stopped
    if (currentMillis - previousMillis >= smokeTime && digitalRead(smokeOnPin)==0) {
      digitalWrite(smokeOnPin, HIGH); // turn the smoke on
      digitalWrite(LED, LOW);
      previousMillis = currentMillis;
    }
    else if (currentMillis - previousMillis >= smokeWait && digitalRead(smokeOnPin)==1 ) {
      digitalWrite(smokeOnPin, LOW); // turn the smoke off
      digitalWrite(LED, HIGH);
      previousMillis = currentMillis;
    }
}

}

```

# Answer
> 0 votes
Yes, the message “... Smoke\_Auto-ATtiny.ino.ino.elf section `.text' will not fit in region`text'” suggests the code is too big to fit in the 8K available on the ATtiny85.

\[In a .elf file, the TEXT section contains executable code.\]

In IRremote.h from Ken Shirriff et al, some comments at line 28 say to disable protocols you don't need:

```
// Supported IR protocols
// Each protocol you include costs memory and, during decode, costs time
// Disable (set to 0) all the protocols you do not need/want!

```

By default, about 13 protocols are enabled and three disabled. If you only use one or two kinds of remotes, you can disable a bunch of the protocols.

Here are a couple of minor things for reducing memory, etc.:

• Instead of switching on `results.value`, a `long`, you could compute an `unsigned int` equal to `results.value-284100000`, since all of your case values start with 2841 and the largest is 284157975.

• Instead of having `smokeStopped = false; // smoke on` seven times within various cases, and `smokeStopped = true;` in one of them, set `smokeStopped` to `false` before the switch, and drop the seven settings-to-false from within the switch.

• Some of your time-related variables would be better as `unsigned long` instead of just `long` variables.

Generally, your code looks clean enough except for those items. Also, the IRremote code doesn't look bloated; but its tables can take a lot of memory.

*Edit 1–* Addressing crowie's comment about using `#define` instead of `const int`, one *can* use `#define`'s, but in general the modern thought is that `const int` is preferable for type safety. Typically there is no difference in generated code – aside from type checking, the compiler treats a `const int` the same way as a `#define`, ie does not allocate memory for it if it isn't used, or if the value is small, may use a load-immediate instead of fetching a value from memory.

My own preference is to use `enum { ... }` to declare integer constants. For example, instead of

```
const int smokeOnPin = 2;  // output to relay
const long RECV_PIN = 1;  // input from IR receiver

```

I'd write

```
enum { smokeOnPin=2, IRinPin=1 }; // Pin# for smoke on and IR input

```

# Answer
> 1 votes
The `avr-nm` tool is great for figuring out what is using up all your memory.

You need to get to a command-line in the temporary directory where your program is compiled. You can find this directory by looking at the scrolling bottom window when you compile your program.

You run the tool like this...

`C:\Users\passp\AppData\Local\Temp\arduino_build_965235>"C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avr-nm" -S --size-sort blink.ino.elf`

...where in my case...

`C:\Users\passp\AppData\Local\Temp\arduino_build_965235` is the temporary directory that the Arduino was using

`C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\` and the directory where the Arduino toolchain was installed

`blink.ino.elf` is the output generated from compiling my `blink.ino` sketch.

The `-S` parameter tells the tool to output the sizes of the symbols listed. By looking at these sizes, we can figure out what is using up all the memory and where to focus our reduction efforts.

The `--size-sort` shorts the symbols in size order so we can easily see which are the biggest.

The output of the tool on my program looks like...

`0080010b 00000001 b click
0080008e 00000001 B datLen
00800088 00000001 b IRcount.1978
00800089 00000001 B msgNum
00800086 00000001 b prevVals.1995
0080008f 00000001 B progDir
00800087 00000001 b sendState.1979
00800109 00000001 b state
0080010a 00000001 b sync
00800092 00000001 B wake
00800066 00000002 D buttonCB
00800068 00000002 D clickCB
0080010c 00000002 B comBuf
00800115 00000002 B datBuf
0000006a 00000002 T emptyCB
00800075 00000002 D holdoff
0080008c 00000002 B ledMode
00800062 00000002 D longButtonCB
0080006f 00000002 d longPressTime
00800090 00000002 b longPressTimer
00000068 00000002 T loop
0080006a 00000002 D mode
00000d00 00000002 T setPort
00800064 00000002 D timerCB
0080008a 00000002 B timerCBcount
00800060 00000002 D timerCBtime
0080007d 00000003 D black
0080007a 00000003 D dark
0080006c 00000003 D outColor
00800077 00000003 D wakeColor
00000da6 00000004 T __mulsidi3
00800093 00000004 b powerDownTimer
00800131 00000004 B prevTimer
00800097 00000004 B sleepTimer
0080009b 00000004 b startTime
00800071 00000004 D timeout
00800105 00000004 b timer
00000a7a 00000006 T disAD
00800080 00000006 b pulseCount.1996
0080009f 00000006 b timeBuf
0080010e 00000007 B blinking
00800117 00000007 B pulsing
00000a80 00000008 T enAD
000000d4 0000000c T setColorRGB
00000a88 0000000e T initTimer
0000005a 0000000e T setup
00000044 00000010 T __do_clear_bss
0080011e 00000013 B fading
0000002e 00000016 T __do_copy_data
00000d66 00000018 T __udivmodqi4
00000a5c 0000001e T initIO
00000ce0 00000020 t sendByte
00000d44 00000022 T __mulhi3
00000822 00000022 T __vector_3
0000006c 00000022 T getTimer
00000d7e 00000028 T __udivmodhi4
00000e18 00000036 T __epilogue_restores__
00000daa 00000036 T __umulsidi3
00000de0 00000038 T __prologue_saves__
000003e8 00000038 T updateLed
0000027c 0000003a T blink
00000d02 00000042 T sendColor
0000008e 00000046 T tileSetup
00000e4e 0000005c T __muldi3
008000a5 00000060 b times
0000035e 0000008a T pulsingUpdate
000002b6 000000a8 T blinkUpdate
00000a96 000000d4 T hsv2rgb
00000b6a 00000176 T main
000000e0 0000019c T fadeUpdate
00000844 00000218 T __vector_2
00000420 00000402 T __vector_9` The second column is the amount of space used by the symbol.

So just looking at the bottom of our list, we can see that much of the space is being used by the functions `main`, `fadeUpdate`, `__vector_2` , and `__vector_9`.

`main` and `fadeUpdate` are obvious, but the `__vector_x` functions are actualy interrupt service routines. The actual mapping of numbers to interrupt sources can be different for different chips, so probably the easiest way to figure out what a given vector is would be to comment out the ISR in your code and then do the above process and see which vector evaporates in size.

You will have to look at each function carefully and individually to see how to possible reduce its size, but at least with this procedure you know where too look!

---
Tags: attiny
---


title: Control the "TV remote"

text:
# Question
Title: Control the "TV remote"
My idea is to use Arduino to control the TV remote. Not make the Arduino become a TV remote, I want to make an Arduino that can touch button of a remote control.

Any ideas?

# Answer
My rather fancy solution would be to make a 3 axis device with x and y controlled by stepper motors and z a simple solenoid to press the buttons. For extra marks you could add a camera and try to recognise the buttons in software so any remote would work. How do you plan to control the arduino? Perhaps with a remote controller?
> 2 votes

---
Tags: arduino-uno, remote-control
---


# Question
Title: How to programmatically upload an Arduino sketch generated by node.js (electron) or from browser?
We are trying to make an app that generates an Arduino sketch (.ino) using Google's Blockly and node.js, and uploads it to Arduino.

Even after searching a lot, I am unable to find how to build and upload the generated code to the board. Is there any tool or API available for node.js to do the same?

Or could I call some binary for this function. Please help.

# Answer
There are two things you need to do:

1. Compile the sketch into a .HEX file
2. Upload the sketch to the board

The first part can be done with `arduino-builder` which is part of the IDE since 1.6.6, or you can use one of various `Makefile` projects on a platform that supports `make`, or you can manually script it yourself calling the correct `avr-gcc` and `avr-g++` commands. You can check the output of the IDE for what those are.

The second part is done, usually, using `avrdude` \- again see the output of the IDE for the correct command format.
> 1 votes

---
Tags: arduino-mega, uploading, compile, build, node.js
---


# Question
Title: Connecting high sampling rate DAC and ADC to arduino DUE, timer consideration
I'm in the echopen association, our goal is to create a low cost, open source echographic probe. In order to do that, we use an arduino due for the first step. For doing acoustic imaging, we use ultrasonic transducer wich works at high frequency, typically 5 MHz. So, for our purpose we need to send and receive analogic signal at high frequencies. We want to connect a 80 Msps DAC and a 80 Msps ADC to the arduino due so we can generate and mesure analog signal up to 42 MHz. I have found here (http://www.instructables.com/id/Arduino-Timer-Interrupts/#step0) how to use arduino timer interrupts in order to send and receive data at 84 MHz. I haven't connect my converters for the moment, but I have preliminary questions. First, is the definition of the timer is the same for the arduino due (i.e. timer1 is a 16 bits timer) ? Morever, my ADC and DAC are 14 bits converters, can I tell to the arduino to sent only 14 bits digital signal ? Secondly, as we work at high frequencies we will have to send a lot of data from the microcontroller to a computer via the serial port. I have make a test and at 250000 bauds it takes nearly 0.5 second to transfer 4300\*8 bits datas. It is to slow for our purpose, how can I do it faster ?

# Answer
> 2 votes
If I'm interpreting the datasheet correctly, you might be able to use the Static Memory Controller (SMC) capability of the Cortex M3 Sam3X to attach some 128K x 8 SRAM devices to your Due. If your ADC and DAC support tri-state outputs then they could be attached the same way as memories (but ignoring address lines as irrelevant), allowing memory-to-memory DMA transfers. Ie one could either input and store batches of ADC results at 42 MSPS, or could output batches of data to DAC at 42 MSPS, or could do simultaneous I/O at 21 MSPS. I haven't read the DMA section closely enough to verify that this will work with the M3.

See Figure 25-2 in Section 25.6.2 of the datasheet regarding memory controllers, and Section 26, “Peripheral DMA Controller (PDC)”, regarding DMA. Also see the eevblog.com page, “Looking for Cortex M3 or M4 with DMA to GPIO capability”.

# Answer
> 1 votes
I'm sorry, but by your description you are doomed to failure from the start.

The Arduino Due runs at 84MHz. That doesn't mean that it can communicate at 84MHz, only that it can process its instructions at around 84 million per second.

In order for you to transmit or receive 80 million samples per second you have to be able to a) transmit sample words (14 bits) 80 million times per second, and b) process the information between each sample.

That means you are going to require a processor that operates considerably faster than 84MHz.

For instance, assuming you are using high speed synchronous serial communication (say, SPI) to transfer the data. For 16 bits of data (you won't get it to do just 14 bits using hardware and software would be way too slow) would require a transmission clock of (80000000 * 16) 1.28GHz.

If you're using a 16-bit parallel interface then you would only need an 80MHz communication clock to move the data around, but receiving that data and storing it somewhere and also processing it would require many many more instructions between each clock. Far more than the Due could perform. Certainly it's way way outside the scope of a timer interrupt.

I would suggest instead investigating systems that run in the high hundreds of Megahertz or even Gigahertz range. Maybe one of the newer "version 2" Raspberry Pi embedded computers may be suitable.

# Answer
> 0 votes
May I suggest you decorrelate the acoustic frequency with the sampling frequency ?

While you need the high frequencies to get spatial resolution, what you are interested in is only the signal return amplitude (not the exact waveform), which you could sample at a much lower rate using appropriate analog front end.

---
Tags: arduino-due, timers
---


# Question
Title: Help: convert Arduino code to avr-gcc code
I need to convert Arduino code to avr-gcc code. This is code:

```
#include <Servo.h>

Servo myservo;

void setup() {
  myservo.attach(11);
}

void loop() {
  myservo.write(67);
}

```

I use Arduino Mega.

# Answer
> 2 votes
Try this:

```
#include <Servo.h>

extern "C" void init(void);

Servo myservo;

int main()
{
    init();
    myservo.attach(11);
    for (;;) {
        myservo.write(67);
    }
}

```

Note that this still needs the Arduino core library, as the Servo library depends on it, which means all this is an exercise in futility. If you are using the Arduino core, the simplest thing is to use it the Arduino way. If you do not want to use Arduino core, then you will have to partially re-implement the Servo library.

---
Tags: arduino-mega, c++, c, avr
---


title: Possibility of getting a UID on Arduino

text:
# Question
Title: Possibility of getting a UID on Arduino
Im working on a project where I will be using multiple Arduino (pro mini)'s which emit sensordata through LoRa.

The problem I am currently facing is, when I have multiple sensors, how do I know what data is coming from which Arduino (given they all have exactly the same source-code)?

1. Does the arduino have a UID like some sort of MAC code?
2. What could be a solution to give the Arduino a UID?
3. Do you guys have any other solutions for my issue?

In order to answer #2, I could add a random number calculator to create, but this doesn't feel right to me.

# Answer
You could use a small silicon serial chip like the Maxim DS2401 (http://pdfserv.maximintegrated.com/en/ds/DS2401.pdf)

An other method is to use good old dipswitches. That way you set each of your 'transmitter' to different address using the dipswitch. On boot the Arduino reads the switches to know it's address and uses that.
> 1 votes

---
Tags: arduino-pro-mini
---


title: Serial Communication

text:
# Question
Title: Serial Communication
When I send data using

Serial.println()

in what format does it go? I want to observe the data using the software 'Terminal'. When I observe there, if I've sent 255 using Serial.println(), I get a series of numbers 0 0 224 on the terminal. I've kept the baud rate same in both places(9600), Stop Bits as 1 in Terminal.

# Answer
> 0 votes
On the Arduino Serial.print() method web page it says:

> Prints data to the serial port as human-readable ASCII text.

...which is suitable for most terminal programs. ASCII or American Standard Code for Information Interchange is (usually) an 8 bit code for printing characters. It is not a code which you can do normal math with. That is the integer 1 (which is, in binary, b00000001) is not the same as the character '1' (which is, in binary, b00110001).

* Example: If you want to print "123" on most terminals you can use the Serial class method print:

Serial.print(123);

Now, you have to understand that the Arduino paradigm is to make programming simple. So the print method in the Serial class will assume you want to see the characters "123" on the terminal. So, guessing, the print method will convert each decimal number into an ASCII character and print them out as 3 values to the terminal. That is, the ASCII value for 1, followed by the ASCII value for 2 finally followed by the ASCII value for 3.

If this is not what you want there are other variations for the print method in the Arduino Serial class. But all tend to print using ASCII codes.

If you want to print out the binary values, see the Serial.write() method. This method will send the value of the argument to the terminal with out converting into ASCII code.

* Example: If you want to print "1" on most terminals you can use the Serial class method write:

Serial.write(49);

...as 49 is the decimal equivalent of the ASCII code for the character '1'.

# Answer
> 0 votes
Try using terminal program on PC side. NOT Arduino Serial port monitor built into Arduino IDE.

For example try http://docklight.de/

With this or some other similar terminal program, you can see each byte not only as ASCII representation, but also in HEX or binary format.

So you will easily in no time understand difference between ASCII "224" string and single byte 224 value.

With binary format you can have much much faster PC communication especially when sending float numbers. 4 bytes vs 3.7348823457458743 for example :)

On docklight you even have possibility to define macros for sending back to Arduino i ASCII or in binary format. Or even adjustable macros to send most of the string fixed, but change one byte inside string every time when sending.

But even basic ASCII or binary representation of data is enough for now to help you understand this problematic.

---
Tags: serial
---


title: Peak counting in serial Arduino

text:
# Question
Title: Peak counting in serial Arduino
I want to count peak of photocell data with serial communication in Arduino.

Here is the question. My problem is when I count one of the peaks it continues the counting and doesn't stop counting. My project is count Michelson Morley fringes with a photocell and Arduino.

If somebody can help me with the coding part I would appreciate it.

Here is the code that I used:

```
int count=0;
int val;
int data;

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

void loop() {
  data=analogRead(A0);
  val=map(data,0,1023,1000,0);
  if(val>700) {
   count++;
  }
  Serial.println(count);
  delay(100);
}

```

This picture shows what I am trying to achieve:

Example Michelson Morley fringes:

# Answer
keep in mind that since you used

```
delay(100)

```

your 'loop' code runs in 10HZ (10 times a second) So, every time you are lighting on your sensor, if its for longer than 1/10 of a second, you are likely going through several instances of 'loop', in which the condition

```
(val>700)

```

is satisfied.

If you **know** that your peaks are going to take several loops, and only want to count each peak once- a simple way would be to make sure you dropped from the previous peak before incrementing the counter. you can achieve that with something like:

```
int count=0;
int val;
int data;
bool inPeak = false;

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

void loop() {
  data=analogRead(A0);
  val=map(data,0,1023,1000,0);
  if(val>700) {
     if (!inPeak)
     {
        count ++;
        inPeak = true;
     }
  }
  else
  {
      inPeak = false;
  }

  Serial.println(count);
  delay(100);
}

```
> 2 votes

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


title: shiftOut using SPI isn't working

text:
# Question
Title: shiftOut using SPI isn't working
I made a sample using two of them using Arduino UNO.
So I did that like this:

(There aren't any resistor on that image, but there are 220ohm resistor on every LEDs.)
And uploaded this code.

```
//1.6us+62.5ns
#include <SPI.h>

#define sbi(port, bit) (port) |= (1 << (bit))
#define cbi(port, bit) (port) &= ~(1 << (bit))

int latchPin = 12;
int clockPin = 13;
int dataPin = 11;

byte data[]={ 0b10101010,0b11001100 };

void _595_out() {
    cbi(PORTB, 4);
    SPI.transfer(data[0] );
    SPI.transfer( data[1] );
    sbi(PORTB, 4);
}

void setup() {
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);
    pinMode(dataPin, OUTPUT);

    SPI.setClockDivider(SPI_CLOCK_DIV2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
    SPI.begin();
}

void loop() {
    _595_out();
}

```

And this worked as I expected. But, when I changed sketch like this,

```
//1.6us+62.5ns
#include <SPI.h>

#define sbi(port, bit) (port) |= (1 << (bit))
#define cbi(port, bit) (port) &= ~(1 << (bit))
#define CHIPNO 2
int latchPin = 12;
int clockPin = 13;
int dataPin = 11;

byte data[]={ 0b10101010,0b11001100 };

void _595_out() {
    cbi(PORTB, 4);
    SPI.transfer(data[0]);
    SPI.transfer(data[1]);
    sbi(PORTB, 4);
}

void setup() {
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);
    pinMode(dataPin, OUTPUT);

    SPI.setClockDivider(SPI_CLOCK_DIV2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
    SPI.begin();
    Serial.begin(9600);
}

void loop() {
    for(unsigned int z = 0; z < 65535; z++) {
        data[0] = z & 255;
        data[1] = (z & 65280) >> 8;
        Serial.println("A");
        Serial.print(data[0]);
        Serial.print("/");
        Serial.println(data[1]);
        Serial.println("B");
        _595_out();
        Serial.println("C");
        delay(500);
    }
}

```

74HC595s aren't working. Any LEDs aren't on.
Printing Serial works well. Only 74HC595s aren't working.
And Removing all Serial-related thing doesn't solved this problem.
Where did I do wrong?

# Answer
```
int latchPin = 12;

```

You use pin 12 as the latch pin. Once you activate SPI the hardware takes over control of the pins MOSI, MISO and SCK. Pin 12 is MISO and thus attempting to change it in your code will have no effect.

You should use some other pin as the latch pin (pin 10 is often used).

---

> And shiftOut using SPI is working when I use first code

`shiftOut` is a software-based method of clocking out bits. It doesn't use hardware and thus it doesn't take control of pin 12.

---

Note: Answered originally on the Arduino Forum
> 0 votes

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


# Question
Title: How to use multiple SPI slaves in MKR1000 if it doesn't have Slave Select (SS/CS) pin?
I'm using a `Genuino MKR1000` and I want to use the `SPI` interface, which I've seen that there is no `Slave Select (SS)/Chip Select(CS)` pin usage.

How can I use the `SPI` interface with multiple slaves then?

# Answer
> 3 votes
The Arduino doesn't care what pin you use for SS since you just use `digitalWrite()` on it anyway. You use any pin you like for one slave, so you can use any other pin you like for another slave.

The ATMega-based boards need pin 10 to be set as an output for SPI to function, but you don't then have to use that for the actual slave select. The only time it becomes a real slave-select pin is when using the Arduino itself as a slave.

# Answer
> 1 votes
If the number of slaves is large, consider using a multiplexed arrangement for select lines. As an example, the 16-pin 74LS138 Decoder/Demultiplexer pulls one of eight lines low depending on the state of its three address lines, while the 24-pin 74LS154 pulls one of sixteen lines low depending on the state of its four address lines. Both of these chips have two or three enable lines, allowing use of two to four of them together to multiply the number of output lines by two to four via use of one or two more address lines.

---
Tags: arduino-uno, spi, mkr1000, genuino
---


title: How to setup OpenCV with Arduino?

text:
# Question
Title: How to setup OpenCV with Arduino?
**My question is how to do it (set it up), not if I can do it or with what Arduino.**

I've previously setup OpenCV with Visual Studio 2015. It was a tough one, but I made it through. Now I want to set it up so that it would work with the Arduino and its IDE.

***How should I proceed? Is there any specific things to do?***

My setup:

* Windows 7
* Arduino IDE 1.8.1
* OpenCV 3.1

# Answer
> 9 votes
If you are thinking of using OpenCV with a "normal" Arduino, such as the Uno or Mega, then think again. OpenCV runs on a computer - be that a desktop computer or an embedded computer. Basically you need an operating system; "normal" Arduinos don't have an operating system.

It may be possible to run OpenCV on an Arduino that runs Linux (some of the strange Intel things that are being marketed as Arduino do, as does the Yún), but in that case you will be writing a Linux application, not working in the Arduino IDE. You would need to treat it as a normal Linux computer and use the normal Linux tools for developing on it (note that OpenWRT that the Yún runs is tricky to develop for - the best way is to cross-compile on a real computer running Linux using the OpenWRT "Buildroot" system).

# Answer
> 1 votes
As some people said before, you just can't run OpenCV on Arduino. but, you can use Arduino/Raspberry Pi to capture information and send it to a server for analysis. For example, Azure, Bluemix or your main computer.

In your case, I would use Raspberry Pi + camera to capture images/videos. then, send it through Wi-Fi to a server. Then, on the server, process all images using OpenCV.

---
Tags: arduino-ide, opencv
---


title: Cheap ATtiny programmer on Debian

text:
# Question
Title: Cheap ATtiny programmer on Debian
I've recently purchased a no-brand 1€ ATtiny programmer off eBay, and with the ridiculous price obviously came no documentation nor support from the seller.

At first I thought that using it with the Arduino IDE would have been as simple as plugging and programming, but no default lib worked. My hopes definitely crumbled when I realized the device wasn't even being picked up by Debian, showing instead this in the logs:

```
kernel.info: [ 2758.501968] usb 6-3: new low-speed USB device number 2 using ohci-pci
kernel.err: [ 2758.641798] usb 6-3: device descriptor read/64, error -62
kernel.err: [ 2758.885515] usb 6-3: device descriptor read/64, error -62
kernel.info: [ 2759.125231] usb 6-3: new low-speed USB device number 3 using ohci-pci
kernel.err: [ 2759.265065] usb 6-3: device descriptor read/64, error -62
kernel.err: [ 2759.508779] usb 6-3: device descriptor read/64, error -62
kernel.info: [ 2759.748500] usb 6-3: new low-speed USB device number 4 using ohci-pci
kernel.err: [ 2760.156027] usb 6-3: device not accepting address 4, error -62
kernel.info: [ 2760.291871] usb 6-3: new low-speed USB device number 5 using ohci-pci
kernel.err: [ 2760.699382] usb 6-3: device not accepting address 5, error -62
kernel.err: [ 2760.699421] usb usb6-port3: unable to enumerate USB device

```

and with `lsusb` outputting this:

```
Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 003: ID 07d1:3c0a WiFi Dongle
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 002: ID 045e:0745 Mouse/Keyboard BT Dongle
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

```

Reading up on the subject seemed to confirm that it was something I shouldn't have bought, and the closest I've got to a better understanding was with this question (link) which I can't comment.

So building up on the answer there, can anyone please explain a bit more in detail what for and where `micronucleus` would be needed?

Alternatively, is it possible to go with something as easy as installing the drivers and plugging it into the Arduino IDE?

# Answer
Micronucleus is a bootloader - in the same way that Optiboot is a bootloader used on the Uno. It provides the USB connection to program the chip.

Without it you can't do anything at all with that, since the USB port just plugs direct into the ATTiny chip. With no software on the chip the USB port doesn't do anything. It's kind of a catch-22 situation - you need software on the chip in order to put software on the chip.

In essence Micronucleus turns the ATTiny into a kind of Mini Leonardo.

You need to first put Micronucleus on the chip (which you can do with an Arduino as an ICSP programmer) and then once that is installed you should be able to start using that little board with the chip to program it.

Since you're on a decent operating system there's no need for "drivers".
> 2 votes

# Answer
It isn't clear to me what you need to do- both for specific chip and your programming needs.

You can easily program an ATTiny with just an arduino and a breadboard. A breakout board and a socket are fun, you could also build or buy a permanent shield for this.

With that breakout board (you could just use a breadboard, too) and an Arduino, you can program your ATTiny from the ArduinoIDE or from avrdude (if for example you have just a .hex file from an Instructable. You will find that the Arduino IDE doesn't support uploading .hex files directly, but since the IDE calls on avrdude for all the actual work- you can invoke avrdude from the command line to upload your .hex file to the chip).

If you mention which ATTiny you need to program, I've missed it.

Overall process is: From the Arduino IDE, add these core libraries from: Tools/ Boards/ Boards manager

github.com/damellis/attiny This will get you:

```
ATtiny 25 (8 pin)
ATtiny 45 (8 pin)
ATtiny 85 (8 pin)
ATtiny 24 (14 pin)
ATtiny 44 (14 pin)
ATtiny 84 (14 pin)

```

Add: github.com/MCUdude/MicroCore (this will need manual install, instructions are provided)

and sourceforge.net/projects/ard-core13/files/latest/download (I forget if this can be added from the IDE or needs manual install).

if you need ATtiny13 support. Each has some advantages the other does not.

You will want to use IDE 1.6.x.

Wire up your breakout board (or breadboard) to your Arduino appropriately for the ATTiny you are using. For example, according to the wiring diagram here for the ATTiny85: highlowtech.org/?p=1695

And from there you should be able to program your ATTiny so that it can run independently from your Arduino.

If you need to upload a .hex file to your ATTiny check the examples here: arduinodiy.wordpress.com/2012/09/11/programming-hex-code-on-an-attiny85-with-the-arduino/

You can do that by using the Arduino as an ISP and then uploading the .hex file to the ATTiny using AVRdude. You'll have to tweak the avrdude command line params a little specific to your situation.

I've just done programming of ATTiny13 using an Arduino Uno, a breadboard, and 6 jumper wires just fine. Both uploading sketches I made in the Arduino IDE as well as using compiled .hex files that were part of an Instructables.com project I was building worked fine.

If you need to upload a program to a board and then use that board to mass-produce many identically programmed ATTiny without using an Arduino, adafruit as a solution, as does shop.myavr.com. I can't justify the expense but they look really neat. Using the Arduino as ISP for this of course works as well.

htlinux has a shield for Arduino's that is really inexpensive and comes with sockets for many Atmel pinouts:

www.htlinux.com/product/attiny-isp-shield/

I ordered one and it isn't here yet, it took a month to get the shipping notice, but it looks like a convenient all-in-one solution. It still needs an Arduino to act as programmer. It would meet your requirement of "removing all wiring" if you are find with a shield.

You could easily build your own shield with a proto board, too. http://www.instructables.com/id/ATtiny-Programming-Shield-for-Arduino-1/?ALLSTEPS

I hope this helps! I spent a while figuring out all this stuff, hopefully having many items in one answers helps the next person looking to program ATTiny with Arduino. I'm working from OS X, it should be even easier from Windows or Linux.
> 2 votes

# Answer
Judging by the picture it's **just a board**.

If it is anything like this link on eBay (the first hit for "attiny programmer board") then this is the description:

> Development board supporting chip:ATtiny13A / ATtiny25 / ATtiny45 / ATtiny85 etc

It *supports* the named chips, it doesn't have them on it.

I presume you are supposed to do a few things with it:

* Purchase an ATtiny85 (or similar) chip
* Install it on the board
* Solder in an ICSP header onto the 8 pins on the right
* Program the Micronucleus bootloader using a suitable other piece of hardware (like a ICSP programmer)
* **Then** use the board as a ATtiny development board.

It's not responding because there is no chip there (unless you can see one on the other side). That's why it's cheap. You are buying a board, not a microcontroller on a board.

This other link on eBay for a slightly different board (for the same price) shows that the other side does not have a processor on it.
> 1 votes

---
Tags: arduino-ide, usb, attiny, programmer
---


# Question
Title: How do I stop 5v on the I2C port of a pro mini so I can use 3.3v devices?
The theory is that you can use 3.3v I2C devices from a 5v device as long as the pull ups are only to the 3.3v. I have a 5v pro mini connected to a bmp180 board which has a 3.3v regulator but no level shifters. It is working and giving me data but I am hoping I can get better quality measurements. One observation is the power rail on the BMP board after the 3.3v regulator is being pulled towards 5v. On the scope this looks to happen between i2c messages. I am using the "Adafruit-BMP085-Library" which is in turn using "Wire". In the wire library there is a comment that says that the writedigital() of 1 to the port is setting the pull ups.

Does anyone have any general advice on this issue?

What does the comment about setting the pull-ups mean? How is that function setting the pull ups?

When does the I2C switch back to being an GPIO? Are the lines being pulled high between messages because it is reverting to an GPIO?

# Answer
Whoever decided it would be a good idea to default to using the Arduino internal pull-up resistors on I2C needs taking out back and giving a good kicking. It is so wrong on so many levels.

Yes, if you disable the internal pull-up resistors you can safely use 3.3v devices. The simplest way to do this is to turn them off again as soon as you have done `Wire.begin();` by writing 0 to the pins with `digitalWrite()`.
> 2 votes

---
Tags: i2c, arduino-pro-mini, adafruit, pull-up
---


# Question
Title: LED doesn't register as LOW after a switch has cut all power to it
I have the following build:

And the following code:

```
const int buttonPin = 3;
const int ledPin = 2;
int buttonState = 0;

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

  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

}

void loop() {
  while (digitalRead(ledPin) != LOW){
    buttonState = digitalRead(buttonPin);

    if (buttonState == LOW){
      digitalWrite(ledPin, LOW);
    }
  }
}

```

But it doesn't seem like anything is registered, as my program doesn't respond to the shut down of the LED. What have I done wrong?

# Answer
> 0 votes
Looking at your schematic, I get a bit confused. You should start out with creating the schematic, try to base it on existing schematics on the web/tutorials.

I believe you're trying to read out a button and set an led accordingly?

So start out with the schematic and then try to build a breadboard setup for this. Randomly wiring things up on your breadboard doesn't really make sense, you need a plan.

I've created a shematic of which I believe should work a treat.

simulate this circuit – Schematic created using CircuitLab

*Using internal pull-ups on the SW1, to avoid the input floating. Using 220ohms resistor, based on "Basic Red 5mm - Sparkfun LED", 5V source, 2V forward 16mA (http://led.linear1.org/1led.wiz). Be carefull not to set the SW1 as an output (high) and push the button, this theoretically burns out the I/O pin. But even then, this is only basic, you may want to consider input protection (http://www.thebox.myzen.co.uk/Tutorial/Protection.html)*

It's very easy to mess something up or do something incorrectly in electrical engineering. To be honest, it may help to watch a lot of tutorials or read books on electronics. It's very usefull to have a basic understanding before wiring things up.

At least base your actions on a (good) tutorial or reference material from Arduino self.

Try to wire up the circuit according to my schematics

Mouseover for example (but please try it yourself before checking!)

>

The same actually counts for programming, first try to make it clear what you want to achieve. Maybe even write out the steps that your program should do on a functional level.

I have no idea how you program could actually compile, the while and if statements don't have any closing brackets.

```
const int buttonPin = 2;//I switched the LED and button in my design.
const int ledPin = 3;//So the LED is on a PWM pin, which makes more sense.

void setup() {
  //Serial.begin(9600); //We're not using serial, so why start serial?
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
}

void loop() {
   int value = digitalRead(buttonPin);
   digitalWrite(ledPin, value);
   //or digitalWrite(ledPin,digitalRead(buttonPin));//for short
}

```

# Answer
> 0 votes
The diagram is open to several different interpretations, depending on what's inside the four-terminal switch. On many such SPST switches, two adjacent terminals are connected to each other inside it, and the other two likewise. Which are which in the diagram isn't indicated.

That aside, what is clear from the diagram is that pin 2 is connected by wires to +5V, and will always read in as high.

---

*Edit 1:* The schematic \[posted later\] is unclear. It should be arranged so that solid lines represent wires or pins, with solid lines between things that are connected. Place items in the drawing to reduce unnecessary and confusing crossing lines. For example, supposing that the dashed line from pin 2 of R1 represents a wire between pin 2 of R1 and pin 2 of LED1, it is unclear whether the wire bends around the top right pin of S1 (can't read number) or connects with that pin on its way to LED1. For another example, nothing is shown connecting to pin 1 of R1, and only one long dashed line connects the R1/S1/LED1 group to the Uno.

---
Tags: arduino-uno
---


# Question
Title: Is it better to use Vraw or Vcc on Mini Pro?
I have 12V and 5V power available. Is it better to feed the 5V through the Vcc pin or either the 12V or 5V through the Vraw pin?

# Answer
> 2 votes
Use the 5V connected to the Vcc pin.

If you use the Vraw pin, the voltage goes through a voltage regulator. This voltage regulator will convert the higher voltage down to 5V by converting the extra volts to heat. So in case of using 12V you'd be throwing away around 60% of the power. Which is both wasteful, and will heat up the regulator quite a bit (depending on the load).

---
Tags: voltage-level, arduino-pro-mini
---


# Question
Title: Electronically, should single or several ground pins be used?
I have heard two theories of grounding: pretty much ground a board at single point, or ground everything in sight.

With the Mini Pro, is it better to provide one source of ground through the Gnd pin next to the Vraw pin, or ground with multiple Gnd pins on the board?

# Answer
There are times when you want a single ground point (*star* grounding), separate grounds with filters (separate analog and digital grounds, for instance), or you just don't care (99% of the time).

Regardless, this is usually a concern when you are laying out a circuit on a PCB. When you already have a PCB the grounds become a moot point because the PCB dictates how they operate.

For a module like an Arduino, unless otherwise stated, all grounds are equal and can be used for whatever whenever.
> 2 votes

---
Tags: arduino-pro-mini
---


title: Set pins to LOW over time

text:
# Question
Title: Set pins to LOW over time
I've written a simple sketch that adds threshold to an PIR sensor. If the PIR sensor sends 3 `HIGH` ex. `HIGH`...`LOW`...`HIGH`...`LOW`...`HIGH` (The `LOW` == no movement) it will trigger and alarm.

I want to reset the counter of `HIGH`s if there's no movement detected. The problem is the `loop` will get delayed if I put it inline. My code: (Don't mind my code, I'm pretty newbie)

```
int calibrationTime = 30;
int pirPin = 5;
int ledPin = 6;
int sensorState;
int stateCount = 0; //How much movement is detected
int stateThreshold = 3; //THRESHOLD
bool isSensorHigh;

void setup() {
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  digitalWrite(pirPin, LOW);
  Serial.print("calibrating sensor ");
  for (calibrationTime; calibrationTime > 0; calibrationTime--) {
    Serial.print(calibrationTime);
    delay(1000);
  }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
}
void loop() {
  sensorState = digitalRead(pirPin);
  //Serial.println(sensorState);
  if (sensorState == 1) {
    isSensorHigh = true;
  }
  if (sensorState == 0 && isSensorHigh == true) {
    isSensorHigh = false;
    stateCount++;
  }
  //Set pins 2,3,4 here to LOW if there's no movement detected over time
  if (stateThreshold == 3) {
    switch (stateCount) {
      case 1:
        digitalWrite(2, HIGH);
        break;
      case 2:
        digitalWrite(3, HIGH);
        break;
      case 3:
        digitalWrite(4, HIGH);
        break;
    }
  }
  if (stateCount == stateThreshold) {
    blinkLeds();
    delay(3000);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    digitalWrite(ledPin, LOW);
    stateCount = 0;
  }
  Serial.println(stateCount);
  delay(150);
}

void blinkLeds() {
  for (int x = 4; x > 0; x--) {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    delay(1000);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    delay(1000);
  }
}

```

# Answer
> 1 votes
Use millis() instead on delay. Ref: https://www.arduino.cc/en/reference/millis

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


title: SIM900 random shutdowns

text:
# Question
Title: SIM900 random shutdowns
I have a SIM900 GPRS/GSM Shield and an Arduino Mega. Now for the past week I have been using USB as power to send and receive GPRS data with no issue. Today the SIM900 module is continually randomly turning off, not even turning of at specific stages of communication.

I thought this could be power related, so have external power (5V 5A UBEC) into the 5V pin of the Mega, which I believe should cover the voltage and current requirements of the SIM900 shield. However this has not solved the problem.

Any ideas on what could be causing the random shutdowns?

EDIT: Is it safe for me to wire power up like this:

# Answer
> 1 votes
Cool, an UBEC is indeed a smart choice for powering a SIM900. I could get away with a small switching power supply and just putting in a big capacitor (since the sim900 only draws high current in very short peaks).

But, the limiting factor in this case would be the 6AA batteries. Your UBEC may be able to supply 5A's but those AA's may not.

Also, look up "transient response" (related) according to the related article, you can have an 20A power supply, but still have the voltage drop out when the sim900 starts to transmit. This is because your supply needs to be able to deliver the required 2A in a very short period of time, so basically if your supply can't go from 100ma to 2A fast enough, it'll dip.

I suggest finding a more optimal source as AA's and adding a "big ass capacitor" close to the sim900's input.

# Answer
> 0 votes
Pumping 5Amps into the Mega isn't going to make a difference to the current the SIM900 is receiving (needs \>2A) it will still get 500mA (?).

You need to feed the power directly into the SIM900 from the PSU, because when it transmits it needs a nuclear reactor to power it. Don't forget the common ground.

---
Tags: arduino-mega, power, communication
---


title: How to detect pinout at run-time

text:
# Question
Title: How to detect pinout at run-time
Is it possible to query the **pin-out** and each pin's attributes at *run-time* with Arduino?

If not, can it be done at compile-time?

Finally, if not, how can I incorporate this kind of information into my project to avoid completely rewriting my program for each possible Arduino model?

I am looking for something like this:

```
PinProperties props= getPinProperties(pinNumber);

props.supportsDigitalInput();
props.supportsDigitalOutput();
props.supportsAnalogInput();
props.supportsAnalogOutput();
props.supportsPWM();
props.analogInputBits();
props.analogOutputBits();
props.pullupResistance();
props.pulldownResistance();

```

etc.

NOTE: This question is similar and I might use the board model to look up a pre-stored pin-out.

# Answer
pins\_arduino.h has some standard macros that can be used for some of what you're looking to do. Using the `arduino:standard` variant used by Uno for example:

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins\_arduino.h#L35:

```
#define digitalPinHasPWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11)

```

Or if you want to use your naming scheme:

```
#define supportsPWM(p) digitalPinHasPWM(p)

```

After that it gets a bit more sketchy:

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins\_arduino.h#L28

```
#define NUM_DIGITAL_PINS 20

```

So, assuming that Arduino digital pins will always be numbered consecutively from 0 and any pin that supports digital input also supports digital output(which is the case in any variant I'm familiar with), you could use that to write some macros:

```
#define supportsDigitalInput(p) ((p) < NUM_DIGITAL_PINS)
#define supportsDigitalOutput(p) supportsDigitalInput(p)

```

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins\_arduino.h#L29

```
#define NUM_ANALOG_INPUTS 6

```

Could be used to write this macro(with numbering assumption):

```
#define supportsAnalogInput(p) ((p) < NUM_ANALOG_INPUTS)

```

Note that this will not work for the `An` analog pin names(e.g. `A0` vs `0`).

As for:

```
props.supportsAnalogOutput();
props.analogInputBits();
props.analogOutputBits();
props.pullupResistance();
props.pulldownResistance();

```

I'm don't know of pre-existing code for those. There is probably a way to get it for the first three in an architecture specific manner. The last two you'd most likely need to get the information from datasheets for all of your target microcontrollers and define then using processor specific macros.
> 1 votes

# Answer
There is no strong relation with pin numbering and the hardware as far as I know.

To be more specific, the datasheet tells you what registers can be used for what functions. The microcontroller does not neccesarily know what registers it has or what functionality it's registers have.

You could make your own library or class for a pin.

I would go by something like:

```
Pin input1 = new Pin(.....);

if(input1.isAnalog()){
   input1.setupAnalog();
}

if(input1.analogIsReady()){
   input1.readAnalog();
}

```

Instead of having a "pinproperties" object for a pin.

You'll have to look how you want to make the class. You can create one single class that has all functions and just checks if there is an implementation for that pin.

You may go by classes like:

```
class pin

class analogPin extends pin

class pwmPin extends pin

```

However, this may fail if your analog pin doesn't support the regular "pin" functions (like I/O).

Theoretically you could use C++'s multiple inheritance to inherit things as I/O, PWM and Analog, but I've heard that it doesn't perform very well on embedded targets.

---

Alternatively you could make a list of pins that support PWM. And a list of pins that support Analog. And a list of pins that support I/O.

When a person (runtime) tries to set a pin's state, you can check if that pin supports I/O, but I'm not sure what behaviour you'll expect if one tries to set a pin that doesn't support that option.
> 0 votes

# Answer
> Finally, if not, how can I incorporate this kind of information into my project to avoid completely rewriting my program for each possible Arduino model?

The libraries are designed so that you don't really need to know that. One issue is the relationship between the chip pins and the board pins. Just as an example, pin 19 on the Atmega328P goes to the *board* pin 13 (digital pin 13) on a Uno.

If your program needs a couple of digital inputs and a couple of digital outputs, you could use (say) D2 and D3 as inputs and D4 and D5 as outputs. Then let the underlying libraries work out which chip pin that is, and configure it correctly when you use `digitalRead`, `digitalWrite` and `pinMode`.

You can self-query for the chip type (for example here) however that doesn't tell you what board the chip is mounted on.

---

> to avoid completely rewriting my program for each possible Arduino model

What are you envisaging that would require a *complete rewrite*? Many libraries and projects are written to work on multiple boards with only minor changes (if any). You can detect the processor type at compile-time.

I simply don't see where "complete rewrite" comes into it. Use functions to abstract out the parts that interface with pins (as `digitalRead`, `digitalWrite` and `pinMode` **already do**) and a few constants at the start of the code to indicate which pins you have chosen for this particular board.
> 0 votes

---
Tags: pins, hardware
---


# Question
Title: How safe is it to use my body as part of a circuit?
I have two polystyrene balls wrapped in copper tape. When the balls touch, the tape completes a circuit from a digital pin on an Arduino inside one of the balls to an Arduino inside the other (both powered by 9v batteries). This allows them to send information to each other via the copper tape path.

I was testing the balls out, and they were working too well. Even when the balls weren't quite touching, the signal was getting through! Turns out that's because the signals were travelling via my body. Even if I held one ball in one hand and the other ball in the other hand, digital reads on one Arduino were correctly reading the digital writes from the other.

This is actually great for my project!... unless it's not safe. So I'm looking for two things:

1. A reliable reference on what is and isn't safe in terms of voltage/wattage/amperage travelling from hand to hand.
2. A second opinion on the voltage/wattage/amperage that two Arduinos will actually pump through me (from digital pin to digital pin).

# Answer
> 6 votes
If you are talking about running at 5V, then I doubt there is any safety issue. After all, 9V batteries (the sort you put in your smoke detector) just have bare terminals and no-one tells you not to touch them.

There is quite a bit of related information at How much voltage is “dangerous”?. That link seems to have enough information that there isn't a lot of point of repeating it all here.

There is a reference on that page to someone holding a metal pole connected to a 12V battery wading through water which completed the circuit and he was unable to let go of the pole. But that is **12V** (more than twice 5V) and in circumstances where there was good conduction (his body was wet).

---

In the interests of science I set up a small test. I connected myself to a 5V lab supply via an ammeter. I grasped the terminals firmly (with dry hands) and measured about 3 µA of current. From the page I referenced above there seems to be a consensus that 1 mA would be just noticeable, so this is about 300 times less.

I found if I wet my fingers I got up to about 20 µA of current, still a lot less than 1 mA.

That page mentions that 60V is getting into the range where you might get a shock.

---

Hopefully it goes without saying that if you are going to touch metal balls then you need to be certain that 5V is the maximum, and that some sort of failure in a power supply might not deliver a lot more. But if the balls are battery powered you should be pretty safe.

---

You've added that they are powered by 9V batteries. That doesn't change my answer much. The most that could "escape" due to some malfunction is then 9V. Under normal operation you would have 5V from a digital output pin.

I measured my body resistance as being around 1.5 MΩ, which is consistent with getting 3 µA of current through it.

```
I = V / R
I = 5 / 1500000 = 0.000003 A

```

# Answer
> 1 votes
In fact the voltage is almost irrelevant. The current is the issue. 30mA is normally considered the limit - this is the value RCD are set to trigger at.

Even low voltages applied to intimate places can be fatal. (I have a couple of wires in my heart, these can certainly cause a significant impact).

There is little risk with the low energy available, but if you want to be safe you can use a series resistor. I have (a very early) touch sensor installed on lights in my house. The touch pad is effectively connected to 240V, but is quite safe as the pad is connected through 2 10MΩ resistors. (2 are needed as they are rated at 500V.)

---
Tags: safety, electricity
---


# Question
Title: Serial Communication Issue with Telit LE910 LTE Modem
I have a project that uses a Telit LE910 4G LTE Modem to allow me some basic monitoring via SMS and HTTP POST to Exosite.

I can connect to a Exosite server with and send a successful HTTP GET request to pull a UNIX timestamp (as a test).

**Problem**

The problem lies with receiving. The information received cuts off halfway through the HTTP headers, before reaching the body of the information.

This image shows what prints out on the Serial monitor:

This image shows what the expected result should be:

And this image shows the code the executes to send the request:

The result is the same with PrintModemResponse() and with GetModemResponse(). Additionally, I have the same issue with receiving SMS messages. The data appears to cut off partway through the expected response. The modem serial (SW\_Serial) baud rate is set to 115200.

**Question**

Am I doing something wrong with reading the Serial information from the modem? Am I hitting a timeout of some sort?

# Answer
First, please don't post screen images. Just select the text and paste it into your questions. You can copy code from the editor or messages from the Serial Monitor window. Paste into your post, select the section again, and press ctrl-K to format it as a code block in your question (like below).

> Am I doing something wrong with reading the Serial information from the modem?

Yes, you are using delay to "wait" for the response to appear.

> Am I hitting a timeout of some sort?

In a way. The input buffer only has room for 64 characters. If you don't read any of them because you're blocked at a `delay` statement, the 65th character (and all others) will be ignored. **These answer your specific questions.**

---

### Further Suggestions:

To fix the real problem, not just the symptoms, you will have to change your sketch structure.

There are many ways to implement this in a non-blocking way (i.e., without using `delay`). I prefer Finite-state Machines; there are many good tutorials for this technique (e.g., Nick Gammon's site).

Although it's not as flexible, you could also use your own `while` loop for each response, with a timeout. Here's a simple example that reads one line.

```
char resp[20];
char resp_Len = 0;
const uint32_t TIMEOUT_MS = 5000UL; // 5 seconds

AltSoftSerial modem_port; // pins 8 & 9 ONLY

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

void loop()
{
  uint32_t startTime = millis();
  while (millis() - startTime < TIMEOUT_MS) {
    if (modem_port.available()) {
      char c = modem_port.read();
      if (c == '\n') {
        resp[ respLen ] = '\0'; // NUL terminate
        respLen = 0; // reset for another line
        break;

      } else if (respLen < sizeof(resp)-1) { // Room for more?
        resp[ respLen++ ] = c; // accumulate one more character
      }
    }
  }

  Serial.print( F("Response = '") ); // F macro saves RAM
  Serial.print( resp );
  Serial.println( '\'' );
}

```

But when the response is long (hundreds of bytes), you may not have sufficient RAM to save the whole response, and then parse it. You MUST use an FSM to parse the bytes *as they are received*.

For your application, you should skip all the stuff at the front and watch for the "Content-type:" pattern and the two newlines, then save the next line (as above) for parsing:

```
enum state_t { SKIP_TO_CONTENT_TYPE, SKIP_TO_EMPTY_LINE, SAVING_TIMESTAMP };
state_t state = SKIPPING
uint8_t index = 0;

const char ContentType[] = "Content_type:";

bool watchForTimestamp()
{
  if (modem_port.available()) {
    char c = modem_port.read();

    // Handle this one character, based on our current "state"

    switch (state) {
      case SKIP_TO_CONTENT_TYPE:
        if (c == '\n')
          index = 0;

        else if ((index < sizeof(ContentType) && (c == ContentType[ index ])) {
          // next char matches
          index++;

          if (index == sizeof(ContentType)) {
            // All matched!
            state = SKIP_TO_EMPTY_LINE;
            index = 0;
          }
        }
        break;

      case SKIP_TO_EMPTY_LINE:
        if (c == '\n') {
          index++; // this counts newlines since "Content-type:"

          if (index == 2) {
            state = SAVING_TIMESTAMP;
            index = 0;
          }
        }
        break;

      case SAVING_TIMESTAMP:
            ... Hint: something like the line-saving technique above.
        if (something) {
          return true;
        }
        break;
    }
  }

  return false;
}

```

Some part of `loop` will just call `waitForTimestamp` over and over:

```
void loop()
{
    ...

  bool gotResponse = false;
  state = SKIP_TO_CONTENT_TYPE;

  while (millis() - startTime < TIMESTAMP_TIMEOUT) {
    gotResponse = waitForTimeStamp();
    if (gotResponse) {
      // parse the timestamp from the resp array
         ...
      break;
    }
  }

  if (gotResponse) {
    Serial.print( F("Timestamp = ") );
    Serial.print( resp );
    // now you can parse the small response array
       ...

  } else {
    Serial.println( F("Didn't receive timestamp!") );
     ... other error code
  }
}

```

This may be a "main" FSM for loop, with a nested FSM for parsing the HTTP response. The rest is up to you. :)

BTW, SoftwareSerial is **very** inefficient. It cannot send and receive at the same time, and it disables interrupts for long periods of time.

If you can use pins 8 & 9, you should use AltSoftSerial instead. It is very efficient.

If you can't switch to those pins, you could use NeoSWSerial if the modem is running at 9600, 19200 or 38400.
> 1 votes

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


# Question
Title: String use in arduino IDE (this question for understanding)
I'm using arduino several month now, And i don't understand when i can use the arduino object of String. I'll explain, I read a lot and the it's look like that this object is a good way to read/write and use strings, But everywhere they say that this object take a lot of RAM. So i made some project, And almost in all of them the String object not work as i expected. When i check the RAM in my projects i see that when my usage of RAM is greater then 65% the string object start to do problems. Because of this i stop use the string object and use only char arrays.

So my question is:

* How can i know when i can use String from the beginning?
* there is a way to change from char array to string or vase versa easily (i know this is completely different logic)?
* How can i avoid the memory problems with the String object?

All this questions come from that the String object is very effective and easy to use and i want to use it, But i'm fear from RAM problems so i'm not using it.

Thank you very much for reading all this, Hope you can help me!

# Answer
> 1 votes
String objects are simple to use. There is a trade-off for simplicity. Strings work by using dynamic memory allocation. Something like this for example:

```
String foo;
...
foo += 'a';

```

By adding one character to a string the class has to allocate new memory for the slightly longer string. If you keep doing this you get memory fragmentation.

You are probably better off deciding what your maximum size string is and making that a static array of characters.

---

### So should I use the String objects?

For occasional use they are fine (for example, holding the name of something). They tend to fall down once you start with a small String and keep adding to it, because the code has to dynamically allocate memory, allocating (say) 5 bytes, then 6 bytes, then 7 bytes, and in the process freeing up the original 5 bytes, then 6 bytes and so on. This allocating/freeing process can leave holes in the "heap" causing a thing known as memory fragmentation.

Done to excess you can run out of memory. That is, you might need 100 bytes but have 10 lots of 10 bytes free, with stuff in-between that isn't free.

You don't have lots of memory to start with, so it is probably better, faster and more efficient to decide the largest amount you need for some string, and just make that a character array.

---
Tags: arduino-uno, arduino-ide, string
---


# Question
Title: Graphical programing language for Arduino
I am looking for a graphical programming language for a project of mine, where I am using an Arduino.

It HAS to meet the following conditions:

* It supports uploaing sketches to ATmega328 (Arduino Uno/Nano)
* New functions can be defined inside the programming enviroment (I am trying to use a motor connected to an H-bridge with a single command block)
* The program can run on Windows 7
* Libraries can be used inside the code
* C++ can also be used to write the code inside the same program
* Sketches can be uploaded via Bluetooth 4.0

It would be nice if it met the following condition:

* The programming enviroment is easy to use
* The graphical programming language is somewhat similar to Scratch
* The program can be understood by 10-14 year olds with no programming experience

# Answer
The most full featured Scratch-like environment for Arduino, to my knowledge that is close to your listed criteria is http://www.mblock.cc/

It's currently in beta development for enabling bluetooth uploads and supports a range of "extension" plugins. I believe you can also add functionality by writing your own extensions if you have sufficient programming knowledge.

The software has more features if you use their mblock hardware, while offering a reduced set of commands for other boards such as the Uno.

I'm sure you can add library's to your code but at the expense of the scratch-like interface. A children's visual design tool being able to provide graphical API to libraries written by an open source community is quite a coding challenge. You can get a feel for this by trying to use any reverse engineering C++ to UML diagram tools.

I recommend perhaps using one of these scratch tools to build simple firmware as a learning tool with the idea of progressing to an actual programming language soon after.

In any case I hope you find what you're looking for among these options for your project.
> 2 votes

# Answer
Give Visuino a look, they are making noise lately: https://www.visuino.com/
> 0 votes

---
Tags: programming, arduino-nano
---


title: Huge nested loop in Arduino

text:
# Question
Title: Huge nested loop in Arduino
I am completely new to programming and I am trying a brute force programming on my garage door opener. I want to use an Arduino for learning purposes. I wrote the following program that finally did what it should and now I am wondering whether there is a shorter code that does the same. Is anyone able to help me in that matter?

I do know that about 2^12 possibilities existed so I ran through all of them. I also knew that some parts of the "pulsetrain" (the set of necessary pulses) start with a particular sequence that is always the same (for all "brute forced" trains) and that the closing sequence is also always identical. I then simply wrote that down in the following, nasty code:

```
/*
  Transmitter is connected to Arduino Pin #2
*/

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

void pulsetrain(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m) {
  PORTD &= ~_BV(PD2);
  //set to LOW, hardwired to make it faster, see http://www.instructables.com/id/Arduino-is-Slow-and-how-to-fix-it/?ALLSTEPS
  delayMicroseconds(283); // (D2)
  PORTD |= _BV(PD2); //set to HIGH
  delayMicroseconds(566);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(283);
  PORTD |= _BV(PD2);
  delayMicroseconds(566);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(a);
  PORTD |= _BV(PD2);
  delayMicroseconds(b);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(c);
  PORTD |= _BV(PD2);
  delayMicroseconds(d);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(e);
  PORTD |= _BV(PD2);
  delayMicroseconds(f);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(g);
  PORTD |= _BV(PD2);
  delayMicroseconds(h);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(i);
  PORTD |= _BV(PD2);
  delayMicroseconds(j);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(k);
  PORTD |= _BV(PD2);
  delayMicroseconds(l);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(m);
  PORTD |= _BV(PD2);
  delayMicroseconds(283);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(566);
  PORTD |= _BV(PD2);
  delayMicroseconds(283);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(566);
  PORTD &= ~_BV(PD2); // last LOW
}

void loop() {
  int signals[2] = {283, 566};
  for (int a = 0; a < 2;  a++) {
    for (int b = 0; b < 2;  b++) {
      for (int c = 0; c < 2;  c++) {
        for (int d = 0; d < 2;  d++) {
          for (int e = 0; e < 2;  e++) {
            for (int f = 0; f < 2;  f++) {
              for (int g = 0; g < 2;  g++) {
                for (int h = 0; h < 2;  h++) {
                  for (int i = 0; i < 2;  i++) {
                    for (int j = 0; j < 2;  j++) {
                      for (int k = 0; k < 2;  k++) {
                        for (int l = 0; l < 2;  l++) {
                          for (int m = 0; m < 2;  m++) {
                            pulsetrain(signals[a], signals[b], signals[c], signals[d], signals[e], signals[f], signals[g], signals[h], signals[i], signals[j], signals[k], signals[l], signals[m]);
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

```

# Answer
All those variables `a`, `b`, etc. are just the individual bits of a 13-bit number. When you loop through all combinations, you are actually looping through all the possible *numeric values* of a 13-bit number. This can be simplified as this (warning: not tested):

```
void setup() {
    pinMode(2, OUTPUT);
}

// the bitstream is: 0.101x xxxx.xxxx xxxx.0101
void pulsetrain(uint16_t code) {
    uint32_t bitstream = (((uint32_t) code) << 4) | 0x0a0005UL;
    for (uint8_t i = 0; i < 21; i++) {
        PIND = _BV(PD2);    // toggle pin
        if (bitstream & 0x100000)
            delayMicroseconds(566);
        else
            delayMicroseconds(283);
        bitstream <<= 1;
    }
    PORTD &= ~_BV(PD2); // last LOW
}

void loop() {
    for (uint16_t code = 0; code < 0x2000; code++) {
        pulsetrain(code);
    }
}

```
> 1 votes

---
Tags: programming
---