title: Using Arduino for Industrial process

text:
# Question
Title: Using Arduino for Industrial process
I was wondering if the Arduino is applicable for Industrial monitoring, I want to make a real time status of the presses in our company. I haven't seen or read much about people using Arduino at an Industrial level, most of what I have seen or read are prototype projects. I'm new in electronics and don't know if there is a better way of doing this rather than using Arduino. I was thinking of using Arduino Uno and Arduino Ethernet Shield or Wifi Shield.

Any help on some information on how to start on this is helpful.

# Answer
I wouldn't use the Arduino in an industrial environment, as I wouldn't trust its PCB to be able to handle much noise. Use the Arduino and shields to prototype your application, and then move to a circuit board that uses proper techniques suited to an industrial environment.
> 7 votes

# Answer
I don't see any reason *not* to use Arduino in an industrial, engineering, or laboratory environment, if it meets your needs and does the job well. It is highly recommended, however, that you provide *some* sort of pin protection to keep industrial noise or voltage spikes from frying pins. Minimum pin protection could consist of using current-limiting resistors (or better yet, the other, more robust techniques shown here) on pins used for output and input signals. Optical isolation is also a good option, especially if potentially dangerous voltages are being used. Lastly, after you prototype and test your Arduino setup you should solder the wires to the Arduino and provide a protective case. You don't want to accidentally fry the Arduino or a pin via accidental static discharge (hence the case, and pin protection above), and you don't want jumper wires vibrating loose and connections slowly oxidizing over time and loosing electrical connectivity in any type of industrial or laboratory application that is expected to be used regularly (hence replacing your jumper wires with soldered wires). Shields, however, are prob. ok for low-humidity and room-temperature environments, as they are generally much more secure and solidly connected than individual jumper wires.

Note that you can solder wires to *any* Arduino, even the Uno, Leonardo, or Mega, for example, simply by soldering to the exposed portions of the pins on the bottom of the board. You can also cut off and desolder the female headers and either solder directly to the holes, or solder on male headers that you then solder to other PCBs. I especially like the Arduino Nano, Pro Mini, and Micro since they are small, have exposed holes or male pin headers, and can easily be soldered onto a professionally-manufactured circuit board or cheap protoboard, for better mounting in a final application. Keep reading below for more details on this.

I am an aerospace research engineer and use Arduino in my line of work regularly to solve problems. Here are some examples of current applications in use today, that I implemented, that are based on and using Arduino boards:

1. **sensorless brushless motor RPM sensor, motor commander, and data acquisition device** for bench-top testing
2. **linear actuator closed-loop controller** (linear stepping resolution is 0.01mm \[10um\], full moving range is 0 to 15mm); the Arduino commands the actuator driver board via a custom PWM signal using the Timer1 library (http://playground.arduino.cc/code/timer1); position is read via a custom quadrature encoder reader algorithm on the arduino; the actuator is used for very precise aiming of certain instruments; the $30 Arduino is taking the place of a $500 board that the actuator manufacturer makes, and the Arduino gives us much more functionality than the $500 board would give us. The Arduino and actuator will be used to precisely aim a laser for experiments in a wind tunnel.
3. **flight controller interfaces** between MATLAB and off-the-shelf Radio Control transmitter (read and write RC PWM & PPM communication signals)
4. **Professional film studio communication interface on robotic, drivable camera system** (info sheet & video).

Those are just a few cases. If it works, do it. Once you prototype with a solderless breadboard, however, it is recommended that you at least hand-solder the final configuration to a permanent prototyping board, to make it more durable and noise-resistant (ie--primarily: so that it will have solid connections that can't corrode, break, come apart, or vibrate free easily).

Here's a soldering article I wrote (http://electricrcaircraftguy.blogspot.com/2014/08/recommended-soldering-kit.html#.VP-JCPzF-So). see the links at the bottom for recommended soldering tutorials. The one about how to make "solder tracks" was especially useful to me once I got past the breadboard stage and started prototyping things on double-sided perf board.

Here are some double-sided prototyping boards (or "perf boards") to look into once you get to this stage: (Ebay search for "double sided pcb") http://www.ebay.com/sch/i.html?\_from=R40&ghostText=&\_sacat=0&\_nkw=double+sided+pcb&rt=nc&LH\_BIN=1 -- get the ones with all the little holes in them. You can put the whole thing in a plastic case if you want too. You can permanently solder an Arduino (esp. the Nanos or Micros more easily) to one of these perf boards.

Here's another example of double-sized perf board. (image source: http://www.elecfreaks.com/store/doublesided-protoboard-8cm-x-12cm-p-410.html)

**Professional PCBs:**

If you need to make more than a few of some device, hand-soldering wires and pieces all over a perfboard can get to be VERY tedious. In this case, you need to design a more professional PCB with custom traces and pads and layout and all for your project. If you don't have PCB-designing skills yet with a professional tool like Eagle or KiCad, you can use Fritzing (http://fritzing.org/home/) to design a PCB, and then send it off to a company like OshPark (https://oshpark.com/) for high-quality, reasonably-priced, low-quantity US-based manufacturing---or send it off to the Fritzing Fab lab in Germany for high-quality PCB manufacturing that supports the Fritzing project. Lastly, for a couple really inexpensive Chinese options, look at ITEAD Studio and Seeedstudio. Fritzing and any other PCB CAD software tool can output the necessary Gerber files for manufacturing.

*Quick tip*: when designing a PCB, don't use *any* 90 deg corners for your traces. They can act as antennas (sending *or* receiving) and cause electromagnetic (including radio) interference and noise. Use multiple 45 deg edges and corners instead.

Once you get your boards back, solder your Arduino to them, and solder any extra parts or hardware to them you need as well. Now you have quite a professional product, even if it has an Arduino soldered right to it.

**Summary:**

**In summary, yes I think Arduino is great. Without it, I wouldn't know how to even blink an LED or load a single code to a microcontroller, because getting into using microcontrollers was just to enigmatic, difficult, and complicated for someone not professionally trained in it, such as an Aeronautical engineer like myself. With Arduino, however, I learned to build up my skills and solve real-world problems in professional environments.**

**I am very grateful to Massimo Banzi, David A. Mellis, and others who have made Arduino possible. It has changed my life and my ability to *be* useful in this life. My favorite part about it is that even though it is a tool meant to get the non-programmer or lay-person to do basic stuff like blink a light using poorly-written blocking code, it has opened up my world beyond what I ever imagined before, and it is a fully-capable microcontroller that doesn't permanently hide away the low-level stuff. The low-level AVR functions, registers, etc are ALL STILL THERE AND ACCESSIBLE once you get to a level where you need them!**

Cheers,
Gabriel Staples

PS: To see many of the very helpful links which I've referenced as I've built up my Arduino and ATmega328 microcontroller skillset, please see this article here, esp. all of the links at the bottom: http://electricrcaircraftguy.blogspot.com/2014/01/the-power-of-arduino.html
> 12 votes

# Answer
Industruino just came out a couple days ago:

1. https://blog.arduino.cc/2015/09/21/industruino-makes-industrial-automation-easy-now-atheart/
2. https://industruino.com/page/home
3. https://www.youtube.com/watch?t=200&v=MhE1zlwsUu0
4. https://industruino.com/shop/product/industruino-ind-i-o-kit-2

Also:
1. Ruggeduino has much better pin protection than a standard Arduino.

One of the above may meet your need.

(No, I am not affiliated in any way with the above links; I just saw the Industruino the other day on the Arduino website and wanted to point out a couple other options).
> 5 votes

---
Tags: arduino-uno, wifi
---


# Question
Title: Light multiple RGB Led Strips from same 3 RGB PWM outputs
I need to control about 6 RGB Led Strips from an Arduino Board. The problem is that i need 3 PWM outputs for each led strip, but each will have probably the same colors. I was wondering if i could put two strips receiving a signal from the same PWM output, then i would have to use half the PWM outputs but send the same signal for each pair of strips.

The scheme i found is this one:

And what i want is something like this:

Is this possible? What should i modify to make it work?

Thanks in advance.

# Answer
You have few options:

1. do as you represented in the drawing: it should work, as I expect the transistors to not load too much the input.
2. add a logic buffer inbetween the arduino and the driver stage
3. use other pins from the arduino for driving the additional strips and bitbang the PWM, instead of using the HW blocks

Whether the solution you propose (1) will work or not depends entirely on the max current that each PWM pin can output vs the total load from the 3 transistors it will have to drive.
> 0 votes

---
Tags: led, pwm
---


# Question
Title: Sets of Ultrasonic frequencies using arduino uno
Is it possible to create a set of ultrasonics frequencies using only the Arduino? What code to be used? And how am I going to do for it to work? For this project I need to focus in the emitter side; all resources on Google are only on sensor and distance detector. I just want to use ultrasonic on other field just like for example on repelling rats. Thanks!

# Answer
There are three parts to this project, one of which you asked:

1. I need to generate a frequency greater than 40 khz using arduino uno?

This one is easy: Yes. You can use the tone() library call. You can specify a frequency up to 8mhz. You can call this in the `void setup{}` part of your code, and (if you don't want to do anything else), leave the `void loop() {}` empty. You might want to generate an audible tone for a short period first, to show that it is working.

2. You need something to actually make the sound.

Depending on the frequency, most speakers won't do the trick, or will do it at a very low volume. Speakers are made to work with audible frequencies. Even then, some speakers (larger ones) are better at low frequencies; others (smaller ones) are better at higher audible frequencies. I think piezoelectric buzzers would give you a better response at higher frequencies. In any case, whatever you buy find out the frequency response for the specific part, find the frequency you intend to use along the bottom, then see what the volume (db) is for that frequency - this will give you an indication of how loud it will be. Remember that you won't be able to hear it.

The circuit is pretty trivial. Google piezo arduino

3. Efficacy:

From https://en.wikipedia.org/wiki/Electronic\_pest\_control#Effects\_on\_rodents

> Rodents adjust to the ultrasound (or any new sound) and eventually ignore it. At best, ultrasonic waves have only a partial or temporary effect on rodents. Numerous studies have rejected ultrasonic sound as a practical means of rodent control.Tests of commercial ultrasonic devices have indicated that rodents may be repelled from the immediate area of the ultrasound device for a few minutes to a few days, but they will nearly always return and resume normal activities. Other tests have shown that the degree of repellance depends on the frequency, intensity, and pre-existing condition of the rodent infestation. The intensity of such sounds must be so great that damage to humans or domestic animals would also be likely; commercial ultrasonic pest control devices do not produce sounds of such intensity.
> 1 votes

# Answer
Another answer to generating ultrasonic frequencies is to ditch the Arduino altogether - use a 555 timer circuit (for lower range frequency, probably up to low mHz), or a resonator. A quick search found a 2.4 gHz resonator for less than an Arduino. 555 timers can be tuned, resonators cannot. I think you could build a 555 square-wave generator for about $1-$2.
> 0 votes

---
Tags: arduino-uno, frequency
---


# Question
Title: Newbie need help to make a motor run for a laser scanner and some questions
I am trying to make a laser scanner consisting of a webcam and a line laser scanner. I have tried to use a manual scanning (by hand) and has worked, but would now like to consider automating the laser rotation (upwards and downwards) as a higher accuracy entails a slow and smooth rotation.

I came across arduino a few weeks back and realised it could possibly help to make this a reality. From my limited readings so far, I have obtained an Arduino Uno and a motor shield that seems to be the essentials for my purpose.

I have a few queries that hopefully someone can help:

1. Do I need a stepper motor for slow rotations, instead of a normal brushed motor?
2. Do I need to connect the Arduino to computer to make it run? Can I run it off battery, if so, does it have an 'ON' button?
3. How long will a standard 9V battery last?
4. For the code, I thought of using the simple one here: Arduino Motor Shield Tutorial. Would it be able to allow me to control the amount of rotation, speed and the ability to reverse its rotation?

# Answer
> 2 votes
1. A servo motor would have a lot more control than a normal motor. You usually command them to go to one of the predefined steps (stops) by using a function call in the servo motor library.
2. You can run independently of the computer. Many people do this. Certainly you can run off a battery. It doesn't have an ON button, you normally would have this between your battery and the Uno (eg. built into the battery pack). Like this:

3. A 9 V battery? I wouldn't use one, especially to drive a motor. It won't last long. Get something like 3 x AA batteries in a battery holder.

To show you the idea, I have this servo motor (SG-5010) I got from Adafruit.

I measured it using about 200 mA of power when operating. Now, I looked up a typical Alkaline 9 V battery, and found that, consuming 200 mA, it lasts for around 400 mAh. Thus, you could say it would be good for two hours at that rate. Plus, the Arduino will take around 50 mA, so maybe less than two hours.

4. A smallish servo motor won't need a motor shield. The pictures on the linked page show ordinary brushed motors. A servo motor has 3 leads:
    * Power (eg. 5 V)
    * Gnd
    * Data

Make sure you connect the grounds together, but the power could go to a separate power pack. A bit depends on how much power your motor will use. The data goes to the Arduino for the information about which rotation point to step to.

You should be able, in code, to change the rotation position, forwards and backwards.

# Answer
> 2 votes
Nick gives some great advice, I am trying to answer your questions more directly.

1. Do I need a stepper motor for slow rotations, instead of a normal brushed motor?

Many kinds of motors can be made to work. I advise starting with the same type as in the Instructables you mention below. You can change the speed with gears if the motor speed range is not good enough.

2. Do I need to connect the arduino to computer to make it run? Can I run it off battery, if so, does it have an 'ON' button?

You only need to connect the Arduino to a computer to load or change the program. The motor is probably your biggest battery user, I would connect it to a separate battery from the Arduino. One advantage of the servo motors Nick mentions is that they are used by model car and airplane enthusiasts and there are lots of motors, batteries and battery chargers available.

3. How long will a standard 9V battery last?

Not long!

4. For the code, I thought of using the simple one here: Arduino Motor Shield Tutorial. Would it be able to allow me to control the amount of rotation, speed and the ability to reverse its rotation?

I looked through this code and it should work well as long as you use the same type of motor. You may have to modify things if you need the stop and start points to be very precise, but this will get you started and is a big step beyond scanning by hand.

---
Tags: motor, arduino-motor-shield
---


# Question
Title: Is there a away to transmit sensor signal over RF without Arduino?
I would like to place analog sensor in a place, that is impractical to reach with a wire. But it looks like an overkill to use a separate small Arduino board to read and transmit sensor signal to main Arduino board at a close range (~1 m).

Is there a cheap practical way to setup such sensor signal broadcast over RF without using Arduino board? Something that could work for considerable duration with a small tablet like battery?

# Answer
You don't have to use a $30 Arduino. You can make a "breadboard" one for a few dollars, like this:

$5 for the chip and a couple of dollars for a couple of capacitors and resistors.

---

Add to that a NRF24L01 transceiver like this:

Available from eBay for around $1 each. You need two, as you need to transmit from one and receive from another.

So the whole thing could be done for under $10.

---

> Something that could work for considerable duration with a small tablet like battery?

See Power saving techniques for microprocessors
> 1 votes

# Answer
I would recommend investigating the ESP8266 modules. Many people use them as a WiFi interface to an Arduino, but they are also capable of being used completely standalone.

You can pick up a cheap module and program it using a readily available USB to TTL UART adapter using the ESP8266 plugin to the Aduino IDE.

https://github.com/esp8266/Arduino

It's like having an Arduino and a WiFi interface all embedded in one chip, and the modules are tiny too - perfect for embedding in a project.

There are many different modules available, some with more pins than others for IO. The best one is the NodeMCU since it has the programming interface built in (go for version 1.0 not version 0.9 since it has better IO options), but the higher end ESP8266 modules on carrier boards (ESP-12, etc) are as good, if a little harder to work with.
> 1 votes

---
Tags: sensors, c++, power, analogread, rf
---


title: Arduino due slow clock

text:
# Question
Title: Arduino due slow clock
To reduce the components amount I don't want to put the 32.768 kHz oscillator on my own Due. Can I leave the corresponding XTAL inputs unconnected?

What is the main target of the slow clock? What I can not do with the high clock but can do with the slow one? Will I face to any issues if I don't use the low freq. oscillator?

# Answer
The slow clockr is primarily used for the real time clock (RTC) module inside the SAM3X chip. It can also be routed to other places when you want a low speed clock source, but the only places it is actually *required* are the RTC and the watchdog.

The slow clock can be generated from an internal RC oscillator instead of requiring an external crystal, but the accuracy and stability of the RC oscillator is many orders of magnitude worse than a crystal. Trying to use that for the RTC module will result in the clock drifting over time. The watchdog won't really care if the clock isn't perfectly accurate.
> 4 votes

# Answer
Atmel datasheet says:

**If the user does not need the crystal oscillator, the XIN32 and XOUT32 pins can be left unconnected**
> 0 votes

---
Tags: arduino-due
---


title: Arduino Analog Input Oscillating

text:
# Question
Title: Arduino Analog Input Oscillating
I'm making a simple Infrared detector using a thermopile. I have a few extra capacitors than what that schematic says. I'm currently following another, but this is the gist.

Schematic and Breadboard-

**I can add breadboard picture if needed. I don't have 10 points in this Stack so I can't post more than 2.**

I'm using a 9V battery through a 24v - 5v regulator (had one around) to power my op amp and schematic. The signal from the OPAMP will be between 0-5V so voltage hasn't damaged the Arduino Uno. The final project will be something like: output \> A then power green, A \< output \< B power yellow, B \< output red.

The issue is that I'm getting an oscillating value from my Serial Monitor that goes from 0 to 1023 (or I have a conversion to change it back to output voltage. So 0V to 5V. See code).

It does this oscillation when I have the board connected to any of the AX pins (X=0-5) or nothing plugged in at all (I understand it will output weird numbers with the pin floating).

**I had a picture of the serial monitor but I don't have 10 points to add more than 2 pictures. Please see image below**

I know that the output from the OPAMP works because when I use a VoltMeter to read the output, it works fine. 0.3XXV when no flame, 5V when flame is directly on top of my theromopile.

Would anyone happen to have a suggestion to why the Arduino is acting this way? The volt meter reading is directly out of the Op amp pin 1. **no more than 2 links. AD822 op amp**

Here's my code before adding if statements for the LED's. It was incorrect.

```
int TP=A2; // Assign Thermopile to pin A2
int val; // Declare readValue Variable
float Voltage; // Declare real world voltage variable - Float = in between variable
int ledG = 11;
int ledY = 12;
int ledR = 13;

void setup() {
 pinMode(TP,INPUT); // Declare Thermopile pin as input
 pinMode(ledG, OUTPUT);
 pinMode(ledR, OUTPUT);
 pinMode(ledY, OUTPUT);
 Serial.begin(9600); // Start your Serial Port
}

void loop() {
  val = analogRead(TP); // Read Thermopile pin and place value into readValue

  Voltage = (5./1023.)*val; // To do "floating point math" have a "." //after the number. If not, it will return real number (5/1023 = 0) according to Arduino

Serial.println(Voltage); // Print readValue to Serial Monitor
  delay(100); // Delayed output to 1/4 a second
}

```

# Answer
> 3 votes
It seems you haven't connected the circuit ground to the Arduino ground. This is essential to complete the circuit between your breadboard and the Arduino. Without the ground connection the electrons that you send to the Arduino have no way of getting back again.

Here's a couple of diagrams that I drew for another question which deals with the Arduino driving a remote device, but the theory holds true no matter which way around it is.

In that diagram the red arrows (*not the aerial display team I hasten to add*) represent the connection between your breadboard circuit and the Arduino. Without the ground connection there is no circuit, and a circuit is always needed for current to flow (and hence your signal). With the ground connection the red arrows become a loop which allows the current to flow and transfer your signal.

---
Tags: input
---


title: Asynchronous control framework

text:
# Question
Title: Asynchronous control framework
Can anyone recommend an Arduino-based asynchronous scheduling library for controlling a small mobile robot?

I'm writing the control code for a small 2-wheeled Arduino-Uno based robot. It has a few bumper sensors, IR sensors, and ultrasonic sensors. I've written an initial pass from scratch, using `loop()` to read sensors and set motor values appropriately and then wait for the motor to have effect, but I'm finding this cluggy. Some of the sensors, like the ultrasonic range finders, require a small delay to operate, and the motors require a delay to have an effect. Blocking `loop()` is the simplest way to achieve this, but it wastes cycles, and can be difficult to time each action properly without throwing off other behaviors. Writing an asynchronous scheduler would be more efficient, but a lot more complicated, and I expect I would be reinventing the wheel.

I found this list, of existing scheduling libraries, but I'm not sure which, if any, would be appropriate.

# Answer
I recommend writing your own in C++. Arduino works well with C++ as it is written in C. You can focus on getting the asynchronous behavior to do what you need instead of writing drivers. I don't think it will take any longer to learn enough C++ to make this work than it will to learn to use, and possibly fix, a library. Your C++ knowledge will be much more generally useful than knowing a specific library.

Igor points out the advantages of going to a real time operating system. I agree and think that, if you want to work on robots long term, you should go with an RTOS and get away from Arduino. Working with C++ and Arduino is one way to get started.
> 1 votes

# Answer
I would recommend ChibiOS: albeit it just got support for Arduino and it lacks a few drivers (I'm writing one for INTx and PCINT), it's got a fundamentally healthy design, a community around it and the author himself is very responsive.

You might have to write or port the drivers for external shields, however the upside is to get rid of the cruft that plagues most of the Arduino libraries.

You can even choose between 2 RTOS:

* ChibiOS RT, a full fledged RTOS.
* ChibiOS NIL, a minimalistic OS, actually almost a scheduler, which leaves more space and execution time for your own code. - But if you check the amount of FLASH taken up by a typical binary built with the default Arduino libraries, you will see that it pulls in a large amount of typically unused stuff, so you could trade that for the use of the full fledged RT.

Disclaimer: I'm just a very happy user of the OS, I do not have any other involvement with it, especially the commercial part.
> 0 votes

---
Tags: arduino-uno, library, core-libraries
---


# Question
Title: Querying streaming sensor data on the Arduino board
I am new to Arduino and this forum, so please forgive me if I am asking something really trivial and stupid.

I have an Arduino board which collects sensor readings from an MPU6050 sensor (acceleration+gyroscope). The next step for me would be to process these data directly on the board. I want to somehow store N last sensor values and then query this set (collection, vector, array, whatever you call it) to fetch certain values. This set will be constantly updated with new values, whereas older values will be pushed out, so that only the most up-to-date values are stored in the set. For example, I want to know if the acceleration exceeded 10 m/s in the last minute.

In the literature this kind of set with most recent values is sometimes called *window* \- this approach allows limiting an unbounded sequence of constantly generated tuples to a bounded bag and then apply traditional SQL-like query operators. For example, Oracle has come with CQL \- an engine and a query language for handling streaming data.

Before I start implementing this, I am wondering if there is a similar (and, of course, much simpler) library for Arduino? If not, which data structure should I use to implement such functionality?

Also, my intention is to query not just individual values, but certain patterns and sequences - e.g., I want to know if the acceleration first decreased and then increased again (something similar to the WHERE condition of an SQL query). Does it look realistic to implement with Arduino?

# Answer
It sounds like you are after my Average library:

It allows you to store a rolling set of data where you get to "push" values into it and the oldest one drops off the end. (It's implemented internally using a circular buffer).

You can then do various forms of analysis on the data - get the *mean* average, the *mode* average, calculate the standard deviation, find the maximum and minimum values of the set, and even access individual entries within the set.

It's a fully templated library, so you can use it with any numerical data type (float, double, int, long, etc).
> 0 votes

---
Tags: programming, sensors, c++, library
---


# Question
Title: Serial.readString() - how does it work exactly?
Someone posted a solution for a problem I had which used Serial.read() .Why doesn't readString() seem to work though? From the docs it seems it reads the data as a String object which would make things a bit cleaner.

But here's my Python code:

```
import serial

arduinoSerialData = serial.Serial('com7', 9600, timeout=0)

while True:
    arduinoSerialData.write('ALIVE\r\n')

```

And Arduino code:

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

  pinMode(13, OUTPUT);

}

void loop() {
    if (Serial.readString() == "ALIVE") {
        digitalWrite(13, HIGH);
    } else {
        digitalWrite(13, LOW);
    }
}

```

If this was right, the green LED on the Arduino would light up when the Python program would run, but it doesn't. What is Serial.readString() expecting that it doesn't get? I even tried `if (Serial.readString().startsWith("ALIVE"))` instead, as well as `arduinoSerialData.flush()` before `arduinoSerialData.write()`

# Answer
`readString()` will read characters from the serial (or other Stream) device until a timeout occurs. That timeout is, by default, 1 second. It is only appropriate to use `readString()` if your data is arriving in chunks with a minimum time between each chunk.

It is more appropriate to use `readStringUntil()` which will read characters from the serial device until *either* it times out, *or* it receives a certain character. It is most common to use either the line feed (`\n`) or carriage return (`\r`) characters as the end of string marker. You must, of course, ensure that your sending program sends the string terminated in the right way.

However, that all said, you really should avoid using String objects when possible, since the constant creation and destruction of temporary objects all over the place can make a real mess of your heap.

It is far better to learn to use character arrays and fill them using `Serial.read()`. A tutorial I wrote for that is here:
> 3 votes

---
Tags: serial, python
---


# Question
Title: USB 1.1 Low Speed project for Arduino UNO/ATmega328P to learn USB protocol
Arduino UNO is 5V, 16 MHz.

USB 1.1 Low Speed spec operate:

* at 5V level - so we avoid to maintain voltage level
* at 1.5 Mb/s - so we have 16/1.5 ~= 10 instructions per elementary protocol signal

Is it possible to make Arduino as slave USB device from UART lines connected to USB D+/D- interface with careful timing and assembler programming?

I doesn't familiar with ATmega328P pin I/O capabilities, may be them can't operate at 1.5 MHz so project isn't possible?

**UPDATE** I found V-USB library that:

```
implementation of a low-speed USB device for Atmel’s AVR® microcontrollers,
making it possible to build USB hardware with almost any AVR® microcontroller,
not requiring any additional chip.

```

Still dig into docs to realize possibilities.

# Answer
> 1 votes
Not exactly the answer to your question, but have you tried the typical way to emulate slave devices with Arduino UNO?

It uses the 2nd ATMega present onboard (this applies only to UNO, afaik) and lets you use the main ATMega for other tasks, delegating the USB protocol to the smaller ATMega16.

Do you have any specific reason why you would use the serial lines?

---
Tags: usb, project
---


title: atmega16 in Arduino Board

text:
# Question
Title: atmega16 in Arduino Board
I had a very common question. Why a additional MEGA used in most of the Arduino Boards. Arduino board Mega2560 also have a MEGA16U2 controller on board which i think is used for programming via USB. Is there any other specific usage of atmega16 on arduino board.

Thanks

# Answer
> 3 votes
It's an ATmegaU2, which has USB hardware and handles the USB communication. It passes the hex file on to the bootloader in the main microcontroller. That is its only job.

---
Tags: hardware
---


# Question
Title: Is it difficult to do high voltage parallel programming using Nick Gammon library?
I have bricked a few AT328P by invalid fuse settings.

Has anybody used the above sketches and the associated circuitry to perform high voltage programming?

# Answer
> 1 votes
I have not tried with those instructions, as I have an AVRDragon, but it's a good exercise for precision, since you have to wire lots of pins.

20+ iirc

My guess is that if anything fails, it's likely to be because of a mistake in the wiring.

If you are planning to do it often, you might consider soldering the wires and the ZIF socket to a prototype board, to preserve your mental sanity.

---
Tags: arduino-uno, fuses
---


# Question
Title: Is the Serial buffer going from Arduino to PC and from PC to Arduino different?
I'm both sending and receiving strings to Arduino from my Python program on the PC and the opposite. I don't check by code if one is finished before doing the other. Are they seprate buffers, or is it just pure luck my program has been running fine until now and each program has been reading the right string ?

# Answer
There shall be separate buffers for Tx and Rx (in Arduino Serial library). The actual buffer size may vary, but shall be around 8-16 bytes and there is also hardware buffer in MCU. Please try to increase serial baudrate, if possible.

**UPD:** In HardwareSerial.h:

```
#if (RAMEND < 1000)
#define SERIAL_TX_BUFFER_SIZE 16
#else
#define SERIAL_TX_BUFFER_SIZE 64
#endif

....

unsigned char _rx_buffer[SERIAL_RX_BUFFER_SIZE];
unsigned char _tx_buffer[SERIAL_TX_BUFFER_SIZE];

```

It seems for Atmega328 the buffers are 16 bytes each

**UPD:** As Nick pointed, for Atmega328:

```
#define RAMEND       0x8FF     /* Last On-Chip SRAM Location */

```

So the buffers are 64 byte each.
> 0 votes

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


# Question
Title: Parallel connection to Wiegand 26bit RFID readers
I have situation where I need to read RFID cards. There is already installed Roger security system, Roger gate control board and two rfid readers in parallel. By default board and RFID readers communicate in RACS(some sort of coded protocol) but at the moment system is configured to communicate in Wiegand26. Earlier I used chinese wiegand26 reader with Arduino with no problem.

With Arduino I need to read card read by RFID readers. Then I process data and make HTTP POST request. Arduino is supplied from Roger board ~13.5V DC I do not get anything in arduino, even if I connect RFID readers directly to arduino.

* CLK is D0 to Arduino Nano pin 2
* DTA is D1 to Arduino Nano pin 3

This question is not related only to Arduino.

I want to ask is it possible to do? To read data maybe I need some additional electronics?

What i also noticed that when Arduino is connected in parallel the Roger board not always reads the card from RFID readers.

Roger PR402-BRD And two readers PRT62LT

This is copy of Electronics.stackexchange

# Answer
> 2 votes
It looks to me like the Wiegand interface is an open-collector interface (like I2C), which is why they can be wired in parallel like that.

As long as the Arduino has both connections set to `INPUT` (not `INPUT_PULLUP` and certainly NOT `OUTPUT`) it shouldn't interfere at all.

By the way, for Wiegand, the two signals are DATA0 and DATA1. To transmit a 0 the DATA0 line is pulled low. To transmit a 1 the DATA1 line is pulled low.

You should also check that the idle voltage on the lines is indeed 5V as it should be. Anything more than that could cause the Arduino to chip the voltage to 5V through its internal ESD protection diodes.

Also you must ensure that the Arduino has its ground pin connected to the ground connection of the Wiegand system (which it should be since you are powering it from that).

# Answer
> 1 votes
If you would like to use more than 1 Wiegand reader, technically it should be possible to use **AVR pin change interrupt**. In this case you can use ANY 2 pins, even analog pins.

For example, see http://thewanderingengineer.com/2014/08/11/arduino-pin-change-interrupts/

**UPD:** There is informationon Wiegand timing, might be useful: http://proxclone.com/wiegand.html

---
Tags: communication
---


title: Arduino circuit diagram help

text:
# Question
Title: Arduino circuit diagram help
I'm new to the arduino and to EE in general. I've built the basic examples and a, now trying to get a deeper understanding of what the physics is doing. As such, I'd like some help in understanding the diagram here:

https://www.arduino.cc/en/Tutorial/Blink

**Question 1:**

Specifically,it seems that the flow is going from Pin 13 to Ground. Is the diagram using the conventional flow or the electron flow approach.

Specifically, is it the *electrons* flowing from Pin 13 to ground or does the diagram show protons flowing? It seems that its showing the electron flow as the diagram has the anode attached to the resistor so the electrons flow from the pin to the resistor to the positive end (anode) of the LED.

**Question 2:** This is about bread boards, like one shown here:

https://www.google.com/search?q=arduino+breadboard&biw=1696&bih=988&tbm=isch&tbo=u&source=univ&sa=X&ved=0CFEQsARqFQoTCIjsw5WhkMgCFdWYiAodttcKIw#tbm=isch&q=breadboard&imgrc=KwnTrtjnYJdB1M%3A

1) Would I connect Pin 13 (or say the 5V pin) to the + (the red line). Then I would connect the blue line (the -) to the ground on the arduino? Do I need to connect the blue line?

2) Also, is it again the electron flow notation so that from Pin 13, the electrons flow to the + (red), then to one of the lettered columns and then to whatever component I have?

Thank you for your help! I realize these are basic questions but I want to go a little beyond building the examples and start trying things out myself. As such I want to make sure I'm getting the theory behind it right!

# Answer
The thing to remember about electrons is they are a negative charge. That means that the direction of current flow (positive charge) is opposite to the direction of flow of the actual electrons (negative charge). Picture it like those "compression jams" you get on the motorway (freeway) where cars that are travelling too close together have to slam their breaks on to avoid running into each other. The one at the front slams its breaks on briefly then carries on. The one behind has to do the same, and so on and so forth. You then get a wave effect travelling in the opposite direction to the direction of travel of cars as they slam their breaks on in turn. The cars are moving forwards, but the compression jam is moving backwards. Similar in a circuit - the electrons are moving forward, but the charge is moving backwards.

Another way to visualize it is as a bubble in a pipe of stationary water. The bubble moves in one direction, but in order for it to do that the water has to flow past the bubble in the opposite direction.*

So the current flows out of pin 13 through the LED and to ground, but the electrons themselves are actually flowing from ground through the LED and in to pin 13 (where they eventually return back to ground through the power supply).

For how the IO pin works it's best to picture it as a pair of switches - one connected to Vcc and one connected to GND. For instance, this is the LED wired up with the IO pin set to HIGH:

You can see that S1, being on, forms a circuit between the battery and the LED to allow the current to flow.

When the IO pin is set to LOW the circuit looks a bit like this:

You see that S1 is now turned off, and S2 is turned on. the connection from that battery is now broken, and current can't flow.

But, you ask, what is the point of S2 here? It doesn't actually do anything. No, not in that circuit it doesn't. But consider if you re-arrange the circuit to be like this:

Now it's S2 that is controlling the connection to the battery. S1 is now the redundant switch.

This leads to some terminology.

When S1 is closed the IO pin is said to *source* current since it is pretty much connected directly to the positive power source.

When S2 is closed instead the IO pin is said to *sink* current since it is connected to ground, so current can "sink" down to ground through it.

As far as breadboards are concerned - they are just collections of metal strips that are used to join wires and component leads together in whatever way you need to. There is no one part of it that is any different to any other, and there is nothing that says you must use this bit in a certain way, or that bit in another way.

Your typical breadboard has sprung metal clips that are arranged in this pattern:

You can use any collection of holes for any purpose you choose.

That said, normally the blue (or black) marked line of holes down each side is used for ground, and the red line of holes is used for power. As both sides of the board are separate it is possible to use different voltages on each side, or the same voltage on both sides, etc. That can be especially useful when you're working on a circuit that has, say, +3.3V and +5V in it. Another common split usage is for a positive voltage on one side and a negative voltage on the other - common when working with op-amps. Just remember which is which.

---

* This is a complete lie, but it's as close as you need to know at this point in your education. https://en.wikipedia.org/wiki/Lie-to-children
> 5 votes

# Answer
It doesn't matter whether you use conventional current or electron current to describe a circuit; in the end they give the same results.

Protons are not a charge carrier in 99.99999% of circuits; positive charge carriers are the quasiparticles known as **holes**, but they only flow in semiconductors.

The power rails on a breadboard should be used for power only, never signals. It is possible to use them for other things, and it is possible to not use them at all, but when they are used they should only be used for supply in order to cause the least confusion.
> 2 votes

# Answer
Protons don't flow. They are part of the atom nucleus. If they flowed the copper wire would be flowing. Electrons are what flow, particularly if there are some free ones hanging around, like teenagers hanging around a mall.

You don't need to worry about that however. Most people think of current as flowing from positive to negative (ie. pin 13 to ground) even if in fact the electrons are flowing from ground to pin 13.

See Conventional Versus Electron Flow. I quote:

> When Benjamin Franklin made his conjecture regarding the direction of charge flow (from the smooth wax to the rough wool), he set a precedent for electrical notation that exists to this day, despite the fact that we know electrons are the constituent units of charge, and that they are displaced from the wool to the wax—not from the wax to the wool—when those two substances are rubbed together. This is why electrons are said to have a negative charge: because Franklin assumed electric charge moved in the opposite direction that it actually does, and so objects he called “negative” (representing a deficiency of charge) actually have a surplus of electrons.
>
> By the time the true direction of electron flow was discovered, the nomenclature of “positive” and “negative” had already been so well established in the scientific community that no effort was made to change it, although calling electrons “positive” would make more sense in referring to “excess” charge. You see, the terms “positive” and “negative” are human inventions, and as such have no absolute meaning beyond our own conventions of language and scientific description. Franklin could have just as easily referred to a surplus of charge as “black” and a deficiency as “white,” in which case scientists would speak of electrons having a “white” charge (assuming the same incorrect conjecture of charge position between wax and wool).

Quote courtesy of Design Science under this license.

---

> Would I connect Pin 13 (or say the 5V pin) to the + (the red line). Then I would connect the blue line (the -) to the ground on the arduino? Do I need to connect the blue line?

When using a breadboard I connect the 5V pin to the red line, the Gnd pin to the blue line, and other things (signals) to the internal (numbered) holes. The internal ones are connected cross-ways, so that is useful, for example, to put a series resistor for the LED there.

I trust you are using a resistor for the LED, if not you might damage both the LED and the Arduino. See The care and feeding of LEDs.
> 1 votes

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


# Question
Title: I2C Master send reset command to the slave counter
My name is Gianni, I live in Olbia Sardinia Italy and I have some experience in electronics.

For several years I have been passionate about Arduino.

They are now engaged in a project to counter with hall sensors.

The slave sends data to the master via I2C, for my project. I'm using the sketch of Gammon which uses a structure enum to send a request to the slave.

I have the need to send a reset command from master to slave.

I edited the sketch and I can see the command on the slave but will not let me use it to reset the counter.

---

## Master code section

```
   void RstCounter()
  {

  Serial.println ("funzione azzera attivata");
   Serial.println (sensor);
  char key = keypad.getKey();
  if (key !='A')
  {

   char cmdrst = 'a';
   //set=key;

     if (sensor==11)
    {
    sendCommand (CMD_WRITE_D2, 1);

    Wire.beginTransmission(SLAVE_ADDRESS); // testiamo questa istruzione
    Wire.write(cmdrst);
    Wire.endTransmission();

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

   else
  {
  m=0;
  }

   azzera =true;
  }
   else if (key=='A')
    {
   Serial.println("");
   Serial.println("AZZERA close");
   azzera = false;
   }
     delay(100);
    }

```

---

## SLAVE code section

```
#include <Wire.h>

const byte MY_ADDRESS = 42; // address in valore esadecimale

/************  VARIABILI SENSORI **********************/

#define Sensor11 2
int lastValueSensor11 =0;
int ValueSensor11=0;
int contatore11=0;
int counter11;

// various commands we might get
/************  VARIABILI ENUMERATORE **********************/
enum {
    CMD_ID = 1,
    CMD_READ_D2  = 2,
    CMD_READ_D3 = 3,
    CMD_READ_D4 = 4,
    CMD_WRITE_D2 = 5
    };

char command;
int sensor;
char cmdrst;

/************  SETUP **********************/
void setup()
  {
  command = 0;

  pinMode (Sensor11, INPUT);
  digitalWrite (Sensor11, HIGH);  // enable pull-up

  Serial.begin(9600);
  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

  }  // end of setup

/************  LOOP **********************/
void loop()
  {
        /************************ CONTATORE SENSOR 1 ***********************/
   ValueSensor11  = digitalRead(Sensor11);

            if ( ValueSensor11 != lastValueSensor11)
               { if ( ValueSensor11 == LOW)
                    {
                      contatore11 = contatore11 + 1;

                        }
                     }
   lastValueSensor11 = ValueSensor11;

/************  I2C RECEIVE **********************/
void receiveEvent (int howMany)
  {

  command = Wire.read ();  // remember command for when we get request
  //Serial.println(command);
  switch (command)
     {
     case CMD_WRITE_D2:
     Serial.println("comando 5 ricevuto");
     char cmdrst=Wire.read();
     delay(100);
     Serial.println (cmdrst);
     break;
    }
} // end of receiveEvent

void sendSensor1 (const byte which)
  {
  int val11 = contatore11;
  Serial.println(contatore11);
  byte buf11 [2];

    buf11 [0] = val11 >> 8;
    buf11 [1] = val11 & 0xFF;
    Wire.write (buf11, 2);
  }  // end of sendSensor

void requestEvent ()
  {
  switch (command)
     {
     case CMD_ID:
     Wire.write (0x55);
     break;   // send our ID

     case CMD_READ_D2:
     sendSensor1 (2);
     break;  // send A0 value

     case CMD_READ_D3:
     sendSensor2 (3);
     break;    // send D8 value

     case CMD_READ_D4:
     sendSensor3 (4);
     break;

     }  // end of switch

  }  // end of requestEvent

```

# Answer
```
void receiveEvent (int howMany)
  {

  command = Wire.read ();  // remember command for when we get request
  //Serial.println(command);
  switch (command)
     {
     case CMD_WRITE_D2:
     Serial.println("comando 5 ricevuto");
     char cmdrst=Wire.read();
     delay(100);
     Serial.println (cmdrst);
     break;
    }
} // end of receiveEvent

```
* Don't do serial prints inside an interrupt service routine (ISR). That is, not here.
* Don't do `delay` inside an ISR.

---

```
  if (key !='A')
  {

```

I would be checking for NO\_KEY first, otherwise you will assume that no key press is not 'A' and be doing that transmission to the slave **a lot**.
> 1 votes

---
Tags: c++, i2c
---


title: help with 7- segment display

text:
# Question
Title: help with 7- segment display
I'm playing with a 7 segment display.

The following works on my breadboard:

```
5V -> 330 Ohm Resistor (same row, row 9)
330 Ohm Resistor -> Com Port (row 9 to row 15)
h led (the dot/row 17) -> ground rail

```

I get the dot to light up.

However, the following does not light up:

```
5V -> h led (the dot/row 17)
Com Port -> 330 Ohm Resistor (Row 15 -> row 38).
330 Ohm Resistor to negative rail (row 38 -> negative rail)

```

I realize that the row numbers are meaningless -- things just need to be on the same row. I've included them to make it easier to visualize.

So basically, if the circuit goes:

5V -\> Resistor -\> Com, then I can use the ground wire to light up any part I want.

If the circuit goes Com -\> Resistor to Ground, I can't use the 5V to light up any part.

I'm not sure why given that all the stuff is in serial?

# Answer
Because you have a common-anode display and you're trying to use it as a common-cathode display. LEDs, like all diodes, only conduct freely in one direction.
> 2 votes

---
Tags: serial, led, electronics
---


# Question
Title: Using an Arduino as a electrical mains switch
How do I make an electrical switch using Arduino, that when it receives signal (wirelessly or through a LAN port) to switch off it disconnects the switch and then again told to turn on turns the switch on?

The main problem I am facing is that I need to give a 5V output to turn off the transmission between two wires having voltage rating of 230V.

# Answer
> 4 votes
You need to use Relays. There all kind of relays.

Regular and Solid state ... for controlling a Regular Relay using Arduino you will need a transistor (so you will able to provide the right current to the relay to close a circle)

There are a lot of guides for Arduino and Relays (for example)

# Answer
> 1 votes
As pointed out in the comments, I would need to use something known as a relay with my Arduino.

---
Tags: arduino-uno
---


# Question
Title: Just sanity-checking a concept... poor man's self-monitored alarm system
If I wanted to throw together a simple burglar-alarm system that had wireless sensors talking to an Arduino (which would then send me an SMS message via cellular shield as a silent alarm telling me which alarm sensor had changed state\_)... what technology would you recommend for the sensor-to-arduino signalling?

It needs to be something that draws little or no power until the alarm is triggered, resistant to radio interference, and as always cheap is a huge plus.... but I haven't gotten much beyond that.

(Of course if anyone's already implemented something like this and there are descriptions/sketches I can adopt and adapt, feel free to point me in the right direction.)

EDIT: To provide more info,this is a wood-framed house, 2 storey plus basement, brick chimney possibly in the way. No straight-line distances greater than 60 feet. Wifi, wireless phone, usual electronics and a wood shop I'm still putting together. Shouldn't be difficult, I just want a robust solution in case a friend asks me to replicate it... and for purely aesthetic reasons.

# Answer
> 4 votes
NRF24L01+ for communication. Extreme low power if not sending. Detects packet loss, and automatically resend the packet.

You would however need a small arduino board at the sensor, to read the sensor, and signal to NRF24L01 to send a message.

You'll have to put the arduino in to low power sleep mode to get some good battery life. Either have the sensor wake the arduino up with an interrupt, of poll the sensor like every half second, and immediately go back to sleep.

---
Tags: sensors, power, system-design, wireless
---


title: Measure Vcc using 1.1V bandgap

text:
# Question
Title: Measure Vcc using 1.1V bandgap
For an battery driven application I want to measure the Vcc (using an Atmega 32u4). That is my code:

```
int readBandGap() {
  ADMUX = (B01 << REFS0)    // VCC
        | (0 << ADLAR)      // right-adjusted result
        | (B011110 << MUX0) // 1.1V
        ;
  // switch off any ADC conversion
  ADCSRA &= ~(1 << ADEN);
  // enable ADC
  ADCSRA |= 1 << ADEN;
  // start ADC
  ADCSRA |= 1 << ADSC;
  // wait until finished
  while (bit_is_set(ADCSRA, ADSC));
  // first read low, then high!
  uint8_t low = ADCL;
  uint8_t high = ADCH;
  // switch off any ADC conversion
  ADCSRA &= ~(1 << ADEN);
  return (high << 8) | low;
}

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

void loop() {
  int value = readBandGap();
  float vcc = 1.1 * 1023 / value;
  Serial.print(value);
  Serial.print("  ");
  Serial.println(vcc);

  delay(1000);
}

```

My Olimexino 32u4 board has the ability to switch the voltage between 5V and 3.3V. There are two strange things:

1. the first measurement is always significantly different than the later measurements
2. with 5V I'm getting 450, followed by ~367; with 3.3V I'm getting 422, followed by ~395. I would have expected a higher Vcc resulting in a lower measured value (bandgap should be measured compared to Vcc).

Any ideas what is wrong with my approach?

# Answer
> 0 votes
After tweaking a lot, I've now have found following code to work quite good.

```
float readVcc() {
  ADMUX = (B01 << REFS0)    // VCC
        | (0 << ADLAR)      // right-adjusted result
        | (B011110 << MUX0) // 1.1V
        ;
  // enable ADC
  ADCSRA |= (1 << ADEN);
  // seems necessary
  delay(2);
  // start ADC
  ADCSRA |= 1 << ADSC;
  // wait until finished
  while (bit_is_set(ADCSRA, ADSC));
  // first read low, then high!
  long value = ADCL;
  value |= ADCH << 8;
  return 1.1 / value * 1023;
}

```

# Answer
> 1 votes
The bandgap voltage reference needs some time to stabilize, after you enable it. See http://jeelabs.org/2012/05/12/improved-vcc-measurement/

Doing 3 dummy measurements, gives it enough time to do that.

---
Tags: c++, voltage-level, adc
---


title: Standalone Arduino

text:
# Question
Title: Standalone Arduino
I have an Arduino Uno and I am using arduino 1.0.5 IDE. I followed he procedures for bootloading an atmega328P-PU on a breadboard using an Arduino Uno from the link:

https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

I uploaded the ArduinoISP sketch first, made the connections(using the External Oscillator) and then wired it up. Then, I selected the programmer as Arduino as ISP, selected the board as Arduino duemilanove w/ Atmega328P . Then I selected the correct serial port and clicked Burn Bootloader. I got the following errors:

```
avrdude.exe: stk500_program_enable(): protocol error, expect=0x14,
resp=0x50avrdude.exe: initialization failed, rc=-1 Double check
connections and try again, or use -F to override this
check.avrdude.exe: stk500_disable(): protocol error, expect=0x14,
resp=0x51

```

How to solve this issue? Also, can I upload the bootloader directly by using it on the Uno in place of the original chip. If so, how?

# Answer
> 1 votes
See How to make an Arduino-compatible minimal board.

> Also, can I upload the bootloader directly by using it on the Uno in place of the original chip.

No, a blank chip cannot install its own bootloader. You use a second chip. My page above describes how to do that. An alternative is a stand-alone ICSP programmer, which can be purchased for around $20. The tutorial page you linked uses your Uno as a stand-alone programmer.

I think my method of using a Uno as a programmer is easier, frankly.

# Answer
> 0 votes
I had the same problem; I never figured it out. I eventually threw down some cash for am ICSP (I got the FreeTronics USBASP), and have never looked back. In fact, with an ICSP, you don't even need a bootloader. It's also real easy to solder a 6-pin header onto your custom soldered board; then you will realize you don't need an Arduino at all, just an Atmel chip.

---
Tags: arduino-uno, arduino-ide, atmega328, bootloader, icsp
---


title: Help with socketIO Example

text:
# Question
Title: Help with socketIO Example
I'd like to get a TCP based connection from an arduino to a node.JS server. I found an example, I've tried to run it but its throwing the errors below, would appreciate any help.

Error Messages Arduino: 1.6.6 Hourly Build 2015/09/24 05:43 (Windows 7), Board: "Arduino/Genuino Uno"

```
WARNING: Category '' in library ArduinoJson is not valid. Setting to 'Uncategorized'
socketio.ino: In function 'void hello(Client&, const char*)':

socketio:19: error: expected unqualified-id before '.' token

socketio.ino: In function 'void setup()':

socketio:38: error: invalid conversion from 'void (*)(Client&, const char*)' to 'void (*)(Client&, ArduinoJson::JsonArray&)' [-fpermissive]

In file included from socketio.ino:6:0:

C:\arduino_1.6.6\libraries\socket.io-arduino-client.2/SocketIOClient.h:56:8: error:   initializing argument 2 of 'void SocketIOClient::setEventHandler(const char*, void (*)(Client&, ArduinoJson::JsonArray&))' [-fpermissive]

   void setEventHandler(const char* eventName, void (*handler)(Client& client, JsonArray& data));

        ^

socketio:39: error: invalid conversion from 'void (*)(Client&, const char*)' to 'void (*)(Client&, ArduinoJson::JsonArray&)' [-fpermissive]

In file included from socketio.ino:6:0:

C:\arduino_1.6.6\libraries\socket.io-arduino-client.2/SocketIOClient.h:56:8: error:   initializing argument 2 of 'void SocketIOClient::setEventHandler(const char*, void (*)(Client&, ArduinoJson::JsonArray&))' [-fpermissive]

   void setEventHandler(const char* eventName, void (*handler)(Client& client, JsonArray& data));

        ^

exit status 1
expected unqualified-id before '.' token

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

```

Arduino Code #include #include

```
#include <ArduinoJson.h>
#include <SocketIOClient.h>

EthernetClient ethClient;
SocketIOClient client(ethClient);

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char hostname[] = "192.168.100.40";
int port = 3000;

// Socket.io "hello" EVENT handler
void hello(Client& client, char const * data) {
    Serial.print("[hello] event happening: ");
    Serial.println(data);
    Client.emit("goodbye", "Arduino here, goodbye!");
}

// Socket.io "goodbye" EVENT handler
void goodbye(Client& client, char const * data) {
    Serial.print("[goodbye] event happening: ");
    Serial.println(data);
    Serial.println("That is all.");
}

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

    if(!client.connect(hostname, port)) {
        Serial.println(F("Not connected."));
    }

    //Event hanlders
    client.setEventHandler("hello", hello);
    client.setEventHandler("goodbye", goodbye);

    //Say hello to the server
    client.emit("hello", "Arduino here, hello!");
}

void loop() {
    client.monitor();
}

```

SocketIO.h

```
/*
    socket.io-arduino-client: a Socket.IO client for the Arduino

    Based on Bill Roy's Arduino Socket.IO Client (which is based on
    Kevin Rohling's Arduino WebSocket Client) with event handling by
    @dantaex

    Copyright 2014 Quentin Pigné

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef SocketIOClient_H
#define SocketIOClient_H

#include <Arduino.h>
#include <Client.h>
#include <SPI.h>

#include <ArduinoJson.h>

#include "HashMap.h"

//Length of static data buffers
#define DATA_BUFFER_LEN 200
#define SID_LEN 24

//Max size of the HashTable
#define HASH_SIZE 20

class SocketIOClient {
    public:
        SocketIOClient(Client& client);
        //Public connection methods
        bool connect(const char* hostname, int port = 80, const char* resource = "socket.io", const char* nsp = "/");
        //Public event handling methods
        void setEventHandler(const char* eventName, void (*handler)(Client& client, JsonArray& data));
        //Public data emitting methods
        void emit(const char* event, const char* data);
        //Monitoring for incoming data
        void monitor();

    private:
        //Connection attributes
        Client& client;
        char* hostname;
        int port;
        char* resource;
        char* nsp;
        char sid[SID_LEN];
        //Incoming data reading attributes
        char databuffer[DATA_BUFFER_LEN];
        char* dataptr;
        //Event handling attributes
        int nbEvent;
        static HashType<const char*, void(*)(Client& client, JsonArray& data)> hashRawArray[HASH_SIZE];
        static HashMap<const char*, void(*)(Client& client, JsonArray& data)> eventHandlers;

        //Private incoming data reading methods
        bool waitForInput();
        void eatHeader();
        void readInput();
};

#endif

```

# Answer
> 1 votes
Make your `char *` parameters `const char *`.

---
Tags: node.js
---


title: RGBs, photoresistors, and delays

text:
# Question
Title: RGBs, photoresistors, and delays
I am having a little trouble with a program of mine. My circuit consists of (mainly) an arduino UNO, two RGB LEDs, and a photoresistor. My current code(programmed in c#) operates the hardware as so: When the lights in the room are on, the two LEDs alternate blue/off once per second in a loop. When the lights are off, or the photoresistor is not sensing any light, both LEDs turn on, and stay on, red. My code:

```
int prPin = A0;

void setup()
{
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(prPin,INPUT);
  Serial.begin(9600);
}

void loop()
{
  int prVal = analogRead(prPin);
  Serial.write(prVal);
    if(prVal>450)
    {
      digitalWrite(5,HIGH);
      digitalWrite(6,HIGH);
      digitalWrite(7,HIGH);
      digitalWrite(8,LOW);
      digitalWrite(9,HIGH);
      digitalWrite(10,HIGH);
      delay(1000);
      digitalWrite(5,LOW);
      digitalWrite(6,HIGH);
      digitalWrite(7,HIGH);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
      digitalWrite(10,HIGH);
      delay(1000);
    }
    else
    {
      digitalWrite(5,HIGH);
      digitalWrite(6,HIGH);
      digitalWrite(7,LOW);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
      digitalWrite(10,LOW);
      delay(10);
    }
}

```

The problem I am having is when the lights turn off, the LEDs will not operate according to the "else" statement/loop until it finishes going through the "if" statement/loop. Any suggestions or answers are appreciated. I'm an open book, so I'll take anything you guys give me.

# Answer
Instead of the two delays of one second, have the program check if the current time is an even or odd number of seconds.

```
int prPin = A0;

void setup()
{
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(prPin,INPUT);
  Serial.begin(9600);
}

void loop()
{
    int prVal = analogRead(prPin);
    Serial.write(prVal);
    if(prVal>450)
    {
      if( (millis()/1000)%2 == 0 ) // check if even or odd number of seconds have passes since the program started
      {
        digitalWrite(5,HIGH);
        digitalWrite(6,HIGH);
        digitalWrite(7,HIGH);
        digitalWrite(8,LOW);
        digitalWrite(9,HIGH);
        digitalWrite(10,HIGH);
      }
      else
      {
        digitalWrite(5,LOW);
        digitalWrite(6,HIGH);
        digitalWrite(7,HIGH);
        digitalWrite(8,HIGH);
        digitalWrite(9,HIGH);
        digitalWrite(10,HIGH);
      }
    }
    else
    {
      digitalWrite(5,HIGH);
      digitalWrite(6,HIGH);
      digitalWrite(7,LOW);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
      digitalWrite(10,LOW);
      delay(10);
    }
}

```
> 0 votes

---
Tags: programming
---


title: Interrupt not firing on motion

text:
# Question
Title: Interrupt not firing on motion
I'm trying to get MMA8452Q to trigger an interrupt when motion is detected and wonder if I'm missing something very obvious here.

So I setup CTRL\_REG4 to 0x0B with

```
void MMA8452Q::setupISR()
{
    writeRegister(CTRL_REG4, 0x0B);
}

```

then I setup FF\_MT with

```
void MMA8452Q::setupFF_MT()
{
    writeRegister(FF_MT_CFG, 0xF8);
    writeRegister(FF_MT_THS, 0x0F);
    writeRegister(FF_MT_COUNT, 0x00);
}

```

and I read ISR with

```
#define SRC_PULSE 2
#define SRC_FF_MT 1

byte MMA8452Q::readISR()
{
    byte intStat = readRegister(INT_SOURCE);

    if (intStat & 0x0B)
    {
        readRegister(FF_MT_SRC);
        return intStat & 0x0B;
    }
    else
        return 0;
}

void printISR()
{
  byte isr = (accel.readISR() >> 2);
  if (isr & SRC_PULSE)
    Serial.print("(ISR) Tap");
  else
    Serial.print("(ISR) No Tap");

  Serial.print("\t");

  if (isr & SRC_FF_MT)
    Serial.print("(ISR) Motion");
  else
    Serial.print("(ISR) No Motion");

  Serial.print("\t");
}

```

AFAIK, that should already have FF/MT interrupt enabled. Even when I'm getting readings in `FF_MT_SRC`, I'm not picking up an interrupt in `INT_SOURCE`.

Interrupts are fired on (most) taps, but not on motion at all.

Am I missing something here?

Thanks

# Answer
Here's an extract from page 39 of MMA8452Q-rev8.1.pdf, the MMA8452 spec sheet:

Rather than saying `writeRegister(CTRL_REG4, 0x0B);` in `MMA8452Q::setupISR()`, try `writeRegister(CTRL_REG4, 0xD);`.

0xB is 1011 in binary, while 0xD is 1101, which turns on INT\_EN\_FF\_MT to enable freefall/motion interrupts.

The above should answer your question as asked. The following expands on my earlier comment which said

> Absent other info, it looks like MMA8452Q::readISR() is not an interrupt processing routine, but instead a routine that polls an interrupt-source register to find out what source would have triggered an interrupt if correctly wired and initialized.

"Interrupt" as used in your question (and code) refers to when the MMA8452 signals (via an I1 or I2 output line) that an interrupt-worthy condition has occurred.

"Interrupt" as in the question does not refer to an interrupt from the Uno's point of view, because (per diagram) neither of I1 or I2 connects to the Uno.

If speed of response becomes important, you may wish to hook I1 or I2 to one of the Uno's Digital Pins With Interrupts, ie pin 2 or 3, as noted in the AttachInterrupt page at arduino.cc. Then you'd replace the polling loop that now periodically reads the MMA8452's ISR (interrupt status register) to check for set bits, with an interrupt service routine which would set a flag to cause loop() to use Wire.read to get ISR data.
> 0 votes

---
Tags: arduino-uno, sensors, c, accelerometer
---


title: Identical statements, different outcome

text:
# Question
Title: Identical statements, different outcome
First a little background on me and my project. Most of my programming experience is with PHP and javascript. I have just recently started looking at C and C++ for this Arduino project. My project is a weather station that feeds its data to a web based database in real time. I will be writing the code for a web site that will access this data base and present the data in realtime. I am currently working on the temperature section of my weather station. It is an RTD coupled to a constant current circuit and feeds a varying voltage to analog pin 5 on my Arduino Uno. My problem is with the code. I have a working code but I decided to make it object oriented so that I could reuse it in other projects. Here is the code that works.

```
const unsigned int RTD_PIN = A5;
const float MVOLTS_CTS = 4.882813;
const float OHMS_DEGREE = 0.3851;
const unsigned int SAMPLES = 10;
const float MILLI_AMPS = 19.125;
unsigned long currentMillis;
unsigned long oldMillis = 0;
unsigned long timeBetweenSamples = 1000; // milliseconds between samples
int measurement[SAMPLES];
int read_index = 0;
int total = 0;
int average_cts = 0;
boolean initialized = false;
float degC = 0;
float degF = 0;

void setup() {
  Serial.begin(9600);
  for (int i = 0; i < SAMPLES; i++) {
    measurement[i] = 0;
  }
}

void loop() {

  // Reset the counter when we go over the
  // set number of samples
  if (read_index >= SAMPLES) {
    read_index = 0;
    initialized = true;
  }

  // only take a measurement if one second has passed
  currentMillis = millis();

  if (currentMillis - oldMillis >= timeBetweenSamples) {
    // subtract one element from the total
    total = total - measurement[read_index];

    // take a measurement
    measurement[read_index] = analogRead(RTD_PIN);

    // add the new measurement back into the total
    total = total + measurement[read_index];

    // take an average of the readings
    average_cts = total / SAMPLES;

    // calculate degrees
    degC = (average_cts * MVOLTS_CTS / MILLI_AMPS -100) / OHMS_DEGREE;
    degF = degC * 1.8 + 32;

    // print results only if all elements of measurement[] are filled
    if (initialized) {
      Serial.print(degC);
      Serial.print(" degrees C ");
      Serial.print(degF);
      Serial.print(" degrees F ");
      Serial.println(average_cts);
    }

    read_index++;
    oldMillis = currentMillis;

  }
}

```

And this is the code that doesn't work.

```
#include "Arduino.h"
#include "Sensor.h"

    Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long sampleRate) {

     sensorPin = analogPin;
     samples = numSamplesInAverage;
    _sampleRate = sampleRate;
     int measurement[samples];

     // initialize the measurement array
     for (int i = 0; i >= samples; i++) {
       measurement[i] = 0;
     }

  }

  int Sensor::update() {

    if (read_index >= samples) {
       read_index = 0;
     }

     // only take a measurement if sample rate has been exceeded
     // and return a rolling average
     currentMillis = millis();

     if (currentMillis - oldMillis >= _sampleRate) {
       //subtract one element from the total
       total = total - measurement[read_index];

       // take a measurement
     measurement[read_index] = analogRead(sensorPin);

       // add the new measurement into the total
       total = total + measurement[read_index];

       // take an average of the readings
       average_cts = total / samples;

       // increment the read_index
       read_index++;
       oldMillis = currentMillis;

      return average_cts;
     }

     // return false if the sample rate has not expired
     return false;

  }

```

It seems like the issue is with this one line of code on line 34.

```
measurement[read_index] = analogRead(sensorPin);

```

When this line has not been remarked out the read\_index only goes to 4 before it resets to 0 and it does it at the rate of program execution instead of every second like expected.

If this line is remarked out the the read\_index is incremented from 0 to 9 once every second as expected.

Here is where the read\_index is defined.

```
#ifndef Sensor_h
#define Sensor_h

#include "Arduino.h"

class Sensor
{
   public:
     Sensor(int analogPin, int numSamplesInAverage, unsigned long sampleRate);
     int update();

   private:
     unsigned int sensorPin;
     unsigned long currentMillis;
     unsigned long oldMillis;
     unsigned long sampleRate; // milliseconds between samples
     int read_index = 0;
     int total = 0;
     int average_cts = 0;
     int samples;
     unsigned long _sampleRate;
     int measurement[];
};

#endif

```

and this is the Arduino sketch that calls update()

```
#include <Sensor.h>

Sensor rtd(4, 10, 1000);  // instantiate a Sensor object
int cts;

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

void loop() {

  rtd.update();

  Serial.println(rtd.read_index);
}

```

can anyone tell me why this works in my procedural code but not the objected oriented code?

# Answer
> 1 votes
You have made a few fundamental errors with your class.

Firstly you have not provided a storage size (number of elements) for the `measurement` array class member variable:

```
class Sensor
{
   public:
     Sensor(int analogPin, int numSamplesInAverage, unsigned long sampleRate);
     int update();

   private:
     // ... cut ...
     int measurement[];           // <<-- How big is this?!
};

```

Then it seems like you try to dynamically allocate the space for it in your constructor:

```
Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long sampleRate) {

    sensorPin = analogPin;
    samples = numSamplesInAverage;
    _sampleRate = sampleRate;
    int measurement[samples];    // <<-- Here
    // ... cut ...
}

```

BUT that's *not* what you are doing. What you are doing there is creating a *new* local variable (local to *just that one single function*) called `measurement` with an array size of `samples`. As soon as you leave the constructor that variable is thrown away.

You haven't touched the class member variable `measurement` at all. So, when you do:

```
measurement[read_index] = analogRead(sensorPin);

```

you are storing the read value into an array of no size that points nowhere. And of course that then causes a crash because you're writing to memory that you shouldn't be writing to.

If you want to be specifying the number of array elements in the constructor you need to be learning about *dynamic memory allocation* using `malloc()` and `free()` and all the pitfalls that go along with using those on a small microcontroller with very tight RAM constraints.

For an example of how it can be done you should take a look at my Average Library which uses dynamic allocation to allocate the array memory in the constructor and free it in the destructor.

# Answer
> 0 votes
I was going to add to Majenko's excellent answer, but what I want to say is too long. :)

---

Change:

```
int measurement[];

```

to:

```
int * measurement;

```

and then in the constructor do:

```
measurement = new int [samples];

```

And check that measurement is not NULL, in case there is not enough memory.

---

Also, this is wrong in two ways:

```
// initialize the measurement array
for (int i = 0; i >= samples; i++) {
  measurement[i] = 0;

```

It should be:

```
// initialize the measurement array
for (int i = 0; i < samples; i++) {
  measurement[i] = 0;

```

You need to test less than, and you don't test equals (that would initialize one too many).

---

You should also have a destructor that frees the memory, ie.

```
delete [] measurement;

```

---

> When would this destructor come into play? How and when should I call it?

The destructor is automatically called when an instance of the class is destroyed. This is when you do things like free memory you allocated. You don't call it directly.

An example:

```
class Sensor
{
public:
  // constructor
  Sensor(int analogPin, int numSamplesInAverage, unsigned long mysampleRate);
  // destructor
  ~Sensor ();
  // call to update samples
  int update();

private:
  unsigned int sensorPin;
  unsigned long currentMillis;
  unsigned long oldMillis;
  unsigned long sampleRate; // milliseconds between samples
  int read_index;
  int total;
  int average_cts;
  int samples;
  int * measurement;
};

Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long mysampleRate)
  {
  sensorPin = analogPin;
  samples = numSamplesInAverage;
  sampleRate = mysampleRate;
  read_index = 0;
  total = 0;
  average_cts = 0;
  measurement = new int [samples];

  if (measurement == NULL)
    exit (1);  // can't continue

  // initialize the measurement array
  for (int i = 0; i < samples; i++) {
    measurement[i] = 0;
  }

}  // end of constructor

// destructor
Sensor::~Sensor ()
  {
  delete [] measurement;
  }  // end of destructor

```

---

> Can you please explain how these two line of code work `int * measurement` and `measurement = new int [samples];`

`int * measurement` creates a pointer to an int (called `measurement`). However pointers can also point to the start of an array (or indeed, to the middle of an array) of ints. So this variable will hold the start of your array of ints.

`measurement = new int [samples];` allocates the memory for this array - in this case "samples" lots of ints.

Once the memory is allocated you can treat the pointer as an array, eg.

```
measurement [5] = 42;

```

For more detail about this see So what is meant by the "equivalence of pointers and arrays" in C? and also Google: `pointer vs array`.

Also Google: `new` and `delete` with reference to the C++ language.

---
Tags: arduino-uno, programming, c++, analogread
---


title: Linking Arduino With Twitter

text:
# Question
Title: Linking Arduino With Twitter
My project is having Arduino with my WiFi shield connect to Twitter and look for any messages that other users have tweeted at me that contain a certain color, (I.E. @myTwitterHandle I want red) and then changes an RGB LED to become that color.

I have been searching online for different methods, and found a few different solutions which I could use as a starting point. However, these apparently call to an old Twitter API that is not supported anymore (support stopped mid 2013).

One solution I came across was to use node-red as well as MQTT. I am not too familiar with these programs.

Does anyone know how to have Arduino parse a twitter account for mentions containing certain strings and have it print to LED? Any help with be appreciated

# Answer
The new Twitter 1.1 API requires OAuth authorization over SSL, for which Arduino is under-powered.

You will need to write a proxy application, which would parse the tweets and then send a RGB color value to your Arduino.

You should split your project into three parts.

1. Retrieving tweets with the Twitter API.
You can get some library to do it for you.
2. Communicating with your Arduino.
Just try to send an arbitrary color to your Arduino over internet.
3. And finally joining first two pieces of code together.

And if you get stuck somewhere, you can always ask for help here on StackExchenge.
> 0 votes

---
Tags: arduino-uno, wifi
---


title: Basic Serial Transmission Protocol

text:
# Question
Title: Basic Serial Transmission Protocol
I have a small piece of code here that I hope to run on Arduino. Basically what this code is doing is, it takes a nibble from the user, appends a `startbit` to it, and transmits the code through a transmitter module. The receiver end receives the bits and checks if `startbit` is being received. If `startbit` is not being received, then it prints out whatever was transmitted. If `startbit` is received, then it doesn't print the startbit, just the nibble all in one line.

My question is: is it convention/clever to use the bool array or should I not do that? Second, is there a way to make my code more efficient? Where can I clean it up? Also, is my code legible or very convoluted?

```
#include <Arduino.h>
#include <WirelessComm.h>

int tx_pin;
int rx_pin;
WirelessComm::WirelessComm(int rxPin, int txPin)
{
    pinMode(rxPin, INPUT);
    tx_pin = txPin;
    rx_pin = rxPin;
}

int countDigit(long n)
{
    int count = 0;
    while (n > 0)
    {
        n /= 10;
        count++;
    }
    return count;
}

void getDigit(bool *data, long num)
{
    int cd = countDigit(num);
    long shift = 1;
    for (int i = 0; i < cd; i++)
    {
        data[i] = (num / shift) % 10;
        shift *= 10;
    }
}

int WirelessComm::writeTx(long nibble)
{
    int i;
    bool data[11]; // warning: I didn't check for buffer overrun!
    int32_t startBit = 110101L; // larger than 32767, so cannot be in int
    if(nibble != 0)
    {
        int sbLen = countDigit(startBit);
        for (int i = 0; i < (int)(sizeof(data) / sizeof(data[0])); i++)
            data[i] = 0;
        getDigit(data, startBit);
        getDigit(data + sbLen, nibble);
    }
    else
        return -1;

    for(i = 0; i < 10; i++)
    {
        if(data[i] == 1)
        {
            digitalWrite(tx_pin, HIGH);
        }
        else
        {
            digitalWrite(tx_pin, LOW);
        }

    }
    return 1;
}

int WirelessComm::readRx(long nibble)
{
    bool first = 0;
    bool second = 2; //initially set to some random value
    bool third = 2;
    bool fourth = 2;
    bool fifth = 2;
    bool sixth = 2;
    bool counter = 0;
    bool val = 0;
    while(true)
    {
        first = digitalRead(rx_pin);
        if(first == 1);
        {
            second = digitalRead(rx_pin);
            if(second == 1)
            {
                third = digitalRead(rx_pin);
                if(third == 0)
                {
                    fourth = digitalRead(rx_pin);
                    if(fourth == 1)
                    {
                        fifth = digitalRead(rx_pin);
                        if(fifth == 0)
                        {
                            sixth = digitalRead(rx_pin);
                            if(sixth == 1)
                            {
                                while(counter < 4)
                                {
                                    val = digitalRead(rx_pin);
                                    Serial.print(val);
                                    counter++;
                                }
                                Serial.println();

                            }
                            else
                                Serial.println(first);
                                first = digitalRead(rx_pin);
                        }
                        else
                            Serial.println(first);
                            first = digitalRead(rx_pin);
                    }
                    else
                        Serial.println(first);
                        first = digitalRead(rx_pin);
                }
                else
                    Serial.println(first);
                    first = digitalRead(rx_pin);
            }
            else
                Serial.println(first);
                first = digitalRead(rx_pin);
        }
        else
            Serial.println(first);
            first = digitalRead(rx_pin);
    }
}

```

# Answer
> 5 votes
What you are doing is called "bit-banging" (wikipedia link) but you have no guarantees about the timing of your bits.

In your `writeTx` routine you are changing `tx_pin` at some rate which depends on:

1. the clock speed of your MCU
2. the code that the C compiler generates

Moreover, the timing will be all screwed up if you happen to get an interrupt while sending the bits.

The same applies to your read routine.

The Arduino (really the Atmel MCU) has special hardware to perform both synchronous and asynchronous serial IO. The set up is rather complex because the hardware is very versatile and capable of a lot of different functions. In particular, it can deliver the bits at a specific baud rate for you so your code doesn't have to do it. It can also read in a serial stream and set a flag or invoke an interrupt when a complete word has been received.

This article can give you an idea of what the USART in an Atmel processor is capable of:

http://maxembedded.com/2013/09/the-usart-of-the-avr/

# Answer
> 3 votes
> So to clarify, SoftwareSerial uses bit-bang? How are you able to tell?

By reading the code. For example, this is how it reads 8 bits. It does a delay (which you don't) for the exact amount of time, and then reads the pin, and "ors" it into the variable which is the assembled byte.

```
// Read each of the 8 bits
for (uint8_t i=0x1; i; i <<= 1)
{
  tunedDelay(_rx_delay_intrabit);
  DebugPulse(_DEBUG_PIN2, 1);
  uint8_t noti = ~i;
  if (rx_pin_read())
    d |= i;
  else // else clause added to ensure function timing is ~balanced
    d &= noti;
}

```

---

And to write the 8 bits:

```
// Write each of the 8 bits
for (byte mask = 0x01; mask; mask <<= 1)
{
  if (b & mask) // choose bit
    tx_pin_write(HIGH); // send 1
  else
    tx_pin_write(LOW); // send 0

  tunedDelay(_tx_delay);
}

```

---

Your rather elaborate nested `if` just seems complete overkill, when you see how SoftwareSerial does it in half a dozen lines.

---

Another typo:

```
if(first == 1);

```

You don't want that semicolon.

---

> Second, is there a way to make my code more efficient?

Use loops, like SoftwareSerial does.

> Also, is my code legible or very convoluted?

Very convoluted.

> Where can I clean it up?

I suggest you browse through the SoftwareSerial library for ideas.

Meanwhile, HardwareSerial is available, so you don't need to write any of this. For that matter, SoftwareSerial is available too. If you are just doing it to learn, well and good.

---

You really should read about loops. Whenever I have to do something 8 times I have a loop of 8 (or even for "x" times, a loop of "x"). Unrolling into 8 different variables is just confusing and prone to errors. As you had, before you fixed it, doing `if(fourth = 1)` instead of `if(fourth == 1)`.

---
Tags: c++, wireless, project-critique
---


title: Arduino Pro Micro Analog Pinouts

text:
# Question
Title: Arduino Pro Micro Analog Pinouts
I have the Arduino Pro Micro and I would like to use all the **analog** pins that I can on it.

It currently looks like it has a total of **9 Analog pins** that can be used.

A0, A1, A2, A3, A6, A7, A8, A9 and A10.

However, I am unsure how to call these pins since all of those are also **digital pins**.

Would A0-A3 be defined as:

```
#define analog1 A0;
#define analog2 A1;
#define analog3 A2;
#define analog4 A3;

```

While the other pins would be this?:

```
#define analog5 4;
#define analog6 6;
#define analog7 8;
#define analog8 9;
#define analog9 10;

```

Then just call:

```
analogRead(analog1);
analogRead(analog2);
.....
analogRead(analog8);
analogRead(analog10);

```

Would that be the correct way of defining the 9 analog pins?

# Answer
Assuming you have the Pro Micro core, they are called A0, A1, A2, A3, A6, A7, A8, A9 and A10. There is no need to "special case" the others, since the pins are known as both.
> 4 votes

---
Tags: arduino-ide, arduino-leonardo, analogread, arduino-pro-micro
---


# Question
Title: How to fix baud rate when hardware capacity has a low limit?
I have a transmitter(simple 433 MHz transmitter) connected via digital pins on the Arduino. The receiver is connected to another arduino. Now, I kept that pin on HIGH for 1 second, and it transmits only 1000 ones. But I've seen different example transmitter sketches having baud rates of 1200, 9600, etc. So the situation is, when the transmitter is transmitting at maximum capacity(just HIGH for a whole second), it can only transmit 1000 ones.

I am able to read that it only transmits 1000 ones because my receiver just has a simple read function that reads and prints the data. and it prints 1000 ones every second. Give or take one or two. So when you specify a baud rate of 1200, is it useless? how will it transmit 1200 bits/sec? Does the baud rate actually increase the hardware limit or what exactly is going on? Can someone please provide me some insight into this? I'd be glad to clarify this question more if need be.

# Answer
> 1 votes
The transmitter you're using is very basic, and only transmits "on" and "off". As such it is *protocol-agnostic*. In order to use it effectively we use it with a protocol that uses "on" and "off" as its signalling, but also includes framing information so that we can know when the data flow starts and stops.

One such protocol is the UART protocol consisting of 1 start bit, 5 to 9 data bits, an even, odd, or no parity bit, and 1, 1.5, or 2 stop bits, all being generated at a specific rate. This rate is the "baud rate", and must match in both the sending device's and the receiving device's UART in order for them to communicate. This is true whether the devices are connected by a wire, an optical link, or a radio link.

The TX and RX pins on an Arduino are connected to a hardware UART which will handle the framing and signal generation for you. The hardware UART(s) can be accessed via `Serial` on non-USB-native Arduinos as well as `Serial1`, `Serial2`, and `Serial3` on Arduinos where they are present.

Additionally, `SoftwareSerial` can be used to generate a UART signal on arbitrary pins in software, but you're almost always better off using a hardware UART when possible.

---
Tags: communication, softwareserial
---


title: Arduino coding of producing frequency

text:
# Question
Title: Arduino coding of producing frequency
Im new here. Anyone that could give a code or sample that would generate I wanted to use a frequency in range of 35k-43kHz. Please help me.

# Answer
> 3 votes
The code below generates 38 kHz and modulates its duty cycle.

```
// Example of modulating a 38 kHz frequency duty cycle by reading a potentiometer
// Author: Nick Gammon
// Date: 24 September 2012

const byte POTENTIOMETER = A0;
const byte LED = 10;  // Timer 1 "B" output: OC1B

// Clock frequency divided by 38 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 38000L;

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

  // set up Timer 1 - gives us 38.005 kHz
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  }  // end of setup

void loop()
  {
  // alter Timer 1 duty cycle in accordance with pot reading
  OCR1B = (((long) (analogRead (POTENTIOMETER) + 1) * timer1_OCR1A_Setting) / 1024L) - 1;

  // do other stuff here
  }

```

# Answer
> 1 votes
use the 'tone' function: arduino tone function

example:

```
//tone(pinNumber, FrequencyInHertz);
tone(6, 35000); //generate a 35kHz tone on pin 6
delay(10);
tone(6, 43000); //generate a 43kHz tone on pin 6

```

# Answer
> -1 votes
This is meant to be a comment, but I can't put (pseudo) code in a comment.

A 40 kHz square wave? Simple:

```
for(;;){
   wait ( 1 / 2 * 40.000 );
   make pin high;
   wait ( 1 / 2 * 40.000 );
   make pin low;
}

```

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


# Question
Title: Enternal Analog Reference mode not compiling in Arduino + Intel Galileo Gen 2
I am trying to use external voltage reference in Intel Galileo gen 2 operating in Arduino mode.

So I created a setup code like this:

```
void setup() {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);

  // If you want to set the aref to something other than 5v
  analogReference(EXTERNAL); // use AREF for reference voltage
}

```

I selected the board as Intel Galileo Gen 2 in Tools option. When I compiled I am getting the following error:

```
LM35_temp_sensor.ino:21:19: error: 'EXTERNAL' was not declared in this scope

```

But when I change the board to Arduino Uno in Tools option, the program in compiling fine.

This means that Intel Galileo Gen 2 does not support external analog voltage reference?

# Answer
There is no such thing as an external analog reference on the Galileo. If you look at the block diagram that is on the Galiley Arduino.cc page you can clearly see that the Aref pin goes nowhere:

So no, it won't support the EXTERNAL analog reference function.
> 1 votes

---
Tags: arduino-galileo
---


title: Detect closed shutter

text:
# Question
Title: Detect closed shutter
I want to controll some ambient lights in my living room.

Therefore, I got some 433mhz outlets which can be turned on or off with an remote, a 433mhz transmitter and receiver on the arduino.

The arduino receives the remotes signals and knows which lamp has which state and will turn any lamp off at specific times.

Now I want to turn on the lights automatically when I close the shutter, but I have no idea how I could do this.

A light sensor behind the window won't do the job. I don't want to turn on the lights when it get's dark, but when the shuhtter get's closed.

Edit: What came to my mind first was an light sensor inside the window, facing outside, and a IR LED. I'd attach some tinfoil to the inside of the shutter to return the IR light, which the sensor will notice. But maybe the're are some simpler solutions? Also, the tinfoil would fall off quickly...

# Answer
> 1 votes
I would go for a normally open read switch (should cost \>$0.1) and a magnet on the shutter (again should cost \>$0.1). There are formulas to work out the distance that the reed switch will operate at, and it depends on the magnet, but the common ones are about 40mm. (If you can wait 2 weeks for delivery you can get the parts off AliExpress.com)

---
Tags: remote-control
---


# Question
Title: Connect GPS module with GPS antenna SIM39EA to Arduino Uno
I bought a GPS module with GPS antenna SIM39EA online.

The manual for the GPS module is here:

http://www.vis-plus.ee/pdf/SIM39EA\_Hardware\_Design\_V1.00.pdf

I have an Arduino board. It has 3 ground pin, one Vcc and two input/output pin.

I want to know how can I connect this module to Arduino GPS module and get GPS coordinates?

# Answer
> 0 votes
Your data comes back via the GPS's UART port.
Use the softserial library to create a second serial port on your Arduino (means you can still use the normal serial to read the console).

Then write a program that sucks data from the GPS and squirts it out of the Arduino serial port back to your PC using printf.

I only had a quick flick through and didn't see the default serial speed, so start with 9600 and experiment.

What should come out is probably a line of comma separated values which is in NEMA format. Google for the specification and you will be able to find out the bits of interest.

Hope that helps.

---
Tags: arduino-uno, hardware, gps
---