# Question
Title: How can I get my Arduino to recognize a specific object using some kind of sensor?
This is my first question on this site, and I'm relatively new with Arduino. I do have some experience using the board to reprogram a robot that used infrared proximity sensors, servos, and switches.

I would like to add a sensor on to the robot that will allow him to recognize specific "obstacles" that I will put in his environment (not walls!) For instance, when he sees a red card, he needs to spin, but when he sees a green card, he needs to roll in the opposite direction. I do not want to spend much on the cards, but I would be willing to put a small battery and LED in them if I had to. The cards do not necessarily need to be colored, I was just using that as an example.

The robot will be in a well-lit room with noise in the background. He will be controlled by an Arduino Uno, an infrared sensor and a remote control. He can be pretty close to the cards if he has to (3 centimeters or so would be enough). It would be ideal if he could discern different types of cards, but that is not necessary as long as he's able to tell a card from the rest of his environment.

I am simply not sure how to go about implementing this. I have read about using photoresistors to differentiate color, and they're really cheap, but will they be accurate enough from a distance? This is the light sensor I was considering using:

http://www.mouser.com/ProductDetail/Adafruit/161/?qs=GURawfaeGuDpQ5XPTNqKUw%3D%3D&gclid=Cj0KEQiA6IC2BRDcjPrjm\_istoUBEiQASrLz1rQNwZgntUcccnOmrFph-pCbu60R00GNozB\_XbZxYz0aAn0j8P8HAQ

I'm willing to pay about 5$ for one if I need to.

If I use the light sensor method, can I just use brightly colored cards or will I need to use LEDs? Is there a better way to accomplish my goal that you are aware of?

Thank you for your time. If there is missing information in my question, please tell me and I will add it.

# Answer
> 0 votes
If you are controlling your robot with a remote control, why do you need it to detect cards, instead you can tell it to do whatever you want right?

If you want to detect specific objects according to their colors, arduino is not a platform i will choose, because it doesn't have processing power to do image processing.

But take a look at this, http://charmedlabs.com/default/pixy-cmucam5/ it can talk to arduino, and you can train it by telling it identify colored objects which i might think is apt for your case. RFID tags will be a good idea as @Majenko said.

# Answer
> 1 votes
You can get an RFID reader for $7 from eBay:

Cards are around 30 cents:

I have example code for an entry control system which uses that reader.

The cards tend to activate at around 3 cm to 5 cm, so that sounds about right. Of course they aren't particularly directional, but if you are driving in a certain direction and it detects a card it is probably in front of you (however possibly off to one side).

You could combine card detection with simple range finding using an ultrasonic detector.

# Answer
> 0 votes
Detecting colour with RGB illumination and an LDR is not particularly accurate in my experience. The idea is you illuminate the card (or whatever) with red light, take an LDR reading, then with green then blue.

This gives you a set of 3 light levels for the different colour components of the object. Combining them together gives you an RGB signature for the object. Ideally, on say a red card, the value from the LDR under red illumination is much stronger, and blue & green much weaker.

RGB LED + LDR colour detection *does work*, but it's not accurate, and it helps to block out ambient lighting. Maybe if you put a lot of time into calibration, it would for you. I had a classroom of 14 kids, each made-up one of these circuits, yet only a couple had any moderate success, if at all. That said, we were using very cheap RGB LEDs and similar quality LDRs.

There's a bunch of stuff you can do to help the accuracy, like subtract readings with only ambient illumination, take multiple readings, etc.

I think you would save yourself a lot of time and frustration buy using a purpose-made colour sensor.

Something like the ADAFruit Colour Sensor - https://www.adafruit.com/products/1334

---
Tags: sensors, photoresistor
---


title: Defining object

text:
# Question
Title: Defining object
I am trying to hide libraries behind another, for simplicity. But I can't deal with the objects required by the libraries. Basically I want to use the objects both in my .cpp and .ino file, but I am getting errors about double definition, or not declared in this scope.

*test.ino*

```
#include "lib.h"
#include "obj.cpp"

void setup() {
  mesh.setNodeID(40);
  mesh.begin();
}

void loop() {
  mesh.update();
}

```

*lib.cpp*

```
#include "Arduino.h"
#include "lib.h"

#include "obj.cpp"

int message = 1;

void send() {

  if (!mesh.write(&message, 'C', sizeof(message))) {

    // If a write fails, check connectivity to the mesh network
    if ( ! mesh.checkConnection() ) {
      //refresh the network address
      Serial.println("Renewing Address");
      mesh.renewAddress();
    } else {
      Serial.println("Sending failed, Test OK");
    }
  } else {
    Serial.print("Sent OK");
  }
}

```

lib.h

```
#ifndef lib_h
#define lib_h

void send();

#endif

```

obj.cpp

```
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
#include <EEPROM.h>

RF24 radio(7, 8);
RF24Network network(radio);
RF24Mesh mesh(radio, network);

```

# Answer
> 1 votes
```
#include "obj.cpp"

```

Don't include .cpp files. That gets them compiled twice (or more) and then you get duplicate definitions. Include .h files only.

What you are calling obj.cpp should probably be obj.h, however I haven't actually tried to compile it.

---

> it says that I have multiple definitions of the three objects

I tried compiling but I don't have the RF24 library. Anyway, this is wrong:

**obj.h**

```
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
#include <EEPROM.h>

RF24 radio(7, 8);
RF24Network network(radio);
RF24Mesh mesh(radio, network);

```

You can't *define* things there (like `radio`) which get included in multiple files. `obj.h` or `obj.cpp` it will be the same thing.

These lines need to be in **one** .cpp file:

```
RF24 radio(7, 8);
RF24Network network(radio);
RF24Mesh mesh(radio, network);

```

Thus you cannot include that file in another file. However you can refer to them by making them `extern` in a header file, eg.

```
extern RF24 radio;
extern RF24Network network;
extern RF24Mesh mesh;

```

---
Tags: c++, library, compile, class
---


# Question
Title: Unpacking Arduino binary data on a python sketch
As a follow up to my earlier post: Simultaneously reading data from multiple serial ports, I am stuck trying to develop a python sketch that can read the incoming serial data from the com port on my Arduino and unpack them from the buffer into two separate cvs files.

One of the csv files would contain the data from the first sensor, while the other would contain the data from the second sensor. I have been able to develop the sketch to a point where on receiving the first header byte the first sensor data is unpacked. I am finding it hard to adjust the sketch to allow for the second byte header to be called to unpack the second sensor data from the data packet. Below is my abbreviated sketch thus far. Thanks all.

```
def run(self):
    #Creating a csv file to read data from the first sensor
    self.click = open("ball_Data.csv", "wb")
    #Creating a csv file to read data from the second sensor
    self.flick = open("rugby_Data.csv", "wb")
    #creating the serial port object
    self.push = serial.Serial('COM6', 9600)
    while True:
        #If the incoming byte is equivalent to '$'
        if node == b'$':
            # the byte object is equivalent to the available bytes
            node = self.push.read()
            #an array to hold the sensor data
            sensor_array = []
            i = 0
            #This while loop initiates a count from 0 to 9
            #through the sensor array
            while i < 10:
                #The available byte present
                malcolm = self.push.read()
                #The next byte
                turnbull = self.push.read()
                #The incoming uint_16 data is unpacked into the variable lingo
                lingo= (struct.unpack('b', turnbull)[0] << 8) | struct.unpack('B',malcolm)[0]
                #The variable lingo is then appended to the sensor array
                sensor_array.append(lingo)
                #If the length of the sensor array is equivalent to 9
                #write the data through each count into the sensor array
                if len(sensor_array) == 9:
                    self.click.write(str(sensor_array[0] ..+ str(sensor_array[9]))
                    #My idea is that this else statement was supposed to trigger
                    #the next header for the second sensor which would be an '#'
                    #sign before unpacking the data
                    else:
                        oldde = self.push.read()
                        sensor_array = []
                        i = 10
                        while i < 20:
                            #The available byte present
                            malcolm = self.push.read()
                            #The next byte
                            turnbull = self.push.read()
                            lingo= (struct.unpack('b', turnbull)[10]<<8)|struct.unpack('B',malcolm)[10]
                            sensor_array.append(lingo)
                            if len(sensor_array) > 19:
                                self.flick.write(str(sensor_array[10]..+ str(sensor_array[19]))

                                The Packet data structure for the first and second sensor is:
                                    Packet1 from sensor 1:
                                        data_array[0] = headerbyte('#')
                                        data_array[1] = acceleration_xAxis
                                        data_array[2] = acceleration_yAxis
                                        data_array[3] = acceleration_zAxis
                                        data_array[4] = temperature
                                        data_array[5] = gyro_xAxis
                                        data_array[6] = gyro_yAxis
                                        data_array[7] = gyroz_xAxis
                                        data_array[8] = checksum
                                        Packet2 from sensor 2:
                                            data_array[9] = headerbyte('$')
                                            .
                                            .
                                            .
                                            data_array[17] = checksum

```

# Answer
> 4 votes
I'm somewhat confused by the flow of your program, so instead I will tell you how I would handle the data.

You have a single-byte header, then 7 bytes of data, followed by a single byte checksum.

PySerial's read is (I believe) blocking by default, so it's simple to read the next serial character - unlike an Arduino. It also has a "multi-byte" read version where it can read a pre-set number of bytes from the stream for you.

So my methodology would be:

1. Read a byte. Is it a '#' or a '$'?
2. If it is, remember which stream you are dealing with, then:
3. Read 7 bytes with `this.push.read(7)` into a byte array (or a string in python \< 2.6)
4. Read one byte for the checksum. If the checksum is correct (whatever calculation you use for that) then unpack the data in the array.
5. Write the data to the correct file depending on the stream you remembered in step 2.

That way you're not duplicating code for each sensor stream, you are just saying "this packet is stream 2" and using that remembered fact once you have received the packet and verified that it's correct.

A better protocol arrangement, though, which is more reliable, involves both a start byte and an end byte, and your whole packet is wrapped in that pair of bytes. You then have a "sliding window" arrangement whereby the incoming data bytes scroll past a window of a fixed width, and when the first and last characters in that window match your start and end bytes you then extract the middle section and do what you need to do with it. That way if you have a $ or a # that is midway through a stream of data it won't trigger reception since the end byte doesn't match. It makes the whole synchronisation of the data more reliable.

For instance, if you have the current data packet that looks like `$ho9*$fup` and you miss the first bit of the data for whatever reason (arduino started transmitting before you were ready to receive, for instance) it might trigger reception on the second `$` which would give you incorrect values. So instead if you have the start character as `$` and the end character as `#` and include a stream number, so your packet looks like:

```
$1ho9*$fup#

```

Then when you scroll that past the window it would look like:

```
 $         #
 v         v
[..........$]
[.........$1]
[........$1h]
[.......$1ho]
[......$1ho9]
[.....$1ho9*]
[....$1ho9*$]
[...$1ho9*$f]
[..$1ho9*$fu]
[.$1ho9*$fup]
[$1ho9*$fup#]

```

And the first and last characters match, so you receive the content.

If you were to miss the first $ the second $ wouldn't match - say the extended stream looks like: `$1ho9*$fup#$2hdiw83bf#` and you missed $1, the window would look like:

```
 $         #
 v         v
[..........o]
[.........o9]
[........o9*]
[.......o9*$]
[......o9*$f]
[.....o9*$fu]
[....o9*$fup]
[...o9*$fup#]
[..o9*$fup#$]
[.o9*$fup#$2]
[o9*$fup#$2h]
[9*$fup#$2hd]
[*$fup#$2hdi]
[$fup#$2hdiw] <= Doesn't match even though it starts with $
[fup#$2hdiw8]
[up#$2hdiw83]
[p#$2hdiw83b]
[#$2hdiw83bf]
[$2hdiw83bf#] <= Matches - starts with $ and ends with #

```

As you can see the synchronising of your packet is then much more reliable. It would normally have incorrectly triggered on the first $ it saw.

There is always a chance that there may be a $ and a # in just the right positions within successive packets to fool the system, but the chances of that are somewhat slim. You can add extra protection against that by "escaping" the start and stop bytes if they appear within your stream. There's many possible ways of handling that if you really need it.

---
Tags: serial, arduino-mega, python, datalogging
---


title: Arduino compiled sketch on sd card

text:
# Question
Title: Arduino compiled sketch on sd card
Hello I have just got my Arduino to read text from a text file and it is running perfectly. I was interested in being able to load a sketch into the Arduino and having it execute it, from and SD card. The Arduino wouldn't be connected to my laptop at all. I researched it and it is possible, with a different boot loader. Which is a bit annoying because I don't want to change the boot loader on my Arduino. I could put it on a standalone atmega chip but lets pretend I don't have those. So I was thinking if you had pre-compiled Arduino code. Which is in hex format and ready to be put on the board, would it be able to be loaded from the SD card? If so how would I go about doing this?

# Answer
Yes it is possible:

**With a different bootloader**.

You need something which will erase the old sketch from the chip, read the data from the SD card, and write that into the flash of the chip. The only thing that can do that is the bootloader or some external device (another ATMega328p chip which we have to pretend you don't have).

Due to the way the architecture works you can only execute code out of the flash, so you need to program your sketch into the flash somehow. And that is the role of the bootloader.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Is it possible to change pin operation from output to input within the Arduino loop (event-driven)?
**Is it possible to change pin operation from output to input within the Arduino loop (event-driven)?**

I would like to change the operation of a couple of Arduino pins from input to output during execution of the Arduino loop in an event-driven way. Is this possible please?

# Answer
> 6 votes
Yes.

Just call `pinMode([pin], [mode])` whenever you want to change from input to output or output to input.

How to decide when to do that is entirely up to you. You can do it any time you choose using any stimulus you like.

---
Tags: arduino-uno
---


title: Arduino disecting a string

text:
# Question
Title: Arduino disecting a string
Hello I have a String that contains the following: "println('hello world')". I want to be able to remove everything from the String except for the text insie the brackets. Bear in mind that this text will change multiple times as the programme runs. How can I remove everything except for what is in the brackets from the string.

```
    String line1 = "println('hello world')";

```

Please help me thx.

# Answer
> 1 votes
> How can I remove everything except for what is in the brackets from the string?

There are a number of String class member functions that can help with this. First, indexOf(val) will help locate the character of interest. Second, substring() will help cut out the part you want. And as a bonus, using lastIndexOf() will allow brackets within the string.

```
String s = "println('hello world')";
s = s.substring(s.indexOf('(') + 1);
s = s.substring(0, s.lastIndexOf(')'));

```

Cheers!

---
Tags: arduino-uno
---


# Question
Title: Trying to run two simultaneous loops that do the same task with different delay cycles
I'm trying to control a pellet stove auger motor in such a way that I can use a toggle switch to do High/Low (H/L) - so the way that I have it now is:

```
 void setup() {
   // initialize digital pin 13 as an output.
   pinMode(13, OUTPUT);
   pinMode(12, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(12, HIGH);
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(2850);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(11250);

```

Which is just LED on/off but it also controls another relay that controls the blower motor - what I'm trying to set up is a H setting that would be the 2850 delay-ON - and then have say: pin 11 have a delay-OFF of 7000, and have pin 13 still resetting to the delay-ON of 2850.

What I mean is:

* loop A: pin12 on -delay 2850 pin12 off -delay 11250
* loop B: pin13 on -delay 2850 pin13 off -delay 7000

I saw and tried the code for 'multi-blink' - as the one I use is pretty much modified 'blink'.

Any assistance would be awesome - I run the one I show above now, on my pellet stove and it was recently -31.4 and worked like a charm, but I'd like to be able to have a high/low option.

PS: I also have a coffee roaster control project as well... help on that one is always appreciated as well.

# Answer
The Arduino Simple Timer library (and other similar timer libraries) are made for exactly this kind of application. Your `setup()` routine calls the SimpleTimer library, naming a callback-function and how often it should get called. Your loop function must then call `timer.run()` reasonably frequently (where reasonably frequently" depends on the timing accuracy and jitter tolerance of your application). `timer.run()` will call each of your callback-functions at its appropriate time. You write the callback-functions to do whatever you need them to do when the timer calls them.

There are one-shot timers and repeating timers - it sounds like your application could one of each per LED: One that fires periodically, to to call a turn-on-LED12 function every (ON\_TIME\_12+OFF\_TIME\_12) ms, and a one-shot that calls a turn-off-LED12 function, started by the turn-on-LED\_12 function for (ON\_TIME\_12) msec. Same for LED13, ( ..., etc.)

Your loop function is free to do whatever else, as long as it calls `timer.run()` frequently enough that your application can meet its timing requirements.
> 2 votes

# Answer
This seems to be the perfect example for the simple scheduler:

```
#include <Scheduler.h>

const int pinA = 12;
const int pinB = 13;

void setup()
{
  Serial.begin(9600);
  while (!Serial);
  Scheduler.start(setupA, loopA);
  Scheduler.start(setupB, loopB);
}

void loop()
{
  Serial.print(millis());
  Serial.print(F(":pinA="));
  Serial.print(digitalRead(pinA));
  Serial.print(F(",pinB="));
  Serial.println(digitalRead(pinB));
  delay(1000);
}

void setupA()
{
  pinMode(pinA, OUTPUT);
}

void loopA()
{
  digitalWrite(pinA, HIGH);
  delay(2850);
  digitalWrite(pinA, LOW);
  delay(11250);
}

void setupB()
{
  pinMode(pinB, OUTPUT);
}

void loopB()
{
  digitalWrite(pinB, HIGH);
  delay(2850);
  digitalWrite(pinB, LOW);
  delay(7000);
}

```

Cheers!
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: What does it mean when there are two addresses listed in the data sheet for a particular register?
I have been trying to grasp a better understand of registers and port manipulation. I have been looking through the ATmega 328P datasheet to look at the different registers.

For some of the registers, I see that there are two addresses listed. For example, for PORTB is listed at 0x05 (0x25). Similarly, for its DDRB and PINB, they are listed at 0x04 (0x24), and 0x03 (0x23), respectively. What does this mean for the register? Thank you.

# Answer
One (the lower number) is the IO port address which is used when using the IN or OUT op-code. The other (higher number) is the memory mapped address.

Different methods of access are more programatically efficient depending on how you are manipulating the values. For instance IN and OUT are more efficient at setting or reading the entire register value, but SBI and CBI on the memory mapped address are more efficient when manipulating individual bits.
> 4 votes

---
Tags: pins, port-mapping
---


title: Arduino substring not working

text:
# Question
Title: Arduino substring not working
Hello I have an Arduino programme where a string is loaded from an SD card. That all works fine. I want to see if the string that has been loaded contains a certain phrase. I am using substring but it doesn't seem to be working. What am I doing wrong? Here's my code:

```
file = SD.open("/classes/basic.txt", FILE_READ);
 Serial.print("Reading, Checking and Compiling \n");
  while(file.available()) {
   character23 = file.read();
   content.concat(character23);
  }
if (content != "") {
  l1 = content;
  Serial.println(l1 + "\n");
}

if(l1.substring(0) == "print"){
  printlnMethod();
}
file.close();

```

it all works until it gets to l1.substring and that doesn't work because the method inside doesn't run. The string that gets loaded into the Arduino from the SD card is : println("hello world");

What am I doing wrong?

# Answer
Substring takes either one or two arguments.

In the single-argument version that you are using the argument specifies the *start* of the substring. The substring then contines to the end of the string. So, since you are asking it to start at index 0 the returned value is the entire string - from 0 to the end.

Instead you probably want to use the two-argument version. In that version you provide two numbers - the index in the string to start from, and the index in the string after the last character you want. So if the string starts with "print" you then want to use `l1.substring(0, 5)` to get the characters 0 to 4 inclusive.
> 0 votes

---
Tags: arduino-uno
---


title: How many bits can an Arduino uno read?

text:
# Question
Title: How many bits can an Arduino uno read?
What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

# Answer
> 1 votes
> What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

A digital input is by nature binary (i.e. a single bit). The answer to your question is therefore one bit per digital input.

The total number of digital inputs depends on the board. It ranges from Arduino Micro (which has fewest less with than 10) to Arduino Mega which has the most with more than 60).

Another possible interpretation of your question is the resolution of an analog pin (ADC). The AVR has max 10 bit resolution.

Cheers!

# Answer
> 0 votes
Do you mean *simultaneous* read or write? The AVR processors are 8-bit processors and their I/Os are grouped into 8-bit registers. If you configure all of the bits in a register to the same direction - all inputs or all outputs - then the entire 8 bits could be read/written at once. in C/C++ you would use the \`PORTWhich I/Os are assigned to which register is designed into the chip - but the data sheet describes which physical pins are connected to which I/O register. You can take advantage of that to make use of a single register's-worth of pins for up to 8 signals that need to be set or read simultaneously.

---
Tags: arduino-uno
---


title: How to upload a sketch via Arduino Nano

text:
# Question
Title: How to upload a sketch via Arduino Nano
I have two Nano boards, but the first one seems the CH340 chipset was burn. :( ,

1. Nano v3, CH340 chipset but unable to identify after connect to my Mac using USB
2. Nano v3, FTDI chipset and in good condition
3. USB to Serial module, using FTDI chipset

I am trying to upload a sketch via a USB-to-Serial module OR another Nano board (or UNO board v3) to my CH340 Nano Board.

**Question:**

1. How to wire them up?
2. Is it need upload a "Arduino as ISP" first?
3. step-by-step tutorial or website talking about this ??

# Answer
> 2 votes
I presume you have boot loader on your Nano, so you can use your USB to serial, just wire (D0)TX-\>RX(USB), (D1)RX-\>TX(USB), GND-GND and supply power to the target Nano. You will need to reboot Nano just before the uploading the code. Uploading is same as usual.

Using other Arduino as ISP needs more wires as well as 2nd Arduino, so i would use above method.

# Answer
> 0 votes
Check this video https://www.youtube.com/watch?v=0zuRukW7o0A

* Reboot and press CMD+R immediately after reboot to enter in Recovery Mode
* Open Terminal from Recovery mode
* Run the command csrutil enable --without kext
* Reboot
* Install driver

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


# Question
Title: Why doesn't my object's method return back to my caller method?
I am creating a miniature computer using an Arduino, and I am creating a full-scale interpreter for it. Everything works, and the code begins to run after calling the runCode method, but once the run is finished it doesn't return to the calling function. I have Serial outputs to tell me where the code reaches.

My code contains an **"Function" object** with a name and a function pointer, an **object to run the code** (with a working Lexer object that splits the inputted code by spaces), and an **in-computer editor** (which completely works except the one function) to input programs to be run.

The function that calls the runCode method for my code-running object (called Joker) **is in the editor**. The problem is, once the runCode finishes, it does not return. **The system halts.** I will post the Function class, runCode Method, and calling method.

P.S. There are Serial prints to determine where the code reaches. It outputs "Function End!", but not "Failed!"/"Succeeded".

P.P.S. It uses a parallax 4x20 Back-lit Single-pin Serial LCD which completely 100% works.

P.P.P.S It uses the QueueList library which is basically a dynamic list that works like a stack.

One more note: The code heavliy uses dynamic lists, function pointers, and lambda expressions, so.... be prepared....

---

Code for Function class (no it does not have any actual functions):

```
class Function {
public:
  String f_name;
  bool (*f_run) (QueueList<float> &stack, SoftwareSerial &lcd);
};

```

Code for runCode method:

```
bool Joker::runCode(QueueList<String> lineTable, SoftwareSerial &lcd) {
  // Set up lexer
  Lexer lexer;
  // Get all lexer words
  lexer.getWords(lineTable);

  String cur_word = "";
  float num_val = 0.0f;
  bool quit = false;

  while(!quit) {
    cur_word = lexer.nextWord();
    if(cur_word == "")
      quit = true;
    else {
      // Get word in uppercase
      cur_word.toUpperCase();

      Serial.println(cur_word);

      // Parse the first number from it
      num_val = cur_word.toFloat();

      // Check if we have a function
      if(queueListContains(cur_word, dictionary)) {
        Function theFunc = getDictionaryFunction(cur_word, dictionary);
        if(!theFunc.f_run(stack, lcd)) {
          error(F("Unable to process word!!"), lcd);
          return false;
        }
      } else if(num_val != 0) {         // check if the parse was good
        stack.push(num_val);            // if it was: push num to the stack
      } else if(num_val == 0) {         // if zero it could be parsing a zero or it could have failed
        if(cur_word.indexOf("0") != -1) // if it didn't fail:
          stack.push(num_val);          // push to the stack
        else {                          // otherwise:
          error(F("Unknown word!!"), lcd);   // Unknown word error
          return false;
        }
      } else {
        error(F("Unknown word!!"), lcd);
        return false;
      }
    }
  }

  // Test printing the stack
  /*while(!stack.isEmpty()) {
    lcd.print(stack.pop());
    lcd.print(' ');
  }*/

  Serial.print(F("Function end!"));
  return true;
}

```

And the caller method:

```
void line_editor::RunProgram(SoftwareSerial &lcd) {
  Serial.println("Running program!!");
  // Move to top line
  currentLine = 0;
  while(!lineTableB.isEmpty()) {
    lineTableA.push(lineTableB.pop());
    // Serial.print(lineTableB.peek());
  }

  // Clear the string
  lcd.write(12);
  delay(5);
  lcd.write(128);

  // Joker language object
  Joker joker;

  QueueList<Function> PrintingWords;

  // Create the printing functions
  Function printWord;
  printWord.f_name = "BC"; // print "Beginning Card"
  printWord.f_run = [] (QueueList<float> &stack, SoftwareSerial &lcd) {
    if(stack.isEmpty()) {
      return false;
    }

    float num = stack.pop();
    lcd.print(num);
    lcd.write(13);

    return true;
  };
  PrintingWords.push(printWord);

  // Print the whole stack
  Function printStack;
  printStack.f_name = "AC"; // print "All Cards"
  printStack.f_run = [] (QueueList<float> &stack, SoftwareSerial &lcd) {
    while(!stack.isEmpty()) {
      lcd.print(stack.pop());
      lcd.print(' ');
    }

    lcd.write(13);

    return true;
  };
  PrintingWords.push(printStack);

  // Add all the functions
  joker.addWords(PrintingWords);

  // Run Program here...
  if(joker.runCode(lineTableA, lcd))
    Serial.println("Success!!");
  else
    Serial.println("Failed!!");

  // lineTableA.push(lineTableB.pop());

  Serial.println("Here!!");

  return;
}

```

Sorry if I confused anyone. If there are any questions, then leave a comment, and I'll try to clear up the confusion. Any help would be appreciated.

**EDIT::ADDING FULL CODE:** Here is a LINK to the rest of the code on github.

Also, here is the rest of the Joker.cpp:

```
void Joker::addWords(QueueList<Function> new_dict) {
  while(!new_dict.isEmpty()) {
    dictionary.push(new_dict.pop());
  }
}

bool Joker::queueListContains(String theWord, QueueList<Function> &list) {
  Serial.println("Finding word:");

  QueueList<Function> temp;

  while(!list.isEmpty()) {
    Function r = list.pop();
    temp.push(r);

    Serial.print(">> ");
    Serial.println(theWord);
    Serial.print(">> equals? ");
    Serial.println(r.f_name);
    delay(5);

    if(r.f_name.equals(theWord)) {
      while(!temp.isEmpty())
        list.push(temp.pop());
      return true;
    }
  }

  while(!temp.isEmpty())
    list.push(temp.pop());

  return false;
}

Function Joker::getDictionaryFunction(String theWord, QueueList<Function> &list) {
  QueueList<Function> temp;

  while(!list.isEmpty()) {
    Function theFunction = list.pop();
    temp.push(theFunction);

    if(theFunction.f_name.equals(theWord)) {
      while(!temp.isEmpty()) {
        list.push(temp.pop());
      }
      return theFunction;
    }
  }
}

void Joker::error(String message, SoftwareSerial &lcd) {
  lcd.write(12);
  delay(5);
  lcd.write(128);

  lcd.print(message);

  delay(2000);
}

```

And the header:

```
#pragma once

class Joker {
private:
  bool queueListContains(String theWord, QueueList<Function> &list);
  Function getDictionaryFunction(String theWord, QueueList<Function> &list);

public:
  QueueList<float> stack;
  QueueList<Function> dictionary;

  void error(String message, SoftwareSerial &lcd);
  void addWords(QueueList<Function> new_dict);
  bool runCode(QueueList<String> lineTable, SoftwareSerial &lcd);
};

```

# Answer
> 1 votes
The short answer here is - It does not return because you have corrupted the stack.
The return address is pushed onto the stack as part of the function call. If you overwrite (corrupt) that address the program cannot jump back to where it was (return).

So where is the cause of the problem?

Does `getDictionaryFunction(cur_word, dictionary)` ever return NULL or an invalid pointer? The code tries to execute it anyway. EDIT: What happens below when *theWord* is not matched or *list* is empty? Actually I'm surprised this compiles, since there's a few paths where no value is returned. (I'm no expert on the GCC AVR compiler, but what happens if we don't assign a return value at all?)

```
Function Joker::getDictionaryFunction(String theWord, QueueList < Function > &list)
{
    QueueList < Function > temp;

    while (!list.isEmpty())
    {
        Function theFunction = list.pop();
        temp.push(theFunction);

        if (theFunction.f_name.equals(theWord))
        {
            while (!temp.isEmpty())
            {
                list.push(temp.pop());
            }
            return theFunction;
        }
    }
    // BAD-JUJU HAPPENS IF WE GET HERE
    assert(false);
}

```

Coding style tip: except in trivial cases, it's good to only return from the bottom of your function. Then the above never happens, and supposedly it's easier for the compiler to optimise. NOTE: I'm unsure if `assert()` will even do anything on Arduino. It's left as a marker to mean *Handle Error Here*.

```
Function Joker::getDictionaryFunction(String theWord, QueueList < Function > &list)
{
    Function dict_func = NULL;
    QueueList < Function > temp;

    while (!list.isEmpty())
    {
        Function theFunction = list.pop();
        temp.push(theFunction);

        if (theFunction.f_name.equals(theWord))
        {
            while (!temp.isEmpty())
                list.push(temp.pop());
            dict_func = theFunction;
            break;
        }
    }
    assert(dict_func != NULL);  // This should never happen
    return dict_func;
}

```

Coding style tip: WoRd CasE ~ lower\_case, mixedCase, CapitalCase, UPPER\_CASE. I use lower case for all\_variable\_names, mixed case for functionNames(), capital case for ClassNames and StructureNames, and upper case for MACROS and CONSTANT\_DEFINITIONS. Pick a system, and stick to it absolutely.

Have you run out of memory - the stack could have hit the heap. What sort of Arduino are you using?

On an Uno, with only 2k of RAM, you might need to make some scope-cuts. Even on an Arduino Mega, you still only have 8k.

Maybe you can make use of a `freeMemory()` function. This will give you an indication of the free space between the stack and the heap. The AdaFruit version is below, but there are others too.

```
int freeRam ()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

```

It may be worthwhile reading their page on Arduino memory usage.

So after having a browse through your code, I can't see any obvious problems. Fix the `getDictionaryFunction()` so you know if it's failing. Check to see if you're running out of RAM - you are making heavy use of it copying strings around, especially with that template class.

Maybe consider re-compiling the code on a workstation in GCC - it wouldn't take much, just change your serial outputs to printf(), and hard-code your input data (or read from a file). That will enable easier debugging.

---
Tags: serial, programming, arduino-mega, c++, pointer
---


# Question
Title: do digital input pins act as a positive or negative
I've gotten contradicting information on the subject. Some say that digital input pins send out positive voltage, and if it goes to ground (for example) it reads LOW but if the pin is connected to power, it will read HIGH. On the other hand, some say that the input pin is receiving voltage from either power (+5V) or ground (0V). which one is it?

# Answer
Digital pins sink or source current. They don't provide negative voltages. If the pin is set to `INPUT` then it is high impedance and will not "send out positive voltage".

However if you activate the internal pull-ups, as Ignacio said, then effectively the pin is connected to +5V via (approximately) a 50k resistor.
> 2 votes

# Answer
It's both, depending on whether or not the internal pullup has been enabled (`INPUT` versus `INPUT_PULLUP`). The pullup ties the input to the positive supply through a moderately large resistance, meaning that it is possible to source a small amount of current from the input pin.
> 1 votes

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


# Question
Title: How can I enable the security bit of a teensy board?
I want to prevent someone from connecting an arduino device to a computer and downloading the code (yes, the hex-dump code) because I want to embed a wifi password inside a device that should be kept secret

With that said, I stumbled upon this answer that mentions a security bit

I would like to ask for more details regarding it - i.e. how can I use it, enable it, what are it's limitations, etc. (Preferably for a Teensy v3.2 board, but if it's standard/generic, I would accept such an answer as well).

# Answer
The Teensy 3.2 board is based on MK20DX256. The processor core is an ARM and not AVR. The best way to learn about security on the MK20DX256 is to read the documentation.

> Chapter 8 Security 8.1 Introduction This device implements security based on the mode selected from the flash module. The following sections provide an overview of flash security and details the effects of security on non-flash modules.
>
> 8.2 Flash Security The flash module provides security information to the MCU based on the state held by the FSEC\[SEC\] bits. The MCU, in turn, confirms the security request and limits access to flash resources. During reset, the flash module initializes the FSEC register using data read from the security byte of the flash configuration field.
>
> NOTE The security features apply only to external accesses: debug and EzPort. CPU accesses to the flash are not affected by the status of FSEC. In the unsecured state all flash commands are available to the programming interfaces (JTAG and EzPort), as well as user code execution of Flash Controller commands. When the flash is secured (FSEC\[SEC\] = 00, 01, or 11), programmer interfaces are only allowed to launch mass erase operations and have no access to memory locations.
>
> Further information regarding the flash security options and enabling/disabling flash security is available in the Flash Memory Module.

The next step is to search for an open-source project that uses the FSEC setting. And by chance the mbed does. Here is link to how it is done in the mbed CMSIS Cortex-M4 Core Device Startup File for the MK20DX256. There should be the same setting in the Teensy Arduino core. Locating that is left to the reader.

Cheers!
> 1 votes

# Answer
It is possible for the AtMega processors - like the Teensy 2.0 (see https://www.pjrc.com/teensy/ ).

Steps:

1. Work out your exact code. It will be a pain to update it once this is done, so thing carefully.
2. Upload the code using ICSP (file-\>upload using programmer). TEST IT HERE!
3. Work out the fuse you need to set. The important one is "RSTDISBL" - this disables the reset pin (makes it behave just like a regular pin). Use the page at http://www.engbedded.com/fusecalc/ to calculate your fuse settings.
4. DOUBLE CHECK IT!
5. Use an ICSP to set the fuse. You will need to work out the 6 pins to connect the ICSP to, since there is no standard ICSP header.

If you did everything right, and the reset pin no longer works - this will protect the code from download!

If anything went wrong (e.g. you set the wrong fuse values - I've been there), or if you want to change the code, you will run into problems. In theory, you can use a high-voltage programmer - like http://www.societyofrobots.com/member\_tutorials/node/239 \- to reset everything to factory, but that takes 20 volts, and there's a high chance one of the other components on the Teensy board will be damaged.

Note that, if you do use the High-voltage programmer, the chip's memory will be wiped, so this can't be used to recover your code.
> 0 votes

# Answer
While this does not answer your question, I believe it may help you with an alternative approach, which won't hide it completely, but will make it a lot harder to figure out.

Rather than keeping the password in plain text (which will be easy to spot in a hex dump), you can hide it somewhat. For example, exclusive-or each byte of the password with a randomly chosen number, put the result in your code; then, when you want to log in to the wifi, exlusive-or it with the same numbers (which must also be on your code).

Note that all the information required MUST be on the Teensy, so it is not impossible to reverse engineer; however, it will be hidden from casual inspection.

Note that, although more complex obfustication is possible (using any off-the-shelf encryption), since both the code and any keys will be available to an attacker, it is a token gesture only.

The Teensy v3 has JTAG, which means a running Teensy can be inspected, single-stepped, all memory and pin states can be viewed & modified. Once someone has your device, it's pretty much a lost cause against a determined attacker.
> 0 votes

---
Tags: teensy
---


# Question
Title: Maintaining pull down on a relay with a shift register
I currently have an Arduino Mega project that uses a relay to switch some high voltage loads. Currently, I use a scheduler library so that every 250ms I check if certain conditions are met and if so I turn off or on the relay. The relay is active when pulled down.

I'm trying to figure out how to transition this project to using a shift register. If the pin needs to be pulled low to be turned on and I want to keep it on, how do I supply a steady "low" signal using a shift register if the register is clocked to only latch every 8 clock cycles (not to mention I only run this code every 250ms). Even if every bit that gets sent by the shift register is low, do I need to no longer use the scheduling library so that every time through the Arduino loop I am sending the low signal so that the low signal can remain constant? With the standard Arduino pin once I set it to low it stays low until I switch it to high. But with a shift register can I keep it low "until I switch it high?"

# Answer
You have misunderstood how shift registers work - and one of the main reasons they exist in the first place.

Shift register ICs have a common 'latch' pin which latches the data present at the input of the cell into the cell, thus updating the output. Some ICs also offer an "output enable", which switches the outputs to a high-impedance state irrespective of the values in the cells - this might not be useful in your case, but the feature exists.

With a serial-to-parallel shift register you can shift in as many bits as you want, at whatever rate you choose, and the outputs will never change **until you trigger a rising edge on the LATCH pin**.

---

**How a (latching) Shift Register works:**

You have eight spaces within the register:

```
             ___    ___    ___    ___    ___    ___    ___    ___
[DATA_IN]-->|___|--|___|--|___|--|___|--|___|--|___|--|___|--|___|-->[DATA_OUT]
            BIT0                                              BIT7

```

The 'spaces' are chained together; at one end of the chain is the `DATA_IN` pin and at the other end is the `DATA_OUT` pin.

Every time there is a rising edge on the `CLOCK` pin, data is *shifted* down the chain from `DATA_IN` to `DATA_OUT`, one space at a time. For example, if the state of the 'spaces' is as the left hand column, then upon the rising edge of the `CLOCK` pin the spaces will change to the values in the right hand column:

```
 DATA_IN PIN = 1  ->  C  -> ?
BIT0 'SPACE' = 0  ->  L  -> 1
BIT1 'SPACE' = 1  ->  O  -> 0
BIT2 'SPACE' = 1  ->  C  -> 1
BIT3 'SPACE' = 0  ->  K  -> 1
BIT4 'SPACE' = 0  ->  E  -> 0
BIT5 'SPACE' = 1  ->  D  -> 0
BIT6 'SPACE' = 1  ->  G  -> 1
BIT7 'SPACE' = 0  ->  E  -> 1

```

You will see that `BIT(n)` changes to the value of `BIT(n-1)`, with `BIT0` changing to the value of `DATA_IN`. The `DATA_OUT` pin is used to daisy-chain multiple shift registers together. The important thing to note here is that **the outputs do not change without a rising edge on the `LATCH` pin**. You can pulse `CLOCK` as many times as you want, with whatever values on `DATA_IN`, and the outputs will not change. Ever.

When you finally trigger the `LATCH` pin, the value in each 'space' is latched into a second row of 'spaces' - these represent the outputs. On a latch trigger, the outputs therefore change to the values of the *last eight* bits that were shifted into the `DATA_IN` pin. For example:

```
OUTPUT = 11001010
                   SHIFT IN "01101111" (starting with RHS first)
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 01101111
                   SHIFT IN "11110000110011001100"
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 11110000   i.e. the LAST EIGHT BITS that were shifted in
                   SHIFT IN "10"
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 10111100   again the LAST EIGHT BITS that were shifted in

```

It is generally never the case with a serial-in-parallel-out register that you would ever shift in less that eight bits at a time, so the last example is only there to illustrate the functioning of the IC.
> 2 votes

# Answer
> ... relay ... active when pulled down ... shift register ... latch ... Arduino ...

TPIC6C595

`shiftOut()` and the '595
> 0 votes

---
Tags: relay, shift-register
---


title: Turn on a light when there is an input

text:
# Question
Title: Turn on a light when there is an input
I am using the pin 4 as an OUTPUT and pin 8 as an INPUT to turn on/off the light, but for some reason it is not working. Light is on all the time, but when I try to input something it gets brighter and doesn't turn off when I don't give anything to pin 8.

LED is connected to pin 4 with a 220 R, and the other side to GND. When pin 8 is connected to 5V pin then the light should come on, and off when I disconnect them.

Here is the code:

```
void setup()
{
  Serial.begin(9600);
  pinMode(4, OUTPUT);
  pinMode(8, INPUT);
}

void loop()
{
   bool on = digitalRead(8);
   if(on)
   {
     digitalWrite(4, HIGH);
   }
   else
   {
     digitalWrite(4, LOW);
   }
}

```

What am I doing wrong?

# Answer
Use input with pullup on pin 8 and a button to ground (GND). See below:

```
const int ledPin = 4;
const int buttonPin = 8;

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
   digitalWrite(ledPin, digitalRead(buttonPin));
}

```

Using the pin as input and disconnecting is not the same as GND. The pin is floating. By using the internal pullup resistor the pin is HIGH when the button is not connected to GND.
> 3 votes

---
Tags: arduino-uno, programming
---


title: ATMega328P-PU not working

text:
# Question
Title: ATMega328P-PU not working
I bought some material on the net to start working with Arduino. I didn't want to buy an Arduino, since it costs a bit too much IMHO, so I bought an ATMega328P-PU, and made an Arduino on a breadboard. However, when I use my USBasp to program it it says that he can't set sck period (settings are: Arduino Uno as Board, USBasp as Programmer). It says that it has loaded the bootloader/program anyway, so I tried to go on and ignore it. The blink program can be loaded via programmer, but it doesn't blink (I'm using a small lamp, connecting it directly to 5V and ground works). Here I describe the circuit:

* First Atmega Pin, Arduino Reset -\> 10 kOhm Resistor (Brown, Black, Black, Red, Brown) -\> Ground (not GND pin);
* 1st pin, Arduino Reset -\> also to USBasp RST;
* 7th pin, Arduino VCC -\> directly to 5V (and USBasp VCC);
* 8th, GND -\> directly to Ground (and USBasp GND);
* 9th, XTAL -\> to one pin of the 16MHz Crystal Oscillator, and to 22 pF capacitor, which connects to ground (not the pin);
* 10th, XTAL -\> exactly as above, but it's connected to the other pin of the same crystal;
* 17th, digital 11 -\> USBasp MOSI;
* 18th, dig 12 -\> USBasp MISO;
* 19th, dig 13 -\> USBasp SCK, and to the lamp whose other pin goes to ground (neither pin nor direct works), but the lamp needs to be disconnected while loading programs to prevent errors (target not responding);
* 20th, AVCC, and 21st, AREF -\> directly to 5V;
* 22nd -\> directly to ground (not pin).

# Answer
> 2 votes
> First Atmega Pin, Arduino Reset -\> 10 kOhm Resistor (Brown, Black, Black, Red, Brown) -\> Ground (not GND pin);

So it's permanently in RESET mode then? How can it ever do anything if you're holding it in RESET all the time?

RESET should be pulled UP by the resistor, not DOWN.

# Answer
> 1 votes
> The blink program can be loaded via programmer, but it doesn't blink (I'm using a small lamp, connecting it directly to 5V and ground works).
>
> 19th, dig 13 -\> USBasp SCK, and to the lamp whose other pin goes to ground (neither pin nor direct works), but the lamp needs to be disconnected while loading programs to prevent errors (target not responding);

The lamp needs to be low power (\< 20 mA) to work this way. If it uses more power you will burn the MCU pin.

Use a LED and a resistor instead. Or at least use a voltmeter.

> 21st, AREF -\> directly to 5V;

This is not a good idea. Should be capacitor to ground. See for instance Uno schematics.

Cheers!

---
Tags: atmega328, hardware
---


# Question
Title: Arduino to breadboard with LM35 temp sensor
I have moved the MCU of the Arduino to a breadboard using these steps https://www.arduino.cc/en/Main/Standalone then interfaced it with an LM35 temperature sensor to the ADC0. But I can't get proper values from the LM35. I think it's because of the Aref or AVcc. Both are just connected to +5? Here is my code:

```
float tempC;
float reading;

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

void loop()
{
    reading = analogRead(0);
    tempC = (reading * 0.4882815) + 5;
    Serial.print(tempC);
    delay(1000);
}

```

I get hex values and sometime high values. What to do with Aref and AVcc?

**EDIT:** I get values like these € Œ

# Answer
> 1 votes
Check the `baud rate` of your serial monitor matches what you have set in your setup() function. In the above code that is 9600. If the baud rate is incorrect you typically get rubbish output in the serial monitor.

You may also want to change the Serial.print(tempC) to

```
Serial.println(tempC,2);

```

To get some decimal places.

As for the circuit ~

* You don't need ARef connected.
* The LM35 VCC should be connected to Arduino 5V
* The LM35 GND to Arduino Gnd (any of them)
* Finally LM35 signal (Vout) to Arduino A0.

# Answer
> 1 votes
> clearly it's not flashing every second.

Is it flashing about every .73 seconds? That would be the period you'd expect if you have a 22.000MHz crystal: period = (16/22 * 1.00 sec). (If so, that is a rather high over-clock rate for the chip but suggests just how hardy they really are.)

> I haven't bought any 16 MHz crystal. What will I do?

Buy a 16MHz crystal. That's the right fix. But you might (if I guessed correctly that you have a 22MHz crystal) - *might* \- get away with trying a baud rate of (16/22) times your present baud rate, de-rating it to compensate for the clock rate. Be as precise as you can. You'll need to reprogram the chip with your Arduino board because the chip's bootloader expects a 16MHz clock.

Or, if it's not 22MHz, you could time a number of blinks (50 or 100), calculate the clock rate error, and re-calculate a baud rate the way I did above. Use a lower baud rate to start with; it is likely to be less affected by small timing errors.

---
Tags: arduino-uno
---


title: PID not working correctly

text:
# Question
Title: PID not working correctly
I'm currently working on a project where I need to use PID to get the correct speed for a motor when it is angled a certain amount.

The problem is that I'm only getting 0.00 and 255.00 as the speed. Nothing in between. The code is supposed to activate when the angle value is more than 1300 and less than -1300. The `ax` variable is from an MPU6050 sensor.

```
int16_t ax, ay, az;

double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp=2, Ki=5, Kd=1;
PID myPID(&Input, &Output, &Setpoint, Kp,Ki,Kd, DIRECT);

void setup() {
  Input = analogRead(ax);
  Setpoint = 100;
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}

void loop() {
  accelgyro.getAcceleration(&ax, &ay, &az);
  int a=ax+10900;
  //Here I set the used variable to around 0. ax is actually around -10900
  //This is always true, this won't be in the final code. This is just making it work.
  if(1) {
    int val;
    val = map(a, -1300, 1300, 0, 1023);
    Input = val;
    myPID.Compute();
    Serial.println(Output);
  }
}

```

# Answer
How fast is your system compared to the loop() sampling time? Does (100-map((ax+10900),-1300,1300,0,1024)) change appreciably during the sub-millisecond loop()?

With kI=5, an error of only 10 will saturate your 0-255 speed output in 26 iterations of loop(), potentially producing the behavior you see. If you don't have control of your sampling time, the integral error can wind up (or down) to the process limits very quickly.

From https://www.arduino.cc/en/Reference/Map map() only linearly transforms the input data to the output data, but does not constrain() it to those limits. If ax=-9000, then val would be greater than 1024. Still, taking the normal working range of ax+10900 to be (-1300,1300) which is then mapped into (0,1024), the Kp=2 term with a setpoint of 100 would produce a range of (-200,2048) constrained to the default (0,255) limits.

Working backwards from the setpoint of 100, through the 0-1024 map is 0.0975 along the (-1300 to 1300) range, or val = -949, or ax = -11849. And the kP=2 times the mapping factor of 1024/2600 would change the output by 2\*1024/2600=0.79 points for each step difference of ax from -11849.

The http://playground.arduino.cc/Main/MPU-6050 pages says the acceleration registers are 16 bit with high sensitivity, and suggests that 50 points of noise is a small variation. If the sensor set for 16 bits for +/-2G into ax, then, each step change 60 micro-G. If that is the source of your ax, then the small variations could easily saturate your control system, making it bang-bang between its output limits with only milli-G variations at the sensor.

Slow down your sampling time, reduce kI, and think of your Kp, Ki, and Kd as conversions of your measured and translated variable ax errors into output space (0-255 speed).

Also, in choosing a sampling time, consider how often you want the PID to make adjustments to the process.
> 2 votes

# Answer
Please respect others by presenting code that is readable. By doing that you may also find obvious errors in your code. Let me clean up the loop() and you will see what I mean.

```
void loop() {
    int a = ax + 10900;
    if (1) {
      int val;
      val = map(ax, -1300, 1300, 0, 1023);
      Input = val;
      myPID.Compute();
      Serial.println(Output);
    }
  }
}

```

So what is "int a = ax + 10900"? "ax" is not defined but the other use of it is as an analog pin number "Input = analogRead(ax)". And "a" is not used.

There is a condition that is always true "if (1)" and so on.

Cheers!
> 2 votes

---
Tags: arduino-uno, motor, mpu6050, pid
---


title: Arduino array length

text:
# Question
Title: Arduino array length
So I have a programme that loads a text file from an sd card into a string array. Each line in the text file is stored in a different string in a string array. Well its supposed to be.

```
file = SD.open("/classes/basic.txt", FILE_READ);
Serial.print("Reading, Checking and Compiling \n\n\n");

for(int i = 0; i < sizeof(result)-1;i++){
 while(file.available()) {
  character23 = file.read();
  content.concat(character23);

}
if (content != "") {
  result[i] = content;
    Serial.println(content);

}

```

}

I want each line in the txt file to be stored in a different string in the array, in chronological order and each string has to be accessible individually. The problem with this code is that it stores the whole text file in one string. How can I fix this?

EDIT: here is what I have now

```
  file = SD.open("/classes/basic.txt", FILE_READ);
  Serial.print("Reading, Checking and Compiling \n\n\n");

 for(int i = 0; i < sizeof(result)-1;i++){
   while(file.available()) {
  character23 = file.read();
  if (character23 == '^') break;
  content.concat(character23);

}
if (content != "") {
  result[i] = content;
  Serial.println(content);

  delay(1000);
}

```

} Serial.println(result\[3\]);

# Answer
To do that, you need to read the file until you reach a line break.

Replace this code:

```
while(file.available()) {
  character23 = file.read();
  content.concat(character23);
}

```

by this:

```
while(file.available()) {
   character23 = file.read();
   if (character23 == '\n') break;
   content.concat(character23);
}

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Exit status 1 expected primary-expression before ']' Arduino
Here's the whole error:

```
 Arduino: 1.6.7 (Windows 7), Board: "Arduino/Genuino Uno"

 *\readMifare\readMifare.ino: In function 'void loop()':

 readMifare:113: error: expected primary-expression before ']' token

    if (uid[] == { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

            ^

 readMifare:113: error: expected primary-expression before '{' token

    if (uid[] == { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

                 ^

 readMifare:113: error: expected ')' before '{' token

 readMifare:121: error: expected '}' at end of input

    }

    ^

 exit status 1
 expected primary-expression before ']' token

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

```

Here's the code

```
 #include <Wire.h>
 #include <SPI.h>
 #include <Adafruit_PN532.h>

 // If using the breakout with SPI, define the pins for SPI communication.
 #define PN532_SCK  (2)
 #define PN532_MOSI (3)
 #define PN532_SS   (4)
 #define PN532_MISO (5)
 // If using the breakout or shield with I2C, define just the pins connected
 // to the IRQ and reset lines.  Use the values below (2, 3) for the shield!
 #define PN532_IRQ   (2)
 #define PN532_RESET (3)  // Not connected by default on the NFC Shield

 // Uncomment just _one_ line below depending on how your breakout or shield
 // is connected to the Arduino:

 // Use this line for a breakout with a software SPI connection (recommended):
 Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);

 // Use this line for a breakout with a hardware SPI connection.  Note that
 // the PN532 SCK, MOSI, and MISO pins need to be connected to the Arduino's
 // hardware SPI SCK, MOSI, and MISO pins.  On an Arduino Uno these are
 // SCK = 13, MOSI = 11, MISO = 12.  The SS line can be any digital IO pin.
 //Adafruit_PN532 nfc(PN532_SS);

 // Or use this line for a breakout or shield with an I2C connection:
 //Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

 #if defined(ARDUINO_ARCH_SAMD)
 // for Zero, output on USB Serial console, remove line below if using      programming port to program the Zero!
 // also change #define in Adafruit_PN532.cpp library file
 #define Serial SerialUSB
 #endif
 #include <Servo.h>

 Servo servo1;

 void setup(void) {
   #ifndef ESP8266
   while (!Serial); // for Leonardo/Micro/Zero
   #endif
   Serial.begin(115200);
   Serial.println("Hello!");

   nfc.begin();

   uint32_t versiondata = nfc.getFirmwareVersion();
   if (! versiondata) {
     Serial.print("Didn't find PN53x board");
     while (1); // halt
   }
   // Got ok data, print it out!
   Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
   Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
   Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

   // configure board to read RFID tags
   nfc.SAMConfig();

   Serial.println("Waiting for an ISO14443A Card ...");
   servo1.attach(9);
 }

 void loop(void) {
   uint8_t success;
   uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
   uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

   // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
   // 'uid' will be populated with the UID, and uidLength will indicate
   // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
   success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

   if (uid[] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

      int position;
      for(position = 0; position < 180; position += 2){
       servo1.write(position);
       delay(20);
      }

   }

```

Please note that I'm using an example from the *Adafruit official PN532 library examples* and trying to edit it.

# Answer
> 3 votes
I wouldn't use `strncmp` because the UID might have zeroes in it. This looks safer:

```
   uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
   uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

   const uint8_t wantedUid [] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 };

   // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
   // 'uid' will be populated with the UID, and uidLength will indicate
   // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
   success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

   if (success &&
      uidLength == sizeof (wantedUid) &&
      memcmp (uid, wantedUid, sizeof wantedUid) == 0) {
      ...

```

I threw in a test for the uidLength being the expected size, otherwise you might find a 4-byte card happens to match the first four bytes of the wanted UID.

`memcmp` compares a block of memory for the number of bytes you specify. It returns zero on a match.

# Answer
> 1 votes
You probably need something like:

```
uint8_t uidTarget[] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 };

...
if (success && !strncmp((const char*) uidTarget,(const char*)uidSource,8)) {

```

Your '=' tries to do an assignment, and an '==' would check if the pointers to the arrays are identical, rather than the contents of the arrays. strncmp() tests equality of strings of characters, and the (const char\*) casts the uint8\_t values as characters.

Nick Gammon's answer is better.

---
Tags: arduino-uno, library, adafruit
---


# Question
Title: How to control nokia 5110 display using esp-01
I am working on a smart device using esp-01 to pull data from internet and display on Nokia 5110 LCD display, and send back the resistive touch inputs to my server and display those on my lcd I am using an Arduino UNO as a secondary device that talks to esp-01, my display and the resistive touch panel. As the esp-01 has got a system on chip, I can program it and do most of the thing my UNO is doing, but because of lack of ports I am using UNO (as far as i know that's the only limitation.. I dont exactly know how is the analog pins on UNO different from the gpio pins on esp) is there any ways if I can do the whole task using only my esp-01 by eliminating UNO. If its only about the less gpio pins on esp-01, will I be able to eliminate UNO by using higher esp such as esp-07 or esp-12E? if not, could you suggest a best way of bi-directional communication between esp and UNO? (so that esp can sent the display info to uno and based on that info, uno can send the resistive touch inputs to esp)

# Answer
Yes, you can use a NodeMCU ESP12E board for example as a standalone microcontroller, you actually don't need an Arduino in your case.
> 1 votes

# Answer
The ESP-12 (don't know about other versions) does have one ADC pin. https://github.com/esp8266/Arduino/blob/master/doc/reference.md#analog-input

I don't know how much your pins display needs. If this is more than one, then you will need a seperate ADC. There are many available as a single chip, but you could also use an arduino as you're doing now.
> 0 votes

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


# Question
Title: Switch MPU6050 to send SCL data through A4 and SDA through A5
I have this MPU6050, and like most of the other MPU6050s, it is set up for SCL to be attached to A4 and SDA to be attached to A5. I have this shield on my Arduino Uno, which is configured for Sainsmart's (the company who made the shield) MPU6050, so the special MPU6050 pins are set up V, G, A5, A4, and my current setup needs V, G, A4, A5. I am using the built-in Wire library, I2CDev library, and the MPU6050 library. So I am wondering whether there is something in these libraries that define which pins it looks for my MPU6050 on, and if so how do I change it.

# Answer
> 1 votes
The pin definition is in hardware. There is nothing you can do to change it. However you could try to reprogram it to use a software i2c library instead of the hardware wire library.

# Answer
> 0 votes
Why not build a small board that converts the pins from V, G, A5, A4 to V, G, A4, A5? Or modify the PCB e.g. cut and rewire the signals in the order you want. It is only two pins!

Cheers!

---
Tags: arduino-uno, pins, i2c, mpu6050, wire-library
---


# Question
Title: Don't know how to work IMU and NRF24 together
I'm having problem on how can I use IMU and NRF24 together.

This is the code that i'm trying to use,

```
 /*
 Copyright (C) 2012 James Coliz, Jr. <maniacbug@ymail.com>
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 version 2 as published by the Free Software Foundation.

 Update 2014 - TMRh20
*/
/**
* Simplest possible example of using RF24Network
*
* TRANSMITTER NODE
* Every 2 seconds, send a payload to the receiver node.
*/
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>
#include <Wire.h>
#include "I2Cdev.h"
#include "RTIMUSettings.h"
#include "RTIMU.h"
#include "RTFusionRTQF.h"
#include "CalLib.h"

RTIMU *imu;                                           // the IMU object
RTFusionRTQF fusion;                                  // the fusion object
RTIMUSettings settings;                               // the settings object

//  DISPLAY_INTERVAL sets the rate at which results are displayed

#define DISPLAY_INTERVAL  300                         // interval between
pose displays

//  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

#define  SERIAL_PORT_SPEED  11520
unsigned long lastDisplay1;
unsigned long lastRate1;
int sampleCount1;

 RF24 radio(7,8);                    // nRF24L01(+) radio attached using
 Getting Started board
 RF24Network network(radio);          // Network uses that radio
 const uint16_t this_node = 01;        // Address of our node in Octal
 format
 const uint16_t other_node = 00;       // Address of the other node in Octal
 format
 const unsigned long interval = 2000; //ms  // How often to send 'hello
 world to the other unit
 unsigned long last_sent;             // When did we last send?
 unsigned long packets_sent;          // How many have we sent already
 struct payload_t {                  // Structure of our payload
 unsigned long ms;
 unsigned long counter;
 };
 void setup(void)
 {
 int errcode;

 Serial.begin(SERIAL_PORT_SPEED);
 Wire.begin();
 imu = RTIMU::createIMU(&settings);                        // create the imu
 object

 Serial.print("ArduinoIMU starting using device "); Serial.println(imu-
 >IMUName());
 if ((errcode = imu->IMUInit()) < 0) {
 Serial.print("Failed to init IMU: "); Serial.println(errcode);
 }

 if (imu->getCalibrationValid())
    Serial.println("Using compass calibration");
 else
    Serial.println("No valid compass calibration data");

 lastDisplay = lastRate = millis();
 sampleCount = 0;

// Slerp power controls the fusion and can be between 0 and 1
// 0 means that only gyros are used, 1 means that only accels/compass are used
// In-between gives the fusion mix.

fusion.setSlerpPower(0.02);

// use of sensors in the fusion algorithm can be controlled here
// change any of these to false to disable that sensor

fusion.setGyroEnable(true);
fusion.setAccelEnable(true);
fusion.setCompassEnable(true);

Serial.println("RF24Network/examples/helloworld_tx/");

SPI.begin();
radio.begin();
network.begin(/*channel*/ 90, /*node address*/ this_node);
}
void loop() {

unsigned long now1 = millis();
unsigned long delta1;
int loopCount1 = 1;

while (imu->IMURead()) {                                // get the latest
data if ready yet
// this flushes remaining data in case we are falling behind
if (++loopCount1 >= 10)
        continue;
    fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(),
imu->getTimestamp());
    sampleCount++;
    if ((delta1 = now1 - lastRate1) >= 1000) {
        Serial.print("Sample rate: "); Serial.print(sampleCount);
        if (imu->IMUGyroBiasValid())
            Serial.println(", gyro bias valid");
        else
            Serial.println(", calculating gyro bias");

        sampleCount = 0;
        lastRate1 = now1;
    }
    if ((now1 - lastDisplay1) >= DISPLAY_INTERVAL) {
        lastDisplay1 = now1;
     RTMath::display("Gyro:", (RTVector3&)imu->getGyro());                // gyro data
      RTMath::display("Accel:", (RTVector3&)imu->getAccel());              // accel data
      RTMath::display("Mag:", (RTVector3&)imu->getCompass());              // compass data
        RTMath::displayRollPitchYaw("Pose:", (RTVector3&)fusion.getFusionPose()); // fused output
       Serial.println();
    }
}

   network.update();                          // Check the network regularly

  unsigned long now = millis();              // If it's time to send a
  message, send it!
  if ( now - last_sent >= interval  )
  {
  last_sent = now;
  Serial.print("Sending...");
  payload_t payload = { millis(), packets_sent++ };
   RF24NetworkHeader header(/*to node*/ other_node);
   bool ok = network.write(header,&payload,sizeof(payload));
  if (ok)
  Serial.println("ok.");
  else
  Serial.println("failed.");
  }
  }

```

My question is what should I put in this part

```
   [code]struct payload_t {                  // Structure of our payload
    unsigned long ms;
    unsigned long counter;
    };

```

so that the output for

```
 RTMath::display("Gyro:", (RTVector3&)imu->getGyro());                //
 gyro data
      RTMath::display("Accel:", (RTVector3&)imu->getAccel());
 // accel data
      RTMath::display("Mag:", (RTVector3&)imu->getCompass());
 // compass data
      RTMath::displayRollPitchYaw("Pose:",
 (RTVector3&)fusion.getFusionPose()); // fused output[/code]

```

will Transmit to the RX ..

What will I put in this part :

```
   Serial.print("Sending...");
   payload_t payload = { millis(), packets_sent++ };
   RF24NetworkHeader header(/*to node*/ other_node);
   bool ok = network.write(header,&payload,sizeof(payload));
   if (ok)
   Serial.println("ok.");
   else
   Serial.println("failed.");

```

Please help me guys. Thanks :)

# Answer
> My question is what should I put in this part

You need to take the data from IMU sensor and put it into the payload. Remember that NRF24L01 allows max 32 byte payload and the library uses some of that.

The RTVector3 is a C++ class with 3 floating point numbers. With AVR float/double that is 12 bytes. This means that you will have to send several messages.

```
enum {
   GYRO_TYPE = 0,
   ACCEL_TYPE = 1,
   COMPASS_TYPE =2
};

struct payload_t {
  int8_t type;
  float data[3];
};

```

This assumes that the sender and receiver have the same data representation. The type field is for the value type (GYRO, ACCEL, COMPASS).

Cheers!
> 1 votes

---
Tags: arduino-mega, mpu6050
---


title: Arduino how to loop a method

text:
# Question
Title: Arduino how to loop a method
Hello I have a method where when you press a button a string is compared with a substring to see if the string contains the substring. The problem is when I load in the string I call the check button press and substring comparing method. Which only ever happens once. I want to know how I can keep calling the method. It sounds simple but it isn't.

```
void loadPrograme(){
   file = SD.open("/classes/basic.txt", FILE_READ);
   Serial.print("Reading, Checking and Compiling \n\n\n");

   for (int i = 0; i < arraysize; i++) {
      while (file.available()) {
         character23 = file.read();
         if (character23 == '\n') break;
         if (character23 != '^') {
            content += character23;
         }
      }
      content.trim();
      if (content != "") {
         result[i] = content;
         content = "";
         delay(1000);
      }
   }
   for (int i = 0; i <arraysize; i++) {
      if(result[i].substring(0,5) == "print"){
         printlnMethod(result[i]);

      }else
         if(result[i].substring(0,5) == "delay"){
            delayMethod(result[i]);
         }else
            if(result[i].substring(0,11) == "buttonPress"){
               buttonMethod(result[i]);

            }

   }

   file.close();
}

void buttonMethod(String s){
   s = s.substring(s.indexOf('{') + 1);
   s = s.substring(0, s.lastIndexOf('}'));
   String btn =" ";
   String daction = " ";
   String indaction = " ";
   btn= s.substring(s.indexOf('"')+1 );
   btn= btn.substring(0, btn.lastIndexOf('"'));
   daction = s.substring(s.indexOf(',')+1);
   daction = daction.substring(0, daction.lastIndexOf('('));
   indaction = s.substring(s.indexOf('~')+1);
   indaction = indaction.substring(0, indaction.lastIndexOf('~'));
   int buttonpressed;
   if(btn == "BUTTON_PIN_ENTER"){
      buttonpressed = 2;
   }else if(btn == "BUTTON_PIN_LEFT"){
      buttonpressed = 3;
   }else if(btn == "BUTTON_PIN_RIGHT"){
      buttonpressed = 4;
   }else if(btn == "BUTTON_PIN_DOWN"){
      buttonpressed = 5;
   }else if(btn == "BUTTON_PIN_UP"){
      buttonpressed = 6;
   }else if(btn == "BUTTON_PIN_ACTION"){
      buttonpressed = 7;
   }

   int btncheck = digitalRead(buttonpressed);
   if(btncheck == LOW){
      if(daction.substring(0,5) == "print"){
         printlnMethod(indaction);

      }else if(daction.substring(0,5) == "delay"){
         delayMethod(indaction);
      }
   }
}

}

```

So basically it loads in the txt file into the string array and loops through it and reads each line. each line is executed. for example if it get the substring of buttonpressed it goes to the buttonmethod(). The problem is in the button method. I want to have the button method keep looping until the button is pressed but it only runs through that method once. How can I keep running threw this method until the button is pressed?

# Answer
> 4 votes
Testing for string equality with '==' is a mistake: https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c The '==' operator on strings will compare the pointers to the strings rather than their content and likely always fail the if() tests.

To loop and block on the last bit, if that is what you mean, you might try:

```
   int btncheck;
   ...
   while(btncheck = digitalRead(buttonpressed)){ // wait for button
      if(strcmp(daction.substring(0,5),"delay")){
         delayMethod(indaction);
      }
   }  // blocked until btncheck == LOW
   if(strcmp(daction.substring(0,5), "print")){
         printlnMethod(indaction);
   }

```

This has the blocking on non-pressed button feature, but also has the same logic as the original. If the string equality tests do not match, it appears you want to do nothing and quickly pass on.

To loop buttonMethod(), put it in a loop:

```
while(1)buttonMethod(string);

```

If you want to condition on getting the button press that corresponds with the string, I'd make buttonMethod return a value and loop conditionally on that:

```
int buttonMethod(...
    int retVal = 0;
    ...

  if(btncheck == LOW){
     retVal = 1;
     ...
  }
  return(retVal);
}

...
while(!buttonMethod(result[i]));  // wait for the button

```

---
Tags: arduino-uno
---


# Question
Title: Writing not permitted on genuino 101 Built in Bluetooth LE (phonegap)
I have a Genuino 101 which has a built in Bluetooth LE module. I have been trying to connect this to my phone using phonegap. I have been using cordova-plugin-bluetootle and with it I have been able to receive data from the arduino and display that data on the phone.
I tired adapting it so that I could send data from the phone to the arduino. I noticed in the CurieBle examples there was a project called "Callback LED" but when I connected to the Arduino from the Phone gap app I noticed in the debug message about characteristics it said `"properties":{"notify": true, "read": true}` but nothing about write. I tried writing "Hello world" (converted into bytes then encoded string) I got an error similar to (I couldn't copy it exactly as it was an alert on the phone): `"error": "write", "message": "Error Domain=CBATTErrorDomain Code = 3 \"Writing is not permitted.\" ..."...`There is more detail to the error message that is not at all relevant and is slightly repetitive.
Here is the arduino code (which is almost straight from the example):

```
#include <CurieBle.h>

const int ledPin = 13; // set ledPin to use on-board LED
BLEPeripheral blePeripheral; // create peripheral instance

BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // create service

// create switch characteristic and allow remote device to read and write
BLECharCharacteristic switchChar("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT); // use the LED on pin 13 as an output
  digitalWrite(ledPin, HIGH);
  while(!Serial);
  digitalWrite(ledPin, LOW);
  // set the local name peripheral advertises
  blePeripheral.setLocalName("LEDCB");
  // set the UUID for the service this peripheral advertises
  blePeripheral.setAdvertisedServiceUuid(ledService.uuid());

  // add service and characteristic
  blePeripheral.addAttribute(ledService);
  blePeripheral.addAttribute(switchChar);

  // assign event handlers for connected, disconnected to peripheral
  blePeripheral.setEventHandler(BLEConnected, blePeripheralConnectHandler);
  blePeripheral.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);

  // assign event handlers for characteristic
  switchChar.setEventHandler(BLEWritten, switchCharacteristicWritten);
// set an initial value for the characteristic
  switchChar.setValue(0);

  // advertise the service
  blePeripheral.begin();
  Serial.println(("Bluetooth device active, waiting for connections..."));
}

void loop() {
  // poll peripheral
  blePeripheral.poll();
}

void blePeripheralConnectHandler(BLECentral& central) {
  // central connected event handler
  Serial.print("Connected event, central: ");
  Serial.println(central.address());
}

void blePeripheralDisconnectHandler(BLECentral& central) {
  // central disconnected event handler
  Serial.print("Disconnected event, central: ");
  Serial.println(central.address());
}

void switchCharacteristicWritten(BLECentral& central, BLECharacteristic& characteristic) {
  // central wrote new value to characteristic, update LED
  Serial.print("Characteristic event, written: ");

  if (switchChar.value()) {
    Serial.println("LED on");
    digitalWrite(ledPin, HIGH);
  } else {
    Serial.println("LED off");
    digitalWrite(ledPin, LOW);
  }
}

```

Here is the write function (phonegap) which is where the error is being produced from :

```
var string = "Hello World";
var bytes = bluetoothle.stringToBytes(string);
var encodedString = _arrayBufferToBase64(bytes);
alert("Service : " + connection.service + "  char : " + connection.char + " Address: " + address);
var params = {"value":encodedString,"service":connection.service,"characteristic":connection.char,"address":address};
alert("params : " + JSON.stringify(params));
bluetoothle.write(function(res) {
alert("Success writing : " + JSON.stringify(res));
}, function(err) {
alert("Error writing: " + JSON.stringify(err));
}, params);

```

I think the error lies in the fact that the Arduino appears not to be advertising the "write" characteristic. BTW the phone tells me that the service was `180d` and the characteristic was `2a37`.

# Answer
> 1 votes
I finally figured it out thanks to finding this GitHub issue. It turns out to be an error with CurieBLE which manifests in a way that means that on IOS it reads the original characteristics and services so when I tried to write it was still thought that the characteristic was `read-only`. I had to restart my phone and it is working now.
There was another thing which is that I needed to send a shorter message, I think it was 20 bytes max per message although I'm not sure, but I sent "h" and the Arduino received it.

---
Tags: bluetooth
---


# Question
Title: Arduino Due interrupt is taken but not executed completely
I tried to build a simple l-meter with my arduino due. I programmed a simple frequency meter with one timer and one counter. The timer takes an interrupt each 10s, 100ms, 10ms and 1ms. But ones the interrupt is taken it is stopped and even a short `Serial.println("Hello World");` does not appear in the serial monitor of the arduino IDE. I don't know what I forgot. Here is my code:

```
#define voltage 26

volatile uint32_t current_range = 10000;               //starts with highest range and decrements. longer measurements produce more precise results. measurements for small l values require 11.111ms
volatile const double c_1 = 2533029590000000.0;        //constant value for l value calculation
volatile double correction_value = 0;
volatile boolean calib = true;
volatile uint32_t counter_value = 0;

void initCounter(){
    pmc_enable_periph_clk(ID_TC0);              //enable peripheral clock for TC0

    REG_TC0_CMR0 = TC_CMR_TCCLKS_XC0;           //External clock 0 connected to PB26 (Digital Pin 22)
    REG_TC0_CCR0 = TC_CCR_CLKEN;                //Enable clock
}

void initTimer(){
    pmc_enable_periph_clk(ID_TC1);              //enable peripheral clock for TC1

    REG_TC0_CMR1 = TC_CMR_TCCLKS_TIMER_CLOCK1;  //42MHz clock
    REG_TC0_IER1 = TC_IER_CPCS;                 //Enable compare RC interrupt
    REG_TC0_IDR1 = ~TC_IDR_CPCS;                //Enable compare RC interrupt (disbale interrupt = 0)
    REG_TC0_CCR1 = TC_CCR_CLKEN;                //Enable clock

    NVIC_EnableIRQ(TC1_IRQn);                   //Enable interrupt in nested vectored interrupt controller NVIC (IRQN number = TC number * channels + channel number)
}

double calc_l(uint32_t CV){
    double freq = (double)CV / ((double)current_range / 1000.0);
    freq = freq * freq;

    return c_1 / freq;
}

void calibrate(){
    Serial.println("---Calibrating... shorten inputs then press enter---");
    while(!(Serial.available() == '\n'));
    Serial.print("Start calibration\n");
    initCounter();                              //initialize counter
    initTimer();                                //initialize timer

    REG_TC0_RC1  = 0x1908B100;                  //RC = 420.000.000 to run 10.000ms

    REG_TC0_BCR = TC_BCR_SYNC;                  //reset and start timer and counter simultaneously
}

void measure(){
    calib = false;

    //Serial.println("---Measure... connect inductivity then press any key---");
    //while(!(Serial.available() > 0));
    initCounter();                              //initialize counter
    initTimer();                                //initialize timer
    REG_TC0_RC1  = 0x1908B100;                  //RC = 420.000.000 to run 10.000ms

    REG_TC0_BCR = TC_BCR_SYNC;                  //reset and start timer and counter simultaneously
}

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

    pmc_set_writeprotect(false);                //disable writeprotect for pmc
    pinMode(13, OUTPUT);
    pinMode(voltage, OUTPUT);                   //set digital pin 26 as output
    digitalWrite(voltage, HIGH);                //set digital pin 26 HIGH
    delay(1000);                                //wait 1 second to get circuit working

    calibrate();
}

void loop() {
    analogWrite(13, 25);
    delay(100);
    Serial.print(REG_TC0_SR1);
    Serial.print(";");
    Serial.print(REG_TC0_CMR1);
    Serial.print(";");
    Serial.print(REG_TC0_IER1);
    Serial.print(";");
    Serial.print(REG_TC0_IDR1);
    Serial.print(";");
    Serial.print(REG_TC0_CCR1);
    Serial.print("\n");
}

void TC1_Handler(){

    uint32_t SR = REG_TC0_SR0;                    //save status register
    uint32_t CV = REG_TC0_CV0;                    //save counter value

    if((SR & TC_SR_CLKSTA) == TC_SR_CLKSTA){      //check whether counter clock is enabled
        if((SR & TC_SR_COVFS) == TC_SR_COVFS){      //check whether counter overflow accured
            switch(current_range){                    //check current range. decrement until smallest range is reached. then print error
                case 10000: REG_TC0_RC1  = 0x280DE80;                   //RC = 42.000.000 to run 1.000ms
                            current_range = 1000;
                            REG_TC0_BCR  = TC_BCR_SYNC;
                            break;
                case 1000:  REG_TC0_RC1  = 0x401640;                    //RC = 4.200.000 to run 100ms
                            current_range = 100;
                            REG_TC0_BCR  = TC_BCR_SYNC;
                            break;
                case 100:   REG_TC0_RC1  = 0x668A0;                     //RC = 420.000 to run 10ms
                            current_range = 10;
                            REG_TC0_BCR  = TC_BCR_SYNC;
                            break;
                case 10:    REG_TC0_RC1  = 0xA410;                      //RC = 42.000 to run 1ms
                            current_range = 1;
                            REG_TC0_BCR  = TC_BCR_SYNC;
                            break;
                case 1:     //Serial.println("Error: l value out of range!");
                            REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                            REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                            break;
            }
        } else {
            if(calib){
                if(CV < 10){
                    //Serial.println("Error: wrong calibration value!");
                    REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                    REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                } else {
                    //correction_value = calc_l(CV);
                    measure();
                }
            } else {
                if(CV < 10){                           //check if counter value is below 10. then l value is to high to get accurate results
                    //Serial.println("Error: l value out of range!");
                    REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                    REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                } else {                               //l value in nH;
                    counter_value = CV;
                    //Serial.print(calc_l(CV) - correction_value);
                    //Serial.print(" nH; ");
                    //Serial.print(CV);
                    //Serial.print(" ticks in ");
                    //Serial.print(current_range);
                    //Serial.println("ms.");
                    REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                    REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                }
            }
        }
    } else {
        REG_TC0_CCR0 = TC_CCR_CLKEN;
        REG_TC0_BCR  = TC_BCR_SYNC;
    }
}

```

It would be very nice if someone could help me with this.

# Answer
Maybe I'm dense, but I don't understand why most of the config code is in the ISR. If the system is getting bound up there, I'd move much of it out and try to simplify it as much as possible, maybe saving only the counter value and the fact that the timer triggered on interrupt, and saving the overflow value if it overflowed. Then, outside the ISR, on the reporting timescale, I'd check that there was valid data and report or reconfigure as needed.

```
int validReading = 0;
uint32_t measuredCount;
int overflowed =0;

void TC1_Handler(){
    measuredCount = REG_TC0_CV0;
    if((SR & TC_SR_COVFS) == TC_SR_COVFS){  //counter overflow occurred
       validMeasurement=0;
       overflow=1;
    else {
       validMeasurement = 1;
       // either reset counter and clock or stop handling interrupts
    }
 }

 loop(){
   ...
   if (validReading) { // report
      ...
   } else {
   if (overflowed ) { // shorten sampling time, calibrate, and initialize
      ...
   }
   if ( measuredCount < 10 ) { // lengthen sampling time?
      ...
   }
   // calibrate and reinitialize
 }

```
> 1 votes

---
Tags: arduino-due, interrupt, timers, isr
---


# Question
Title: Can we detect a magnet using Arduino? If so how?
If so, please tell me and also tell me if any interfacing of other microcontroller needed?

# Answer
> 4 votes
I can't comment yet but you probably are looking for a hall effect sensor.

Something like this is a simple version of the sensor. https://www.sparkfun.com/products/9312

You can then do a digitalRead on the DO pin to detect if a magnet is near the sensor.

You would connect the Vdd to 5v arduino supply and GND to the GND of the board.

# Answer
> 3 votes
If you don't care about measuring the strength of the magnetic field, you can use a magnetic switch (sometimes called a reed switch). A magnetic switch closes when a magnet is put up to it and opens when there is not. The only problem with this is that the magnet has to be within about one inch from the switch. The magnetic switch works just like a normal switch and usually has two contacts. Here is an example.

---
Tags: arduino-uno, sensors, hardware
---


title: Powering a stepper motor

text:
# Question
Title: Powering a stepper motor
I'm working on a project where I need a high torque stepper motor. The stepper motor being used is rated at 12 - 24 volts and when I used a 12 volt battery supply composed of 8 AA batteries it appeared to work fine.

Because I wanted higher torque I set the pot on the Easy Driver to 0.5 amps which is within what was recommended for the motor, and used a Lithium Ion battery originally being used for a power drill rated at 18V and 1.5Ah.

When I connected the battery to the easy driver the motor got very hot and would shake when I tried to turn it but not turn. Now the motor will not work with the 8 AA batteries either. Heres a link to the motor US Ship OSM 5:1 Planetary Gearbox Nema 8 Stepper Motor Samll Size High Torque.

What did I do wrong and how can I fix it?

P.S. I am using a photon as the micro controller and the motor is being controlled using the Blynk app I eliminated the chance of it having to do with the photon or Blynk App.

I found out that the battery I'm using is the Makita BL1815 and it is really composed of 2 batteries which are both rated at 15C. I am not sure if C-rating adds or stays the same when you are using two batteries. When I measure the Voltage on the test points I get 4.27V and when using a formula to find current for the Easy Driver I get 0.480A.

# Answer
How did you set the amps on the http://www.schmalzhaus.com/EasyDriver/ to 0.5A? What was the voltage at the test point? The EasyDriver v4.5 schematic says the formula for coil current is A = V/6. So rearranging, V=A\*6, and to get 0.5A, the voltage should be 0.5\*6=3V at the motor driver's test point.

The linked motor spec is 0.6A max per coil, and if things went wrong, you could have overloaded a motor. The 18V battery could have easily provided 1.8 amps to the 10ohm coil in the motor for a bit, before 3x the rated current of the coils would burn it out, or the easydriver went into thermal shutdown or something.

The easydriver looks like it would be capable of controlling the current adequately, but if misconfigured, could easily overcurrent the motor.
> 2 votes

---
Tags: motor, battery, stepper
---


# Question
Title: How to send a pitch bend MIDI message using arcore?
I'm new to MIDI and started playing with an Arduino Leonardo and arcore. Based on the example code, I can easily send `noteOn/noteOff/controlChange` messages, but I can't seem to send a pitch bend message.

Having a look at this table:

```
0xE0    Chan 1 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE1    Chan 2 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE2    Chan 3 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE3    Chan 4 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE4    Chan 5 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE5    Chan 6 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE6    Chan 7 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE7    Chan 8 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE8    Chan 9 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE9    Chan 10 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEA    Chan 11 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEB    Chan 12 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEC    Chan 13 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xED    Chan 14 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEE    Chan 15 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEF    Chan 16 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)

```

I've tried to send a message like so:

```
MIDIEvent pitchwheel = {0xe0, 127,127};
MIDIUSB.write(pitchwheel);

```

but this didn't work and I'm not sure what I'm missing/doing wrong.

Any hints/tips will be helpful.

# Answer
arcore creator Ralf Kistner provided the answer:

```
// The pitch bend value is a 14-bit number (0-16383). 0x2000 (8192) is the default / middle value.

// First byte is the event type (0x0E = pitch bend change).
// Second byte is the event type, combined with the channel.
// Third byte is the 7 least significant bits of the value.
// Fourth byte is the 7 most significant bits of the value.
void pitchBendChange(byte channel, int value) {
  byte lowValue = value & 0x7F;
  byte highValue = value >> 7;
  MIDIEvent event = {0x0E, 0xE0 | channel, lowValue, highValue};
  MIDIUSB.write(event);
}

```
> 1 votes

---
Tags: arduino-leonardo, midi
---


title: Arduino loading from file

text:
# Question
Title: Arduino loading from file
Hello I have a programme that loads a piece of text from a file. In this case it loads "drawrect(4,10,20,20);" from the txt file and stores it in a string. I then use substrings to change the string into just "4,10,20,20" which is good but I need to simplify it down even more to four strings each with one of those 4 numbers in it.

Currently I use:

```
void drawRectMethod(String s){
  String var1,var2,var3,var4;
  s = s.substring(s.indexOf('(') + 1);
  s = s.substring(0, s.lastIndexOf(')'));
  Serial.println(s);
}

```

to simplify the string down to "4,10,20,20" but this wont work to store each number in a separate string. How can I can I store each variable in a separate string. The numbers will be stored in var1 - var4.

# Answer
Need some more help? As I previously wrote that snippet I might as well continue until you understand how to use indexOf() and substring().

```
  String s = "draw(10,20,30,40)";

  // Parse the argument list
  s = s.substring(s.indexOf('(') + 1);
  s = s.substring(0, s.lastIndexOf(')'));

  // Parse comma separated arguments
  String arg[4];
  for (int i = 0; i < 3; i++) {
    int ix = s.indexOf(',');
    arg[i] = s.substring(0, ix);
    s = s.substring(ix + 1);
    Serial.println(arg[i]);
  }
  arg[3] = s;
  Serial.println(arg[3]);

```

There is absolutely no error handling in this. You will have to add that. You can also improve the parse of the right parenthesis. That could be added last instead.

Later in the game we will come to why using String is a bad idea and why a character buffer and the standard library functions such as strtok() is a much better solution strategy both performance and memory footprint and especially heap.

```
  char* s = (char*) "draw(10,20,30,40)";
  s = strtok(s, "(),");
  Serial.println(s);
  while ((s = strtok(NULL, "(),")) != NULL)
    Serial.println(s);

```

Maybe the simplest solution is to use sscanf(). That will also do the conversion from text to binary.

```
  const char* s = "draw(10,20,30,40)";
  int x, y, w, h;
  int n = sscanf(s, "draw(%d,%d,%d,%d)", &x, &y, &w, &h);
  Serial.print(F("n="));
  Serial.println(n);
  Serial.print(F("x="));
  Serial.println(x);
  Serial.print(F("y="));
  Serial.println(y);
  Serial.print(F("w="));
  Serial.println(w);
  Serial.print(F("h="));
  Serial.println(h);

```

Cheers!
> 2 votes

---
Tags: arduino-uno
---