# Question
Title: Defining an NFC tag as NDEF using the Arduino Uno and the PN532 NFC module
I bought a bunch of blank Mifare Classic NFC cards and I'd like to write NDEF records to them using my Arduino Uno. When I read them using my Uno and a PN532 NFC module using Don's NDEF library however, it tells me they're not NDEF formatted.

Is there any way to define my NFC tags as NDEF using just the PN532 module and an Arduino Uno? (My Android phone doesn't support NFC.)

# Answer
I found the answer to my own question right after posting it, while going through the examples included in the library above:

The library contains an example named "FormatTag" which does exactly what I was looking for.
> 0 votes

---
Tags: arduino-uno, rfid
---


# Question
Title: Controlling Enable Function on MicroStepper Driver
I'm having trouble using the ENABLE pin on my microstepper driver, I'm not sure of the exact model but it looks exactly like the one pictured here

Microstepper Driver

Here's my code:

```
#define MAX_LEN 8
#define MIN_INCREMENT 0.5
#define LIMIT_SWITCH 3
#define ENABLE 10
float buoyancymass = 4401.425;
float centrebuoyancy = 14.164;
float mainarm = 14.3;
float nosearm = 1.8;
float adc = 11.4;
float meanadc = 22.65;
volatile byte enable_state = LOW;

#include <Stepper.h>

const int stepsPerRevolution = 1600;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0;         // number of steps the motor has taken
float stepinch = 0.00524; // 1 step = x"

void setup() {
  // initialize the serial port:
  Serial.begin(9600);
  pinMode(LIMIT_SWITCH, INPUT_PULLUP);
  pinMode(ENABLE, OUTPUT);
  //enable motor
  digitalWrite(ENABLE, enable_state);
  //interrupt
  attachInterrupt(digitalPinToInterrupt(LIMIT_SWITCH), limitbrake, FALLING);
  // set the speed
  myStepper.setSpeed(30);
}

void limitbrake() {
  digitalWrite(ENABLE, !enable_state);
}

```

The problem I'm noticing is that when I set the `pinMode(ENABLE,OUTPUT);` my stepper doesn't draw current and therefor, doesn't drive. This occurs regardless of whether I set my `enable_state` to HIGH or LOW.

Funny enough, when I set it to `pinMode(ENABLE,INPUT);` it does draw current and drive the motor, but unfortunately my limit switch which I've attached an interrupt to doesn't disable the motor when its pressed.

Before you ask, I've tested the enable pin on my driver and my limit switch circuitry in other programs and they both work. I'm just having trouble with putting it together.

Here is the rest of my code if you were wondering.

```
float calc_margin(float pos, float mass) {
  // calculate margin
  Serial.print("Distance: ");Serial.println(pos);
  float batterymoment = mass*pos;
  Serial.println(batterymoment);
  float totalmass = mass + 12404;
  Serial.println(totalmass);
  float totalmoment = 149650+batterymoment;
  Serial.println(totalmoment);
  float buoyancymoment = buoyancymass*centrebuoyancy;
  Serial.println(buoyancymoment);
  float wheelmoment = totalmoment - buoyancymoment;
  Serial.println(wheelmoment);
  float wheelweight = totalmass - buoyancymass;
  Serial.println(wheelweight);
  float cgwheels = wheelmoment/wheelweight;
  Serial.println(cgwheels);
  float maindistance = mainarm - cgwheels;
  Serial.println(maindistance);
  float nosedistance = cgwheels - nosearm;
  Serial.println(nosedistance);
  float mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  Serial.println(mainmass);
  float nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  Serial.println(nosemass);
  float mainmoment = mainmass*mainarm;
  Serial.println(mainmoment);
  float nosemoment = nosemass*nosearm;
  Serial.println(nosemoment);
  float netmoment = buoyancymoment+(mainmoment*2)+(nosemoment*2);
  Serial.println(netmoment);
  float netcg = netmoment/totalmass;
  Serial.println(netcg);
  float staticmargin = adc - netcg;
  Serial.println(staticmargin);
  float answer = staticmargin/meanadc;
  Serial.println(answer);
  float percentage = answer*100;
  Serial.print(percentage); Serial.println("%");
  float result = answer;
  return result;
}

boolean check_margin(float test_margin) {
  if (test_margin > -0.04 && test_margin < -0.02)
    return true;
  return false;
}

float armcalc(float mass) {
  for(float x=0;x<MAX_LEN;x+=MIN_INCREMENT) {
    // calculate margin
    float margin = calc_margin(x,mass);
    if (check_margin(margin)) {
      return x;
    }
  }
  return -1;
}

float stepcalc(float arm){
  int arminch = arm*12;
  float numberofsteps = arminch/stepinch;
  int result = numberofsteps;
  Serial.print("Calculated steps: "); Serial.println(result);
  return result;
}

void loop() {
  // read input
  Serial.println("Enter mass: ");
  while (!Serial.available());
  float mass = Serial.parseFloat();
  float arm = armcalc(mass);
  if (arm < 0) {
    // Error message
    Serial.println("Error!");
    return;
  }
  Serial.print("Arm distance is "); Serial.println(arm);
  // step
  const int steplength = (int) stepcalc(arm);
  Serial.print("Number of steps is "); Serial.println(steplength);
  myStepper.step(-steplength);

  while(1);

}

```

# Answer
> 1 votes
These drivers differ from the H-Bridge-design described here. You don't need to generate pulses for the coils, as you would do with a classic H-Bridge.

1. Connect your motor to `A+`, `A-`, `B+`, `B-` (a is one coil, b the other)
2. Connect Power (guess 12+ volts, mine take up to 48V) to `GND` and `V+`
3. Either connect 5V to `ENA+(+5V)` or a free arduino Pin and `ENA-(ENA)` to GND. This pin enables/disables the driver. If no input is present at this pin, the driver will not work.
4. Connect `DIR+(+5V)` to a free arduino pin and `DIR-(DIR)` to `GND`. This pin controls the direction. `HIGH` makes the motor turn right, while `LOW` on this pin makes the motor turn left.
5. Connect `PUL+(+5V)` to a free arduino pin and `PUL-(PUL)` to `GND`. This pin controls the speed. The more pulses/second one applies, the faster the motor turns. (Up to a limit, of course).

Sketch should be easy.

**Plus**: You could turn around the control connections, by hardwiring all `+5V` pins to 5V and use `INPUT_PULLUP` to switch the current flow on the negative lines. I know that these drivers are optical isolated and draw as little as 10 mA from a pin, if at all. So you should be safe.

---
Tags: arduino-uno, interrupt, stepper
---


title: Breaking a switch case from an ISR

text:
# Question
Title: Breaking a switch case from an ISR
I'm struggling with something. My CPU sits in a switch case state machine like this:

```
switch(expression) {

   case constant-expression_1  :
      statement(s);
      break; /* optional */

   case constant-expression_2  :
      statement(s);
      break; /* optional */

   /* you can have any number of case statements */
   default : /* Optional */
   statement(s);
}

```

I have an interrupt that occurs on a button press. In the interrupt, I change the switch expression to the case I want to go next, like this:

```
void ISR(void){
   expression = constant-expression_2;
}

```

After the interrupt has been handled, I want the CPU to return directly to the case being switched to, and to not continue where it left off.

Does anyone have any good ideas on how to implement this, if it's possible? I'd prefer to not have to wait for the code to finish what was happening in the previous case before going to the one being switched to.

Thanks in advance!

# Answer
It is certainly possible, although I do not think there is any *clean* way of doing it...

Here is an idea that **may** work: right before the switch statement, you save the current context with the `setjmp()` function. Then, in the ISR, you restore that context with `longjmp()`. This is kind of like a goto statement that works across functions:

```
#include <setjmp.h>

jmp_buf env;

ISR(FOO_vect) {
    expression = ...;
    longjmp(env, 1);  // go to start of loop
}

void loop() {
    setjmp(env);  // landing point from ISR exit
    switch (expression) {
        ...
    }
}

```

Notice that the normal exit sequence of an ISR (the `reti` instruction) re-enables the interrupts. Since we are skipping this exit sequence, ~~we have to enable them explicitly upon return from `setjmp()`~~ interrupts are re-enabled not by the `reti` instruction but by `longjmp()` restoring the CPU's status register.

**Warning**: This is a (very dirty) hack that I have *not tested*. If I were to use this trick, I would first:

1. Carefully examine the generated assembly to convince myself it does the right thing.
2. Test, test, test...

In case of problems, debugging this may be harder than just testing the expression inside every slow function you have.

**Addendum**: Although I am saying that there is no clean way of doing what you intend, there certainly is a clean way of achieving the same end result: just make sure your switch statements return fast. My preferred way of doing this would be to make sure no function ever waits. For example:

* A routine reading sensors would not wait for them to respond. Instead, it would return immediately if no reading is available. If a reading *is* available, it would retrieve it, send a query to the next sensor in the list, then return.
* A communication routine would not wait for complete messages. Instead, it would return immediately if no byte is available. If a byte is available, it would buffer it and return. Unless it's the last byte of a complete message, in which case it would process the message.

Obviously this could require a heavy refactoring of your code, probably using finite state machines (see for example the tutorials here and here). It may be easier to just test whether the expression has changed inside every busy-wait loop you have, as recommended by Gerben's and Nick's answers.
> 0 votes

# Answer
Most of the time this isn't a problem, because code normally runs pretty fast. The problem, most of the time, is the use of `delay`s. What I did was use my own delay function that checks if the expression has changed, and if so, immediately returns.

Below is my code. I had to modify it a bit, so it might not work out of the box, but will give you the idea as to how.

```
volatile byte expression;
volatile boolean expressionChanged = false;

switch(expression) {

   case constant-expression_1  :
      statement(s);
      myDelay(1000);
      statement(s);
      break; /* optional */

   case constant-expression_2  :
      statement(s);
      myDelay(500);
      statement(s);
      break; /* optional */

   /* you can have any number of case statements */
   default : /* Optional */
      statement(s);
}

void myDelay(int ms)
{
    uint32_t start = micros();
    while (ms > 0 && !expressionChanged)
    {
        //yield();not implemented in arduino
        if ( (micros() - start) >= 1000)
        {
            ms--;
            start += 1000;
        }
    }
}

void ISR(void){
   expression = constant-expression_2;
   expressionChanged = true;
}

```
> 1 votes

# Answer
First, put your major processing into functions. That looks better anyway. eg.

```
switch(expression) {

   case constant-expression_1  :
      function1 ();
      break; /* optional */

   case constant-expression_2  :
      function2 ();
      break; /* optional */

   /* you can have any number of case statements */
   default : /* Optional */
      function_default ();
}

```

Now inside your functions do a `return` if you notice the expression has changed. This will get you out of any number of nested loops. For your 30 sensors, for example, you can now have a loop.

```
void function1 ()
  {
  for (int i = 0; i < 30; i++)
    {
    if (expression_changed)
       return;
    // take sensor reading
    }
  }  // end of function1

```

Also, as Gerben suggested, replace any `delay` calls with a function that does the delay, however which ends early if the expression changes. It can return a boolean to let you know this happened. eg.

```
boolean myDelay(int ms)
  {
    uint32_t start = micros();
    while (ms > 0)
    {
        if (expression_changed)
           return true;   // early return
        if ( (micros() - start) >= 1000)
        {
            ms--;
            start += 1000;
        }
    }
  return false;   // normal return
  }

```

Now any function that needs delays can use that, like this:

```
void function2 ()
  {
  do_something ();
  if (myDelay (1000))
     return;   // bail out
  do_something_else ();
  }  // end of function1

```

> My problem is, one of my cases includes a communication transceiver method, which can take a lot of time to get through

There must be logical spots where you can just test the expression and do a `return` (preferably cleaning up anything that needs it) when required.
> 1 votes

---
Tags: interrupt, button, isr
---


# Question
Title: Options for communicating between Arduinos
I'm looking to communicate between ~5-10 Arduinos to send commands and data between them. By "Arduino" I mean the ATmega328 programmed using the Arduino programming framework.

Each of the devices would be on the same PCB.

I know I2C and SPI can communicate to some degree, but that they're really meant for peripherals devices connected to a micro controller rather than connecting multiple micro controllers to each other, and that they usually only send a few bytes of data at a time. On the other hand I know LCD displays can be driven using them, and I'd imagine there's a lot of data being transferred in those cases.

Is there a something like I2C (multi-master, multi-slave, single-ended, serial computer bus) for communicating between micro controllers? Allowing each device to send data to each other device unsolicited. For example, if a switch was pressed on device A, it would tell device B, without having device B ask A all the time if a switch was pressed. and vice versa.

**Edit**: I found some libraries that may do what I want with RS-485. Is this the only viable option for ~1k bps transmission between 5-10 devices? I would imagine TCP/IP over Ethernet would work as well, but that seems like too much. Are there any I2C libraries that allow sending that amount of data between only master devices?

# Answer
There are a number of concepts that can help you realize your dream. I can't, in the space of this answer, tell you exactly how to implement what you want, but I can show you the concepts that will help you to implement it.

First off there's the concept of the *bus master*. This isn't necessarily the device that instantiates communication - instead this is the device that *owns* and *controls* the bus.

When a device that isn't the bus master wants to communicate on the bus it first asks permission from the bus master. The old Z80 (well, I say "old", but they are still in use in many forms today) used this concept to allow other chips to use the data and address buses. It consists of two signals - BUSRQ and BUSACK. A device first looks to see if either of BUSRQ or BUSACK are active, and if neither are it then activates BUSRQ. If the bus master is willing to give up the bus to the other device (it's not using it at that moment) it activates BUSACK and the other device then knows that it can use the bus. Nothing else can use it until BUSRQ and BUSACK have both been released. Nice and simple and elegant.

But not perfect. If two devices both decide to ask for the bus at the very same instant you get a *collision*. This is a common problem amongst shared bus systems like this, and causes untold problems unless you know how to handle it properly.

Enter the concept of *listen-while-you-talk*. This involves the device that is sending on the bus also listening to what is being sent on the bus through a separate receiver. It then can know if what it sent on the bus is what actually ended up on the bus. For instance if two devices talk at the same time and one sends `10011001` and the other sends `11001100` the result that appears on the bus might actually end up as something else, such as `11011101` or maybe `10001000` depending on how the bus signals are created. So if you know what you sent got corrupted you can now do something about it.

Next concept: *backing off*. This is where both the senders wait for a short period and try and send again. As long as they both delay for a different amount of time the first one to try will get the bus and be able to communicate. But how do you guarantee that they will both delay for different times? You may think the answer is simple: use a random number, like `rand()` or `random()`. But that is also problematic:

Another concept: *The **pseudo** random number generator*

The Arduino doesn't generate random numbers. It just uses a complex mathematical formula to create a sequence of numbers that, to us, *look* random. They aren't though. Write a small program to print 10 random numbers through serial and run it multiple times (press the reset button). You will find the same "random" numbers in the same order every time. Try it on another Arduino and you get the same numbers again. Always the same.

So what to do? The answer is called *seeding* the random number generator. The next number generated by `rand()` et al depend on the number that had been generated last. So change the *first* number and all the rest of the numbers will change. However, you have a catch-22 situation. You need a random number to seed the random number generator to make it random to be able to generate a random number to seed the random number generator... ad infinitum. You see where that's going? You can't seed from `rand()` since `rand()` isn't random until you have seeded from a random source. So you need to find a random source.

And that's not an easy task. The best source of *entropy* as it's known is *white noise*. This can be generated in a number of ways with a number of different circuits - from the breakdown of a diode junction to very high gain amplification of the thermal fluctuations in a resistor.

All are quite complex for what you want really, but there is a simpler, if slightly less random, method - read an analog input that isn't connected to anything. It won't have as much of a range as a proper entropy generator, but it should provide enough randomness to give a reasonable chance of each device getting a different seed.

Another useful concept is the interrupt.

This is good in a situation where you don't want the complexity of a multi-master bus with all the collisions etc. You have a single master that does all the work on the bus, and when a slave device has something important to say it nudges the master with an interrupt. The master then goes "Yes? What do you want?" to which the slave replies "Someone pressed my button".

That way the master isn't constantly polling the slave to see if the button has been pressed. It is often used in bus arrangements like SPI and there are many chips, such as IO expander chips, that can assert an interrupt when one of their input pins changes state.

But if you have 20 devices does that mean you have 20 interrupt pins? Not necessarily. New concept: *wired OR*.

It's perfectly possible to have multiple different slaves all using the same interrupt pin. The pin is normally held HIGH with a resistor (it could be an internal pullup resistor) and each slave has an *open drain* output connected to that pin. An open drain output, when "off", is not connected to anything - it's like the pin is in input mode (in fact it can be emulated on chips that don't have open drain by switching between input and output mode). When the output is "on" it connects the pin to ground, pulling down the IO pin, just like a button would.

It's then up to the master to make its way round the slaves that it knows are attached to that interrupt to see who needs attention. You can of course implement a number of different interrupt pins with different groups of slaves on each one - maybe a high priority one with just one device, and lower priority ones with multiple devices on each, for example.

The same concept of *wired OR* and *open drain* can be used for allowing multiple devices to all share the same physical wires. That is exactly how I2C works - the two bus lines are pulled up by resistors and the devices on it use open drain outputs to pull the line low to release it back to high to create the different logic levels. If two devices both pull it low together it will just be low. Without the open drain method if you had one device outputting a 1 and another outputting a 0 you would basically get a short circuit between the two and you would end up damaging chips.

And then of course you have the concept of synchronous versus asynchronous communication, but that is an entirely different kettle of fish. Simply said though, protocols with a clock, like SPI and I2C, which have a master generating that clock, are synchronous. Protocols like the UART and RS-232, RS-485, etc are asynchronous - they rely on both ends agreeing on how fast data is being sent (baud rate) so they know how to interpret the signals as they arrive.
> 2 votes

# Answer
Check out PJON - https://github.com/gioblu/PJON. It's a one-wire alternative.
> 2 votes

# Answer
In addition to @Majenko's excellent answer, you need to have a think about what you are communicating.

It sounds like you want to communicate a single bit - perhaps you can get away with individual pins? If you have a master, and up to 13 slaves, you could have one pin on the master connected to one pin on each of the slaves (via a resistor). If slave A wanted to signal it's signal, it would raise the pin; the master would then be able to poll each pin in turn, to work out who said what.
> 0 votes

# Answer
Another option is SPI.

SPI can be used with any number of devices, in a ring. It was explained to me as follows: any participant can toggle the clock line 8 times, to move the byte in it's own buffer, into the next device's buffer, in a ring; the device gets a byte from the previous device. If someone else toggles the clock 8 times, you get notified that the new byte is ready (this is done in hardware).

You need to think carefully about a protocol for this - an "address", "length", "command", and then any number of parameters. The sender sends the "address" byte, sets the "length" byte in the buffer, and holds the rest ready. The next device has received the "address" byte, and sees if it is the intended recipient. If it is not, it notes this down, and pushes the chain round, notes the length, and waits until someone ELSE has pushed that many bytes around. If it IS yours, read the rest of the data, pushing the data around, and blanking it as you go (to stop it coming back). A blank address (e.g. 0) would be reserved, meaning "don't do anything with this, wait for someone else to push it around, and read the next byte as the next address". All devices would need to initialize to 0 on startup.

If you need to set addresses dynamically, set a special byte "all stations", with a command which means "your device number is X, and tell the next device it's device number is X+1". Someone would need to initiate this, of course.

You also run the risk of collisions, if two devices start sending at the same time, or if something doesn't relay what it's supposed to (e.g. a chip is powered down). You need to think about how you're going to detect/recover from this.
> 0 votes

---
Tags: communication
---


# Question
Title: Can a 9V battery be used as a backup power supply (to Arduino Uno) while plugged directly into Vin and ground?
Sorry if this has been asked before, but I've read tons of threads and it seems the answer is only implied on a couple of occasions.

I'm an electrical noob, but I understand that a 9v battery plugged into a wall wort with a diode would serve as a battery backup if the power was cut from the wall wort. I also understand that Vin on an arduino already has a diode to do this.

I'm currently powering a temp/humidity that is dumping data into MySQL using a standard A-B USB cable and 5V DC USB power supply. I'd like to incorporate a 9V battery plugged into Vin and ground, so that if DC power turns off, I can dump the data onto the SD card instead (since my MySQL server may or not be running during an outage).

# Answer
My problem with that is that the other side of the diode on the Arduino is normally powered up. So for example if you have a 12V supply in the power jack you'll have 11.3V at Vin (because of the diode drop). Thus you are pumping 11.3V into your 9V battery which won't be designed to handle it. It will probably get hot and explode.

You would need *another* diode specifically between the battery and Vin. And make sure that Vin is at least 10V so that the normal mains power does not charge the battery.

Bear in mind a 9V battery doesn't have much capacity. With the power LED on, taking sensor readings, and sending data via Ethernet (if that is what you are doing) you may have only bought yourself 15 minutes.

I have a post about a temperature and humidity sensor which runs all the time from 3 x AA batteries. I think the batteries need replacing about every two years. The data is written to an SD card which you remove and plug into your computer when you want to.

---

> when you have 9V hooked up to Vin and 5V coming in from the USB, it will use power from the 9V battery

Looks like I misread the question. @mwwalk is quite right. If you supply more than 6.6V through Vin then the circuitry switches the USB off. See here:

Vin is provided by the power jack (after a diode which drops it by 0.7V) - see blue ellipse. In any case (power jack or not) Vin goes through a voltage divider (two 10k resistors to the left of the red circle). This is compared to the output of the 3.3V voltage regulator. Therefore `GATE_CMD` is HIGH if Vin exceeds 6.6V. This turns **off** the MOSFET (green circle) and disconnects the USB power.
> 3 votes

# Answer
No, when you have 9V hooked up to Vin and 5V coming in from the USB, it will use power from the 9V battery, not usb and the battery will quickly be depleted.
> 3 votes

---
Tags: power, ethernet, sd-card
---


# Question
Title: MQ135 Air Quality Sensor Signal Amplifier needed? Higher Quality Sensor?
I am trying to strengthen the signal from my MQ135 air quality sensor so it can detect aerosols from 3 feet away, as, currently as it stands the resolution is pathetic, it only blips from 0.21 to 0.58 when you practically insert the sensor into the nozzle of a bottle full of vinegar/rubbing alcohol.

It would be ideal if you could guide me as to what sort of signal amplifier to buy to strengthen the signal coming from this board?

Alternatively: Could I increase the sensitivity of this sensor?

I'd like to plot this to a graph at some point, so I will be working on an ASP.NET app that tells me if there are any aerosols in my room or not.

Here's the code:

```
/*
  Graph

 A simple example of communication from the Arduino board to the computer:
 the value of analog input 0 is sent out the serial port.  We call this "serial"
 communication because the connection appears to both the Arduino and the
 computer as a serial port, even though it may actually use
 a USB cable. Bytes are sent one after another (serially) from the Arduino
 to the computer.

 You can use the Arduino serial monitor to view the sent data, or it can
 be read by Processing, PD, Max/MSP, or any other program capable of reading
 data from a serial port.  The Processing code below graphs the data received
 so you can see the value of the analog input changing over time.

 The circuit:
 Any analog input sensor is attached to analog in pin 0.

 created 2006
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe and Scott Fitzgerald

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Graph
 */

void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
}

void loop() {
  // send the value of analog input 0:
  Serial.println(analogRead(A0));
  // wait a bit for the analog-to-digital converter
  // to stabilize after the last reading:
  delay(20);
}

/* Processing code for this example

 // Graphing sketch

// This program takes ASCII-encoded strings
// from the serial port at 9600 baud and graphs them. It expects values in the
// range 0 to 1023, followed by a newline, or newline and carriage return

// Created 20 Apr 2005
// Updated 24 Nov 2015
// by Tom Igoe
// This example code is in the public domain.

import processing.serial.*;

Serial myPort;        // The serial port
int xPos = 1;         // horizontal position of the graph
float inByte = 0;

void setup () {
  // set the window size:
  size(400, 300);

  // List all the available serial ports
  // if using Processing 2.1 or later, use Serial.printArray()
  println(Serial.list());

  // I know that the first port in the serial list on my mac
  // is always my  Arduino, so I open Serial.list()[0].
  // Open whatever port is the one you're using.
  myPort = new Serial(this, Serial.list()[0], 9600);

  // don't generate a serialEvent() unless you get a newline character:
  myPort.bufferUntil('\n');

  // set inital background:
  background(0);
}
void draw () {
  // draw the line:
  stroke(127, 34, 255);
  line(xPos, height, xPos, height - inByte);

  // at the edge of the screen, go back to the beginning:
  if (xPos >= width) {
    xPos = 0;
    background(0);
  } else {
    // increment the horizontal position:
    xPos++;
  }
}

void serialEvent (Serial myPort) {
  // get the ASCII string:
  String inString = myPort.readStringUntil('\n');

  if (inString != null) {
    // trim off any whitespace:
    inString = trim(inString);
    // convert to an int and map to the screen height:
    inByte = float(inString);
    println(inByte);
    inByte = map(inByte, 0, 1023, 0, height);
  }
}

*/

/* Max/MSP v5 patch for this example
 ----------begin_max5_patcher----------
1591.3oc0YszbaaCD9r7uBL5RalQUAO3CvdyS5zVenWZxs5NcfHgjPCIfJIT
RTxj+6AOHkoTDooroUs0AQPR73a+1cwtK3WtZxzEpOwqlB9YveAlL4KWMYh6
Q1GLo99ISKXeJMmU451zTUQAWpmNy+NM+SZ2y+sR1l02JuU9t0hJvFlNcMPy
dOuBv.U5Rgb0LPpRpYBooM3529latArTUVvzZdFPtsXAuDrrTU.f.sBffXxL
vGE50lIHkUVJXq3fRtdaoDvjYfbgjujaFJSCzq4.tLaN.bi1tJefWpqbO0uz
1IjIABoluxrJ1guxh2JfPO2B5zRNyBCLDFcqbwNvuv9fHCb8bvevyyEU2JKT
YhkBSWPAfq2TZ6YhqmuMUo0feUn+rYpY4YtY+cFw3lUJdCMYAapZqzwUHX8S
crjAd+SIOU6UBAwIygy.Q1+HAA1KH6EveWOFQlitUK92ehfal9kFhUxJ3tWc
sgpxadigWExbt1o7Ps5dk3yttivyg20W0VcSmg1G90qtx92rAZbH4ez.ruy1
nhmaDPidE07J+5n2sg6E6oKXxUSmc20o6E3SPRDbrkXnPGUYE.i5nCNB9TxQ
jG.G0kCTZtH88f07Rt0ZMMWUw8VvbKVAaTk6GyoraPdZff7rQTejBN54lgyv
HE0Ft7AvIvvgvIwO23jBdUkYOuSvIFSiNcjFhiSsUBwsUCh1AgfNSBAeNDBZ
DIDqY.f8.YjfjV1HAn9XDTxyNFYatVTkKx3kcK9GraZpI5jv7GOx+Z37Xh82
LSKHIDmDXaESoXRngIZQDKVkpxUkMCyXCQhcCK1z.G457gi3TzMz4RFD515F
G3bIQQwcP3SOF0zlkGhiCBQ1kOHHFFlXaEBQIQnCwv9QF1LxPZ.A4jR5cyQs
vbvHMJsLll01We+rE2LazX6zYmCraRrsPFwKg1ANBZFY.IAihr8Ox.aH0oAL
hB8nQVw0FSJiZeunOykbT6t3r.NP8.iL+bnwNiXuVMNJH9H9YCm89CFXPBER
bz422p8.O4dg6kRxdyjDqRwMIHTbT3QFLskxJ8tbmQK4tm0XGeZWF7wKKtYY
aTAF.XPNFaaQBinQMJ4QLF0aNHF0JtYuHSxoUZfZY6.UU2ejJTb8lQw8Fo5k
Rv6e2PI+fOM71o2ecY1VgTYdCSxxUqLokuYq9jYJi6lxPgD2NIPePLB0mwbG
YA9Rgxdiu1k5xiLlSU6JVnx6wzg3sYHwTesB8Z5D7RiGZpXyvDNJY.DQX3.H
hvmcUN4bP1yCkhpTle2P37jtBsKrLWcMScEmltOPv22ZfAqQAdKr9HzATQwZ
q18PrUGt6Tst2XMCRUfGuhXs6ccn23YloomMqcTiC5iMGPsHsHRWhWFlaenV
XcqwgCQiGGJzptyS2ZMODBz6fGza0bzmXBj7+DA94bvpR01MffAlueO7HwcI
pWCwmzJdvi9ILgflLAFmyXB6O7ML0YbD26lenmcGxjVsZUN+A6pUK7AtTrPg
M+eRYG0qD9j4I7eEbco8Xh6WcO.or9XDC6UCiewbXHkh6xm5LiPEkzpJDRTu
mEB44Fgz4NCtJvX.SM1vo2SlTCZGAe7GZu6ahdRyzFOhYZ+mbVVSYptBw.K1
tboIkatIA7c1cTKD1u.honLYV04VkluHsXe0szv9pQCE9Ro3jaVB1o15pz2X
zYoBvO5KXCAe0LCYJybE8ZODf4fV8t9qW0zYxq.YJfTosj1bv0xc.SaC0+AV
9V9L.KKyV3SyTcRtmzi6rO.O16USvts4B5xe9EymDvebK0eMfW6+NIsNlE2m
eqRyJ0utRq13+RjmqYKN1e.4d61jjdsauXe3.2p6jgi9hsNIv97CoyJ01xzl
c3ZhUCtSHx3UZgjoEJYqNY+hYs5zZQVFW19L3JDYaTlMLqAAt1G2yXlnFg9a
53L1FJVcv.cOX0dh7mCVGCLce7GFcQwDdH5Ta3nyAS0pQbHxegr+tGIZORgM
RnMj5vGl1Fs16drnk7Tf1XOLgv1n0d2iEsCxR.eQsNOZ4FGF7whofgfI3kES
1kCeOX5L2rifbdu0A9ae2X.V33B1Z+.Bj1FrP5iFrCYCG5EUWSG.hhunHJd.
HJ5hhnng3h9HPj4lud02.1bxGw.
-----------end_max5_patcher-----------

 */

```

# Answer
```
int sensorValue;
int pin8 = 8;
void setup()
{
  Serial.begin(9600);
  pinMode(pin8, OUTPUT);

  }

  void loop()
  {
    sensorValue = analogRead(0); // read analog input pin 0
    Serial.print(sensorValue, DEC); //prints the value read
    Serial.println("ppm");
    if (sensorValue > 500) {
      //Activate digital output pin 8 - the LED will light up
      digitalWrite(pin8, HIGH);
    }
    else
    {
      // Deactivate digital output pin 8 - the LED will not light up
      digitalWrite(pin8, LOW);

    }
    delay(50);

}

```
> 1 votes

---
Tags: arduino-uno, sensors, temperature-sensor
---


title: How do I give the ENTER keypress?

text:
# Question
Title: How do I give the ENTER keypress?
I have a Teensy set up as a keyboard, joystick, and I'm giving keyboard commands. Letter and number keys are going fine. But when I try sending ENTER, I get some extra code in my Linux terminal:

```
$ 16424
16424: command not found

```

the code I have to give the ENTER key goes like this:

```
void setup() {
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  // read the digital inputs and set the buttons
  Joystick.button(1, digitalRead(0));
  Serial.println(digitalRead(0));
  if(digitalRead(0)==0){
    Keyboard.println(KEY_ENTER);
  }
  delay(50);
}

```

where is this "16424" coming from, and how do I send an ENTER keypress? I am using a Teensy 2.0, on Linux, with Arduino IDE 1.6.7.

# Answer
You can't just "print" a key like that. You use `print` for sending text.

When you use `println` it sends an enter key along with your text, so you can do :

```
Keyboard.println("ls -al");

```

and it will send the text `ls -al` and press enter for you.

If you want to do it in the 'raw' way you will need to press and then release the key:

```
Keyboard.press(KEY_ENTER);
Keyboard.release(KEY_ENTER);

```
> 4 votes

---
Tags: teensy, keyboard, terminal
---


title: Make LED blink using AVR assembly

text:
# Question
Title: Make LED blink using AVR assembly
I have an ATmega328P Arduino and am trying to make the LED blink using assembly without any additional includes. The goal is to have it blink for 1 second on, then 1 second off, however, it blinks incredibly quickly and is barely perceptible. Am I doing something incorrectly?

```
; DDRB       = 0x04
; PORTB      = 0x05
; TCCROB     = 0x25
; TCNT0      = 0x26
; 0b00000000 = OFF
; 0b00100000 = ON

setup:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x04, r16           ; Set DDRB to output
    out 0x05, r16           ; Set PORTB to ON
    ldi r16, 0b00000101     ; Set r16 with prescaler 1024 value
    out 0x25, r16           ; Set the TCCROB to 1024
    ldi r20, 0              ; Reset r20
    ldi r21, 1              ; Hold value 1 to increment r20
loop:
    in r17, 0x26            ; Read the timer
    cpi r17, 128            ; Check to see if the timer is halfway done (1/2 second, max 255 value)
    brbc 0, increment       ; If r17 <= 128 (max 255 val before resets to 0), invert current LED state
    rjmp loop
increment:
    adc r20, r21            ; Add r21 (1) to r20 (with carry)
    brbs 0, reset           ; If the carry branch is set, reset the register
    rjmp loop               ; Otherwise, run the clock
reset:
    ldi r20, 0              ; Reset the delay register
    cpi r16, 0b00000000     ; Check if r16 is set to LED OFF
    brbs 1, switchon        ; If it is, change it to ON
    ldi r16, 0b00000000     ; Otherwise, change it to OFF
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock
switchon:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock

```

# Answer
> 2 votes
There is a bug with the logic of your program: once TCNT0 gets larger than 128, it will continue to be larger than 128 for quite some time... during which time you are continuously incrementing your r20 counter. The simplest fix would be to reset TCNT0 right after the `increment` label, with something like `out TCNT0, zero_reg`. Then you may want to compare TCNT0 with 61 instead of 128, in order to get closer to the desired blink frequency of 0.5 Hz.

Other than that, there are quite a few problems in the way you write your code. jwpat7 has already pointed out some of them, and here are more:

* You should not increment a register with `adc`, but with plain `add`. Both instructions update the carry bit, but `adc` also adds the previous value of the carry bit to the target register.
* Better yet, increment with `inc`, as it's purpose is more obvious. But then you should test the zero bit, as `inc` does not update the carry bit.
* There is little point in resetting r20 once it has overflowed, as it is zero at this point.

There are also quite a few ways the program could me made simpler. The simplest would probably be to configure timer 1 to deliver an interrupt every second, and toggle the LED in the ISR. If you do not want interrupts, you can configure counter 1 in much the same way, only without the “interrupt enable” bit, and check the interrupt flag in a busy loop.

Below is a slightly simplified version of your program. I tried to keep it as close as possible to yours, without using timer 1, nor interrupts, and not even the interrupt flag. The code checks for timer 0 overflowing by comparing its current value with the previous one.

```
.set PINB,     0x03
.set DDRB,     0x04
.set TCCR0B,   0x25
.set TCNT0,    0x26
.set LED_MASK, 0b00100000
.set PS_1024,  0b00000101

setup:
    ldi r16, PS_1024    ; Set r16 with prescaler 1024 value
    out TCCR0B, r16     ; Set the TCCROB to 1024
    ldi r16, LED_MASK   ; Set r16 to the LED bit
    out DDRB, r16       ; Set LED pin to output
    clr r18             ; Clear the saved timer
loop:
    ldi r20, 61         ; Initialize our software counter
check_timer:
    in r17, TCNT0       ; Read the timer
    cp r17, r18         ; Compare with previous value
    mov r18, r17        ; Save current value
    brsh check_timer    ; unless the timer has decreased, repeat
decrement:
    dec r20             ; decrement the software counter
    brne check_timer    ; if not zero, go back to checking the timer
toggle:
    out PINB, r16       ; toggle the LED
    rjmp loop

```

If we can use the timer overflow interrupt flag, then the test is simpler, and we do not need to store the previous and current values of the timer in registers:

```
check_timer:
    sbis TIFR0, TOV0    ; unless the timer has overflowed
    rjmp check_timer    ; check again for overflow
    sbi TIFR0, TOV0     ; otherwise clear the overflow flag

```

# Answer
> 3 votes
It appears that your intent is to set TCCROB up with a 1024x prescale, and each time it counts up to 128, increment r20, and toggle the LED each time r20 overflows to zero.

That sequence ought to take 1024/16M · 128 · 256 seconds, or about 2.1 seconds, a fairly leisurely toggle rate. If instead it's flashing a hundred or more times too fast, probably one of the comparisons is backwards.

Some of the following items might make it easier to debug the problem:

• Instead of `brbc 0,...`, say `brcc ...`
• Instead of `brbs 0,...`, say `brcs ...`
• Instead of `brbs 1,...`, say `breq ...`

That is, use proper mnemonic branch instruction names, rather than referencing SREG bits.

• If my arithmetic was correct and your branch tests were fixed, your rate would be off by a factor of two. To fix this problem, you could replace one of the more problematic tests (testing for carry clear after `cpi r17, 128`) with `cpi r17, 0` followed by a `breq`, and change the prescale factor to 256 instead of 1024, which gives 256/16M · 256 · 256 seconds, or about 1.05 seconds.

• Use named constants for register names instead of 0x04, 0x05, 0x25, and 0x26.

• Instead of your lengthy toggle sequence use EOR to toggle the value. That is, replace

```
    cpi r16, 0b00000000     ; Check if r16 is set to LED OFF
    brbs 1, switchon        ; If it is, change it to ON
    ldi r16, 0b00000000     ; Otherwise, change it to OFF
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock
switchon:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock

```

with

```
    eor   r18, r16          ; Toggle LED bit
    out   PORTB, r18        ; Set the LED to the new state
    rjmp  loop              ; Go run the clock

```

where r16 and r18 are initialized as follows in setup:

```
    ldi r16, 0b00100000     ; bit mask for LED pin
    mov r18, r16

```

---
Tags: arduino-uno, led, pins, assembly
---


title: Control speed of linear actuator servo

text:
# Question
Title: Control speed of linear actuator servo
I have a linear actuator that I want to be able to slow down. Right now, the shaft moves too quickly. I'm not sure how to do this. I was looking into `varSpeedServo.h` library but couldn't implement it.

```
//Includes
#include <Servo.h>

//Defines
#define LINEARACTUATORPIN 9        //Linear Actuator Digital Pin

const int button1Pin = 4;     // the number of the pushbutton pin

// variables will change:
int button1State = 0;         // variable for reading the pushbutton status

Servo LINEARACTUATOR;  // create servo objects to control the linear actuator

int linearValue = 10000;   //current positional value being sent to the linear actuator.

void setup()
{
  //initialize servo/linear actuator objects
  LINEARACTUATOR.attach(LINEARACTUATORPIN, 1050, 2000);      // attaches/activates the linear actuator as a servo object

  // initialize the pushbutton pin as an input:
  pinMode(button1Pin, INPUT);

  //use the writeMicroseconds to set the linear actuators to their default positions
  LINEARACTUATOR.writeMicroseconds(linearValue);

}

void loop()
{

  // if the pushbutton is pressed set the linear value
  button1State = digitalRead(button1Pin);
  if (button1State == HIGH) {
    // set the position value
    delay(2000);
    linearValue = 1050;

  }

    if (button1State == LOW) {
    // set the position value
    linearValue = 2000;
  }

  //use the writeMicroseconds to set the actuator to the new position
  LINEARACTUATOR.writeMicroseconds(linearValue);
delay(3000);
}

```

# Answer
Have you tried something like the following?

```
#define STEP 50

void loop()
{

  // if the pushbutton is pressed set the linear value
  button1State = digitalRead(button1Pin);
  if (button1State == HIGH) {
    // set the position value
    if (linearValue > 1050)
       linearValue = max(linearValue-STEP,1050) ;

  }

    if (button1State == LOW) {
    // set the position value
    if (linearValue < 2000)
       linearValue = min(linearValue+50,2000) ;
  }

  //use the writeMicroseconds to set the actuator to the new position
  LINEARACTUATOR.writeMicroseconds(linearValue);
  delay(100);
}

```

By changing the STEP value (or the delay in the next-to-last line) you can change the speed of the servo.
> 0 votes

---
Tags: servo
---


title: Arduino LDR sensor stained

text:
# Question
Title: Arduino LDR sensor stained
I bought a light sensor (**LDR**), but he got **stained**, what it means? It is used? Or is **residuum** of time?

I must give back? I have to clean up or something?

I bought as new, so I tested one of the LEDs will not turn on.

I bought the (Mercado Livre in BRAZIL).

The product is: http://www.gbkrobotics.com.br/exemplo-produto/p7-sensor-de-luz-com-leds.pdf

I pay R$8 BRL (equivalent aprox. $2 dollars) but, i just wanted to know if he had something I could do, because only shipping was R$ 13 BRL ($4 dollars)

* I'm starting with Arduino, thx

# Answer
I've read you post a couple of times and I get the impression you would like this board to work, so here are some quick check to try and find the fault.

* You need a bread board
* An arduino
* A 200-300 ohm resistor.
* Some wires. About 6 hands :)

Connect the board ground to the breadboard. Then connect the to the resistor. Then connect that to the power supply ground.

Take the positive off the power supply and touch it to the LED1 pin and check LED1 lights up. Repeat with 2 and 3.

Switch every thing off

Connect the Positive to the Vcc connection of the board. Connect a wire between Arduino A0 and "Sinal Analog"

Load this sketch

```
   void setup() {
       Serial.begin(9600);
    }
   void loop() {
       Serial.println(analogRead(A0));
       delay(250);
   }

```

When you cover the LDR it should read a lower number when you shine a light on it should read a higher number.

Turn everything off again, and if you have a multi meter test the resistance of the resistor on the board it should be 300 ohms, but I can't remember which way to read the bands and it might be 10K ohms, which would be a problem.

If anything doesn't work then they can all be fixed for a few cents and you don't need to worry about the discolouration.

Hope that helps you.
> 0 votes

---
Tags: sensors
---


# Question
Title: Arduino: pins still active after entering sleep mode
I'm writing an Arduino sketch to control a display with my Arduino Nano. I have wired it up as explained here, but used pin 3-7 instead of pin 2-6 listed in the example. The reason I did so is that I also added a push-button on interrupt 0 (= digital pin 2). I'm calling the sleep mode with a method, as explained in the section "Example" here. The Arduino seems to sleep, turning off all LEDs but the on/off one. The problem I have now is that the LCD display is sometimes still enabled (but only sometimes, not always). Why is it behaving like this? And how can I switch off everything possible to save as much energy as possible?

Here is my code piece:

```
int buttonPin = 2;

void setup()
{
  pinMode(buttonPin , INPUT);
  digitalWrite(buttonPin , HIGH);
  ...
}

void loop() {
  ...
  if(counter == 100) {
    enterSleep();            // Enter sleep method!
  }
  delay(1000);
}

void enterSleep()
{
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  attachInterrupt(digitalPinToInterrupt(2), wakeUpNow, LOW);
  sleep_mode();

  /* The program will continue from here. */
  /* First thing to do is disable sleep. */
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(2));
}

void wakeUpNow() {
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

```

# Answer
> 1 votes
The problem is that you are not specifically doing anything to "turn off" the LCD (that is, switch off the back light - note that the LCD module will still be consuming power while you sleep).

When you sleep the MCU it does just that - it goes to sleep. Its clock stops ticking. Not a lot more than that really. So if you are using PWM to control the backlight of the LCD, when the clock stops ticking the PWM will stop happening, and the I/O pin will remain stuck in whatever state it happened to be in at that moment - leaving you with random on or off at sleep time.

The solution? Manually turn off the backlight just before you sleep.

```
digitalWrite(9, LOW);

```

To save more power you might want to consider adding a high-side switch to the power of the LCD module. With that you can physically disconnect the power to the LCD to stop it consuming any power at all during sleep mode. Of course, after re-enabling it you will need to fully reinitialize the module.

The same goes for any other external hardware that takes a power supply.

A high side switch can be built from a P-channel MOSFET being controlled by an N-channel MOSFET. There's plenty of examples on the web.

---
Tags: arduino-nano, lcd, sleep
---


title: Arduino IDE installation Problems

text:
# Question
Title: Arduino IDE installation Problems
When installing the IDE there are many "Unable to open \*.DLL", errors. I check "ignore errors" and the IDE installed. Now when selecting the correct port and board the blink sketch is uploaded and several ATK 500 errors result. I have uninstalled and reinstalled the IDE several time, with repeated results.

# Answer
> 1 votes
You should check to make sure that your Java installation is up to date. It would also be best to make sure that you're bit types between the Java environment and the Arduino IDE are the same(32bit with 32bit, 64bit with 64bit). If this does not work, you should post your actual errors so we can help more :)

---
Tags: arduino-ide
---


# Question
Title: Critical sections in Arduino, interrupt consuming data
We all *know* the interrupts, but how do they really work?

**The problem:**

In my sketch an interrupt method (invoked when pin goes high) is consuming data from a buffer and the main `loop()` is filling the buffer at random speeds (from Internet - I'm using ESP8266, not the Arduino). Although I think there shouldn't be any *threading* problems with this buffer - I might be wrong - the program hangs up after random number of seconds (about half a minute average - and then the built-in watchdog resets it after few seconds). When I detached the interrupt method and merged it into the main `loop()` code, the problem disappeared (but I can't leave it like that). So it's probably either that I'm doing something illegal in the interrupt method (maybe it's just taking too long - how much time can an interrupt method take?) - or the second possibility - it **is** a threading problem.

**The questions:**

The main question is: how to correctly synchronize the interrupt method? How to create a critical section if the interrupt method cannot wait (for a semaphore) and if I leave it, it won't be invoked again because the pin is already high? And the detailed questions:

1. How to create a *thread-safe* variable (a bool flag), so that interrupt method can skip the critical section if the main loop has entered it? (I understand the interrupt method is "safe" - it won't be interrupted - but how to secure the regular code?)
2. If I detach an interrupt method that is triggered when a pin goes high when it is low (for just a few fast instructions), the pin gets high in that time, and then I'll re-attach the method to this pin again, will it be invoked? The same question for `noInterrupts();` How to make sure it **will** be invoked, if I can't check the pin and invoke (or not) the method manually in an atomic transaction with re-attaching the method?
3. If I detach this method (in main loop), is it possible that it will be invoked before the control is back from the `detachInterrupt()` method? (because the pin got high from external device in this very moment) And the same question for `noInterrupts();`
4. I've read that `noInterrupts();` causes some things, like reading incoming serial data, to be skipped. Can this method be even used if I don't want that? Or can I have guaranteed that it won't happen if the method is fast enough? (if so, please define the "fast enough"!)

So, is there a common template for creating a critical section between an interrupt method and the regular code? Or at least synchronizing a variable access? And if not, how to make sure the detached/blocked pin method will be invoked after re-attaching/re-enabling it?

**The common buffer code:**

(if you want to check whether this can cause any "threading" problems)

```
class Buffer
{
  protected:
    byte *buf;
    int len, readpos, writepos;
    bool wasFull, wasEmpty;
    long ratioSum, ratioCount;

  public:
    Buffer(int length)
    {
      len = length;
      buf = new byte[len];
      readpos = writepos = 0;
    }

    bool isFull()
    {
      bool full = writepos - readpos >= len;
      wasFull &= full;
      return full;
    }

    bool isEmpty()
    {
      bool empty = readpos >= writepos;
      wasEmpty &= empty;
      return empty;
    }

    void write(byte b)
    {
      if (isFull()) { if (!wasFull) { wasFull = true; Serial.println("Error: Buffer overflow!"); } return; }
      int pos = (writepos++) % len;
      buf[pos] = b;
      if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
    }

    byte read()
    {
      if (isEmpty()) { if (!wasEmpty) { wasEmpty = true; Serial.println("Error: Buffer underflow!"); } return 0; }
      int pos = (readpos++) % len;
      if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
      return buf[pos];
    }

    int available()
    {
      return writepos - readpos;
    }

    void measureRatio()
    {
      ratioSum += available();
      ratioCount++;
    }

    int getRatio()
    {
      int ratio;
      if (ratioCount > 0)
        ratio = 100 * ((float)(ratioSum / ratioCount) / (float)len);
      else
        ratio = 100 * ((float)available() / (float)len);
      ratioSum = 0;
      ratioCount = 0;
      return ratio;
    }
};

```

**PS:**

I have discovered that printing to Serial in the interrupt method (even without a `flush()` is causing my program to crash after max half a second. Is it just a duration of printing or is it something else? Also if you're thinking that the warning printing in my Buffer code can cause the crashes, then I assure you that they're not because I always check isEmpty() and isFull() before each read and write operation, so they just can't occur.

# Answer
> 6 votes
**Warning**: I am not familiar with the ESP8266 hardware, and some of my answers below may be only valid on the AVR architecture.

The simplest way to synchronize your main code with your interrupt service routine is to define a *critical section* in your `loop()` that wraps access to the shared data, and to make sure this critical section cannot be interrupted:

```
noInterrupts();
buffer.write(data);
interrupts();

```

This should be fine as long as you make the critical section as short as possible. Majenko's recommendation, to inspect the `write()` method with “a fine toothed comb” in order to minimize the critical section, is definitively good advice.

To understand the relevance of the “as short as possible” requirement, think about what could happen if the interrupt triggering event (the pin going high) happens while interrupts are disabled. If this happens *once*, it's not a problem: the interrupt is put on hold (technically, an *interrupt flag* is raised), and then it's serviced as soon as interrupts are enabled again. However, if the pin goes high *twice* while interrupts are blocked, then, when you enable interrupts again, the interrupt handler will be called only once. Whether this is a problem or not I cannot say, it all depends on what job the handler is supposed to do.

Now, to the specific sub-questions:

> How to create a thread-safe variable (a bool flag)

Chances are the boolean can be read and set atomically, so it's inherently thread-safe. On an 8-bit CPU, like the AVR, access to a multi-byte variable has to be protected inside a critical section. But since you have a 32-bit CPU, I bet you have atomic access to variables up to 32-bit wide.

> If I detach an interrupt method that is triggered when a pin goes high when it is low (for just a few fast instructions), the pin gets high in that time, and then I'll re-attach the method to this pin again, will it be invoked?

Hard to say without reading both the datasheet of the hardware and the source code of `attachInterrupt()`. It may be safer to keep the handler attached and start its code with something like `if (doNotRunInterruptHandler) return;`.

> The same question for noInterrupts();

Yes, it will be invoked, but at most once.

> If I detach this method (in main loop), is it possible that it will be invoked before the control is back from the detachInterrupt() method?

Yes, the interrupt can fire while `detachInterrupt()` is checking to see whether you gave it valid parameters.

> same question for noInterrupts();

Check the implementation. On the AVR, `noInterrupts()` is atomic.

> I've read that noInterrupts(); causes some things, like reading incoming serial data, to be skipped.

Nothing like this will happen if your critical section is fast enough.

> please define the "fast enough"!

It depends on how long you can afford to delay the interrupt service routine. For example, if you are reading serial data at 115200 bps and the UART has only a one-byte buffer, then a 86 µs critical section can make you loose one byte.

Then, there is the risk that several interrupts of the same kind fire during the same same critical section. As said before, the interrupt will only be serviced once. If this is a problem, then you should not block interrupts for longer than the minimum possible period of the triggering event.

Also, there is always the risk that several, *unrelated* interrupts fire during the same critical section. Then, the one with the lowest priority will have to wait for the critical section to finish *and then* for the higher priority interrupt to be serviced.

# Answer
> 3 votes
The trick here is not to make your interrupt routine, or your main routine "thread safe" - instead you need to make the single item that is shared by the two "thread safe". That means your Buffer class.

You need to go through that with a fine toothed comb and work out which bits could possibly be accessed by the two contexts at once and protect them.

The bits that jump out at me immediately are the calculations and manipulations of writepos and readpos. Accesses to those variables need to be made as atomic as possible. One of the best ways of doing that is to massively restrict the actual access to those variables and wrap those accesses in critical sections (disable / enable interrupts). That keeps the critical sections as short as possible.

For instance, instead of directly manipulating the variables, as you enter the function you first create "cached" copies of the variables you will modify that could be modified at the same time (such as writepos being written to in the ISR):

```
cli();
int cachedWritePos = writepos;
sei();

```

Then you do your manipulations and calculations on those cached variables. Finally, just before you exit the function, you write your now safely changed cached variable values back to the member variables:

```
cli();
writepos = cachedWritePos;
sei();

```

The critical sections are then as brief as possible, and any heavy calculations (I count the modulus operator `%` as a heavy calculation) don't block the interrupt from firing.

Of course that is not a foolproof method and doesn't protect against two contexts changing the same variable and it getting out of step. To counter that you will have to use a mutex. There's no getting around that, other than ensuring that your program never changes the same variables from two different contexts. The only mutex you really have access to is a manually implemented spinlock.

On that note, I am having some trouble following the logical flow of how your buffer works. There are bits that don't look quite right to me, such as this bit:

```
if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }

```

According to my way of thinking both readpos and writepos have to have reached (or exceeded) the end of the buffer for them to wrap around to the start again. That can't really happen properly in a function that is only writing, or a function that is only reading. I think you want to only be checking writepos and wrapping that in the write function, and only checking readpos and wrapping that around in the read function, not both in both functions.

As far as using Serial in an interrupt goes, the general rule is: don't do it. I don't know about the ESP8266's serial code, but certainly on the Arduino it relies on interrupts being used to take each character from the TX buffer and transmitting it through the UART interface. If you are in an interrupt routine and your (64 byte) serial TX buffer fills up any attempts to write to that buffer (Serial.print) will block until the interrupt that sends the characters has made some room for you - and of course that interrupt will never happen while you're blocking because you are in an interrupt at the time.

On systems with multiple priority levels of interrupt (such as a PIC32) the same holds true if you are in an interrupt routine that is at a higher priority than the Serial interrupt. If you are in a lower priority one the serial interrupt can still interrupt your current interrupt routine and function correctly.

# Answer
> 3 votes
**My problem with crashing is fixed! :)** I will share here what was wrong - maybe someone will have similar problem in the future.

But first...

I have marked Edgar Bonet's answer because he answered most of the difficult questions that were bothering me and for pointing me out that reading a 16-bit variable on 8-bit processor is **not atomic** (it was the most significant clue) and for helping me to understand that `noInterrupts()` is the safe and only way to synchronize with the interrupt method in my case. Thanks Edgar! But credits also go to Majenko because I wouldn't have guessed it without him. He pushed me into the right direction in our chat discussion - that I have to secure **all** the methods accessing `readpos` and `writepos`. Thanks Majenko. I agree with him that my Buffer code is ugly and it's not a good way to implement a circular buffer, but it was still logically OK - it just needed one more thing...

**The solution**

You probably know it already. The key is the non-atomic **reading** of `readpos` and `writepos`. For example: the code from `loop()` starts to read `readpos`, reads the first byte of it, then the interrupt happens, `readpos` changes there and the `loop()` continues reading the other (changed) half, which is then glued with the old (out of date) half - so - a random value. Or another one: the loop writes first byte of `writepos` (as it fills the buffer) and then interrupt fires and reads the first (changed) byte with the old (out of date) second byte. So the solution is to just wrap all access to those variables with `noInterrupts()` \- and the whole code works perfect! :) Thank you guys! Not only for helping me to fix it, but for helping me to understand it.

Here is how it looks like now (non-crashing version):

```
class Buffer
{
  protected:
    byte *buf;
    const int len;
    int readpos, writepos;
    bool wasFull, wasEmpty;
    long ratioSum, ratioCount;

  public:
    Buffer(const int length)
      : len(length)
    {
      buf = new byte[len];
      readpos = writepos = 0;
    }

    bool isFull()
    {
      noInterrupts();
      bool full = writepos - readpos >= len;
      wasFull &= full;
      interrupts();
      return full;
    }

    bool isEmpty()
    {
      noInterrupts();
      bool empty = readpos >= writepos;
      wasEmpty &= empty;
      interrupts();
      return empty;
    }

    void write(byte b)
    {
      if (isFull()) return;//{ if (!wasFull) { wasFull = true; Serial.println("Error: Buffer overflow!"); } return; }
      int pos = (writepos++) % len;
      buf[pos] = b;
      if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
    }

    byte read()
    {
      if (isEmpty()) return 0;// { if (!wasEmpty) { wasEmpty = true; Serial.println("Error: Buffer underflow!"); } return 0; }
      int pos = (readpos++) % len;
      //if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
      return buf[pos];
    }

    int available()
    {
      noInterrupts();
      int result = writepos - readpos;
      interrupts();
      return result;
    }

    int free()
    {
      noInterrupts();
      int result = len - available();
      interrupts();
      return result;
    }

    void MeasureRatio()
    {
      ratioSum += available();
      ratioCount++;
    }

    int getRatio()
    {
      int ratio;
      if (ratioCount > 0)
        ratio = 100 * ((float)(ratioSum / ratioCount) / (float)len);
      else
        ratio = 100 * ((float)available() / (float)len);
      ratioSum = 0;
      ratioCount = 0;
      return ratio;
    }
};

```

---
Tags: esp8266, interrupt
---


title: Having 3 buttons with only 2 input pins

text:
# Question
Title: Having 3 buttons with only 2 input pins
for the purpose of learning, I'm trying to have a kind of digital/binary input where I'm using 3 buttons but only 2 input pins.

I thought of

```
01 = Button 1
10 = Button 2
11 = Button 3

```

My **first attempt** was like this:
I left the resistors out right now. The problem here is of course, that it doesn't matter what button I press, both LEDs are lighting up.

I used 2 Diodes in my **second attempt**:
This time, S1 and S2 work as expected, but S3 brings only one LED up.

Now I was wondering how I can wire things up correctly, using as little components as possible and having in mind, that I'm going to use an Arduino instead of the LEDs.

Thank you for any help!

# Answer
> 2 votes
The logic of your second attempt is perfectly correct.

If you put resistors in series with the LEDs you may get more joy out of it. Having two LEDs in parallel without resistors often results in one LED lighting and the other not.

---
Tags: digital-in
---


title: Dealing with TCCRx

text:
# Question
Title: Dealing with TCCRx
I am totally beginner in Arduino, and i want to ask some questions :

```
    TCCR1B = (TCCR1B & ~(0x07<<CS10)) | (2<<CS10);

```

What does the previous line mean? with good explaination please .

```
    TCCR1A &= ~(3<<COM1A0);

```

for the previous line , is there difference if i wrote '1' instead of '3' ? why ?

# Answer
On the first line, you clear some bits, then set some bits in the same “region” of the byte.

From inside out, get 7 (which is 3 bits of ones: 00000111), shift it upwards (the \<\< operation) by CS10 amount (we don’t know how much, but the compiler does), complement all that (the tilde ~ character) and bitwise ‘and’ it with the value of the TCCR1A register (the & operation). Next, take a 2 (binary 00000010), shift it up by CS10 bits again (\<\< CS10), and bitwise ‘or’ that bit pattern with the earlier result (the | operator). Finally, assign all that to TCCR1A.

For the second line, yes, changing 3 to 1 will certainly change what happens to TCCR1A. It makes a different bit pattern, and I'm sure you can reason it out after reading the previous explanation.
> 2 votes

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


title: How to get neopixel to fade colorwipe?

text:
# Question
Title: How to get neopixel to fade colorwipe?
I'm trying to get a fade to happen when an LED turns on/off during the color wipe rather than just abruptly turning on/off. I'm not quite sure how to do this though.

```
#include <Adafruit_NeoPixel.h>

Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, 3, NEO_RGBW + NEO_KHZ800);
void setup() {
  strip.begin();
}

void loop() {
  colorWipe(strip.Color(255, 255, 255), 150); // Red
 colorWipe(strip.Color(0, 0, 0), 150); // Red
 delay(5000);
}

void colorWipe(uint32_t color, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, color);
      strip.show();
      delay(1000);
  }
}

```

# Answer
You could change the intensity of each colour in steps till you get to your target colour.

```
void colorFade(uint8_t r, uint8_t g, uint8_t b, uint8_t wait) {
  for(uint16_t i = 0; i < strip.numPixels(); i++) {
      uint8_t curr_r, curr_g, curr_b;
      uint32_t curr_col = strip.getPixelColor(i); // get the current colour
      curr_b = curr_col & 0xFF; curr_g = (curr_col >> 8) & 0xFF; curr_r = (curr_col >> 16) & 0xFF;  // separate into RGB components

      while ((curr_r != r) || (curr_g != g) || (curr_b != b)){  // while the curr color is not yet the target color
        if (curr_r < r) curr_r++; else if (curr_r > r) curr_r--;  // increment or decrement the old color values
        if (curr_g < g) curr_g++; else if (curr_g > g) curr_g--;
        if (curr_b < b) curr_b++; else if (curr_b > b) curr_b--;
        strip.setPixelColor(i, curr_r, curr_g, curr_b);  // set the color
        strip.show();
        // delay(wait);  // add a delay if its too fast
      }
      delay(1000);
  }
}

```

To use it:

```
void loop() {
  colorFade(255, 0, 0, 150); // fade into red
  colorFade(255, 255, 255, 150); // and then into white
  delay(5000);
}

```

This is untested, so I dont know if it will be too fast or too slow. You'll have to tweak it to your needs.
> 3 votes

---
Tags: led
---


title: SDS011 Dust Sensor Checksum Error

text:
# Question
Title: SDS011 Dust Sensor Checksum Error
I'm working with an SDS011 particular sensor through its serial interface. The spec sheet (http://inovafitness.com/upload/file/20150311/14261262164716.pdf) indicates that the second to last byte of a serial packet is a checksum equal to sum of all the data bytes.

I am using pyserial to read and interpret the serial data. Here's a snippet of the code:

```
import serial

def read_sensor(port):
    while True:
        header = port.read(2)
        if header == b'\xAA\xC0':
            data = port.read(6)
            checksum = port.read()
            tail = port.read()
            if tail == b'\xAB':
                return header + data + checksum + tail

port = serial.Serial(port=MY_PORT)
packet = read_sensor(port)
data_sum = sum(packet[2:8])
checksum = packet[8]

if data_sum == checksum:
  print('Ok')
else:
   print('Error')

```

However, I haven't got a single packet whose checksum hasn't been an error. Is there anything I could be potentially doing wrong?

# Answer
> 1 votes
Generally, a checksum byte is computed using 8-bit arithmetic, with overflow ignored.

The Python sum function uses arithmetic of indefinite precision (eg, 32- or 64-bit words for small values, with additional words for larger numbers).

Try comparing `checksum` to `data_sum % 256`. If that doesn't fix the problem, print out some of the data packets and checksum values so that you can use a calculator to test different combinations.

# Answer
> 0 votes
I assume `MY_PORT` stands for `COMxx`. Since you set no timeout, it means `port.read()` will block till it gets the number of bytes requested. I suggest you add a `print()` to display the bytes returned, if any.

To get the sum, use `data_sum = sum(packet[2:8]) & 0xff` to ensure you only get a byte. Also add `port.reset_input_buffer()` right before you call `read_sensor()`, to flush the input buffer.

It would also be a good idea to take at least 3 consecutive readings from the sensor in case of any errors in the first reading right after opening the port. Dont forget to add a `port.close()` at the end of your code.

---
Tags: serial, sensors, python
---


# Question
Title: Sending sensor readings from Arduino to Raspberry Pi over 433 MHz
I'm building a garden monitor, so I got myself an Arduino Nano, a soil humidity sensor, an air humidity and temperature sensor as well as a luminosity sensor. Since I had not one but two Raspberry Pis laying around I thought I'll handle the receiving end with one of them. I also got a 433 MHz RF kit.

The trail of the information will look like this: Sensor(s) -\> Arduino -\> 433 MHz Transmitter - - - 433 MHz - - - 433 MHz Receiver -\> Raspberry Pi

Now my question is, what libraries should I use? I checked rc-switch (it has libs for both Arduino as well as RPi) and managed to send some codes but it seems that I'll need to write my own protocol to use this to transmit even simple data as it wasn't developed for sending data, rather simple switch on / switch off signals to simulate remotes.

VirtualWire would seem as the ideal candidate but the problem is it doesn't have an RPi equivalent.

Any suggestions?

# Answer
> 1 votes
You could look into the RadioHead library - there might be a port for RPi, though I couldn't find one with a (very) quick google. This library works well, I use it actually with RFM69H 433 MHz radios (from Moteinos), a little more expensive than the simple 433 kits, but also supports encryption which might be important down the line. If you can't find a good library for RPi one solution could be to have a second Arduino acting as a receiver and sending data serially to RPi. This is what I use with a regular desktop PC which is my home server.

I also found a discussion about connecting a RFM69 to the RPi here which might give you more information about the process in general, even if you won't use the same radio.

# Answer
> 1 votes
There is custom made library to solve this issue here and i recomend you read this discussion.

# Answer
> 0 votes
Presuming you want to get results quickly, I recommend you have a look at openHab This is a Java based home automation framework and server that has plugins for many existing protocols.

Once you get your protocol running it is just a matter of plugging it into openHab for charting and storage. I use for inside home measurements:

Also this post will help you further with connect 433 to RasPi and Arduino.

Specifically for temp and humidity sensors there is the reverse engineered Cresta protocol, that is also used in a lot of commercial sensors. See this Github repo for Arduino code. Also findable for Raspberry Pi.

# Answer
> 0 votes
I am fairly new to Arduino but have had a basic experience with python on RPi (Model 2). I am trying to connect ultrasonic sensors (for distance measuring) on Arduino and then send (RF transmission) the value to Raspberry Pi. I am not able to figure out how to write a code for receiving the transmitted code. I have to receive the code, decode it and then update it in my SQLITE database (on the same RPi).

I have already tried RFSniffer but I am unable to receive value other than "INT". RPi shows nothing if I send any "CHAR" or "STRING".

Please do suggest me how should I proceed.

Thanks in advance

Pradeep Verma

---
Tags: virtualwire
---


# Question
Title: Arduino Yun Python ImportError: No Module named mime.multipart
So, I have an Arduino Yun, and I'm trying to send an email with python. I have this code that I got from https://github.com/amicojeko/YouCantTouchThis

But when I try to call the file with `$python sendemail.py test.png`, it returns me an error:

```
ImportError: No module named mime.multipart

```

I already tried to change to lowercase the imports, but it keeps showing the same error. The python version in the Arduino is 2.7. I've read something about module reorganization but even with the changes the error keep showing.
Here is the code:

```
# coding=utf-8
# Copyright (C) 2014  Stefano Guglielmetti

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import smtplib, os, sys
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

#From address, to address, subject and message body
from_address    = 'FROM_ADDRESS@EMAIL.COM'
to_address      = ['YOUR_ADDRESS@EMAIL.COM']
email_subject   = 'Alert!!! Zombies!!! Ahead!!!'
email_body      = 'A non dead intruder has been detected and needs to be eliminated!'

# Credentials (if needed)
username = 'EMAIL_LOGIN'
password = 'EMAIL_PASSWORD'

# The actual mail send
server = 'smtp.gmail.com:587'

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
    assert type(send_to)==list
    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(f,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)

    smtp = smtplib.SMTP(server)
    smtp.starttls()
    smtp.login(username,password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

send_mail(from_address, to_address, email_subject, email_body, [sys.argv[1]], server) #the first command line argument will be used as the image file name

```

# Answer
`mime.multipart` isnt used in your code at all so you shouldn't be getting that error. The correct import statements for Python 2.7 are:

```
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email.encoders import Encoders

```

Study these examples in the Python 2.7 documentation.
> 0 votes

---
Tags: arduino-yun, python
---


title: Arduino Uno Multiple Modules

text:
# Question
Title: Arduino Uno Multiple Modules
I have an Arduino Uno and I want to connect;

* RFID Reader (*RC522*)
* WiFi Module (*ESP8266 ESP-01*)
* SD Card Module
* RTC (*Real Time Clock - DS1307*)

Same time but pinouts are not enough. Is there a way to doing this with Uno or I have to buy an Arduino Mega ? I saw "*Expansion Sensor Shield*"s but I do not know what is the logic of using this ?

Regards

# Answer
> 4 votes
Let's see which device uses which communication protocol:

1. **WiFi Module (ESP8266 ESP-01)** uses Serial communication.
2. **RTC (Real Time Clock - DS1307)** uses I²C communication.
3. **RFID Reader (RC522)** uses SPI communication.
4. **SD Card Module** also uses SPI communication.

Now, the Arduino UNO supports **One I²C**, **One SPI** and **One Serial** (by default) communication port.

So, you can easily connect your **Wifi** and **RTC** modules.

Now, actual problem is: "How to access multiple SPI interfaces on Arduino" (and that is a solved problem).

Hope it helps and you don't have to buy an **Arduino MEGA**.

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


title: Arduino capacitive touch sensor help

text:
# Question
Title: Arduino capacitive touch sensor help
So I have been messing around with the Arduino Capsense library with the immensely helpful guide; http://www.instructables.com/id/How-To-Use-Touch-Sensors-With-Arduino/ (many thanks to DangerousTim!) using the code provided, i managed to get a relay to operate with a sensor. It worked great and I was able to adjust the distance and sensitivity. But when i tried adding another sensor and relay, it stopped working. I've been trying to isolate the problem for a while now and have gotten nowhere. I'm hoping someone can help me, here's the original code for the single sensor and relay;

```
#include <CapacitiveSensor.h>
#include <CapacitiveSensor.h> //change '42' to any desired pin...

long time = 0;
int state = HIGH;
boolean yes;
boolean previous = false;
int debounce = 200;
CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
// To add more sensors...
//CapacitiveSensor   cs_4_6 = CapacitiveSensor(4,6);        // 10M resistor       between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
//CapacitiveSensor   cs_4_8 = CapacitiveSensor(4,8);        // 10M resistor  between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil

void setup()
{
    cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
    pinMode(13, OUTPUT);
}

void loop()
{
    long total1 =  cs_4_2.capacitiveSensor(30);

    if (total1 > 60){yes = true;}
    else {yes = false;}

    // to toggle the state of state
    if(yes == true && previous  == false && millis() - time>debounce){
        if(state == LOW){
            state = HIGH; }
        else state = LOW;
        time = millis();
    }

    digitalWrite(13, state);
    previous = yes;
    delay(10);
}

```

and here's the code for the two sensors and relays

```
#include <CapacitiveSensor.h>

int led = 13;
int led2 = 12;
long time = 0;
int state = HIGH;
long time2 = 0;
int state2 = HIGH;
boolean yes;
boolean previous = false;
boolean yes2;
boolean previous2 = false;
int debounce = 200;

CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);        // 10M resistor  between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

void setup()
{
    cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
    cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);  //Calibrate the sensor...
    pinMode(led, OUTPUT);
    pinMode(led2, OUTPUT);
}

void loop()
{
    int total1 =  cs_4_2.capacitiveSensor(30);
    Serial.println(total1);
    int total2 =  cs_5_7.capacitiveSensor(30);

    if (total1 > 60){yes = true;}
    else {yes = false;}
    if (total2 > 60){yes2 = true;}
    else {yes2 = false;}

    // to toggle the state of state
    if(yes == true && previous  == false && millis() - time>debounce){
        if(state == LOW){
            state = HIGH;
        }
        else
            state = LOW;
        time = millis();
    }

    if(yes2 == true && previous2  == false && millis() - time2>debounce){
        if(state2 == LOW){
            state2 = HIGH;
        }
        else
            state2 = LOW;
        time2 = millis();
    }

    digitalWrite(led, state);
    previous = yes;
    digitalWrite(led2, state2);
    previous2 = yes2;
    delay(10);
}

```

# Answer
> 1 votes
I think you are making a mistake initializing **cs\_5\_7**.

```
CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

```

You are using same pin 4 for both Capacitive sensors. Try using different pins. I am quite sure that, this would help.

---
Tags: sensors
---


# Question
Title: How to use voltage divider between ESP8266 (3.3v) and IR proximity sensor (5V)?
I am a software developer and I don't know much about circuits so I need help.

I have an ESP8266 (esp-12) 3.3V and I'm planning to use it with an IR proximity sensor (runs between 4.5-5V). I have 2 AA batteries (3V total) and 4 AA (6V total) power supplies. Also, I have a bunch of 10K Ohm and 330 Ohm resistors.

How can I use a voltage divider to supply sufficient voltage to these components, based on what I have? If it would help, I have a 100uF capacitor and I use a CP2102 to TTL Serial Converter to program. Any help will be appreciated. Thank you in advance.

# Answer
My experience with esp8266 tells me that if you power esp8266 with a 3.3V supply and you provide 5V/0V signal to its pins (either Tx/Rx or pin0,1) nothing's gonna happen. It will work fine.

Based on this experience, i would like to suggest you to

1. power your esp8266 with 3.3V pin of your TTL converter
2. power your IR sensor using 5V output pin of your TTL converter
3. connect signal pin of IR sensor to your esp8266 digital pin. (just in case esp8266 heats up, disconnect circuit and try using voltage divided only for this particular connection.

If using those external power supplies don't forget to common GND (or -ive terminal) of those power supplies.
> 0 votes

---
Tags: arduino-uno, esp8266, voltage-level, voltage-protection
---


# Question
Title: NewliquidCrystal example HelloWorld_i2c just flickers
I've bought a cheap I2C LCD display (specs in the end of this question).

I can't make it print. I've tested with two displays of same model, so nothing is broken.

I am using the NewliquidCrystal 1.3.4 library, ie not the "normal" LiquidCrystal library. I'm trying with the I2C example called HelloWorld\_i2c (link to example code). I've only changed the address from 0x37 to 0x27.

It compiles fine, but the result is only that the display flickers.

What is wrong and how do I fix it?

## Super simple example flickers too

Well, this one gives just one blink.

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27);  // Set the LCD I2C address
void setup()
{
  lcd.begin(16,2);               // initialize the lcd
  lcd.home ();                   // go home
  lcd.print("Hello, ARDUINO ");
}
void loop()
{
}

```

## Pictures

In the light it shows that the writing to the display is randomly jumping around.

In the dark, it shows that the background light flickers:

## Details about the LCD display

Text on the backside

```
YwRobot Arduino
QAPASS
LCM1602 IIC V1

```

Text on the chip

```
TLPCF85747
HA
T62281
A N 1
I L knM988223

```

# Answer
I was able to make the example run as intended, by using a different constructor call:

```
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

```

I am not able to tell you, what these parameters and values mean. However, the documentation for this constructor is shown below (source).

```
/*!
    @method
    @abstract   Class constructor.
    @discussion Initializes class variables and defines the I2C address of the
    LCD. The constructor does not initialize the LCD.

    @param      lcd_Addr[in] I2C address of the IO expansion module. For I2CLCDextraIO,
    the address can be configured using the on board jumpers.
    @param      En[in] LCD En (Enable) pin connected to the IO extender module
    @param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
    @param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
    @param      d0[in] LCD data 0 pin map on IO extender module
    @param      d1[in] LCD data 1 pin map on IO extender module
    @param      d2[in] LCD data 2 pin map on IO extender module
    @param      d3[in] LCD data 3 pin map on IO extender module
    */
   LiquidCrystal_I2C( uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
                     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3 )
;

```
> 3 votes

# Answer
Try to pull the I2C sensor at the back of the LCD board, you can see that it is shorted to the SMD mounted on the back, just pull it a little so that it won't touch and short the conductors. This has happened to me, try it if this works.
> 0 votes

---
Tags: lcd
---


title: RF24L01+ VER01 with 10 pins

text:
# Question
Title: RF24L01+ VER01 with 10 pins
How can I connect this little ship to my Arduino? I can find alot of tutorials how to do it so, but all I find is 8 pins, mine includes 10 pins, and from what I could of understand from searching me myself, that there is 2 pins of VCC and 2 GRN pins.

So I would like to know how to connect this? Not necesserly Arduino, but can someone help me with the pins names at least so I can identify them. Thanks.

# Answer
There are some 10pin adapter boards floating around. See e.g. nrf24l01 (8pin) + adapter board (10pin) oops?

Their pinout looks to be the following.
> 1 votes

---
Tags: arduino-uno, nrf24l01+
---


title: Nrf24L01 with Arduino

text:
# Question
Title: Nrf24L01 with Arduino
When I wanted to test my Nrf24L01 I wanted to be sure of it working fine, so I used this code for an Arduino Uno:

```
#include <SPI.h>
#include <RF24.h>
#include "printf.h"
#define RF_CS 9
#define RF_CSN 7
RF24 radio(RF_CS, RF_CSN);
void setup() {
  Serial.begin(9600);
  printf_begin();
  radio.begin();
  radio.printDetails();
}
void loop() {
  radio.printDetails();
  delay(5000);

}

```

The thing is when I opened my Serial, I got this each 5 second:

```
STATUS       = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
RX_ADDR_P0-1     = 0x0000000000 0x0000000000
RX_ADDR_P2-5     = 0xff 0xff 0x00 0x00
TX_ADDR      = 0x0000000000
RX_PW_P0-6   = 0xff 0x00 0x00 0xff 0xff 0x00
EN_AA        = 0xff
EN_RXADDR    = 0xff
RF_CH        = 0xff
RF_SETUP     = 0xff
CONFIG       = 0xff
DYNPD/FEATURE    = 0xff 0x00
Data Rate    = 1MBPS
Model        = nRF24L01
CRC Length   = 16 bits
PA Power     = PA_MAX

```

Which apparently means that there must be something wrong with the connection, as far as I know .

noting that i have this Nrf24L01 with 10 pins, so i tried to attach it just like the following picture shows :

So I tried to plug it in with the Arduino just like this:

What was the mistake?

# Answer
> 2 votes
I think problem lies in your Arduino sketch, specifically in this line:

```
#define RF_CSN 7

```

Now, you have set RF\_CSN pin to pin#7 while actually, its connected to pin#9

To get this to working you, try changing above lines of code to:

```
#define RF_CSN 10

```

Hope it helps.

---
Tags: arduino-uno, nrf24l01+
---


# Question
Title: Arduino and 2 Adafruit Fingerprint modules working together
I want to do a project with fingerprint access control. But my client wants one on both sides of the door (inside and outside). Now I am using this product Adafruit Fingerprint module but I don't want to enroll each person on each fingerprint module. I want to look at enrolling each employee on 1 of these modules and then via arduino "SYNC" the fingerprint models between each other. Is this possible? Can someone maybe point me in the right direction or am I just insane HAHAHA. Look I can do the route of programming/enrolling each person on each module. But we life in a real world and at some point the fingerprint model/id's are not going to match up. And then there is going to come a problem with my online software. As well sorry for my bad lanuage :)

# Answer
> 0 votes
You should get an Arduino Mega, if you arent using one already. You'll need the SRAM and Serial ports.

When I used this module, I didnt have enough time to experiment with it but here goes:

The **enroll** command for the FPM10 sensor takes an image of a fingerprint, processes it and finally creates a 512-byte model/template that is stored in flash memory with a unique ID (**PageID**) and used for future comparisons. However, it is also possible to read those templates from the flash memory with a few commands. You have not said much about the role your web server plays here, so I'll assume its possible for you to store data easily and that its responsible for authorizing fingerprint enrollment and deletion. Since you have more than one sensor, a general solution to your problem would be:

* The server must keep a record of available fingerprint IDs
* When instructing the Arduino to begin enrollment, the server must also send along a fingerprint ID, based on its records of what ID is free. IDs may be assigned sequentially at first but templates may be deleted, leaving holes, hence the need for the server.
* The Arduino `begin()`s the current sensor where the user is located and performs the normal enrollment. As soon as enrollment is done, the template that was just stored, should be loaded by the Arduino from the module's flash library and into one of its character file buffers using the **LoadChar** command. The only parameters for this command are the BufferID and the PageID.
* Then the Arduino should download the template from the character file buffer into a 512-byte buffer that you will create in the Arduino SRAM. The command needed here is the **UpChar** command and its sole argument is the BufferID of the buffer to be read from. As soon as confirmation is received from the module, the sensor begins sending the 512-byte template in packets of 32 bytes (by default), each with a packet identifier of 0x02 until the last packet which has a package identifier of 0x08.
* Then the Arduino `begin()`s the other sensor and sends the **DownChar** command to the module, which tells the sensor to expect a template to be stored in one of its character buffers (must be specified in the command). Once the Arduino receives confirmation, it should start sending the template to this sensor, using the same packet size and format that has been set for that sensor 9or the default I mentioned before if it hasnt been changed).
* Finally, the Arduino sends the **Store** command to the sensor, to store the template in the buffer you just wrote to, into its flash library using the same fingerprint ID it was stored with in the first sensor.
* The Arduino may then send confirmation to the Linux server, which then adds the fingerprint ID to the list of used IDs.

Now both sensors have identical fingerprint libraries and may be used to match fingerprints and get the same results. Deletion of fingerprints may also follow the same process: the server commands the Arduino to delete a print with a given ID and the Arduino sends the **DeleteChar** command to both sensors. All the commands I mentioned here are in the sensor's datasheet, which you must have downloaded along with the Adafruit library.

Use 57600 baud to communicate with the sensors, for reliable results. This is my fork of the Adafruit library with more functions available and without the buffer overflow issues. It should make the interfacing tasks a lot easier.

# Answer
> 1 votes
**Yes, you can easily do that**. This finger Print sensor works over Serial communication.

You can have multiple Serial devices connected to your Arduino UNO using SoftwareSerial library.

All you have to do is to create multiple instances of Adafruit\_Fingerprint initialized with different SoftwareSerial objects. i.e.

```
// pin #2 is IN from sensor1 (GREEN wire)
// pin #3 is OUT from arduino to sensor1  (WHITE wire)
// pin #8 is IN from sensor2 (GREEN wire)
// pin #9 is OUT from arduino to sensor2  (WHITE wire)
SoftwareSerial mySerial1(2, 3);
Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&mySerial1);
SoftwareSerial mySerial2(8, 9);
Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&mySerial2);

```

Now, you can use **finger1** and **finger2** for your finger print operations. (previously referenced as only **finger**)

In order to understand Serial Communication with multiple serial devices, have a look at this Arduino.cc Offical tutorial.

Hope it helps.

---
Tags: arduino-mega, adafruit
---


title: Practicality of recording speech

text:
# Question
Title: Practicality of recording speech
Is it practical to record speech with the Leonardo?

I want to record speech via a MEMS microphone and stream it over a serial connection to a Raspberry Pi for speech-to-text processing.

This article states that the typical bitrate for recording voice podcasts is 64 kbps. The Arduino's `analogRead()` function has a maximum sample rate of typically 8,600 times/sec for a maximum bitrate of 8,600 samples/sec * 10 bits/sample = 86 kbps, so theoretically, it should be fast enough to record decent voice audio.

However, will the serial connection be fast enough to stream this much data? Theoretically, the Leonardo's serial connection can go up to 115,200 bps, but I've never reliably gotten it to go faster than 57,600 bps, which would mean the serial connection would a bottleneck that would prevent it from sending a continuous stream of 64 kbps, and therefore it would be impractical to record speech with the Arduino.

Am I wrong? Has anyone had success with voice recording while streaming it over serial?

# Answer
On my page about the ADC converter I attempted to record a 4 kHz sine wave on the ATmega328P with the following code:

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

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

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

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

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

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

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

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

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

  }  // end of setup

void loop () { }

```

The code (rather inefficiently) sends the results in ASCII, like this:

```
378
710
899
992
966
827
609
367
159
38
35
147
350
593
817
965
1001
917
733
494
259
88
21
76
239
471
711
905
1001
977
839
620
376
164
39

```

This gave reasonable results:

Now the Leonardo is, of course, a different processor. However it is similar. The ADC on it should be capable of similar performance.

---

I should point out that this code records first, then sends the data. This is so the recording can keep up. A normal ADC conversion (if you don't change the ADC prescaler) takes 104 µs. To send 10 bits via serial at 115200 baud rate would take 173.6 µs because it would require two bytes per sample (unless you somehow compress each reading). If you could put up with 8-bit resolution (per sample) then you halve that, and can probably just stream the data out fast enough.
> 3 votes

# Answer
You don't actually have to initialize your connection to 115,200 bps or 57,600 bps. You can use a custom baud rate of 65,000 bps.

One thing to keep in mind that, you can use **any** custom baud rate you want, as long as it's supported by the hardware. The Arduino IDE however only supports standard baud rates.

One more thing, as you are streaming data (kind of), you might also want to look into Arduino serial buffer sizes.
> 1 votes

---
Tags: serial, arduino-leonardo, analogread, audio
---