title: Using L298N to control DC Motor

text:
# Question
Title: Using L298N to control DC Motor
I am developing a system where I want to control the direction of the DC motor (12V) from Arduino Mega/Uno. For that, I am using L298N H-bridge chip without the board as shown below.

My question is, do I need to add extra hardware or is it enough on its own?

Thanks in advance!

# Answer
> 1 votes
In theory, this particular device should work on its own. However you should search for and read the datasheet for it. (I'll leave you to do that yourself, just to make sure you really do read it.)

You should consider a heatsink too by the way, and provision for things like a fuse on the power, and whether you will be using a separate 5V for the logic (again you need the datasheet for that).

---
Tags: arduino-uno, arduino-mega, h-bridge
---


# Question
Title: How to solve Atmega 16A Serial write (println) hang with Arduino Uno firmware?
For doing some experiments I bootloaded an Atmega16a with Arduino Uno. I am powering my Atmega16a from Arduino UNO. I am not using any external clock. Atmega16a is connected to a breadboard. For bootloading I refer the site http://hardwarefun.com/tutorials/use-arduino-as-an-isp-programmer-to-program-non-arduino-avr-microcontrollers I can run blink sketch on my Atmega16a using Arduino as ISP. TX and RX of Atmega16 is connected to Max485's DI and RO respectively.

```
Atmega16a pin 14 (RXD) -> MAX485 pin 1-RO
Atmega16a pin 15 (TXD) -> MAX485 pin 4-DI
Atmega16a pin 17 (D3)  -> MAX485 pin 2 and 3. Also connects a LED to the pin

```

I used a boards.txt downloaded from https://github.com/sudar/arduino-extra-cores/blob/master/boards.txt

### Issue: hang at Serial.println

I faced issues when I started to interface with MAX485.

The program wont run if I add a `Serial.println`, see my program below.

```
void setup() {
   Serial.begin(76800); // I tried 9600 too
   pinMode(3, OUTPUT);
}

void loop() {
  digitalWrite(3, HIGH);
  delay(400);
  Serial.println("20"); //comment this code and could see the led blinks
  delay(2000);
  digitalWrite(3, LOW);
  delay(400);
}

```

### Regression

I tried Latest Arduino IDE as well as 1.0.6 version

I could do a serial communication with Raspberrypi and Arduino Uno via MAX485 without any issues. For the complete connection detail of MAX485 and other Arduino, check my blog.

Some times I receive some string to serial port of Raspberry pi like below. I run a nodejs app in RPi, using serialport npm and parser is RAW.

```
<Buffer fa>
<Buffer 82>
<Buffer 86 ff>
<Buffer fe>
<Buffer fe>

```

How to prevent these hangs?

# Answer
> 1 votes
Unfortunately you can't just simply upload the Arduino bootloader and expect it to work. The ATmega16 is not the same as the ATmega328. One quick look at the datasheet will already explain why this is not working. The UDR(USART data register) is at 0xC6 on the 328, while it's at 0x2B at the Atmega328. So the ATmega16 will look at the location where the 328 stores the received data and will not find it. This could explain the hang, but I expect that other things like UART setup will have gone wrong before you get to the receiving of data.

If you want serial communication with the ATmega16, try programming it directly in C with the AVR libraries and without the Arduino extensions. That will make it harder to figure out.

---
Tags: rs485
---


# Question
Title: Please explain this OneWire communication with Arduino Uno and DS2502-E48
The goal is to read the MAC address from a DS2502-E48chip.

I think I accomplished this goal too with the following code, but I can't get behind at how this works. I had a similar program with a PIC chip as reference.

I checked several references about OneWire and the DS2502 but not the info I needed to hop to the right memory addresses. Where'd I normally attain the information so that I know I have to write: **cc ,f0 , 0, 10** , read a *random* byte, and then I'm at the right position for MAC.

```
#include <OneWire.h>

OneWire ds(2);
void setup()
{
  Serial.begin(9600);

  byte i;
  byte dataLength;
  byte present = 0;
  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
    Serial.print("No more addresses.\n");
    ds.reset_search();
    delay(250);
    return;
  }

  ds.reset();
  ds.select(addr);

  delay(1000);     // maybe 750ms is enough, maybe not

  present = ds.reset();
  if (present != 1 )
  {
    Serial.println("No device present, exiting...");
    return;
  }

    ds.write(0xCC);//SKIP_ROM
    ds.write(0xF0);//READ_MEMORY
    ds.write(0);  // ?
    ds.write(10); // ?
    ds.read();    // ?
    dataLength = ds.read();

    for ( i = 0; i < dataLength; i++) {
    data[i] = ds.read();
    if ( i>3){
      Serial.print(data[i], HEX);
      Serial.print(" ");
    }
  }
}

void loop()
{

}

```

# Answer
> 0 votes
From the DS2502 datasheet:

> **Skip ROM \[CCh\]**
>
> This command can save time in a single-drop bus system by allowing the bus master to access the memory functions without providing the 64-bit ROM code. If more than one slave is present on the bus and a read command is issued following the Skip ROM command, data collision will occur on the bus as multiple slaves transmit simultaneously (open drain pulldowns will produce a wired-AND result).
>
> **READ MEMORY \[F0h\]**
>
> The Read Memory command is used to read data from the 1024-bit EPROM data field. The bus master follows the command byte with a 2-byte address (TA1=(T7:T0), TA2=(T15:T8)) that indicates a starting byte location within the data field. An 8-bit CRC of the command byte and address bytes is computed by the DS2502 and read back by the bus master to confirm that the correct command word and starting address were received. If the CRC read by the bus master is incorrect, a reset pulse must be issued and the entire sequence must be repeated. If the CRC received by the bus master is correct, the bus master issues read time slots and receives data from the DS2502 starting at the initial address and continuing until the end of the 1024-bit data field is reached or until a reset pulse is issued. If reading occurs through the end of memory space, the bus master may issue eight additional read time slots and the DS2502 will respond with a 8-bit CRC of all data bytes read from the initial starting byte through the last byte of memory. After the CRC is received by the bus master, any subsequent read time slots will appear as logical 1s until a reset pulse is issued. Any reads ended by a reset pulse prior to reaching the end of memory will not have the 8-bit CRC available.

So you are telling it that you want to read the memory from whatever device is on the bus, not any one specific one (since you are not needing to provide the ROM ID to identify the exat item on the bus), starting from address ((0 \<\< 8) |10) = 10.

From the DS2502-E48 datasheet you can see the layout of the memory:

> The data record starts with a length byte (0Ah) and the 4-byte UniqueWare Project ID 00001129h. The next 6 bytes contain the 48-bit node address which consists of an incrementing 24-bit extension identifier and the IEEE-assigned 24-bit company ID value 006035h. An inverted 16-bit CRC ends the data record. The remaining bytes of the 32-byte memory page remain unprogrammed. Neither the 24-bit extension identifier nor the 24-bit company ID are related to the 64-bit ROM registration number. The ROM registration number is used to provide a unique address to access the DS2502-E48 when multidropped on a 1-Wire bus.

So translating that into something more pictorial:

```
// Length byte
0x00: 0x0A

// UniqueWare PID
0x01: 0x00
0x02: 0x00
0x03: 0x11
0x04: 0x29

// Serialization ("extension") number
0x05: 0x??
0x06: 0x??
0x07: 0x??

// Company ID Value
0x08: 0x??
0x09: 0x??
0x0A: 0x??

// 16-bit CRC
0x0B: 0x??
0x0C: 0x??

// All the rest is EEPROM data
0x0D - 0x7F: 0x??

```

So by starting at address 10 (0x0A) you are reading the last byte of the company ID, the CRC, and then whatever else is in the memory after that.

To read the entire MAC address (least significant byte first) you should be starting to read at address 5.

# Answer
> 0 votes
I found a nice writeup on this on a blog. To quote his experimental findings:

> Comparing to the OneWire spec, we can tell it’s writing 0xCC, which should be SKIP\_ROM. Following that is 0xF0 (ReadMem), and two bytes starting address: 0x08, 0x00.

Based on this, the zero and 10 that you are writing are apparently an address value.

---
Tags: arduino-uno, 1-wire
---


title: Why can't I print this text to LCD?

text:
# Question
Title: Why can't I print this text to LCD?
I've been working on this for 4+ hours, and have gotten nowhere.

I have an array of weather conditions, and a number is sent over serial port to indicate which member of the array to print to the LCD.

I'm guessing the problem is in how I'm defining the array. These are my current 2 guesses for how to define it:

```
String weatherConditions[49] = { "tornado","hurricane","tropical storm","sev tstorms","tstorms","mix rain-snow","mix rain-sleet","mix snow-sleet","freez drizzle","drizzle","freez rain","showers","showers","snow flur","lt snow show","blowing snow","snow","hail","sleet","dust","foggy","haze","smoky","blustery","windy","cold","cloudy","mostly cloud","mostly cloud","part cloud","part cloud","clear","sunny","fair","fair","mix rain-hail","hot","isol tstorms","scat tstorms","scat tstorms","scat showers","heavy snow","scat snowshow","heavy snow","part cloudy","tshowers","snow showers","isol tshowers","not available" };

```

or:

```
char weatherConditions[49][16] = { "tornado","hurricane","tropical storm","sev tstorms","tstorms","mix rain-snow","mix rain-sleet","mix snow-sleet","freez drizzle","drizzle","freez rain","showers","showers","snow flur","lt snow show","blowing snow","snow","hail","sleet","dust","foggy","haze","smoky","blustery","windy","cold","cloudy","mostly cloud","mostly cloud","part cloud","part cloud","clear","sunny","fair","fair","mix rain-hail","hot","isol tstorms","scat tstorms","scat tstorms","scat showers","heavy snow","scat snowshow","heavy snow","part cloudy","tshowers","snow showers","isol tshowers","not available" };

```

I've tried many other ways of defining the array (including "char\* weatherConditions"), but I'm sure most of them were just ignorant guesses.

Later in the code I have this to display a member of the array:

```
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(weatherTodayHigh);lcd.print("/");lcd.print(weatherTodayLow);lcd.print(" ");lcd.print(weatherConditions[weatherCurrentConditionsCode]);
lcd.setCursor(0, 1);
lcd.print(weatherTomorrowHigh);lcd.print("/");lcd.print(weatherTomorrowLow);lcd.print(" ");lcd.print(weatherConditions[weatherTomorrowConditionsCode);
break;

```

Everything I try ends up causing nothing to be printed on the 1602 LCD display (I have 15 other scrollable "screens" that are displaying just fine on the LCD). The earlier text on this screen (the highs and lows for today and tomorrow) is displaying fine, but after that, where the weather condition text is supposed to be shown, there is nothing.

I'm able to easily display the same weather condition text on the serial monitor (for that I was using "String weatherConditions\[49\] = {..." and then "Serial.println(weatherConditions\[currentValue\]);").

How can I get members of a text array to be printed on the LCD?

# Answer
> 1 votes
Ignacio hit the nail on the head. Once I moved the weatherConditions array to EEPROM, the sketch worked perfectly. Also the IDE stopped giving me errors about low RAM.

---
Tags: c++, lcd, string
---


# Question
Title: C++ Namespace/scope problem when trying to attach arduino interrupt
I have defined a c++ class (RpmDriver) and want to use attachInterrupt in the constructor to link an Arduino pin to its ISR (RpmInt) in the class. When I try this, I get:

error: cannot convert 'RpmDriver::RPMInt' from type 'void (RpmDriver::)()' to type 'void (\*)()'

This is the cpp file:

```
#include "RpmDriver.h"
#include <Arduino.h>
int currentRpm;
long lastMillis;
int pin;

RpmDriver::RpmDriver(int Pins[])
{
    pin=Pins[0];
    currentRpm=0;
    pinMode(pin,INPUT);
    lastMillis = millis();
    attachInterrupt(digitalPinToInterrupt(pin),RPMInt, RISING);
}
RpmDriver::~RpmDriver(void)
{}

bool RpmDriver::GetData(char* dest,char* format)
{
    sprintf(dest,format,currentRpm);
}

void RpmDriver::RPMInt()
{
    double RPMConstant=40000;
    unsigned long newMillis=millis();
    unsigned long t = newMillis-lastMillis;
    t=100;//temp
    currentRpm=(t==0)?0:(int)RPMConstant/t;
    lastMillis=newMillis;
}

```

and the header file is

```
#pragma once
class RpmDriver
{
public:
    RpmDriver(int pins[]);
    ~RpmDriver(void);
    bool GetData(char*,char*);
private:
    void RPMInt(void);
};

```

Any help much appreciated!

# Answer
You can't.

Simply because a class member is not the right format of function for attachInterrupt.

You can only use normal functions with attachInterrupt, so the normal method is to have a normal function outside your class which then calls the member function within your class. How you arrange it so that it knows where your objects are is up to you.

* If you have only one object then assign it to a global pointer in your library using the constructor
* If you have lots of instances then create a linked list within your class in a static context and add each object to it in the constructor, then iterate through that list when the interrupt fires.
> 2 votes

# Answer
You should qualify `RpmDriver::RPMInt()` as `static`. Static member functions are very much like plain functions, only using their class as a sort of namespace. Obviously, you will not be able to access any member data, but this should not be a problem as it seems your class is not storing any data anyway.
> 1 votes

---
Tags: c++, interrupt, class
---


# Question
Title: Can I access individual pixels on my 16x2 LCD display
I have a generic 16x2 LCD display connected to my Arduino. I can use the standard LCD library to display characters, but are there way to turn on and of individual pixels?

# Answer
> 2 votes
It's possible to define custom characters for “generic 16x2 LCD displays” \[ie, displays based on HD44780 or equivalent controllers\], but only up to eight such characters at the same time. See LiquidCrystal.CreateChar for details. See page 2 and part of page 1 of the Print degree symbol ° on LCD arduino.cc thread for create-character examples that don't use the library. Page 1 of that thread also shows a table of all the characters built into typical HD44780 controllers, some of which may perhaps meet your needs.

For pixel-by-pixel LCD control, look at graphics LCDs, eg the KS0108 or LCD12864 and similar.

---
Tags: lcd, library
---


# Question
Title: Arduino Mega, Ubuntu, Time.h: No such file or directory
I'm using an Arduino Mega with Ubuntu 15.10.

Sadly I've got an error during compilation, that the Time.h library cannot be found. The verbose compile output shows:

```
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall
-fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega2560
-DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105
-D__PROG_TYPES_COMPAT__
-I/usr/share/arduino/hardware/arduino/cores/arduino
-I/usr/share/arduino/hardware/arduino/variants/mega
-I/usr/share/arduino/libraries/LiquidCrystal
-I/usr/share/arduino/libraries/SPI
/tmp/build6998056390288565759.tmp/Home_Guard.cpp -o /tmp/build6998056390288565759.tmp/Home_Guard.cpp.o
**Home_Guard.ino:2:20: fatal error: Time.h: No such file or directory**
compilation terminated.

```

I've already tried to use "time.h" instead of "Time.h" but it doesn't help.

# Answer
ok. It seems that the Ubuntu arduino package does not contain this library. The file Time.zip has to be downloaded from the authors website: http://www.pjrc.com/teensy/td\_libs\_Time.html and added in the Arduino GUI menue bar: Sketch -\> Import Library -\> Add Library
> 1 votes

---
Tags: time, ubuntu
---


# Question
Title: What is the best arduino board for a robotic arm?
In my university we need to buy arduino boards and kits to build a moving robotic arm, that moves up and down and clockwise in a specific degree (almost like humans's).

So, what's the most **suitable** arduino board to build this arm? I suggested to use the basic UNO board, but we may need to use relays (for example) if the power source is 12volts. So there is should be a better one.

My regards.

# Answer
If you are hoping to drive the arm straight from the Arduino, that's not going to work.

What you should do is:

* Define the maximum weight and size of the load your arm will carry.
* Define expected precision and speed of the movements.
* Count the Degrees of Freedom (DoF) your arm will need (1 DoF = 1 simple joint)
* Figure out size and materials of each part of the arm
* Calculate the torque required at each joint (yes, you need some basic physics calculation)
* Identify the motors you want to drive (DC are inexpensive but not very well suited for this, without lots of additional control logic & HW - stepper motors are better, but they still do require some additional effort - servos are the easier way but they are a bit more expensive)
* Define the requirements for both the micro controller and the power supply, based on the previous choice.

If you can refine your question, based on the few points I sketched, you will get ahead much faster and with less risk later on to have to backtrack and re-design something.

You might have already answered some of those steps, then I suggest you list here your choices.

Similarly, if you are referring to some link you found (instructables, etc.) please post it.

As reference, hobbyking has an extensive catalog of motors and power supplies. You can find the same items also on ebay, but hobbyking can be used at least as reference for various specs (power, torque, weight, etc.).
> 2 votes

# Answer
Best answer is Arduino Uno because it is enough for your application.

But all Arduino are works on 5 volt or 3.3 volt.

For operating 12 volt devices use transistors or MOSFETs.
> 0 votes

---
Tags: arduino-uno, robotics
---


# Question
Title: How can I reset the program on an Arduino Uno while the device isn't recognised by my computer at all?
So I've recently been playing around with my arduino uno, and today it completely refuses to communicate with my computer at all. I've tried using other cables, switched OS (Tried Windows 8.1 and Ubuntu 14.04), and tried on my laptop, none of them recognise the device at all.

From what I've read, this problem can be caused my a program on it with a Serial.println() frequently used, which I believe is the case here. The solution for this problem is according to other answers, to hold the reset button while I upload an empty sketch to the arduino. However, I can't do this, since the computer doesn't communicate with the arduino at all.

Any ideas what could've gone wrong, and how to fix it?

EDIT: Alright, the problem seems to have resolved itself... I have no idea what made it work, I was frustrated and went to bed last night, and today it works without an issue..

EDIT #2: Scratch that.. now I get this error when I try to upload a program to the arduino:

```
avrdude stk500_getsync() not in sync resp=0x00

```

The device does show up in Device Manager, so I tried installing the arduino drivers for it, but it gives me the error code 10. Windows automatically installs some serial driver for it, but any attempts of serial communication with the arduino fails.

# Answer
> 3 votes
I had the same problem with my Arduino Leonardo. But when I kept the reset button pressed and plugged it into my laptop, it got recognised again. But since you're using an arduino uno it might also be the atmega16u2 which isn't working properly. If holding the reset button while plugging in the arduino to the laptop doesn't work, try to reset your atmega16u2 chip on the arduino. This is the chip which makes the communication from USB possible.

To reset the atmega16u2 follow this tutorial

# Answer
> 1 votes
I also got same problem and actually the problem was is of arduino. Arduino ATmega328 IC and ATmega16u chip was damaged . After that I replace ATmega328 Damaged Ic With new one reprogram it and program in ATmega16u chip and upload firmwares to ATmega16u chip.

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


# Question
Title: Why can't I upload a sketch while other components/devices are connected to my Uno?
I wanted to make a fairly simple circuit which would flash a series of LEDs in sequence, using my Arduino Uno (more specifically, a SainSmart clone). I wrote my sketch and it compiled fine. After that, I connected 8 LEDS+resistors to pins 0 through 7, and then connected the Uno to my computer via USB.

I've uploaded sketches successfully in the past, so I'm sure my settings and drivers etc. are correct. However, when I tried to upload my sketch this time, it didn't work.

I tried removing everything I'd connected to the Arduino's pins, and suddenly the upload worked again.

Why does this happen? Does it mean I have to disconnect everything from the board every time I upload a sketch?

# Answer
The problem is specifically pins 0 and 1. Although they can be used as regular digital IO pins, they also serve as the RX and TX pins for the Uno's serial port. The USB connection (for uploading sketches etc.) is routed to the same pins internally. Unfortunately that means anything connected on pins 0 and 1 can interfere with the serial connection, preventing communication via USB.

In short, it's not necessary to disconnect *everything* when uploading a sketch. It should only be necessary to disconnect anything from pins 0 and 1. Rather than going through that hassle every time a sketch is uploaded though, it may be best just to avoid using those pins unless necessary (e.g. you run out of other pins, or your project needs a serial connection to another device).
> 22 votes

# Answer
" Peter R. Bloomfield " I used to upload sketch in my arduino uno by connecting Rx and Tx pin but my sketch get uploaded. Actually problem is arduino uno driver may be deleted in your case
> 1 votes

---
Tags: serial, pins, uploading, arduino-uno
---


# Question
Title: Arduino UNO does not get recognized by PC(no USB connecting sound), also TX and RX not blinking, neither are lit
I am trying to build a robot, which needs motors to roll around. So I was trying to control two DC motors with H-Bridge that comes with Arduino StarterKit(H-bridge motor driver \[L293D\]). I used Sketch that looks something like that

I did read that Arduino needs separate powering, but i did not use any only USB connection. I connected 5V that comes from arduino to where + pin from battery should have been connected and motors were controlled and working. However when i tried using 9V battery and connecting it as seen on above picture ,H-bridge did not control mototrs and nothing was working. There is also another aspect - when robot was touching the surface then wheels did not move aka motors did not rotate and when you picked it up motors accelerated to quite some speed. Also when robot was on the surface and connected via USB, the PC made these USB connecting sounds repeatedly. I am not sure when RX and TX stopped working. Power LED and L13 LED do work correctly.

Any ideas? Is it Fixable?

# Answer
> 1 votes
You should definitely avoid connecting anything else than 5v to these 5v(!) PINs. The Uno has regulators, but these only work when powered through the power-dc-connector (or USB). You can easily buy a 9v-block to dc-jack cable to connect power to the right point easily.

# Answer
> 1 votes
The "5V" pin takes only regulated 5V input. Your schematic shows the the board powered here, and you mention 9V battery. That's not a good idea.

If you have 7V-12V, then you can supply the board via the "Vin" pin. It passes through the same regulation circuits that the DC jack does.

http://arduino.cc/en/Main/ArduinoBoardUno

> VIN. The input voltage to the Arduino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

# Answer
> 0 votes
May be your ATmega328 IC would have been damaged or ATmega16u or ATmega8u chip was damaged. I also got same few days ago.

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


# Question
Title: Can I simply unplug the Arduino usb if serial communication is active?
So, after the sketch is uploaded, and I want to turn the Arduino off while it is running a sketch, all I have to do is unplug it. Should be safe as long as nothing is uploading. But I wonder, if I use serial communication between the Arduino and my Computer in a sketch, does it harm either if I simply unplug it?

# Answer
> 5 votes
if the sketch is uploaded, it wont hurt it to unplug. Just give it another source of power and it will run its sketch.

# Answer
> 3 votes
You can unplug it, it does not harm. If your arduino does not need power, eg. for writing EEPROM or FLASH, then no danger there. (in case it was writing EEPROM/FLASH it could write it faulty but usually even that is not a problem either)

# Answer
> 2 votes
Yes, you can unplug it directly whether if serial communication is active or not if you dont need power supply anu more using usb cable

---
Tags: arduino-uno, serial, uploading, usb
---


# Question
Title: How to make the motor car move left-forward / left-backward/ right-forward/ right-backward
I'm using an Arduino Uno to make a motor car. And I successfully made it move forward / backward / left / right.

```
void forward(void) {
  analogWrite(EA, 254); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

void backward(void) {
  analogWrite(EA, 255); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

void left(void) {
  analogWrite(EA, 180); //speed 0 - 255
  analogWrite(EB, 180); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

void right(void) {
  analogWrite(EA, 180); //speed 0 - 255
  analogWrite(EB, 180); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

```

The problem is, I found it is quite strange if I need to first press left/ right and press forward to turn around. I would like to make 4 extra buttons for left-forward / left-backward/ right-forward/ right-backward. Any ideas to create 4 extra functions for that?

Thanks for helping.

**Update: Connection**

```
int EN2 = 14;
int EN3 = 15;
int EN4 = 16;
int EN5 = 17;
int EA = 3;
int EB = 5;

```

**Update: Attempted code and hardware connection**

```
void left_top(void) {
  analogWrite(EA, 128); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

void right_top(void) {
  analogWrite(EA, 255); //speed 0 - 255
  analogWrite(EB, 128); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

void left_down(void) {
  analogWrite(EA, 128); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

void right_down(void) {
  analogWrite(EA, 255); //speed 0 - 255
  analogWrite(EB, 128); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

```

Left top / right top seem not to move at all, and right top / down is just similar to right / left.

**And for hardware, I am using**

Arduino AR 293d

For the motor connection, it's like this:

# Answer
Regarding the pins - I wanted to find out the physical (hardware) connections.

Pending an updated answer I presume the EA and EB will set the speed for two motors and EN2/EN3 and EN4/EN5 control the direction of the motors. If that's the case you could make the car turn sideways but changing the speed of only one of the motors. For example:

```
void forwardLeft(void) {
  analogWrite(EA,128); //speed 0 - 255
  analogWrite(EB,255); //speed 0 - 255
  digitalWrite(EN2,LOW);
  digitalWrite(EN3,HIGH);
  digitalWrite(EN4,LOW);
  digitalWrite(EN5,HIGH);
}

```

I assume that EA is the left motor and EB is the right motor. This will make the right one rotate twice as fast as the left one so the car should go forward, but also turn left. If you keep this running the car should end up going in a circle. By making the `128` lower you will change how fast the car is turning.

The other functions should be similar.

***Caveat emptor** \- of course this will mean nothing if the beginning assumptions are incorrect.*

**EDIT**
Can't figure out why it doesn't work without having the thing in my hands. Have not found a schematic for that board, but intuitively it should work as described above.

Things you can do to try to figure out - try different numbers instead of 128, the speed of the motors might not vary linearly with the voltage. What you need to obtain is to have one motor go twice as fast as the other one and in the same direction. That should turn the car around.
> 1 votes

# Answer
just go to this link. Visit to https://www.arduino.cc/en/Tutorial/PWM

At first use PWM to both right side and left side motor. When right side motor spin/rotate at 255 value make leftside motor rotation speed at about 100 then you will see that it goes left-forward like wise you do rest of other.

Eg.

```
void setup()
{
  //LEFT MOTOR
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT); // connect pwm pin of left motor at pin9

  //right motor
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT); motor // connect pwm pin of right motor at pin12
}

void loop()
{
  digitalWrite(7, HIGH);
  digitalWrite(8, LOW);
  analogWrite(9, 100);
  delay(1000);
  digitalWrite(10, HIGH);
  digitalWrite(11, LOW);
  analogWrite(12, 255);
  delay(1000);
}

```
> 0 votes

---
Tags: arduino-uno, programming, motor, analogwrite, digital
---


# Question
Title: PC <-> Xbee <-> Another Xbee Communication
I have this application where I want to send commands from the PC to an Arduino, remotely, and receive an answer back.

The hardware configuration I'm using to achieve that is the following:

```
PC <--> Arduino with an Xbee <--> Another Arduino with another Xbee

```

It's just half-duplex communication. Everything seems easy, but there is a problem.

Each Arduino has an Xbee Shield with an Xbee module connected to it. Reading the documentation of the ArduinoXbeeShield, an excerpt caught my eye:

*"With the jumpers in the Xbee position (i.e. on the two pins towards theinterior of the board), the DOUT pin of the Xbee module is connected to the RX pin of the microcontroller; and DIN is connected to TX. Note that the RX and TX pins of the microcontroller are still connected to the TX and RX pins (respectively) of the FTDI chip - data sent from the microcontroller will be transmitted to the computer via USB as well as being sent wirelessly by the Xbee module. **The microcontroller, however, will only be able to receive data from the Xbee module, not over USB from the computer**.*

*With the jumpers in the USB position (i.e. on the two pins nearest the edge of the board), the DOUT pin the Xbee module is connected to the RX pin of the FTDI chip, and DIN on the Xbee module is connected to the TX pin of the FTDI chip. This means that the Xbee module can communicate directly with the computer - **however, this only works if the microcontroller has been removed from the Arduino board. If the microcontroller is left in the Arduino board, it will be able to talk to the computer normally via USB, but neither the computer nor the microcontroller will be able to talk to the Xbee module**."*

That means I will not be able to build what I want with this configuration? I already tried, but didn't work.

# Answer
Basically with your shield you have two options:

1. Communicate between the MCU and the XBee at the cost of not being able to communicate between the PC and the MCU.
2. Communicate between the PC and the XBee at the cost of having to remove the MCU from the board completely.

Neither of which are particularly ideal. The first option is completely out since that rules out all PC communication. The second option turns the Arduino into just a USB-\>TTL Serial adapter - and a rather expensive one at that (you can get them on eBay for like $2).

What you want is to re-wire the system using jumper wires (messy, I know) so that the TX and RX pins of the XBee connect to other pins on your Uno then use SoftwareSerial to communicate with the XBee. That will leave the Arduino's TX and RX pins free for communicating with the PC.

Alternatively invest in a different Arduino that has more hardware UART interfaces, like a Mega2560.
> 0 votes

---
Tags: arduino-uno, serial, shields, xbee, wireless
---


title: How can i change "+" sign into spaces?

text:
# Question
Title: How can i change "+" sign into spaces?
I'm working with esp8266.i am able to send text from webserver to arduino which is displayed on my 16\*2 lcd display.but the problem is that when i send text including space i.e:john smith, the text show on my serial monitor and also in lcd like that (john+smith)..the spaces i gave is converted into "+" sign..Can anyone suggest me how to overcome from that problem?? my code is given below:

```
  #include <SoftwareSerial.h>
  #include <LiquidCrystal.h>

 SoftwareSerial espSerial(2,3);

  LiquidCrystal lcd(12,11, 7, 6, 5, 4);

const bool printReply = true;
const char line[] = "-----\n\r";
int loopCount=0;

char html[50];
char command[20];
char reply[500];

char ipAddress [20];
char name[30];
int lenHtml = 0;
char temp[5];

void setup()
{
      Serial.begin(9600);
        lcd.begin(16,2);

      Serial.println("Start\r\n\r\n");

      lcd.print("WELCOME ");

      espSerial.begin(9600);

      Serial.println("reset the module");
      espSerial.print("AT+RST\r\n");

      getReply( 2000 );

      Serial.println("Change to station mode");
      lcd.clear();
      lcd.print("station mode");
      espSerial.print("AT+CWMODE=1\r\n");
      getReply( 1500 );

      Serial.println("Connect to a network ");
      lcd.clear();
     lcd.print("connecting...");

      espSerial.print("AT+CWJAP=\"ESP_E61A83\"\r\n");
      getReply( 6000 );

      Serial.println("Get the ip address assigned by the router");
      espSerial.print("AT+CIFSR\r\n");
      getReply( 1000 );

      int len = strlen( reply );
      bool done=false;
      bool error = false;
      int pos = 0;
      while (!done)
      {
           if ( reply[pos] == 10) { done = true;}
           pos++;
           if (pos > len) { done = true;  error = true;}
      }

      if (!error)
      {
            int buffpos = 0;
            done = false;
            while (!done)
            {
               if ( reply[pos] == 13 ) { done = true; }
               else { ipAddress[buffpos] = reply[pos];    buffpos++; pos++;   }
            }
            ipAddress[buffpos] = 0;
      }
      else { strcpy(ipAddress,"ERROR"); }

      Serial.println("Set for multiple connections");
      espSerial.print("AT+CIPMUX=1\r\n");
      getReply( 1500 );

      Serial.println("Start the server");
        lcd.clear();
      lcd.print("Server starts");
      espSerial.print("AT+CIPSERVER=1,80\r\n");
      getReply( 1500 );

      Serial.println("");

   lcd.clear();
      Serial.println("Waiting for page request");
      Serial.print("Connect to "); Serial.println(ipAddress);
      Serial.println("");
lcd.print("feed me more");
delay(1500);
        lcd.clear();

}

void loop()
{
      if(espSerial.available())

          bool foundIPD = false;
          for (int i=0; i<strlen(reply); i++)
          {
               if (  (reply[i]=='I') && (reply[i+1]=='P') && (reply[i+2]=='D')   ) { foundIPD = true;    }
          }

          if ( foundIPD  )
          {

              loopCount++;

              int nameStartPos = 0;
              for (int i=0; i<strlen(reply); i++)
              {
                   if (!haveName)
                   {
                         if (  (reply[i]=='n') && (reply[i+1]=='a') && (reply[i+2]=='m') && (reply[i+3]=='e')  && (reply[i+4]=='=') )
                         {
                             haveName = true;
                             nameStartPos = i+5;
                         }
                   }
              }

              if (haveName)
              {
                    int tempPos = 0;
                    bool finishedCopying = false;
                    for (int i=nameStartPos; i<strlen(reply); i++)
                    {
                         if ( (reply[i]==' ') && !finishedCopying )  { finishedCopying = true;   }
                         if ( !finishedCopying )                     { name[tempPos] = reply[i];   tempPos++; }
                    }
                    name[tempPos] = 0;
              }

              if (haveName) { lcd.clear(); lcd.print("TEACHERS INFO..");Serial.print( "name = ");lcd.setCursor(0,1);Serial.println(name);lcd.print(name);Serial.println("");lcd.print(""); }

              else          { Serial.println( "no name entered");   Serial.println("");lcd.print(""); }

              strcpy(html,"<html><head></head><body>");
              strcpy(command,"AT+CIPSEND=0,25\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              strcpy(html,"<h1 >TEACHERS INFORMATION WEBSERVER</h1>");
              strcpy(command,"AT+CIPSEND=0,40\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              strcpy(html,"<p>CREATED by jack</p>");
              strcpy(command,"AT+CIPSEND=0,31\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              strcpy(html,"<p> Teachers Request number ");
              itoa( loopCount, temp, 10);
              strcat(html,temp);
              strcat(html,"</p>");

              // need the length of html
              int lenHtml = strlen( html );

              strcpy(command,"AT+CIPSEND=0,");
              itoa( lenHtml, temp, 10);
              strcat(command, temp);
              strcat(command, "\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

             if (haveName)
             {

                  strcpy(html,"<p >TEACHER name is "); strcat(html, name ); strcat(html,"</p>");

                  lenHtml = strlen( html );
                  strcpy(command,"AT+CIPSEND=0,"); itoa( lenHtml, temp, 10); strcat(command, temp); strcat(command, "\r\n");
                  espSerial.print(command);
                  getReply( 2000 );
                  espSerial.print(html);
                  getReply( 2000 );
             }

              strcpy(html,"<form action=\""); strcat(html, ipAddress); strcat(html, "\" method=\"GET\">"); strcat(command, "\r\n");

              lenHtml = strlen( html );
              itoa( lenHtml, temp, 10);
              strcpy(command,"AT+CIPSEND=0,");
              itoa( lenHtml, temp, 10);
              strcat(command, temp);
              strcat(command, "\r\n");

              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              strcpy(html,"Name:<br><input type=\"text\" name=\"name\">");
              strcpy(command,"AT+CIPSEND=0,40\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              strcpy(html,"<input type=\"submit\" value=\"Submit\"></form>");
              strcpy(command,"AT+CIPSEND=0,43\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              strcpy(html,"</body></html>");
              strcpy(command,"AT+CIPSEND=0,14\r\n");
              espSerial.print(command);
              getReply( 2000 );
              espSerial.print(html);
              getReply( 2000 );

              espSerial.print( "AT+CIPCLOSE=0\r\n" );
              getReply( 1500 );

              Serial.println("last getReply 1 ");
              getReply( 2500 );

              Serial.println("last getReply 2 ");
              getReply( 2500 );

          }
      }

      delay (100);

}

void getReply(int wait)
{
    int tempPos = 0;
    long int time = millis();
    while( (time + wait) > millis())
    {
        while(espSerial.available())
        {
            char c = espSerial.read();
            if (tempPos < 500) { reply[tempPos] = c; tempPos++;   }
        }
        reply[tempPos] = 0;
    }

    if (printReply) { Serial.println( reply );  Serial.println(line);     }
}

```

# Answer
It is hard to understand what your code does. You said that arduino recives text from the server, but I see in the code is that the arduino **is** the http server, serving an html page with a form in it.

That is also the reason you recieve spaces replaced with "+", the http request is **url encoded**.

The problem with a search and replace solution of a "+" sign is that url encoding is more than a "+" sign. A space can also be encoded into %20 and there are several other characters that are being encoded as well.

What you will have to do is to implement a **decoding** function. It is not that hard but if you are lazy, there are plenty of C implementations available on the net. Here is a quick google search hit: https://gist.github.com/jmsaavedra/7964251
> 1 votes

# Answer
If you have your text in a character array, which it seems you have, then it is simple enough to iterate through that array changing whatever characters you want.

For instance, if the text is in `reply` then:

```
for (char *p = reply; *p; p++) {
    if (*p == '+') *p = ' ';
}

```

That is, starting at the beginning of reply, by creating a pointer `p` and pointing it at the start of reply, check to see if there is anything except the `NULL` character, run the code inside the brackets, and move to the next character (p++).

The code inside the brackets looks to see if the current character is a + and if so then set the current character to be a space.

Another way is to use an integer counter:

```
for (int i = 0; reply[i] != 0; i++) {
    if (reply[i] == '+') reply[i] = ' ';
}

```
> 0 votes

# Answer
Two things: +If you are using strings, try using the String built in object, it is very handy and useful +when using String, you can use replace function
> 0 votes

---
Tags: esp8266
---


# Question
Title: Why does Arduino Due Native Port change serial ports after every reset? (Linux)
Previously I had my Due connected via Programming Port for weeks, and it never changed serial ports after pressing the reset button. Recently I switched to having it connected via the Native Port instead, and was surprised to see that it changes port numbers every time I press the reset button.

For example if it was on ttyATM1 beforehand, after pressing reset it'll be on ttyATM2 instead. It changes numbers like this after every reset. Is this normal behavior?

I have a python script sending serial data to the Due, and I have to change the port number in the python code every time the Due changes ports.

# Answer
It happens because of Linux, not because of the Arduino. Since you unplug/reset the DUE while the port is still open, when it's back online, the old file name is still in use, so a new one is created. Just close the port before resetting the DUE and you will see that after the reset it will have the same one.

You can easily reproduce the same issue with a serial to usb adapter (/dev/ttyUSBS0,1,2,etc) and screen or minicom.

To make your program more robust, you should listen for kernel events and open the port accordingly.
> 1 votes

---
Tags: serial, arduino-due, linux
---


# Question
Title: Any way to pass EthernetClient to function outside of loop automatically?
I have an Arduino webserver that displays many buttons over a webpage (73 at the moment) that toggle different switches. I shortened up the button-drawing code with this function:

```
void displayButton(String toggleName, byte toggle, byte link1, EthernetClient & client, boolean last) {
  if (toggle == 0) client.print("<a href=\"/?");
  else client.print("<a class=\"linkSelected\" href=\"/?");
  client.print(link1);
  client.print("\">");
  client.print(toggleName);
  client.print("</a>");
  if (last) client.print("<br><br>");
}

```

And this is a shortened version of my loop function:

```
void loop() {
  EthernetClient client = server.available();
  if (client) {
    boolean done = false;
    while (client.connected() && !done)
    {
      while (client.available () > 0 && !done)
        done = processIncomingByte (client.read ());
    }  // end of while client connected
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();
      client.print("<HTML><HEAD>");
      displayButton("F8", f8Toggle, 57, client, 0);
      displayButton("F9", f9Toggle, 58, client, 0);
      displayButton("F10", f10Toggle, 59, client, 1);
      client.println("</center></body></html>");
      delay(5); client.stop();
  } // end of "if client"
} // end of loop

```

I'm wondering if there's any way to have the displayButton function use the EthernetClient instance without it having to be passed every time. I'm interested in this in order to clean up my code a little (since I would be able to remove 73 instances of the word "client"), and also as a learning experience.

# Answer
> 1 votes
As Majenko has noted in the comments, the solution was to declare "EthernetClient client;" as a global variable, outside of the loop. Normally I would've tried something like this on my own, but was hesitant to do so because I had never seen anything like that in other code.

---
Tags: web-server
---


# Question
Title: Will there be any pin interference in this Project?
I am working on a project with Arduino Uno Clone. After having a look on my arrangement, please tell me whether I will have to face any difficulty or consider any thing.

I have a relay on pin 2 (drive An Induction cooktop from AC Mains),

6 mini 9g servo from pin 3-8 (want to drive non-pwm pins with any Software library),

a 8 ohm speaker on pin 9,

a microSd card module from pin 10-13 (play .wav files through speaker),

5 pushbuttons from pin A0-A4,

a toy dc motor on A5 (Drive through a transistor). So my questions are:

1. Will I have to face any pin arrangement problem in my project? If yes, please give me a solution
2. I have six servos and a dc motor in which only one will be moving at a time, is there really a need of external power source for motors
3. I have to drive this arrangement through AC Mains, but i dont want to buy An adapter. I have a mobile charger which have written "INPUT 100-250V AC, OUTPUT 4-12V, 800mA" , can I drive my arduino with this?
4. Can I boost the volume of my speaker by using a transistor or capacitor (I have no idea about amplifier IC) ?
5. I have to include these librairies, SD library, tmrpcm, SPI, servo, and any one extra to drive servos on non-pwm pins. What would be the total size because my arduino has only 30kb approx? Thanks To Give Me Time. Please help me.

# Answer
> 1 votes
1. possibly you will face problems with current drain and timing. There is no ready made solution. You have to get a bit farther by yourself and come back with detailed descriptions of your problems.
2. check on other threads (google) the issues with driving directly a coil. There are plenty of explanations why you need to be careful about it.
3. you should at least try to do the math yourself, then ask for verification. Try to calculate the power requirements of each component (average, maximum, peak) and add them up for every scenario. The you can report your finding and ask for confirmation/advice.
4. Sure you can, there are plenty of solutions available, but you have to define your requirements and constraints. Then it's easy to pick one solution (or at least google for it).
5. Just try to include them in the project and compile them. It's fast and you will get the answer immediately. There are ways to optimize things, but first you should assess if it's needed.

All in all, to get more help, you should show more in detail what you have already done, what are your concerns and why.

---
Tags: arduino-uno
---


# Question
Title: Dust sensor for Arduino in open and windy environment
I intend to create a DIY dust sensor, specifically Particulate Matter up to 10 micrometer in size (PM10) using Arduino UNO for the region surrounding a building which is located next to a factory that produces wood-based products. Is there any specific sensor that should suit my need, that is to collect and measure dust particles in an open environment and possibly a windy condition? Any implementation ideas are also welcome.

# Answer
A popular option is the Shinyei PPD42 sensor. There are a few well-documented blogs that describe how to connect it to an Arduino. Some of the users determined that the sensors are more accurate when a fan is placed on the unit to blow air through it, but this might not be necessary in an outdoors and windy environment.

I have two of these sensors hooked up to an Arduino, one monitoring indoors and one outdoors. I found that the indoors unit needed a fan on it to help it detect particles better (otherwise I was getting too many zeros). But the outdoors unit seems fine without the fan.

I mainly followed this blog's instructions for the code: http://www.howmuchsnow.com/arduino/airquality/grovedust/

I think I read a few months ago that the next best sensors are in the $200 range.

I have a Dylos DC1100 dust monitor (considered very accurate) and it usually correlates with my Shinyei readings. But I'm pretty sure I introduced some "magic numbers" into my code to make the Shinyei readings match more closely with the Dylos. The entire process wasn't easy for me, and it took me weeks to get everything to behave the way I wanted.
> 2 votes

# Answer
It depends on how far you want to go. If you are looking for something cheap, than a GP2Y1010AU0F will only cost you a few pounds. Or you could step up to £30 GBP or even £1000GBP.

Since you are looking at using an Arduino and not a PC then I'm guessing the GP2Y1010AU0F would be a good idea. I haven't tried it but this site should steer you the right way: http://arduinodev.woofex.net/2012/12/01/standalone-sharp-dust-sensor/
> 0 votes

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


title: Broken Score on Game Sketch

text:
# Question
Title: Broken Score on Game Sketch
I have modified the code for Flappy Duino to give me a score at the end of the game. Here is the code:

```
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>

Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);

#include "Sprite.h"
#include "Chym.h"
#include "Bar.h"

Chym player;
Bar bar; Bar bar2;
int gameScore = 0;
int highScore = 0;
int KNOCK_PIN = 2;
int LED_PIN = 8;

boolean clicked = false;

void loop(){}

void resetGame() {
  player.respawn();
  bar.setPos(0, 20);
  bar2.setPos(50, 30);
  gameScore = 0;
}

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

  display.begin();
  display.setContrast(50);
  display.clearDisplay();
  display.display();

  digitalWrite(LED_PIN, HIGH);

  pinMode(KNOCK_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);

  resetGame();

  while(1) {
    getInput();
    player.update();
    bar.update(); bar2.update();
    drawLCD();
  }
}

void getInput() {
  int knock = digitalRead(KNOCK_PIN);
  if (knock == 0) { // push down
    clicked = true;
    gameScore = gameScore + 1;
    Serial.println(gameScore);
  }
  else {
    clicked = false;
  }
}

void drawLCD() {
  display.clearDisplay();

  if (!player.isDead()) {
    int ht1 = bar.hitTest(player.getX(), player.getY());
    int ht2 = bar2.hitTest(player.getX(), player.getY());
    int die = ht1 + ht2;
    if (die == 1) {
        // game over
        player.die();
    }

    if (clicked) {
      player.flyUp();
    }
    else {
      player.cancelJump();
    }
    player.render();

    bar.render(); bar2.render();
  }
  else {
    if (gameScore >> highScore) {
      highScore = gameScore;
    }
    display.setCursor(0, 0);
    display.setTextSize(1);
    display.print("ur Score- ");
    display.println(gameScore);
    display.print("HI Score- ");
    display.println(highScore);
    if (clicked) {
      resetGame();
    }
  }

  display.display();
}

```

The first time the game runs thru the gameScore is greater than highScore so gameScore and highScore print as the same. However every other time the function is called up the highScore doesn't change even when the following statement is true:

```
if (gameScore >> highScore) {
          highScore = gameScore;
        }

```

What am I doing wrong?

# Answer
```
if (gameScore >> highScore)

```

You have the wrong operator there. `>>` is *right shift*, so you are right shifting the `gameScore` by `highScore` bits, which if it's more than 16 will end up as 0.

Instead you just want `>` for *greater than*:

```
if (gameScore > highScore)

```
> 1 votes

---
Tags: programming, c++, sketch
---


# Question
Title: Ultrasonic sensor returns random values on external power supply
my Problem is, that I get random values from my ultra sonic sensor if my arduino is connected to any external power supply (vin port 30) on my arduino nano.

If I power up from the laptop usb port, I get consistent values.

I have tested 3 different power supplies between 7-17V and up to 2000mA. I have tested this on 2 different nano boards. Also tested with an extra 2000uF capacitor between vin and gnd

pls help if you got an idea :)

# Answer
So i tried to used a stable 5V input on the 5V input pin and got the same more or less random values (jumping all around... especially on targets more than 1m away)

So I changed form newPing lib (http://forum.arduino.cc/index.php?topic=37712.0) to Ultrasonic lib (http://forum.arduino.cc/index.php?topic=37712.0).

Now the values are correct on each power supply and even more accurate on high distance than with newPing on USB power supply.

Don't know whats broken with the newPing v1.7 lib -.- but this works!
> 3 votes

---
Tags: power, arduino-nano
---


title: Connecting two arduinos using WiFi

text:
# Question
Title: Connecting two arduinos using WiFi
I have two arduinos (An UNO R3 and a Mega 2560), and I need to communicate them via two ESP8266 modules to exchange some values.

In one arduino I'll use a SW-420 vibrarion module, and I need to send a value wirelessly to the other board, which it'll have an LCD screen that will display a message when a value is recieved.

How can I do that with that specific WiFi modules? Thanks in advance

# Answer
> 1 votes
Step 1: I would load NodeMCU on you ESP8266: https://github.com/nodemcu/nodemcu-firmware

Step 2: Connect to your home router or make an ap on one of your ESP and connect them... use the api: https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu\_api\_en over serial connection

Step 3: write a TCP server:

```
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
  conn:on("receive",function(conn,payload)
    print(payload) //This payload will be send to your arduino over soft serial
    conn:send("<h1> Hello, NodeMCU!!! </h1>")
  end)
  conn:on("sent",function(conn) conn:close() end)
end)

```

Step 4: write a TCP client:

```
suc = false;
function sendData( host, pathData )
    suc = false;
    print("GoSending!");
    -- A simple http client
    conn=net.createConnection(net.TCP, 0)
    conn:on("receive", function(conn, payload)
        if(string.find(payload, "200 OK")~=nil) then
            suc = true;
            print("AllDone")
        else
            suc = false;
        end
    end)
    conn:on("connection", function(c)
        print("connected");
        conn:send("GET /".. pathData .." HTTP/1.1\r\nHost: ".. host .."\r\n"
            .."Connection: keep-alive\r\nAccept: */*\r\n\r\n")
        end)
    conn:on("disconnection", function()
        if(suc==false) then
            print("ErrorSending")
        end
    end)
    conn:on("reconnection", function() print("reconnection") end )
    conn:connect(80,host)
end

```

Step 5: Connect your esp boards with software serial to the arduino

Step 6: write (from board 1) to softserial to esp1: sendData( hostIP, yourData)

Step: 7 Parse the Data on sofserial read on the second arduino

Step 8: DONE!

**EDIT:**

Ok more infos on step 6. If you got your script running on your esp, you can call functions by sending the function name with parameters over your serial connection. So, this is some example code for your ardoino if you got the script from above:

```
SoftwareSerial wifi(3, 2); // RX, TX

//at some time in your programm
//Build up your string that will be send over serial
String i1 = "sendData(\"ipFromTheServer\", \"send.php?d=";
String i2 = i1+dataToSend;
String i3 = i2 +"\");";
wifi.println(i3);

```

This will call the sendData function on you esp. this will call the send.php on a Server... you can put a server up on an other esp and call it (dont have to be a php page)

More infos on step 7. the script on top will always print all incoming data. So you just have to read serial data on wifi:

```
if (wifi.available())
    Serial.write(wifi.read()); //this will print all inc data to your arduino console (serial) parse this data!

```

Info: I've build this on my own... dont know if this is best practice :)

---
Tags: arduino-uno, arduino-mega, wifi, communication, esp8266
---


# Question
Title: How to connect the INT pin of a MPU 6050?
I am using an Arduino Leonardo together with a GY-521 breakout board (like this one, schematic) for an MPU 6050.

I am currently trying to get the DMP Version of the examples from Mr Rowberg to work.

For all my tests, I use these connections:

* GY-521 -\> Leonardo
* VCC -\> 5V (3.3V has the same behaviour)
* SDA -\> SDA
* SCL -\> SCL
* GND -\> GND

The "raw" sketch works fine, I can read out the sensor data. For the DMP version I think I need to connect the INT pin to pin 3 on the leonardo, to allow the MPU6050 to trigger an interrupt.

But as soon as I connect INT to anything (pins 0 through 3), the sketches do not find the MPU6050 any more. (They report ""MPU6050 connection failed").

Is my wiring off, or is my chip defective, and even more important, how could I figure that out on my own in the future? =)

**Edit:** The example source code says

```
/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */

```

The example does nothing (that I can see) to configure this pin.

**Edit again:**

I've borrowed an oscilloscope. SDA and SCL sit on 3.3V during normal communication, and I can see packets being exchanged. As soon as I connect the INT pin to any input pin on my Leonardo, both SDA and SCL go to ground. This means nothing to me, but maybe to someone else.

# Answer
> 2 votes
## Possible problem: pin interference

> But as soon as I connect INT to anything (pins 0 through 3), the sketches do not find the MPU6050 any more. (They report ""MPU6050 connection failed").
>
> Is my wiring off, or is my chip defective, and even more important, how could I figure that out on my own in the future? =)

If I'm reading the Arduino Leonardo schematic correctly, Arduino D0 is Rx, Arduino D1 is Tx, Arduino D2 is the I2C\_SDA, and Arduino D3 is the I2C\_SCL.

You're already using the I2C\_SDA and I2C\_SCL as bidirectional I2C communication; connecting some other output pin (such as the MPU6050 INT pin) to either of those pins is going to disrupt that communication and then things won't work.

On most Arduinos, Serial.println() and Serial.read() and the reprogramming process use the Rx and Tx pins. Perhaps connecting the MPU6050 INT pin to either of those pins also causes some sort of problem leading to things that don't work. (Although the Arduino Leonardo actually uses its USB\_D- and USB\_D+ pins for both Serial.println() and reprogramming, so maybe it isn't really a problem for the Leonardo?). I would avoid using those pins for anything other than serial communication, even though I'm not at all sure that would actually cause a problem on the Arduino Leonardo.

> The example source code says ... this sketch depends on the MPU-6050's INT pin being connected to the Arduino's external interrupt #0 pin. ... The example does nothing (that I can see) to configure this pin.

I assume you're using https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/Examples/MPU6050\_DMP6/MPU6050\_DMP6.ino , right?

Interrupts are configured a little differently than I/O. (In particular, "volatile" is critical to getting interrupts working right).

The part that configures that interrupt is in the setup() function:

```
void setup() {
    // ...

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
    // ...
}

```

The "attachInterrupt(0, dmpDataReady, RISING)" line configures the interrupt vector table and the configuration bits so that when something drives Arduino pin D2 (i.e., external interrupt source 0) from a low to a high, no matter what the Arduino is in the middle of doing, the Arduino puts that on hold, executes the dmpDataReady() function, and then the Arduino resumes where it left off.

I don't see how that ever worked, since "external interrupt 0" comes from pin D2, which on the Arduino Leonardo is connected to I2C\_SDA, which we're using for I2C communication, so we can't use it for watching the gyro interrupt pin.

However, since the "attachInterrupt()" gets run long *after* the "MPU6050 connection failed" message gets printed out on your screen, a software bug in how the example code uses attachInterrupt() doesn't explain why you get that "fail" message printed on your screen.

## what to do about pin interference

I would try either using some other pin, or try getting it to work without hooking that pin to the Arduino at all.

## Using some other pin

I would try to assign a dedicated pin on the Arduino to the MPU6050 INT pin. Maybe D9 would work?

I'm guessing on the Arduino Leonardo, the interrupt should be set up something more like:

```
// warning: untested code.
#include <PinChangeInt.h>
#include <PinChangeIntConfig.h>

// connect MPU6050 interrupt to Arduino D9
#define MPU6050_INT D9

void setup(){
    // ...
    // pin change interrupt
    pinMode(MPU6050_INT, INPUT);
    PCintPort::attachInterrupt(MPU6050_INT, dmpDataReady, RISING);
    // ...
}

```

## Getting it to work without hooking INT to the Arduino

It's not at all clear that the Arduino really *needs* to be connected to the MPU6050 INT pin. It appears that another option is for the Arduino to occasionally use the I2C communication to read the status of the MPU6050, which includes the current state of that pin. That simplifies the hardware -- simply leave the MPU6050 INT pin unconnected.

# Answer
> 1 votes
## possible problem: level mismatch

I speculate that maybe some output on this Arduino is trying to push close to 5.0 V into your gyro, which is well outside the specifications of your gyro. You are lucky that anything worked at all.

According to page 12 of the MPU-6050 gyroscope datasheet, the gyroscope is designed to operate from a power supply of VDD = 2.375V to 3.46V.

You might think that is already taken care of by the 3.3V regulator on your breakout board.

However, a VDD of 3.3 also implies that the gyro expects all of its inputs to be in the range 0 V to 3.3 V, and the gyro will drive its outputs in the range 0 V to 3.3 V.

Page 358 of the ATmega32u4 datasheet says that the ATmega32u4 is designed work with any power supply in the range 2.7V to 5.5V.

There is a 3.3V regulator on the Arduino Leonardo and another one on the GY-521 breakout board. So the GY-521 breakout board *should* have its VCC connected to 5V and its GND connected to the Arduino GND so that regulator can power the gyro chip with 3.3.

Unfortunately for you, the Arduino Leonardo is designed to power the ATmega32u4 with VCC = 5.0 V.

## What to do about level mismatch

Perhaps it would work better if we connect things the way they were designed to be used.

If I were you, I would try to keep signal levels within specifications by any one of:

* Use a level converter, perhaps a I2C-compatible level converter for each data connection between the 3.3V I/O pins of the gyro and the 5.0V I/O pins of the Arduino Leonardo. (a) (b) (c) Or,
* Somehow tweak the Arduino Leonardo to connect 3.3 V to the VCC pin of the ATmega32u4. (Does this require cutting traces on the PCB?). Or,
* Use some other Arduino configured to run the processor at 3.3V (LilyPad Arduino USB; Arduino Fio; Arduino Zero; Arduino Due; Arduino TRE; some versions of Arduino Pro Mini; some versions of Arduino Pro; etc.) or easily connected to 3.3V (LilyPad Arduino SimpleSnap; LilyPad Arduino Simple; LilyPad Arduino; etc.)

# Answer
> 0 votes
Is it possible that the INT pin on the MPU 6050 in an input, not an output?

The symptoms you describe make it sound like you're locking the gyro chip into an interrupt state so it's not responding any more.

I wasn't able to figure out the use of the INT pin from a quick scan of the data sheet however. It would take more careful study.

Do you have your Arduino pin set up as an input or an output? And if it's an input, does it have a pull-up or pull-down resistor, either internal or external, set up?

# Answer
> 0 votes
To use external interrupt 4 (INT6), pin D7 on Leonardo board. we need change interrupt register as follows

```
   EICRB |= (1<<ISC60)|(1<<ISC61); // sets the interrupt type
   EIMSK |= (1<<INT6); // activates the interrupt

```

that write in WInterrupts.c

Follow this link

http://forum.arduino.cc/index.php?topic=124057.0

# Answer
> -1 votes
the interrupt pin in the attachInterrupt command should be kept to #4 which is pin D7 as stated here "http://arduino.cc/en/Reference/AttachInterrupt" since we can't use pins D0-D3 the only left out option is D7 but the problem still persists. Somebody please solve this !!

---
Tags: arduino-leonardo, mpu6050
---


# Question
Title: I have two 6 volts DC motors connected to L298N motor Driver. Do I need to use 12 Volts battery?
I have **two 6 volts DC motors** connected to **L298N motor Driver**. Do I need to use 12 Volts battery?

# Answer
> 1 votes
No, you need to use a (roughly) 6V battery. They are 6V motors, so they need a 6V battery.

However, you *do* need to sum the *currents* not the voltages. The battery must be able to provide *at least* the current required by *both* motors together.

---
Tags: arduino-uno, motor, battery
---


title: Efficiently using a serial inteface

text:
# Question
Title: Efficiently using a serial inteface
So at my school we are preapering for a competition. They asked me to do the technical side of it. And I accepted... I was thinking of using an arduino as a usb device for the buttons. I am going to use the serial port for this. But I can't think of a way to do it in the way I want. I want to recieve the button presses fair and well. But I also want to control the lights for the buttons, from my computer. I am using `Serial.printLn()` to send the serial data to the computer. But how can I send serial data to the arduino without delaying other things (What happens when someone presses a button while I am sending a command?)? Thanks in advance!

# Answer
> -1 votes
The nastiest part in what you describe is likely to be the debouncing on the button, rather than the serial communication.

One easy way out is to use some form of bounceless implementation, like an optical coupler. Another is to use HW debouncing, like the MAX 6816 family.

Then you can use a loop where you alternate between serial communications and checks for the status of the buttons.

Or you can rely on interrupts for the buttons, but it's more complex and might be overkill.

---
Tags: serial
---


title: Create a device to detect object state

text:
# Question
Title: Create a device to detect object state
Here is what I want to do or get it done (since I am not a embedded guy)...

* create a prototype with Arduino to detect open window/door of my room using camera(image processing/object state detection)?
* that prototype will take pictures of room door/window at certain interval and than using some algorithm to decide whether they are open or not and will sound an alarm if it is open.
* prototype should work in dark as well
* No false alarms
* Form factor should be small (the final product should not be bigger than smoke detectors that we have it in our room)

My questions are..

* Is it possible? :)
* What all things I need to create a prototype?
* Which camera should I use? Camera should be really small.
* Are algorithms available to detect it?

# Answer
Your answers :-)

* yes, it's possible and should not be too complex
* for a simple prototype, you do not need an embedded device, just a PC with a webcam
* a webcam with few megapixels should be enough
* try OpenCV

After your prototype is ready, you can use a small PC-like platform. Examples: Minnowboard, Edison, BeagleBone, RaspBerry PI 2, Arduino Yun, Galileo 2

A word of warning: depending on the expectations you have, you will have to pick more powerful models. Computer Vision is computationally intensive. The examples I gave are roughly sorted by performance and, unsurprisingly, cost. OpenCV is available for many architectures, but afaik, it is particularly optimized for x86, since it's mostly sponsored by Intel.

Disclosure: I work for Intel, so I am more informed on Intel products, but by no means I'm trying to do advertisement, this answer is simply given to the best of my knowledge.
> 1 votes

# Answer
I wonder if you haven't overspecified the device? Is there a reason that it must be photo-interpretive? Because if you only need to know whether a door or window is open, a couple of switches and some simple wired logic, or the very most basic of micro-controllers, if you choose to go that way, will be more than adequate, less expensive, more reliable in the long term (Ok, I know you won't be in a dorm room for long), less prone to false or missed alarms, totally unaffected by the ambient lighting or the lack of it, unobtrusive (no cameras - plural - in the middle of the room).

But I get that it might not be as much fun to make, if that is one of your top criteria!
> 1 votes

# Answer
I doubt you could make such a thing, especially with no embedded experience.

* You want to use a camera, but it should "work in the dark" - problem there. You would need to somehow "light" the room with (say) infra-red, but then technically it wouldn't be dark any more.
* It should be really small, but has to have the power of image capture and image processing. Maybe a dedicated board designed by people with a lot of experience, and using surface-mounted devices, could do that. I strongly doubt you could do it on an Arduino of any type.
* No false alarms? Without knowing your windows that might be hard to say, but considering windows are usually made of glass, detecting the difference between a closed window, and a wide-open one, might be marginal as you would still see the scene outside through the glass.
* As the sun rises and falls the image captured would change considerably, quite probably leading to false alarms. Imagine a sudden thunderstorm, where the next image is much darker than the previous one. The image comparison would register a "difference".
* Imagine a picture taken during a storm with lightning flashes corrupting the image.
* What is someone enters the room and walks in front of the window? That would register as a difference, but doesn't mean the window is open.

---

What seems much more practical to me would be variants of existing technologies, eg.

* Magnets and reed switches
* Shine a laser on the window and detect if it moves (the angle would probably change).
* Use distance-detection, such as pinging devices. An open window would change the distance (a bit).
* Use passive infra-red to detect the movement when the window opens.
* Vibration detection mounted on the window glass, or possibly the window frame.
* Temperature measurement to detect a difference in temperature as the window opens.

---

The camera sounds to me the least practical.
> 0 votes

# Answer
> Here is what I want to do or get it done (since I am not a embedded guy)...

Welcome to the world of embedded... things. I highly appreciate your interest in the embedded world, after all it's more interesting as just PC things :)

> * create a prototype with Arduino to detect open window/door of my room

You've come to the right place, Arduino (embedded stuff) is very good at input/output. And that seems like a fun project!

> using camera(image processing/object state detection)?

Wait, where did this come from? Humans are good at observing, their main sense would be vision (I guess?) to do so. Microcontrollers are somewhat better at logic signals. They are good at taking sensor signals and turning them into whatever you like. *There is a possibility you'd just like to do something with image processing/detection. If so, please mention that :)*

> * that prototype will take pictures of room door/window at certain interval and than using some algorithm to decide whether they are open or not and will sound an alarm if it is open.

Arduino can read out a simple "Door sensor" and check if the door is, or is not closed. This will both shrink your project and make it easier. Arduino can sound an alarm. You can even add a keypad (for a disable code).

> * prototype should work in dark as well

The drawback of human vision. Is that it does not work so well in the dark. Sensor's based on the touch of the door or a magnetic contact on the door are not affected by darkness.

> * No false alarms

If your sensor won't fail, the alarm won't go off by accident :)

> * Form factor should be small (the final product should not be bigger than smoke detectors that we have it in our room)

Use an arduino nano or micro.

> My questions are.. \- Is it possible? :)

Yup! You can check for existing projects on the web. You can put in your own implementation though.

> * What all things I need to create a prototype?

Whatever you need is what you will need. An sensor as input, an arduino to process it and an "alarm". There are a trillion configurations for this, you can choose to just go by one or check what fits your needs best.

> * Which camera should I use? Camera should be really small.

Unless you really want to get going with camera detection/object tracking, you shouldn't use one. (Especially with arduino it can be quite frustrating.) You should use a PC or raspberry Pi or Android phone.

Or use arduino with said sensor.

* Are algorithms available to detect it?

Yes. For this, it's again application specific. You should check out some resources, check what others use and determine what would work best for you. Try it out and if it won't work you can ask it :) (probably on normal stack-overflow since it's not really arduino related, maybe robotics stackexchange).
> 0 votes

---
Tags: arduino-uno, programming, sensors, hardware, system-design
---


# Question
Title: Which sensor is best for obstacle detecting with retroreflector?
Distance is about 3m. IR or visible light - does not matter.

It is possible that object/obstacle can be shiny, so for correct detection necessary large amount of reflected light.

Maybe for this task better to use specific retroreflector?

**UPDATE:**

there will be two sensors with distance about 3-4 cm between. Object must cross 1st sensor's reflector but do not cross the 2nd one.

The scheme of this sensor should be this:

But the use will be this:

# Answer
I think the question is worded to get a specific answer; I do not know if this is the answer you want. I'll give you that answer first:

I'd say an infrared LED, and an infrared detector.

Strobe the LED, then measure the difference between when it's (known to be) on, and when it's (known to be) off, to compensate for ambient light.

However, if I was doing this, I'd consider an ultrasound sensor - no retroreflector needed; instead you get the distance to the (obstacle or reflector).
> 0 votes

# Answer
I think you're better off with a set-up like this.

*A shiny object might bounce the laser as if it were a mirror. But we wan't to know if the laser was interrupted.*

So. If we place the sensor on the other side, we can accurately say if the light reaches the sensor. Thus if there is an object between (shiny or not).

*But what if another light-source shines into my sensor? It'll think that there is no object.*

We can encapsulate the sensor, so that only light from the direction of the laser can shine into it. And we can filter out other light "colors". Also the strength of the laser should be bigger as any other ambien light (not too strong also). You could even choose to make the laser pulse a specific pattern and let the sensor check if it's right.
> 0 votes

---
Tags: sensors, hardware, system-design
---


title: Arduino number detection

text:
# Question
Title: Arduino number detection
I am planning for a project but i am stuck with a task and hope you could help me. My work is to note down a number which is actually a set of readings displayed on a meter and store it on a arduino. My problem is that i need a detection technique so that i could record the number or extract the number from a image or video if u suggest to use a camera or recorder or purely can be a sensor. Thank you guys, waiting for you.

# Answer
"Number detection" sounds like you're trying to interpret a 7-segment digital display - is that correct? One way would be to place 7 photo-detectors (times the number of digits), one per segment, on or at the face of the display. Sample the photo-detectors and create a 7-bit code representing the lit segments, into a byte. You could start with a simple lookup table that translates from code to the digit it represents. You might need to get clever about interpreting codes that shouldn't appear, but do, due, perhaps to light leakage, ambient lighting, or noise. The "lit" segments may only be lit for a fraction of second at a time, and only one at a time, if the display is multiplexed, so your sampling algorithm will have to take that into account. Must the display remain visible? You might need optics or optical fibers to view the segments without obstructing them.
> 3 votes

---
Tags: sensors
---


title: Arduino + TMP36 + DC Motor

text:
# Question
Title: Arduino + TMP36 + DC Motor
I made this circuit:

The part with the DC motor is from this tutorial: https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v32/experiment-12-driving-a-motor ( I only use another resistor, with 220 OHM)

As you can see, I also have a TMP36 sensor attached. What I would like to do is this: When the temperature is 25 degrees or more, the motor should turn on.

I have this code:

```
//TMP36 Pin Variables
int sensorPin = 0; //the analog pin the TMP36's Vout (sense) pin is connected to
                        //the resolution is 10 mV / degree centigrade with a
                        //500 mV offset to allow for negative temperatures

/*
 * setup() - this function runs once when you turn your Arduino on
 * We initialize the serial connection with the computer
 */
void setup()
{
  Serial.begin(9600);  //Start the serial connection with the computer
                       //to view the result open the serial monitor
}

void loop()                     // run over and over again
{
 //getting the voltage reading from the temperature sensor
 int reading = analogRead(sensorPin);

 // converting that reading to voltage, for 3.3v arduino use 3.3
 float voltage = reading * 5.0;
 voltage /= 1024.0;

 // print out the voltage
 Serial.print(voltage); Serial.println(" volts");

 // now print out the temperature
 float temperatureC = (voltage - 0.5) * 100 ;  //converting from 10 mv per degree wit 500 mV offset
                                               //to degrees ((voltage - 500mV) times 100)
 Serial.print(temperatureC); Serial.println(" degrees C");

 if(temperatureC >= 25){
  analogWrite(9, 250);
 }

 delay(1000);                                     //waiting a second
}

```

But I get this result:

```
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.75 volts
25.20 degrees C <------
0.87 volts
36.91 degrees C
0.66 volts
16.41 degrees C
0.78 volts
27.64 degrees C
0.77 volts
26.66 degrees C
0.84 volts
34.47 degrees C

```

The point where the sensor measures \> 25 degrees, the motor turns on but the circuit gets "poluted" and the temp sensor starts to send all kinds of strange values.

How do I solve this? Thanks in advance!

---

I got it to work in with the following: http:// i.stack.imgur.com/4GFPH.png

# Answer
> 1 votes
Motors tend to use more current than the arduino can supply, try hooking up the motor to a different power supply than the arduino 5V. What most likely is happening, is that when the motor turns on, it alters the value of the voltage, which the temperature sensor is using to tell the arduino what the temperature is. You need to have the temperature sensor hooked up to the arduino to have the reference at the right voltage, so the motor should be on a different power supply. That should fix things.

---
Tags: motor, temperature-sensor
---


title: Pro Micro Voltage regulator burned

text:
# Question
Title: Pro Micro Voltage regulator burned
I'm using Arduino Pro Micro (5v version) in one of my project for my car. The car's 12V +ve connected to RAW input of ProMicro and everything seems to work perfectly until I crank the ignition of my car. Here's what actually happened, my circuit works perfectly fine when car's ignition is in ON state. However, as soon as I started my car the voltage dropped from 12v to between 9-10volt and the LG33 (SMD voltage regulator) burned out. Now, I want a good solution as what should I do now? I have already LM2596 DC 3A Step-Down regulator. So should I use that to step-down 12v to 5v OR is there anything else I can do which might be a better solution?

# Answer
> 3 votes
What happened was the ignition caused massive spikes on the 12V power. You require an automotive grade regulator that can cope with spikes in excess of around 70V or more.

Your best bet is probably a car USB charger adapter since they are cheap and easy to get hold of.

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


# Question
Title: Arduino Mega 2560 multiple slave via SPI
I'm new to Arduino and microcontroller . I want to connect my Arduino Mega to three slaves which Arduino Unos. I know that these slaves will share MISO, MOSI, and SCK lines. However, SS is unique to each slave.

For single slave, the SS is pin 53. So, for three slaves, which other two pins can I use as SS?

Thank you for your help.

# Answer
> 2 votes
Any you like. There's nothing magic about them, as long as you have the main SS pin as an output to ensure the SPI port is in master mode.

# Answer
> 2 votes
You can use any pin for the Slave Select. The SS pin on the Arduino is only used as SS when the arduino is an SPI slave, not (like in your case) when it's the master. The only thing you have to take care of is to not use the SS pin as an Input.

Just make sure the library you are using allows you to specify your own SS output pin.

---
Tags: arduino-mega, spi
---


# Question
Title: How to write data in RAM memory using Arduino Uno or Arduino Due?
I know that it is possible to write data in ROM(Read Only Memory).
But what about if I want to write data in RAM(Random Access Memory)?
Can I do it using "Arduino Uno R3"?
RAM is normally associated with volatile types of memory.

There are several examples about writing data in EEPROM as in a (Read Only Memory) which may have 8 pins.
In order to store values read from analog input 0 into the EEPROM we need to use the "EEPROM.write()" function.
These values will stay in the EEPROM when the board is turned off and may be retrieved later by another sketch.
ROM is a Non-volatile type memory.
SD card is also Non-volatile type of memory.
We know that there are few SD card shields for "Arduino Uno" and it is possible create your own shields.

But what about volatile types of memory?
what about if I want to write data in RAM like a "DDR SDRAM" or in a DDR3 memory which may have 240 pins instead of 8 pins?
So my question is is it possible to write data in "DDR SDRAM" using "Arduiono Uno R3"?
How? Where should I connect those 240 pins?

# Answer
DRAM of any kind requires a memory controller which is not present in any AVR device. Larger AVR devices such as the ATmega64A and ATmega128A do have an external memory bus that can be used for SRAM and MMIO.
> 3 votes

# Answer
Your program is already using the on board RAM:

```
int a = 5; // This is RAM. Where did you think it goes? (This might go to a CPU Reg)
int a[5000]; // This is RAM

```

**DDR3 RAMs** require (typically) `1633 MHz` clocks, and store gigabytes of data, not something you use with Arduino, which has a `16 MHz` CPU.

If you need **EXTRA** (emphasis on extra) `RAM`, my first advice would be to refactor your project, and reduce processing on *Arduino*.

However, if must have more `RAM`, get `SRAM`. In most cases, `DDR3` trade high maintenance for cost. Have a look here.
> 3 votes

# Answer
The easiest way to read and write DDR SRAM would be to install it in a PC and write a serial server that allowed the Arduino to access the data by requesting it over the serial port.

Now although that is possible to do, the performance probably won't be great. So it might be worth looking into memory that interfaces over SPI or IIC, there are several ICs that you could use. Most of them would have libraries already available and you would be looking at about £1 per 256kbits.

But like it has been said above if you are looking at storing multi-GBs of data then you probably want SD cards. If the write speed is going to be a problem then look at multiplexing the data over many SD cards.
> 1 votes

---
Tags: arduino-uno, shields, memory-usage, eeprom, sram
---


# Question
Title: Timer interrupt won't work if the ISR is not set
I am using an Arduino Mega 2560.

I have a code in a c file, that looks like this:

```
    #include <avr/io.h>             /* for DDRB, PORTB, etc. */
#include <util/delay.h>         /* for _delay_ms () */
#include <arduino.h>

int main(void){
  DDRB    |= ((1 << DDB7)); // Define pin 13 as output

  noInterrupts();

//set timer1 interrupt at 1Hz
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  interrupts();

  while(1){
        asm("nop");
  }
return 0;
}

  ISR(TIMER1_COMPA_vect)          // timer compare interrupt service routine
{
  PORTB ^= ((1 <<  PB7));   // toggle LED pin
  PINB |= _BV(7);
  PINB = PINB | _BV(7);
}

```

Which is called from an ino file, like this:

```
    extern "C"
 {
 void foo ();
 }

void setup ()
  {
  foo ();
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

However, if I set up another timer interrupt (ex Timer Interrupt 0 or 2, the blink will stop happening, for some reason...

For example:

```
//set timer0 interrupt at 2kHz
  TCCR0A = 0;// set entire TCCR2A register to 0
  TCCR0B = 0;// same for TCCR2B
  TCNT0  = 0;//initialize counter value to 0
  // set compare match register for 2khz increments
  OCR0A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);

```

Now, the strangest part happens that if all the three (or just the same two) timer interrupts are set, and with everything defined in the INO file, it works fine...

```
//this code will enable all three arduino timer interrupts.
//timer0 will interrupt at 2kHz
//timer1 will interrupt at 1Hz
//timer2 will interrupt at 8kHz

//storage variables
boolean toggle0 = 0;
boolean toggle1 = 0;
boolean toggle2 = 0;

void setup(){

  //set pins as outputs
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(13, OUTPUT);

cli();//stop interrupts

//set timer0 interrupt at 2kHz
  TCCR0A = 0;// set entire TCCR2A register to 0
  TCCR0B = 0;// same for TCCR2B
  TCNT0  = 0;//initialize counter value to 0
  // set compare match register for 2khz increments
  OCR0A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);

//set timer1 interrupt at 1Hz
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

//set timer2 interrupt at 8kHz
  TCCR2A = 0;// set entire TCCR2A register to 0
  TCCR2B = 0;// same for TCCR2B
  TCNT2  = 0;//initialize counter value to 0
  // set compare match register for 8khz increments
  OCR2A = 249;// = (16*10^6) / (8000*8) - 1 (must be <256)
  // turn on CTC mode
  TCCR2A |= (1 << WGM21);
  // Set CS21 bit for 8 prescaler
  TCCR2B |= (1 << CS21);
  // enable timer compare interrupt
  TIMSK2 |= (1 << OCIE2A);

sei();//allow interrupts

}//end setup

ISR(TIMER0_COMPA_vect){//timer0 interrupt 2kHz toggles pin 8
//generates pulse wave of frequency 2kHz/2 = 1kHz (takes two cycles for full wave- toggle high then toggle low)
  if (toggle0){
    digitalWrite(8,HIGH);
    toggle0 = 0;
  }
  else{
    digitalWrite(8,LOW);
    toggle0 = 1;
  }
}

ISR(TIMER1_COMPA_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
//generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles for full wave- toggle high then toggle low)
  if (toggle1){
    digitalWrite(13,HIGH);
    toggle1 = 0;
  }
  else{
    digitalWrite(13,LOW);
    toggle1 = 1;
  }
}

ISR(TIMER2_COMPA_vect){//timer1 interrupt 8kHz toggles pin 9
//generates pulse wave of frequency 8kHz/2 = 4kHz (takes two cycles for full wave- toggle high then toggle low)
  if (toggle2){
    digitalWrite(9,HIGH);
    toggle2 = 0;
  }
  else{
    digitalWrite(9,LOW);
    toggle2 = 1;
  }
}

void loop(){
  //do other things here
}

```

Is anybody able to explain why it works in the first case, doesn't work in the second, and in the third, it works as well?

# Answer
> 1 votes
I found out that it's not enough to just define the interrupts, there must also be an ISR method with the compare vector...

```
  ISR(TIMER0_COMPA_vect)          // timer compare interrupt service routine
{
  PORTB ^= ((1 <<  PB6));   // toggle LED pin
  PINB |= _BV(6);
  PINB = PINB | _BV(6);
}

```

There was no error at compile, though.

---
Tags: programming, arduino-mega, c, interrupt
---


# Question
Title: Circuit doesn't work when multimeter/current meter is attached
I'm working on a battery-powered data logger, using a bare Atmega 328. I'm using sleep between sensor readings, via the Narcoleptic library. Everything seems to work fine, until I connect my multimeter to check on the current.

The multimeter uses manual range-setting (i.e., not autoranging). If I set the multimeter to the 0-20 mA range, I can see that my idle current is about 0.250 mA, but the upper value is off-scale. If I try to get a reading on the 0-200 mA range, the circuit misbehaves, never goes into sleep, and doesn't record any data. The current stays constant somewhere around 14-20mA.

Do I need to do something special to accurately measure current in the range of 0.25-40+mA? Or do I need a different kind/quality of multimeter?

My multimeter is a $15 digital unit from Circuit Test, model DMR-1100A.

# Answer
> 6 votes
Multimeters have something called a "burden voltage". See this PDF: uCurrent - A professional precision current ... - EEVblog.

Also see Dave Jones' video: µCurrent

Meters measure current by dropping voltage over an internal resistor, and measuring the drop. By definition therefore, there is a voltage drop, which is the "burden voltage".

> the circuit misbehaves, never goes into sleep, and doesn't record any data

If you put a voltmeter on the processor side of the ammeter you will probably find that the voltage going into your processor is somewhat less than you think. That would account for the misbehaving.

One possible approach is to crank up the voltage from your power source, checking the voltmeter to see that it reaches the expected voltage on the **processor** side of the ammeter, however in a circuit which might turn on and off (ie. sleep) this voltage might jump around (depending on the current) so this should be done with caution (to not exceed the maximum processor voltage).

---

> Or do I need a different kind/quality of multimeter?

A higher quality meter may well help - watch that video and look at the PDF to see what I am talking about. My meters (which cost more than $15) don't have this problem to the same extent.

# Answer
> 1 votes
If your tester has autorange function, you have to disable it, as it can interfere with normal operations by changing the internal shunt resistor.

Did you configure the meter as current meter, DC, connected in series between the power supply/battery and the rest of the circuit?

The tester might give a poor reading at low current values but it shouldn't interfere(much) with the circuit itself.

---
Tags: power, current
---