# Question
Title: Can't play melody and FastLED lights at same time
I'm trying to make an OO state machine based program to play music and lights at the same time. It uses the FastLED library and a 13 pixel neopixel strip. I've confirmed that with the currently wired setup that I can separately play music and also separately run the FastLED Cylon example code. However when I upload the code below it just kinda hangs out and doesn't do anything and doesn't even print the statements in the setup statement. The weird thing is that if I comment out the Lights lightstrip1() instantiation line and the lightstrip.Update() line, it does play the melody part ok.

```
#include "pitches.h"
#include "FastLED.h"

class Melody{

// notes in the melody Minuet in G.
int melody[126] = {
  NOTE_D4, NOTE_G3, NOTE_A3, NOTE_B3, NOTE_C4,
  NOTE_D4, NOTE_G3, NOTE_G3,
  NOTE_E4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_FS4,
  NOTE_G4, NOTE_G3, NOTE_G3,

  NOTE_C4, NOTE_D4, NOTE_C4, NOTE_B3, NOTE_A3,
  NOTE_B3, NOTE_C4, NOTE_B3, NOTE_A3, NOTE_G3,
  NOTE_FS3,NOTE_G3, NOTE_A3, NOTE_B3, NOTE_G3,
  NOTE_A3,

  NOTE_D4, NOTE_G3, NOTE_A3, NOTE_B3, NOTE_C4,
  NOTE_D4, NOTE_G3, NOTE_G3,
  NOTE_E4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_FS4,
  NOTE_G4, NOTE_G3, NOTE_G3,

  NOTE_C4, NOTE_D4, NOTE_C4, NOTE_B3, NOTE_A3,
  NOTE_B3, NOTE_C4, NOTE_B3, NOTE_A3, NOTE_G3,
  NOTE_A3, NOTE_B3, NOTE_A3, NOTE_G3, NOTE_FS3,
  NOTE_G3,

 // Second part
  NOTE_B4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_G4,
  NOTE_A4, NOTE_D4, NOTE_E4, NOTE_FS4, NOTE_D4,
  NOTE_G4, NOTE_E4, NOTE_FS4, NOTE_G4, NOTE_D4,
  NOTE_CS4, NOTE_B3, NOTE_CS4, NOTE_A3,
  NOTE_A3, NOTE_B3, NOTE_CS4, NOTE_D4, NOTE_E4, NOTE_FS4,
  NOTE_G4, NOTE_FS4, NOTE_E4,
  NOTE_FS4, NOTE_A3, NOTE_CS4,
  NOTE_D4,

  // BACK TO G MAJOR!!!!
  NOTE_D4, NOTE_G3, NOTE_FS3, NOTE_G3,
  NOTE_E4, NOTE_G3, NOTE_FS3, NOTE_G3,
  NOTE_D4, NOTE_C4, NOTE_B3,
  NOTE_A3, NOTE_G3, NOTE_FS3, NOTE_G3, NOTE_A3,
  NOTE_D3, NOTE_E3, NOTE_FS3, NOTE_G3, NOTE_A3, NOTE_B3,
  NOTE_C4, NOTE_B3, NOTE_A3,
  NOTE_B3, NOTE_D4, NOTE_G3, NOTE_FS3,
  NOTE_G3

  };

// note durations: 4 = quarter note, 8 = eighth note, etc.:
float noteDurations[126] = {
  4, 8,8,8,8,
  4, 4, 4,
  4, 8,8,8,8,
  4, 4, 4,
  4, 8,8,8,8,
  4, 8,8,8,8,
  4, 8,8,8,8,
  1.5,

  4, 8,8,8,8,
  4, 4, 4,
  4, 8,8,8,8,
  4, 4, 4,
  4, 8,8,8,8,
  4, 8,8,8,8,
  4, 8,8,8,8,
  1.5,

  // Second part

  4, 8,8,8,8,
  4, 8,8,8,8,
  4, 8,8,8,8,
  4, 8,8, 4,
  8,8,8,8,8,8,
  4, 4, 4,
  4, 4, 4,
  1.5,
  4, 8,8, 4,
  4, 8,8, 4,
  4, 4, 4,
  8,8,8,8, 4,
  8,8,8,8,8,8,
  4,4,4,
  8,8,4,4,
  1.5
  };

  unsigned long OnTime;  // This will be the time in millis to turn on a note.
  unsigned long OffTime; // This will be the time in millis to turn off a note.

  int ToneState;
  unsigned long previousMillis;

  int speakerPin;
  int noteNumber;
  int maxNoteNumber;

  public:
  Melody(int pin) {
     speakerPin = pin;
     pinMode(speakerPin, OUTPUT);
     previousMillis = 0;
     OnTime = previousMillis;
     ToneState = 0; // Off
     noteNumber = 0; // Start at the first note.
//     maxNoteNumber = sizeof(noteDurations); // This turns out to 504 for some reason.
     maxNoteNumber = 125;

  }

  void Update() {
     unsigned long currentMillis = millis();

     if (ToneState == 0 && currentMillis >= OnTime) {
       tone(speakerPin, melody[noteNumber]);
       OffTime = currentMillis + (1000 / noteDurations[noteNumber]);
       ToneState = 1;
       Serial.print(noteNumber);
       Serial.print("/");
       Serial.println(maxNoteNumber);

     } else if (ToneState == 1 && currentMillis >= OffTime) {
       noTone(speakerPin);
       OnTime = currentMillis + ((1000 / noteDurations[noteNumber]) * 0.30);
       ToneState = 0;
       if (noteNumber < maxNoteNumber) {
         noteNumber += 1;
       } else {
         Serial.println("RESET");
         noteNumber = 0; // Reset to the begining of the song.
       }
     }
  }
};

class Lights {
    int ledPin;
        int ledCount;
    unsigned long NextOn;
        int led_R;
        int led_G;
        int led_B;

        CRGB leds[12];

    int ledOn;
        int lightdelay;

    public:
    Lights(int pin, int ledcount, int led_r, int led_g, int led_b) {
      ledPin = pin;
      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, LOW);
      ledCount = ledcount;
      led_R = led_r;
      led_G = led_g;
      led_B = led_b;
      ledOn = 0;
      lightdelay = 100;
      NextOn = 0;
      FastLED.addLeds<NEOPIXEL, 7>(leds, ledCount); // It complains if I try to use a variable for the 7. It has to be a constant.
      for (int i = 0; i < ledCount; i++) {
        leds[i] = CRGB::White;
      }
      FastLED.show();
    }

    void Update() {
      unsigned long currentMillis2 = millis();

      if (currentMillis2 > NextOn) {
         if (ledOn >= ledCount) {
           leds[ledOn] = CRGB::Black;
           ledOn = 0;
           leds[ledOn] = CRGB::Red;
         } else if (ledOn == 0) {
           leds[ledCount - 1] = CRGB::Black;
           leds[ledOn] = CRGB::Red; // Need to put RGB to HSV converter in later.
         } else {
           leds[ledOn - 1] = CRGB::Black;
           leds[ledOn] = CRGB::Red; // Need to put RGB to HSV converter in later.
         }
         Serial.print("LED: ");
         Serial.println(ledOn);
         Serial.println(NextOn);
         FastLED.show();
         NextOn = currentMillis2 + lightdelay;
         ledOn++;
      }
    }

};

Melody melody1(2);

Lights lightstrip1(7, 12, 250, 0, 0);

void setup() {
  Serial.begin(115200);
  Serial.println("Started");
}

void loop() {
   melody1.Update();
   lightstrip1.Update();
}

```

Any ideas?

# Answer
I asked on the FastLED library github page and they provided me with the correct instantiation for the object:

```
Lights *lightstrip1;

void setup() {
  lightstrip1 = new Lights(7,13, 250, 0, 0);
}

void loop() {
  lightstrip1->Update();
}

```

It now works fine and plays the music and the lights simultaneously without issue.
> 1 votes

# Answer
The WS2812 device requires precise timing down to +/- 150 x 10<sup>-9</sup> seconds. For details look at this chip specification. As such, it is likely the FastLED library uses processor resources that can not be shared. Look through the FastLED library's code to verify this.

It appears your sketch plays a note, changes the LED pattern then repeats this cycle. Assuming the resources for FastLED are initialized in the constructor of the library, you might consider destroying and re-instantiating the FastLED class for each of these cycles.

added later...

Comments about memory space and large amounts of static data in the sketch have merit. Consider moving your static (unchanging) data from limited RAM to FLASH memory. This resource explains how this is accomplished.
> 1 votes

---
Tags: led, class, sound
---


# Question
Title: Which relay should I use to control the power from mains?
I was making a home automation project in which I want to control appliances like a fan and a bulb through voice commands with the help of an arduino uno and a relay but I am confused which relay to use. Please tell me the specifications of a 4 channel relay fit for this project.

# Answer
There are two factors you need to consider when choosing a relay:

1. Can it power the devices I want it to power without the contacts melting?
2. Can I control it?

The first one is simple enough. Find out the current requirements for each of the devices and add them together. Make sure that the relay is capable of switching *at least* that much at the *AC* voltage of your country's mains supply. If in doubt go slightly higher.

For the second point you need to consider the interfacing circuitry and what DC power supply you are using in your system. For instance, if you have a 12V power supply for the Arduino you might consider a 12V coil relay and use the 12V power as the switching power. If you are running from 9V then you might consider a 5V relay and use the Arduino's regulated 5V pin as the switching power source. Either way you need a driving circuit. That could be as simple as an NPN transistor, two resistors, and a diode (the circuit can be found throughout the web if you Google "Arduino Relay"), or more complex involving an opto-isolator.

The simplest solution is to find an all-in-one module - a relay with driver circuit all as a single product. There are many of these around directly targeted at the Arduino, and most are the slightly more complex (and thus better) opto-isolator driving circuit. You still have to consider the same two points - switching capacity and coil voltage - but you don't then need to worry about making your own driving circuit for them.
> 0 votes

# Answer
In the US there is a set of products - plug-in modules - collectively known as X10, which uses signals sent over the house wiring to control devices elsewhere in the house. If they are available where you are, **this is the safest way to control mains-powered devices with an Arduino** because the Arduino needs no connection to the house wiring.

The Wireless Transceiver module receive X10 commands over RF and transmit them onto the power wiring. Using this and a small RF transmitter known here as "X10 Firecracker CM17A", your Arduino can be completely isolated from the house wiring, sending its control commands over the air instead. Amazon shows both products on this page; the CM17A (which you use by removing its circuit board from the plastic package), and the RF control module, of which you only need one. The transceiver module can directly control one fan or light; for additional devices you'd use any other, non-RF (read "less expensive") X10 module, which will "hear" whatever the transceiver module sends.

There is an Arduino library already written for X10 communication.
> 0 votes

---
Tags: arduino-uno, relay
---


# Question
Title: How can i receive data from Mega2560 on PC with Visual C#
How can i receive the data from my Arduino Mega 2560 with Visual C# on my PC.

I send a short databyte (2 bytes) and a timestamp (4 bytes) over USB to PC

```
//initialization

const int RX = 0;
const int TX = 1;

void setup(){

pinMode(RX, INPUT);   //readpin for USB
pinMode(TX, OUTPUT);  //writepin for USB
...

Serial.begin(28800);   //open interface
}

 //loop()

 Serial.print(incomingByte, BIN); //sending databyte

 sendBinary(currentMillis);   //send timestamp

//method for timestamp

void sendBinary(long currnetMillis)
 {
  int temp = currentMillis&0xFFFF;  //16 bit of the low-byte
  sendBinary(temp);
  temp = currentMillis >> 16;       //16 bit of the high-byte
  sendBinary(temp);
 }

```

I have surched in the internet for an example but i didn´t find a good. So i ask here what ist the best way with Visual Studio C# to receive the incoming data? An example code will be nice because i´m a beginner and didn´t understand the jargon.

With frindly wishes sniffi

# Answer
> 0 votes
I haven't tried the code below, but it should point you in the right direction.

All you have to do is write a C# program that opens the Serial port that your Arduino is connected to and read and write from there like you would from a file.

1. Open Visual Studio, create a C# command line project.
2. Paste this code inside main()

```
    System.IO.Ports.SerialPort port = new SerialPort("COM1", 9600);
    try
    {
        while (true)
        {
            int readData = port.ReadByte();
            System.Console.WriteLine("Read {0} from the port", readData);
        }
    }
    catch(Exception)  // Press CTRL-C to exit.
    {
    }
    port.Close();

```
3. Compile the code and run it.

---
Tags: arduino-mega, visualstudio, c#
---


# Question
Title: how do you capture the top value in a fallen edge in analogs data (flex sensor)
Guys i'm working with a flex sensor and I'm trying to capture a specific value which is the moment before the user lets go of a flexed flex sensor and its represented as the top point of a falling edge as sub picture A in the picture I included. using an array I tried two methods, which can produce a close value at times but at other it will give me wrong values first I tried the following logic, whenever I detect a value below a certain threshold it indicates that a fallen edge has occurred so get me the value that came right before it as shown in sub picture C but depending on the delay this can be quite unpredictable.

the second method is to store the maximum value of but this returns the peak and it's not always the top of the fallen edge as shown in subpicture B

what do you guys suggest to capture those values? this is my code so far

```
bool loaded = false;
int threshold = 760;
int index = 0 ;
int _max=0;
int values[4];
int values_size = 4;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int data = analogRead(A0);

  if (loaded) {
    values[index] = data;
    if(data>_max){
      _max=data;
      }

    if (data < threshold) {
      loaded = false;
      Serial.flush();
      Serial.print('a');
      Serial.print(',');
      Serial.print(_max);
      Serial.println();
      _max=0;
      delay(300);
    }
    index++;
    index %= values_size;
  }
  else if ( data > threshold && !loaded) {

    loaded = true;
  }

  delay(20);

}

```

# Answer
I suggest you consider as “top value of the falling edge” the maximum of the values you have read during a specified time window before the edge is detected. This means you have to compute the maximum at the time you detect the edge. If you instead continuously compute a running maximum, then you are going to get a global maximum. Amended source:

```
bool loaded = false;
int threshold = 760;
int index = 0 ;
const int values_size = 4;  // this controls the time window
int values[values_size];

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

void loop() {
  int data = analogRead(A0);

  if (loaded) {
    // Store the reading.
    values[index] = data;
    index = (index + 1) % values_size;

    // Detect falling edge.
    if (data < threshold) {
      loaded = false;

      // Find the max.
      int _max = 0;
      for (int i = 0; i < values_size; i++) {
        if (values[i] > _max) _max = values[i];
        values[i] = 0;  // clear, for next time
      }

      // Report it.
      Serial.flush();
      Serial.print('a');
      Serial.print(',');
      Serial.print(_max);
      Serial.println();
      delay(300);
    }
  }

  // Detect rising edge.
  else if (!loaded && data > threshold) {
    loaded = true;
  }
  delay(20);
}

```

Notice the line `values[i] = 0;`. It is intended to avoid the reading of one falling edge being seen on the next one.
> 0 votes

---
Tags: arduino-uno, analogread, signal-processing, analog-sampling
---


# Question
Title: Using only Rx pin to receive data from HC 05 and attiny85 (Arduino IDE)
I was building a Bluetooth car with attiny85 (Arduino IDE) and HC05 bluetooth module. I need 4 IO pins to control the car. Since attiny have only 5vIO's, I am left with only 1 pin to connect to HC05. I would only be receiving data from HC05. So, I want to use that leftover pin as RxD to receive data.

```

#include //the software serial library
#define RxD 4

SoftwareSerial blueToothSerial(RxD);

```

But when I do this It gives the following error

```

No matching function for call to 'SoftwareSerial::SoftwareSerial(int)'
```

Though it works fine, when I also define a TxD pin. But I want to use only one pin (RxD). Please help.

# Answer
> 1 votes
I suggest you get rid of SoftwareSerial and use instead this Simple ATtiny USI UART. This is a driver for a receive-only UART that uses the USI port of the ATtiny85. It is superior to a software-only UART as it makes good use of the hardware, leaving more time for the CPU to do more useful things (or sleep and save battery). Also, unlike SoftwareSerial, it does not need to block interrupts for long periods, which is a good thing.

# Answer
> 0 votes
The constructor for the SoftwareSerial object expects to be given both a TX and and RX pin (and, optionally, a boolean value representing whether or not it should use inverse logic.) From SoftwareSerial.h, see:

```
SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

```

If you want to use the library in the way you've written, you'll need to either modify the existing constructor or write a new one into the library.

As a quick test, I've added the following lines to each of the listed source files:

**SoftwareSerial.h**

```
SoftwareSerial(uint8_t receivePin, bool inverse_logic = false);

```

**SoftwareSerial.cpp**

```
SoftwareSerial::SoftwareSerial(uint8_t receivePin, bool inverse_logic /* = false */) :
_rx_delay_centering(0),
_rx_delay_intrabit(0),
_rx_delay_stopbit(0),
_tx_delay(0),
_buffer_overflow(false),
_inverse_logic(inverse_logic)
{
  setRX(receivePin);
}

```

Now there's a constructor that allows for a single RX pin argument like you've outlined in your initial example. The problem is that this is likely to break anytime the Arduino codebase gets updated and your changes get blown away.

Best practice may dictate writing your own driver to use the serial functionality of your ATTiny without the possibility of accidentally using the TX functions, but if this is a one-off then maybe Bence Kaulics' suggestion of just feeding it a nonsense pin would be the least time-consuming.

---
Tags: bluetooth, softwareserial
---


title: Arduino Mega different SPI Pins

text:
# Question
Title: Arduino Mega different SPI Pins
I am working on a project that uses Arduino and Water Level Sensor MS5540C sensor that uses SPI to communicate with Arduino.

When I use Arduino UNO, it was working like a charm using pins 11, 12 and 13, and pin 9 as clock.

Then When I switched to Arduino MEGA, I changed SPI pins to 51, 50 and 52, and I can't get right reads input from the sensor.

Is there any tricks that should be used when switching between Arduino UNO and MEGA ?

Here's the code I use.

Thanks.

```
#include <SPI.h>
int clock = 9;

void resetsensor() //this function keeps the sketch a little shorter
{
 SPI.setDataMode(SPI_MODE0);
 SPI.transfer(0x15);
 SPI.transfer(0x55);
 SPI.transfer(0x40);
}

void setup() {
 Serial.begin(9600);
 SPI.begin(); //see SPI library details on arduino.cc for details
 SPI.setBitOrder(MSBFIRST);
 SPI.setClockDivider(SPI_CLOCK_DIV32); //divide 16 MHz to communicate on 500 kHz
 pinMode(clock, OUTPUT);
 delay(100);
}

void loop()
{
 TCCR1B = (TCCR1B & 0xF8) | 1 ; //generates the MCKL signal
 analogWrite (clock, 128) ;

 resetsensor();//resets the sensor - caution: afterwards mode = SPI_MODE0!

 //Calibration word 1
 unsigned int word1 = 0;
 unsigned int word11 = 0;
 SPI.transfer(0x1D); //send first byte of command to get calibration word 1
 SPI.transfer(0x50); //send second byte of command to get calibration word 1
 SPI.setDataMode(SPI_MODE1); //change mode in order to listen
 word1 = SPI.transfer(0x00); //send dummy byte to read first byte of word
 word1 = word1 << 8; //shift returned byte
 word11 = SPI.transfer(0x00); //send dummy byte to read second byte of word
 word1 = word1 | word11; //combine first and second byte of word

 resetsensor();//resets the sensor

 //Calibration word 2; see comments on calibration word 1
 unsigned int word2 = 0;
 byte word22 = 0;
 SPI.transfer(0x1D);
 SPI.transfer(0x60);
 SPI.setDataMode(SPI_MODE1);
 word2 = SPI.transfer(0x00);
 word2 = word2 <<8;
 word22 = SPI.transfer(0x00);
 word2 = word2 | word22;

 resetsensor();//resets the sensor

 //Calibration word 3; see comments on calibration word 1
 unsigned int word3 = 0;
 byte word33 = 0;
 SPI.transfer(0x1D);
 SPI.transfer(0x90);
 SPI.setDataMode(SPI_MODE1);
 word3 = SPI.transfer(0x00);
 word3 = word3 <<8;
 word33 = SPI.transfer(0x00);
 word3 = word3 | word33;

 resetsensor();//resets the sensor

 //Calibration word 4; see comments on calibration word 1
 unsigned int word4 = 0;
 byte word44 = 0;
 SPI.transfer(0x1D);
 SPI.transfer(0xA0);
 SPI.setDataMode(SPI_MODE1);
 word4 = SPI.transfer(0x00);
 word4 = word4 <<8;
 word44 = SPI.transfer(0x00);
 word4 = word4 | word44;

 long c1 = word1 >> 1;
 long c2 = ((word3 & 0x3F) << 6) | ((word4 & 0x3F));
 long c3 = (word4 >> 6) ;
 long c4 = (word3 >> 6);
 long c5 = (word2 >> 6) | ((word1 & 0x1) << 10);
 long c6 = word2 & 0x3F;

 resetsensor();//resets the sensor

//Temperature:
 unsigned int tempMSB = 0; //first byte of value
 unsigned int tempLSB = 0; //last byte of value
 unsigned int D2 = 0;
 SPI.transfer(0x0F); //send first byte of command to get temperature value
 SPI.transfer(0x20); //send second byte of command to get temperature value
 delay(35); //wait for conversion end
 SPI.setDataMode(SPI_MODE1); //change mode in order to listen
 tempMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
 tempMSB = tempMSB << 8; //shift first byte
 tempLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
 D2 = tempMSB | tempLSB; //combine first and second byte of value

 resetsensor();//resets the sensor

 //Pressure:
 unsigned int presMSB = 0; //first byte of value
 unsigned int presLSB =0; //last byte of value
 unsigned int D1 = 0;
 SPI.transfer(0x0F); //send first byte of command to get pressure value
 SPI.transfer(0x40); //send second byte of command to get pressure value
 delay(35); //wait for conversion end
 SPI.setDataMode(SPI_MODE1); //change mode in order to listen
 presMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
 presMSB = presMSB << 8; //shift first byte
 presLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
 D1 = presMSB | presLSB;

 const long UT1 = (c5 * 8) + 20224;
 const long dT =(D2 - UT1);
 const long TEMP = 200 + ((dT * (c6 + 50))/1024);
 const long OFF  = (c2*4) + (((c4 - 512) * dT)/4096);
 const long SENS = c1 + ((c3 * dT)/1024) + 24576;

 long PCOMP = ((((SENS * (D1 - 7168))/16384)- OFF)/32)+250;
 float TEMPREAL = TEMP/10;
 Serial.print("pressure =    ");
 Serial.print(PCOMP);
 Serial.println(" mbar");

 const long dT2 = dT - ((dT >> 7 * dT >> 7) >> 3);
 const float TEMPCOMP = (200 + (dT2*(c6+100) >>11))/10;
 Serial.print("temperature = ");
 Serial.print(TEMPCOMP);
 Serial.println(" °C");
 Serial.println("************************************");

 delay(300);
 }

```

# Answer
> -1 votes
The problem was basically because some limitations in Arduino MEGA, You can't use `pin 9`, instead use `pin 12`.

It works like a charm.

Thanks.

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


# Question
Title: ESP8266 - Error: unknown opcode or format name 'jmp'
I bought a nodeMCU 8266 and I'm hoping that it can replace my bulkier UNO+WiFi 101.

I'm getting an error when I compile: Error: unknown opcode or format name 'jmp'

I'm using it in void SoftReset() function:

```
void softReset() {
  delay(1000);
  asm volatile ("  jmp 0");
}

```

This reset works great with my Uno+101 setup but, for whatever reason, doesn't like the ESP8266. I removed the WiFi101 library and added the ESP8266 WiFi libraries. That has been the only change.

Can you please help me understand why I'm receiving this error?

EDIT: I have read this SO answer but the "syntactical sugar" didn't work for me.

I am also perusing various ESP8266 sites but they are not as well managed as SE/SO and answers are tough to find.

# Answer
The proper way to reset the esp8266 when using the Arduino IDE is to call `ESP.reset()`. You may need to `#include <Esp.h>`, but almost all esp8266 headers you include to use any of its functionality will have included it already.
> 3 votes

# Answer
The ESP8266 is not an Arduino Uno. It talks a completely different language.

It's like you're talking Spanish to a Chinese person. It can't understand you.

If you want to use assembly language then you have to use the assembly language of the chip you are programming for - not the assembly language of a completely different chip.

The assembly language is detailed here: http://techblog.realisaatio.fi/wp-content/uploads/2015/04/xtensalx\_overview\_handbook.pdf

Bear in mind, though, that jumping to 0 may not reset the device - it may do something nasty.

The only sure-fire way of resetting a chip where you don't really know what is going on inside is to connect a GPIO signal to the RESET pin and use that GPIO to pull RESET low and reset the board that way.

If you want to call address 0 and don't know how to do it in assembly there are ways of arranging it in C using a function pointer:

```
void (*addressZero)() = 0;

void setup() {
    addressZero(); // Call address 0
}

void loop() {
}

```

That way it will work on multiple different architectures without having to understand the underlying assembly language. That, of course, is assuming that calling address 0 is a valid way of resetting the board on the target chip.

Browsing through the document I link to above it looks most likely that you would first have to load a register with 0 and then use `JX` to jump to the address stored in the register (i.e., zero).
> 2 votes

---
Tags: arduino-ide, esp8266
---


# Question
Title: Is it possible to overclock the baudrate from the mega to 230400 bps?
i have a Arduino Mega 2560 and want send data with 230400bps to my laptop without any framingerror.

I want send the data over USB with serial.print ist that possible or must i use the ethernet?

When that is possible it will be really nice when someone can write what i have to do.

With friendly wishes sniffi

# Answer
> 1 votes
> Is it possible to overclock the baudrate from the mega to 230400 bps?

Yes, setting that baud-rate is not a problem but this specific baud-rate may will give a high error rate. According to the AVR baud-rate calculation (UBRRn Settings for 16 Mhz system clock) the error is 8.5% (U2Xn=0) and -3.5% (U2Xn=1).

Simply choosing 250000 bps will remove this error.

Cheers!

---
Tags: serial, arduino-mega, baud-rate
---


title: Need help on HC05 and Nano

text:
# Question
Title: Need help on HC05 and Nano
I am new to Arduino programming and currently working on this instructable http://www.instructables.com/id/Control-Led-RGB/ (following this diagram http://cdn.instructables.com/F6Q/IMHF/I0LCDK6B/F6QIMHFI0LCDK6B.LARGE.jpg)

I have ordered these parts as well.

1. Arduino Nano: www.ebay.in/itm/Arduino-Nano-SOLDERED-PINS-V3-0-ATmega328-CH340G-BUY-2-GET-1-USB-CABLE-FREE-/172117729247?
2. HC-05: www.amazon.in/Bluetooth-Transceiver-Module-TTL-Outputs-HC05/dp/B00R95Y0AK?ie=UTF8&psc=1&redirect=true&ref\_=ox\_sc\_act\_title\_2&smid=A1NDZY44BCNIQJ

My questions are:

1. Is there need to add voltage divider? If yes can you please provide link?
2. Can I connect two 5050 RGB modules?
3. Will 12 V, 1 A will be enough to power this board.

# Answer
1A will be enough to power you arduino but the total powerconsumtion will depend on the amount of leds that you want to drive. If you follow the instuctable, it should be enoug but it's never a good idea to use your power source at max capacity all the time.

It allows you to connect 2 modules indeed.

Why would you need a voltage divider?
> 0 votes

---
Tags: arduino-nano, hc-05
---


# Question
Title: How can I made my Arduino follow the time exactly?
I am making an Arduino clock. You can set time to it, and then it keeps on going. The problem is that it is always within a minute off. It is not a major issue, but one that I would like to fix. I use the millis function. The program checks if millis is evenly divisible by 60,000(1 minute). After I set the time, millis is NOT at 0, meaning that is ahead of what I set by a number of seconds. How can I fix this? Code:

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int hours=0;
int minutes=0;
const int modePin=6; //button
int prevModeState=HIGH; //prev state of button
unsigned long timer;
int modeState;//current state
int mode=0;//mode of alarm
int buttonCounter=0;
const int incrementPin=9;
const int switchPin=7;
int incrementState;
int switchState;
int prevIncrementState=HIGH;
int prevSwitchState=HIGH;
int switching=0;

void setup() {
lcd.begin(16, 2);
lcd.setCursor(6, 0);
lcd.print("Time:");
lcd.setCursor(6, 1);
lcd.print("00:00");
pinMode(modePin, INPUT_PULLUP);
pinMode(incrementPin, INPUT_PULLUP);
pinMode(switchPin, INPUT_PULLUP);
}

void loop() {
modeState=digitalRead(modePin);
if(prevModeState!=modeState){
      prevModeState=modeState;
   if(modeState==LOW){
    buttonCounter++;
  if(buttonCounter%2==0){
    mode=0;
    lcd.clear();
    lcd.setCursor(6, 0);
    lcd.print("Time:");
    writeTime();
}
  else{
    mode=1;
    switching=0;
    lcd.clear();
    lcd.setCursor(4, 0);
    lcd.print("Set Time:");
}

   }
  }
if(mode==0){
  timer=millis();
  if(timer%60000==0){
     minutes++;
    writeTime();
    }
}
else if(mode==1){
 incrementState=digitalRead(incrementPin);
  switchState=digitalRead(switchPin);
  if(prevSwitchState!=switchState){
    prevSwitchState=switchState;
    if(switchState==LOW){
    switching++;
    }
    if(switching==4){
      switching=0;
    }

    }

  if(prevIncrementState!=incrementState){
    prevIncrementState=incrementState;
    if(incrementState==LOW){
      if(switching==0){
        if(hours<14){
        hours+=10;
        }
        else if((hours>=14)&&(hours<20)){
        hours-=10;
        }
        else{
          hours-=20;
        }
        }

        else if(switching==1){
          if((hours==9)||(hours==19)){
            hours-=9;
          }
          else if(hours==23){
            hours-=3;
          }
          else{
          hours++;
          }
        }

        else if(switching==2){
          if(minutes<50){
             minutes+=10;
          }
          else{
            minutes-=50;
          }

        }
        else if(switching==3){
          if(minutes%10==9){
            minutes-=9;
          }
          else{
          minutes++;
          }
        }

    }

  }

  writeTime();
}
}

void writeTime(){
  lcd.setCursor(6, 1);
   if(minutes>=60){
        minutes=0;
        hours++;
        }
     if(hours>=24){
        hours=0;
     }
if(minutes<10){

      if(hours<10){
        lcd.print(String("0")+hours+":"+"0"+minutes);
      }
      else{
        lcd.print(hours+String(":")+"0"+minutes);
      }
    }
    else{
      if(hours<10){
         lcd.print(String("0")+hours+":"+minutes);
      }
      else{
         lcd.print(hours+String(":")+minutes);//possibly split if problems arise
      }

    }
}

```

# Answer
Three things you can do - any combination of these is good, but the more the better:

1. Use an RTC module to keep more accurate track of the time.
2. Connect the Arduino to the internet and use NTP to get the exact time.
3. Use the time provided by GPS.

The RTC chip can keep track of time when there is no external power, using just a very small button cell. The GPS and internet time are both very accurate.

Using either or both of those sources to set and maintain the correct time in the RTC chip is the best and most accurate way of keeping the right time on the Arduino.

To increase the accuracy of your existing method you should count seconds, not minutes.

Start by recording the current millis. When 1000 of them have passed you can increase your seconds. Don't rely on `millis() % 1000` since you may miss it whilst doing other things. Also don't rely on your millisecond counter check executing at exactly 1000ms intervals - work on the principle of "at least 1000ms" and move the next check to 1000ms from where it *should* have happened, not where it *did* happen. This can help to combat some clock drift.

```
static unsigned long mscount = millis();

if (millis() - mscount >= 1000) {
    mscount += 1000;
    seconds ++;
}

```

Then every 60 seconds you can increase your minutes:

```
if (seconds == 60) {
    seconds = 0;
    minutes ++;
}

```
> 3 votes

# Answer
First of all, let me second Majenko in suggesting the use of an RTC. The Arduino Uno is clocked from a ceramic resonator, and these are nowhere accurate enough for proper timekeeping. C.f. the answers to How do I get an accurate time?.

Next, instead of counting seconds, I suggest you instead count *milliseconds*. I know it sounds like overkill, but it's actually simpler because you already have `millis()` returning a millisecond count:

```
void loop()
{
    uint32_t now = millis();
    static uint32_t last_minute;

    // Increment the time every minute.
    if (now - last_minute >= 60000) {
        last_minute += 60000;
        if (++minutes >= 60) {
            minutes = 0;
            if (++hours >= 24)
                hours = 0;
        }
    }

    // Do not advance the seconds when the user sets the time.
    if (time_is_being_set_by_the_user()) {
        last_minute = now;
    }
}

```

Oh, wait! No! Do not count milliseconds, instead **count microseconds**:

```
void loop()
{
    uint32_t now = micros();
    static uint32_t last_minute;

    // Increment the time every minute.
    if (now - last_minute >= 60000000) {
        last_minute += 60000000;

        // The rest does not change...
    }
}

```

Why? Because, as I said before, the ceramic resonator of your Arduino is not very accurate. You will eventually find out that it drifts significantly. However, if you compare to a good reference, you will be able to *calibrate* the drift. If, for example, you find that it drifts forward by 0.0025% (about 15 seconds per week, quite optimistic), you will be able to fix it simply by replacing 60000000 by 60001500. The same would work if counting milliseconds, except that you would only be able to do a coarse tuning. Oh, and do not worry about `micros()` overflowing.
> 2 votes

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


title: Piezo not loud enough

text:
# Question
Title: Piezo not loud enough
I'm trying to get 110dB out of a 25khz Piezo Transducer. This piezo resonates at 25khz and as per the illustration in its datasheet should emit 110dB with 10 volts and 25khz frequency.

Any assistence as to what I'm doing wrong here would be GREATLY appreciated !!

My code is bit-banging it. With an oscilloscope, I confirmed that I'm getting a nice clean 25khz square wave.

I have attached a step-up circuit to the device and am seeing 10volts across the terminals of the piezo while it is emitting it's 25khz frequency.

However, instead of 110dB, I'm only getting 50dB.

I've tried upping the voltage to 20, and still get the same volume level. The voltage is adjustable via the screw on the top of the blue capacitor on the Voltage Step Up (pictured below).

I've tried changing the duty cycle having HIGH go for 25microseconds and LOW go for 5microseconds. I've tried several combinations and a 50/50 duty cycle appears to achieve maximum volume which is 50dB.

Here's how I'm connected: 1. The inputs of the Step Up are attached to GND and 3.3V pins on the Arduino. 2. The output+ of the Step Up is connected to 1 pin of the Piezo. 3. The output- of the Step Up is NOT connected to anything. (tried to connect it to GND but it didn't change anything. 3. The other pin on the Piezo is connected to D11 on the Arduino.

I'm Running the following code:

```
 #include<Wire.h>

const int SPK = 11;

void setup()
{
  Serial.begin(9600);
  pinMode(SPK, OUTPUT);
  digitalWrite(SPK, LOW);
}

void loop()
{
  long startTime = millis();
  for (int i = 0; i < 25000; i++)
  {
    digitalWrite(SPK, HIGH);
    delayMicroseconds(15);
    digitalWrite(SPK, LOW);
    delayMicroseconds(15);
  }

  Serial.println(millis() - startTime);
}

```

UPDATE:

Ok, I am now set up to look like this:

Is this the next step (ie: Adding an Inducer) ?

# Answer
> 1 votes
The device you pictured seems to be a switch-mode power module which will output 10V **DC**. Get rid of it before you do any damage.

You don't post any link to data, but I assume you mean the Transducer needs 10V peak-to-peak.

This can easily be accomplished by using 2 digital outputs, connected to the transducer, and driven in anti-phase.

The answer to Push-Pull tone code may be an answer to your problem, but may be overkill. If you just want to output a single tone it is easily done with simple code.

I don't know why you think the transducer outputs 50dB. If it really is doubling the drive voltage will only give 56dB.

# Answer
> 1 votes
Alternatively there are COTS parts (Common Off The Shelf) which are simpler to use and may satisfy your requirements. This is just the 1st one I found (search for "5 volt piezo buzzer"). Of course you have no control over the frequency. These type of devices are just to get your attention (you didn't say what your application was for). While it works at 5 volts it is only rated at 85dB @ 10cm. It appears to contain an internal driver so (apparently) only needs 3 to 15 volts to start making noise. It is specified to draw 10mA at 12V. So be careful and measure the current (using a power supply, not from an Arduino) demand at 5 volts. I think the GPIO pins on an Arduino can only handle less than 40mA. So stay well below that to be safe.

---
Tags: arduino-nano, piezo, inductive
---


# Question
Title: What is using up all the RAM in my program?
I am running a program on the ATtiny and for some reason I am way over the 512 bytes of RAM that are available to me. This is confusing because when I did the math by hand I should have 432 bytes. Here is my code:

```
#include <SoftwareSerial.h>

#define FASTADC 1

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

SoftwareSerial mySerial(0,1);    //This uses 47 bytes of RAM

byte i = 0;      This uses 1 byte of RAM

byte pixelsArray1[128];   //Arrays use 128 bytes of RAM each
byte pixelsArray2[128];
byte pixelsArray3[128];

void setup()
{
#if FASTADC
// set prescale to 16
sbi(ADCSRA,ADPS2);
cbi(ADCSRA,ADPS1);
cbi(ADCSRA,ADPS0);
#endif

pinMode(1,OUTPUT);        //Setting the 1 pin to be used for output
pinMode(0,OUTPUT);        //Setting the 0 pin to be used for output
pinMode(A3,INPUT);         //Input for Camera 3
pinMode(A2,INPUT);         //Input for Camera 2
pinMode(A1,INPUT);         //Input for Camera 1

mySerial.begin(9600);     //Setting the data transfer rate
}

```

It's telling me that I am using 510 Bytes of memory but my math gave me 432 bytes of RAM. Does anyone see what I'm missing?

# Answer
There is a lot you are missing. Such as:

1. SoftwareSerial is using RAM.
2. The system stack is using RAM.
3. The Arduino core software is using RAM.

There's plenty more going on than just your sketch. For instance, where do you think it stores the current `millis()` and `micros()` counts? Where do you think incoming serial data gets buffered? Where do you think your registers, PC, etc, get stashed when a function (such as `setup()`) is called? All that takes RAM.
> 9 votes

---
Tags: attiny, memory-usage, memory
---


# Question
Title: Difference between Arduino IDE giving me headaches
For some time now I've been playing around with the latest version of Arduino IDE and my UNO and ATTiny with simple 433 RF links with the Manchester Library. It all worked fine, but for my next project I want to take the step up and use a better wireless thingy... like the nRF24l01 or the nfm12b.

And then starts the pain. Attiny does not have hardware serial, but people seems to have solved this by implementing software-serial. But then they have to use some other boards for ATTiny, because when I try to run the examples I get error messages that it could not find and so on. I use the ATTiny boards I found over at google code.

Regarding the RFM12B I got something to compile. If I went back and downloaded Arduino IDE 1.5.0 (no other!) it actually work with the JeeLib - hurray! Why is this, why can't I use the latest version of the Arduino IDE?

Regarding the NRF24 chip this case is unresolved. I have not found the correct combination of boards, IDE and library versions. Could anyone point me in the right direction?

What are the difference between the Arduino IDE's? Why can I get stuff to work on 1.5.0 but not the latest 1.6.x?

# Answer
To get RF24 working:

1. Download the latest IDE (not 1.0\*)
2. Use the library manager to download the latest RF24.
3. See https://github.com/TMRh20/RF24/issues/236#issuecomment-205354077 about what core to use.
4. Don't forget to define ATTiny in the sketch
Ex: `#define __AVR_ATtiny84__`
(84, 44, 24 are the choices)

ATTiny\* do not have SPI, that's why it can't find SPI.h (SPI library).
> 0 votes

# Answer
As far as I know, there was an internal dispute in the Arduino company. So now there are two companies selling under the Arduino name.

www.arduino.cc 's latest ide is 1.5.x and that has more features than www.arduino.org 's ide 1.6.x. So make sure you use arduino.cc's version only because they do the major development of the IDE.
> 0 votes

---
Tags: arduino-ide, attiny, nrf24l01+
---


title: Overwritten EEPROM

text:
# Question
Title: Overwritten EEPROM
I have a problem with the Teensy, its EEPROM and another Array.

My program contains two Arrays, the first one is a 128x4 long Array, the other one a 2560x2 double Array. The first Array is meant to be written to the EEPROM once a certain time (=number of loops) is reached. The other Array is meant to be written to an SD-Card or just the terminal, can't deiced yet.

My problem is that whenever I uncomment the save()-function the first 17 data-quadruples in the EEPROM get somehow overwritten by random data. Always the first 17 with would be the first 68 numbers or 272 byte.

I have tried renameing the save()-function, but the onlything that works for now is to comment the function in the loop()-function out so that it won't be called at all. I even have enough RAM left, the Arduino IDE tells me I am using about 73% of the RAM for variables.

Could it be that be creating more variables somewhere else the Teensy overwrites the Array for the EEPROM? But than again why doesn't that happen if I don't write into the everything-Array?

Thank you in advance for any help!

Greetings,

John

PS: Please excuse my not perfect English for it's not my native language.

```
//Includes
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <SPI.h>
#include <String.h>
#include <EEPROM.h>

elapsedMillis looptime = 0; //time for each loop in ms
int loopnumber = 0; //number of loops
elapsedMillis overalltime = 0; //overalltime in ms
const int iterationtime = 25; //time for each loop in ms

//EEPROM
//Deklarations
int nsd = 0; //counter for saving into eepromArray
const int maxArrayrows = 128; //Max number of row in eepromArray
int iArray = 0; //Number of used rows in eepromArray
long eepromArray[128][4]; //Array for EEPROM-storage
bool writtentoEEPROM = false;
double everything[2560][2]; //Big Araay with a pair of numbers of each loop

// Some more variables
double z, zpunkt, alpha, angle;

void setup() {
 // Just inititialing stuff, nothing to do with the Arrays
}

void loop() {
  //Calculating more stuff

  ++nsd;
  if (nsd >= 20) {
    WritetoArray();
  }

  save(loopnumber);

  ++loopnumber;

  looptime = 0;
}

//********************************************************
//
// Save Data in Array. If full write into EEPROM
//
// long: 4 byte
// Storeage needed for each quadruple: 4*4 byte = 16 byte
// EEPROM-size: 2 kibyte
// Max number of quadruples: 2048 byte / 16 byte = 128
// Quadrupels per second: 2
// Max time: 128 / 2 = 64 s
//
//********************************************************
void WritetoArray() {
  int scale = 10000;
  long zArray = (long)(scale * z);
  long zpunktArray = (long)(scale * zpunkt);
  long alphaArray = (long)(scale * alpha);
  long angleArray = (long)(scale * angle);
  if (iArray < maxArrayrows) {
    eepromArray[iArray][0] = zArray;
    eepromArray[iArray][1] = zpunktArray;
    eepromArray[iArray][2] = alphaArray;
    eepromArray[iArray][3] = angleArray;
    ++iArray;
  }
  else {
    if (writtentoEEPROM == false) {
      WritetoEEPROM();
      writtentoEEPROM = true;
    }
    while(true){
      for(int n = 0; n < 2560; ++n){
        Serial.printf("%f, %f\n", everything[n][0], everything[n][1]);
      }
      Serial.println("----------");
    }
  }
  nsd = 0;
}

//********************************************************
//
// Write Data to EEPROM
//
//********************************************************
void WritetoEEPROM() {
  byte data;
  int adress = 0;
  int  i = 0;
  while (adress < 2048) {
    for (int n = 0; n <= 3; ++n) {
      for (int a = 0; a <= 3; ++a) {
        data = (eepromArray[i][n] >> ((3 - a) * 8)) & 0x000000ff;
        EEPROM.write(adress + a, data);
      }
      adress = adress + 4;
    }
    ++i;
  }
}

//********************************************************
//
// Save data-pair for later usage
//
//********************************************************
void save(int l) {
  everything[l][0] = z;
  everything[l][1] = angle;
}

```

# Answer
> 2 votes
In your loop(), you increment repeatedly loopnumber without ever resetting it. You should at the very least replace

```
loopnumber++ ;

```

with

```
loopnumber = (loopnumber+1)%2560 ;

```

Otherwise, when loopnumber becomes \>= 2560, your save() function will begin writing outside the 'everything' array and overwriting whatever is written in the adjacent positions of memory.

---
Tags: teensy, eeprom, array
---


title: Create a library without a class?

text:
# Question
Title: Create a library without a class?
I'd like to know if it's possible to create a library for Arduino that does not contain a class, just functions.

I know how to create a library with a class, but I'd like to create a library of general purpose functions that don't need to be instantiated to be used. Just used like the standard functions included in the Arduino IDE: sizeof(), etc..

Is this possible? If so, can anyone point me in the direction of a template? I've been searching, but haven't found anything.

Thanks!

# Answer
> 3 votes
Yes, it's possible.

Just don't make a class. Just make functions instead.

Like a class-based one, have a `.cpp` and a `.h` file. In the `.cpp` file (or `.c` file if you don't want any of the C++ functionality or 90% of the Arduino API available to you) place your functions.

In the `.h` file place prototypes for them. I am in the habit of adding the `extern` keyword, but you don't actually need to for functions.

For example:

```
foo.cpp:

void doSomething() {
    // whatever
}

foo.h:

extern void doSomething();

```

Then you can include your `.h` file and call your functions:

```
#include <foo.h>

// ...

doSomething();

```

---
Tags: library, class
---


# Question
Title: Arduino mega 2560 Stacked with Ethernet/SD card Shield Heat up
Stacked mega and ethernet/sd shield:

When I do this stacking, it heats up. I tried connecting the SPI via ports 13-10 (no stacking), it doesn't work. Also tried connecting the ICSP (red circled mark) via male-female wires without stacking, it works, but still heats up. So I think the ICSP has a defect? or does it? Is it supposed to be like this and I'm just being paranoid?

\*PS: the heat in the "pain" level when I touch it, no burning IC odor. Maybe it's because I unplug it immediately after short use? IDK.

\**update, I think I got it working, the problem was not about the heating, but the program. Consulted a more experienced person, he said what's happening is normal.

# Answer
> 0 votes
> *the heat in the "pain" level when I touch it, no burning IC odor. Maybe it's because I unplug it immediately after short use? IDK. So I think the ICSP has a defect? or does it? Is it supposed to be like this and I'm just being paranoid?*

Well you're right in being a bit paranoid. And temperature building up is very likely to mean you've got a short somewhere, it might be a bad solder or a component that fails (like a cap that conducts).

So you've got to isolate the issue:

1. Isolate the faulty board: whichever board is getting hot, it might be that one that has a failure *or* the other one ruining it
    * you need to try the shield with another arduino (whatever version it is) and see if the issue is replicating
    * then you need to try the arduino you were using with another shield running on ICSP (like another ethernet shield, or an SDCard shield), which will confirm the hypothesis that only one component of the two is failing.
2. Once you've isolated the board, you need to isolate the component.
    * you first have to isolate which component is building up heat.
    * If you've got access to a thermal camera, it's a good idea to use it.
    * If not: start locating the area where heat is building with your finger, and then test each component of the area with a thermometer (like the ones you plug on a multimeter, or simply a "meat" thermometer for cooking).
3. Once you've isolated the component, then look it up on the schematics and layout, and lookup all connected components. Either that component or one on the track is failing, or there's a short on that track.

If the solution is not obvious, you can come back on Stack Exchange (get on the electronics QA site with your results), and some EE expert will help you find out what's wrong!

HTH

---
Tags: ethernet
---


# Question
Title: Why doesn't my 1602A LCD display text with this code?
```
#include <SPI.h>
#include <MFRC522.h>
#include <LiquidCrystal.h>
#include <Servo.h>

#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Servo myservo; // create servo object to control a servo

String read_rfid;
String ok_rfid_1 = "6722323b";
String ok_rfid_2 = "99be859e";
int posClosed = 180; // variable to store the servo position for locked
int posOpen = 0; //same for open...

/*
  Initialize.
*/
void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin(); // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  lcd.begin(16, 2);
  lcd.clear();
  lcd.print("Scan your card:");
  Serial.println("Scan your card:");
  //Choose which lock below:
  myservo.attach(7); // attaches the servo on pin 7 to the servo object
}

/*
  Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
  read_rfid = "";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
}

void open_lock() {
  //Use this routine when working with Servos.
  lcd.print("Servo Unlocking");
  myservo.write(posOpen);
  Serial.println("Servo Unlocking");
  delay(10000);
  myservo.write(posClosed);
  lcd.clear();
  lcd.print("Servo Locking");
  Serial.println("Servo Locking");
}

void loop() {
  lcd.clear();
  lcd.print("test");
  // Look for new cards
  if (!mfrc522.PICC_IsNewCardPresent())
    return;
  // Select one of the cards
  if (!mfrc522.PICC_ReadCardSerial())
    return;
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  if (read_rfid == ok_rfid_1) {
    open_lock();
    lcd.clear();
    lcd.print(read_rfid + " (FRED FARMER)" + " -Access Granted");
    Serial.println(read_rfid + " (FRED FARMER)" + " -Access Granted");
    delay(10000);
    lcd.clear();
    lcd.print("Scan a card:");
    Serial.println("Scan a card:");
  }
  if (read_rfid == ok_rfid_2) {
    open_lock();
    lcd.clear();
    lcd.print(read_rfid + " (JOHN DOE) " + " -Access Granted");
    Serial.println(read_rfid + " (JOHN DOE) " + " -Access Granted");
    delay(10000);
    lcd.clear();
    lcd.print("Scan a card:");
    Serial.println("Scan a card:");
  } else {
    lcd.clear();
    lcd.print(read_rfid + " -Access Denied");
    Serial.println(read_rfid + " -Access Denied");
    delay(10000);
    lcd.clear();
    lcd.print("Scan your card:");
    Serial.println("Scan your card:");
  }
}

```

I have tried running the Arduino library's "Hello World" example, and it successfully runs the text onto the screen. Therefore I have determined that it is not a hardware problem, rather a code problem. It occasionally does display "ff" on the LCD, but that's it.

# Answer
> 1 votes
Pins number 12, 11 are used by some other library in your code. And that's the reason there is no LCD output. Change pins/connections from 12, 11 to 7, 6.

Then your code uses `lcd.clear()` too often, so whatever data you display vanishes before you were able to read. Don't clear the display unnecessarily.

---
Tags: arduino-uno, lcd, rfid, code-review
---


# Question
Title: How to disable the write protection of the USART mode register?
I have a device which transmits USART with inverted polarity, and I would like to read data from it with the help of an Arduino. I use an Arduino Due, which has a SAM3X processor, so it should be able to invert the polarity without any external hardware.

The settings accessible from the Arduino SDK are minimalistic, `Serial.begin()` only allows to set the baudrate and start/parity/stop, nothing else.

In the SAM3X datasheet I found the "USART Mode Register", `US_MR`, which dedicates bit 23 (`INVDATA`) to invert the polarity.

Although it seems not to be documented anywhere, I found in a forum that to access the `US_MR` register, I have to use `UART->UART_MR`. I can read that register but cannot change it. The SAM3X datasheet mentions that this register might be write protected, and that the write protection can be cleared in the `US_WPMR` register.

However, the Arduino SDK doesn't seem to know about this register. I tried several possibilities,

```
US_WPMR
UART_WPMR
WPMR
UART->US_WPMR
UART->UART_WPMR
UART->WPMR

```

None of which are known.

The string `WPMR` is nowhere to be found in any of the files in my Arduino installation folder.

**EDIT:**

Interestingly, the source code for the UART class doesn't contain any reference to the WPMR. It just sets the required configuration registers without bothering with it.

```
void UARTClass::begin( const uint32_t dwBaudRate )
{
  // Configure PMC
  pmc_enable_periph_clk( _dwId ) ;
  // Disable PDC channel
  _pUart->UART_PTCR = UART_PTCR_RXTDIS | UART_PTCR_TXTDIS ;
  // Reset and disable receiver and transmitter
  _pUart->UART_CR = UART_CR_RSTRX | UART_CR_RSTTX | UART_CR_RXDIS | UART_CR_TXDIS ;
  // Configure mode
  _pUart->UART_MR = UART_MR_PAR_NO | UART_MR_CHMODE_NORMAL ;
  // Configure baudrate (asynchronous, no oversampling)
  _pUart->UART_BRGR = (SystemCoreClock / dwBaudRate) >> 4 ;
  // Configure interrupts
  _pUart->UART_IDR = 0xFFFFFFFF;
  _pUart->UART_IER = UART_IER_RXRDY | UART_IER_OVRE | UART_IER_FRAME;
  // Enable UART interrupt in NVIC
  NVIC_EnableIRQ(_dwIrq);
  // Enable receiver and transmitter
  _pUart->UART_CR = UART_CR_RXEN | UART_CR_TXEN ;
}

```

However, when I try to change `UART_MR`, it remains the same.

# Answer
Under Windows, Arduino puts the source code for hardware specific stuff in User\AppData\Local\Arduino, and not in the installation folder.

```
/* -------- US_WPMR : (USART Offset: 0xE4) Write Protect Mode Register -------- */
#define US_WPMR_WPEN (0x1u << 0) /**< \brief (US_WPMR) Write Protect Enable */
#define US_WPMR_WPKEY_Pos 8
#define US_WPMR_WPKEY_Msk (0xffffffu << US_WPMR_WPKEY_Pos) /**< \brief (US_WPMR) Write Protect KEY */
#define US_WPMR_WPKEY(value) ((US_WPMR_WPKEY_Msk & ((value) << US_WPMR_WPKEY_Pos)))

```

I would guess unlocking / locking would take the format:

```
????->US_WPMR = (US_WPMR_WPEN | US_WPMR_WPKEY(0x555341));
????->US_WPMR = (~US_WPMR_WPEN & US_WPMR_WPKEY(0x555341));

```
> 1 votes

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


# Question
Title: Lighting LED Strip via HC-06 Bluetooth Module
**What I Am Working With:** I am working on a project involving an Arduino, some RGB led strip, and my PC.

**My Project:** The PC sends UART (serial) data to the Arduino over Bluetooth (through a HC-06 Bluetooth module connected to the Arduino) to change the color of the LED strip. The user could also change "lighting modes" to instruct the Arduino to make the LED blink, fade, etc.

**My Problem:** Having no RTOS nor interruptions on data reception, it would be impossible for me to make the LED fade and, also, to receive Bluetooth data to change the lighting mode.

I would appreciate whatever input the community has regarding this problem.

Thanks in advance, Stanislas.

# Answer
> 0 votes
Yes, it can be done. You don't need a realtime OS for something as simple as that. Basically in your loop function you would check the serial port and parse the input (if available) to see if the PC instructed the arduino to change its mode. Then you would call a function - say nextstep() - which would perform whatever the next step is, depending on your current mode. True, when you get serial input your loop() will take longer to execute, which will alter the 'rhythm' of your fades etc. If this is important, you should replace the call to delay() with a loop checking millis() against a value stored at the start of loop().

```
int currentmode ;
int previousmode ;

void loop()
{
   previousmode = currentmode ;
   currentmode = getnewmode(currentmode) ;
   if (currentmode != previousmode)
      initmode(currentmode) ;  // turn new mode on e.g. change LED color
   nextstep(currentmode) ;     // if current mode is dynamic, make change
   delay(DELAY_INTERVAL) ;
}

int getnewmode(oldmode)
{
   if (!serialpending()) // no serial input
      return oldmode ;
   return parseinput() ;
}

```

---
Tags: bluetooth, interrupt, rgb-led, threads
---


title: Measuring Time Between Inputs

text:
# Question
Title: Measuring Time Between Inputs
I'm trying to measure the amount of time that has passed between every time a reed switch mounted on a wheel is activated to calculate the speed of a bike in miles per hour and display it on two 7 segment LEDs. This is what I have so far (without 7 seg code, as that works):

```
const int reed = A3;
float circumference;
float pi = 3.141592653589
unsigned long time0 = 0;
unsigned long time1;
unsigned long revolutionTime;

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

void loop() {
  circumference = (pi * 26); //26 = the diameter of the wheel
  int reedState = digitalRead(reed);
  if (reedState == HIGH) {
    time1 = millis();
    revolutionTime = (time1 - time0);
    time0 = time1;
    int mph = ((circumference / revolutionTime) * (3600000 / 63360)); //this is the conversion from inches/millisecond to miles/hour.
    Serial.println(mph);
    //And I'd print the result on the 7 segment displays here
  }
}

```

This code results in around 25 printed entries in the serial monitor from a single activation of the reed switch, all of which consist of randomly alternating values of either 0 or 4571.

Following each step of the code, I assume that the program would generate a garbage result for the first entry (because the time before the reed is activated for the first time could vary greatly), but that following entries would be the correct mph displayed on the 7 segment displays until the reed switch is activated again and a new mph is calculated.

So how would I go about modifying the code to get useful data?

# Answer
Currently your code is not working, because Arduino is fast enough to check the closed switch state many times before it opens again, so before calculating a new speed value, you need to see LOW on the input.

Still, there are at least 2 better ways to do what you want.

**pulseIn()** \- a function intended just for what you are trying to do: measuring lenght of a pulses. If your switch is active HIGH, you need to measure length of a LOW pulse:

```
unsigned long duration;
duration = pulseIn(reed, LOW);
// calculate speed basing on duration (in microseconds)

```

Keep in mind, that `pulseIn()` is a blocking function, so no code will be executed, until it receives the pulse. You can counter it bu specifying a timeout, after which, the program will continue.

**External interrupts** are an another approach. Interrupt handling routines are executed when a specified event occurs, no matter if the microcontroller is busy doing something else or not. They would guarantee, that you will not miss any pulse even if they would have frequency in order of kHz.

```
volatile unsigned long lastTime = 0;

void setup() {
    attachInterrupt(0, readTime, RISING);
}

void readTime() {
    unsigned long t = millis();
    // calculate speed basing on t - lastTime
    lastTime = t;
}

```

Interrupt handling routine should be as short as possible. Avoid using delays in it, doing Serial.print and other communications. Also, millis() and micros() will not increment during execution of interrupt handler.

**Debouncing** \- even with above two methods, things may still not work properly. The most probable cause would be switch "bouncing". You can counter it by

* software debouncing - delaying after `pulseIn()` or ignoring interrupts for some period of time after first interrupt is detected
* adding a small (10-100nF) capacitor at the input, that will act as a low-pass filter, cutting out short pulses
* using not a reed switch, but a hall sensor with hysteresis
> 3 votes

# Answer
A: Use interrupts to detect the state change on the reed switch
B: Use a hall sensor instead of the reed, they do not suffer switch bounce
C: Use a debounce circuit, a 74HC14 with a small capacitor connected between ground and the input
Put a 4K7 resistor as pullup between VCC & the input
Put a 100 ohm resistor on the wire coming from the Reed, which is connected to GND on the other side

The 100 ohm prevents discharge damage to the contacts from the capacitor and suppresses RF interference

Ground all unused inputs and feed the output of the active channel to the Arduino The 74HC series are 3v3 & 5V compatible, the 74HCT series is only 5V compatible but are more suited as level shifters from 3v3 signals to 5V output

D: use a software debounce routine
> 1 votes

# Answer
Imagine your wheel rotating very slow ... imagine time was slowed down. Imagine the magnet comes to the reed sensor and closes the switch. You will now take a measurement. The Ardunio code loop will end and immediately restart ... because time has been slowed (in our story), the wheel will have barely moved and AGAIN you will take another measurement because the reed switch is STILL closed because the magnet hasn't moved far enough.

I believe you need to change your logic such that after you detect the reed switch closing, you then need to detect that the reed switch is OPEN again ... before once more looking for the reed switch to close. Something like:

```
if (reedState == HIGH) {
   // do something
   while(digitalRead(reed) == HIGH) {
      // do nothing
   }
}

```
> 0 votes

# Answer
Your test `if (reedState == HIGH)` does not tell you when the reed switch is *activated*, it tells you when it's *active*, which is not the same. You should instead look at when the switch transitions from `LOW` to `HIGH`, which means you also have to remember the last state.

For example (untested):

```
void loop() {
    static int lastReedState;
    static unsigned long lastTransition;
    int reedState = digitalRead(reed);

    // On a rising transition of the reed switch:
    if (reedState == HIGH && lastReedState == LOW) {

        // Compute time since last valid transition.
        unsigned long now = millis();
        unsigned long revolutionTime = now - lastTransition;

        // Debounce: this transition is valid only if enough time has
        // elapsed since the last valid one.
        if (revolutionTime > 20) {

            // Compute and report speed.
            int speed = circumference / revolutionTime;
            Serial.println(speed);

            // Remember this transition.
            lastTransition = now;
        }
    }

    // Remember last state.
    lastReedState = reedState;
}

```

This assumes `circumference` has already been calculated and has the appropriate unit (miles⋅ms/h if you want the speed reported in mph). Actually it could be a compile-time `int` constant (4641), which would avoid having floating point calculations at run time.
> 0 votes

---
Tags: programming, time, millis
---


# Question
Title: ATtiny85 (Sparfun Clone/Trinket), detect/read operation voltage
I just started with Arduino programming and currently I'm using this Sparkfun clone board:

o http://nl.aliexpress.com/item/Digispark-kickstarter-Micro-development-board-ATTINY85-module-for-Arduino-usb/32584975067.html

It's really nice and like the way to program it and 'burn' it, it's easy to do. For the first project, I came along this instructable, an USB volume knob:

o http://www.instructables.com/id/Digispark-Volume-Control/

I'm using the Sparkfun Arduino programming IDE with added AdaFruit Trinket USB library (Trinket is also ATtiny85), download source, tweak it a bit to my needs and it's working perfectly. Had some programming question though, see also:

o https://stackoverflow.com/questions/37740026/change-override-trinket-attiny85-usb-identification-name-device-name/37743886#37743886

o https://stackoverflow.com/questions/37769451/arduino-make-a-library-more-optional-by-project?lq=1

o https://stackoverflow.com/questions/37824336/arduino-trinket-attiny85-usb-possible-to-read-the-state-of-all-keys

Anyway, optimized the source code (original not really a beauty), play with it and added also a fade-In/fade-out idle feature to the LED on PIN 1 and it blinks when turning the dial encoder.

I want to add add some more features to this knob, such as pushbuttons to change some internal modes. For example:

* Toggle button for knob sensitivity (3-modes: slow (default), normal, fast)
* A mute button

I want to that device 'remember' the state of the toggle button but there is no option (flash memory) to save the state. So I came with the idea to use a backup button cell to keep the device 'alive' when disconnected from USB (or computer turned off). A Button cell is 3V and USB is 5V so maybe is possible to 'test' the input voltage. If this is possible you can put the device in sleep mode (low power mode) directly after detecting USB connection lost and this voltage drop.

I have read already an article how to put the device into sleep mode (and awake from it):

o https://bigdanzblog.wordpress.com/2014/08/10/attiny85-wake-from-sleep-on-pin-state-change-code-example/

**Question is:**

Can I measure somehow the voltage is used to power the device? Any ideas (code example please if it is possible)?

# Answer
> 1 votes
There are a few solutions.

* If you want to save te state of your toggle button you can save it in the eeprom of your attiny85
* You can use an ADC pin to check your VCC against the internal 1.1V reference
* alternatively you can read the 1.1ref aganist Avcc. https://digistump.com/board/index.php?topic=1104.0

---
Tags: c++, voltage-level, attiny, input
---


title: Remove certain characters from char*

text:
# Question
Title: Remove certain characters from char*
I've got an array of char\* with serial data that I'm trying to remove ':' from. I have tried to iterate through the char\*, find and remove any colons but it just comes out as garbage.

```
  char* espData[15];

  // pull data from serial and tokenize with strtok > feed to espData

  for(int x = 0; x < index-1; x++){
    size_t nullTerm = strlen(espData[x]);
    espData[x][nullTerm - 1] = '\0';
    char* output
    for(size_t i = 0; i < strlen(espData[x]); ++i){
      if(espData[x][i] != ':') output += espData[x][i];
    }
    espData[x] = output;
    Serial.println(espData[x]);
  }

```

Moving the null character works fine (I wanted to get rid of the last character in every string). Most of the answers I found for general C++ used std::string which we don't have access to.

# Answer
> 1 votes
You've assumed that a `char *` is some kind of string object, since you've got the following line of code: `output += espData[x][i];`, and then later `espData[x] = output;`

It quite simply doesn't work like that. At best you can point `output` inside `espData[x]` and then do some other logic: but your attempt to "accumulate" the correct characters is incorrect.

Please consider the following code instead:

```
char* espData[15];

for(int x = 0; x < index-1; x++){
    size_t nullTerm = strlen(espData[x]); // Get current length
    char* output = espData[x];            // Start of string
    for (size_t i = 0; i < nullTerm; ++i){
        if(espData[x][i] != ':') {        // If it's NOT a colon
            *output++ = espData[x][i];    // Copy character 'up'
        } // if
                                          // If it WAS a colon, then
                                          // output does NOT get incremented
    } // for
    *output = '\0'; // End string off with NUL
    Serial.println(espData[x]);
} // for

```

---
Tags: string, array, pointer
---


# Question
Title: Would rewriting my code in C help reduce RAM usage?
So my program fails to run because there is not enough room for my variables as well as the Arduino Core and Stack. I can't find any more ways to optimize my program so I'm thinking about just rewriting it in C.

However, I'm not sure if that will actually help me. For example I know that in C my program will run faster because things like `digitalWrite()` and `analogRead()` have a bunch of "extras" that make it go slower, but I don't know if this will affect RAM.

So can any of the experts on here tell me if writing my code will help before I waste time doing so?

Here is my code:

```
#include <SoftwareSerial.h>
#include <avr/pgmspace.h>

#define FASTADC 1

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

SoftwareSerial mySerial(0,1) PROGMEM;

byte i;

byte pixelsArray1[128];   //Array to hold the values of the individual pixles.
byte pixelsArray2[128];   //Array to hold the values of the individual pixles.
byte pixelsArray3[128];   //Array to hold the values of the individual pixles.

void setup()
{
  #if FASTADC
   // set prescale to 16
   sbi(ADCSRA,ADPS2);
   cbi(ADCSRA,ADPS1);
   cbi(ADCSRA,ADPS0);
  #endif

  pinMode(1,OUTPUT);        //Setting the 1 pin to be used for output
  pinMode(0,OUTPUT);        //Setting the 0 pin to be used for output
  pinMode(A3,INPUT);        //Input for Camera 3
  pinMode(A2,INPUT);        //Input for Camera 2
  pinMode(A1,INPUT);        //Input for Camera 1

  mySerial.begin(9600);     //Setting the data transfer rate
}

```

Notes:

* I'm programming on the ATtiny85
* I'm running Windows 10
* I've never programmed in Arduino before

# Answer
> 4 votes
The simplest approach to reducing RAM usage of the program shown is to get rid of the three 128-byte pixel arrays. They are not needed for the program to function.

Instead of writing

```
pixelsArray1[i]=analogRead(A1)/4;
pixelsArray2[i]=analogRead(A2)/4;
pixelsArray3[i]=analogRead(A3)/4;

```

write

```
if (analogRead(A1)/4 == 0 && analogRead(A2)/4 == 0 && analogRead(A3)/4 == 0) ++foundZero;

```

where `foundZero` is initialized to zero before the loop. After the loop, you say something like

```
while (foundZero--) {
  digitalWrite(1, HIGH);
  delay(2000);
  digitalWrite(1, LOW);
  delay(2000);
}

```

to toggle pin 1 as many times as there were three zero pixels.

Note, the timing of the `if (...) ++foundZero;` statement may differ from pixel to pixel because the `&&` evaluation may short circuit. If the timing matters, save data in temporary variables, or check if the sum of the three is zero, etc.

# Answer
> 0 votes
I don't believe that rewriting it in C is going to help you much: the framework is pretty tight already, and you'd only get the C library's versions of the various drivers' buffers etc.

I do think your only solution (apart from getting larger hardware!) is to 'optimise' the `pixelArray`s. To do that, could you consider the following questions:

1. What is the worst value resolution that you'll get away with? You're currently compressing each camera feeds' pixel to the range 0-255, to store them into their individual bytes. What about 0-31? (See why below)
2. Will you always be comparing each feed's individual pixels against the same pixel in another feed? If so, perhaps you could pack all three values into one 16-bit quantity:
`X 11111 22222 33333`
where each quintet of bits is that feed's value compressed down. The `X` is cute: before compressing, you could compare all three values with each other, or zero, or something, and if true set the X bit to `1`. That then means that you can later test for that exact condition in the triple-pixel with a `<0` check - the sign bit will be set, so the condition will be true.
3. Or, if compressing down to 0-31 is too extreme, what about storing a 'master' copy of the pixel, and then two (scaled) differences from there: `11111111 2222 3333` where the master `1` value is unscaled (other than `/4`), while the other values are from the following table:

`0000` \- Identical pixel value
`0001` \- Within +2
`1111` \- Within -2
`0010` \- Within +4
`1110` \- Within -4
`0011` \- Within +8
`1101` \- Within -8
`0100` \- Within +16
`1100` \- Within -16
`0101` \- Within +32
`1011` \- Within -32
`0110` \- Within +64
`1010` \- Within -64
`0111` \- Within +128
`1001` \- Within -128
`1000` \- More than ±128
4. Even more radical: could you do all the tests when you read the data (do you have time???), and then simply store a one-bit result for each pixel? Such a packed-bit array is VERY efficient - if you can boil down your decision to yes/no...

I'd be happy to help write (reasonably) efficient C code to implement the TriplePixel functions - or even attempt it in assembly...

---
Tags: programming, c, attiny, memory-usage, memory
---


# Question
Title: Unable to create a desired periodic signal with Arduino Mega 2560 and DAC0808
I wrote the code to produce the periodic signal by using arduino and DAC0808 where i turned on and off the respectively pins of PORTA by using a logic in iterative manner and created the periodic signal. But even without using delay logic, i couldn't get signal time period as comparable to 50 Hz voltage signal. And what i seek to get is to decrease the time period of generated signal. Pls note, blue signal is reference signal of 50Hz frequency.

```
float increment = 3.14159 / 500;
float initial = 0;
float value = 0;

void setup() {
  Serial.begin(115200);
  DDRA  = B11111111;
}

void loop() {
  // put your main code here, to run repeatedly:

  PORTA = B00000000;
  while (1)
  {
    initial = initial + increment;
    value = sin(initial)  * 255;
    PORTA = abs(value);
  }

}

```

# Answer
As has been mentioned before, in comments and in jwpat7's answer, your main problem here is the time taken to compute the sines. I already provided a link to a faster fixed-point implementation of `sin()` but, since you have an Mega2560 with loads of RAM, I would go to the simpler look-up table method. I would not even bother optimizing the size of the table.

For controlling the timing, you can use the canonical method described in the Blink Without Delay Arduino tutorial, with one twist: times should be measures with `micros()` instead of `millis()`. Here is a first version of the program:

```
const float FREQUENCY = 50;            // hertz
const float PERIOD = 1e6 / FREQUENCY;  // microseconds
const size_t TABLE_SIZE = 512;
const uint16_t SAMPLE_TIME = PERIOD/TABLE_SIZE + 0.5;
uint8_t wavetable[TABLE_SIZE];

void setup()
{
    // Prepare the wavetable.
    for (size_t i = 0; i < TABLE_SIZE; i++) {
        wavetable[i] = 255 * abs(sin(M_PI * i / TABLE_SIZE));
    }

    // Set port A as output.
    DDRA = 0xff;
}

void loop()
{
    uint16_t now = micros();
    static uint16_t last_sample;
    static size_t phase;

    if (now - last_sample > SAMPLE_TIME) {
        last_sample += SAMPLE_TIME;
        PORTA = wavetable[phase];
        phase = (phase + 1) % TABLE_SIZE;
    }
}

```

A few things worth noting:

1. The float constants `FREQUENCY` and `PERIOD` are used only at compile time.
2. The table size is a power of two because wrapping a table index modulo a power of two is way faster than modulo, say, 500: the compiler optimizes the modulo into a bitwise AND.
3. The `+ 0.5` in the expression of `SAMPLE_TIME` is intended to ensure that the result is rounded to the *nearest* integer. In this instance it happens to be useless because rounding down would give the same result.
4. The `micros()` function returns a 32-bit integer, but in this application it is sufficient and faster to track only the 16 least significant bits, hence the `uint16_t` timing variables. And no, these variables overflowing is not a problem.

This should give you, in theory, a frequency of 50.08 Hz, i.e. 0.16% too fast. The discrepancy is due to `SAMPLE_TIME`, which should be 39.0625 µs, being rounded to 39 µs. You could fix this by counting time with a higher resolution, but given the poor accuracy of the ceramic resonator clocking the Arduino, this is probably not worth the trouble.

A potentially worse problem is the large jitter you have with this approach, on the order of 10 µs. This is due both to the time taken to run through the loop and the occasional timer interrupt taking some extra time. You can get rid of this jitter by using a timer interrupt instead of `micros()`. Here is a second version of the program that uses this approach:

```
#include <avr/sleep.h>

const float FREQUENCY = 50;              // hertz
const float PERIOD = F_CPU / FREQUENCY;  // CPU cycles
const size_t TABLE_SIZE = 512;
const uint16_t SAMPLE_TIME = PERIOD/TABLE_SIZE + 0.5;
uint8_t wavetable[TABLE_SIZE];

int main()
{
    // Prepare the wavetable.
    for (size_t i = 0; i < TABLE_SIZE; i++) {
        wavetable[i] = 255 * abs(sin(M_PI * i / TABLE_SIZE));
    }

    // Set port A as output.
    DDRA = 0xff;

    // Configure Timer 1.
    OCR1A = SAMPLE_TIME - 1;  // set the period
    TIMSK1 = _BV(OCIE1A);     // enable TIMER1_COMPA interrupt
    TCCR1B = _BV(WGM12)       // CTC mode with TOP = OCR1A
           | _BV(CS10);       // clock at F_CPU / 1

    // Sleep while waiting for interrupts.
    sei();
    sleep_enable();
    for (;;) sleep_cpu();
}

// Service routine for the Timer 1 interrupt.
ISR(TIMER1_COMPA_vect)
{
    static size_t phase;

    PORTA = wavetable[phase];
    phase = (phase + 1) % TABLE_SIZE;
}

```

Again, a few notes:

1. The `SAMPLE_TIME` is now computed in CPU cycles and, since it is an integer number of cycles (namely 625), there should in principle be no frequency discrepancy.
2. For counting 625 cycles we need a 16-bit timer clocked at the full CPU speed (prescaler = 1). We are using Timer 1 here. See the datasheet of the ATmega2560, chapter 17, for details on using the timer.
3. Sleeping between interrupts is needed in order to obtain cycle-accurate timings. If we had simply an infinite loop, there could be a few CPU cycles of jitter, which may not be a big deal.
4. Writing `main()` instead of `setup()` and `loop()` is a way to skip the initialization normally done by the Arduino core library. In this application that initialization is better avoided, because it creates an extra jitter-inducing interrupt and it messes with Timer 1 in a way that we would need to undo.
> 0 votes

# Answer
I'm interpreting your phrase “even without using delay logic, i couldn't get signal time period as comparable to 50 Hz” as meaning that the code shown runs Too Slow. At 1000 samples per cycle and 50 Hz on an 8-bit 16-MHz processor, you only have 320 clocks to compute a `sin()`, which probably is not enough to compute a 32-bit floating `sin()`.

To speed it up, you can either issue fewer samples per cycle or make the loop go faster.

For the “fewer samples per cycle” approach, you would make `increment` bigger; for example, instead of 3.14159/500, or 1000 samples per cycle, perhaps an interval of 2π/500, or 500 samples per cycle.

For the “make the loop go faster” approach, you could use a lookup table or fixed-point integer arithmetic or both. Note, the lookup table only needs to cover 90° (or π/2 radians); index in reverse for quadrants 2 and 4, and negate values for quadrants 3 and 4.

Note, after you speed up the code, you will need to set up a time base for issuing samples. This could use a clock-based interrupt routine that gets and issues the next array value, or that sets a flag so your main loop can get and issue a value. Or you could spin until `micros()` exceeds a deadline, at which time you (1) issue a value, (2) set the next deadline, and (3) compute the next value.
> 1 votes

---
Tags: arduino-mega, arduino-ide, electronics
---


# Question
Title: Feasibility of a Wi-Fi Positioning System
In the project of guiding a sight disabled person in a known environment, we need to have a precise way of figuring out where the user is. Our current solution is to use WPS.

This is however our first project with Arduino, and we're not quite sure if we're going the right way about this. We're thinking of getting a compass component and such, but is there something we should know before advancing further in the project?

EDIT: Additional information. The system is placed on the user, most probably strapped to the arm. The communication to the Wi-Fi beacons will be done from there, as well as the calculations.

The environment is supposed to be as complex as an exposition hall, but we can aim higher.

Budget range is around $100, Arduino itself excluded. A UNO is already provided to us.

# Answer
I don't think that arduino is the right hardware for such a project. Better use a cheap android phone, there you have a stronger processor with more memory as well as a lot of sensors like compass, accelerometer, gyroscope and maybe in newer ones barometer, which you will need - also you have wifi. An arduino uno just comes without wifi and all the sensors. Also I guess a lot of persons already have a phone, so this will lower your project costs, because hardware is already available at most users. Last but not least I think you could use mobile phone vibrations to give feedback to the sight disabled users, oder sound commands like "go left" etc.
> 1 votes

---
Tags: wifi, components
---


title: Add string inputs into an array

text:
# Question
Title: Add string inputs into an array
I have been working on this a while and I cannot seem to figure it out. Essentially, I am using the app/server Blynk and their Terminal Widget to sent String inputs to my Arduino board. My code is below: `String INFO;
 String fromTerminal = param.asStr();
 int indexstart = fromTerminal.indexOf(",");
 int indexend = fromTerminal.lastIndexOf(",");
 int counter = indexstart - indexend;
 INFO[counter] = fromTerminal;`

My thoughts on the code was, based on the number of "," I enter in the string then that will assign my input to an index within the INFO array. However as I have tried several different things, I constantly get errors such as: cannot convert 'String' to 'char' in assignment. Oddly enough if I set: INFO\[counter\] = fromTerminal.toInt(); I dont get an error but I dont think that will allow me to print out my actual input. Any help is much appreciated, thanks!

# Answer
> 1 votes
I think you should better read about the String Object and don't mix this up with string as char array.

---
Tags: array
---


# Question
Title: Random output on decoding time from LTC audio using arduino UNO
I am a newbie in Arduino and I am trying to decode time from ltc audio. For this I got Arduino UNO.

I got a sample code from here.. Here my code:

```
#define icpPin 8        // ICP input pin on arduino
#define one_time_max          588 // these values are setup for NTSC video
#define one_time_min          422 // PAL would be around 1000 for 0 and 500 for 1
#define zero_time_max          1080 // 80bits times 29.97 frames per sec
#define zero_time_min          922 // equals 833 (divide by 8 clock pulses)

#define end_data_position      63
#define end_sync_position      77
#define end_smpte_position     80

volatile unsigned int bit_time;
volatile boolean valid_tc_word;
volatile boolean ones_bit_count;
volatile boolean tc_sync;
volatile boolean write_tc_out;
volatile boolean drop_frame_flag;

volatile byte total_bits;
volatile byte current_bit;
volatile byte sync_count;

volatile byte tc[8];
volatile char timeCode[11];

/* ICR interrupt vector */
ISR(TIMER1_CAPT_vect)
{
 //toggleCaptureEdge
 TCCR1B ^= _BV(ICES1);
  //Serial.println("Inter");
 bit_time = ICR1;

 //resetTimer1
 TCNT1 = 0;

if ((bit_time < one_time_min) || (bit_time > zero_time_max)) // get rid of anything way outside the norm
 {
   //Serial.println(bit_time, DEC);
   total_bits = 0;
 }
 else
 {
   if (ones_bit_count == true) // only count the second ones pluse
     ones_bit_count = false;
   else
   {
     if (bit_time > zero_time_min)
     {
       current_bit = 0;
       sync_count = 0;
     }
     else //if (bit_time < one_time_max)
     {
       ones_bit_count = true;
       current_bit = 1;
       sync_count++;
       if (sync_count == 12) // part of the last two bytes of a timecode word
       {
         sync_count = 0;
         tc_sync = true;
         total_bits = end_sync_position;
       }
     }

     if (total_bits <= end_data_position) // timecode runs least to most so we need
     {                                    // to shift things around
       tc[0] = tc[0] >> 1;

       for(int n=1;n<8;n++)
       {
         if(tc[n] & 1)
           tc[n-1] |= 0x80;

         tc[n] = tc[n] >> 1;
       }

       if(current_bit == 1)
         tc[7] |= 0x80;
     }
     total_bits++;
   }

   if (total_bits == end_smpte_position) // we have the 80th bit
   {
     total_bits = 0;
     if (tc_sync)
     {
       tc_sync = false;
       valid_tc_word = true;
     }
   }

   if (valid_tc_word)
   {
     valid_tc_word = false;
/*
     timeCode[10] = (tc[0]&0x0F)+0x30;      // frames
     timeCode[9] = (tc[1]&0x03)+0x30;      // 10's of frames
     timeCode[8] =  '.';
     timeCode[7] = (tc[2]&0x0F)+0x30;      // seconds
     timeCode[6] = (tc[3]&0x07)+0x30;      // 10's of seconds
     timeCode[5] =  ':';
     timeCode[4] = (tc[4]&0x0F)+0x30;      // minutes
     timeCode[3] = (tc[5]&0x07)+0x30;      // 10's of minutes
     timeCode[2] = ':';
     timeCode[1] = (tc[6]&0x0F)+0x30;      // hours
     timeCode[0] = (tc[7]&0x03)+0x30;      // 10's of hours
*/

         timeCode[9] = ((tc[0]&0xF0)>>4)+0x30; // user bits 8
       timeCode[8] = ((tc[1]&0xF0)>>4)+0x30; // user bits 7
       timeCode[7] = ((tc[2]&0xF0)>>4)+0x30; // user bits 6
       timeCode[6] = ((tc[3]&0xF0)>>4)+0x30; // user bits 5
       timeCode[5] = '-';
       timeCode[4] = ((tc[4]&0xF0)>>4)+0x30; // user bits 4
       timeCode[3] = ((tc[5]&0xF0)>>4)+0x30; // user bits 3
       timeCode[2] = '-';
       timeCode[1] = ((tc[6]&0xF0)>>4)+0x30; // user bits 2
       timeCode[0] = ((tc[7]&0xF0)>>4)+0x30; // user bits 1

       drop_frame_flag = bit_is_set(tc[1], 2);

     write_tc_out = true;
   }
 }
}

void setup()
{
 Serial.begin(9600);
 pinMode(8, INPUT);                  // ICP pin (digital pin 8 on arduino) as input

 bit_time = 0;
 valid_tc_word = false;
 ones_bit_count = false;
 tc_sync = false;
 write_tc_out = false;
 drop_frame_flag = false;
 total_bits =  0;
 current_bit =  0;
 sync_count =  0;

 Serial.println("Finished setup ");
 delay (1000);

 TCCR1A = B00000000; // clear all
 TCCR1B = B11000010; // ICNC1 noise reduction + ICES1 start on rising edge + CS11 divide by 8
 TCCR1C = B00000000; // clear all
 TIMSK1 = B00100000; // ICIE1 enable the icp

 TCNT1 = 0; // clear timer1
}

void loop()
{
  if (write_tc_out)
   {
     write_tc_out = false;
     //if (drop_frame_flag)
       //Serial.print("TC-[df] ");
     //else
       //Serial.print("TC-[nd] ");
     Serial.print((char*)timeCode);
     //Serial.print("\r");
   }
}

```

I am generating LTC audio from this link. On running my code I am getting this output:-

```
Finished setup
?>-00-0000??-??-77=??>-??-;?????-??-?>???>-:?-=????>-??-?=???>-;=-??5>?>-;=-??=7?>-?;-??=>?>-?:-??=7?>-;=-??>??>-;;-??=7??-?=-=7?>?>->7-?????>-;;-??=7?>-;>->??:??-?=-7????>-;?-??5>?>-;?-?=?>??-?=-?7>??>-7:-?67=?>-;?-???5?>-;=-7?==?>-;;-??=7?>-7=-??>>?>-:?-7????>-;=-?;;=??-?=->?=5?>-;=-???=?>-;?-?=5>??-?;->=???>-?>-7>;???-?;->????>-;?-?7=??>-;>-??>;?>-;=-;?5>?>-??-=7;7?>-;=-;?=??>-;=-??=7?>-;=-??:??>->7-=?????-?7-=?>>?>-?6-??;>?>-7;-???=?>-??-;=???>-;=-?7=7?>-?=-??>;?>-:?->??

```

So, can anyone one tell me where is mistake.

# Answer
> 1 votes
```
((tc[0]&0xF0)>>4)+0x30

```

Will generate values in the range x30 to x3F, which are 0 to 9 :;\<=\>? This is what you are seeing in you output (because you are adding in x2D '-')

I'm not sure what you are expecting to see, but as far as I can tell there are no mistakes and your code is working fine.

If you are trying to turn tc\[0\] into a hex digit then I would use this function

```
char ToHex (const char input)
{
    char output = '0';
    if (input > 9)
    {
        output = (input - 10) + 'A';
    }
    else
    {
        output = input + '0';
    }
    return output;
}
char TCToHex (const char input)
{
    return ToHex(((input & 0xF0) >> 4));
}
char* CharToHex(const char input, char buffer[3])
{
    buffer[0] = ToHex((input & 0xF0) >> 4);
    buffer[1] = ToHex((input & 0x0F));
    buffer[2] = '\0'; // Always null terminate a string
    return buffer;
}

```

So what you will get if you call the functions is

```
    char buffer[3];
printf("CharToHex 0x%s\n", CharToHex('A', buffer));  //0x41 65 in decimal, ASCII A
printf("TCToHex = 0x%c \n", TCToHex(0x50)); // 5, because this function only takes the high nibble.
printf("ToHex = 0x%c \n", ToHex(0x0f)); // F

```

Hope that helps.

---
Tags: arduino-uno, time, audio, sound
---


# Question
Title: How can an Arduino Mega 2560+Wifi Shield 2.0 (SeeedStudio) receive data from database in a XAMPP server on my PC?
I'm trying to connect my Arduino Mega via Wifi to my XAMPP server. My main objective is get a value from my database and store it on a variable in Arduino code. With this new variable I'll be able to control the rest of the program... So I need your help. Can someone give me advice?

I already tried every thing that I found on the internet but it just doesn't work.

I think that the simple way is to send a GET request to the server and read its response... But for some reason I can't send a GET request through...

I tested it on the browser directly and the value shows up, so I think that the server side is all right.

Here is my Arduino code:

```
#include <Arduino.h>
#include <SoftwareSerial.h>
#include "WiFly.h"
#include "HTTPClient.h"

#define SSID      "mySSID"
#define KEY       "myKEY"
#define AUTH      WIFLY_AUTH_WPA2_PSK
#define HTTP_GET_URL "http://192.168.1.80/xampp/training/send_data_db.php/?temp=0"

// Pins' connection
// Arduino       WiFly
//  2    <---->    TX
//  3    <---->    RX
SoftwareSerial uart(10, 11);
WiFly wifly(uart);
HTTPClient http;
char get;

void setup() {
  Serial.begin(9600);
  Serial.println("------- WIFLY HTTP --------");
  uart.begin(9600); // WiFly UART Baud Rate: 9600
  // Wait WiFly to init
  //  delay(3000);

  // check if WiFly is associated with AP(SSID)
  if (!wifly.isAssociated(SSID)) {
    while (!wifly.join(SSID, KEY, AUTH)) {
      Serial.println("Failed to join " SSID);
      Serial.println("Wait 0.1 second and try again...");
      delay(100);
    }
    wifly.save(); // save configuration,
  }
  Serial.println("\r\nTry to get url - " HTTP_GET_URL);
  Serial.println("------------------------------");
  while (http.get(HTTP_GET_URL, 10000) < 0) {
  }
  while (wifly.receive((uint8_t *)&get, 1, 1000) == 1) {
    Serial.print(get);
  }
  if (wifly.commandMode()) {
    Serial.println("\r\n\r\nEnter command mode. Send \"exit\"(with \\r) to exit command mode");
  }
}

void loop() {
  int c;
  while (wifly.available()) {
    c = wifly.read();
    if (c > 0) {
      Serial.write((char)c);
    }
  }
  while (Serial.available()) {
    c = Serial.read();
    if (c >= 0) {
      wifly.write((char)c);
    }
  }
}

```

And here is my PHP code:

```
<? php
include("./connection/database_connect.php");
include("./top_table.php");

if ((isset($_SESSION["ID"])) AND (isset($_GET["temp"]))) {
  $id = $_SESSION["ID"];
  $sql = "SELECT temp FROM perfil, client WHERE perfil.ID ='$id'";
  $consult = mysqli_query($connect, $sql);
  $result = mysqli_num_rows($consult);
  if (($result == 1)) {
    $person_data = mysqli_fetch_array($consult, MYSQLI_ASSOC);
    $temp = $person_data["temp"];
    header("HTTP/1.1" . " " . 200 . "OK");
    header("Content-Type: text/html; charset=UTF-8");
    header("Content-Length: 1112");
    header("Connection: close");
    header("/r/n");
    echo $temp;
  } else {
    //se user dosen't exist on data base
    header("Location: http://192.168.1.80/xampp/training/login.php");
    exit;
  }
} else {
  header("Location: http://192.168.1.80/xampp/training/login.php");
  exit;
}
?>

```

# Answer
> 1 votes
You should forget about the $\_SESSION\["ID"\]; on PHP side, because you are working stateless without any session! You should give a parameter for identifying your variable from arduino to php script - is this the temp=0? If so you need to exchange

```
$sql="SELECT temp FROM perfil, client WHERE perfil.ID ='$id'";

```

with

```
$sql="SELECT temp FROM perfil, client WHERE perfil.ID =" . $_GET["temp"];

```

assuming that perfil.id is only an integer - if it is a string, then add "'".

# Answer
> 0 votes
Yes you are right!

Meanwhile i finished this project.

The problem was with the Wi-Fi shield that I was using. The Http request wasn't in a right format.

---
Tags: programming, arduino-mega, shields, wifi, web-server
---


title: Creating date string for error log

text:
# Question
Title: Creating date string for error log
Well, googling didn't do much to help me here and I'm shocked that something I can do in two lines of code in C#

```
DateTime dateTime;
string text = dateTime.ToLongDateString();

```

is this difficult for Arduino, but how do you get a string version of a date time stamp?

I want the current date and time as a string in this format

> May 4, 2016 17:15:33

Since I can't use any of the C++ includes, like ctime, I'm not sure how to accomplish this.

# Answer
> 1 votes
You need additional hardware like a RTC for example an DS1307 or on the other hand an arduino/shield with ethernet or wifi so you could get the time by NTP another option might be DCF77 time via the air - sorry forgot GPS could also be used to get the time .... the rest then should be simple creating a string.

---
Tags: arduino-uno, time
---


# Question
Title: Computer to Arduino to hardware, controlling on / off state of hardware via user input on computer
First time coding for Arduino. I'm working on code to operate an electronic valve switch. We have a laptop connected to an Arduino Mega, and that Arduino is hooked up to the valve (hardware) on Pin 53.

I was trying to work off of the "blink" example originally, but that gives no basis for user prompted control. Basically I want to have the computer ask me if I should turn it on or off, type in my response (I was using "HIGH" for on and "LOW" for off, as in voltage control), and have that activate or deactivate the hardware.

My main problem right now stems from how best to ask for that input. I've been trying to work with the Messenger.h library thus far. I'm definitely getting hung up on how to define the pin, or what the simplest method for user input would be. (HIGH or LOW? 0 or 1? Something else?)

Code is below. Thanks!

```
#include <Messenger.h>

Messenger message = Messenger();

// Variable definitions. Switchinput is what the user commands, current state is whether the air is flowing or not.
boolean currentstate;
boolean switchinput;
String pin53; // Something is up on this line?? How to define this pin??

// FUNCTION DEFINITIONS
// Startup fxn
void start()
{
  Serial.print("LOW = off, HIGH = on. Switch is ");
  Serial.println(currentstate);
  Serial.print("Enter LOW to turn on or HIGH to turn off: ");
  switchinput = Serial.read();
}

// Go off to on
void offtoon()
{
    digitalWrite(pin53,HIGH);
    currentstate = switchinput;
}

// Go on to off
void ontooff()
{
    digitalWrite(pin53,LOW);
    currentstate = switchinput;
}

// Stay same -- already off
void staysameoff()
{
  if ((currentstate = switchinput) && (switchinput = LOW))
  {
      void start();
  }
}

// Stay same -- already on
void staysameon()
{
  if ((currentstate = switchinput) && (switchinput = HIGH))
  {
    void start();
  }
}

// Running actual code
void setup()
{
  // initialize digital pin 53 as an output.
  pinMode(pin53, OUTPUT);

  // Sets default state to switch being off (Off = LOW, On = HIGH)
  String currentstate = LOW;
}

void loop()
{
   if ((currentstate != switchinput) && (switchinput = HIGH))
  {
      void offtoon();
  }

  if ((currentstate != switchinput) && (switchinput = LOW))
  {
      void ontooff();
  }

  if ((currentstate = switchinput) && (switchinput = LOW))
  {
      void staysameoff();
  }

  if ((currentstate = switchinput) && (switchinput = HIGH))
  {
      void samestayon();
  }
}

```

# Answer
> 1 votes
This seems way too complex for your purpose:

* you really do not need to do anything to stay in the same state
* if you want to switch the valve ON, no need to check whether it's OFF: there is no harm in switching ON a valve that is already ON.

Here is a simplified version of the program:

```
void setup()
{
    Serial.begin(9600);
    Serial.println("Type '0' to turn OFF, '1' to turn ON");
}

void loop()
{
    int command = Serial.read();
    if (command == '0') digitalWrite(53, LOW);
    if (command == '1') digitalWrite(53, HIGH);
}

```

Notice that `Serial.read()` returns -1 if there is nothing in the input buffer, and since -1 is neither '0' nor '1', this will not change the output.

If you want to use more elaborate commands (not single characters), you may want to take a look at this simple command-line interpreter. It is intended to be easy to adapt to different purposes.

---
Tags: arduino-mega, hardware, input
---


title: Windows 10 problem installing driver

text:
# Question
Title: Windows 10 problem installing driver
So the arduino shows up as "Unknown device" when connected to my computer. Followed somr guides on google but still failed, this error came up, what should I do? I've tried "Disable Driver Signature Enforcement" and the regedit thing..

# Answer
Install the latest Arduino IDE with windows administrator rights.
> 1 votes

---
Tags: arduino-uno
---