# Question
Title: Lowering cost of using NRF24L01 radio module for communication between several Arduinos
I have several Arduino Uno's if I am using several NRF24L01 modules to transmit a simple pulse (1 bit of information which can be high or low) between them-from one Arduino to the rest of them. Then I was considering, because the information is one bit of information only can I replace the other receiving NRF24L01 module's with something cheaper (and probably simpler) ?-may something based on like a simple tank LC circuit?-or it maybe another simple circuit instead of the LC one. The intuition for asking the question is because only 1 bit of information (which maybe represented by a string of 1's or another known string X if it makes the decoding simpler) is transmitted then the receiving circuit maybe simplified somehow -rather than use something like the full circuitry of a NRF24L01 module. Elaborating further on a possible scheme for decoding X may be done by just counting the "marks ratio"-as done "in a marks and spaces style scheme"-e.g. if there are known ratio of 1's, than compared to the usual ratio, then we can consider that to be a high signal received -the number of 1s sent is such that the binary information from the NRF24L01 protocol, that sends X, would not significantly affect the ratio of the 1s. however I don't know how accurate my intuition is here.

So in a nutshell, I want to know if there is a simple circuit that does what I want - an answer may include a custom Arduino sketch suggestion for the transmitter and/or receiver.

# Answer
> 3 votes
To receive a signal from an nRF24L01 you either need another nRF24L01 or to reimplement the nRF24L01 in discrete components. That's a big, complex circuit requiring precision components and PCB layout. At 2.4GHz, with GFSK modulation, you need amazing skills to create something that would work reliably - and the cost would be astronomical compared to the cost of an nRF24L01.

Your thought that you are "only sending 1 bit of data" is completely wrong. Yes, you may be providing only 1 bit of data to the library that controls your nRF24L01 - however the nRF24L01 then encapsulates that single bit into a fixed length packet including source and destination addresses, checksums, and even implements a reliable ACK/NACK system for packet retransmission. None of that can be thought of as a "single bit" once it gets out onto the airwaves - so the system that you came up with would have to be able to interpret and handle that entire packet and provide any requested ACK/NACK signals back to the transmitter.

If you want to receive with a simpler system then you need to also transmit with a simpler system. The simplest system is probably the 433MHz PAM systems you find on eBay. You pull the input pin HIGH on the transmitter and the output pin on the receiver goes HIGH. You pull the transmitter pin LOW and the receiver pin goes LOW. (Basically you turn the carrier on and off at one end, and the other end tells you if the carrier is on or off - Pulse Amplitude Modulation \[also known as On Off Keying - OOK\]).

Coupling that with UART signals it's possible to send actual data, but if all you need is HIGH/LOW signalling then you can drive it direct with any GPIO pin.

They are incredibly crude, and would never pass any kind of emissions testing, but they get the job done at a very low cost.

While it may be possible to create a crude 2.4GHz PAM transmitter and receiver, owing to the broadband spectrum harmonics you would have unless you managed to produce an absolutely pure sine-wave with zero harmonic distortion, the interference it would cause to other devices nearby (such as your WiFi connection) would cause untold problems. No doubt your neighbours would have something to say about that - and maybe FCC / OFCOM / whoever.

# Answer
> 0 votes
> I have several Arduino Uno's if I am using several NRF24L01 modules to transmit a simple pulse (1 bit of information which can be high or low) between them-from one Arduino to the rest of them.

Let us assume that the broadcast has to reach all. None of the listeners are allowed to drop messages. How would this be achieved? Each listener would have to acknowledge the message.

Anyway reasoning about the application requirements and communication protocol may help determine if a "cheaper" solution is possible.

IMHO using NRF24L01+ is a cheap solution in this scenario.

Cheers!

---
Tags: arduino-uno
---


title: Basic Question - ESP8266 Board Pins

text:
# Question
Title: Basic Question - ESP8266 Board Pins
I have an embarrassingly simple question.

My experience to date has been limited to Arduino Uno + Wifi101. I bought an ESP8266 and noticed that the GPIO pins don't match the printed numbers on the board.

When programming and defining pins, does `#define <pin name> 16` call the pin with the printed designation D0?

I can't find a straight answer to this anywhere.

Image credit: http://crufti.com/content/images/2015/11/nodemcudevkit\_v1-0\_io.jpg

# Answer
> 2 votes
Looks like you're using https://github.com/esp8266/Arduino, in which case - yes, 16 is GPIO16, which on the NodeMCU board you have is labeled D0.
I am not entirely sure why the NodeMCU guys had to do this "pin remapping", but the end result is inconvenience when using the module with anything but their Lua.

# Answer
> 2 votes
It looks like they are using a similar system to the Arduino pin mappings, for example:

(Image credit: https://www.arduino.cc/en/Hacking/PinMapping168)

There, for example, pin 2 on the chip, is D0 (digital pin 0) on the board.

Their board will use their own mappings, but the concept is the same.

> does #define 16 call the pin with the printed designation D0?

That doesn't "call" anything. It would depend on the code. If the code in question addresses the actual chip pins, then it is chip pin 16. If it goes through a library and the library maps the chip pins to the board pins, that it will refer to board pin 16. I notice BTW that the board doesn't have a pin 16.

# Answer
> 0 votes
Well based on my experience with NodeMcu and Arduino, in Arduino you use the GPIO by reffering its pin number (like 0-13), whereas in NodeMcu you will have to use D0-D8.

It's better to use D0 to use GPIO 16.

---
Tags: pins, esp8266
---


title: Comma between two values in a macro

text:
# Question
Title: Comma between two values in a macro
I am working on a project involving an Aduino and screen.

As i was going through the u8glib (Arduino Monochrome Graphics Library for LCDs and OLEDs), something caught my attention:

```
#define U8G_ESC_DLY(x) 255, ((x) & 0x7f)
#define U8G_ESC_CS(x) 255, (0xd0 | ((x)&0x0f))

```

How can i interpret this macro for a given x value ?

# Answer
> How can i interpret this macro for a given x value ?

As normal. First expand the macro, and *then* worry about what the comma means in context. In an expression the result is the expression on the right of the comma. In a function call it stands in for two arguments. Just look at where it's used and that's what it will mean.
> 3 votes

---
Tags: c, u8glib
---


title: Cannot set Pins to LOW

text:
# Question
Title: Cannot set Pins to LOW
I am controlling 2 motors from my Arduino Pro Mini and L293D motor driver module. Problem is, I have to set a pin high and after 1 second set it to LOW. But that doesn't happen... The pin just stays HIGH and is never LOW.

Here's my Code -

```
    int IN2Left = 10;
    int E1 = 12;
    int E2 = 7;
    int IN3RevRight = 6;
    int trigPin1 = A0;
    int echoPin1 = A1;
    int distance1 = 0;
    int IN4Right = 5;
    int IN1RevLeft = 11;

    void setup()
    {
      pinMode(IN2Left, OUTPUT);
      pinMode(E1, OUTPUT);
      pinMode(E2, OUTPUT);
      pinMode(IN3RevRight, OUTPUT);
      pinMode(IN4Right, OUTPUT);
      pinMode(IN1RevLeft, OUTPUT);
      pinMode(trigPin1, OUTPUT);
      pinMode(echoPin1, INPUT);
      pinMode(13, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
  digitalWrite(13, HIGH);
  digitalWrite(E1, HIGH);
  digitalWrite(E2, HIGH);
  digitalWrite(IN2Left, HIGH);
  digitalWrite(IN4Right, HIGH);
  delay(3000);
  digitalWrite(IN4Right, LOW);
  digitalWrite(IN3RevRight,HIGH);
  delay(500);
  digitalWrite(IN3RevRight, LOW);
  digitalWrite(IN4Right, HIGH);
  delay(1500);
  digitalWrite(IN2Left, LOW);
  digitalWrite(IN1RevLeft, HIGH);
  delay(500);
  digitalWrite(IN1RevLeft, LOW);
  digitalWrite(IN2Left, HIGH);
  delay(100000);
    }

```

The `IN2Left` Pin never goes LOW... I am assuming a faulty Arduino but my Arduino seems to be working just fine as it runs other stuff (tested blink and reading an Ultrasonic sensor) just fine.

My deadline is 2 hours from now...

EDIT: Here's the complete void loop function... Note the two pins on top which go HIGH? They Never go LOW again in the entire code.

# Answer
> 1 votes
Your code sets it high, delays for 1000ms, sets it low, and then... turns around and sets it high almost immediately after. Try delaying in between.

# Answer
> 1 votes
```
  digitalWrite(IN2Left, HIGH);
  delay(1000);
  digitalWrite(IN2Left, LOW);

```

It would go LOW for a few microseconds. Maybe put a delay after going LOW?

---
Tags: programming, c++, motor, arduino-pro-mini
---


# Question
Title: Cannot assign COM port to HC-05 bluetooth device
I can't set a COM port to my paired BT module. For better understanding I recorded a YouTube video to make sure I show everything.

Hardware:

* Arduino Nano knock-off by RobotDyn (atmega168)
* Bluetooth module HC-05 (zs-040) which looks like this
* Windows 10 Home 64 bit on tablet

I have wired them up like this .

However, before that, I tried to wire it up without the resistors (so I hope I didn't damage anything).

Here is my very simple code which should just echo back what it get.

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

void loop() {
  if(Serial.available())
  {
    Serial.println(Serial.parseInt());
  }
  delay(100);
}

```

# Answer
Based on my experience, there is nothing wrong (yet) on the Arduino. You can check this or this. Unlike previous windows version, Win 10 tend to "ignore" bluetooth connection, so you have to assign the COM port manually.
> 1 votes

---
Tags: serial, bluetooth, arduino-nano, communication, hc-05
---


# Question
Title: Sim800L's library can not compile on Arduino Due
Sim800L's library can not compile on Arduino Due. Is there any way to create a library for Arduino Due?

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

Sim800l Sim800l;
char* text;
char* number;
bool error;

void setup(){
    Sim800l.begin();
    text = "Testing Sms";
    number = "2926451386";
    error = Sim800l.sendSms(number,text);
    // OR
    //Sim800l.sendSms("+540111111111","the text go here")
}

void loop(){
    //do nothing
}

```

I guess that the problem is the software serial library, too. However, I don't know how to replace this library for Arduino Due.

Any help appreciated.

# Answer
First we must delete the SoftwareSerial and SIM800L libraries, then define Sim800l and assign it to Serial 3 on pins 14 and 15. In `setup`, call `Sim800l.begin()` and the rest of the code is unchanged.

```
#define SIM800l Serial3

void setup () {
  Serial.begin (9600);
  SIM800l.begin (9600);
  while(!Serial);
  SIM800l.write ("AT+CMGF=1\r\n");
  delay (1000);
  SIM800l.write("AT+CMGS=\"5432154552"\"\r\n");
  delay(1000);
  Serial.println("send SMS");
  SIM800l.write ("test send SMS");
  delay (1000);
  SIM800l.write ((char)26);
  delay(1000);
}

void loop (){}

```
> 1 votes

---
Tags: arduino-due, shields, gsm, code-optimization
---


title: Shrink array to save memory

text:
# Question
Title: Shrink array to save memory
In my project I need three arrays to store data inside.

I define a maximal number of elements as a macro variable. However, at a certain point in the setup function, the program could determine, that the arrays would actually store a smaller number of elements. In other words, it is possible (and even likely) that there is more memory reserved for the arrays than actually necessary.

As I think that memory might be a critical factor on a micro controller like the Arduino, I would like to set the excess memory free.

Is there a way to dynamically resize **and shrink** the arrays at runtime?

Something like this (pseudocode)

```
#define maxSize 50
int theArray[maxSize];

int actualSize = getActualArraySize();
// sets actualSize to a value <= 50, let's assume actualSize = 20
shrinkArray(theArray, actualSize);
// shrinkArray doesn't exist :) I need something like that.

```

# Answer
> 1 votes
This is a common question when designing software. The simple answer (rule of thumb) is **statically allocate the maximum size of the array**. In this case the maximum size of the arrays. This simple rule will keep you out of trouble and make testing etc much simpler.

Using dynamic allocation (adjusting array size etc) especially for small scale embedded systems such as the Arduino opens a "can of worms" with possible memory (heap) fragmentation and hidden concurrency and performance issues.

If the required maximum size of the array is 32 elements the application has to allow that and there is no memory to save. Statically allocating will make the sketch simpler and easier to test.

Cheers!

---
Tags: c++, memory-usage, array
---


# Question
Title: Problems reading I2C sensor when using a Xbee module
I'm developing a project where I can control a RC boat with GPS and a magnetometer. How ever, I was developing everything connected to my computer and worked pretty well. When I was going to make some test with a battery and a couple of Xbee's (PC and "Arduino"), the magnetometer signal was not updating. So, I read the first value and continued to transmit the same value (thing that never happened on computer). Has someone had the same issue before? How can I solve this? Oh, one thing. The GPS and magnetometer comes in the same module, and I'm having no problems with GPS coordinates. And even if I power de MCU with my computer and transmitting with the Xbee's it doesn't work either. Seems like a communication problem.

Hardware used:

GPS Module + Compass

ATmega1284P

**UPDATE:**

I want to share also the code I'm using for the I2C reading.

```
#include <Wire.h> //I2C Arduino Library
#define address 0x1E //0011110b, I2C 7bit address of HMC5883

void setup(){
  //Initialize Serial and I2C communications
  Serial.begin(9600);
  Wire.begin();

  //Put the HMC5883 IC into the correct operating mode
  Wire.beginTransmission(address); //open communication with HMC5883
  Wire.send(0x02); //select mode register
  Wire.send(0x00); //continuous measurement mode
  Wire.endTransmission();
}

 void loop(){

  int x,y,z; //triple axis data

  //Tell the HMC5883L where to begin reading data
  Wire.beginTransmission(address);
  Wire.send(0x03); //select register 3, X MSB register
  Wire.endTransmission();

 //Read data from each axis, 2 registers per axis
  Wire.requestFrom(address, 6);
  if(6<=Wire.available()){
    x = Wire.receive()<<8; //X msb
    x |= Wire.receive(); //X lsb
    z = Wire.receive()<<8; //Z msb
    z |= Wire.receive(); //Z lsb
    y = Wire.receive()<<8; //Y msb
    y |= Wire.receive(); //Y lsb
  }

  //Print out values of each axis
  Serial.print("x: ");
  Serial.print(x);
  Serial.print("  y: ");
  Serial.print(y);
  Serial.print("  z: ");
  Serial.println(z);

}

```

# Answer
> 1 votes
I have solved the problem by adding a delay just before I select the continuous measurement mode.

```
void setup(){
  //Initialize Serial and I2C communications
  Serial.begin(9600);
  Wire.begin();

  //Put the HMC5883 IC into the correct operating mode
  Wire.beginTransmission(address); //open communication with HMC5883
  Wire.send(0x02); //select mode register
  Wire.send(0x00); //continuous measurement mode
  delay(100);
  Wire.endTransmission();
}

```

# Answer
> 0 votes
There are 2 possible problems:

Lack of power or libraries not supporting each other.

1 - Try powering the circuit with some USB 5V. Make sure that your other modules can support 5V. Also check your clock speed. High clock speeds with low voltages might cause your ATmega to function incorrectly.

2 - Some libraries for certain module / breakout uses software I2C which pretty much emulate I2C. They might not be compatible with another module that needs the `wire` library to function proprely. To debug it, test out 1 module at the time with the battery.

---
Tags: serial, arduino-ide, i2c, gps, magnetometer
---


title: MPU6050 hanging/freezing

text:
# Question
Title: MPU6050 hanging/freezing
I am really short of interrupt pins on my Arduino because I have a project that already uses a lot of Arduino pins and to read DMP data from MPU6050 you always have to use an interrupt pin. I searched A LOT in the internet and many people says it's impossible to retrieve DMP data without interrupt pin. Some people also said the only way to do that would be if I could reverse engineer the MPU6050 code (which I don't know how to do).

But today, playing with MPU6050 I could finally get all of its DMP data without the interrupt pin, you just have to connect 4 pins (VCC, GND, SCL and SDA). Upload the code below to your Arduino and see that it works!

```
#include "MPU6050_6Axis_MotionApps20.h"
MPU6050 mpu;
uint16_t packetSize;
uint16_t fifoCount;
uint8_t fifoBuffer[64];
Quaternion q;
VectorFloat gravity;
float ypr[3];

void setup() {
  Wire.begin();
  TWBR = 24;
  mpu.initialize();
  mpu.dmpInitialize();
  mpu.setXAccelOffset(-1343);
  mpu.setYAccelOffset(-1155);
  mpu.setZAccelOffset(1033);
  mpu.setXGyroOffset(19);
  mpu.setYGyroOffset(-27);
  mpu.setZGyroOffset(16);
  mpu.setDMPEnabled(true);
  packetSize = mpu.dmpGetFIFOPacketSize();
  fifoCount = mpu.getFIFOCount();

  Serial.begin(115200);
}

void loop() {
  while (fifoCount < packetSize) {
    fifoCount = mpu.getFIFOCount();
  }

  if (fifoCount == 1024) {
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));
  }
  else {
    if (fifoCount % packetSize != 0) {
      mpu.resetFIFO();
    }
    else {
      while (fifoCount >= packetSize) {
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        fifoCount -= packetSize;
      }

      mpu.dmpGetQuaternion(&q, fifoBuffer);
      mpu.dmpGetGravity(&gravity, &q);
      mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

      Serial.print("ypr\t");
      Serial.print(ypr[0] * 180 / PI);
      Serial.print("\t");
      Serial.print(ypr[1] * 180 / PI);
      Serial.print("\t");
      Serial.print(ypr[2] * 180 / PI);
      Serial.println();
    }
  }
}

```

There is only one problem: Intermittently the Arduino hangs in the `getFIFOBytes` function for no reason. I am pretty sure it's a bug because when you call too many times `getFIFOBytes` for some reason the Arduino freezes.

# Answer
I added a mpu.resetfifo after de mpu.dmpGet.... lines. Since then 2 different systems work for at least 5 hours and with the original interupt pin attached
> 1 votes

---
Tags: mpu6050
---


# Question
Title: Will a transistor always reduce the voltage?
I have an NPN transistor that's connected over a 12V adapter. I have tried using a potentiometer to change the resistance of the incomming current. Even if i take the resistance down to 0, I end up with at most 11 Volts when measuring over the magnet.

I have measure the energy without the transistor, in that case it's 12V. Is this expected behaviour of a transistor or is something wrong?

# Answer
Yes, it is, as both VCE(sat) and the "Collector-Emitter Saturation Voltage vs Collector Current" chart in the datasheet tells you.
> 0 votes

---
Tags: power, transistor
---


# Question
Title: What pin is the external interrupt #0 for an arduino micro?
I'm putting an MPU6050 on an arduino Micro but the interrupt is different than the arduino uno. The external interrupt #0 pin on an arduino uno is pin 2 but its not pin 2 on an arduino micro. So I'm trying to figure out what pin it is on an arduino micro

# Answer
> 2 votes
The ATmega32U4 pin mapping says 3.

---
Tags: arduino-micro, mpu6050
---


title: Clear GET params from URL

text:
# Question
Title: Clear GET params from URL
I have a simple GET webform that takes in text. Once that text is submitted the URL permanently displays the text as the parameter. This causes echoing issues when I check the input from the web form; the string I am looking for is always found because the URL is never cleared. I cannot use an HTTP redirect and am looking for a way to do this based upon code.

# Answer
this is exaclty waht get are supposed to do. Use a POST or use a redirect; a POST is way better as the "back" button of the browser will take care of it
> 1 votes

---
Tags: web-server, web
---


title: Power an arduino on a 12V circuit

text:
# Question
Title: Power an arduino on a 12V circuit
I am doing a simple circuit with a 12V power supply to power a 12V LED strip. I'd like to be able to switch ON/OFF the strip with a relay connected to my Arduino. I'd like to know if I can power my Arduino directly from the VIN pin using 12V source. I saw that the Arduino can support up to 12V.

Thank you in advance for the help.

# Answer
As you have noted, many Arduino (and clones) are rated for supply voltage up to 12V. But note that if you use 12V power, the on-board regulator will get rather hot. Providing decent ventilation and maybe even extra heat sink would be a good idea.
> 1 votes

# Answer
The answer is yes, you can. Since there are no information about which Arduino you are using, Lets assume that you use Arduino uno. Based on the official webpage documentation, the recomended voltage input is ranging from 7 - 12 V. Therefore it is possible.
> 1 votes

---
Tags: power
---


# Question
Title: How do I output tone() and audioFX board output through a single speaker?
I'm building a BMX start gate controller. It requires a voice sample to be played ("Riders ready, watch the gate!") before playing a series of tones at very specific frequencies and intervals. After the tones are complete, a relay is triggered which drops the start gate.

I'm intending to use one of the header pins with the tone() function to output the tones, and an Adafruit AudioFX board to play the voice sample.

How do I connect both of these to an Adafruit mono amplifier (https://www.adafruit.com/product/2130) ?

Note that only one or the other will be playing at one time.

Can I use a "passive mixer" (which I think is putting a 10kΩ resistor on each input source for the amplifier?)

# Answer
> 1 votes
Yes, a passive mixer would do fine. I would recommend capacitors to remove any DC component too, before you do the mixing. 22uF should do fine.

I will draw a circuit in the morning.

---
Tags: adafruit, audio
---


# Question
Title: How can I use stepper for specific degree?
I use Arduino and I'm beginner. I use the code below, but I don't understand what `stepper.step(num)` and `STEPS` in `Stepper stepper(STEPS, 2,3,4,5)` are, and I want to use stepper for specific degree and I don't know what I can do. for example if I want to use stepper for 40 degree what are STEP and num?

```
#include <Stepper.h>

// change this to the number of steps on your motor
#define STEPS 100

// create an instance of the stepper class, specifying
// the number of steps of the motor and the pins it's
// attached to
Stepper stepper(STEPS, 2,3,4,5);

// the previous reading from the analog input
int previous = 0;

void setup()
{
  // set the speed of the motor to 30 RPMs
  stepper.setSpeed(100);
}

void loop()
{
  // get the sensor value
  //int val = analogRead(0);

  // move a number of steps equal to the change in the
  // sensor reading
  //stepper.step(val - previous);
  stepper.step(25);
  delay(1000000);
 // stepper.step(-5);

  // remember the previous value of the sensor
  //previous = val;
}

```

-----------------------------------------EDIT #2----------------------------- my stepper is the first one in this link: https://grahamwideman.wikispaces.com/file/view/28byj48\_models\_table.jpg/538898220/604x265/28byj48\_models\_table.jpg ( I think! ) and I don't know what it means? ------------------------------------------EDIT #3---------------------------- Thank you very much, I saw the link.

> Step Angle (8-Step sequence: Internal Motor alone): 5.625° (64 steps per revolution)

and I run this code for 45deg :

```
#include <Stepper.h>

#define STEPS_PER_MOTOR_REVOLUTION 32
#define STEPS_PER_OUTPUT_REVOLUTION 32 * 64  //2048
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 2, 3, 4, 5);

int  Steps2Take;

void setup()
{

}

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{

  Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 8.11;
  small_stepper.setSpeed(100);
  small_stepper.step(Steps2Take);
  delay(10000);
}

```

because I understand each turn has 2048 steps, for example if I want to have 1/2 turn, I have to have num=1024 ( 2048/2). ok, So, for 45deg, it's 1/8 turn so I have to set num=2048/8. but for example for 33 deg what should I do? I thought num= 33\*5.61 so for 45deg I use num=45\*5.61 you know we have a lot of floating point and I'm not sure we do it correct. right? I'm a little confused.

# Answer
`stepper.step(num)`is used to rotate your motor 'num'-step. i.e. `num=25`, then calling `stepper.step` will cause your motor do 25-step.

STEPS is number of steps per revolution for your motor. It will be depending on the motor you used. For more information, you can check here.

You have to check for your motor stepper resolution. Most common motor stepper has 200 steps per revolution, which means 1 step is 360/200 = 1.8 degree. If you try `Stepper.step(1)`, your motor will rotate 1.8 degree.

So in your case, if you already found out the resolution of your motor stepper, just do a simple conversion task:

```
const float resolution  = xx.xx; // put your step resolution here
int step_degree(float desired_degree){
    return (desired_degree/resolution);}

```

This can be use by calling

```
stepper.step(step_degree(40)); //rotate 40 degree.

```

**--EDIT--**
You can check this link, since it (perhaps) using same motor stepper (24BYJ48)

Based on 24BYJ48 datasheet, it has 5.625 degree resolution / 64 steps per revolution.
> 4 votes

---
Tags: stepper
---


title: Problem understanding code

text:
# Question
Title: Problem understanding code
This is a segment of an Arduino sketch, that I am trying to understand.

I know that the purpose of the entire code is to control 2 stepper motors linked to their respective drivers which are linked to a Mega 2560, but since I am new to Arduino, I am having problems with some functions.

This is a segment of the code. I am having problems with some statements such as `unsigned short FLG = 0;` and I cannot make out at all the timer interrupts part.

What does it all mean?

```
/* The “define” function is NOT A PROGRAMMING STATEMENT. Actually it sets up a macro which causes a text replace to occur before code is compiled. The pre-processor of the IDE will replace the variables such as “stp” to the integer value 22 in the following subsequent sections like the “void setup” function and the “loop” function if they are called. This function helps reduce RAM usage. */

#define stp 22
#define dir 23
#define stp2 26
#define dir2 27
#define EN  24
#define dir_ 25

int i, j, t, X = 0, Y = 0, Z = 0;
// here, the integer is creating variables such as i, j, t
//and also assigning values to some of them such as X, Y and Z.

unsigned short FLG = 0;

unsigned int Speed1 = 0, Speed2 = 0; // creating variables assigning initial values; due to unsinged only positive

int ser_1[3];

int po(int, int);

void setup() {     // You define how your Arduino will be used and set up any pins and communications you will be using. This will run first and only once.

  Serial.begin(9600); // begin the data transmission between Arduino and pc at speed of 9600 bits per sec
  delay(500); // stop for 500 milliseconds

  Serial.println(“hi”); // this will print the word “hi” on the serial monitor window on pc via serial port

  pinMode(stp, OUTPUT); // tells arduino to use digital Pin 22 to output electricity
  pinMode(dir, OUTPUT); // tells arduino to use digital Pin 23 to output electricity
  pinMode(stp2, OUTPUT); // tells arduino to use digital Pin 26 to output electricity
  pinMode(dir2, OUTPUT); // tells arduino to use digital Pin 27 to output electricity
  pinMode(EN, OUTPUT); // tells arduino to use digital Pin 24 to output electricity

  noInterrupts(); // to prevent disruption of timing of codes, disables some functions in the background

  /* To use timers, the built-in timer registers on the AVR chip that store timer settings need to be configured.  There are a number of registers per timer.  Two of these registers –the Timer/Counter Control Registers- hold setup values, and are called TCCRxA and TCCRxB, where x is the timer number (TCCR1A and TCCR1B, etc.).   Each register holds 8 bits, and each bit stores a configuration value. */

  TCCR1A = 0x80; //
  TCCR1B = 0x0A; // Enable reset on compare match, 1:8 clock. don’t understand
  OCR1AH = 0x9C;
  OCR1AL = 0x3F;
  TIMSK1 = (1 << OCIE1A); // enable timer compare interrupt
  interrupts();
}
ISR(TIMER1_COMPA_vect)   // timer compare interrupt service routine
{
  res();
}
void loop(){

if(Serial.available())
 {
  ser_1[i] = Serial.read();
  char ch = Serial.read();
if(ch==’S’)
   { i=0;
     X=0;
     while(1)
{
  if (Serial.available() > 0)
     {
      ser_1[i]=Serial.read();
      ser_1[i]=ser_1[i]-48;
      X=X+(ser_1[i]*(po(10,i)));
      i++;
     if(i==3)
       {
        FLG++;
        break;
        }
      }
    }
}

if (ch==’A’)
  { i=0;
    Y=0;
     while(1)
     {
        if (Serial.available() > 0)
      {
      ser_1[i]=Serial.read();
      ser_1[i]=ser_1[i]-48;
      Y=Y+(ser_1[i]*(po(10,i)));
       i++;
      if (i==3)
          {
           FLG++;
           break;
           }
          }
        }
      }

     if(FLG==2)
    {
      Speed1=X;
      Speed2=Y;
      digitalWrite(EN,LOW);
        delay(100);
      StepForwardDefault();
        delay(1000);
      StepForwardDefault2();
         delay(1000);
      ReverseStepDefault2();
      ReverseStepDefault();
      delay(1000);
      digitalWrite(EN,HIGH);
      delay(1000);
      }
      else
      Serial.println(“sequence is stop”);
}
 /*****************po******************/

int po(int num, int pow)
{ int result=1;
  if(pow==0)
  return 1;
  else
 {
  for(int f=1;f<=pow;f++)
    {
  result=result*num;
    }
 return result;
 }
}

/************ MOTOR 1 Function *****************/

void ReverseStepDefault()
{
  Serial.println(“motor a reverse”);
  Serial.println(“Moving in reverse at default step mode.”);
digitalWrite(dir_, HIGH); // Pull direction pin high to move in “reverse”
digitalWrite(dir, LOW);
delay(100);
for(int x=1; x<200; x++) // Loop the stepping enough times for motion to be visible
{
  digitalWrite(stp, HIGH); //Trigger one step
  delay(305-X);
  digitalWrite(stp, LOW);  // Pull step pin low so it can be triggered again3
  delay(305-X);
  }
}

/************ MOTOR 2 Function *****************/

void ReverseStepDefault2()
{
  Serial.println(“Moving b reverse”);
  digitalWrite(dir_, HIGH); // Pull direction pin high to move in “reverse”
  digitalWrite(dir2, LOW);
  delay(100);
  for(int x =1; x<200; x++) // Loop the stepping enough times for motion to be visible
  {
   digitalWrite(stp2,HIGH); // Trigger one step
   delay(305-Y);
   digitalWrite(stp2,LOW); // Pull step pin low so it can be triggered again3
   delay(305-Y);
   }
}

void StepForwardDefault2()
{
   Serial.println(“motor b forward”);
   digitalWrite(dir_,HIGH); // Pull direction pin high to move in “reverse”
   digitalWrite(dir2,HIGH);
   delay(100);
   for(int x=1; x<200; x++) // Loop the forward stepping enough times for motion to be visible

{
  digitalWrite(stp2,HIGH); // Trigger one step forward
  delay(305-Y);
  digitalWrite(stp2,LOW); // Pull step pin low so it can be triggered again
  delay(305-Y);
    }
}

void res()
 {
   if(Serial.available())
  {
   ser_1[i]=Serial.read();
   char ch = Serial.read();
   if(ch ==’T’)
      {
       FLG=0;
       Serial.println(“stop is pressed”);
      }
   }
}

```

# Answer
> 5 votes
> I am having problems with some statements such as "unsigned short FLG = 0;"

This is the C and C++ syntax for declaring a variable. The statement means “Let `FLG` be an unsigned short integer and let it's initial value be zero”. An `unsigned short` can hold any integer value between 0 and 65535 inclusive.

The Arduino language reference documents the types `short` and `unsigned int` but, for a mysterious reason, it does not document `unsigned short`.

> I cannot make out at all the timer interrupts part.

Nobody can unless they know the internals of the AVR timers, which are non trivial but are well covered in the datasheet. It's a thick document, but you only need to study chapters 14: *Interrupts* and 17: *16-bit Timer/Counter (Timer/Counter 1, 3, 4, and 5)*.

I recommend you first read the Timers and counters tutorial by Nick Gammon, then go to the datasheet for the most authoritative information.

**Edit**: Just a comment... I find the program you have posted to be written with poor programming style. More specifically, the section setting the Timer 1 registers would be better written as follows:

```
TCCR1A = bit(COM1A1);  // set OC1A to LOW on compare match
TCCR1B = bit(WGM12)    // CTC mode, TOP = OCR1A
       | bit(CS11);    // clock at F_CPU / 8
OCR1A  = 40000 - 1;    // period = 40000 prescaled clock cycles
TIMSK1 = bit(OCIE1A);  // enable COMPA interrupt

```

It is still obscure if you don't know the timer, but using explicit bit names instead of pure numbers makes things a lot easier when you refer to the datasheet. Also, there is no point in setting each byte of `OCR1A` in a different statement: it only makes things harder to read.

# Answer
> 2 votes
I'm assuming you don't mean "all" when you ask "what does it *all* mean?" I also assume that the comments are from you - in which case you've done reasonably well!

```
/* The “define” function is NOT A PROGRAMMING STATEMENT... */

```

True, `#define` isn't a programming statement that produces code: it's a way of defining a symbol that you can use in the rest of the code, both for explanation purposes and ease of changing: without having to search for all copies of `22` \- and then decide if *this particular* `22` is for that pin or not.

```
unsigned short FLG=0;

```

`int` is 16 bits in the Arduino, but in some systems it's 32 (and in others 64). `short` is (practically) always 16 bits regardless of system, so many programmers use `short` when they know they definitely want a 16-bit integer. `unsigned` merely means that it can never go negative - which allows the variable to hold higher values (0 to 65,535 instead of -32,768 to 32,767).

```
int ser_1[3];

```

This is an array of 3 `int`s called `ser_1`, which can be accessed as `ser_1[0]`, `ser_1[1]` and `ser_1[2]`. In C, all arrays start at `0`. Why use an array? It makes it possible to use *another* variabe to say *which* `ser_1` you want: e.g. `ser_1[i]`. If `i` is `2`, you get the last one.

```
int po(int,int);

```

This says that there will be a function called `po` that takes two `int` values, processes them, and returns an `int` result.

```
noInterrupts(); // to prevent disruption of timing of codes, disables some functions in the background

```

Pretty much. An interrupt can happen at any time: the CPU will stop executing the main program, execute the interrupt code, then resume where it left off in the main program. Sometimes that's a bad thing! If the interrupt code is going to change something that *this* code needs to stay the same (or vice versa!), then Bad Things can happen. To prevent that, you can turn off interrupts temporarily with this function, and turn them on again later with `interrupts()` (which you'll see below).

```
/* To use timers, the built-in timer registers on the AVR chip that store timer settings need to be configured.  There are a number of registers per timer.  Two of these registers –the Timer/Counter Control Registers- hold setup values, and are called TCCRxA and TCCRxB, where x is the timer number (TCCR1A and TCCR1B, etc.).   Each register holds 8 bits, and each bit stores a configuration value. */

 TCCR1A = 0x80; //
 TCCR1B = 0x0A; // Enable reset on compare match, 1:8 clock. don’t understand

```

OK, this is complicated:

* By default, a timer simply counts from `0` to `65,535` (maximum 16 bit value), then resets and starts again.
* How quickly? One 'tick' is the system clock, so *very* quickly! But you can "pre-scale" that with a divisor. In this case, they're using a divisor of 8, so the timer will "tick" an eighth as fast.
* You can configure the timer to interrupt when it resets, so that special code will execute on a timed basis.
* You can also tell it that if at any time it hits a certain number to *also* interrupt (Compare Match) - that's two different interrupts.
* You can *also* tell it that when it hits that Compare number, to reset back to `0` and start counting again. That means that the timer will interrupt more often.

`OCR1AH = 0x9C;`
`OCR1AL = 0x3F;`

These stand for "Output Compare Register 1A High" and "Output Compare Register 1A Low" - a 16 bit value that is 0x9C3F (37839 decimal). If you divide the system clock by that number, (and a further 8 for the pre-scaler), you'll find out how often it interrupts.

```
interrupts();

```

This turns on interrupts again.

```
ISR(TIMER1_COMPA_vect)   // timer compare interrupt service routine
{
res();
}

```

This is the code that executes every timer interrupt. I don't know what `res()` does.

# Answer
> 1 votes
Here is some explanation :

```
TCCR1A = 0x80; //OC1 will cleared on compare match
TCCR1B = 0x0A; //Turn on CTC mode --> it means the interrupt counter will reset to 0, and causing the interrupt happen again and again.
               //Divide clock 1:8 (prescaler)
OCR1AH = 0x9C;
OCR1AL = 0x3F; //compare value = 0x9C3F = 39999
TIMSK1 = (1<<OCIE1A); // the micro will jump to the Output Compare A Interrupt vetor upon compare match.

```

Overall, this setup will make your program do whatever you put in the Interrupt Service Routine `ISR(TIMER1_COMPA_vect){...do whatever here...}`

The interrupt interval is =

> (OCR1A+1) × prescaler ÷ F\_CPU
>
> (39999+1) × 8 ÷ 16.000.000 = 0.02 sec

as for `res();` and `unsigned short FLG;` I dont know what that is, since its probably your own creation (not from arduino libs)

You can found more detailed explanation here and here

---
Tags: arduino-mega
---


title: Regarding Arduino Mega hardware serial

text:
# Question
Title: Regarding Arduino Mega hardware serial
I have a doubt interfacing with fingerprint module (R305) with the Arduino Mega. I have been able to interface it to Arduino Uno before but not Arduino Mega so far.

I have used the Mega's hardware Serial1 pins 19 (Rx) and 18 (Tx) pins.

However, I am unable to get output from the module. How do I connect hardware serial and what is a sketch to do this?

# Answer
Try Pin digital pins 0 (RX) and 1 (TX), as they also should be Serial0 on ArduinoMega (PWM 0 and 1)

see: https://www.arduino.cc/en/Reference/Serial

The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX). To use these pins to communicate with your personal computer, you will need an additional USB-to-serial adaptor, as they are not connected to the Mega's USB-to-serial adaptor. To use them to communicate with an external TTL serial device, connect the TX pin to your device's RX pin, the RX to your device's TX pin, and the ground of your Mega to your device's ground.
> 2 votes

---
Tags: arduino-mega
---


title: Servos and ultrasonic at the same time

text:
# Question
Title: Servos and ultrasonic at the same time
So recently I started making a sonar out of ultrasonic HC-SR04 sensor and servo motor. The idea was to slowly rotate servo 180 degrees while measuring distance.

Soon after I noticed that regular pulseIn() command could wait 20ms while doing nothing. So I started learning interrupts. I came up with a code which sends TRIG signal and records sending time with micros() function. When an interrupt occurs on ECHO pin, we subtract current time with TRIG time and get time of round trip of the sound.

The code works as intended without servos connected, but it behaves interestingly ! I always get distance which is 8 cm bigger than actual distance. So I had to subtract 8 cm every time ! Also I noticed that max reliable range decreased , using pulseIn() I could measure distance of 400cm, and with mine code it starts to show weird numbers after 150cm...

So i thought that 150cm is enough for me, and tried to run the code with servos attached. everything ran as intended, until the servos started to move. Now I was getting distance along with pretty much random numbers, periodically positive and negative.

I could just use one the fancy libraries out there, but I am curious what am I doing wrong, why i need to subtract 8cm each time , why my reliable range decreased so much, and most importantly why am I getting weird values while servos are on ?

CODE :

```
#include <Servo.h>

#define ECHO 2
#define TRIG 7

 Servo servo;
 int distance;
 volatile long echoTime = 0;
 long trigTime = 0,sendTime = 0,timeServo = 0;
 bool scanning = false;
 byte servoDir = -1,servoAngle = 0;

void setup()
{
  servo.attach(12);
  Serial.begin(115200);
  pinMode(ECHO,INPUT);
  pinMode(TRIG,OUTPUT);
  attachInterrupt(digitalPinToInterrupt(ECHO), echo_interupt, FALLING);

}
void loop()
{
  // SERVO

   if((millis() - timeServo > 10)){
     if(servoAngle <= 0 || servoAngle >= 180)servoDir = -servoDir;
     servoAngle += servoDir;
     servo.write(servoAngle);
     timeServo = millis();
   }

  // GETTING RESULTS
  if(echoTime > 0){
    distance = echoTime - trigTime;
    distance /= 58;
    echoTime = 0;
    trigTime = 0;
    Serial.println(distance - 8);
  }
  // SENDING PULSE
  if(millis() - sendTime > 20){
  digitalWrite(TRIG,LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG,HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG,LOW);
  trigTime = micros();
  sendTime = millis();
  }
}

 // INTERUPT
void echo_interupt(){
  echoTime = micros();
}

```

# Answer
> 1 votes
8cm is 233µs of sound travel time. There and back again would be 466µs. 466µs, at 16MHz, is around 7400 instructions.

When an interrupt is triggered you don't get an instant response. First the built in interrupt function is called. That then looks to see if you have registered an interrupt function. It then calls that interrupt function.

All that takes time, and when you're working with microseconds it makes a big difference.

And then you have to go and get the current micros() value, which again takes time to do.

So it all adds up to a delay. Not ideal.

For greater accuracy you should investigate using *input capture* which will start a timer running when you send the trigger and the timer will automatically stop the nanosecond the echo is received. From that you can calculate a much more precise distance.

As for why you are getting strange results with the servos on? Most likely because you are moving the receiving head while the pulse is being received. I made a similar system while playing once and found that the best results were achieved by moving the head to the desired position, waiting a moment for any vibration to settle, do the ping and get the result, then move the head to the next position.

Oh, and by the way, the HC-SR04 is (from memory) only really rated for up to 2m - I have never achieved anything more than around 1.8m with any accuracy.

# Answer
> 0 votes
I had problems with `Servo` library and `VirtualWire`. They both use the same internal timer. The solution was to change `Servo.h` to `ServoTimer2.h` lib.

---
Tags: serial, sensors, c++, interrupt, servo
---


title: L298N vs Motor Shield R3

text:
# Question
Title: L298N vs Motor Shield R3
I'm new to Arduino and need some clarification on motor drivers.

I was wondering if I can use a L298N instead of the Motor Shield R3, I hope not to be comapring apples to oranges, the doc of the Motor Shield R3 say "The Arduino Motor Shield is based on the L298" and more or less I see similar projects (Robot cars) using both but as mention I don't if I can use one or the other as "replacement".

(L298N)

(Motor Shield R3):

# Answer
> 0 votes
Yes. The shield is easier to user, but the breakout board you've shown uses the same chip. I'd suspect that the breakout board, which has a much bigger heat sink, can handle larger motors, though. You'll need to put wires from PWM and digital pins to the breakout board you're showing, but it's not super challenging to use those. I've used extremely similar boards in the past, as well as shields, and both work great. How big are your motors? If they're WAY too big (the breakout board can only handle 2 amps IIRC) then you'll need something else anyway.

---
Tags: arduino-uno, arduino-motor-shield, l298n
---


title: Running quartz clock off an arduino

text:
# Question
Title: Running quartz clock off an arduino
I am trying to run a clock off of an arduino following this site: http://www.cibomahto.com/2008/03/controlling-a-clock-with-an-arduino/comment-page-1/ and I tried to combine it with this to get it to run accurately. https://contractorwolf.com/arduino-pwm-interrupt-clock/

For the project that I want to do I need to slow down the minute hand by 23.9345 (So that it will run on sidereal time)

Now the bare code of the first link with some mods works perfectly, but the delay does not seem to be accurate:

```
    const int a1  =  8;     //use digital I/O pin 8
    const int a2  =  9;
    const int tick1 = 1000;
    const int tick2 = 50;

    void setup()
    {
    pinMode(a1,OUTPUT);   //set pin 8 to be an output output
    pinMode(a2,OUTPUT);   //set pin 9 to be an output output
    }

    void loop()
    {
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
       delay(tick2);          //delay 1000 milliseconds
       digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
       delay(tick2);          //delay 1000 milliseconds
       digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
    }

```

For this reason I have tried to merge it with the 1 wire clock project and got

```
const int a1  =  8;     //use digital I/O pin 8
const int a2  =  9;
const int tick1 = 1000;
const int tick2 = 50;

int cyclesPerSecond = 974;

//pins
int clockInterrupt = 0; //interrupt 0 is pin 2 on UNO
int pwmOut = 6; //pin 6

//timekeeping
int seconds = 0;
int masterClock = 0;//number of square waves

void setup()
{
attachInterrupt(clockInterrupt, clockCounter, RISING);
pinMode(a1,OUTPUT);   //set pin 8 to be an output output
pinMode(a2,OUTPUT);   //set pin 8 to be an output output

Serial.println(pwmOut);
analogWrite(pwmOut, 127); // this starts our PWM 'clock' with a 50% duty cycle//digital pin 10 for analogWrite pwm out
}

void clockCounter() // called by interrupt 0 (pin 2 on the UNO) receiving a rising clock edge PWM
{
masterClock ++; // with each clock rise add 1 to masterclock count
if(masterClock >= cyclesPerSecond*23.9345) // 974hz on pin 6, may be 490Hz if you use pin 9 or 10
{
seconds ++; // after one cycle add 1 second
masterClock = 0; //reset clock counter
}
}

void loop()
{
  if (seconds == 1){
   digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
   delay(tick1);          //delay 1000 milliseconds
   digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
   else if(seconds == 2)
   seconds = 0;
   digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
   delay(tick1);          //delay 1000 milliseconds
   digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
  }
}

```

However this does not seem to move the second hand properly, so the clock does tick but not strong enough to actually work. Is this a hardware thing or a processor thing? I have no idea why this would not work while the other code does.

# Answer
> 2 votes
As I said in my comment, the idea of using the Arduino's own PWM as a clock source is completely misguided. It will be no more accurate than using `millis()` or `micros()`: both these functions and the PWM rely on the same primary clock source, namely the ceramic resonator clocking the chip.

Also, you should avoid using `delay()` for timekeeping. The time it takes to run around the `loop()` is the sum of all your delays *plus the time needed to execute the actual instructions*, which you do not know accurately. It is far better to use either `millis()` or `micros()`.

Here is a tentative sidereal clock code, not tested:

```
// Pins driving the clock.
const int a1 = 8;
const int a2 = 9;

// Length of one sidereal second in microseconds.
const unsigned long SIDEREAL_SECOND = 997270;

void setup()
{
    pinMode(a1, OUTPUT);
    pinMode(a2, OUTPUT);
}

void tick()
{
    static int activePin = a1;

    // Pulse the pin.
    digitalWrite(activePin, HIGH);
    delay(50);
    digitalWrite(activePin, LOW);

    // Next time use the other pin.
    if (activePin == a1) activePin = a2;
    else activePin = a1;
}

void loop()
{
    static unsigned long last_tick;
    if (micros() - last_tick >= SIDEREAL_SECOND) {
        tick();
        last_tick += SIDEREAL_SECOND;
    }
}

```

You can tune the speed of the clock by changing the constant `SIDEREAL_SECOND`. I set the constant to the actual length of a sidereal second, in microseconds, but you may find that the clock does not run exactly at the correct speed. This is because the ceramic resonator inside the Arduino is not very accurate. You can remove most of the inaccuracy by calibration: measure how fast or slow it runs and change the value of `SIDEREAL_SECOND` to compensate. You will still face some residual inaccuracy owing to the fact that the resonator's frequency is not very stable, and is highly temperature-dependent.

If you want to build a clock that has decent accuracy, your best bet is to use a 32768 Hz quartz crystal, as suggested by Ignacio Vazquez-Abrams in his comment. I did that on a bare ATmega chip (a “barebones Arduino”) to make a 24-hour analog wall clock. You should be able to easily adapt the code I published in that page to fit your project.

# Answer
> 1 votes
I'm not 100% certain of what you are trying to do but I noticed a few bits in the code which don't look right to me. For instance this function:

```
void clockCounter() // called by interrupt 0 (pin 2 on the UNO) receiving a rising clock edge PWM
{
  masterClock ++; // with each clock rise add 1 to masterclock count
  if(masterClock >= cyclesPerSecond*23.9345) // 974hz on pin 6, may be 490Hz if you use pin 9 or 10
  {
    seconds ++; // after one cycle add 1 second
    masterClock = 0; //reset clock counter
  }
}

```

This is causing a part of your inaccuracy. You are incrementing the integer `masterClock` variable and then seeing if it is `>=` to a floating point value, the equals is not necessary and will almost never be true. If the condition occurs then you increment seconds before setting `masterClock` to zero, losing any part of a second you had left over.

Looking at what others have said I would be inclined to take a different approach to this project rather than try and fix this code.

# Answer
> 1 votes
Writing another answer because I just had a completely different idea.

A standard option for keeping reasonably accurate time with an Arduino is to use an RTC module. If possible, choose one based on the DS3231 rather than the DS1307, as the former has builtin temperature compensation, which makes it significantly more accurate.

The RTC is typically used to provide the time over I2C in a broken-down form: year, month, day, hour, minute and second. This is not really convenient for a sidereal clock, as it would require complex conversions to derive the sidereal time. However, most RTC modules have the option to output a 32,768 Hz square wave. If you can feed this signal to the digital pin 5 of your Arduino Uno, then you can use the Timer/Counter 1 to count the cycles and raise an interrupt every sidereal second, i.e. every 32,678.53 cycles of the RTC signal.

There is small issue with the above number not being an integer. One could just round it to the nearest integer, which would make the clock slow by about 14 ppm, or 1.2 s/day. This may not seem like a large error, but the DS3231 is capable of much greater accuracy: ±2 ppm from 0°C to +40°C.

An elegant solution is to count the cycles internally using a 32-bit fixed-point number, with 16 bits for the integer part and 16 bits for the fractional part. On each timer interrupt, we compute what value the timer should have on the next interrupt (variable `next_count` below), simply by adding 32,678.53 to the previous value. Then we use the integer part of the result (16 most significant bits) to program the next interrupt. This way the interrupts will be spaced by either 32,678 or 32,679 signal periods, with the average being exactly the value we need. This provides very high granularity, as our time unit is now effectively 2<sup>−31</sup> s ≈ 0.466 ns.

In the code below, the first three functions are left empty, as “an exercise for the reader”. Or rather because they are dependent on the specifics of the hardware setup. I am only showing the logic of using the Timer 1 for getting an interrupt every sidereal second.

```
/*
 * RTC-based sidereal clock.
 *
 * Configure the RTC to output a 32,768 Hz square wave.
 * Feed this square wave to pin T1 = PD5 = digital 5.
 */

#include <avr/sleep.h>

static void setup_rtc()
{
    // Configure the RTC to output a 32,768 Hz square wave.
}

static void setup_clock_pins()
{
    // Configure the pins for driving the clock.
}

static void tick()
{
    // Advance the clock by one second.
}

/*
 * For better granularity, time is counted in units of 2^-16 cycles of
 * the 32768 Hz square wave (~ 0.47 ns), as a 32-bit unsigned integer.
 * Timer 1 holds the 16 most significant bits.
 */
const uint32_t SI_SECOND       = 32768UL << 16;
const uint32_t SIDEREAL_SECOND = 0.99726958 * SI_SECOND;

// Interrupt fired every sidereal second.
ISR(TIMER1_COMPA_vect)
{
    static uint32_t next_count;
    next_count += SIDEREAL_SECOND;
    OCR1A = next_count >> 16;  // use the 16 most significant bits
    tick();
}

void setup()
{
    // Configure Timer 1.
    TCCR1A = 0;            // normal counting mode
    TCCR1B = _BV(CS10)     // count rising edges of T1
           | _BV(CS11)     // ditto
           | _BV(CS12);    // ditto
    TIMSK1 = _BV(OCIE1A);  // enable COMPA interrupt

    // Enable pullup on T1 = PD5.
    PORTD |= _BV(PD5);

    setup_rtc();
    setup_clock_pins();
}

void loop()
{
    sleep_mode();
}

```

---
Tags: arduino-uno, oscillator-clock
---


# Question
Title: Making a current GPS code run once, and only once, after the code is 'activated'
I have a GPS code that I need to run only once, but every different try gives me errors, including placing the whole code in `void setup()`. Is there any way that this code can be run just once? As of now, the code repeats itself, putting out data over and over again - I need just one set, right when the code is activated.

Here is the code:

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

SoftwareSerial mySerial(3, 2);
Adafruit_GPS GPS(&mySerial);
#define GPSECHO  true
boolean usingInterrupt = false;
void useInterrupt(boolean);

void setup() {
  Serial.begin(115200);
  Serial.println("Adafruit GPS library basic test!");
  GPS.begin(9600);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
  GPS.sendCommand(PGCMD_ANTENNA);
  useInterrupt(true);
  delay(1000);
  mySerial.println(PMTK_Q_RELEASE);
}

SIGNAL(TIMER0_COMPA_vect) {
  char c = GPS.read();
#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;
#endif
}

void useInterrupt(boolean v) {
  if (v) {
    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  } else {
    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

uint32_t timer = millis();
void loop() {                  // run over and over again
  if (! usingInterrupt) {
    char c = GPS.read();
    if (GPSECHO)
      if (c) Serial.print(c);
  }
  if (GPS.newNMEAreceived()) {
    if (!GPS.parse(GPS.lastNMEA()))
      return;

  if (timer > millis())
    timer = millis();

  if (millis() - timer > 2000) {
    timer = millis(); // reset the timer
    Serial.print("\nTime: ");
    Serial.print(GPS.hour, DEC); Serial.print(':');
    Serial.print(GPS.minute, DEC); Serial.print(':');
    Serial.print(GPS.seconds, DEC); Serial.print('.');
    Serial.println(GPS.milliseconds);
    Serial.print("Date: ");
    Serial.print(GPS.day, DEC); Serial.print('/');
    Serial.print(GPS.month, DEC); Serial.print("/20");
    Serial.println(GPS.year, DEC);
    Serial.print("Fix: "); Serial.print((int)GPS.fix);
    Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
    if (GPS.fix) {
      Serial.print("Location: ");
      Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
      Serial.print(", ");
      Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
      Serial.print("Location (in degrees, works with Google Maps): ");
      Serial.print(GPS.latitudeDegrees, 4);
      Serial.print(", ");
      Serial.println(GPS.longitudeDegrees, 4);
      Serial.print("Speed (knots): "); Serial.println(GPS.speed);
      Serial.print("Angle: "); Serial.println(GPS.angle);
      Serial.print("Altitude: "); Serial.println(GPS.altitude);
      Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
    }
  }
  }
}

```

I've been trying to get this for a while, and I'm new to programming!

# Answer
Here's your sketch, modified to use my library, NeoGPS. It is smaller, faster, more reliable and more accurate than all other libraries.

I added a `waitForFix` routine that, well, waits for the GPS to get a fix. Then it calls `printFix`, just once:

```
#include <NMEAGPS.h>
#include <NeoSWSerial.h>

NeoSWSerial gpsSerial(3, 2);
NMEAGPS     GPS;
gps_fix     fix;

void setup()
{
  Serial.begin(115200);
  Serial.println( F("Run once!") ); // F macro saves RAM!

  gpsSerial.begin(9600);
  gpsSerial.println( F("$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28") ); // RMC & GGA only
  gpsSerial.println( F("$PMTK220,1000*1F") ); // 1Hz update rate

  waitForFix();
  printFix();
}

void loop()
{
}

void waitForFix()
{
  uint8_t fixes = 0;

  do {
    if (GPS.available( gpsSerial )) {
      fix = GPS.read();
      fixes++;
    }
  } while ((fixes < 2) && !fix.valid.location);

} // waitForFix

void printFix()
{
  Serial.print( F("Time: ") );
  if (fix.valid.time) {
    if (fix.dateTime.hours < 10)
      Serial.print( '0' );
    Serial.print(fix.dateTime.hours);
    Serial.print(':');
    if (fix.dateTime.hours < 10)
      Serial.print( '0' );
    Serial.print(fix.dateTime.minutes);
    Serial.print(':');
    if (fix.dateTime.hours < 10)
      Serial.print( '0' );
    Serial.print(fix.dateTime.seconds);
    Serial.print('.');
    if (fix.dateTime_cs < 10)
      Serial.print( '0' );
    Serial.print(fix.dateTime_cs);
  }
  Serial.println();

  Serial.print( F("Date: ") );
  if (fix.valid.date) {
    Serial.print(fix.dateTime.day);
    Serial.print('/');
    Serial.print(fix.dateTime.month);
    Serial.print('/');
    Serial.print( fix.dateTime.full_year() );
  }
  Serial.println();

  Serial.print( F("Fix status: ") );
  if (fix.valid.status)
    Serial.print( (int) fix.status );
  Serial.println();

  if (fix.valid.location) {
    Serial.print( F("Location: ") );
    Serial.print( fix.latitude(), 4 );
    Serial.print( F(", ") );
    Serial.println(fix.longitude(), 4);
  }

  if (fix.valid.speed) {
    Serial.print("Speed (knots): ");
    Serial.println( fix.speed() );
  }

  if (fix.valid.heading) {
    Serial.print( F("Angle: ") );
    Serial.println( fix.heading() );
  }

  if (fix.valid.altitude) {
    Serial.print( F("Altitude: ") );
    Serial.println( fix.altitude() );
  }

  if (fix.valid.satellites) {
    Serial.print( F("Satellites: ") );
    Serial.println( fix.satellites );
  }
}

```

The NeoGPS library waits for a complete batch of sentences, because the speed is in one sentence (RMC) and the altitude is in another sentence (see this table). NeoGPS provides complete "fixes", as assembled from all the sentences your GPS device sends. The fixes are available once per second, or whatever you have configured your device to provide.

You may also notice that I used another library I maintain, NeoSWSerial. `SoftwareSerial` is *very* inefficient because it disables interrupts for long periods of time. This can interfere with other parts of your sketch or other libraries.

If you can put the GPS on pins 8 & 9, AltSoftSerial would be even better. It only works on those two pins.

Your original sketch uses 12124 bytes of program space and 1031 bytes of RAM.

The NeoGPS version uses 10680 bytes of program space and 446 bytes of RAM. A significant savings!
> 0 votes

# Answer
Put everything from your `void loop()` into your `void setup`. Put them AFTER the original setup and you should be good to go.

**DO NOT DELETE THE VOID LOOP!! ONLY KEEP IT EMPTY!!**

Here, try this:

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

SoftwareSerial mySerial(3, 2);

Adafruit_GPS GPS(&mySerial);

#define GPSECHO  true

boolean usingInterrupt = false;
void useInterrupt(boolean);

void setup()
{

  Serial.begin(115200);
  Serial.println("Adafruit GPS library basic test!");

  GPS.begin(9600);

  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);

  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);

  GPS.sendCommand(PGCMD_ANTENNA);

  useInterrupt(true);

  delay(1000);

  mySerial.println(PMTK_Q_RELEASE);

  if (! usingInterrupt) {

    char c = GPS.read();

    if (GPSECHO)
      if (c) Serial.print(c);
  }

  if (GPS.newNMEAreceived()) {

    if (!GPS.parse(GPS.lastNMEA()))
      return;

    if (timer > millis())  timer = millis();

    if (millis() - timer > 2000) {
      timer = millis(); // reset the timer

      Serial.print("\nTime: ");
      Serial.print(GPS.hour, DEC); Serial.print(':');
      Serial.print(GPS.minute, DEC); Serial.print(':');
      Serial.print(GPS.seconds, DEC); Serial.print('.');
      Serial.println(GPS.milliseconds);
      Serial.print("Date: ");
      Serial.print(GPS.day, DEC); Serial.print('/');
      Serial.print(GPS.month, DEC); Serial.print("/20");
      Serial.println(GPS.year, DEC);
      Serial.print("Fix: "); Serial.print((int)GPS.fix);
      Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
      if (GPS.fix) {
        Serial.print("Location: ");
        Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
        Serial.print(", ");
        Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
        Serial.print("Location (in degrees, works with Google Maps): ");
        Serial.print(GPS.latitudeDegrees, 4);
        Serial.print(", ");
        Serial.println(GPS.longitudeDegrees, 4);

        Serial.print("Speed (knots): "); Serial.println(GPS.speed);
        Serial.print("Angle: "); Serial.println(GPS.angle);
        Serial.print("Altitude: "); Serial.println(GPS.altitude);
        Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
      }
    }
  }
}

SIGNAL(TIMER0_COMPA_vect) {
  char c = GPS.read();

#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;

#endif
}

void useInterrupt(boolean v) {
  if (v) {

    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  } else {

    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

uint32_t timer = millis();

void loop()                     // run over and over again
{
}

```
> 0 votes

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


# Question
Title: WARNING: Category '' in library *any library* is not valid. Setting to 'Uncategorized'
I'm using Ubuntu 14.04 with arduino Galileo and the newest arduino IDE from arduino.cc and every time I compile I got this warnings with *any library* in place of EEPROM, SD, Wire, Wifi and a lot of others.

When I check the boards manager I got the following:

Invalid library found in /home/User/.arduino15/packages/Intel/hardware/i586/1.6.2+1.0/libraries/Wire: /home/User/.arduino15/packages/Intel/hardware/i586/1.6.2+1.0/libraries/Wire

Anyone knows how to solve this?

# Answer
As sated above you need to "Edit or add library.properties to that folder so that you specify a valid category."

This link has some good info on the structure of the file: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

From that link:

library.properties file format

The library.properties file is a key=value properties list. Every field in this file is UTF-8 encoded. The available fields are:

```
**name** - the name of the library
version - version of the library. Version should be semver compliant. 1.2.0 is correct; 1.2 is accepted; r5, 003, 1.1c are invalid
**author** - name/nickname of the authors and their email addresses (not mandatory) separated by comma ","
**maintainer** - name and email of the maintainer
**sentence** - a sentence explaining the purpose of the library
**paragraph** - a longer description of the library. The value of sentence always will be prepended, so you should start by writing the second sentence here
**category** - if present, one of these: "Display", "Communication", "Signal Input/Output", "Sensors", "Device Control", "Timing", "Data Storage", "Data Processing", "Other"
**url** - the URL of the library project, for a person to visit. Can be a github or similar page as well
architectures - a comma separated list of architectures supported by the library. If the library doesn’t contain architecture specific code use “*” to match all architectures
**dot_a_linkage** - (available from IDE 1.6.0 / arduino-builder 1.0.0-beta13) when set to true, the library will be compiled using a .a (archive) file. First, all source files are compiled into .o files as normal. Then instead of including all .o files in the linker command directly, all .o files are saved into a .a file, which is then included in the linker command.
**includes** - (available from IDE 1.6.10) a comma separated list of files to be added to the sketch as #include <...> lines. This property is used with the "Include library" command in the IDE. If the property is undefined all the headers files (.h) on the root source folder are included.

```
> 3 votes

# Answer
Edit or add library.properties to that folder so that you specify a valid category.

Example of library.properties:

```
name=WebServer
version=1.0
author=Cristian Maglie <c.maglie@example.com>, Pippo Pluto <pippo@example.com>
maintainer=Cristian Maglie <c.maglie@example.com>
sentence=A library that makes coding a Webserver a breeze.
paragraph=Supports HTTP1.1 and you can do GET and POST.
category=Communication
url=http://example.com/
architectures=avr

```
> 3 votes

# Answer
From: https://www.bountysource.com/issues/29336127-one-wire-library-still-in-v2-3-0-causes-useless-warning

> The Arduino library manager still defaults to v2.3.0, which causes the IDE to raise the following warning on compile :
>
> WARNING: Category '' in library OneWire is not valid. Setting to 'Uncategorized'

Solution (In 1.6.12):

1. Sketch -\> Include Library -\> Manage Libraries
2. In the upper-right "Filter Your Search" box enter (without the quotes): "OneWire"
3. Click the "OneWire by Jim Studt, Tom P..."
4. Select version 2.3.1 (or newer)
5. Click "Install"
> 1 votes

---
Tags: library, arduino-galileo, ubuntu
---


# Question
Title: The easiest and most time efficent way to connect to the internet regardless of the cost
I am working on my graduation Project. I want to use the cayenne (mydevices) platform to control my Arduino. Mainly I want to be able to control a servo Motor through the Cayenne app and I want to use a gyro sensor that would also control the servo using the app after obtaining the readings from the sensor. The Options are: 1- Yun arduino 2- Arduino Ethernet 3- Arduino uno (which I currently have) + Arduino Ethernet shield or arduino wifi shield

Cayenne (mydevices) APP supports all of the above Options

What is the easiest to implement? I have short time period and working on the mechanical design for the Project in the same time.

Your help is appreciated

# Answer
> 1 votes
The Arduino Uno and Arduino Ethernet are very simple to program, to connect it to the Internet.

I never used the Yun Arduino, but it seems a little bit harder.

# Answer
> 1 votes
If you want to stick with Arduino (instead of SBC), I suggest you use Arduino Yun.

The Linux side of the Yun will provide very much greater scope for web programming compared to Arduino+Ethernet shield. There also a bridge library to communicate with the Yun.

---
Tags: sensors, wifi, ethernet, servo, arduino-yun
---


title: Arduino Uno "Keyboard Not Found"

text:
# Question
Title: Arduino Uno "Keyboard Not Found"
This is my first script written with Arduino. I wrote a simple Hello World program but I'm getting the following error.

```
Test:18: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
   Keyboard.begin();
   ^
exit status 1
'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?

```

Here is the code:

```
#include "Keyboard.h"

void typeKey(int key)
{
  Keyboard.press(key);
  delay(50);
  Keyboard.release(key);
}

void setup()
{
  // Begining the Keyboard stream
  Keyboard.begin();

  // Wait 500ms
  delay(500);

  delay(400);

  Keyboard.print("Hello World!");

  // Ending stream
  Keyboard.end();
}

void loop() {}

```

I have `Arduino/Genuino UNO` selected as my board on the IDE. Any suggestions on how I can fix this? Thanks

# Answer
Based on the documentation :

> These core libraries allow a 32u4 based boards or Due and Zero board to appear as a native Mouse and/or Keyboard to a connected computer.

Core libraries (such as `Keyboard.h`) are not availabe if your board doesn't mentioned.

I don't know which one is right, since your question title mentioned "Arduino Micro" while at the end of your question, the board is "Arduino Uno".

Just for further information, Arduino Uno is based on - ATmega328P, and Arduino Micro is based on - ATmega32U4. So sure, that "hello world" program will works on Arduino Micro, but not on Arduino Uno.
> 4 votes

---
Tags: arduino-uno
---


# Question
Title: Can I avoid having a bootloader if I use ISP to flash to an arduino?
My Trinket Pro waits about 10 seconds upon booting before starting the program that I have loaded on it.

Can I avoid this delay and the bootloader taking up space if I flash my program directly to the Arduino with ArduinoISP?

# Answer
It looks like the Trinket Pro has an Atmega328P processor. You can change the fuses to not run the bootloader, in which case you don't need the space taken by it.

I have a hex uploader sketch which will upload a .hex file from an SD file directly to the chip, removing the need for a bootloader. Using ArduinoISP is another approach which will probably work. I'm not sure whether that fixes up the fuses for you.

If you just want to avoid the time (and not the space - the bootloader is probably only 512 bytes) you can use the sketch I linked to (without needing an SD card) to make fuse changes.

See Engbedded Atmel AVR® Fuse Calculator for fuse calculations. Basically you need to toggle the BOOTRST fuse (the low-order bit of the High fuse).
> 2 votes

---
Tags: bootloader, isp, arduinoisp
---


# Question
Title: Arduino not running the sketch with external power supply of 9v, but runs the program when connected to pc
Can anyone please help me figure out/ point the reason of this arduino problem? I uploaded a simple arduino sketch (blink an LED ) just to test if my real program was the reason of the "abnormality" of this board. It works fine when I connected it to PC via arduino cable, but doesn't run the program when I use an external power supply(9v) and connected it to the Vin pin of arduino.

Need help and hoping for fast replies. I will be having a competition tomorrow, this is very urgent. please guys.

for the schematic diagram, there are no other parts inserted to the arduino board, aside from the 9v battery. I was able to say that the program work on "LED blink" by observing the lights of "TX" LED on the board. please help me. :(

# Answer
TX LED is blinking because of communication (indicating data transmit via serial). It will not blink if there are **no communication from Arduino through USB cable**.

For simple observation, use LED\_BUILTIN pin. Its a build in-LED indicator on Arduino.

```
pinMode(LED_BUILTIN, OUTPUT);

```

then

```
digitalWrite(LED_BUILTIN, HIGH);
delay(500)
digitalWrite(LED_BUILTIN, LOW);
delay(500)

```

Arduino fail on external power supply is usually because of voltage drop or your system draw too much current.
> 1 votes

# Answer
There is a possibility that you blew the regulator circuit with too much current while supplying your Vin pin with the 9V source. This would depend on your system power draw; something that you were using the board with before the blinker program - and also what kind of board you have.

To check this, try another similar board with the blinker program and the same 9V source. Don't forget to make the changes as suggested in the previous answer. The other problem could be your power source: to check whether your power source supplies the desired volts, measure the power source terminal voltage while connected to the board. Most boards will have the minimum voltage requirement on Vin, depending on their regulator design.
> -1 votes

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


# Question
Title: Can anyone recommend a breadboard for the new Arduino 101?
I just got an Arduino 101 board. I was told that it's practically the same as the UNO. But have no experience using the UNO and I've only done super simple things on the 101 board without using a bread board.

What I want to do is have 2 servos connect to the board. I've only connected one servo without using a breadboard. I've looked on Instructables.com and other places that connect at least 2 to up most 12 servos. They all use different breadboards without specify if the brand, model, or if size even matters. I don't know how breadboards work and which holes I plug the wires into. Furthermore, I haven't found any videos on people working on the 101 board.

Next, I'm not sure if the servos will share the same volt port. There's only 3V and 5V on my Arduino 101 board. If they all need 5V, I'm not sure how to make both servos share. I don't know how they will share the same ground port as well. I know for sure, they will have their own analog port.

A list of recommendations would be nice. Thanks.

# Answer
A breadboard is nothing but a way to attach multiple wires to the same pins. There are many different kinds as can be seen in these images. There's no right or wrong when it comes to breadboards, as long as you have enough pins to prototype you should be good to go.
> 2 votes

# Answer
I agree to "A breadboard is nothing but a way to attach multiple wires to the same pins.", but just one recommendation for the breadboard. Don't buy the ones without the rails for voltage and ground, they are useful.
> 0 votes

---
Tags: arduino-uno, servo
---


# Question
Title: How to control an Arduino connected device accross the Internet?
Actually i am trying to do IoT based work.

Until now the sensed data(temperature and humidity) has been made available to only for one user on the Internet using Apache tomcat. So far we have just created a one way communication link between the sensor node and the Internet through the PC.

Now I need to control a device (say a fan) according to the variation with sensed temperature from anywhere through the internet. For the HTML I have used Java Script, which I am new to.

# Answer
Perhaps a message brokering service like MQTT is what you are looking for. Far too much to it to explain it all here, but basically it lets you publish messages and subscribe for messages, over a network.
> 2 votes

# Answer
If you are planning on keeping the Arduino connected to the PC then you are looking for help with your javascript, which isn't a question for this forum.

If you are looking at making the Arduino independent from the PC then you want to look at possible network options for the Arduino, ESP8266 shield, Mobile phone, C5100 (?).

Of course you might also want to look at using an ESP8266 rather than an Arduino and programming that through ArduinoIDE and using its web server rather than Apache. There are samples that would show you how to do this, you could get them without getting the hardware, but obviously they won't run.
> 1 votes

# Answer
How about this:

http://www.instructables.com/id/How-to-communicate-with-Arduino-using-HTML-Chrome/

But i also would prefer MQTT, but this requires Network connection for Arduino
> 0 votes

# Answer
> For the HTML i have used JAVA SCRIPT(but i am new to java)

You have to keep in mind Java is not the same as javascript.

I've once used my Raspberry Pi to communicate with my Arduino Uno. There is a library available to use on your RPi called PySerial, you can use Python on your Raspberry to listen to your Arduino output and store your values to a database for example. You can also use some Python scripts to send things over your serial connection to your Arduino, for example for your fan to start. You can build a web interface to read or view your data and to control your fan with Java or Javascript.

It may not be the most useful way to do it because you can use a Raspberry Pi as your main device but I've done it before and it is nice for learning purposes.

Good Luck!
> 0 votes

---
Tags: arduino-uno
---


title: Continuous Rotation

text:
# Question
Title: Continuous Rotation
I was wondering how can I make a Servo rotate continuously by using an Arduino code. I looked through several forums and websites already, but all of them just show how to make it run by changing the servo physically, I wanted to be able to do it with just the code.

Thanks for your help already!

# Answer
> 3 votes
The objective you seek will require a servo that has been manufactured to be continuously rotatable. The locations you've found are for those with extra servos who might not want to purchase a slightly more expensive servo and might want to use what they have on hand.

Once you have such a servo, self-modified or purchased as such, your code will work as you suggest. You should be able to easily locate the necessary code to operate a 360 degree servo using current libraries.

# Answer
> 0 votes
Normally, a servo is rotating 180 degrees because it has a drag inside on gears who stop rotating continuously (360 degrees). To make a servo to rotate 360 degrees, you need to buy a new servo or modify this one.

---
Tags: programming, motor, continuous-servo
---


# Question
Title: USB Communication like serial RS232 with an Attiny
Basically I want to use an Attiny running an Arduino boot loader as an usb device. I'm not sure how to even start or what phrases to search for.

So here's what I ultimately wish to do.

* Load a listener like that of an RS232 serial communication program
* trigger pin states based on received commands
* plug the Attiny directly into a windows environment USB port for communication.

I understand that this will require some kind of driver to do this but i don't know what. I do have experience with serial port communication using Visual Studio C# as well.

Assuming what I would like to do is possible, im looking for pointers in how to make the Attiny can be seen by windows.

# Answer
Generally there are (or could be many) USB Devices and (only one controlling) USB Host. The differences are discussed in this stackexchange.com question. Briefly, USB Hosts are usually very complex hardware and software devices that may know about many many different types of peripherals. They are usually only found on computers. USB Devices are usually dedicated peripherals. They only need to know about them selves. Many people do not realize that there are many protocols built into USB. These are normally called Device Classes. The USB Serial Protocol (or CDC) is one of dozens of Device Classes.

So, assuming you want a build a Serial Port USD Device, you would first need a processor with built in USB Device hardware. (There are likely some project out in the wild that have implemented this feature using software. It might be a good experience. But for practical purposes it is usually better to use hardware for this.) The next feature you need to implement is a software USB Device driver. This is not trivial. But is much simpler than the USB Host software. The next feature you need to implement the serial protocol inside the USB protocol.

In the real world, the USB code, even for a USB Device, is complex enough that most developers use the USB code provided by the processor manufacturer. This is very common as most manufacturers want you to use their hardware and provide the USB code for free. Here is Atmel's support page for CDC USB (serial port) support. (Of course, Atmel makes the processor found in most Arduino boards.)

Thus far this answer has been general and is likely difficult to implement in a practical sense. A more turn key solution is to use an existing platform which contains a USB CDC Device. The Arduino Uno comes in several versions. One has a USB CDC chip made by FTDI. Another has a 2nd processor programmed specifically to handle USB CDC type communications. Either version provides a USB CDC interface used for programming. I believe this web page explains how you can also use this port to communicate with your sketch.
> 1 votes

---
Tags: arduino-ide, usb, communication, attiny, rs232
---


title: Stepper motor release L298N

text:
# Question
Title: Stepper motor release L298N
I'm Driving a stepper using a L298N driver and an arduino mega. I want to release the stepper after the movement so it can swing freely, because it gets hot, and it doesn't need to hold position.

Anyone know how to do it? I'm using just the basic stepper library.

Thank you.

# Answer
Usually you should set Enable (A and B) pins on L298 to LOW, effectively turning off the driver.
> 0 votes

---
Tags: arduino-mega, stepper, l298n
---


title: Should I buy a retired Arduino?

text:
# Question
Title: Should I buy a retired Arduino?
I am a beginner who would like to buy an Arduino Yún (58 dollars).

It is retired so will I have any problem?

Else I can buy an Arduino Uno and an Arduino Yún Shield. But in this case I don't understand the difference between an **Arduino Uno + Arduino Yún Shield** and an **Arduino Uno + ESP8266 serial WIFI wireless module**.

Arduino Yún Shield: I can't find the price. I only found an Iduino.

ESP8266 serial WIFI wireless module: 7 dollars.

# Answer
When a board is retired, it may: \- get no support (never had support from Arduino zelf though) \- not be readily available.

Which may or may nog be a problem. The biggest problemen with retired boards is that they often didn't sell very well.

So they may: \- target niche applications. \- not have a lot of people post tutorials on it. \- not have/get elaborate answers on Arduino.se

I believe you should only get something that fits your needs. Usually you van get away with an Uno, and since there are millions if (beginner) tutorials, i'd pick that as my first Arduino.

If you want to do anything more "pc-like" like USB, camera or a "server", my first pick would be a raspberry pi. Also, since there are hundreds of tutorials. You can choose to do it with a yún, and it may work, but you should check if there are tutorials/documentation for whatever you'd like to do with it.
> 1 votes

# Answer
It is retired so will I have any problem?

It depends on what you want to do with your arduino. If you need a project that requires future support then dont buy a retired board. If you just want to do basic beginners stuff (like blinking LEDs, controlling motors, sending serial information wired or with an add on shield to send wireless information)-then any arduino can do these basic projects and probably at a cheaper price than 58 dollars.
> 2 votes

# Answer
The question of the Arduino Yun being retired can be answered here: http://www.arduino.org/forums/yun/retriered-boards-894?p=3495&hilit=Retired#p3495 At least regarding Arduino.org the answer is no. The Yun is **not** retired.
> 1 votes

---
Tags: arduino-uno, esp8266, wifi, shields, arduino-yun
---


# Question
Title: I need help purchasing materials for a arduino fpv quadcopter
I am an absolute noob in FPV quadcopters and quads in general. My aim is to create a simple quadcopter with a live video transmission. Based on my research I need:

* 4 rotors
* 4 Props
* 4 Electronic Speed Controllers
* Camera Kit
* Lipo battery
* Power Distribution Board
* Accel. and Gyro
* Arduino UNO
* Receiver Kit

Am I missing anything? and how would you wire it?

# Answer
**These are my suggestions.**

You don't need the following:

* Accel. (a gyro is enough)

---

You are missing the following:

* You need 2 sets of receiver/transmitter. One of them is for the controller, the other one, for video.
* You also need a screen or PFV goggles to display the received video.
* You need a frame.

---

Here is my suggestions for a couple of your parts.

* Buy a DIY Flame Wheel Kit. They should include : motors, ESCs, props and the frame itself.
* Get a GoPro Hero (original) for your camera. They're cheap and should give you good enough quality for a DIY quadcopter build.
* Use and Arduino Pro Mini, they are smaller. Note that you need an external FTDI programmer for it.
* Use at least a 3S lipo.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: ble_write slows down my sketch causing problems (Blend Micro & NRF8001)
I'm working on a prototype which uses the RedBearLabs Blend Micro with the NSC's nrf8001 ble chip, but have ran into a problem that I'm not sure how to solve.

I have two tactile buttons connected to the input pins on the Blend Micro, which are used to increase or decrease counters (integers) in my sketch that is in turn displayed on a OLED screen. When I use these buttons to manipulate the counter in offline mode (meaning that the bluetooth is not connected) I can repeatedly press the buttons very quickly and the counter is increased with every push - but when I connect to my phone and try to push the buttons with high frequency (\>1-2 per second) the program is not able to react to every button interaction, causing only every second or third click to be registered.

The only thing that I do differently when I am connected is that I'm sending 5 bytes using "ble\_write" (part of the RBL nrf8001 library), which seem to cause this delay resulting in missed clicks. Even sending one byte using "ble\_write(X)" seem to slow down the sketch so much that this phenomena occurs.

Do any of you had similar problems and possible ways to solve this? I've been considering batching clicks together until I reach a certain amount and then send them at all once - this however may risk that a button is being pressed at the same time as the ble\_write is executed, causing missed click.

Offline click looks like this:

```
if(digitalRead(A4)) {
while (digitalRead(A4)) {        }
offlineIn++;
localIn++;
totCount++;
sleepTimer = 0;
  }

```

And the online like this:

```
if (digitalRead(A4)) {
  while (digitalRead(A4)) {        }
  totCount++;
  localIn++;
  sleepTimer = 0;
  ble_write('0');
  ble_write('0');
  ble_write('0');
  ble_write('1');
  ble_write('1');
}

```

Thanks!

# Answer
> -1 votes
I've solved it by overclocking my blend micro to 16mhz (done in the Arduino IDE). Not a perfect solution but works. :)

---
Tags: bluetooth, code-optimization
---


# Question
Title: How to wire Christmas lights with LEDs to use for Arduino Project?
First things first, I am new here and this is my first post. So if this is in the wrong place I apologize and please just let me know.

I am a programmer that is getting into working with an Arduino compatible board, so my questions are 99% of the time with the hardware side and not the software side.

I just went through a tutorial on how to connect LEDs in parallel to a shift register so that I can control each LED individually.

My project goal is to make a Christmas house for a family member that will use some predefined songs to blink the lights to. So what I am actually looking for suggestions for is how to make a string of LEDs (5mm) that I can hook up to a small house without it looking messy. I was thinking I could maybe use 2 wires to run along the + and - of all the LEDs and then maybe there is some kind of connector I can use to split the 8 LEDs off to their respected hookups on the shift register.

Any good ways of doing this and keeping the metal unexposed?

I thank you in advance for your answers and your time!

# Answer
> 2 votes
Here is a string of Stripleds operated from a CPU 12V supply with built-in double-sided tape under the hand rail in one of my homes. Red downstairs and blue upstairs.

Now define your input and output attributes to modulate the current.

---
Tags: wires
---


# Question
Title: What boards have integrated USB charging?
I've been building wearables, using the adafruit trinket, which I love, its small size is easy to tuck away. But I hate having to unplug the battery to charge it every time. I wired in a SPDT switch, and a small USB charger, but it's kind of a cockamamie solution.

I've seen some devices with a battery adapter, and integrated USB charging, but they are larger, and harder to tuck away.

I don't need more than 4 IO ports, I'm just looking for a tiny microcontroller platform with integrated USB charging. I just saw the mkr1000 today, which looks decent, but is still larger than I would like. If you know of a product that meets this description, please let me know.

# Answer
> 2 votes
The Feather mainboards are fairly small and have integrated LiPo/Li-ion charging. They're not as small at the Trinket but if you don't need the space on the proto boards then you can examine the design files to see what can be cut away.

---
Tags: power, usb, adafruit, charging
---


title: Re-enable Arduino after short

text:
# Question
Title: Re-enable Arduino after short
I happened to short-circuit my Arduino by mistake. It was powered by USB on my Windows 7. The OS was so smart to pop-up warning about USB power surge and shut it down immediately. Arduino survived.

I fixed the circuit and connected it back. Arduino was powered again, but it was not recognized as COM port anymore. There was no unknown device in Device manager. I tried different USB connector on the same computer and it was found and it worked. But the other USB was out.

I restarted the computer and connected the Arduino back to the broken connector. The drivers were automatically reinstalled (I don't know why) and it worked again.

Is it possible to re-enable Arduino on the same USB connector without restart? I'd like to understand what happened on the computer side.

# Answer
> 1 votes
Most likely, your motherboard detected a over-current situation, and disabled power to that port. Since it has to way to know if the cause of the over-current has been fixed, it will continue to disable the port (since the only way to know would be to turn the power back on, and doing that to many times might cause permanent damage).

I wouldn't expect there to be a way to force your MoBo to reset the port, as this is an unlikely event. You should be glad the MoBo prevented any damage.

Using a different port sounds like an okay solution.

---
Tags: usb
---


# Question
Title: Library, instantiation of a class object
I am python experienced, an arduino noob, and absolutely no experience of C other than what has been forced upon me by arduino use.

I have just spent a day hammering google for the precise syntax of creating and using a class for user libraries, and have finally won.

However, I find that there are two forms that both seem to work for instantiating an object in the main program.

With my python experience, I find it easier to recognise the obj= style, used by Alan Zucconi in his examples, though the arduino.cc library tutorial on the Morse library uses the other form.

Is either preferrable, or are they equivalent in every way? Are there any subtle side effects of which I am unaware, that will bite me if the interfaces get more complicated, or some assumptions get corrected in future releases of the arduino IDE or compiler?

```
#include "Minimal_library.h"

// allocate buffer to be used
#define BUF_SIZE 40
char buff[BUF_SIZE+1];

// which of these two instantiation calls works?

// Minimal_library obj = Minimal_library(BUF_SIZE, buff);  //alanzucconi - works
Minimal_library obj(BUF_SIZE, buff);   //  Morse - that seems to work as well now
...

```

I presume that any private variables defined within the class become fully fledged persistent variables unique to the object created (it's been a long and frustrating day, not quite got around to testing the persistence or uniqueness yet, compiling without error, and then working, are enough for today!)

# Answer
The statement

```
Minimal_library obj(BUF_SIZE, buff);

```

means “create an object named `obj`, initialized by calling the class constructor with the supplied parameters”.

On the other hand,

```
Minimal_library obj = Minimal_library(BUF_SIZE, buff);

```

means “create an *unnamed* object initialized as before, then copy it into an object named `obj`, then delete the unnamed object”.

The compiler would normally optimize the second form into the first one. It is even allowed to do so in some weird cases where they may not be equivalent. In the end, it's mostly a matter of style. I prefer to do the optimization myself and write the first form. But if you find the second form more readable, go ahead: you can normally trust the compiler to optimize out the unneeded copy.
> 1 votes

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


# Question
Title: Unable to send serial data to XBee connected to Arduino Uno without a shield
So here are some pictures of the setup I have with an LED, 330 Ohm resistor, Arduino UNO, 2 XBee S1s, and many wires,

https://i.stack.imgur.com/QT1KF.jpg

For specifics, here is the wiring,

* XBee Pin 1 (VCC) is connected to Arduino Uno Pin 3.3V
* XBee Pin 2 is connected to Arduino Uno Pin 1 (TX)
* XBee Pin 3 is connected to Arduino Uno Pin 0 (RX)
* XBee Pin GND is connected to the minus column on the breadboard.
* Arduino Uno Digital Pin 9 is connected to a 330 ohm resistor which is connected to an LED that is connected to the minus column on the breadboard
* Arduino Uno Pin GND is connected to the minus column on the breadboard
* And lastly I have another XBee connected to my laptop through a USB dongle

I'm trying to send data in the form of bits through my computer using a program called XCTU to turn the LED on and off. Here is the code for the Arduino,

```
int led = 9;
int bufferSize = 100;
byte readBuffer[100];
byte lastByte = 0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  int toRead = Serial.available();
  if(toRead > 0){
    while(toRead > bufferSize){
      Serial.readBytes(readBuffer, bufferSize);
      toRead = toRead - bufferSize;
    }

    Serial.readBytes(readBuffer, toRead);
    lastByte = readBuffer[toRead - 1]; //reads last big in serial input

    if(lastByte == '1'){
      digitalWrite(led, HIGH);
    }
    else if(lastByte == '0'){
      digitalWrite(led, LOW);
    }
  }
  delay(250);
}

```

However, when I send a '0' through XCTU, the LED doesn't turn off. What could be causing this? Note that I did not use a shield to connect the XBee to the Arduino Uno, I soldered the pins to the appropriate spots because I thought it was possible after watching this video, https://www.youtube.com/watch?v=wtal7SWZek0

Also, I will be cross-posting this on arduino forums to get as much input on this as possible. I will update both topics frequently to attribute answerers for their input (https://forum.arduino.cc/index.php?topic=435027.msg2998240#msg2998240)

# Answer
So after experimenting with the SoftwareSerial library, it seemed that all the wiring was done correctly but the original code was replaced with,

```
#include "SoftwareSerial.h"

SoftwareSerial XBee(1, 0); //TX is 1, RX is 0 on the Arduino Uno
int LED = 9;

void setup()
{
  // Baud rate MUST match XBee settings (as set in XCTU)
  XBee.begin(9600);
  pinMode(LED, OUTPUT);
}

void loop()
{
  if (XBee.available())
  {
    byte c = XBee.read();
    if (c == '1')
    {
      digitalWrite(LED, HIGH);

    }
    else if (c == '0')
    {
      digitalWrite(LED, LOW);
    }
  }
  delay(150);
}

```

and I am now able to turn an LED on or off with data sent from XCTU.

**Note:** I forgot to include this in my question but some configuration details were that the XBees I was working with were "XBee 1mW Wire Antenna - Series 1 (802.15.4)". Settings for each XBee configured in XCTU include,

Baud Rate: 9600

Data Bits: 8

Stop Bits: 1

no Parity nor flow control

Channel and Pan ID were identical across both XBees

For the XBee connected to the laptop, DH = 0, DL = 2, MY = 1, and CE = Coordinator\[1\]

For the XBee connected to the Arduino Uno, DH = 0, DL = 1, MY = 2, and CE = End Device\[0\]

\*Credit to user PaulS on the arduino forum for helping me out.
> 0 votes

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


# Question
Title: Problem with connecting pins on an Arduino board with an L239D shield
I have an L239D motor shield just like the Adafruit motor shield. I had a question in my mind. While making a robot, I could not connect my pins from various sensors in Arduino as the motor shield is already fitted on the board. So how can I connect my pins?

PS: I have the same board as shown in the picture

# Answer
> 1 votes
That's a common problem that has many solutions.

The cheapest way is to solder the wires directly as many comments said. Though this is quite dirty, it should work for you.

The more professional way is to use these Arduino stackable header. They can even let you have a shield on top of your shield. This is the best choice in my opinion.

---
Tags: arduino-uno, shields, arduino-motor-shield
---