# Question
Title: Arduino Uno not able to handle 2-dimensional array
Now the code I'm writing in Arduino (Using Arduino) uses multiple 2-dimensional arrays. Now when I print some thing using the Serial Monitor it prints it correctly but when I declare and initialize the 2-dimentional array it won't print it.

Code:

```
void setup()
{
  Serial.begin(9600);
  int image_width = 56;
  int image_height = 96;

  int image_result[image_width][image_height];
  for (int i=0; i<image_height; i++) {
    for (int j=0; j<image_width; j++) {
      image_result[j][i] = 5;
    }
  }

  Serial.print("code works");
}

```

Now in this case "code works" does not print but when I remove the array declaration and initialization code works is printed. What is the problem?

Do 2 dimensional arrays work differently in Arduino or is it a space issue?

# Answer
2D arrays work fine on arduino, but you run out of space very quickly.

An uno has 2 kilobytes of ram; your array has 56\*96 = 5376 2-byte elements.

I would guess that you are writing over some critical memory value with a 5 at some point causing the program to fail.
> 9 votes

# Answer
You are trying to use more memory than you have available: 96 * 56 * 2 = 10.752KBytes. Not much that the MCU can do when this happens.

If you look into the datasheet, you'll see that your microcontroller (ATmega328p) only has 2KBytes of RAM.

I guess the question then, is to ask yourself if you really need that large an array. You may consider getting an external flash chip or an SDcard shield. If you only need it for read-only purposes (such as a lookup table), you can use some of your flash program memory (you have 32KBytes).
> 3 votes

# Answer
This is what I fed my Uno:

```
#define IMAGEWIDTH 56
#define IMAGEHEIGHT 96

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

  int i, j;
  int image_result[IMAGEWIDTH][IMAGEHEIGHT];

  for (i = 0; i < IMAGEWIDTH; i++) {
    Serial.print("\nIMAGEWIDTH ");
    Serial.print(i + 1);
    Serial.println(":");
    for (j = 0; j < IMAGEHEIGHT; j++) {
      image_result[i][j] = i + j;
      Serial.print("image_result[");
      Serial.print(i + 1);
      Serial.print("][");
      Serial.print(j + 1);
      Serial.print("]: ");
      Serial.println(image_result[i][j]);
    }
  }
  Serial.println(F("\nDone!"));
}

void loop() {
}

```

This will run over the whole array, while printing progress over Serial, which then print "Done!" once it is. I suggest changing:

```
#define IMAGEWIDTH 56
#define IMAGEHEIGHT 96

```

To lesser values, unless you have a few good minutes at hand.
> 0 votes

# Answer
Indeed, this is an issue of RAM available. If you do not need 8 bits per piece of data (if you are perhaps willing to reduce image quality, for example), consider compacting your data such that you have multiple piece of data per bit. For example, hex values or BCD (binary coded decimals) could work, depending on the size of each piece of data.
> 0 votes

# Answer
As others have noted, your array is larger than the available RAM in your Arduino. Others mentioned Flash memory which could be a solution for you. Your Arduino has 32 KB of memory which could hold your array. See the following reference for more info about Flash memory. Keep in mind that Flash and EEPROM have a limited number of write cycles before becoming unreliable.

Hidden Powers - storing data in Flash and EEPROM
> 0 votes

# Answer
In case the matrix is mostly empty or anyway has values that can be calculated programmatically, sparse arrays might come to the rescue. It requires memory allocation and hopping, so the access time to individual elements is not deterministic, but you can calculate the worst-case scenario.
> 0 votes

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


title: PPM from remote control is very noisy

text:
# Question
Title: PPM from remote control is very noisy
I tried to use a function that could smooth out the PPM by using 10 input values and finding the averages. But even this still doesn't seem to be a good way prevent the noise that is occurring when using my Remote. Is there any way to fix this? Here is the code from the smoothing project. (Although i feel it's not really necessary to add it here, but here it is anyways.)

My code is using the PPMrcIn library. An int is created and then using if statements I make an object do work. My problem is that i have a very small window for work.

My values are between 50 and 200
Where 140 is the preferred midpoint i'd like to work with.
This is my somewhat cryptic number line.
140 is in the middle. Where my window of stability is between 130 and 150
and values below 100 and above 180 are where the robot does some work.
50 ---x---\<100-----130--\<140\>--150----180\>---x---200

```
  /*

    Smoothing

    Reads repeatedly from an analog input, calculating a running average
    and printing it to the computer.  Keeps ten readings in an array and
    continually averages them.

    The circuit:
      * Analog sensor (potentiometer will do) attached to analog input 0

    Created 22 April 2007
    By David A. Mellis  <dam@mellis.org>
    modified 9 Apr 2012
    by Tom Igoe
    http://www.arduino.cc/en/Tutorial/Smoothing

    This example code is in the public domain.

  */

  // Define the number of samples to keep track of.  The higher the number,
  // the more the readings will be smoothed, but the slower the output will
  // respond to the input.  Using a constant rather than a normal variable lets
  // use this value to determine the size of the readings array.
  const int numReadings = 10;

  int readings[numReadings];      // the readings from the analog input
  int index = 0;                  // the index of the current reading
  int total = 0;                  // the running total
  int average = 0;                // the average

  int inputPin = A0;

  void setup()
  {
    // initialize serial communication with computer:
    Serial.begin(9600);
    // initialize all the readings to 0:
    for (int thisReading = 0; thisReading < numReadings; thisReading++)
      readings[thisReading] = 0;
  }

  void loop() {
    // subtract the last reading:
    total= total - readings[index];
    // read from the sensor:
    readings[index] = analogRead(inputPin);
    // add the reading to the total:
    total= total + readings[index];
    // advance to the next position in the array:
    index = index + 1;

    // if we're at the end of the array...
    if (index >= numReadings)
      // ...wrap around to the beginning:
      index = 0;

    // calculate the average:
    average = total / numReadings;
    // send it to the computer as ASCII digits
    Serial.println(average);
    delay(1);        // delay in between reads for stability
  }

```

also link to my code in github https://github.com/tisaconundrum2/RCRoomba/blob/master/RCRoomba2.2.ino

Since this is being asked. Let me clarify on this black voodoo thing called a PPM.

Many RC Transmitters and Receivers provide access to the PPM Stream, this is a single stream of pulses which includes the information for all of the receiver channels in a single connection.
The stream is made up of a series of short pulses, the first pulse is the start marker. The time between the start marker and the start of the next pulse defines the pulse length for channel one. The time to the next pulse defines the pulse length for channel 2 and so on. The end of the pulse stream is marked by a gap know as the frame space. This gap indicates that there are no more channels to receive and the next pulse will be the start of a new frame. Each frame contains the pulse widths for all of your receiver channels. Note - unlike servo signals, in a PPM Stream it is the gaps between pulses that defines the pulse width for a channel, not the duration of the pulse itself which can be very short. -http://rcarduino.blogspot.com/2012/11/how-to-read-rc-receiver-ppm-stream.html

As discussed above. My PPM signal is highly varied. I want to be able to just get a solid 140. However, the signal will jump irratically between 135 and 142 for reasons I do not completely understand. In an attempt to clear this fuzziness I tried to go for smoothing.

# Answer
> 1 votes
First, I want to thank you for making this post. I have a few remote-controlled cars/boats/helicopters, and I've often wondered how the remote control works. :)

---

To answer your question - and because I was too lazy to work out how to connect to an actual controller - I made a "remote simulator" like this:

```
// PPM generator

const byte SIGNAL_PIN = 3;
const int SIGNAL_COUNT = 6;
const unsigned long PULSE_WIDTH = 300;  // µs
const unsigned long BLANK_TIME = 25;    // ms
const int widths [SIGNAL_COUNT] = { 600, 2000, 1000, 1500, 2200, 2400 };

void setup ()
  {
  pinMode (SIGNAL_PIN, OUTPUT);
  }  // end of setup

void loop ()
  {
  delay (BLANK_TIME);
  digitalWrite (SIGNAL_PIN, HIGH);  // start
  delayMicroseconds (PULSE_WIDTH);
  digitalWrite (SIGNAL_PIN, LOW);   // end of start pulse

  for (byte i = 0; i < SIGNAL_COUNT; i++)
    {
    delayMicroseconds (widths [i] - PULSE_WIDTH);
    digitalWrite (SIGNAL_PIN, HIGH);  // start of pulse
    delayMicroseconds (PULSE_WIDTH);
    digitalWrite (SIGNAL_PIN, LOW);   // end of pulse
    }  // end of for loop

  delay (1000);
  }  // end of loop

```

This is intended to generate a series of pulses (six in this case) which might be generated by some fancy ~~toy~~ fun device.

---

Output from it:

As you can see from the cursor, it is doing what it is bid. The pulse width shown by the scope cursor is indeed 2000 µs, as per the table of widths.

*Note*: Output on pin 3 on the Uno.

---

Now we need a decoder. So let's use interrupts:

```
const byte SIGNAL_PIN = 2;
const int SIGNAL_COUNT = 6;

volatile unsigned long widths [SIGNAL_COUNT + 1];
volatile byte count;

unsigned long lastPulse;

// ISR
void gotPulse ()
  {
  unsigned long now = micros ();

  // a long gap means we start again
  if ((now - lastPulse) >= 25000)
    count = 0;

  lastPulse = now;
  if (count >= (SIGNAL_COUNT + 1))
    return;

  widths [count++] = now;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  attachInterrupt (0, gotPulse, RISING);
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  }  // end of setup

void loop ()
  {
  if (count >= SIGNAL_COUNT)
    {
    Serial.println (F("Got sequence."));
    for (int i = 1; i < SIGNAL_COUNT + 1; i++)
      {
      Serial.print ("Channel ");
      Serial.print (i);
      Serial.print (" = ");
      Serial.println (widths [i] - widths [i - 1]);
      }
    count = 0;
    }

  }  // end of loop

```

This uses an interrupt (on pin 2 on the Uno) on the rising edge to detect the start of the pulses. It stores them, and then works out their widths later.

---

Results?

```
Got sequence.
Channel 1 = 612
Channel 2 = 2020
Channel 3 = 1016
Channel 4 = 1512
Channel 5 = 2220
Channel 6 = 2428
Got sequence.
Channel 1 = 612
Channel 2 = 2020
Channel 3 = 1016
Channel 4 = 1512
Channel 5 = 2220
Channel 6 = 2424
Got sequence.
Channel 1 = 616
Channel 2 = 2020
Channel 3 = 1012
Channel 4 = 1516
Channel 5 = 2220
Channel 6 = 2424
Got sequence.
Channel 1 = 616
Channel 2 = 2020
Channel 3 = 1012
Channel 4 = 1516
Channel 5 = 2216
Channel 6 = 2432

```

Highly consistent results, with a small error factor of around 16 µs compared to `600, 2000, 1000, 1500, 2200, 2400`

---

In case it isn't clear, this test required two Unos. One to generate the pulses and a second one to decode them:

The one with the USB cable is the decoder, which writes to the serial port. The other one is powered by 5V/Gnd from the first one, and the white wire is the data with the pulses.

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


# Question
Title: How to sense mobile signal coming to a room using arduino uno
How to make arduino sense mobile signal coming into a room and display the calling number on an LCD screen

# Answer
> 3 votes
You can't.

Mobile phone signals don't respect artificial boundaries like a room's walls. You can detect the mobile phone signal from the local cell, but you can't narrow it down to "what is talking to a device in this room".

And if you could just intercept the signals and find out who was calling whom there wouldn't be much security, would there? It's all encrypted and locked down - you can't get at that sort of information "from the air".

What you *could* do though, is to have your mobile phone send out the phone number of an incoming call via bluetooth (many hands free kits already use this kind of facility) and have your Arduino receive that information to display it.

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


title: Split a string as 2x16 for LCD

text:
# Question
Title: Split a string as 2x16 for LCD
How do I split a string into two based on it's length to display on a 2x16 LCD?

I have seen a function called length() to get the length of a string. But, any ideas how to split it in to 2x16 and trim the rest of the string?

Thanks

# Answer
> 3 votes
String::Substring does take a start and an end value. So you can do something like this:

```
String s1 = longtext.substring(0,15);
String s2 = longtext.substring(16,31);

```

# Answer
> 2 votes
That's what `String::substring()` is for. Simply take the first 16 characters and the characters from 16 to 32, and output them.

---
Tags: lcd
---


# Question
Title: Arduino Pro Mini and GDEW0154T1 ePaper (e ink) display
I just got my Arduino Pro Mini and GDEW0154T1 ePaper display (GDEW0154T1 display) and I'm trying to figure out a way to make them "talk". I started reading documentation and multiple sites but I still have no idea. I bought Breadboard, USB connector for Arduino and cables.

I think I need some port to connect display to Breadboard. Could you tell me where to look for it? What next?

Thank you for any advice!

# Answer
You need to build a special driver board. Most of the drive circuitry is on the main chip built into the display, which is convenient, but it requires a number of capacitors (which are too big to fit into the display itself) on the various voltage pins, and a special power control circuit to ensure that the different voltages get enabled at the right time.

The datasheet details the capacitors that need connecting (Figure 7.5(2)), as well as the power control circuit (Figure 7.5(4)).

There is another small circuit snippet there as well (Figure 7.5(3), temperature sensor) but I haven't worked out the relevance of that yet.

Also you will need the right FPC connector, and a surface mount PCB to solder it on to, as well as the ability to solder it (reflow oven), so it's not a trivial task. You may be able to find the right connector already soldered onto a breakout board if you look around - but make sure it *is* the right one, since there are many variations - number of pins, pitch of pins, upper or lower connection, etc.
> 2 votes

---
Tags: display
---


# Question
Title: How to make C++ code compatible with Arduino IDE?
I wrote some code in C++ (Used libraries like fstream, vectors etc.) Now when I transferred the code to Arduino it wouldn't compile so I added the following library: https://github.com/maniacbug/StandardCplusplus I downloaded the IDE from here: https://www.arduino.cc/en/main/software

Now almost all my code works: All the libraries I've used work except for fstream which I've used to read a specific file.

Now is there a certain problem with the 'StandardCplusplus' library and how can I counter this problem.

Plus can someone give me an alternative for fstream that works with Arduino. Was reading a bmp image using C++. Now fstream works in a certain way (reads the file in a certain way). Is there some alternative to fstream.

# Answer
> 4 votes
When you run that library on the Arduino and ask it to open a file, where do you imagine it would read the file from? Your Arduino has no hard disk or other file system.

One way to solve this is to include a library that emulates a read-only file system in the Arduino's flash. I dunno whether this exists (such libs do exist for for some other targets, for instance for the Nintendo DS), but it would be a bit of overkill IMO.

Another way is to include the data that is in the file in your program, as a const (expr) array of bytes, and read from that array instead of from the file. But if you have a library that is coded to use file read calls this would require some rewriting.

A third approach would be to do the reading and interpreting of the file on your host PC, output the *interpreted* content to a const (expr) byte array, and include that in your application. This frees you from having to include the bmp-read code in your image.

# Answer
> 2 votes
If you want to write C++ for an Arduino, I'd recommend you cease using the Arduino IDE and instead use Atmel Studio. The microcontroller on board is an Atmel AVR, and you can write for that using the gcc-avr toolchain that comes with Atmel studio.

You'll lose the spiffy libraries that come with the arduino platform that abstract away a lot of the intricacies of the hardware, and you'll instead be looking at the AVR datasheet and the schematic of the arduino, but you'll learn quite a bit in the process and have direct control over the hardware.

With all that said though, the AVR does not have a file system so using fstream doesn't make any sense to begin with.

# Answer
> 1 votes
The Arduino IDE *does* compile your code using the avr-g++ compiler. In other words, it *is* C++.

> Was reading a bmp image using C++.

This isn't practical on the smaller Arduinos, at least, because they have so little RAM. They also don't have a file system. There is a streaming library for output, which is very handy for streaming out things to Serial, LCDs, etc.

One of the replies here mentioned that if you switch to Atmel Studio you can look at the datasheet and get down to the intricacies of the hardware. Well, you can certainly do that as well with the IDE. All the hardware registers are available for use. I often use the "bare" registers for timers, watchdog, interrupts etc.

Also Atmel Studio only runs on Windows. You are out of luck if you use a Mac or Linux.

There is also a port of the Standard Template Library for the Arduino, if you want to use vectors, lists, maps etc.

There is also another port of the STL which may work better and be easier to install.

# Answer
> 1 votes
Are you using Arduino UNO? Look at the datasheet and see how much RAM the Arduino has. Assuming you are using Arduino Uno, it should be around 2kilobyte or less. So it is highly likely not to have enough memory to read the BMP file. Even if you are trying to read very small BMP file, the code reading the file would vary depending where you are reading the BMP file from (SD Card, SPI Flash memory, etc.) It cannot read files directly from your computer using just fstream.

# Answer
> 0 votes
To answer your compile problem.. Are you using c++11? The issue could be that Arduino Compiler may not support entire C++11 features.

So if you cant find an alternative for fstream (I dont know any) then you have to find a different way compile the C++11 code and upload it. You can do this with a Makefile, avr-gcc. Its plenty of generators out there.

---
Tags: c++
---


# Question
Title: Does the arduino board have to be always physically connected to the electronic device you are running?
If I have a basic electronic board with some LEDs and sound fx and I want to program them (I'm a beginner, learning about arduino), does the arduino board always have to be connected to the actual electronic board I'm running or is there a way to "upload" the programming to the circuit board?

# Answer
> 2 votes
If the "basic electronic board" is programmable, then yes, you can upload a program to it.

In general, though, "some LEDs" and similar devices are not programmable, and without something to *drive* them (i.e., the Arduino) they won't do anything at all. The Arduino is what has the program and it tells the "basic electronic board", moment by moment, what it should be doing. It is the *brain* of the operation. Remove the brain from someone and you'll find their body no longer functions.

# Answer
> 0 votes
And Arduino UNO is basically a ATMega328 chip (with some extras) on a circuit board. So if you add an ATMega328 to your own circuitboard, you don't need an Arduino Uno.

# Answer
> 0 votes
If the question is "Can I program the Arduino without anything else connected to it?", then yes, you can program it with out the sound and light board connected. But the program will start running shortly after the upload finishes.

If some devices were connected to it and some were not, it's possible the program won't function properly at that point (and obviously the not-connected devices won't function at all!), so you should make sure the Arduino can't or won't try to do anything to the few connected ones that might be harmful when some others are not connected, in case that is possible (this would be an unusual, but plausible, situation).

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


title: xBox receiver code output is scrambled

text:
# Question
Title: xBox receiver code output is scrambled
I'm running the following code:

```
#include <XBOXRECV.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
XBOXRECV Xbox(&Usb);

void setup() {
  Serial.begin(115200);
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); //halt
  }
  Serial.print(F("\r\nXbox Wireless Receiver Library Started"));

}

void loop() {
  Usb.Task();
  if (Xbox.XboxReceiverConnected) {
    if (Xbox.getAnalogHat(LeftHatY) == 0) {
      Serial.print(Xbox.getAnalogHat(LeftHatY));
    }
   Serial.print("TEST");
  }
}

```

After running the example that the library includes and a spin off I wrote for test purposes I keep getting random output, this is just some of it:

> 9�\]==�=�~=���y��:.�:�:����9�=��������:�:�\\=���^=�?�}�:^���:�|\]=9�\\=�������:�ܗ��.\�~=���

# Answer
Seems like wrong baud-rate. Change baud-rate in the Arduino IDE serial monitor.
> 0 votes

---
Tags: arduino-uno, programming, shields, usb
---


title: Hall Effect Current Sensor Wiring

text:
# Question
Title: Hall Effect Current Sensor Wiring
I need help with wiring this current sensor so that I can read the output voltage as an analogue input. - http://www.tamuracorp.com/clientuploads/pdfs/engineeringdocs/L03SXXXD15.pdf

This is how I have it wired right now - 1 - +15v 2 - 15v ground 3 - output to arduino 4 - arduino ground

This seemed simple but reviewing the wiring diagram again I have a hunch that this is not at all how I should be wiring this up.

Thanks

# Answer
Looking at the datasheet the output is +/- 4 volts, so this is not suitable to connect directly to the Arduino, because the input pin will not tolerate -4 V.

I am no Hall Effect sensor expert, but a quick search on Google showed another potential problem: If you are planning to measure AC current, and you try to sample the output on the Arduino, the reading will average out to zero (half of the time positive, half of the time negative).

What may help - and this is a bit of a guess - is to put a diode in series with the sensor output, oriented so that you only get the positive pulses. That is, the anode connected to the Hall Effect sensor, and the cathode (with the black line) on the Arduino side.

Then you probably want to smooth the voltage so you can read the average voltage with the ADC converter, rather than what it is at a particular millisecond. A low-pass filter will take an average, which you can then read with `analogRead`.

Something like this:

---

I made up that circuit driven by a signal generator (8 V peak to peak, i.e. +/- 4 V) and found a 400 mV drop over the diode using a 1N4148 normal diode, and a 160 mV drop using a BAT85 Schottky diode.

With a 3 V peak-to-peak signal the voltage drop with the Schottky diode reduced to 120 mV, so it wasn't totally linear.

---

As Majenko pointed out, there is a voltage drop over the diode. You can make a Precision Rectifier out of an op-amp and a few other parts, like this:

This avoids the problem of the voltage drop (put this in place of the diode in the earlier circuit).

If the signal is AC then the smoothing circuit I described above will only give you an average voltage, not a peak one. You may want to sample rapidly in order to find the peak values.
> 2 votes

# Answer
To read the sensor properly you have to convert the output signal into something the Arduino can work with.

At full current the output will swing between +4V and -4V, and over-current will cause that to be nearer +6V to -6V. The frequency of that swing will be the frequency of the input voltage - so typically 50 or 60Hz.

The Arduino can only read between 0V and 5V, so you will need to convert the provided voltage to fit.

You need to first reduce the voltage by about a half, so it fits into +/- 2V, and then you need to add a 2.5V offset voltage to it so that it swings between 0.5V and 4.5V.

Once you have done that you then need to sample the incoming signal fast enough that you can get the peak values, from which you can then calculate the incoming current.

Often for this kind of thing you would use a simple voltage divider with an offset voltage applied to it, but the output impedance of the sensor (set by RL) is 10KΩ which is around the upper limit for the input impedance of the Arduino's input. A voltage divider that wouldn't adversely affect the output accuracy would be using resistors in the order of 1MΩ, which would be way too high for the ADC on the Arduino to be able to sample accurately.

So you need to buffer the signal with a high impedance buffer. That can be achieved most simply with an inverting op-amp circuit with a gain of 0.5. You want a rail-to-rail op-amp which is capable of running from a single supply voltage.

In this circuit the output current is converted into a voltage by the 10KΩ resistor RL. It is then *AC coupled* to the rest of the circuit through C1 which has to be high enough in value as to not reject the frequency you are working with (it acts like a high-pass filter). R1 and R2 set the gain of 50/100, or 1/2, so the voltage is halved. R3 and R4 form a voltage divider to provide a VCC/2 offset voltage into the non-inverting input of the op-amp. This is known as the *virtual ground* voltage and is the voltage the output of the op-amp will swing around.

The result is the input voltage inverted, halved and off-set by 2.5V, which can be read directly by the Arduino's ADC.

Note the magic word *inverted* there, though. The values you read will be upside down. Anything read above 512 from the ADC will equate to a negative voltage. Anything read below 512 will be a positive voltage. So it is necessary to first "invert" the reading, which can simply be done by subtracting it from 1023.

Then it's just a matter of sampling often enough and recording the peak (and negative peak) values over a short period. The faster you can sample the better your results will be.

From those peak values you can then do all sorts of calculations and things. You can use them "as is" to directly give you the "peak-to-peak" current, or calculate the RMS voltage to then give you the RMS current.
> 2 votes

---
Tags: sensors, analogread
---


# Question
Title: Arduino code of making a LED digit display not functioning properly
I want to make an LED one digit display using 14 leds used in pairs so I have 7 pairs which show number. (Similar to the display in calculators). Now the problem is that my code won't function properly. The problem that is arising is that the leds won't go off, all of them would work at the same time, here's the code

```
int a = 2;
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;

void setup()
{
   for(int i = 2; i++ ; i<9)
   {
      pinMode (i, OUTPUT);
   }
}
void _1()
{
   digitalWrite ( b, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _2()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _3()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _4()
{
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( b, HIGH);
   delay(1000);
}
void _5()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _6()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   digitalWrite ( d, HIGH);
   delay(1000);
}
void _7()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _8()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _9()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _0()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void wait()
{
   digitalWrite ( a, LOW);
   digitalWrite ( b, LOW);
   digitalWrite ( c, LOW);
   digitalWrite ( d, LOW);
   digitalWrite ( e, LOW);
   digitalWrite ( f, LOW);
   digitalWrite ( g, LOW);
   delay(100);
}
void loop()
{
   _0();
   wait();
   _1();
   wait();
   _2();
   wait();
   _3();
   wait();
   _4();
   wait();
   _5();
   wait();
   _6();
   wait();
   _7();
   wait();
   _8();
   wait();
   _9();
   wait();
}

```

The problem is that it stays at \_0 and then never changes. Any suggestions?

# Answer
The `for` loop in your `setup()` function isn't quite right. The condition (`i<9`) and the iterator (`i++`) need to be the other way round, like this:

```
for (int i = 2; i<9; i++)
{
  pinMode (i, OUTPUT);
}

```
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Replacing Atmega8a pu 1440 arduino Ic with 1337
I have one Arduino uno, and one atmega8a 1337 ic. Can i replace the Arduino uno ic with 1337 to program the 1337 one?

# Answer
> 2 votes
If you have a bootloader installed on the 8A then yes, you can. The two chips are pin and electrically compatible.

---
Tags: arduino-uno
---


# Question
Title: Arduino, lcd 16x2 and UTP cable shows gibberish text?
I'm using an arduino uno, and an 16x2 LCD that is connected to the arduino uno with a 1m long UTP cable to transmit data and as well power the LCD screen.

I used to test my code and my wiring with short wires and everything worked perfectly, as soon as I used the UTP cable to move my lcd a bit away from the arduino, the same code and wiring doesn't work, all i see is gibberish text (nonsense characters on the screen). I have other components in the circuit, but I have disabled them all and checked again (quadruplechecked) everything, including the LCD alone, but the problem remians. I also gave the lcd a whole separate powering line, as I thought it could have run low in energy bcs of other components using the same 5v line.

Anyone has any idea of what could the problem be? Has anyone tried connecting components with UTP cables? Should I maybe use STP instead?

Thanks!

# Answer
Is the cable shielded? Have to performed continuity test on all leads of the cable to ensure there no break internally that could be causing an issue, or a short?

What is the impedance of your total length of cable?

These sorts of checks will help you further narrow down the issue. If you are certain your wiring is correct, then the most probable issue is either a hardware failure (continuity test) a hardware limitation (Too much resistance for accurate data travel) Improper Hardware, unshielded wires can be subject to crosstalk, or signal corruption/distortion due to external signals interfering.
> 1 votes

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


# Question
Title: How would i capture and split serial data?
How would i capture the following serial data, and split it into parts? `<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>`

the parts i need from this is Alarm - This is a state. i.e Alarm, Idle, Paused, Working MPos: - This is a series of positions X,Y,Z WPos: - This is a series of positions X,Y,Z

What i want to do is capture the string from serial (See above for formatting) Then display the information on the LCD.

i.e. X: 0.000 Y:0.000 Z: 0.000 Idle

I've managed to figure out how to do all the LCD display stuff, and send commands to the serial, but it appears there are so many variations on how to split the data up, that i't really confusing to me, as well, almost all of the examples i find use loop to do this, but i would like to have this done in a function, that way i can display this info only when needed, not constantly, as i'll be useing the LCD for a menu system.

# Answer
> 2 votes
This string is actually fairly easy to split up, because everything is separated by commas nice and regularly.

Assuming you have the string in a char array (aka a C string) and not a String object (I and most other programmers abhor the String class) you can use the function `strtok()` to split the string up into parts.

So you have the string:

```
char string[] = "<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>";

```

The function `strtok()` takes, on its first call, the string you want to split and the delimiter that you want to split on. It returns a pointer to the chunk:

```
char *alarm = strtok(string, ",");

```

`alarm` now contains `<Alarm` and `strtok()` moves its internal pointer to point at the next character, so it sees the string as `MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>`

With the next and subsequent calls to `strtok()` you don't give it the string, or it will reset its internal pointer. You just pass it `NULL` and it gives you the next block:

```
char *mposX = strtok(NULL, ",");
char *mposY = strtok(NULL, ",");
char *mposZ = strtok(NULL, ",");
char *wposX = strtok(NULL, ",");
char *wposY = strtok(NULL, ",");
char *wposZ = strtok(NULL, ">");

```

Note that I changed the delimiter on the last one to `>` so it chops off that extra character that we don't want (and there is no `,` after the last part).

So now you have 7 variables that point to chunks of the string, which has internally been chopped up and modified into individual substrings:

```
*alarm = "<Alarm";
*mposX = "MPos:0.000";
*mposY = "0.000";
*mposZ = "0.000";
*wposX = "WPos:0.000";
*wposY = "0.000";
*wposZ = "0.000";

```

So now we can clean up the three entries that have extra stuff in them, and that is a simple as adding an offset value to the pointers we have:

```
alarm += 1;
mposX += 5;
wposX += 5;

```

Our list of pointers now looks like this:

```
*alarm = "Alarm";
*mposX = "0.000";
*mposY = "0.000";
*mposZ = "0.000";
*wposX = "0.000";
*wposY = "0.000";
*wposZ = "0.000";

```

The position variables can now be passed through strtod() to convert them to float values:

```
float mx = strtod(mposX, NULL);
float my = strtod(mposY, NULL);
float mz = strtod(mposZ, NULL);
float wx = strtod(wposX, NULL);
float wy = strtod(wposY, NULL);
float wz = strtod(wposZ, NULL);

```

You can do different things depending on the content of the `*alarm` string by using `strcmp()`:

```
if (strcmp(alarm, "Busy") == 0) {
    // Something to do when Busy
}

```

etc.

Or you can just use it to print the content to the LCD.

---
Tags: arduino-uno, serial, arduino-mega, arduino-ide, lcd
---


title: Remote Wireless Tripwire

text:
# Question
Title: Remote Wireless Tripwire
I've had an idea for an Arduino project, but I'm not sure where to start. My idea is this: have an Arduino Nano connected to an HC-SR04 ultrasonic sensor, as well as an nRF24L01+ radio. This will be the tripwire module, which will send an alert to a second Arduino (connected to another nRF24L01+ of course) whenever something passes by.

This wouldn't be a stationary unit, it would need to be able to be placed and sense in a variety of locations so the distance would need to be set on power up.

Another issue I'm running into is getting the nRF24L01+ units to work for this purpose. I want to know that the units are wirelessly connected, so having a packet sent every second or so lets the receiving unit know that they're connected, and an additional packet for the tripwire trigger sets off an indicator led.

Is this even possible?

# Answer
This sounds very doable. The first point, tuning the distance threshold at startup, could be done with a bank of DIP switches or a potentiometer on an analog pin to set the value. You might include some startup code continuously pings the transducer and displays the result on an LED, until you press a button to tell it "use this".

The second, is a very typical communication technique - sending "hello" packets periodically to confirm that communication is up. In your case, the same packet could carry a hit/no-hit bit within it.
> 1 votes

---
Tags: nrf24l01+, remote-control, wireless
---


# Question
Title: Cannot upload sketch to Atmega328p TQFP soldered on PCB
After creating a working prototype with DIP ATMega328 chip/ Arduino UNO I recently got PCBs assembled with SMD components and ATMega328P TQFP soldered onto them, but now I'm having a hard time trying to upload the Arduino program.

**This is the schematic of the PCB with ATMega328P TQFP with ISP headers for programming:**

I'm using USBasp programmer with upgraded firmware to upload the code. The chip gets detected and also I can upload sketches to it but the problem is the code runs slow, which I found out is due to the default 8MHz internal clock.(the blink program makes LED blink every 16 seconds instead of 1 second,i.e. with delay(1000))

Now to switch to the external 16MHz clock which I want to use I found out here that I have to change the fuse values from the default

> **lfuse: 0x62 hfuse: 0xD9 efuse: 0x3F**

to

> **lfuse: 0xFF hfuse: 0xDE efuse: 0x05**

I tried it two times and both the times it screwed up the ATMega328P chip

```
C:\Users\p>avrdude -p m328p -c usbasp -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efu
se:w:0x05:m

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x1e950f
avrdude: reading input file "0xFF"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xFF:
avrdude: load data lfuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified
avrdude: reading input file "0xDE"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.03s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xDE:
avrdude: load data hfuse data from input file 0xDE:
avrdude: input file 0xDE contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0x05"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.03s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0x05:
avrdude: load data efuse data from input file 0x05:
avrdude: input file 0x05 contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified

avrdude: safemode: Fuses OK

avrdude done.  Thank you.

C:\Users\p>avrdude -p m328p -c usbasp

avrdude: error: programm enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

```

Both of the PCBs are not responding to the USBasp programmer and now I have only got one PCB left. I desperately want to get the final one working.

This is my first time using the SMD ATMega328P chips and any help would be appreciated.

# Answer
> 3 votes
It looks like the capacitors on your crystal are considerably bigger than they should be.

You are switching the clock to the external crystal, and because you have such massive capacitors on it it's failing to oscillate. Without that oscillation the chip can't run, and so it can't respond to the programming.

The crystal capacitors should be roughly 2x the "load capacitance" of the crystal you are using.

> CX1 = CX2 = 2(CL \- CSTRAY)

---
Tags: arduino-uno, arduino-ide, atmega328, programmer
---


# Question
Title: Including libraries from header files sometimes doesn't work
I, once again have difficulties including libraries from code files other than my .ino file.

I have several .cpp and .h files in my project to keep it sorted and clean. However one of my header files starting like this:

```
#ifndef DPLANDEF
#define DPLANDEF
#include <Arduino.h>
#include <EEPROM.h>
#include "syssettings.h"

```

yields the following errors:

> In file included from /var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build4605486877500371361.tmp/dplan.cpp:2:0: /var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build4605486877500371361.tmp/dplan.h:5:20: fatal error: EEPROM.h: No such file or directory #include ^ compilation terminated. Fehler beim Kompilieren.

EEPROM.h should be known to the IDE, because I can find it in the libraries menu, too. If it was a custom library, I might have botched something during installation, but this is a standard library. It should work out of the box. What's the problem here?

# Answer
> 2 votes
The problem here is that it's a header file. The IDE doesn't treat header files like it does INO files - it doesn't parse them for included libraries, etc.

In order for it to work you must also include EEPROM.h in your main INO file so that the IDE knows that you want to include it in the rest of your files.

---
Tags: arduino-ide, core-libraries
---


# Question
Title: Handling serial streams biggers than the available ram
I need to parse text coming into my MC (Leonardo) over the hardware serial port. The data comes in burst, and the parsing routine manage the data flow with easy when it is less than the serial buffer.

I will like to be able to receive around 512Kb of serial data, save it somewhere (not in the arduino memory of course) and the execute the parsing routine on it. I think saving the stream to an external EEPROM and then retrieving it slowly so my parsing code can actually fallows will do the trick. I can control the speed of the serial stream from 300 bauds (not optimal) up to 112000 bauds.

Is the approach correct? Can I write to the EEPROM faster than a 9600 bauds serial stream without collapsing the arduino?

# Answer
> 2 votes
You can parse indefinitely large amounts of data with a state machine parser.

General description: State machines

As an example, I wrote recently an HTTP server which parses incoming HTTP data (eg. cookies, parameters, POST data, GET data) on-the-fly.

You need enough RAM for **one** item of data, naturally. But then you act upon it, and then discard it. In the case of the web server, you could conceivably process a complex form with thousands of actions on it (eg. turn on switch 5, pump 3, heater 22). It parses each action, and then you act on it, then you parse another action.

---

You can even consider the Arduino bootloader as an example of this. The Optiboot bootloader is 512 bytes on a Uno, but it can re-flash 32 KB of program memory. How? The programming data comes down in bursts (packets, if you like) and it processes each packet at a time, then discards it and reads the next one.

---
Tags: serial, arduino-leonardo, eeprom
---


# Question
Title: Waking Raspberry Pi on time schedule using Sleepy Pi
I'm have a Sleepy Pi and am having extreme difficulties trying to program a wake/sleep cycle. Sleepy Pi is an Arduino board with a RTC. My ultimate goal is for a time-lapse project.

I have the Raspberry Pi programmed and operational to take a picture on boot, my trouble is coming from trying to program the Arduino board to actually do it's job.

I would like the Sleepy Pi to wake at 8am, 9am, 10am, ..., 3pm, 4pm, and 5pm, each for 5 minutes, then go back to sleep. I've been working with the SleepyPi, Time, TimeAlarms, LowPower, and DS1374RTC libraries in the Arduino IDE. However, I cannot find any examples on how to put everything to sleep until a specific time comes around. Also, in several of my tests, it seems that the clock actually stops when the Sleepy Pi is asleep!

Here is what I've been working with (and this is non-working). It's probably completely wrong.

```
#include "SleepyPi.h"
#include <Time.h>
#include <TimeAlarms.h>
#include <LowPower.h>
#include <DS1374RTC.h>
#include <Wire.h>

// Set the status LED pin constant
const int LED_PIN = 13;

void setup()
{
  // Configure "Standard" LED pin
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN,LOW); // Switch off LED

  // Start with the Pi off
  SleepyPi.enablePiPower(false);

  // Set our communication rate
  Serial.begin(9600);

  // Set up our boot times
  Alarm.alarmRepeat(8,0,0, startPiUp);
  Alarm.alarmRepeat(9,0,0, startPiUp);
  Alarm.alarmRepeat(10,0,0, startPiUp);
  Alarm.alarmRepeat(11,0,0, startPiUp);
  Alarm.alarmRepeat(12,0,0, startPiUp);
  Alarm.alarmRepeat(13,0,0, startPiUp);
  Alarm.alarmRepeat(14,0,0, startPiUp);
  Alarm.alarmRepeat(15,0,0, startPiUp);
  Alarm.alarmRepeat(16,0,0, startPiUp);
  Alarm.alarmRepeat(17,0,0, startPiUp);
}

void loop()
{
  // Tick the alarm clock every second
  SleepyPi.enableWakeupAlarm();
  Alarm.delay(1000);

  // Cut Power if we detect Pi not running
  bool pi_running;
  pi_running = SleepyPi.checkPiStatus(true);
  if(pi_running == false){
    SleepyPi.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
  }

  // Flash the LED
  digitalWrite(LED_PIN,HIGH);
  delay(1000);
  digitalWrite(LED_PIN,LOW);
}

// Function to tell the Pi to boot up
void startPiUp()
{
  // Turn the Pi on
  SleepyPi.enablePiPower(true);

  // Turn on the LED to signal we're here
  digitalWrite(LED_PIN,HIGH);

  // Keep the Pi on for 5 minutes
  delay(300000);

  // Start a shutdown
  digitalWrite(LED_PIN,LOW);
  SleepyPi.piShutdown(true);
}

```

I also cannot find a good way to "debug" things. I've been trying to use the LED flashes as a "I'm here" echo, but have been unsuccessful with this as well.

**NOTE:** I do not have enough reputation on this site yet to create new tags. Someone with over 150, please tag this with and . Thank you.

# Answer
> 1 votes
I have the same problem and I just saw that they fixed a bug in a library used by SleepyPi

More specific, the RTC library file `DS1374RTC.cpp` reads since March: '2015
(which is after the question was asked)

> Releases
> ========
> V1\_0 - 10 Aug 2013 - Initial release
> V1\_1 - 11 Mar 2015 - Mod: Added "ackAlarm" and "ackRTCOSF" functions to aid Alarm use
> \- Bugfix: **Changed the way the "SetAlarm(tmElements\_t &tm)" was updating the Alarm time.** It wasn't mapping correctly

They also added a new example to wake up the Pi: `WakePeriodicallySimple.ino`

# Answer
> 0 votes
Same probem. Kludgy solution ... but it works

Get the startstopsimple skectch from GitHub.

Set the period to 60 minutes Set the timeout to whatever makes sense for you

Modify the setup function to loop until the clock says the minute is 59. something like

```
do
{
   delay (100);
} while !(minute() == 59);

```

Then it will go into the loop function. It will be asleep. So it will then do a whole "empty" loop and sync after that, dunno how one gets rid of first the empty loop. But it works .... :-)

---
Tags: programming
---


# Question
Title: run two motors in turns without using delay()
I googled solutions and tried, but I still cannot get it working.

I've tried BlinkwithoutDelay.

I feel it is very confusing to track timing of two motors (i.e., step, direction, speed) for the following routine loop:

* step 1: run motorA\_forward() for 10 seconds;
* step 2: run motorAB\_stop() for 1 seconds;
* step 3: run motorB\_backward() for 3 seconds
* step 4: run motorAB\_stop() for 1 seconds
* step 5: run motorA\_backward() for 10 seconds
* step 6: run motorAB\_stop() for 1 seconds

Please help me on this!! I really appreciate your time and comments.

Thank you.

The following is my working code.

```
// ----------LIBRARIES--------------

#include <Wire.h>
#include <LIDARLite.h>
LIDARLite myLidarLite;

// ----------CONSTANTS--------------

const int motorA_pin_1 = 8;           // the pin numbers for the motors
const int motorA_pin_2 = 11;
const int motorA_pin_speed = 9;
const int motorB_pin_1 = 12;
const int motorB_pin_2 = 13;
const int motorB_pin_speed = 10;

//------------VARIABLES--------------

byte motorA_state_1 = LOW;             // used to record whether the motots are on or off
byte motorA_state_2 = LOW;             // LOW = off
byte motorB_state_1 = LOW;
byte motorB_state_2 = LOW;

int currentMillis               = 0;     // stores the value of millis() in each iteration of loop()
int motorA_Forward_Interval     = 5000;  // will store last time the motor was moved
int motorA_Backward_Interval    = 5000; // will store last time the motor was moved
int motorA_Stop_Interval        = 2000;  // will store last time the motor was moved
int motorB_Stop_Interval        = 2000;  // will store last time the motor was moved
int motorAB_BreakTime_Interval  = 2000;

unsigned long motorA_Forward_Timer      = 0;     // will store last time motorA start was updated
unsigned long motorA_Backward_Timer     = 0;     // will store last time motorA start was updated
unsigned long motorB_Forward_Timer      = 0;     // will store last time motorA start was updated
unsigned long motorB_Backward_Timer     = 0;     // will store last time motorA start was updated
unsigned long BreakTime_timer   = 0;     // will store last time motorA/B break time was updated

//------------INITIALIZATION--------------

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

  pinMode(motorA_pin_1,OUTPUT);         // set the motor pins as output:
  pinMode(motorA_pin_2,OUTPUT);
  pinMode(motorA_pin_speed,OUTPUT);
  pinMode(motorB_pin_1,OUTPUT);
  pinMode(motorB_pin_2,OUTPUT);
  pinMode(motorB_pin_speed,OUTPUT);

}

//------------LOOPING----------------------
// Notice that none of the action happens in loop() apart from reading millis()
// It just calls the functions that have the action code

void loop()
{
    Serial.println(myLidarLite.distance());

    unsigned long currentMillis = millis();

    motorA_forward();  // for 10 seconds
    motorAB_stop();    // for 1 seconds
    motorB_backward(); // for 3 seconds
    motorAB_stop();    // for 1 seconds
    motorA_backward(); // for 10 seconds
    motorAB_stop();    // for 1 seconds

}

//------------SUBROUTINE----------------------

void motorA_forward()
{
  if(currentMillis - motorA_Forward_Timer <= motorA_Forward_Interval)
  {
    motorA_state_1 = HIGH;   // Turn motor A on - backward
    motorA_state_2 = LOW;  //
    motorB_state_1 = LOW;   // Turn motor B off
    motorB_state_2 = LOW;   //

    analogWrite(motorA_pin_speed,255);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,255);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    motorA_Forward_Timer = currentMillis;
  }
}

void motorA_backward()
{
    if(currentMillis - motorA_Backward_Timer <= motorA_Backward_Interval)
  {
    motorA_state_1 = LOW;   // Turn motor A on - backward
    motorA_state_2 = HIGH;  //
    motorB_state_1 = LOW;   // Turn motor B off
    motorB_state_2 = LOW;   //

    analogWrite(motorA_pin_speed,255);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,255);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    motorA_Backward_Timer += currentMillis;
  }
}

void motorB_forward()
{
    motorA_state_1 = LOW;   // Turn motor A off
    motorA_state_2 = LOW;   //
    motorB_state_1 = HIGH;  // Turn motor B on - forward
    motorB_state_2 = LOW;   //

    analogWrite(motorA_pin_speed,255);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,255);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    motorB_Forward_Timer = currentMillis;
}

void motorB_backward()
{
    motorA_state_1 = LOW;   // Turn motor A off
    motorA_state_2 = LOW;   //
    motorB_state_1 = LOW;   // Turn motor B on - backward
    motorB_state_2 = HIGH;  //

    analogWrite(motorA_pin_speed,255);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,255);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    motorB_Backward_Timer = currentMillis;
}

void motorAB_stop()
{
    motorA_state_1 = LOW;   // Turn motor A off
    motorA_state_2 = LOW;   //
    motorB_state_1 = LOW;   // Turn motor B off
    motorB_state_2 = LOW;  //

    analogWrite(motorA_pin_speed,0);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,0);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    BreakTime_timer = currentMillis;
}

```

# Answer
> 2 votes
```
int currentMillis               = 0;     // stores the value of millis() in each iteration of loop()
...

void loop()
{
    Serial.println(myLidarLite.distance());
    unsigned long currentMillis = millis();

```

You have **two** `currentMillis` variables. The global one never changes. You change a **different** one inside `loop`.

---

Remove the data definition. eg.

```
void loop()
{
    Serial.println(myLidarLite.distance());
    currentMillis = millis();  // change the global variable

```

---

Also make the **global** one unsigned long:

```
unsigned long currentMillis               = 0;     // stores the value of millis() in each iteration of loop()

```

# Answer
> 2 votes
This is a classic example where Object Oriented Programming (OOP) can make your life so much easier.

The principle behind OOP is to define a *Class* which contains all the actions you want to perform on something - in this case a motor. The *Class* contains all the instructions on how to do things like set the motor speed, the direction, start it, stop it, etc.

From that *Class* you then create *Objects*. The beauty is there is only one *Class* which has the abstract concept of "Motor Control", but that *Class* is used to create one *Object* for each motor you want to control.

A *Class*, and hence the *Objects* derived from it, are all completely self contained, which makes it so much easier to manage. All the variables associated with a single motor are wrapped up inside the *Class* and you don't need to worry about unique names for them all on a per-motor basis.

For example, you might define a class like this:

```
class Motor {
    private:
        int _speedPin;
        int _directionPin1;
        int _directionPin2;

    public:
        Motor(int sp, int dp1, int dp2) {
            _speedPin = sp;
            _directionPin1 = dp1;
            _directionPin2 = dp2;
        }
        void begin() {
            analogWrite(_speedPin, 0);
            pinMode(_directionPin1, OUTPUT);
            pinMode(_directionPin2, OUTPUT);
            digitalWrite(_directionPin1, LOW);
            digitalWrite(_directionPin2, LOW);
        }
        void forward() {
            digitalWrite(_directionPin1, HIGH);
            digitalWrite(_directionPin2, LOW);
        }
        void reverse() {
            digitalWrite(_directionPin1, LOW);
            digitalWrite(_directionPin2, HIGH);
        }
        void speed(int speed) {
            analogWrite(_speedPin, speed);
        }
        void stop() {
            analogWrite(_speedPin, 0);
            digitalWrite(_directionPin1, LOW);
            digitalWrite(_directionPin2, LOW);
        }
};

```

Everything you need to control a motor is in there. Then you could use that to create two motor objects:

```
Motor leftMotor(3, 4, 5);
Motor rightMotor(6, 7, 8);

```

You provide the pins that control the motor to the *constructor* of the object - that is pin 3 is the speed pin of the first motor, and pins 4 and 5 are the direction control pins, etc.

You can now control the motors very simply. Configure the pins by calling the begin function defined in the class above:

```
void setup() {
    leftMotor.begin();
    rightMotor.begin();
}

```

And now you can use similar decision making as normal to decide when to do what. The main difference is that your motor control code now looks as simple as:

```
leftMotor.forward();
rightMotor.reverse();

```

or

```
leftMotor.stop();
rightMotor.forward();
rightMotor.speed(30);

```

You then end up with a program that is much cleaner and easier to follow. And adding a third or forth motor is as simple as defining more Motor objects with their pins.

This video is a good introduction to what OOP is and how it differs from the "traditional" approach:

---
Tags: arduino-uno, c++, motor, millis
---


# Question
Title: How do I use 3 Hc-sr04 ultrasonic sensors to control 3 vibration dc motor?
This code we are using only one motor and one hc-sr04 ultrasonic sensor, the code is shown below:

```
#define trigPin 7
#define echoPin 6
#define motorPin 5

void setup()
{
  Serial.begin(9600);// to use the serial monitor
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(motorPin, OUTPUT);
}

void loop()
{
  int duration,distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2)/29.1;
  Serial.print(distance);//to print the distance on the serial monitor
  Serial.println("cm");

  // to make the motor vibrate depending on the distance
  // if the ultrasonic sensor is too far from the obstacle it will vibrate slowly
  // if the ultrasonic sensor is very close to the obstacle it will vibrate very fast

    if(distance <= 60 && distance >= 45)
    {
      // to make the motor vibrate
    digitalWrite(motorPin, HIGH); // making the motor on

    delay(200);
    digitalWrite(motorPin, LOW);// making the motor off
    delay(200);
    }

    else if(distance < 45 && distance >= 30)
    {
    digitalWrite(motorPin, HIGH);
    delay(100);
    digitalWrite(motorPin, LOW);
    delay(100);
   }
    else if(distance < 30){

    digitalWrite(motorPin, HIGH);
    delay(50);
    digitalWrite(motorPin, LOW);
    delay(50);
  }
  else
  {
    digitalWrite(motorPin, LOW);
  }
}

```

We want you to tell us your comment about the code.

And we want to add two more motors and two ultrasonic sensors, one of them in the left and the other in the right.

We want you to help us in the code, because we don't know how we can change it for two other motors.

# Answer
There's a few things you need to consider when making multiple things happen at the same time.

Firstly is timing. You can't make two things happen concurrently with different timings if you have `delay()` in there, since nothing else can happen while `delay()` is executing. So you have to get rid of all `delay()` calls and replace them with examining the difference between successive calls to `millis()`.

For instance, imagine you're in the kitchen and you want to boil and egg and make a cup of tea at the same time. You fill the kettle and turn it on. You put a pan of water on the stove with an egg in it to boil.

Now you could sit and stare at the egg until it's boiled enough for you to eat, but what happens to the kettle while you're doing that? It's boiled, turned itself off, and started to go cold.

So instead you put the egg in the pan and look at the clock. Then you think "in 5 minutes I will take the egg out of the boiling water". You might set an alarm for 5 minutes time if you have one, or you may keep glancing at the clock periodically to see if the 5 minutes have past yet. Meanwhile the kettle has boiled and you've made your cup of tea.

Then the 5 minutes have passed. You know that because *you remembered what time you put the egg on to boil* and *you know what the time is now*, so you can subtract one from the other to find that 5 minutes have passed.

Now let's make it a little more complex. Imagine you want two eggs - one soft boiled and one hard boiled. The hard boiled one may want 8 minutes, the soft boiled one 5 minutes.

So you put one egg on to boil and remember the time. Roughly three minutes later you put the other egg in and also remember that time.

Once enough time has passed that the first egg has been in 8 minutes you take it out.

Once enough time has passed that the second egg has been in 5 minutes you take it out.

You have had to remember two start times which you then compare separately to decide what to do with each egg when.

To translate that to your program - you have to remember a start time for each action for your motors, along with the state of the motors - and when the right time has elapsed you change the state of the motor (motor on -\> motor off - egg in pan -\> egg on plate) and remember the time at which you changed the state so you can know when to change the state again.

That's exactly what the BlinkWithoutDelay example does to make an LED change state (on -\> off -\> on) at certain times by remembering *when* it last changed state so you know *when* to change the state next.
> 1 votes

---
Tags: arduino-uno, sensors, c++, motor
---


# Question
Title: How can i read serial data into a string until a certain character is recieved?
This is not a duplicate of my other question. This question deals with reading specific data within a serial stream. The other question deals with reading and adding data into a manageable data string.

What I'm trying to do is send a command to serial, get the response, and put it into a string, and then break that string up into usable parts of data.

The problem I'm having, is there is a delay between the time the serial command is sent, and the response. meaning the serial data isn't being captured before the function moves onto the next line. Using delay() doesn't appear to work, as i believe it halts everything for that delay period.

What I'm hoping to do, is read the data from serial and if the character '\<' is received, place it, and everything after it into the buffer until the character "\>" is received. After the last character is received, and placed into the buffer, continue on with the script.

Unless of coarse someone has a better idea on how to approach this. i would also like to note that this is just a part of a larger project. If you need to see the entire project, please let me know and i will provide a link where you can download it.

The string i'm expecting as a response would be similar to this:

```
<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>

```

Here is the code i have so far:

```
float mx;
float my;
float mz;
float wx;
float wy;
float wz;
String dAlarm;
char buffer;
void gPos() {
  Serial1.print("?\n");
  buffer = Serial1.read();
  char string[80];
  string[buffer];
  char *alarm = strtok(string, ",");
  char *mposX = strtok(NULL, ",");
  char *mposY = strtok(NULL, ",");
  char *mposZ = strtok(NULL, ",");
  char *wposX = strtok(NULL, ",");
  char *wposY = strtok(NULL, ",");
  char *wposZ = strtok(NULL, ">");
  alarm += 1;
  mposX += 5;
  wposX += 5;
  mx = strtod(mposX, NULL);
  my = strtod(mposY, NULL);
  mz = strtod(mposZ, NULL);
  wx = strtod(wposX, NULL);
  wy = strtod(wposY, NULL);
  wz = strtod(wposZ, NULL);

  if (strcmp(alarm, "Idle") == 0) {
    dAlarm = "Idle";
  } else if (strcmp(alarm, "Run") == 0) {
    // Something to do when Busy
    dAlarm = "Run";
  } else if (strcmp(alarm, "Hold") == 0) {
    // Something to do when Busy
    dAlarm = "Hold";
  } else if (strcmp(alarm, "Door") == 0) {
    // Something to do when Busy
    dAlarm = "Door";
  } else if (strcmp(alarm, "Home") == 0) {
    // Something to do when Busy
    dAlarm = "Home";
  } else if (strcmp(alarm, "Alarm") == 0) {
    // Something to do when Busy
    dAlarm = "ALARM!";
  } else if (strcmp(alarm, "Check") == 0) {
    // Something to do when Busy
    dAlarm = "Check";
  }
  dispPos();
}

void dispPos() {
  int state = 0;
  int x = analogRead (0);
  if (x < 800) {
    state = 1;
  }
  if (state == 1) {
    dPos = false;
  }

  if (dPos == true) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("X");
    lcd.print(mx);
    lcd.setCursor(8, 0);
    lcd.print("Y");
    lcd.print(my);
    lcd.setCursor(0, 1);
    lcd.print("Z");
    lcd.print(mz);
    lcd.setCursor(8, 1);
    //lcd.print(" ");
    lcd.print(dAlarm);
    delay(3000);
  } else {
    mainMenu();
  }
}

```

# Answer
What you need to do here is implement a small *finite state machine*.

Basically you need to look at each character as it comes in and make a decision what to do with it *depending on what state you're in at the moment*.

Basically the operational decisions you need to make are:

* Is the character a \< and am I currently not reading a string?
    + Yes, start reading the string.
* Is the character a \> and am I currently reading a string?
    + Yes, finish reading the string and process it
* Is it any other character and I am currently reading the string?
    + Yes, add it to the buffer.

So you can see there some common questions:

* What is the character?
* What am I doing at the moment?

So you need to have a simple state variable that remembers if you're reading the string or not, and something to say where in the buffer you are so you know where in the buffer to add any incoming characters.

```
boolean readingString = false;

```

A simple true/false will suffice to depict if we're reading the string or not. Start off not reading the string.

```
char buffer[80] = "";

```

A buffer to store the text - maximum of 80 characters (*including the NULL terminating character*)

```
int charPointer = 0;

```

Something to know where in the buffer are currently.

Now to read the characters:

First get the next character from the serial port:

```
loop() {
    if (Serial.available()) {
        int incoming = Serial.read();

```

Now decide what to do with it. We have a number of possible situations, some of which can be combined into single options. For instance, if we get a "\<" while reading a string it's an error condition - but do we really care? It could be that we lost the end of the last string and have just started a fresh one - so we can just treat it as the start of a string regardless of what state we're in. Let's use a `switch` for this since it's nice and tidy:

```
        switch (incoming) {
            case '<':
                readingString = true; // Start reading string
                charPointer = 0; // Set the buffer pointer to the start
                buffer[0] = 0; // Make the string empty
                break;

            case '>':
                if (readingString) {
                    processBufferData(); // Do something with the buffer
                }
                readingString = false; // Finish reading
                break;

            default: // Anything that's not > or <
                // If we are reading the string and the buffer isn't full
                if (readingString && charPointer < 78) {
                    // Add the character to the buffer and increment the pointer
                    buffer[charPointer++] = incoming;
                    buffer[charPointer] = 0; // Don't forget to terminate the string
                }
        }
    }
}

```

So the reception of a \< starts the string reading, the reception of a \> stops it and triggers the processing of the string, and anything else (while we are reading the string) gets added to the buffer.
> 1 votes

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


title: Need help in modifying the design

text:
# Question
Title: Need help in modifying the design
I am planning to do a project on Sequential tilt motion lock using Arduino uno and accelerometer. I would like to present the accelerometer **within** a rotatable object. So what other components do i have to add to be able to do it i.e.. for wireless transmission of data from the object(that has the acc. meter) to the Uno board.

# Answer
If you do a google search for "arduino wireless serial" you'll get several results. Plugging them into the arduino should be trivial. Most suppliers (other than ebay) will also have examples for you to reference where it comes to coding your project to use the module.

You should also be aware that you will usually need a transceiver, and a receiver.

You might take a look into the XBEE solutions, as they appear to be popular.
> 0 votes

---
Tags: arduino-uno, accelerometer
---


# Question
Title: Does SMS format depend on the sender's mobile?
I want to read the SMS using Arduino and GSM module, I want to perform conditional programming based on the received SMS.

What I found really interesting is SMS format is different if I send message from different phones.

Output of my code is

Case 1:(From a smartphone)

Mobile Number is: +91954xxxxxxx Message Text: 5+22" Hello Arduino

Case 2:(From a normal phone)

Mobile Number is: +91984yyyyyyy Message Text: Hello Arduino

---

Does it really depend on the sender's mobile phone? If yes, how to move further to make my code independent on the sender mobile.

---

My code is

```
//===final code

char RcvdMsg[200] = "";
int RcvdCheck = 0;
int RcvdConf = 0;
int index = 0;
int RcvdEnd = 0;
char MsgMob[15];
char MsgTxt[50];
int MsgLength = 0;

void Config() // This function is configuring our SIM900 module i.e. sending the initial AT commands
{
   delay(1000);
   Serial.print("ATE0\r");
   Response();
   Serial.print("AT\r");
   Response();
   Serial.print("AT+CMGF=1\r");
   Response();
   Serial.print("AT+CNMI=1,2,0,0,0\r");
   Response();
}

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

void loop()
{
   RecSMS();
}

void Response() // Get the Response of each AT Command
{
   int count = 0;
   Serial.println();
   while(1)
   {
      if(Serial.available())
      {
         char data =Serial.read();
         if(data == 'K'){Serial.println("OK");break;}
         if(data == 'R'){Serial.println("GSM Not Working");break;}
      }
      count++;
      delay(10);
      if(count == 1000){Serial.println("GSM not Found");break;}

   }
}

void RecSMS() // Receiving the SMS and extracting the Sender Mobile number & Message Text
{
   if(Serial.available())
   {
      char data = Serial.read();
      if(data == '+'){RcvdCheck = 1;}
      if((data == 'C') && (RcvdCheck == 1)){RcvdCheck = 2;}
      if((data == 'M') && (RcvdCheck == 2)){RcvdCheck = 3;}
      if((data == 'T') && (RcvdCheck == 3)){RcvdCheck = 4;}
      if(RcvdCheck == 4){RcvdConf = 1; RcvdCheck = 0;}

      if(RcvdConf == 1)
      {
         if(data == '\n'){RcvdEnd++;}
         if(RcvdEnd == 3){RcvdEnd = 0;}
         RcvdMsg[index] = data;

         index++;
         if(RcvdEnd == 2){RcvdConf = 0;MsgLength = index-2;index = 0;}
         if(RcvdConf == 0)
         {
            Serial.print("Mobile Number is: ");
            for(int x = 4;x < 17;x++)
            {
               MsgMob[x-4] = RcvdMsg[x];
               Serial.print(MsgMob[x-4]);
            }
            Serial.println();
            Serial.print("Message Text: ");
            for(int x = 46; x < MsgLength; x++)
            {
               MsgTxt[x-46] = RcvdMsg[x];
               Serial.print(MsgTxt[x-46]);
            }

            Serial.println();

            //****Resetting all the variables*****//

            //RcvdMsg[200]={0};
            RcvdCheck = 0;
            RcvdConf = 0;
            index = 0;
            RcvdEnd = 0;
            MsgMob[15];
            MsgTxt[50];
            MsgLength = 0;

            Serial.flush();

         }
      }
   }
}

```

# Answer
If you're not trying to capture the mobile number or whatever SMS text was sent, but only react to specific SMS messages, then don't try to parse the whole message, but design the protocol between any arbitrary phone and your Arduino to be detectable independent of everything else, e.g.:

```
#L 5 on        ; set an LED state<br>
#M 3 137       ; set a motor speed<br>

```
> 1 votes

---
Tags: arduino-uno, gsm
---


# Question
Title: Powering arduino and sensors and motor damaging 16x2 LCD?
I have an application that requires reading sensors and moving a stepper motor. The sensors draw about 200mA between them, and need 5V to work. (Too much to draw through the Arduino, I thought) The stepper is recommended to run off 12V, and is driven through a BigEasy board. And, of course, the Arduino needs 5V.

My actual setup has an old laptop power brick, which puts out nominally 12V. This is fed into a voltage regulator (one of the cheap ones with a voltmeter built in) which outputs a steady 5V, even if the input voltage changes a bit. So, I've got a reasonable 12V supply and a fairly fixed 5V supply.

From the 5V supply, I run wiring to the sensors, and from the 12V supply I wire the stepper driver.

The thing is, to power the Arduino, I thought I could just wire up a USB socket (only the power lines) and wire the USB socket to the 5V regulated output. Then I could either plug my arduino into my computer to program it, or plug it into the dummy usb socket to power it standalone.

This arrangement seemed to work for a while, but I've noticed strange behaviour with the 2x16 LCD board which is also attached. I should point out that the LCD takes it's power from the regulated 5V, not from the 5V rail of the Arduino, although the data lines go to the Arduino. The LCD has gone into a "lock-down" mode whereby it only displays half blocks on the top line and nothing else.

I'm wondering if it could be related to effectively powering the system with 2 supplies; one for the majority of the load through the old laptop power brick, and the Arduino through the USB port of my (also laptop) PC. Somewhere along the line, ground get connected to ground, but are all grounds equal?

Is there a standard solution for having the Arduino plugged into your development PC (so as to get debug messages through the Serial COM monitor) whilst still be able to safely power the high-draw loads of the rest of the system. I did consider powering the Arduino through it's barrel jack, but then I'll need an additional 7V supply. (The 5V regulated supply would be too much, and the 12V "semi-regulated" supply would be too much).

And can I do something to protect the next LCD that I use? (Stick a 5.2V Zener across the power pins to prevent spikes??)

# Answer
> 1 votes
In some instances, it is a known issue that certain LCD's pull more power from the arduino than is sustainable depending on the power source.

A few suggestions:

Put something like a 100-200 ohm resister in the 5V to the LCD and connect just that and GND, then measure the voltage drop across said resister. That will give you the current with ohms law, if its much more than 4mA its a faulty LCD or a fault in your wiring.

You should also check the pins for continuity errors, or shorts.

Another idea, is to make sure the voltage, and amperage coming from the 5vdc step down you are using is adequate for the task at hand.

And finally, you'll need to calculate the complete pull on your power source. i.e. you'll need to know how much load your bigeasy driver pulling from the 12vdc power supply, as well as how much your 5v stepdown is using. if they are exceeding the output of the PSU, you can run into issues.

I ran into a similar issue with my own project, using an arduino Uno with grbl + 3x easydriver motor controllers, & mega 2560 + lcdkeypad shield. Powering the easydrivers with 12vdc & using a voltage stepdown module also gave me issues, as it didn't provide enough current for the stepper motor drivers and the LCD + mega + uno from the 5vdc. I was overloading the power supply, and the 5v wasn't producing the correct power requirements.

I bought a better power supply that had 24, 12, 7, and 5v on it, and haven't had an issue since.

---
Tags: power, lcd
---


# Question
Title: How to program a CLK signal and its inverse with Arduino/AVR
Is it possible to simultaneously output a clock signal and it's inverse using the timer register(s)?

I'm using the following code in arduino to output a 1MHz signal on OC1A:

```
//Use Timer/Counter1 to generate a 1MHz square wave on Arduino pin 9.
//J.Christensen 27Apr2012

void setup(void)
{
    DDRB = _BV(DDB1);                  //set OC1A/PB1 as output (Arduino pin D9, DIP pin 15)
    TCCR1A = _BV(COM1A0);              //toggle OC1A on compare match
    OCR1A = 7;                         //top value for counter
    TCCR1B = _BV(WGM12) | _BV(CS10);   //CTC mode, prescaler clock/1
}

void loop(void)
{
}

```

# Answer
> 4 votes
How about this?

```
void setup()
  {
  // Defining PB1 and PB2 as outputs by setting PORTB1 and PORTB2
  // Setting DDB1 and DDB2
  DDRB |= bit (DDB1) | bit (DDB2);

  // stop timer 1
  TCCR1A = 0;
  TCCR1B = 0;

  TCCR1A = bit (COM1B0) | bit (COM1B1)  // Set OC1B on Compare Match, clear
                                        // OC1B at BOTTOM (inverting mode)
         | bit (COM1A1)                 // Clear OC1A on Compare Match, set
                                        // OC1A at BOTTOM (non-inverting mode)
         | bit (WGM11);                 // Fast PWM, top at ICR1
  TCCR1B = bit (WGM12)  | bit (WGM13)   //       ditto
         | bit (CS11);                  // Start timer, prescaler of 8

  // Initialize OCR1A = 300 (pulse_width = 150us), OCR1B, and ICR1
  ICR1 = 0xFFFF;
  OCR1B = 299;
  OCR1A = ICR1 - OCR1B;

  }  // end of setup

void loop()
  {
  }

```

Results on a Uno:

Output on Uno pins 9 and 10.

Change the prescalers and counters to your desired frequency.

---

The screenshot doesn't show one signal exactly the inverse of the other. The *pattern* is inverted. If you had a 50% duty cycle, it would be an exact inverse.

---

> It looks good except they overlap (slightly) by 50ns. If I set them to 16 and 8, respectively, they don't overlap but they are slightly asymmetrical

OK, make OCR1A and OCR1B both 7:

```
  ICR1 = 15;
  OCR1B = 7;
  OCR1A = 7;

```

*Why 7? And why 15?*

The counts are zero-relative. So by counting to 15 on a 16 MHz processor we are actually getting 1/16th of the clock, namely 1 MHz. And half of that is 8 (which, zero-relative, is 7). So we are really doing:

* Period: 16 ticks of the 16 MHz clock
* Duty cycle: 8 ticks of the 16 MHz clock

---

Now, one cycle:

They change over at the same instant - pulse width exactly 500 ns.

And they change back at the same moment - pulse width also 500 ns.

# Answer
> 1 votes
Various AVRs have the capability to output both the normal and inverted timer waveform from a single output compare register simultaneously on two pins. These devices include, but are not limited to, ATtinyX5/V, ATtiny26/L, ATtinyX61A, and ATmegaXXU4.

The ATmega328P does not have this capability, therefore the smallest primary source Arduino that does is the Leonardo (ATmega32U4) and comparable devices. The Adafruit Trinket and the Digispark (both ATtiny85-based) also offer this.

# Answer
> 0 votes
What about also setting COM1B0 and then setting the initial values of OC1A and OC1B to opposites by writing to PORTB?

Also, I presume you mean 1 MHz and not 1 mHz?

# Answer
> 0 votes
Another option is to do this in hardware - it's trivial to invert a signal.

For example, see the selected answer for https://electronics.stackexchange.com/questions/30238/how-to-invert-a-digital-signal \- the second diagram - connect Vs to your clock, and Vo will be your inverted clock. For the two resistors, anything over 1k should be fine. Or use an inverter (which is the same thing, in one component, but is much less likely to be in your random-part box).

Note: There will be a very short delay going through this circuit - one place I saw suggested 1.5ns, but see the spec sheet of your transistor. A 1mhz clock "ticks" at 1,000ns (I guess, 500ns on, 500ns off), so this delay shouldn't be significant.

---
Tags: avr
---


# Question
Title: avr-g++ (or avr-gcc) and LiquidCrystal library
I'm trying to run a simple Hello World program from Arduino 1.6.5 from terminal. When I run it in Arduino IDE, it works good. When I'm trying to get it by `avr-g++` I have hard way to figure out how to include all libraries - so far I got this script:

```
avr-g++ -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o main.o main.cpp
-I"../arduino-1.6.5-r5/libraries/LiquidCrystal/src/"
-I"../arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/"
avr-g++ -mmcu=atmega328p main.o -o main
avr-objcopy -O ihex -R .eeprom main main.hex
sudo avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM1 -b 115200 -U flash:w:main.hex

```

First line (with both `-I` flags) compiles, but after running second line, I get:

```
main.o: In function `main':
main.cpp:(.text.startup+0xa): undefined reference to `LiquidCrystal::begin(unsigned char, unsigned char, unsigned char)'
main.cpp:(.text.startup+0x16): undefined reference to `Print::print(char const*)'
main.o: In function `_GLOBAL__sub_I_lcd':
main.cpp:(.text.startup+0x3a): undefined reference to `LiquidCrystal::LiquidCrystal(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
collect2: error: ld returned 1 exit status

```

How can I also include some libraries? I need the exact bash script.

# Answer
> 1 votes
I made a Makefile to compile the Blink program a little while back. It wasn't trivial.

```
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

```

---

I basically did this by observing what the IDE does (as Ignacio Vazquez-Abrams suggested) and replicated it. Now to add libraries you have to add even more steps.

---
Tags: arduino-uno, avrdude, avr-gcc
---


# Question
Title: Is Roboteq motor driver compatible with Arduino?
I'm planning use Roboteq motor driver for 24V brushed DC motor but I can't be sure that it's true or wrong. You know, Roboteq controller is too expensive and I don't want to spend money in vain. Have you any experience this controller? Are they compatible with Arduino?

http://www.roboteq.com/index.php/roboteq-products-and-services/brushed-dc-motor-controllers/mdc2230-detail Roboteq Controller Link

I also think, Pololu RoboClaw driver. https://www.pololu.com/product/1499 I don't know is it enough for wheelchair. Because, I already have used Pololu VNH5019 and it is not enough. (synchronicity and noise problems etc.)

If you have any ideas, I will be glad. Thank you.

# Answer
> 0 votes
It is not directly supported. But the device description lists RS232 port that can be interfaced with an Arduino using a TTL to RS232 converter. The description also mentions "several Analog, Pulse and Digital I/Os which can be remapped as command or feedback inputs, limit switches, or many other functions" so it is totally possible to control the controller with an Arduino, but depending on the method you choose it may require some effort.

---
Tags: arduino-mega, motor
---


title: Arduino selection for RTOS

text:
# Question
Title: Arduino selection for RTOS
I am brand new to Arduino and am having a difficult time understanding the "lay of the land". I'm looking for the beefiest, fastest, most compute-centric Arduino available to the market that will run embox.

As I understand it, there is really only the Uno and the Mega, both of which are 32-bit. However I also believe that 64-bit variations/designs exist and was wondering if anyone has actually implemented Arduino Uno/Mega as a 64-bit MCU. I also see there is the Arduino Due, but not sure how that fairs (beefiness-wise) with Uno/Mega.

So to summarize: **What is the beefiest Arduino one can find, is it 32- or 64-bit, and will it run an embedded RTOS like embox?**

# Answer
While I'm not experienced with running an RTOS on it, I'd highly recommend Teensy 3.1 as the "beefiest, fastest, most compute-centric Arduino". FreeRTOS and ChibiOS both support Teensy.
> 3 votes

# Answer
You could try an Intel Edison Arduino Kit.

It's 64 bit and can be programmed with a variant of the Arduino IDE. You can interleave Arduino code with system calls to the Linux OS, depending on which approach better suits a specific need.

Running an RTOS inside Edison seems a bit overkill, however it should be doable.

Otoh you could just rely on the much higher clock to provide quasi-deterministic response.

Or just ditch the Arduino IDE and write a normal program with your programming language of choice.
> 0 votes

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


title: Execute Code sent over Serial

text:
# Question
Title: Execute Code sent over Serial
I was wondering if its possible to send code to the Arduino, and then have it execute this code.

What I'm trying to do is use an Arduino Mega with a bunch of stuff connected to it send code to an Uno with a TFT LCD display to do whatever the Mega tells it to do with the Adafruit GFX Library. I want to add things to this 'system' gradually so I want the whole program hosted on the Arduino Mega, and a minimal amount of code on the Uno.

Sorry I'm really new at this so if its not possible at all let me know!
Thanks in advance,

-Will

# Answer
> 0 votes
No, it's not possible as you describe it.

The Arduino's main chip, the ATMega328p, is what is known as *Harvard Architecture*. This means that the Flash memory and RAM both occupy completely separate memory address spaces. The CPU in the chip is only able to fetch its instructions from the memory space the Flash is connected to (the *Instruction Bus*) and not the memory space the RAM is connected to (the *Data Bus*). This means it can only run instructions that are in Flash and not RAM.

It is possible to re-program the flash on the fly - after all, that's what the bootloader does, and while the actual act of reprogramming flash is fairly trivial, generating the instructions in the right way is far from trivial.

There are other options though.

1. Use an interpreted language. I believe there are versions of BASIC available for the Arduino that would allow you to upload a program through the serial port and execute it.
2. Define a protocol (or use an existing protocol) to send pre-defined control commands to the Uno. Firmata might be of use here.

---
Tags: arduino-uno, serial, arduino-mega, adafruit
---


# Question
Title: How can I make motor vibrate using arduino depending on the ultrasonic distance?
I want to make the vibration motor vibrate depending on the distance to an obstacle, for example if the distance is too short it should vibrate quickly and vice versa.

How can i make motor vibrate using arduino depending on the distance? Can you explain for me how can I use the delay in the vibration code? I found this code in the internet for vibration:

```
digitalWrite(y, HIGH);
delay(50);
digitalWrite(y, LOW);
delay(50);

```

I know that I can change the delay, but how can we do it depending on our purpose? Please help me .. I don't know the use of the delay :(

# Answer
> 1 votes
You could just replace the "50" in the first delay with the ultrasonic distance variable, I'll explain a bit more below.

Let's assume your ultrasonic sensor outputs an analogue value between 0V and 5V. The output is connected to analog pin A0. Then you just set pinMode(A0, INPUT) and analogRead the value from the pin and store it in the variable X or whatever. Then you just use the variable X as a delay and it will do what you want. The higher the value gets the longer it will vibrate. Something like this:

```
[...]
val = analogRead(A0);
digitalWrite(5, HIGH);
delay(val);
digitalWrite(5, LOW);
[...]

```

Second option, if you only wish to turn it on if it is above or under a certain limit, would be using an if condition.

For example:

```
if(variable > 50){
  // if the variable named variable is over 50 this code is going to be executed
} else {
  // If the variable is below 50 this is executed
}

```

If you are unfamiliar with if conditions then I suggest reading this too.

# Answer
> 1 votes
> I know that I can change the delay, but how can we do it depending on our purpose?

Are you asking how to use a *variable*? An example:

```
const int LED = 13;

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

void loop()
  {
  int amount = analogRead (A0);   // get a reading
  digitalWrite(LED, HIGH);
  delay(amount);
  digitalWrite(LED, LOW);
  delay(amount);
  }

```

That code reads some analog device, and adjusts the delay based on the figure it read.

# Answer
> 0 votes
I want to show you my thinking, and tell me please if it is right or wrong:

I build an relationship between the distance and the speed.

I know that (speed = distance/time) and if the obstacle is too close to the ultrasonic sensor the speed of the motor should be maximum, so I have decrease the time which is the delay, right?

I make the code according what i said above and it is shown below:

```
    if(distance <= 60 && distance >= 45)// the distance is too large
    {
    digitalWrite(motorPin, HIGH);

    delay(200);// I increase the delay to make the motor vibrate slowly

    digitalWrite(motorPin, LOW);

    delay(200);

    }

    else if(distance < 45 && distance >= 30)
    {
    digitalWrite(motorPin, HIGH);

    delay(100);

    digitalWrite(motorPin, LOW);

    delay(100);

   }
    else if(distance < 30){

    digitalWrite(motorPin, HIGH);

    delay(50);

    digitalWrite(motorPin, LOW);

    delay(50);

  }
  else
  {
    digitalWrite(motorPin, LOW);// If the distance is too large the motor will be off
  }

```

---
Tags: arduino-uno
---