# Question
Title: Issue while connecting ESP8266 with Arduino Mega. It always says “Module have no response.”
I am having Issue while connecting ESP8266 with Arduino Mega. It always says "Module have no response."

Please check and correct me if I am wrong anywhere.

I am using below code and and wiring diagram is

My Code:

```
//#include <SoftwareSerial.h>
   //use mega Serial 2 for serial monitor; Serial 1 on pins 19 (RX) and 18 (TX);// Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX).
   #define SSID "SopraSteria"
   #define PASS "1234567890"
   #define DST_IP "220.181.111.85" //baidu.com
   //SoftwareSerial dbgSerial(10, 11); // RX, TX
   void setup()
   {
     // Open serial communications and wait for port to open:
     //serial 2 is to esp8266
     Serial2.begin(115200);//9600 (mine), 57600, 115200
     Serial2.setTimeout(2000);

     //serial 0 is to usb
     Serial.begin(115200);

     while(!Serial);
     while(!Serial2);

     //dbgSerial.begin(9600); //can't be faster than 19200 for softserial
     //dbgSerial.println("ESP8266 Demo");
     Serial.println("ESP8266 Demo on Mega2560");

    while(Serial2.available()>0)
    Serial2.read();

     delay(1000);
       //test if the module is ready
     Serial2.println("AT+RST");
     //delay(1000);
     //delay(1000);
     Serial.println("Resetting module");
     Serial2.flush();
     //Serial.println(Serial2.read());
     //if(Serial2.find("ready"))
     if(Serial2.find("Ready")||Serial2.find("ready"))
     {
       //dbgSerial.println("Module is ready");
       Serial.println("Module is ready");
     }
     else
     {
       //dbgSerial.println("Module have no response.");
       Serial.println("Module have no response.");
       //while(1);
     }
     delay(1000);
     //connect to the wifi
     boolean connected=false;
     for(int i=0;i<5;i++)
     {
       if(connectWiFi())
       {
         connected = true;
         break;
       }
     }
     if (!connected){
      //while(1);
      Serial.println("Not Connected.");
     }
     delay(1000);
     //print the ip addr

   Serial2.println("AT+CIFSR");
     Serial.println("ip address:");
     while (Serial2.available())
     Serial.write(Serial2.read());

     //set the single connection mode
     Serial2.println("AT+CIPMUX=0");
   }
   void loop()
   {
    //connectWiFi();
     String cmd = "AT+CIPSTART=\"TCP\",\"";
     cmd += DST_IP;
     cmd += "\",80";
     Serial2.println(cmd);
     Serial.println(cmd);
     Serial.println(cmd);
     if(Serial2.find("Error")) return;
     cmd = "GET / HTTP/1.0\r\n\r\n";
     Serial2.print("AT+CIPSEND=");
     Serial2.println(cmd.length());
     if(Serial2.find(">"))
     {
       //dbgSerial.print(">");
       Serial.print(">");
       }else
       {
         Serial2.println("AT+CIPCLOSE");
         //dbgSerial.println("connect timeout");
         Serial.println("connect timeout");
         delay(1000);
         return;
       }
       Serial2.print(cmd);
       delay(2000);
       //Serial.find("+IPD");
       while (Serial2.available())
       {
         char c = Serial2.read();
         //dbgSerial.write(c);
         Serial.write(c);
         //if(c=='\r') dbgSerial.print('\n');
         if(c=='\r') Serial.print('\n');
       }
       //dbgSerial.println("====");
       Serial.println("====");
       delay(1000);
     }
     boolean connectWiFi()
     {
       Serial2.println("AT+CWMODE=1");
       String cmd="AT+CWJAP=\"";
       cmd+=SSID;
       cmd+="\",\"";
       cmd+=PASS;
       cmd+="\"";
       //dbgSerial.println(cmd);
       Serial2.println(cmd);
       Serial.println(cmd);
       delay(2000);
       if(Serial2.find("OK"))
       {
         //dbgSerial.println("OK, Connected to WiFi.");
         Serial.println("OK, Connected to WiFi.");
         return true;
         }else
         {
           //dbgSerial.println("Can not connect to the WiFi.");
           Serial.println("Can not connect to the WiFi.");
           return false;
         }
       }

```

# Answer
Your transmitter and receiver pins need to be crossed, rx-\>tx and tx-\>rx. As a mnemonic, the two ends of the antenna point to the board edge with the receiver pin and it is that pin that needs the voltage divider. While you're at it, it would be a good idea to tie the RST pin high, as well as the CH\_PD. I use one 10K pullup for both.

Recent versions of these boards are shipped with their baud rates set to 115200. Since you're using a hardware UART on the Mega board, you can send/receive to it at that rate.

*Note to readers using a software UART (SoftwareSerial): First thing, change the board's baud rate to 9600 and communicate with it at that rate. You can use SoftwareSerial to make the change as it sends at 115200 reasonably reliably, but its receive function can't keep up at that rate).*

You can confirm your connections and baud rate with:
`EspSerial.println("AT");`
You should receive \`OK' in reply.
> 1 votes

# Answer
I took your code as a starting point and got it to work with some small modifications. I am providing my version below for your review. I had to add a bunch of delays. I am also communicating with the ESP8266 at 19200 baud.

I have not optimized the timing yet but I was able to run this code for 24 hours straight with no issues. I am using Pins 6 and 7 on the Arduino for COMM to the ESP8266.

```
#include <SoftwareSerial.h>
#define SSID "YOURSSID"
#define PASS "YOURPW"
#define DST_IP "220.181.111.85"

SoftwareSerial Serial2(6, 7); // RX, TX

void setup() {

// Open serial communications w ESP8266
Serial2.begin(19200);
Serial2.setTimeout(5000);

// serial 0 is to usb
Serial.begin(115200);
while(!Serial);
while(!Serial2);

Serial.println("ESP8266 Demo on Mega2560");

while (Serial2.available() > 0)
Serial2.read();
delay(1000);
while (Serial2.available() > 0)
Serial2.read();

//test if the module is ready
Serial.println("RESETTING ESP8266 WIFI CHIP");
Serial2.write("AT+RST\r\n");
delay(2500);
while (Serial2.available() > 0)
Serial.write(Serial2.read());

delay(2500);
while (Serial2.available() > 0)
Serial.write(Serial2.read());
Serial.println("");

//  connect to the wifi
boolean connected=false;
for(int i=0;i<5;i++) {
if(connectWiFi())
{
connected = true;
break;
}
}

if (!connected){
Serial.println("Not Connected.");
}

Serial2.println("AT+CIFSR");
delay(2000);
while (Serial2.available())
Serial.write(Serial2.read());
delay(2000);
while (Serial2.available())
Serial.write(Serial2.read());

//  set the single connection mode
Serial2.println("AT+CIPMUX=0");
delay(2000);
while (Serial2.available())
Serial.write(Serial2.read());
delay(2000);
while (Serial2.available())
Serial.write(Serial2.read());
}

void loop() {

String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += DST_IP;
cmd += "\",80";
Serial2.println(cmd);
Serial.println(cmd);
delay(5000);

if(Serial2.find("Error")) return;

cmd="GET / HTTP/1.0\r\n\r\n";
Serial2.print("AT+CIPSEND=");
Serial2.println(cmd.length());
delay(2000);

if(Serial2.find(">"))      {
Serial.print(">");
}
else {
Serial2.println("AT+CIPCLOSE");
Serial.println("connect timeout");
delay(2000);
return;
}
Serial2.print(cmd);
delay(2500);

while (Serial2.available()) {
char c = Serial2.read();
Serial.write(c);;
if(c=='\r') Serial.print('\n');
delay(5);
}

Serial.println("");
Serial.println("====");
delay(2000);
}

boolean connectWiFi() {

String cmd;
int iIP;

iIP = 0;
Serial2.println("AT+CWMODE=1");
delay(5000);
while (Serial2.available())
Serial.write(Serial2.read());

cmd="AT+CWJAP=\"";
cmd+=SSID;
cmd+="\",\"";
cmd+=PASS;
cmd+="\"";

Serial2.println(cmd);

delay(2000);
Serial.println("Line 1");
while (Serial2.available() > 0)
Serial.write(Serial2.read());

delay(2000);
Serial.println("Line 2");
while (Serial2.available() > 0)
Serial.write(Serial2.read());
if (Serial2.find("OK")) {
Serial.println("WIFI OK was received!");
iIP = 1;
}

if( iIP == 1 ) {
Serial.println("OK, Connected to WiFi.");
return true;
}
else  {
Serial.println("Can not connect to the WiFi.");
return false;
}

}

```
> 0 votes

# Answer
As shown in the Fritzing diagram, you have connected the ESP8266 to the Mega's Serial1 pins (18 and 19), but in the program, you try to interact with Serial2 (pins 16 an 17). For this to work, your wiring and your program must match.
> -1 votes

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


# Question
Title: Cheapest way to change digital output source
Powering at 5 volts, atmega328 output ~4.7 volts. I need to output between 12 and 24 volts @ 2 amp. I'm currently using relay but they are costly. Is there a way to do it with transistors or any thing cheaper?

Thanks

# Answer
As @Gerben said in the comments, I would also recommend an N-channel MOSFET. OnSemi has a great application note on how to determine what type of MOSFET you would need based on your given load requirements and how to use it as a switch. You can find that app note here.

The basic idea is to provide an enable signal from your atmega328 to the gate of the MOSFET to drive it into saturation or to turn it off. You would connect your 12/24V supply to the drain of the MOSFET and connect your load to the source of the MOSFET. The basic circuit can be seen in the application note.

Hope that helps!
> 2 votes

---
Tags: atmega328, digital
---


# Question
Title: Yikes! Invalid device signature. Fail to burn bootloader and read fuses
I know this problem is kinda common but I had to post it anyway.

Before anything, I would like to inform you guys that I changed the fuse of my Arduino Pro 3v3 @ 8MHz to allow 1.8 V brownout and also programmed CKDIV8 AND CLKOUT. In other words, the fuse configuration is this: E:FE, H:DA, L:3F.

The programmer is the Arduino 2009 running as ISP programmer. The target is Arduino Pro Mini 3V3 @ 8Mhz.

I also used a 0.1uF cap between reset and ground in the Arduino programmer.

After a good time using the Arduino Pro without problems, some random problems began to appear when I tried to upload a program with the programmer (Arduino as ISP). So I tried to burn the bootloader again and the following message appeared ""avrdude: Yikes! Invalid device signature."

The same occurs when I try to communicate with avrdude using this command "avrdude -c arduino -p m328p -P COM3 -b 19200 -v".

Some tests I did:

* Continuity test directly at uC pins between those signals: SCK, MISO, MOSI, (/SS - /RESET). No problem good connection.
* Verified the clock in XTAL1 and XTAL2. No problem 8MHz.
* Verified the clock in CKOUT (Arduino Pro pin 2) and measured 1MHz.
* I also tried to delay the avrdude using -B5, B10 and another values. With a quick search on Google some people are saying that those delays don't work with the Arduino as ISP.
* I used some sketches for slow clocks, which I don't remember, and no luck.
* External power and no luck again.

What am I missing? Do I need to change something to communicate with Arduino Pro running at 1MHz?

# Answer
If you are burning the bootloader through the IDE it won't expect the CKDIV8 fuse to be set.

I have a bootloader programmer which you could use to reprogram the bootloader. You just need another Arduino (eg. Uno, Mega) and connect 6 wires between each of them like this:

The sketch for programming the bootloader is available on Github:

https://github.com/nickgammon/arduino\_sketches

You want the one in the "Atmega\_Board\_Programmer" subdirectory.
> 1 votes

---
Tags: bootloader, arduino-pro-mini, arduinoisp
---


# Question
Title: Why does Serial.print print out the wrong thing?
I am using a flame sensor. I am reading the state and then printing it. Here is my code:

```
void loop(){
 flameState = digitalRead(flamePin);//variables already defined and are global
existsFire();//calls the void
delay(1000);
}

void existsFire(){

Serial.println("Flame: " + flameState);

}

```

Before, this printed out the right thing. Today, it was printing out "lame:". The "F" and the flameState were missing. I changed it to:

```
void existsFire(){

Serial.print("Flame: ");
Serial.println(flameState);

}

```

Everything worked fine. Is there a problem with my Arduino Mega. What do I need to do to fix this?

# Answer
> 5 votes
You've stumbled across the difference in the C++ language between a `String` and an "array of characters". What you gave `Serial.println()` was an array of characters:

```
Serial.println("Flame: "...);

```

and then tried to add a number to it.

```
Serial.println("Flame: " + flameState);

```

If it had have been a `String`, then what you typed would have been fine:

```
String flame = "Flame: ";
Serial.println(flame + flameState);

```

Adding (literally `+`) a number to a `String` adds characters to the `String` to represent the number. Unfortunately you didn't start with a `String`, you started with an array of characters:

```
"Flame: "

```

Adding a number to THAT changes where the array starts. `flameState` must have been `1`, and `"Flame: " + 1` would have been `"lame :"` \- as you found out!

The version that worked did so through a little bit of magic:

```
Serial.print("Flame: ");
Serial.println(flameState);

```

The first line called a version of `print()` that accepted an array of characters and printed each of them out. The second line called a *different* version of `println()` that accepted a number and printed out its representation as a series of characters (digits) - followed by a new line (the `ln` part of the name).

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


title: Write to EEPROM during power down

text:
# Question
Title: Write to EEPROM during power down
I am making a counting device, and I would like to be ensure that the count is not lost if the power is lost. As I need to count to many millions I cannot use EEPROM writes as I will trash the nvm after ripping through the 100,000 max write cycles. I also need to ensure the count is accurate, so can't update 'every-so-often' either.

I want to write to EEPROM when the Arduino detects power down. I am reading on an Analogue input pin and am then planning on using a capacitor to hold the power on to complete the write. I have this set up but am having issues testing as I have found that when Ground is connected to GND pins and then when 5v is supplied to any I/O pin the device powers up. I have now tested a Nano and Uno and have found the same thing on both.

I have looked through the arduino site and tried looking for forums where this has been discussed, but to no avail.

Is this damaging to the Arduino if powered in this way? Does this pass the sanity check as a way of achieving my main objective of not loosing the count on power down?

thanks in advance :)

# Answer
A more sophisticated version of @MikaelPatel's techique is not to store the individual counts, but to store a derivative:

1. Reserve a block of storage with (say) 8 counters. Each counter has as many bits as necessary to store the largest value - but see below for what "largest" means.
2. Each time the count goes up, write into the next counter along (modulo the number of counters).
3. But don't write the value of the counter, write the value divided by the number of counters - `counter/8`.
4. Here's the trick: while that looks like you're losing precision, you're not - because the counter location is information too! In fact you're *gaining* size.

It's best shown with an example. For ease, I'll assume an 8-bit counter, and only 8 counters:

```
0000: 03 03 03 03 03 02 02 02

```

Assuming that everything started at `00`, that means that it took 8 counts for them all to get to `01`, a further 8 counts for them all to get to `02`, and only 5 counts to get the first 5 to `03`. That's a total of `8+8+5` or `21`.

At boot time, look for where the number sequence goes down. That's your current buffer position for future updates, plus the information for the current value:

```
CurrentCount = [Smaller number] * [Number counters] + [Number of larger];

```

Once you've worked it out, keep the current value for incrementing, and the buffer pointer for where to store the next count.

### Advantages:

A. You write as often as you would storing a counter - but in different locations, spreading the load.
B. Each location (8, 16 or 32 bits) can store a certain maximum - but the total maximum is a factor of `Number of Counters` larger than that!

Odometer manufacturers use this exact technique to store the current mileage in digital dashboards - they have a legal requirement to maintain the correct number. They only use 16-bit counters (which would overflow after 65,535 miles), but then they use 16 counters, for a total mileage maximum of over a million. Each location only gets written every 16 miles, and they don't need to use 32-bit locations.
> 3 votes

# Answer
I would suggest powering it from the 12V input and monitor the 12V with a power supply monitoring chip or circuit which will send an interrupt to your system when the voltage drops to whatever voltage you design it for. This can be accomplished with a few resistors and a comparator.

Your hold up time will be controlled by the amount of capacitance on the 12V side. When the interrupt is tripped write the value to EEPROM and then shut down.

The analog input is a good sounding idea but there is a lot of latency between the time the voltage starts to fail and is detected. The hardware interrupt will be much faster giving you more time to save your counter and the additional capacitance on the 12V side will give you a lot more time then back feeding through the GPIO pins..
> 1 votes

# Answer
A typical method of increasing the number of writes to EEPROM is to use a vector of counters instead of a single value. The counter value is written to the EEPROM vector in a cyclic fashion.

On startup the vector is searched for current counter value, i.e. the highest counter in the vector. The write index is restored by locating the lowest counter value.

The number of writes is increased with the length of the vector.

Please read more about this method here.
> 1 votes

# Answer
The arduino chips have clamping diodes on all the GPIO pins. So if the voltage on one of the pins is above Vcc (which is 0v is there is no power applied to the chip), the internal diode will 'redirect' this voltage to the Vcc line. This will damage the chip, is too much current is going through the clamping diodes.

Instead, connect the 5v signal via a large resistor (e.g. 100k) to the input pin.

Using a capacitor (plus diode to prevent backfeeding) will work. You just have to be careful if you have connected anything to an output pin that uses current. An led running at 20mA will drain a charged capacitor pretty quickly.

What I've done in the past is use the entire EEPROM space to store a single value. Just write every next value to a higher address. On powerup read the entire EEPROM till you find two adjacent address that don't contain successive numbers. Then you know where the last written value was, and you can read this last value, and continue writing the the address right after that one.
> 0 votes

---
Tags: power, eeprom
---


title: Shift Register w/ Internal Pullups?

text:
# Question
Title: Shift Register w/ Internal Pullups?
Is there a chip that is just a parallel in / serial out shift register but with integrated internal pullups?

I could use a full-blown I/O expander but I really just need more momentary button inputs. I don't need outputs and I would rather not bother adding resistors or with writing commands to initialize the chip.

# Answer
> 3 votes
Logic integrated circuits such as shift registers normally do not contain pull up resistors on their input(s). This is because they are normally connected to a totem pole driver. Such a driver eliminates the need to avoid floating inputs.

Also, pull up resistors require current when the input is driven toward the opposite power rail. Even though adding internal pull up resistors may not change the overall behavior of the chip, designers will avoid parts if they unnecessarily add to the over all power demand.

Based on your comments and your question, consider an old ps/2 keyboard. It is essentially a switch matrix with a built in decoder chip which may fullfill your requirements. The chip scans the switch matrix, debounces the switches and converts button presses & button releases into a serial stream of data.

Added later...

Here is a description about connecting a ps/2 keyboard to an Arduino. Included are schematics, code examples and supporting library.

(USB keyboards are not well suited for this purpose as they require a USB Host. As most Arduinos do not have this, a USB Host shield is required.)

---
Tags: pull-up
---


# Question
Title: Is it possible to use a USB camera with Arduino?
It is necessary to recognize the motion and record video live.

**Update**
Save enough on your memory card.

***PS****
Maybe I'll repeat the question, but I am not guided in English.
Sorry for my English*.

# Answer
> 1 votes
An Arduino is not a powerful processor and can not do much image processing. I doubt that there is a USB camera that could be connected to the Arduino.

There are a range of OVO cameras that can connect to the Arduino, but I don't think you will be able to record live video on an Arduino with these, where would you store the file for starters?

There is a PIXY camera system, this has its own microprocessor and interfaces with an Arduino. It can record video and do object recognition. http://charmedlabs.com/default/pixy-cmucam5/

Hope that helps.

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


title: SD Card Info Unexpected

text:
# Question
Title: SD Card Info Unexpected
So I have just begun testing my Wireless SD Shield from Arduino with my Arduino UNO. Upon running my the basic CardInfo sketch, it uploads and displays data, but far more than expected. The SD Card is entirely empty, as in, if I plug it into my computer, there are no files on it. However, this is the Serial Monitor Output I receive:

The reason I have included screenshots rather than copy and pasting the output, is that if I try and copy and paste, it does not copy all of the Files Found on the card, it only copies the first 8 lines.

Any help would be greatly, appreciated!

This code does not compile for me and gives me an avrdude error which I believe is due in some part to the above pictures:

```
//Program by Jeremy Blum
//www.jeremyblum.com
//SD Card Demonstration
//Based on Example by Tom Igoe

#include <SD.h>

//Set by default for the SD Card Library
//MOSI = Pin 11
//MISO = Pin 12
//SCLK = PIN 13
//We always need to set the CS Pin
int CS_pin = 4;

void setup()
{
  Serial.begin(9600);
  Serial.println("Initializing Card");
  //CS Pin is an output
  pinMode(CS_pin, OUTPUT);

  if (!SD.begin(CS_pin))
  {
      Serial.println("Card Failure");
      return;
  }
  Serial.println("Card Ready");

}

void loop()
{
  String dataString = "Hello";

  //Open a file to write to
  //Only one file can be open at a time

  File dataFile = SD.open("log.txt", FILE_WRITE);
  if (dataFile)
  {
    dataFile.println(dataString);
    dataFile.close();
    Serial.println(dataString);
  }
  else
  {
    Serial.println("Couldn't open log file");
  }
  delay(5000);
}

```

Whereas, this code does:

```
#include <SD.h>         //SD Card Library
#include <Wire.h>       //I2C Library
#include <DallasTemperature.h>
#include <OneWire.h>

OneWire oneWire(2); // initiate pin connected to DS18B20
DallasTemperature sensors(&oneWire); // pass oneWire as parameter to Dallas Temp. library

//SPI SD Card Pins
  //MOSI = Pin 11
  //MISO = Pin 12
  //SCLK = PIN 13
  int CS_pin = 4;
//  int pow_pin = 8;

//Light Sensor Pins
  int light_pin = 0;

float refresh_rate = 500;  //Dataloger Refresh Rate
float id = 0;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  sensors.begin(); // initiate the sensors on the DS18B20
  Serial.println("Initializing Card");
  //CS Pin is an output
  pinMode(CS_pin, OUTPUT);

//  //SD Card will Draw Power from Pin 8, so set it high
//  pinMode(pow_pin, OUTPUT);
//  digitalWrite(pow_pin, HIGH);

  //Initialize Card
  if (!SD.begin(CS_pin))
  {
      Serial.println("Card Failure");
      return;
  }
  Serial.println("Card Ready");

  //Write Log File Header
  File logFile = SD.open("LOG.csv", FILE_WRITE);
  if (logFile)
  {
    logFile.println(", , , ,"); //Just a leading blank line, incase there was previous data
    String header = "ID, Light, Temp";
    logFile.println(header);
    logFile.close();
    Serial.println(header);
  }
  else
  {
    Serial.println("Couldn't open log file");
  }

}

void loop()
{
  //Check Light Level
  int light_level = analogRead(light_pin); //Write the value of the photoresistor to the serial monitor.

  //Read Temperature
  sensors.requestTemperatures(); // request the temperatures from the DS18B20, does not actually do anything simple sets it up
  float currentTemp; // initialize variable to store and hold current temperature readings
  currentTemp = sensors.getTempCByIndex(0); // go and get temperature in Celcius for the first temp probe, temperature probe 0 (could have more than one sensor here if wanted)

  Serial.print("Temperature = ");
  Serial.print(currentTemp); // prints actual temperature and starts new line
  Serial.print(" Celcius ");
  /* Serial.print((char)223); print degree symbol in LCD format */
//  Serial.println("C");

  //Create Data string for storing to SD card
  //We will use CSV Format
  String dataString = String(id) + ", " + String(light_level) + ", " + String(currentTemp);

  //Open a file to write to
  //Only one file can be open at a time
  File logFile = SD.open("LOG.csv", FILE_WRITE);
  if (logFile)
  {
    logFile.println(dataString);
    logFile.close();
    Serial.println(dataString);
  }
  else
  {
    Serial.println("Couldn't open log file");
  }

  //Increment ID number
  id++;

  delay(refresh_rate);
}

```

Both sketches are quite different, so I reccomend just looking at the intial void setup() part of each if you want to read through them.

# Answer
Joy of tech... It's full file table, with old, deleted entries appearing as current files. You can nuke it with a quick or slow format, but the problem will return later. I don't know this shield, but there must be some problem with the code - it really shouldn't show deleted entries. Try another library, or google for problems with your current lib.
> 1 votes

# Answer
They are Mac's OS X "Spotlight" hidden indexing files. This answer shows how to turn it off.
> 1 votes

---
Tags: arduino-uno, serial, sd-card
---


# Question
Title: How to get readings on serial monitor in every 10s?
I am doing my final year project and here I am attaching the code I am using. According to the code, I will get the sensor output in serial monitor. But I want to get reading once n 10ms. Since serial monitor can't work with that resolution, I need to save the reading in an array and then output the array in serial monitor or any other way. Please help me in modifying the code.

The code is as follows:

```
/*
   The circuit:
  * VCC connection of the sensor attached to +5V
  * GND connection of the sensor attached to ground
  * TRIG connection of the sensor attached to digital pin 2
  * ECHO connection of the sensor attached to digital pin 4
 */

const int trigPin = 2;
const int echoPin = 4;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop()
{
  long duration, cm;

  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  cm = microsecondsToCentimeters(duration);

  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(100);
}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}

```

# Answer
There is one fundamental error with your code that I feel I should point out - one that I see time and time again.

The basic structure of your code is:

* Forever:
    + Send a ping
    + Wait for the pong
    + Print the result
    + Delay for 100ms (or whatever time you choose)

And you expect to get a result every (delay) milliseconds.

However, you won't. What you will actually get is a result *every so often*, where that time is defined as 100ms + the time to send and receive a ping.

So if it takes 11.6ms (200cm, the limit of most pin sensors) to receive the pong, then you also delay for 100ms, you're going to end up with 111.6ms between each print. It's even worse if the pong never arrives back - then `pulseIn()` will wait for up to a second before returning. You can, of course, reduce that to say 15ms by adding the timeout parameter as per the manual

When you reduce your printing delay to just 10ms you actually run the risk of delaying for more than double the time you expect to (21.6ms instead of 10ms).

Instead you need to use `millis()` to check to see *if it is time to print something* so that it doesn't matter how long the pong took to arrive, as long as that never exceeds the amount of time you want between prints, otherwise it's going to get delayed regardless.
> 2 votes

# Answer
Yeah it shouldn't be an issue, remember `delay(time`) is a millisecond command, so if you want to get a reading every 10ms, simply put `delay(10)`, and **not** `delay(100)`. Like the comment above mentions, you should have no problem with a 9600 baud rate serial monitor link showing data every 10ms.

Also, I would highly reccomend checking out the NewPing library (https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home) which is an update library for the ultrasonic distance sensor which I assume you are using based off your code. With that, you can send up to 30 "pings" per second, so if the above solution doesn't fix it for you, this definitely should.
> 0 votes

---
Tags: arduino-mega, sensors
---


title: Engine Speed Control Observation

text:
# Question
Title: Engine Speed Control Observation
I am using an Arduino Mega to control the speed of an internal combustion engine.

The speed is sensed via a Variable Reluctance Sensor (VRS) on the crankshaft. This signal is then converted into a 5V square wave which is feed into Interupt 2 (Pin 21) on the Arduino.

The flywheel of the engine, onto which the VRS is sensing has one tooth. Therefore one square wave blip (from 5v to 0V) as it is passing it and then back up to 5v. The interupt that this is attached to increases a counter by 1. The time taken for the counter to reach 20 is recorded. I want to use this speed reading value in a PID algorithm which then in turn actuates a servo.

This methodology was sucessfully used in a very similar engine with a 22 toothed flywheel but is not working on this engine with 1 tooth.

The problem is the speed reading - the values that I am recording for the time taken for 20 revs ( in micro seconds), and displayed on the serial terminal is wrong and I do not know why. The numbers printed are all mulitples of one another e.g. 440960,551200,661440,771680 which all divide into one another with an even fraction. The correct reading here is 661440, this has been verified with observation of the square wave input through and oscilloscope.

I cannot find why!

I have attached the code here

# Answer
> 1 votes
Your methodology there is somewhat flawed. Not only will you never see that Counter1 \>= 20 (since you immediately set it to 0 before returning the count), but if you never get a pulse (engine is stalled) you'll never reach 20 pulses anyway.

A better method is to reverse everything and instead of timing how long it takes to get 20 pulses, count the number of pulses you get in a pre-defined time period.

Your interrupt remains the same, counting each pulse as it arrives, but you then sit and watch the clock (using `millis()`) and when a certain (to be decided by you) time has elapsed (the *sample time*) you record the pulse count and reset it to 0. You then have a number of rotations per time period.

If you set that time period to be 1 second (the simplest) then you immediately have the number of rotations per second.

```
void loop() {
    static uint32_t ts = millis();
    uint32_t pulses;

    if (millis() - ts >= 1000) {
        ts += 1000;
        uint8_t sr = SREG;
        noInterrupts();
        pulses = Counter1;
        Counter1 = 0;
        SREG = sr;
        Serial.print(pulses);
        Serial.println(" revolutions per second");
    }
}

```

Decreasing the sample time means you can respond faster, but you are working with smaller numbers and hence less accuracy. For instance, setting it to 100ms instead of 1 second you need to multiply your count by 10 to get the current pulses per second. It all depends on how fast your engine runs as to what a good sample time would be.

---
Tags: arduino-mega, sensors, isr
---


title: MQTT for GSM/GPRS sheild

text:
# Question
Title: MQTT for GSM/GPRS sheild
I want to publish sensor data to server using MQTT protocol via GPRS/GSM modem.

I googled MQTT for Arduino, AQTT Arduino available only for Ethernet shield or will MQTT Arduino Ethernet shield work in GSM modem?

# Answer
> 1 votes
Nick O'leary published an MQTT client for Arduino. I use it extensively. You can find it here: http://knolleary.net/arduino-client-for-mqtt/.
Once you have established a tcpip connection you can use this library to send/receive via the MQTT protocol across a GPRS/GSM modem. I have used it successfully on:

* the Arduino GSM shield
* the Seeeduino GPRS IoT panel
* a Freetronics Arduino Mega connecting via ethernet to a TPLink MR3020 router

# Answer
> 1 votes
Arduino MQTT Library for SIM800 (and SIM900) GSM Modem is available at ElementzTechBlog, ElementzGithubRepository

**Functionalities:**

**Auto connect**

* Automatically connect to TCP and to MQTT server.

**connect function**

* This function can be used to connect your client to MQTT broker.
* Use only if you do not use Auto connect functionality.
* Optionally you can use username, password, WILL topic and WILL Message.

**OnConnect CallBack function**

* This call back function is called when MQTT connection is established.
* You can call subscription and publish functions inside it (according to your need).

**publish function** \- This function can be used to publish messages to different topics.

* You can select QoS levels and RETAIN flag according to your need.

**subscribe function**

* This function can be used to subscribe messages from different topics.

**OnMessage CallBack function**

* This callback function is called when messages are received from subscribed topics
* Topic, TopicLength, Message, MessageLength are the arguments of OnMessage callback function.
* Inside this, you can write your custom code.

**unsubscribe function**

* This function can be used to unsubscribe from a previously subscribed topic.

**disconnect function**

* This function can be used to disconnect your client from MQTT broker.

**Keep Alive**

* You can specify your KeepAlive duration while initializing.
* Ping requests are sent and received automatically.

**Subscribe Publish examples are also provided.**

# Answer
> 0 votes
MQTT is an TCP/IP protocol. MQTT-SN is for wireless serial and is slightly different but you can bridge the two. Since you can establish a TCP/IP session over GSM, I would expect that functionality would not be duplicated in any way by MQTT, but would instead depend on your GSM hardware providing the TCP layer.

And the final comment, I doubt if you would ever see this on an Arduino. Simple alternative, use a common smartphone as a wifi hot spot, done.

---
Tags: programming
---


# Question
Title: Arduino Micro Cannot get Interrupt 6 work on PIN 7
After finding out about the situation with pin7 from this tutorial:

https://forum.sparkfun.com/viewtopic.php?f=32&t=35847

```
    void setup(){

    EICRB |= (1<<ISC60)|(0<<ISC61); // sets the interrupt type for EICRB (INT6).
                                  // EICRA sets interrupt type for INT0...3

    /*
    ISCn0  ISCn1   Where n is the interrupt. 0 for 0, etc
      0      0   Triggers on low level
      1      0   Triggers on edge
      0      1   Triggers on falling edge
      1      1   Triggers on rising edge
    */
EIMSK |= (1<<INT6); // activates the interrupt. 6 for 6, etc

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

ISR(INT6_vect) {
  // interrupt code goes here
  }

```

I have set:

```
EICRB |= (0<<ISC60)|(0<<ISC61);

```

Because I need it to be triggered on LOW.

I could still not get it work on the micro. IF I use the pin as regular input pin I can clearly see LOW/HIGHs on pin 7 with digitalread.

I have a sensor attached there which goes LOW in case it is triggered.

I wonder if anybody knows what else can I try to get it work. I already hardwired everything in my circuit board, there are no more free interrupts and no way to change them.

# Answer
I've used following code and loopback from pin 8 to pin 7:

```
// loopback:  pin 8 -> pin 7

void setup() {
  pinMode(7, INPUT_PULLUP);
  pinMode(8, OUTPUT);
  pinMode(LED_BUILTIN_TX, OUTPUT); // to see pin 8 logic level on TX led
  pinMode(LED_BUILTIN, OUTPUT); // toggled by ISR

  EICRB |= _BV(ISC60);  // Triggers on edge
  EIMSK |= _BV(INT6);   // activates the interrupt
}

ISR(INT6_vect) {
  PINC = _BV(PC7);  // toggle led 13 (@ PC7)
}

void loop() {
  digitalWrite(8, HIGH);
  digitalWrite(LED_BUILTIN_TX, HIGH);

  delay(500);
  digitalWrite(8, LOW);
  digitalWrite(LED_BUILTIN_TX, LOW);
  delay(500);

}

```

And it works perfectly. Only problem I can imagine is to figure out correctly which pin is really 7 as label is on the right side of pin (not under nor left).
> 1 votes

---
Tags: arduino-micro
---


title: Array deletion problem

text:
# Question
Title: Array deletion problem
I am a bit confused about how memory works in Arduino. I have created an integer array like so:

```
int* arr = new int[3] {1, 2, 3};

```

When I go to delete it:

```
delete[] arr;

```

The first element is deleted, and all the remaining ones are still present and accessible.

```
Serial.println(arr[0]); // prints 0
Serial.println(arr[1]); // prints 2
Serial.println(arr[2]); // prints 3

```

# Answer
First of all: it is not a good idea to do dynamic memory maagement in embedded systems (in casu arduino)
Secondly freeing memory means: marking the memory as available. It does not mean "setting the memory to 0"
because `ar` still points to the same locaton in memory it is "normal" that it also still reads the old values. Only -according to the C CP0P0 pàrogramming rules- you should not do so. Reading will not cause problems but writing will very likely.
> 1 votes

# Answer
It is not a good idea to use dynamic memory in such a small devices in general.

And delete doesn't mean setting values to something at all. It's just returning allocated memory back ("to system" is not correct term here as there is no system).

You should try to use objects with some action in constructor and destructor (like printing values).

For example:

```
class test {
public:
  test(int _i):i{_i} { Serial.print("test:"); Serial.println(i); }
  ~test() { Serial.print("~test:"); Serial.println(i); }
  int i;
};

void setup() {
  Serial.begin(57600);
  test * arr = new test[3] {4,6,9};
  delete[] arr;

}

void loop() {
}

```

prints:

```
test:4
test:6
test:9
~test:9
~test:6
~test:4

```
> 0 votes

# Answer
Deleting `new`ed memory only informs the system that you are no longer using it and releasing it for re-assignment. The pointer still points to memory containing your array but that memory is no longer reserved for you. You could, in theory, go on using it, but another `new` might well reassign it for another use and the data that was in it would likely get over-written.

It would be good form to zero your pointer (`arr = (int *)0;`). It accomplishes several things:

* Your code clearly reminds you that the pointer is no longer usable;
* Your code clearly informs the next reader that the pointer is no longer usable;
* An attempt to use the pointer is quite likely to fail immediately (depends on the envrionment's ability to trap attempted accesses to location 0). The alternative is your code may work anyway - until someday that memory actually *does* get re-assigned and suddenly, code that has worked "forever", breaks, and in a non-obvious way. Save yourself or the guy or gal who follows you some grief, and make it a habit to zero your pointers once they are no longer valid.
> 0 votes

---
Tags: memory-usage
---


# Question
Title: Bizarre transistor behavior and voltage with DC motor in simple circuit
I started a new motor related project recently with a new Arduino Uno, beginning with several tutorial circuits included in the Vilros Arduino guide. The circuit in question is #10, a simple DC motor circuit with a transistor switch (https://i.stack.imgur.com/KLC0K.jpg). The Arduino is being powered for the moment via USB.

The circuit, completed according to the diagram/common sense, does not work. The voltage across the transistor base is clearly not sufficient to activate the switch with the motor in the circuit. 5V (more like 4.6V) from Pin 13 is running across a 330 ohm resistor to the transistor base, but there is no current between the collector and the base. Bypassing the collector/base gap with a piece of metal will complete the circuit and activate the motor.

For some reason, the transistor *will* switch properly when the motor is replaced by a simple LED. *AND*, switching the cable from Pin 13 to the +5V out is enough to activate the transistor switch. I was under the impression that the transistor should only require .7V above the common grounded element.

But, even more bizarrely, with a cable running from +5V to the transistor base (through a resistor), a voltmeter across the DC motor is reading a potential difference of anywhere from 9V to 1702V (see https://i.stack.imgur.com/mwFKp.jpg, yes, with 4 digits). The multimeter is otherwise working normally, so I don't see a good explanation. Is the Arduino pin just incapable of providing sufficient current/voltage to activate the transistor, or am I missing something obvious. And does anyone have some idea why the voltmeter is reading so high and fluctuating so wildly? It is curious that the Arduino disconnects from the PC whenever the circuit is completed with the motor in it, so the Arduino likely is overdrawing from the USB.

The transistor included was not the one listed, but a common MPS2222A.

Thanks

# Answer
There is nothing wrong with the circuit (although drawn in a bizarre method). Your understanding of how a transistor works is mistaken - forget voltage - transistors are controlled by current.

Most likely you have connected the transistor incorrectly.

The voltage reading is due to back EMF. If you used an analog meter it would give the reading you expect.

In all likelihood you have damaged the transistor.
> 1 votes

# Answer
According to second image transistor seems to be connected in oposite direction (switched Collector with Emitter). It means common collector configuration is used instead common emitter and it's usually not enough to drive motor. And C-E can handle only about 10V Max (more or less, depends on transistor) even if it could handle much more in oposite direction.

See link for more details:

> * Common Base Configuration – has Voltage Gain but no Current Gain.
> * Common Emitter Configuration – has both Current and Voltage Gain.
> * Common Collector Configuration – has Current Gain but no Voltage Gain.

I've just tested this circuit an it must be powered by power jack. USB is not strong enough.
> 1 votes

---
Tags: arduino-uno, motor, transistor
---


title: Difficulty with shifting data

text:
# Question
Title: Difficulty with shifting data
Im trying to shift LEDs using 595 register. Using SN74HC595N registers. Im using 4 of the registers as i got alots of LEDs to shift. My code for shifting doesn't seem working.. i can shift some with 2 registers but not 4 registers

```
// include the library code:
#include <LiquidCrystal.h>
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;

// initialize the library with the numbers of the interface pins
// RS-12, E-13, D4-8, D5-9, D6-10, D7-11
LiquidCrystal lcd(12, 13, 8, 9, 10, 11);

int row[]={8,9,10,11};// Digital output connect directly to all rows
int col[] = {A0,A1,A2}; // Analog input with 10K pull-up to 5V.
int i,j; // Two counter variables to count inside for loop
int col_scan; // Variable to hold value of scanned columns

//Pin connected to ST_CP of 74HC595
int latchPin = 3;
//Pin connected to SH_CP of 74HC595
int clockPin = 4;
////Pin connected to DS of 74HC595
int dataPin = 5;

//holder for infromation you're going to pass to shifting function
byte data = 0;
byte data1 = 0x55;
byte data2 = 0xAA;

void setup()
{
  Wire.begin();
  RTC.begin();
  Serial.begin(9600);
  for(i=0;i<=3;i++)
  {
    pinMode(row[i],OUTPUT);
    //pinMode(col[i],INPUT);
    //digitalWrite(col[i],HIGH);
  }

  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Medicine Box");

  //set pins to output because they are addressed in the main loop
  pinMode(latchPin, OUTPUT);

  if (! RTC.isrunning())
  {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }

  for (i=0;i<=4; i++)
  {
    digitalWrite(latchPin, 0);
    shiftOut(dataPin, clockPin, data1);
    shiftOut(dataPin, clockPin, data1);
    digitalWrite(latchPin, 1);
    delay(500);
    digitalWrite(latchPin, 0);
    shiftOut(dataPin, clockPin, data2);
    shiftOut(dataPin, clockPin, data2);
    digitalWrite(latchPin, 1);
    delay(500);
  }
}

void loop()
{

  DateTime now = RTC.now();
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  //lcd.print(millis() / 1000);
  //Serial.println(now);
  //Serial.print("    ");
   /*   Serial.print(now.day(), DEC);
      Serial.print('/');
      Serial.print(now.month(), DEC);
      Serial.print('/');
      Serial.print(now.year(), DEC);
      Serial.print(' ');
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println(" ");*/

      lcd.print(now.day(), DEC);
      lcd.print('/');
      lcd.print(now.month(), DEC);
      lcd.print('/');
      lcd.print(now.year()-2000, DEC);
      lcd.print(' ');
      if (now.hour()<10)
        lcd.print('0');
      lcd.print(now.hour(), DEC);
      lcd.print(':');
      if (now.minute()<10)
        lcd.print('0');
      lcd.print(now.minute(), DEC);
      lcd.print(':');
      if (now.second()<10)
        lcd.print('0');
      lcd.print(now.second(), DEC);
      //lcd.println(" ");

  for(i=0; i<=3; i++)
  {
    digitalWrite(row[0],HIGH);
    digitalWrite(row[1],HIGH);
    digitalWrite(row[2],HIGH);
    digitalWrite(row[3],HIGH);
    digitalWrite(row[i],LOW);

    for(j=0; j<=2; j++)
    {
      col_scan=analogRead(col[j]);
      if(col_scan < 1000)
      {
        while(analogRead(col[j])< 1000);
        keypress(i,j);
      }
    }
  }
  digitalWrite(latchPin, 0);
  shiftOut(dataPin, clockPin, data1);
  shiftOut(dataPin, clockPin, data1);
  digitalWrite(latchPin, 1);
}

void keypress(int i, int j)
{
  if(i==0&&j==0)
    Serial.println("1");
  else if(i==0&&j==1)
    Serial.println("2");
  else if(i==0&&j==2)
    Serial.println("3");
  else if(i==0&&j==3)
    Serial.println("A");
  else if(i==1&&j==0)
    Serial.println("4");
  else if(i==1&&j==1)
    Serial.println("5");
  else if(i==1&&j==2)
    Serial.println("6");
  else if(i==1&&j==3)
    Serial.println("B");
  else if(i==2&&j==0)
    Serial.println("7");
  else if(i==2&&j==1)
    Serial.println("8");
  else if(i==2&&j==2)
    Serial.println("9");
  else if(i==2&&j==3)
    Serial.println("C");
  else if(i==3&&j==0)
    Serial.println("*");
  else if(i==3&&j==1)
    Serial.println("0");
  else if(i==3&&j==2)
    Serial.println("#");
  else if(i==3&&j==3)
    Serial.println("D");
}

// the heart of the program
void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
  // This shifts 8 bits out MSB first,
  //on the rising edge of the clock,
  //clock idles low

  //internal function setup
  int i=0;
  int pinState;
  pinMode(myClockPin, OUTPUT);
  pinMode(myDataPin, OUTPUT);

  //clear everything out just in case to
  //prepare shift register for bit shifting
  digitalWrite(myDataPin, 0);
  digitalWrite(myClockPin, 0);

  //for each bit in the byte myDataOut�
  //NOTICE THAT WE ARE COUNTING DOWN in our for loop
  //This means that %00000001 or "1" will go through such
  //that it will be pin Q0 that lights.
  for (i=7; i>=0; i--)  {
    digitalWrite(myClockPin, 0);

    //if the value passed to myDataOut and a bitmask result
    // true then... so if we are at i=6 and our value is
    // %11010100 it would the code compares it to %01000000
    // and proceeds to set pinState to 1.
    if ( myDataOut & (1<<i) ) {
      pinState= 1;
    }
    else {
      pinState= 0;
    }

    //Sets the pin to HIGH or LOW depending on pinState
    digitalWrite(myDataPin, pinState);
    //register shifts bits on upstroke of clock pin
    digitalWrite(myClockPin, 1);
    //zero the data pin after shift to prevent bleed through
    digitalWrite(myDataPin, 0);
  }

  //stop shifting
  digitalWrite(myClockPin, 0);
}

```

# Answer
Your code looks unnecessarily convoluted for merely sending data to a shift register. You can use the SPI hardware for that.

For example:

```
#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

void loop ()
{
  digitalWrite (LATCH, LOW);
  SPI.transfer (0xAB);
  SPI.transfer (0xCD);
  SPI.transfer (0xEF);
  SPI.transfer (0x42);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop

```

You have to use the SPI hardware pins for this to work. On a Uno these are:

* Chip pin 14 (DS) goes to MOSI (D11)
* Chip pin 11 (SH) goes to SCK (D13)
* Chip pin 12 (ST) goes to SS (D10) (or any other pin by changing LATCH)

Example wiring:

More details on my page about the 595 chip.
> 1 votes

---
Tags: arduino-uno
---


title: Send button press over RF

text:
# Question
Title: Send button press over RF
I'm trying to send a button press over RF (performing a closed circuit operation on the receiving end).

I have a controller with an UP and DOWN button. Unfortunately I am limited to the cable length, and would like to extend it with radio frequency. The controller has one cable for GND and one each for the corresponding UP and DOWN buttons.

The RF units is the typical 433mhz bought online (ebay).

Can I in someway send the signal over RF (directly on the data pin of the transmitter) without hooking it up to a microcontroller (Arduino)?

# Answer
> 1 votes
No. You need a micro-controller at both the sending, and receiving sides.

eBay does set RF remotes with a few buttons. This might be easier and cheaper than making your own.

---
Tags: electronics, rf
---


# Question
Title: Can I use a PIR sensor to turn on an arduino?
I'd like to use a PIR sensor (HC-SR501) to control the power to an Arduino Uno. Note that I'm not talking about using a PIR sensor as input to the Arduino and sensing the output pin from the PIR, I'm talking about using the output pin from the PIR to turn the Arduino itself on and off.

Hooking it up directly doesn't seem to work as I'm guessing the PIR doesn't handle that much current output. Would I use a transistor of some kind to do this?

My reason for wanting to do this is simple, power preservation. The PIR uses so little current when it doesn't sense anything that I thought it would be nice for something like a mailbox sensor that doesn't need to run that often. Thanks.

# Answer
Yes you can.

It all depends on how you are turning the power on. You sensor needs to flip a 'switch' rather than actually power the Arduino directly. (I'm sure you know that but just in case).

So you need a normally open relay in between you power source and you Arduino. Normally open because you don't want it powered unless you 'turn it on'. Your relay might be able to be switched by your PIR sensor's data output, but if you need more current then you are going to have to use a transistor and draw more power from the power source.

You have the PIR sensor, so now find the relay capable of carrying the maximum current you need for the Arduino.
> 1 votes

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


title: Adding Date and Time to existing sketch

text:
# Question
Title: Adding Date and Time to existing sketch
I am currently **trying to add a clock functionality to my current sketch** for a peristaltic pump \[run by NEMA 23\].

*The current sketch waits for a button on my breadboard to be pressed, it then runs the motor for a specified amount of steps and then stops and waits for the next press of the button*. It also displays the amount of steps to the Serial Monitor. I have a working sketch for a clock using an RTC DS3231 module and have unsuccessfuly attempted to fit it into my motor sketch. **The problem is, the clock seems to be taking precedent over the rest of my sketch, so pressing the button no longer works and the time is simply consistently output onto the Serial Monitor.**

***The ideal functionality would be the time and date displayed on LCD constantly (or at least blinking so rapidly that one could not tell the difference) with the number of button presses displayed under it, changing in value only when a button is pressed.***

Attatched find my code, it is really quite simple, and thank you so much for the time and help.

```
#include <Bounce2.h>
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <Wire.h>       //I2C Library
#include <OneWire.h>
#define DS3231_I2C_ADDRESS 0x68

AccelStepper stepper(1, 9, 8); // initiate stepper motor

LiquidCrystal lcd(6, 7, 5, 4, 3, 2);

int pos = 0; // variable to store position
int buttonPresses = 0;

const byte ButtonPin = 10;
const byte LedPin = 13; // for debugging and visualization

unsigned long ledOnTimer = 0;

const unsigned int ledPeriod = 3000;

Bounce button;

void setup() {
  Wire.begin();
  Serial.begin(9600);
  lcd.begin(16, 2);
  button.attach(ButtonPin);
  pinMode(LedPin, OUTPUT);
  stepper.setMaxSpeed(4000);
  stepper.setSpeed(2000);
  stepper.setCurrentPosition(0);
}

byte bcdToDec(byte val)  {
  // Convert binary coded decimal to normal decimal numbers
  return ( (val / 16 * 10) + (val % 16) );
}

void loop() {
  motor();
  printDate();
}

void motor() { // functioning motor sketch by itself

  //if led is on
  if (digitalRead(LedPin)) {
    stepper.runToNewPosition(21000); //about 420 steps per 10 mL
    digitalWrite(LedPin, LOW);
    // }
  }

  //if led is off
  else {
    button.update();
    if (button.fell()) { // if the button "fell" from a value from HIGH to LOW (so now it is off)
      stepper.setCurrentPosition(0);
      digitalWrite(LedPin, HIGH);
      buttonPresses++; // count presses of button and print to monitor
      lcd.clear();
      Serial.print("Number of Button ");
      lcd.setCursor(0, 1);
      Serial.print("Presses = ");
      Serial.println(buttonPresses);
    }
  }
}

void printDate() { //functioning time sketch by itself

  // Reset the register pointer
  Wire.beginTransmission(DS3231_I2C_ADDRESS);

  byte zero = 0x00;
  Wire.write(zero);
  Wire.endTransmission();

  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);

  int second = bcdToDec(Wire.read());
  int minute = bcdToDec(Wire.read());
  int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
  int weekDay = bcdToDec(Wire.read()); //0-6 -> sunday - Saturday
  int monthDay = bcdToDec(Wire.read());
  int month = bcdToDec(Wire.read());
  int year = bcdToDec(Wire.read());

  //  print the date EG   3/1/11 23:59:59
  Serial.print(month);
  Serial.print("/");
  Serial.print(monthDay);
  Serial.print("/");
  Serial.print(year);
  Serial.print(" ");
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.println(second);
}

```

Last note: Everything compiles, and I will change "Serial" to "lcd" after I finish debugging the sketch, so that is why everything is currently beign sent to the Serial Monitor.

# Answer
Even if you want to display time with the seconds showing, you don't need to check the time on the RTC continiously. Once a second should be enough. You can use a timer interrupt that triggers an ISR(Interrupt Service Routine) every second to do that check for you. This will free a lot of time which your arduino can use to do other stuff.

Same goes for your button(s): you can use an External Interrupt (INT) or a Pin Change Interrupt (PCINT) for them. This way the arduino will only look at them when they are pushed (and/or released).

If you combine those two interrupts (for the clock and the button), your arduino will have a lot of spare time. This is especially handy if you later want to expand your project with more buttons and motors.
> 1 votes

# Answer
I think you need to look at using interrupts.

The printDate function is quite processor intensive with all the Wire and Serial.print calls, it will be taking the majority of the time in each loop(). Whilst in printDate it won't be looking at the state of the button, so you have to press at just the right time.

If you place an interrupt on the button's pin I think you will get a more responsive system. Another thing that you could look at it only reading the clock once a second, this could be done with a timer interrupt.
> 1 votes

# Answer
Attaching interrupt (PIN change or LEVEL change) to the push button would work fine. You can trigger a flag and the flag should access the controller to run motor() function.
> 0 votes

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


title: Xbee not activate on arduino micro

text:
# Question
Title: Xbee not activate on arduino micro
I have 2 nodes: one is a PC+arduino mega+xbee the other one is arduino micro+xbee. The 2 xbees are communicating fine, I have tested this with 2 separate arduinos. My problem is that when the second xbee hooked up to the micro it seems it does not try to send or receive data from the serial lines. It is connected to the first RX/TX pins in proper order (RX-\>Tx, Tx-\>Rx) on the micro.

This is obvious for me because if I start my program's setup section on the ardu with:

```
void setup()

{
  Serial.begin(9600);
  while (!Serial);

```

The whole main program won't be running because the serial just never gets ready only if I plug my PC in.

When I try to send data from the PC-\>micro through xbee I see the Xbee receives it (led goes on the board) but nothing happens on the micro.

The micro right now is set to periodically send some debug data through the serial, I don't get that back either otherwise I would see the serial TX led on the micro blinking that it is sending the data. It only works when the PC is connected through USB.

Do I need some additional code for the xbee or is it require a hardware modification? I use a 5V-3V ttl converter as an extra hardware.

# Answer
> 1 votes
It is probably because you are using the only Serial to communicate to both the devices - your PC and XBee. At any instant, you can communicate to only one device. So you might need an extra serial to get you go.

And, may be due to this conflict you can see TX led blinking. May be it's communicating with anyone of them, and the other one is receiving garbage.

# Answer
> 0 votes
From your description, it kind of hard to figure out which arduino doesn't react. Maybe a picture would help.

If it is the arduino that is connected to the PC then the problem is that the serial connection is already used to talk to te PC and therefore can't be used to talk to the XBee. you'll need to use one of the other serial connections on the atmega (serial1, 2 or 3)

Mind you that you don't need a microcontroller to connect an XBee to the PC. A simple UART to USB converter is enough.

---
Tags: wireless, xbee
---


# Question
Title: Large values are changed by Arduino when viewing with `Serial.print()`
**Why are (big) values being changed?**

I tried out printing some values and noticed bigger values are changed more, they seem to be rounded to quarters and then to halves when the value gets bigger.

**MWE**

```
void setup() {
  Serial.begin(9600);
  Serial.print("12457591.51 is changed into ");
  Serial.println(12457591.51);
  Serial.print("2457591.80 is changed into ");
  Serial.println(2457591.80);
  Serial.print("1234567.89 is changed into ");
  Serial.println(1234567.89);
}

void loop() {}

```

gives me

```
12457591.51 is changed into 12457592.00
2457591.80 is changed into 2457591.75
1234567.89 is changed into 1234567.87

```

I'm working with an Arduino Nano ATMega328.

**Background** I need the calculation `(2457591.33 + 0.5 - 2440588) * 60 * 60 * 24` to be precise to within preferably a hundred, but currently it's off by about `7000`.

# Answer
Floating point numbers doesn't have infinite precision. But you can always change your equation to use smaller numbers (preferably integers or longs as floating point is extremely slow)

For example on AVR Freaks they mentioned precision about 6 or 7 digits. It makes sense as 24bits signed number range is from -8388608 to 8388607
> 1 votes

---
Tags: variables
---


# Question
Title: Should I control each of the four robot wheel separately or wire two from each side together?
I am making a remote controlled Arduino robot. I has 4 DC motors for wheels. I have 2 motor drivers available that control two dc motors each. I was wondering what the downsides are of wiring 2 dc motors together. The DC motors are 6v and the maximum current per channel of my motor driver is 1.2A which should be plenty for the motors. The motor driver that I am using can be found here. Each motor is getting controlled using a PWM signal. The DC motors are controlled separately.

# Answer
it looks like you have two channels on each controller, so you have some options here. but first I'm going to talk a bit about your motors. If you have a spec sheet for them you can gather most of this info through that, but it doesn't hurt to do some experimentation. A motor will draw max current when it is stalled (is trying to drive but it can't), and you can determine this "stall current" with a multimeter or from the spec sheet. when you're driving the robot, this can occur when you drive up to a wall and try to push through the wall (hint, no robot this size will damage a well built wall) but likely the driver will reach a wall and stop driving (unless she can't see the robot while driving, idk). the lowest current it will draw (aside from zero when it can't...) is it's "free speed" current, this is when it's spinning as fast as it can with no load on it. while you're driving the robot you can expect the current to be between these numbers, if you want to get super fancy (and you want to equip your robot to do this) you could log the instantaneous current every 10ms or however often (this can be useful if you want to diagnose faults, but again its a small robot)... so if you have two motors in parallel (which you want to do because in series one will drive harder than the other), then the current drawn by each will add, so you can double it for two motors.

anyways, here's a few options for the motor configuration:

if two of your motors in parallel draw less than continuous 1.2 amps, you could use a single controller for one robot, controlling left wheels on channel 0 and right on channel 1.

if your motors draw more than that in parallel, you will have to use two channels per side, however you could Y the PWM lines between the motor controller and the arduino

if you are using something like omni wheels and want control over every single wheel, obviously you will want one channel per wheel...
> 1 votes

---
Tags: arduino-mega, motor, arduino-motor-shield, robotics, remote-control
---


# Question
Title: is the Arduino shield pinout a standard, so that any Arduino shield can work with any Arduino board
I'm new to Arduino and dying to delve in.

There are lots of Arduino base board vendors, and lots of shield vendors.

In general, should I be able to plug any shield into any Arduino board, even with existing shields?

# Answer
No, they are not standard - not entirely - although there have been some attempts to make them more standard.

Some things to watch out for:

* SPI
    + The Uno originally had SPI on pins 10-13
    + The Mega had it on another COMMS header instead

SPI has now been standardized to the 6-pin ICSP header, though not all shields honour that, and still use pins 10-13 instead, so they won't work on boards like the Mega

* I2C
    + The Uno has I2C on pins A4/A5
    + The Mega has it on the COMMS header instead

I2C has now been standardized on a special pair of pins added to the end of the digital IO header (pins 8-13 + GND + AREF) though many shields still look for it on pins A4/A5, so they won't work on boards like the Mega

Some other boards, like the Leonardo, also have these (and other) functions on other pins, so may not work with some shields that don't use the SPI / I2C headers.

The basic functions, though, i.e., digital IO and analog inputs and UART 1 are all in the same places on the majority of boards, and most have PWM in the same places too. But you can't rely on any thing more than that between any two boards.
> 1 votes

# Answer
Most shields will fit most of the "regular sized" boards. the obvious exception is the boards like the nano which are tiny. Shields are going to have the best compatibility with the Uno, just because that one is the most common, so if you are going to get one arduino and a bunch of shields, get an uno. Some shields (the gen 1 ethernet and wifi shields in particular had an issue where they could not be used on Megas because the mega listens to SPI on pins 50+ which simply were not connected to the shield, however most of the newer shields will connect to the 6-pin block in the center now-adays to allow Mega usage.

The next thing you want to look at is if you are stacking shields, if they will collide on pin usage (SPI gets around this through multiplexing) and some of the 3.3 volt devices may have conflicts with 5-volt shields. Although the 3.3v devices do provide 5v power-out pins in the same locations as the Uno, it becomes more of an issue with trying to read a 5v on a 3.3v pin, which could damage the microchip.

the best thing to do is to check the documentation of the shields and check which pins they use, what voltages they need/supply, and comparing this with the particular arduino you are using.
> 1 votes

---
Tags: arduino-uno, shields, pins
---


# Question
Title: Who makes this cool Arduino display shield, and what model is it?
Anyone recognize Mfgr/model of this display that reads: "Wireless Internet Of Things". The Arduino board is a WIOT.

I've been looking and looking for a source for Arduino display like this, but cannot find.

# Answer
That will be an SSD1306 based blue OLED display with SPI interface. There's lots of them around by lots of different people. Some are I2C interface, and some of those have a "broken" I2C interface that doesn't send ACKs (especially cheap ones on eBay) and need a special ACK-less Software I2C implementation.

The SPI ones, of course, won't suffer from that problem.

They are generally 0.96" diagonal, and that one, I think, is 96x39 pixels (or it may be 128x64).
> 3 votes

---
Tags: lcd, shields
---


title: Send sensor information to processing

text:
# Question
Title: Send sensor information to processing
I am currently working on an Arduino project where the Arduino will send data to a processing program via bluetooth and processing will draw the data. However, my code doesn't seem to work.

Here is my Arduino code:

```
#include <SoftwareSerial.h>

int bluetoothTx = 1;
int bluetoothRx = 0;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

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

void loop() {
  Serial.println("Hello");
}

```

And here is my Processing code:

```
import processing.serial.*;
Serial myPort;

void setup() {
  myPort = new Serial(this, "COM42", 9600);
  myPort.bufferUntil('\n');
}

void serialEvent( Serial myPort) {
  String data = myPort.readStringUntil('\n');
  println(data);
}

```

I identified that the incoming port from the HC-05 module is "COM42" from my Bluetooth settings. I am expecting to see several "Hello" lines being printed on the processing console but this does not happen

# Answer
Your whole sending program is a complete mess, sorry to say:

First you create a SoftwareSerial port using the HardwareSerial pins. (Why on earth would you do that?)

Then you "begin" that SoftwareSerial port.

Finally you try and print `Hello` through the **HardwareSerial** port!

Either use SoftwareSerial **OR** use the hardware UART. You can't mix and match both. And since you are using the hardware UART pins, why even consider using SoftwareSerial?

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

void loop() {
    Serial.println("Hello");
}

```

**OR, to use *other pins than 0 and 1*:**

```
#include <SoftwareSerial.h>

const int bluetoothTx = 2;
const int bluetoothRx = 3;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

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

void loop() {
    bluetooth.println("Hello");
}

```
> 1 votes

---
Tags: arduino-uno, serial, bluetooth, datalogging, processing-lang
---


title: 4 channel Remote Control

text:
# Question
Title: 4 channel Remote Control
I'm trying to make a 4 channel RC using Arduino and nrf24L01 module. I already know how to deal with this module, but the question is "What does 4 channel mean ?", and how to make it supports 4 channel ?

# Answer
4 channel means having the ability to send 4 individual values (maybe speeds?) at once.

Since the nRF24L01+ is a packet based system it is as simple as sending the different "channels" as different bytes (or groups of bytes if more than 0-255 or -128 to +127 is needed).

For instance, if you want 4 channels that can represent 0-255 then you need 4 bytes, and so you can set both sender and receiver to have a packet size of 4 bytes (for efficiency) and send a packet made up of the 4 channel values.

If you want to represent numbers bigger than that then you need to split the variable into bytes (two bytes for an int, 4 for a long) or create a `struct` to represent your packet of data. Of course you then need the sender and receiver to be set to a packet size *at least* big enough to contain the data, and both ends must agree on the packet size.
> 2 votes

---
Tags: arduino-uno, wireless
---


# Question
Title: Help me restructure code for multitasking Neopixel + IR remote + arduino
First of all, I'm completely new to both arduino, and programing. Second, as for a good newbie, i'm trying to build a fairly complicated project. So, any help and suggestion is welcome. The goal is: light up a shelf, with 2x 1m led strip, with 2 different "fire" animation. And remote control the arduino to switch between effects and colors.

The state of the project so far https://circuits.io/circuits/2459366-arduino-ir-with-neopixel

I learned one arduino is not enough to decode IR signals and drive led strips. So, I'm using two. Successfully merged 2 sketches: one, that receives, decodes and sends the IR signal to another arduino.

And based on tutorial https://learn.adafruit.com/multi-tasking-the-arduino-part-3/put-it-all-together-dot-dot-dot

I managed to control the LEDs via IR remote control. Here is code currently using (a bit bloated since its contains all the effect from the tutorial.)

Here is code so far:

```
#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#define I2C_SLAVE_ADDRESS 8

// Remote control button codes
const unsigned int BUTTON_1 = 0xFD08F7;
const unsigned int BUTTON_2 = 0xFD8877;
const unsigned int BUTTON_3 = 0xFD48B7;
const unsigned int BUTTON_4 = 0xFD28D7;
const unsigned int BUTTON_5 = 0xFDA857;
const unsigned int BUTTON_6 = 0xFD6897;
const unsigned int BUTTON_7 = 0xFD18E7;
const unsigned int BUTTON_8 = 0xFD9867;
const unsigned int BUTTON_9 = 0xFD58A7;
const unsigned int BUTTON_UP = 0xFD50AF;
const unsigned int BUTTON_DOWN = 0xFD10EF;
const unsigned int BUTTON_VOL = 0xFD906F;

int t = 0; // variable for switching led rings with the remote
int b = 255; // brigtness starting value
// IR received code
unsigned int irCode = 0;            //ir code ends here
// Pattern types supported:
enum  pattern { NONE, RAINBOW_CYCLE, THEATER_CHASE, COLOR_WIPE, SCANNER, FADE, FIRE };
// Patern directions supported:
enum  direction { FORWARD, REVERSE };

// NeoPattern Class - derived from the Adafruit_NeoPixel class
class NeoPatterns : public Adafruit_NeoPixel
{
    public:

    // Member Variables:
    pattern  ActivePattern;  // which pattern is running
    direction Direction;     // direction to run the pattern

    unsigned long Interval;   // milliseconds between updates
    unsigned long lastUpdate; // last update of position

    uint32_t Color1, Color2;  // What colors are in use
    uint16_t TotalSteps;  // total number of steps in the pattern
    uint16_t Index;  // current step within the pattern

    void (*OnComplete)();  // Callback on completion of pattern

    // Constructor - calls base-class constructor to initialize strip
    NeoPatterns(uint16_t pixels, uint8_t pin, uint8_t type, void (*callback)())
    :Adafruit_NeoPixel(pixels, pin, type)
    {
        OnComplete = callback;
    }

    // Update the pattern
    void Update()
    {
        if((millis() - lastUpdate) > Interval) // time to update
        {
            lastUpdate = millis();
            switch(ActivePattern)
            {
                case RAINBOW_CYCLE:
                    RainbowCycleUpdate();
                    break;
                case THEATER_CHASE:
                    TheaterChaseUpdate();
                    break;
                case COLOR_WIPE:
                    ColorWipeUpdate();
                    break;
                case SCANNER:
                    ScannerUpdate();
                    break;
                case FADE:
                    FadeUpdate();
            case FIRE:
                    RainbowCycleUpdate();
                    break;
                default:
                    break;
            }
        }
    }

    // Increment the Index and reset at the end
    void Increment()
    {
        if (Direction == FORWARD)
        {
           Index++;
           if (Index >= TotalSteps)
            {
                Index = 0;
                if (OnComplete != NULL)
                {
                    OnComplete(); // call the comlpetion callback
                }
            }
        }
        else // Direction == REVERSE
        {
            --Index;
            if (Index <= 0)
            {
                Index = TotalSteps-1;
                if (OnComplete != NULL)
                {
                    OnComplete(); // call the comlpetion callback
                }
            }
        }
    }

    // Reverse pattern direction
    void Reverse()
    {
        if (Direction == FORWARD)
        {
            Direction = REVERSE;
            Index = TotalSteps-1;
        }
        else
        {
            Direction = FORWARD;
            Index = 0;
        }
    }

    // Initialize for a RainbowCycle
    void RainbowCycle(uint8_t interval, direction dir = FORWARD)
    {
        ActivePattern = RAINBOW_CYCLE;
        Interval = interval;
        TotalSteps = 255;
        Index = 0;
        Direction = dir;
    }

    // Update the Rainbow Cycle Pattern
    void RainbowCycleUpdate()
    {
        for(int i=0; i< numPixels(); i++)
        {
            setPixelColor(i, Wheel(((i * 256 / numPixels()) + Index) & 255));
        }
        show();
        Increment();
    }

    // Initialize for a Theater Chase
    void TheaterChase(uint32_t color1, uint32_t color2, uint8_t interval, direction dir = FORWARD)
    {
        ActivePattern = THEATER_CHASE;
        Interval = interval;
        TotalSteps = numPixels();
        Color1 = color1;
        Color2 = color2;
        Index = 0;
        Direction = dir;
   }

    // Update the Theater Chase Pattern
    void TheaterChaseUpdate()
    {
        for(int i=0; i< numPixels(); i++)
        {
            if ((i + Index) % 3 == 0)
            {
                setPixelColor(i, Color1);
            }
            else
            {
                setPixelColor(i, Color2);
            }
        }
        show();
        Increment();
    }

    // Initialize for a ColorWipe
    void ColorWipe(uint32_t color, uint8_t interval, direction dir = FORWARD)
    {
        ActivePattern = COLOR_WIPE;
        Interval = interval;
        TotalSteps = numPixels();
        Color1 = color;
        Index = 0;
        Direction = dir;
    }

    // Update the Color Wipe Pattern
    void ColorWipeUpdate()
    {
        setPixelColor(Index, Color1);
        show();
        Increment();
    }

    // Initialize for a SCANNNER
    void Scanner(uint32_t color1, uint8_t interval)
    {
        ActivePattern = SCANNER;
        Interval = interval;
        TotalSteps = (numPixels() - 1) * 2;
        Color1 = color1;
        Index = 0;
    }

    // Update the Scanner Pattern
    void ScannerUpdate()
    {
        for (int i = 0; i < numPixels(); i++)
        {
            if (i == Index)  // Scan Pixel to the right
            {
                 setPixelColor(i, Color1);
            }
            else if (i == TotalSteps - Index) // Scan Pixel to the left
            {
                 setPixelColor(i, Color1);
            }
            else // Fading tail
            {
                 setPixelColor(i, DimColor(getPixelColor(i)));
            }
        }
        show();
        Increment();
    }

    // Initialize for a Fade
    void Fade(uint32_t color1, uint32_t color2, uint16_t steps, uint8_t interval, direction dir = FORWARD)
    {
        ActivePattern = FADE;
        Interval = interval;
        TotalSteps = steps;
        Color1 = color1;
        Color2 = color2;
        Index = 0;
        Direction = dir;
    }

    // Update the Fade Pattern
    void FadeUpdate()
    {
        // Calculate linear interpolation between Color1 and Color2
        // Optimise order of operations to minimize truncation error
        uint8_t red = ((Red(Color1) * (TotalSteps - Index)) + (Red(Color2) * Index)) / TotalSteps;
        uint8_t green = ((Green(Color1) * (TotalSteps - Index)) + (Green(Color2) * Index)) / TotalSteps;
        uint8_t blue = ((Blue(Color1) * (TotalSteps - Index)) + (Blue(Color2) * Index)) / TotalSteps;

        ColorSet(Color(red, green, blue));
        show();
        Increment();
    }

    // Calculate 50% dimmed version of a color (used by ScannerUpdate)
    uint32_t DimColor(uint32_t color)
    {
        // Shift R, G and B components one bit to the right
        uint32_t dimColor = Color(Red(color) >> 1, Green(color) >> 1, Blue(color) >> 1);
        return dimColor;
    }

    // Set all pixels to a color (synchronously)
    void ColorSet(uint32_t color)
    {
        for (int i = 0; i < numPixels(); i++)
        {
            setPixelColor(i, color);
        }
        show();
    }

    // Returns the Red component of a 32-bit color
    uint8_t Red(uint32_t color)
    {
        return (color >> 16) & 0xFF;
    }

    // Returns the Green component of a 32-bit color
    uint8_t Green(uint32_t color)
    {
        return (color >> 8) & 0xFF;
    }

    // Returns the Blue component of a 32-bit color
    uint8_t Blue(uint32_t color)
    {
        return color & 0xFF;
    }

    // Input a value 0 to 255 to get a color value.
    // The colours are a transition r - g - b - back to r.
    uint32_t Wheel(byte WheelPos)
    {
        WheelPos = 255 - WheelPos;
        if(WheelPos < 85)
        {
            return Color(255 - WheelPos * 3, 0, WheelPos * 3);
        }
        else if(WheelPos < 170)
        {
            WheelPos -= 85;
            return Color(0, WheelPos * 3, 255 - WheelPos * 3);
        }
        else
        {
            WheelPos -= 170;
            return Color(WheelPos * 3, 255 - WheelPos * 3, 0);
        }
    }

   // brightness, need some improvements probably
   void incbrigtness() {
   if (b >= 255) {
      b = 255;
   setBrightness(b);}
   else {b = b + 10;
   setBrightness(b);}
   }

   void decbrigtness() {
   if (b <= 5) {
      b = 5;
   setBrightness(b);}
   else {b = b - 10;
   setBrightness(b);}
   }

};

void Ring1Complete();
void Ring2Complete();

void receiveEvent(int numBytes) {//decode the ir signal
  byte byte1 = Wire.read();
  byte byte2 = Wire.read();
  irCode = byte2;
  irCode = irCode << 8;
  irCode = irCode | byte1;
}

// Define some NeoPatterns for the two rings and the stick
//  as well as some completion routines
NeoPatterns Ring1(24, 6, NEO_GRB + NEO_KHZ800, &Ring1Complete); // led parameters
NeoPatterns Ring2(24, 7, NEO_GRB + NEO_KHZ800, &Ring2Complete);

// Initialize everything and prepare to start
void setup()
{
   Serial.begin(9600);
   Serial.println("my-main-program starting!");
   Wire.begin(I2C_SLAVE_ADDRESS);
   Wire.onReceive(receiveEvent);
   Serial.println("my-main-program successfully started!");
 }
// Main loop
void loop()
{
    // Update the rings.
   if (irCode) {             //Reads the ir code
    handleButton(irCode);
    irCode = 0;
  }
 Ring1.Update();
 Ring2.Update();
 }

void handleButton(unsigned int irCode) {
  switch (irCode) {
   case BUTTON_UP:      // button up  will control led stip 1, button 2 will control let strip 2, button 3 both.
      t = 1;
     Serial.println(t);
     break;
   case BUTTON_DOWN:
      t = 2;
     Serial.println(t);
      break;
   case BUTTON_VOL:
     t = 0;
      Serial.println(t);
     break;
   case BUTTON_1:
     if (t == 1) {    // this also needs some improvements
      Serial.println(t);
     Ring1.TheaterChase(Ring1.Color(0,255,0), Ring1.Color(0,0,50), 100);
      }
     else if (t == 2) {
     Serial.println(t);
     Ring2.TheaterChase(Ring1.Color(255,0,0), Ring1.Color(0,50,0), 100);
      }
     else {      // some random effects for testing
     Serial.println(t);
      Ring1.TheaterChase(Ring1.Color(0,0,255), Ring1.Color(50,0,0), 100);
     Ring2.TheaterChase(Ring1.Color(0,0,255), Ring1.Color(50,0,0), 100);
      }
   break;
    case BUTTON_2:
      Serial.println("2");
       Ring1.Scanner(Ring1.Color(255,0,0), 55);
     break;
    case BUTTON_3:
     Ring1.ColorWipe(Ring1.Color(0,255,255), 55);
     Serial.println("3");
      break;
    case BUTTON_4:
      Ring1.Scanner(Ring1.Color(0,255,255), 55);
     Serial.println("4");
      break;
    case BUTTON_5:
      Serial.println("5");
      break;
    case BUTTON_6:
      Serial.println("6");
      break;
    case BUTTON_7:
      Serial.println("7");
      break;
    case BUTTON_8:         //  test the brightness here.
   Ring1.incbrigtness();
   Serial.println(b);
     break;
    case BUTTON_9:
   Ring1.decbrigtness();
   Serial.println(b);
     break;
    default:
      Serial.print("Unrecognized code received: 0x");
      Serial.println(irCode, HEX);
      break;
  }
}

//------------------------------------------------------------
//Completion Routines - get called on completion of a pattern
//------------------------------------------------------------

// Ring1 Completion Callback
void Ring1Complete() //dont really need to do anything specific after loop ended so should go back to update.
{Ring1.Update(); }

void Ring2Complete()
{Ring2.Update(); }

```

The problem: What I need is help, how to restructure 2 different effects. to fit into the above code. Loops replaced wilth millis() and delay with an updater.

here is the first, fire code by danesparza:

```
#include <Adafruit_NeoPixel.h>
#define PIN 6

Adafruit_NeoPixel strip = Adafruit_NeoPixel(29, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.setBrightness(brightness);
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {

  //  Uncomment one of these RGB (Red, Green, Blue) values to
  //  set the base color of the flame.  The color will flickr
  //  based on the initial base color

  //  Regular (orange) flame:
  //  int r = 226, g = 121, b = 35;

  //  Purple flame:
  //  int r = 158, g = 8, b = 148;

  //  Green flame:
  int r = 74, g = 150, b = 12;

  //  Flicker, based on our initial RGB values
  for(int i=0; i<strip.numPixels(); i++) {
    int flicker = random(0,55);
    int r1 = r-flicker;
    int g1 = g-flicker;
    int b1 = b-flicker;
    if(g1<0) g1=0;
    if(r1<0) r1=0;
    if(b1<0) b1=0;
    strip.setPixelColor(i,r1,g1, b1);
  }
  strip.show();

  //  Adjust the delay here, if you'd like.  Right now, it randomizes the
  //  color switch delay to give a sense of realism
  delay(random(10,113));
}

```

And a ripple effect that needs a restructure by suhajdab

```
#include <Adafruit_NeoPixel.h>
#define PIN 2
#define Pixels 24
#define BG 1
Adafruit_NeoPixel strip = Adafruit_NeoPixel(Pixels, PIN, NEO_GRB + NEO_KHZ800);

int color;
int center = 0;
int step = -1;
int maxSteps = 16;
float fadeRate = 0.6;
int diff;

//background color
uint32_t currentBg = random(256);
uint32_t nextBg = currentBg;

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop () {
  ripple();
}

void ripple() {
  if (BG){
    if (currentBg == nextBg) {
      nextBg = random(256);
    }
    else if (nextBg > currentBg) {
      currentBg++;
    } else {
      currentBg--;
    }
    for(uint16_t l = 0; l < Pixels; l++) {
      strip.setPixelColor(l, Wheel(currentBg, 0.1));
    }
  } else {
    for(uint16_t l = 0; l < Pixels; l++) {
      strip.setPixelColor(l, 0, 0, 0);
    }
  }

  if (step == -1) {
    center = random(Pixels);
    color = random(256);
    step = 0;
  }

  if (step == 0) {
    strip.setPixelColor(center, Wheel(color, 1));
    step ++;
  }
  else {
    if (step < maxSteps) {
      strip.setPixelColor(wrap(center + step), Wheel(color, pow(fadeRate, step)));
      strip.setPixelColor(wrap(center - step), Wheel(color, pow(fadeRate, step)));
      if (step > 3) {
        strip.setPixelColor(wrap(center + step - 3), Wheel(color, pow(fadeRate, step - 2)));
        strip.setPixelColor(wrap(center - step + 3), Wheel(color, pow(fadeRate, step - 2)));
      }
      step ++;
    }
    else {
      step = -1;
    }
  }

  strip.show();
  delay(50);
}

int wrap(int step) {
  if(step < 0) return Pixels + step;
  if(step > Pixels - 1) return step - Pixels;
  return step;
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos, float opacity) {

  if(WheelPos < 85) {
    return strip.Color((WheelPos * 3) * opacity, (255 - WheelPos * 3) * opacity, 0);
  }
  else if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color((255 - WheelPos * 3) * opacity, 0, (WheelPos * 3) * opacity);
  }
  else {
    WheelPos -= 170;
    return strip.Color(0, (WheelPos * 3) * opacity, (255 - WheelPos * 3) * opacity);
  }
}

```

So, can someone help me how to include these 2 effects based on the tutorial (unfortunately not much help on my current skill level) to the first code? Much appreciated.

# Answer
> 1 votes
You see in the second part is a `void ripple(){`, which is just like a `void loop(){` but only runs when it is called.

You can merge these codes by placing an if-statement after your `void loop(){` to check if it needs to run the loop or the ripple. You can simply use a boolean for this. For example:\`

```
void loop(){
  if(state == true){  //I've called the boolean state
    ripple();  //this calls the ripple function, and runs void ripple()
  }

  //here's the rest of the loop, this runs if state != true.
  //you can change state wherever you'd like.
}

```

You could even create a new function based on what's currently in your loop. Example:

```
void loop(){
  if(state == 1){
    originalLoop(); //what's originally in your loop, but now as a separate function
  }
  else if(state == 2){
    ripple();
  }

  //rest of the loop in which you can change state to 1 or 2 however you like
}

```

Hope this helps a bit :)

---
Tags: arduino-uno, millis, neopixel
---


title: Stepper Motor Button Press

text:
# Question
Title: Stepper Motor Button Press
I am having difficulties programming what should be a simple sketch that gets my **stepper motor to run at one step per second indefinitely at the press of a button and then stops at the press of another button.** I am using the *Bounce2.h* and *accelstepper.h* libraries and have been unable to figure out how to do it. Any help would be greatly appreciated, and as for hardware I am using a ***NEMA 23 High Torque Stepper Motor*** connected through a ***M542T Motor Driver*** powered by a ***Switching Power Supply*** and running on an ***Arduino UNO.***

Attatched find my code, and thank you so much for the help!

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

AccelStepper stepper(1, 9, 8); // initiate stepper motor

//int buttonPresses = 0;
const byte ButtonPin = 10;
const byte LedPin = 13; // for debugging and visualization

Bounce button;

void setup() {
  Serial.begin(9600);
  button.attach(ButtonPin);
  pinMode(LedPin, OUTPUT);
  stepper.setSpeed(1);
}

void loop() {
  if (button.rose()) {
    stepper.runSpeed();
    digitalWrite(LedPin, HIGH);
    //    buttonPresses++; // count presses of button and print to monitor
    //    Serial.print("Number of Button ");
    //    Serial.print("Presses = ");
    //    Serial.println(buttonPresses);
  }
  else {
    button.update();
    digitalWrite(LedPin, LOW);
    if (button.fell()) {
      stepper.stop();
    }
  }
}

```

**As of now, a button press runs the motor at 1 step/second, but a second press or any subsequent presses thereafter do nothing to stop the motor. Thanks so much!**

***!!EDIT!!***

Upon adding a boolean buttonState and setting it to LOW in the setup and changing my void loop() code to look like:

```
void loop() {
  button.update();
  if (button.rose() == true && buttonState == LOW) {
    stepper.runSpeed();
    digitalWrite(LedPin, HIGH);
    buttonState = HIGH;
  }
  else {
    if (button.fell() == true && buttonState == HIGH) {
      stepper.stop();
      buttonState = LOW;
    }
  }
}

```

I know get a step every button press. Just thought it may help in answering.

**EDIT 2**

So I I tried pulling the runSpeed() out of the loop and adding `if (buttonState = HIGH){stepper.runSpeed();}` but that now just runs the stepperMotor constantly and at variable speed and will not turn it off?

**EDIT 3 and Working Code** Thank you Janw for the help. I realized my fault in calling the runSpeed function within the if statement. Further, I also needed to change button.fell() to button.rose() since button.fell() returns true when the button is released, so basically I was stopping the motor everytime I let go of the button. Here is the final, and working void loop() in case anyone runs into a similar problem in the future:

```
void loop() {
  button.update();
  if (button.rose() == true && buttonState == LOW) {
    digitalWrite(LedPin, HIGH);
    buttonState = HIGH;
  }
  else {
    if (button.rose() == true && buttonState == HIGH) {
      stepper.stop();
      buttonState = LOW;
    }
  }
  if (buttonState == HIGH) {
    stepper.setSpeed(1);
    stepper.runSpeed();
  }
}

```

# Answer
You will probably get only 1 step each button press because your *runSpeed()* is within the *if (button.rose() == true && buttonState == LOW)*-statement.

The *runSpeed()* needs to be called every loop to check if the motor needs to step.

A simple way to change this is to set a boolean to true or false if you check your button and add something like this pseudocode:

```
if(motorRun == true) stepper.runSpeed();

```
> 0 votes

---
Tags: arduino-uno, timers, button, stepper
---


title: Data transfer using SPI

text:
# Question
Title: Data transfer using SPI
Sorry for my code is long and my English is not good.

I'm working with **8x8x8 LED cube** project using **Arduino nano**. I tried to understand code, but I don't understand how `cube[][]` data write on `pins`.

I just want to know, how write the data from `cube[8][8]` to hardware using **SPI**. code download using this link.

Thanks in advance.

My code is here :

```
#define AXIS_X 1
#define AXIS_Y 2
#define AXIS_Z 3
#define REFRESH_RATE 120

int CUBE_SIZE = 8;
int SPI_CS = 10;// This SPI Chip Select pin controls the MAX72xx
byte value[8];

volatile unsigned char cube[8][8];
volatile int current_layer = 0;

void setup()
{
  Serial.begin (115200);
  Serial.println("jolliFactory 8x8x8 jolliCube Demo example 1.0");

  pinMode(SPI_CS, OUTPUT);

  SPI.begin();

  maxTransferAll(0x0F, 0x00);   // 00 - Turn off Test mode
  maxTransferAll(0x09, 0x00);   // Register 09 - BCD Decoding  // 0 = No decoding
  maxTransferAll(0x0B, 0x07);   // Register B - Scan limit 1-7  // 7 = All LEDS
  maxTransferAll(0x0C, 0x01);   // 01 = on 00 = Power saving mode or shutdown
  maxTransferAll(0x0A, 0x0F);   // Set Brightness Intensity

  setUpInterrupts();
}

// Get the current status of a voxel
unsigned char getvoxel(int x, int y, int z)
{
    if (inrange(x,y,z))
    {
        if (cube[z][y] & (1 << x))
        {
            return 0x01;
        } else
        {
            return 0x00;
        }
    } else
    {
        return 0x00;
    }
}

void maxTransferAll(uint8_t address, uint8_t value)
{
  digitalWrite(SPI_CS, LOW);

    for ( int c=1; c<= CUBE_SIZE;c++) {
        SPI.transfer(address);
        SPI.transfer(value);
    }

  digitalWrite(SPI_CS, HIGH);
}

void maxTransferOne(uint8_t whichMax, uint8_t address, uint8_t value)
{
  byte noop_reg = 0x00;    //max72xx No op register
  byte noop_value = 0x00;  //value

  digitalWrite(SPI_CS, LOW);

  for (int i=CUBE_SIZE; i>0; i--)   // Loop through our number of Max72xx ICs
  {
    if (i==whichMax)
    {
      SPI.transfer(address);
      SPI.transfer(value);
    }
    else
    {
      SPI.transfer(noop_reg);
      SPI.transfer(noop_value);
    }
  }

  digitalWrite(SPI_CS, HIGH);
}

void maxTransferLEDCube(uint8_t address)
{
  digitalWrite(SPI_CS, LOW);

  for (int i=0; i<CUBE_SIZE; i++)   // Loop through our number of Max72xx ICs
  {
      SPI.transfer(address);
      SPI.transfer(value[CUBE_SIZE-i-1]);
  }

  digitalWrite(SPI_CS, HIGH);
}

void setUpInterrupts()
{
  cli();//stop interrupts while we set them up
  //set up an interrupt with timer1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;
  OCR1A = (16000000/REFRESH_RATE/1024/CUBE_SIZE -1);
  TCCR1B |= (1 << WGM12);
  // Set to CS10 and CS12 so we have the 1024
  TCCR1B |= (1 << CS12) | (1 << CS10);
  TIMSK1 |= (1 << OCIE1A);
  sei();//re-allow interrupts
}

ISR(TIMER1_COMPA_vect)
{
  for(byte y = 0 ; y < CUBE_SIZE ; y++)
  {
    byte b = 0;

    for(byte x = 0 ; x < CUBE_SIZE ; x++)
    {
      //form data byte
      b = b << 1;

      if (getvoxel(x,y,current_layer)==1)
      {
        b |= 1;
      }
    }
        value[y] = b;
  }

  maxTransferLEDCube(CUBE_SIZE - current_layer);

  current_layer++;

  if (current_layer == 8)
    current_layer = 0;
}

```

# Answer
> 1 votes
First, you need to know how the LEDs are arranged. There are 8 layers, each with 8 rows, each with 8 LEDs.

Each LED is represented as a single *bit* inside `unsigned char cube[8][8];` \- the first `[8]` is the array of layers, the second `[8]` is the array of rows, and the `unsigned char` holds 8 bits to represent the state of the 8 LEDs in that row.

Each LED layer has one MAX7219 8x8 LED Matrix Controller. To tell it what to do you need to give it a Command byte and a Data byte. So to tell it to light up LEDs 1, 2, and 7 on the fourth row, you need to tell it `0x04 0x86`. You send this command by setting `CS` `LOW`, sending the 16 bits of the Command+Data, then setting `CS` `HIGH`.

Each MAX7219 is connected one after the other in an SPI string. To command all of them at once you need to set `CS` `LOW`, send 16 bits for each MAX7219 (128 bits in all), then set `CS` `HIGH`. If you only want to command one MAX7219, you need to send a `NOP` Command+Data (`0x00 0x00`) to all the others.

The way the program works is:

1. **`setup()`**

a. Initialise the `Serial` port, and print a message.
b. Set the `CS` pin as an `OUTPUT`, then initialise `SPI`.
c. Initialise all the MAX7219 chips by sending a series of commands -
the same Command+Data to each of them (`maxTransferAll()`).
d. Initialise the Timer interrupt (`setUpInterrupts()`).
2. **`loop()`**
This isn't shown in the code. Presumably it alters the `cube[8][8]` array to make the special effects.
3. **`TIMER1_COMPA_vect`** (the interrupt handler)
Every time the timer ticks, the handler will command all of the MAX7219s to show the next row of LEDs. This will last until the next timer tick, when the next row will be displayed. If this is done fast enough, the human eye's "persistence of vision" will not see the rows flickering.

```
For each row (`y`) in the `cube` array
   Set `b` to 0
   For each bit ('x') in the `cube` data
      If the bit is set (`getvoxel(...)`) set a bit in `b`.
   Store `b` in the `value[y]` array

```

`value` now holds the bytes needed as Data for the next row for each of the MAX7219 chips.

```
    Send value over SPI using `maxTransferLEDCube(...)`

```

Since the cube displays the same row for each layer simultaneously, the Command doesn't have to change, only the Data does. That's what the `value` array holds: the Data to be sent to each MAX7219 chip.

---
Tags: arduino-nano, c
---


title: Exporting ADC data to excel

text:
# Question
Title: Exporting ADC data to excel
Do I need third party s/w to export to a spreadsheet? I have built a heat flux sensor meter and wish to log my data.

# Answer
You need some way of getting the data from the Arduino to the PC. There's a number of ways of doing it depending on what resources you have available.

* Through serial as CSV

This entails printing the data to the serial port in CSV format then using some software on the PC to capture that and save it to a file. That could be as simple as a good terminal emulator that provides "capture to file" or similar, or you could write your own program in your favourite programming language. This method is essentially free.

* To an SD card

Writing the data as a CSV file onto an SD card directly attached to the Arduino can be quite convenient. It means you can then just take the SD card with the data on it and slip it into your computer to import the data as you would with any other file. It needs an SD card shield or breakout board attaching to the Arduino

* Through the network

If your Arduino has a network connection of some form (WiFi shield, Ethernet shield, etc) you could POST the data to a web page running on your PC and store it in a CSV file for later importing. Probably the most expensive option but it does mean you can do things with the data "live" as it comes in.
> 1 votes

# Answer
Use tabs to separate columns of data, and newlines between each row. Then you can copy the serial output, and paste it into Excel.
> 0 votes

---
Tags: arduino-uno
---