# Question
Title: Serial Comm. timing issue between Arduino and Pyserial
This is my first post to Stack Exchange so please forgive any formatting errors.

I am conducting an experiment that has 7 total sensors: 5 thermocouples, 2 humidity sensors and 1 pressure sensor. I am reading their signals via Arduino Mega analog input ports. I chose to use Python to save and compile the data in a nice csv file, therefore I am using Pyserial.

My problem is that I cannot go above 1 sample/second. As you can see in my code, I have a 1 second delay in Arduino and Python. I have ran successful calibration tests with my thermocouples, so I know at that rate Python and Arduino are communicating well. Anything faster than 1 sample/second (i.e. I change my delays to .5 or .25 seconds), a timing error occurs and my data is "cut up" and sent in odd chunks instead of the standard layout I programmed.

Additionally, I tried to increase the baud rate from 9600 and anything above that will send "garbage" ASCII characters (e.g. little blank blocks and odd characters) to the Serial Comm. I changed the baud rate in Arduino, Python *and* the COM port in my devices manager settings to no avail.

I would really like to increase my sampling rate to increase my signal-to-noise ratio and I believe it's good practice as a metrologist to have a higher sampling rate than 1 samp/sec. I am sending ~1072 bits each time I write to the Serial Comm (if I'm counting right??) so I should have enough room to increase the amount of bits to send per second (around 3 times what I am currently sending).

**In summary, my two main issues are: if I increase the baud rate, I get garbage in my Serial Comm and if I try to increase my "sampling rate" by decreasing my delays, timing issues appear and my data is split up erroneously. Should I be using a different function, like Serial.flush()?**

**I greatly appreciate any feedback, thank you for your time!**

```
// Data acquisition
// updated  March 30, 2017

//Note: This version is for TEMPERATURE, HUMIDITY and PRESSURE data
acquisition ALONE. No motor/conveyor control.

//***GLOBAL VARIABLES***//

float lfactor = 125.0;
float afactor = 1.15;

/////////////////////////

//Standard setup with analogReference to 5Volts.

void setup() {

Serial.begin(9600);
}

void loop() {

//******THERMOCOUPLES*******//

//get voltage reading
// [code]; TC # - Location

float tcv1 = analogRead(A4) * ( 5.0 / 1024.0 ); //TC 1
float tcv2 = analogRead(A7) * ( 5.0 / 1024.0 ); //TC 2
float tcv3 = analogRead(A8) * ( 5.0 / 1024.0 ); //TC 3
float tcv4 = analogRead(A9) * ( 5.0 / 1024.0 ); //TC 4
float tcv5 = analogRead(A10) * ( 5.0 / 1024.0 ); //TC 5

//convert to temperature using custom equation based on 5V reference
float tc1 = ( 188.7755 * tcv1 ) - 245.3959;
float tc2 = ( 188.7755 * tcv2 ) - 245.3959;
float tc3 = ( 188.7755 * tcv3 ) - 245.3959;
float tc4 = ( 188.7755 * tcv4 ) - 245.3959;
float tc5 = ( 188.7755 * tcv5 ) - 245.3959;

//******HUMIDITY SENSORS********//

float hs1 = ((( analogRead(A13) * ( 5.0 / 1024.0) ) / 5.0 ) * 100.0 ); //HS
1
float hs2 = ((( analogRead(A15) * ( 5.0 / 1024.0) ) / 5.0 ) * 100.0 ); //HS
2

//******PRESSURE SENSORS********//

//obtain voltage signal from Sensirion sensor
float pvolt = analogRead(A0) * (4.995 / 1024.0);

//convert to Pascals using equation from datasheet, including altitude
compensation
//P = lfactor * (voltage[V] - .250 ) / 3.750

float pressure =  lfactor * ( pvolt - .250 ) / 3.750;
float pascals = pressure * afactor;

Serial.print("TC1");
Serial.print(":");
Serial.print(tc1);
Serial.print(";");

Serial.print("TC2");
Serial.print(":");
Serial.print(tc2);
Serial.print(";");

Serial.print("TC3");
Serial.print(":");
Serial.print(tc3);
Serial.print(";");

Serial.print("TC4");
Serial.print(":");
Serial.print(tc4);
Serial.print(";");

Serial.print("TC5");
Serial.print(":");
Serial.print(tc5);
Serial.print(";");

Serial.print("RH 1");
Serial.print(":");
Serial.print(hs1);
Serial.print(";");

Serial.print("RH 2");
Serial.print(":");
Serial.print(hs2);
Serial.print(";");

Serial.print("Pressure");
Serial.print(":");
Serial.print(pascals);
Serial.print(";");

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

  }

```

**Python Code:**

```
from threading import Thread
import time
import serial
import os
global datalist
global fileName

global motorspeed

motorspeed = 0

def serInitialization():
    #activate the serial port, if possible
    try:
        ser = serial.Serial('COM9', 9600) #initialize the serial port
        print "Serial connection successful."
        return ser
    except:
        print "Error: serial port cannot be initialized"
        while(1):
            voidholder = 1

def getDateTime():
  """Function grabs current time and date, then returns values in a 2-
 element list. """
   timeNow = time.strftime("%H:%M:%S")
   dateToday = time.strftime("%m/%d/%y")
  return [dateToday, timeNow]

def writetocsv(data):

    """ function writes datalist values to a csv file. If daily csv file
exists already,
    list values are simply appended to end of file. If it does not, function
creates the file,
    then appends values.
    """

    global csv_success

    header = ["date", "time", " ", "TC1", " ", "TC2", " ",
"TC3", " ", "TC4", " ", "TC5", " ", "HS1", " ", "HS2"," ",
"PRESSURE", " ", "PRESSURE(alt)", "\n"]

    fileName = str(time.strftime("%m_%d_%y_")+ "log.csv")

    if os.path.exists(fileName):
        f = open(fileName, "a")

    else:
        f = open(fileName, "a+")

        for element in header:
            f.write(element + ",")
        f.write("\n")

    for element in data:
        if type(element)==str:
            f.write(element + ",")
        if type(element) == list:
            for i in element:
                f.write(i + ",")

    f.write("\n")
    f.close()
    csv_success = True

def mainprogram():

    data = []

    if ser.inWaiting():
        datetimeData = getDateTime()

        for i in datetimeData:
            data.append(i)

        val = ser.readline().strip('\n\r').split(';')
        print "Current readings: "
        for i in range(0,len(val)):
            sensorData = val[i].split(':')
            data.append(sensorData)

            print sensorData

        writetocsv(data)

        time.sleep(1)

        print "\n" * 50

#Initializes the serial port with the arduino so now we can read what
Arduino is sending us!
print "*******************************"
print "DATA ACQUISITION PROGRAM       "
print "*******************************"
print "Data files are saved under "
print "C:\\Users\\lpaw\\Downloads\\python workspace"
print "*******************************"

ser = serInitialization()

while True:

   mainprogram()

```

**Screenshots of errors:**

# Answer
Your main problem is in erroneously having a delay in both the sender and the receiver. While this sometimes works by lucky accident, it essentially never does what is hoped for by those who try it.

In a system such as this, you should have a delay in the sender only, in order to produce quasi-regular sample intervals, but no delay in the receiver. Rather, the receiver should accept data whenever the transmitter produces it, or more specifically in your case, every time it completes a terminated line of data.

But you also seem to want to write the data in an organized way as sets of measurements. To do that, you should reject data until you see the first "TC1", then collect lines to fill in a data block until and end of data condition is recognized (in your case a blank line), and write it out to disk in a timestamped file. You may also want to include code that abandons a corrupted block unwritten if any of the intermediate reading headers aren't as expected, and goes back to looking for the next hopefully clean TC1, or marks it as erroneous, or whatever.

To use a different baud rate, you must apply a matching setting in both the Arduino and the python ends of the link.

Also note that while the Arduino serial monitor is indeed useful for debugging, you *must not* have it open while trying to collect data with python - this will either cause an error in that one program is disallowed, or the two programs to fight over the data and each get incomplete results.

Another technique which can be simple and useful, especially during development, is to write every received line of serial data out to a text file with a numeric timestamp at the start of each line. You can then have a second process which reads this file, grabs complete multi-line records, and writes them out using either the timestamp of the first or last element of the record. In particular this lets you get an intermediate view of the data to understand any oddities. With various Unix style command line tricks you can even run the first program both saving the intermediate format and feeding the second record extraction program in real time.
> 3 votes

# Answer
You certainly should use a single Serial.flush at the end of your loop()

```
Serial.println("");
Serial.flush()
delay(100);

```

Remember you have limited SRAM to store characters. I'd suggest you should use the inbuilt serial monitor in the Arduino IDE with the above alteration, and increase your baud rate. There should be no problems sending data at 115k baud.

You should also consider sending a signal back from Python that you have received a valid reading string (ACK/NAK) that way you can remove delays altogether (you still need the flush).
> 0 votes

# Answer
Does your Python code have any way of determining the start & end of a data set?
Does it 'assume' that when it reads a chunk of data from the serial port that the first byte it gets will always be the start of a "Cond.temp" and the last byte will be the ; at the end of Press(alt)?
After reading a chunk of data, do you have any check to see if it is complete or if you should wait a few 10's of milliseconds and go back to read some more?

I'm assuming the answers to these questions are No, Yes & No.

Your PC and your Arduino are running completely asynchronously - neither one really knows what the other is doing.
When your python code reads a chunk of data from the serial port (I'm making another assumption here - that you're not reading it byte-by-byte), you have no way of knowing that the beginning of that chunk is really the beginning of your data set.
Similarly, you also have no way of knowing that the end of that chunk is the end of your data set - maybe it's only a small piece - or maybe you're getting the beginning of the next set glued to the end of this on.

If you're using a USB-Serial adapter then your data is even more likely to arrive in bits & pieces which you'll need to reassemble - just by the nature of how these beasties often work - they could be buffering some number of serial bytes before packaging them together in a single USB packet.

You need some way of flagging the start and/or end of your data sets. Even something as simple as a \n newline character at the end of each one might work for you.
Then, you need to read in *and buffer* the data you're receiving *until you know you've reached the end of a data set*.
So, for the \n example:
\- read some stuff
\- add it to a buffer
\- do you have a \n *anywhere in the buffer*?
-- yes - pull that section from the start of the buffer up to the \n & process it
-- no - go back to the beginning and wait for more stuff
\- after you've pulled some stuff out of the buffer to process,
*don't just forget the rest - it could be the start of your next data set!*
\- move it to the start of your buffer
\- rinse & repeat

For your baud-rate issue I can't say much for sure. The garbage you're seeing is typical for a mismatched baud-rate situation.
Check that your particular Arduino supports the baud rates you're trying to use at whatever clock speed you're running it at.
Check that your USB-Serial adapter (if you're using one) works at those speeds (either loop pins 2&3 and type to yourself in a terminal or get another, preferably different one, and hook them together with a 3-wire link pin 2-3, pin 3-2, pin 5-5).
> 0 votes

---
Tags: serial, communication, python
---


# Question
Title: NodeMCU with RFID RC522 and I2C interface LCD module together
I'm newbie in Arduino programming so I hope to get a clear answer.

I have NodeMCU v1 12-E, I connected it with RFID RC522 as in attachment picture.

Now my question:
I need to connect I2C interface LCD module with it to print some words in.
The RFID use the default SDA and SCL pins on NodeMCU V1.0 "D1 and D2" also when I see wiring for the LCD I2C it use same D1 and D2 pins.
So now if I change the RFID instance creation code to

```
MFRC522 mfrc522(0,2);

//SS_PIN 3 RST_PIN 4

```

Is the RFID will work as previous pins and the LCD will work also?

# Answer
You can have multiple devices on the I2C bus so long as they all have different addresses. This means you should be able to connect D1 and D2 to the RFID and LCD. HOWEVER I'm not sure that you are using I2C to talk to the RFID board, if you aren't then you may need to move the RFID boards pins and leave I2C on D1&2.
> 0 votes

---
Tags: i2c, lcd, rfid, nodemcu
---


# Question
Title: No such file or directory compilation terminated
I tried a simple blink for my fingerprint sensor which is GT-511C1R, but I have experienced of having an error.

> FPS\_Blink.ino:12:26: fatal error: FPS\_GT511C1R.h: No such file or directory compilation terminated.

I downloaded the whole library but still same error.

# Answer
Please learn how to install a library from here. And see if error is coming or not.
> 2 votes

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


# Question
Title: Suggest me Arduino device with USB for Mass storage
I want to make a temperature data logger by using Arduino.

I can read a data every 1sec and I want to store 30days data with date&Time.

In data logger, I want to write a temperature data with date&time in the .csv file and this file will be generated after I attaching USB.

So, Please suggest me Arduino board with USB compatible(working on 3V battery) and also suggest me EEPROM who able to store 30 days data.

# Answer
> 4 votes
60 samples per minute, 60 minutes per hour, 24 hours per day, 30 days - that's 2592000 samples. At 10 bytes per sample (a very generous allocation) that's less than 30MB of data.

You could fit that many many times over on even the smallest of today's SD cards, so why mess with the complexity of USB? *Any* Arduino can work with an SD card.

A bigger concern of yours should not be the storage medium, which is trivial - you should instead be thinking about *how you will run the board off a 3V battery for 30 days*.

# Answer
> 1 votes
Despite your poor written question, I'll reply to you with a code, I used in my temperature logger 2 weeks ago. Includes LCD, temp sensor and SD card.

Delay is set for 9,1s which sums up with the calculation times of Arduino to 10 +/- 0.05 sec.
Lower it down to 100ms, if you want to be written every 1 second.

PS: The lower row, most right: There is a sign in letters, the condition of the sistem.

N = something's wrong, not inserted card/not connected SD card module
O = everything's okay, it's data logging

```
#include <OneWire.h>
#include <DallasTemperature.h>
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>
#define ONE_WIRE_BUS 6 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); LiquidCrystal lcd(8, 7, 5, 4, 3, 2);

const int chipSelect = 10;

void setup() {

  Serial.begin(9600);   Serial.println("Arduino Digital Temperature // Serial Monitor Version");   sensors.begin();
     lcd.begin(16, 2);   lcd.setCursor(0, 0);   lcd.print("Temperatura:");   //*********************************************
    while (!Serial) {   }   lcd.setCursor(15, 1);   lcd.print("??");   Serial.print("??");

  if (!SD.begin(chipSelect)) {
    Serial.println("NO");
      lcd.setCursor(15, 1);
      lcd.print("NO");
    return;   }   else   {   lcd.setCursor(15, 1);   lcd.print("OK");   Serial.println("OK");   }   //********************************************* }

void loop() {

  String dataString = "";

  float abc;

  sensors.requestTemperatures();     Serial.print("Temperature is: "); Serial.println(sensors.getTempCByIndex(0));   lcd.setCursor(0, 1);   lcd.print(sensors.getTempCByIndex(0));

  File dataFile = SD.open("datalog.txt", FILE_WRITE);

    if (dataFile) {
    dataFile.println(sensors.getTempCByIndex(0));
    dataFile.close();    Serial.println(sensors.getTempCByIndex(0));
    }
       else {
    Serial.println("error opening datalog.txt");   }

  //delay(9100);    }

```

---
Tags: arduino-uno, usb
---


title: HC-SR04 pulse at multiple angles

text:
# Question
Title: HC-SR04 pulse at multiple angles
I have a HC-SR04 sensor mounted on a stepper motor, mounted on a car. The idea is this:

* The car moves forward with the ultrasonic sensor facing the front
* If the sensor reads a small distance the car do the following:
    + Stop
    + Turn the sensor to the left and get a new distance
    + Turn the sensor to the Right and get a new distance
    + Drive slightly backward
    + The car turns the to direction the distance was the highest
    + Drive forward again

I think I must have wrongly understood how the echo/ultrasonic sensor works. Because when I read values to the left and right, it will always return zero, but reading values when driving forward works very well.

Below is the relevant code

```
//Trigger
void triggerEcho(){
  digitalWrite(echoTrigPin,LOW);
  delayMicroseconds(5);
  digitalWrite(echoTrigPin,HIGH);
  delayMicroseconds(10);
  digitalWrite(echoTrigPin,LOW);
}

//Trigger, receive and calculate distance (cm)
long getEchoDistance(){
  triggerEcho();
  pinMode(echoRecPin, INPUT);
  long echoDuration = pulseIn(echoRecPin, HIGH);

  return echoDuration / 58;
}

void loop(){

  long distance = getEchoDistance();

  //If front obstacle is encountered
  if((distance < 5) && (distance != 0)){
      carStop();
      servo.write(180);                     //turn echo sensor left
      delay(250);
      long distanceL = getEchoDistance();   //trigger and read sensor value
      servo.write(0);                       //turn echo sensor right
      delay(250);
      long distanceR = getEchoDistance();   //trigger and read sensor value

      //this will always show distance as 0
      Serial.print("  LEFT :"); Serial.print(distanceL); Serial.print("\n");
      Serial.print("  RIGHT:"); Serial.print(distanceR); Serial.print("\n");

      carDriveBackward(135, 1.185, 1.0);     //drive backwards
      delay(250);
      if(distanceR>distanceL)                //turn in the direction that was furthest
        carTurnRight(100,1250);
      else
        carTurnLeft(100,1250);
      carStop();
      servo.write(90);                        //face sensor forward
      delay(250);
    }
    else
      carDriveForward(135, 1.185, 1.0); //R - L
}

```

I bet something is wrong with how I'm implementing the `triggerEcho()` and `getEchoDistance()`. I excluded anything on the wiring and pins, as the reading of the distance is very correct when reading the facing the front.

# Answer
> 0 votes
I doubt you have misunderstood the way ultra sound works. You send a pulse and then go quiet waiting for a reply. The time it takes to send the pulse is the minimum distance you can detect things at.

If you are not getting returns left and right then it could be there is nothing there or turning the head is breaking a connection.

Firstly jack the vehicle up off the floor so it doesn't go anywhere. Place a solid object (book) in front of the vehicle and make sure it detects it. Now place the same object to the right of the vehicle, do it detect it? Stop the US sensor when it is looking right (by killing the power) and check that it is looking horizontally. Check the connections, are they being pulled loose?

Your code looks fine, you US works forwards so I think it is a mechanical issue with your car.

---
Tags: hc-sr04
---


title: EEPROM PUT and GET audio playback

text:
# Question
Title: EEPROM PUT and GET audio playback
I am new to Arduino.

My project is an electronic piano that has 8 tactile switch keys that can play 8 octaves. I want to record a song that a user plays on the keys into EEPROM. I have implemented it. However, the playback is bad. You can't hear different note frequencies but you can hear soft buzzing when a note is supposed to be played.

Here is my code. Could you please help me find the problem? Thank you in advance.

```
#include <EEPROM.h>
#include "pitches.h"
#define speaker A5
#define record_button 3
#define play_button 5
#define record_led 2
#define play_led 4

int eeAddress = 0;
int eeAddressplay = 0;
const int inPot = A1; // potentiometer to change octaves (8 octaves total)
byte octave;
byte tone_out;
int tone_key; // frequency of key
boolean silence;
int maxNumber = 500;
byte time = 20;
byte check = 0;
byte buttons[] = {6,7,8,9,10,11,12,13};
int saveSounds[500];
int saveNumber = 0;

byte melody1[8] = {
  NOTE_C1 , NOTE_D1, NOTE_E1, NOTE_F1, NOTE_G1, NOTE_A1, NOTE_B1, NOTE_C2};
byte melody2[8] = {
  NOTE_C2 , NOTE_D2, NOTE_E2, NOTE_F2, NOTE_G2, NOTE_A2, NOTE_B2, NOTE_C3};
int melody3[8] = {
  NOTE_C3 , NOTE_D3, NOTE_E3, NOTE_F3, NOTE_G3, NOTE_A3, NOTE_B3, NOTE_C4};
int melody4[8] = {
  NOTE_C4 , NOTE_D4, NOTE_E4, NOTE_F4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5};
int melody5[8] = {
  NOTE_C5 , NOTE_D5, NOTE_E5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_B5, NOTE_C6};
int melody6[8] = {
  NOTE_C6 , NOTE_D6, NOTE_E6, NOTE_F6, NOTE_G6, NOTE_A6, NOTE_B6, NOTE_C7};
int melody7[8] = {
  NOTE_C7 , NOTE_D7, NOTE_E7, NOTE_F7, NOTE_G7, NOTE_A7, NOTE_B7, NOTE_C8};

//PIANO FUNCTION
void freePlay()
{
  octave = map(analogRead(inPot),0,1023,1,7);
  if (digitalRead(buttons[0]) == HIGH) {
    tone_out = 0;
    silence = false;
  }
  else if (digitalRead(buttons[1]) == HIGH) {
    tone_out = 1;
    silence = false;
  }
  else if (digitalRead(buttons[2]) == HIGH) {
    tone_out = 2;
    silence = false;
  }
  else if (digitalRead(buttons[3]) == HIGH) {
    tone_out = 3;
    silence = false;
  }
  else if (digitalRead(buttons[4]) == HIGH) {
    tone_out = 4;
    silence = false;
  }
  else if (digitalRead(buttons[5]) == HIGH) {
    tone_out = 5;
    silence = false;
  }
  else if (digitalRead(buttons[6]) == HIGH) {
    tone_out = 6;
    silence = false;
  }
  else if (digitalRead(buttons[7]) == HIGH) {
    tone_out = 7;
    silence = false;
  }
  else {
    silence = true;
  }

  if (silence == false)
  {
    switch(octave)
    {
    case 1:
      tone_key = melody1[tone_out]; break;
    case 2:
      tone_key = melody2[tone_out]; break;
    case 3:
      tone_key = melody3[tone_out]; break;
    case 4:
      tone_key = melody4[tone_out]; break;
    case 5:
      tone_key = melody5[tone_out]; break;
    case 6:
      tone_key = melody6[tone_out]; break;
    case 7:
      tone_key = melody7[tone_out]; break;
    }
    tone(speaker,tone_key);
  }
  else {
   noTone(speaker);
   delay (5); }
}

//SETUP FUNCTION
void setup()
{
 for(int i = 0; i < 8; i++)
 {
  pinMode(buttons[i], INPUT);
 }
 pinMode(speaker, OUTPUT);
 pinMode(melody_button, INPUT);
 pinMode(record_led, OUTPUT);
 pinMode(play_led, OUTPUT);
 pinMode(inPot, INPUT);
}

//MAIN CODE
void loop() {
freePlay();
if (digitalRead(record_button) == HIGH) {
  digitalWrite(record_led, HIGH);
    for(int i = 0; i < maxNumber ; i++) {
      octave = map(analogRead(inPot),0,1023,1,7);
        if (digitalRead(buttons[0]) == HIGH) {
        tone_out = 0;
        silence = false;
        }
        else if (digitalRead(buttons[1]) == HIGH) {
        one_out = 1;
        silence = false;
        }
        else if (digitalRead(buttons[2]) == HIGH) {
        tone_out = 2;
        silence = false;
        }
        else if (digitalRead(buttons[3]) == HIGH) {
        tone_out = 3;
        silence = false;
        }
        else if (digitalRead(buttons[4]) == HIGH) {
        tone_out = 4;
        silence = false;
        }
        else if (digitalRead(buttons[5]) == HIGH) {
        tone_out = 5;
        silence = false;
        }
        else if (digitalRead(buttons[6]) == HIGH) {
        tone_out = 6;
        silence = false;
        }
        else if (digitalRead(buttons[7]) == HIGH) {
        tone_out = 7;
        silence = false;
        }
        else {
        silence = true;
        tone_key = 0;
        }

        if (silence == false) {
        switch(octave) {
        case 1: tone_key = melody1[tone_out]; break;
        case 2: tone_key = melody2[tone_out]; break;
        case 3: tone_key = melody3[tone_out]; break;
        case 4: tone_key = melody4[tone_out]; break;
        case 5: tone_key = melody5[tone_out]; break;
        case 6: tone_key = melody6[tone_out]; break;
        case 7: tone_key = melody7[tone_out]; break;
        }
        tone(speaker,tone_key);
        delay(time);
        }
        else {
        noTone(speaker);
        tone_key = 0;
        delay (time);
        }

    saveSounds[saveNumber] = tone_key;
    saveNumber++;
    if (digitalRead(play_button) == HIGH){
    break;}
    }

digitalWrite(record_led, LOW);
tone(speaker, 700);
delay(200);
noTone(speaker);
check++;
}

for (int i = 0; i<500; i++) {
  EEPROM.put(eeAddress,saveSounds[i]);
  eeAddress = eeAddress + 2;
}

if(check >= 1) {
  while (0 == 0){
    freePlay();
    if(digitalRead(play_button) == HIGH) {
      digitalWrite(play_led, HIGH);
        for(int i = 0; i < maxNumber; i++) {
        if(saveSounds[i] != 0) {
          tone(speaker,EEPROM.get(eeAddressplay,saveSounds[i]));
          eeAddressplay = eeAddressplay + 2;
          delay(25);
        }
        else {
          noTone(speaker);
          delay(time);
        }
        }
      noTone(speaker);
      digitalWrite(play_led,LOW);
    }
    freePlay();
  }
}
}

```

# Answer
> 1 votes
NOTE: this is not an answer, but a response not able to put in a comment as request from the submittor mirandamg.

For the first example

Instead of

```
if (digitalRead(buttons[0]) == HIGH) {
  tone_out = 0;
  silence = false;
}
else if (digitalRead(buttons[1]) == HIGH) {
  tone_out = 1;
  silence = false;
}
...

```

Use

```
for (int buttonIndex = 0; buttonIndex < 8; buttonIndex++)
{
    if (digitalRead(buttons[butonIndex] == HIGH)
    {
       tone_out = buttonIndex;
       silence = false;
    }
}

```

This method does not work directly for variables melody1, 2, 3... Therefore, make an array, instead of:

```
byte melody1[8] = {
...

```

use

```
byte melodies[8][8] = {
...

```

The first 8 is for the number of melodies, the second is for the number of notes.

You can improve it even further by making 2 constants:

```
const byte NR_OF_MELODIES = 8; // Number of melodies
const byte NR_OF_NOTES = 8;    // Number of notes per melody

```

And the array can be created s

```
byte melodies[NR_OF_MELODIES][NR_OF_NOTES] = {

```

If you make a const for the number of buttons:

```
const byte NR_OF_BUTTONS = 8; // Number of physical buttons

```

Then also the first line in the loop in my example can be changed as:

```
for (int buttonIndex = 0; buttonIndex < NR_OF_BUTTONS; buttonIndex++)

```

If you later need to change the number of notes, melodies or buttons, you don't need to iterate over your application to find all values. Especially since they are all 8.

---
Tags: arduino-uno, eeprom
---


title: Wired IoT sensor network with PoE?

text:
# Question
Title: Wired IoT sensor network with PoE?
**Objective:** Maybe I'm a bad Googler, but I am finding very little on ***wired*** Internet of Things sensor networks using Arduino.

**Project Goals:**

* Arduino based sensor nodes that connect to the local network (not out to the internet)
* All the benefits of adding adding/removing nodes, moving nodes, adding new routers for more ports.
* Black box sensors that don't take any soldering to plug into the network (although they contain soldered components in the black box.
* Using a master Raspberry Pi on the network to identify the nodes and read data from them.
* Using Power over Ethernet (PoE) to power my sensor nodes.
* Don't want to actually connect to the outside internet, just want the convenience of assembling a network with node names and such.

**Why not use wireless solutions (e.g. XBee):**

Currently, it seems Xbee is the way to go, but I don't want a wireless solution.

* I want the reliability of a wired connection.
* I don't want to have to worry about batteries

**What I'm doing right now:**

Currently, I have all my sensors wired to a central Arduino MEGA using 4-conductor security cable (Vcc, GND, and two signal conductors). The MEGA communicates over serial with a Raspberry Pi. This is annoying for the following reasons:

* I have to solder/unsolder every time I want to change something.
* I have to figure out which digital I/O pins are available on the MEGA and have to write down which signal conductor goes to which pin on the MEGA and means what on the sensor.
* There is a finite number of pins.
* Each sensor is its own unique project. I want to start standardizing these sensors to clean up the code.

**What I have found so far:**

I've been looking at XPort sensors; however they are very expensive (i.e. $60 ea.) and don't support PoE. If there is a solution using Arduino and an Ethernet Shield, it brings down the base cost of a sensor by a lot.

**Request:**

Where can I find out more information about *wired* Arduino sensors? Are there any prebuilt solutions that already do what I am looking for?

# Answer
I think I am using a setup like you wish at my home:

1. PoE Switch (for example Cisco SG300-28P)
2. Arduino Ethernet's with PoE Module (https://www.arduino.cc/en/Main/ArduinoBoardEthernet) I bought one for every room ;-)
3. Use DHCP-Server on raspberry PI
4. Put your sensors on your Arduino ethernet board
5. I am also using MQTT as protokoll for example http://pubsubclient.knolleary.net/
6. Use MQTT broker Mosquitto on raspberry pi

For the case that you want to use your switch also for internet connectivity, define a vlan (search wikipedia) for your arduino sensor network.

Hope that helps.
> 2 votes

# Answer
Enviromon.net has PoE sensors that are plug and play with their base units. The base unit is then connected to your internal network.

If your a bit more experienced (which it seems you are) their base units can also be integrated into other systems like network monitoring apps, and SCADA programs.

You could most likely configure the base unit to slave to your raspberry pi, and bonus, no soldering. All their sensors are PoE. Although unfortunately they are not for the Arduino.

But you mentioned if anyone knew if there was a prebuilt solution.

Heres a link to their sensors you might be interested in http://www.enviromon.net/environmental-monitoring-sensors/
> 0 votes

---
Tags: sensors, ethernet
---


# Question
Title: Using voltage divider to read voltage from sensor
Good morning,

I would like to use an Arduino Duemilanove to read the voltage signal generated from a current sensor (CSLA2CD). The datasheet for this sensor can be found here.

The problem is that the sensor requires a supply voltage of 6 to 12v. The signal output voltage is half the supply when no current flows through the sensor. I am using a 8v regulator for its supply, so the signal voltage may range from 4v (no current sensed) all the way to about 6v (about 60 amps).

Unless I'm mistaken, the arduino's analog pin can detect from 0v to 5v. So it would only accurately provide me data up to the 5v signal mark.

My questions are:

1. Would a voltage divider be a good solution to reduce the signal voltage to a range the Arduino can read? If so,
2. what would be the best resistor combination to use?

If there are better solutions than a voltage divider then please share.

Thanks very much!

# Answer
> 1 votes
It should work, but I don't know if its the best way.

Because the maximum voltage is 12 volts (I know you are only giving it 8, but you don't want to fry your board) you need the divider to send the Arduino 5/12 of the power. You don't need much current, so you can use big values or resistors. 10K and 24K should work, but you should research or test this before you hook it up to you kit.

---
Tags: sensors, analogread, arduino-duemilanove, voltage
---


title: Shift Register on ATMEGA328p

text:
# Question
Title: Shift Register on ATMEGA328p
I want to learn more about the shiftout function used with Arduinos and used the implementation with my ATMEGA328p.

**The Setup**

This is the original `shiftout` function used in Arduino Programming, except that I replaced 1 with HIGH.

```
#define F_CPU 1000000UL
#define BAUD 9600UL
#define LSBFIRST 0
#define MSBFIRST 1
#define HIGH 0x1
#define LOW  0x0
#define INPUT 0x0
#define OUTPUT 0x1

#include <avr/io.h>
#include <util/delay.h>
#include <USART.h>
#include <pinDefines.h>

#define DATA PD7
#define LATCH PB2
#define CLOCK PB0

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;
    for (i = 0; i < 8; ++i) {
        if (bitOrder == LSBFIRST) {
            PORTD |= (!!(val & (HIGH << i)) << DATA);
            } else {
            PORTD |= (!!(val & (HIGH << (7 - i))) << DATA);
        }
        PORTB |= (HIGH << clockPin);
        PORTB &= ~(HIGH << clockPin);
        }
}

```

**Main**

```
int main(void)
{
    initUSART();
    DDRD |= (HIGH << DATA);
    DDRB |= (HIGH << LATCH) && (HIGH << CLOCK);

    PORTB |= (HIGH << LATCH);
    shiftOut(DATA, CLOCK, LSBFIRST, 1);
    printBinaryByte(PIND);
    PORTB ^= (HIGH << LATCH);

    /* Replace with your application code */
    while (1)
    {

    }

    return (0);
}

```

I created an example to understand more about the function, but the outcome does not add up to what I expected to see.

**Szenario**

```
PORTD |= (!!(val & (HIGH << 0)) << DATA);

```

This is what I expect for `val = 1`

* `(HIGH << 0)` = `00000001`
* `val & (HIGH << 0)` = `00000001 & 00000001`
* `!!(val & (HIGH << 0))` = `1`
* `PORTD |= (1 << DATA)`

As `PORTD` is the data pin on the shift register, it should get `00000001`. When I print the binary number within `PORTD` I get: `10000111` and my LED Array connected to the 74HC595 displays: `10101111`

I am really lost.... I checked the connections to the LEDs and they are all good. Can you explain to me why I receive this awkward result?

# Answer
> This is what I expect for val = 1
>
> PORTD |= (1 \<\< DATA) As PORTD is the data pin on the shift register, it should get 00000001.

your deduction is correct and the code is correct -\> remember this is the case for LSBFIRST. so "val = 0x01" should be sent out as "0b1000 0000", which is precisely what the code is doing.

> !(val & (HIGH \<\< 0))

the "!!" operator is often used to turn a logic value into either '1' or '0'.

the code for shiftout() can be greatly improved.
> 1 votes

# Answer
First of all, PORTD represents the current output state of 8 physical GPIO pins (I think some devices have fewer pins on a port but usually there's 8). I think what you're trying to do is shift a sequence out of a single pin. So just reading it will only tell you what each of the 8 pin states are at that moment, not what you shifted out. I think Arduino's way of doing things is actually harder than just writing the plain C code so I'll ignore it (what is the '!!' ???).

So taking a step back, here's code for pushing an 8bit number serially out of a pin:

```
uint8_t serialData = 0b10011101;  // random data to shift out
uint8_t pin = 3;                  // the pin on PORTD we want to toggle

uint8_t i;
uint8_t nextBit;
for (i = 0; i < 8; i++) {

  // Find the nextBit value to set by shifting our input data by our index
  //   and clearing the other values.  E.g. if serialData == 0b10011101 and
  //   i == 2 then (0b10011101 >> 2) == 0b00100111.  0b00100111 & 1 == 1
  nextBit = (serialData >> i) & 0b00000001;

  // If the next bit is a one, we "or" it to set it
  if (nextBit) {
    // The 'or' operator can only set bits to 1
    PORTD |= 1 << pin;        // in this case, (1 << 3) == 0b00001000
  } else {
    // The 'and' operator can only clear bits to 0
    PORTD &= ~(1 << pin);    // in this case, ~(1 << 3) == 0b11110111
  }
}

```

If you want to add a "clock" pin to go along with the data (like the arduino code) then you can set the clock pin to whatever state before the "for" loop then use an "xor" operator to toggle it each time through the loop:

```
clockPin = 4;

// just before the 'for' loop set the clock to whatever starting state you
//   want.  In this case I'll start it at 0.
PORTB &= ~(1 << clockPin);
.
.
.
// Now in the 'for' loop (at the bottom for example)
PORTB ^= (1 << clockPin);

```

If you want the clock to toggle up then down in a sing loop cycle then you can just repeat the 'xor' twice in a row or force the state using 'or' and 'and' operators. Also, pay attention to timing, you might be toggling things too quickly if the microcontroller clock is fast. You can add delays to the loop to shape the timing of the pattern.
> 1 votes

# Answer
That is some ugly and needlessly slow code!

Nonetheless, I think the main point you need to keep in mind is that when you `OR` the value `00000001` into `PORTD`, you are *only* changing the bottom bit to a `1` \- all other bits will be left untouched to whatever value they already had.

So, it seems that `PORTD` had the value of either `10000111` or `10000110` before you executed `PORTD |= (1 << DATA)` (which is the equivalent of `PORTD |= 0b00000001`)....

```
   10000110
OR 00000001
===========
   10000111

```

The output of your shift register is also just an artifact of whatever the most recent series of bits that you sent to it was. Each time you send a new bit, whatever was there will get shifted over and only the single new bit will be shifted in.

Make sense now?
> 0 votes

---
Tags: avr, c
---


# Question
Title: Multiplex 7 segment during delay (external IC?)
I am using some sensors with the arduino which take a second to receive the data from them. My guess is that there is a delay used somewhere in the library. During this time the multiplexed displays stop working as the rapidly changing grounds are temporarily paused and only one of the displays has the digit lit up. I could change the sensor I'm using (DHT11) to something I could AnalogRead, however I'm curious if there is an external IC for this which drives multiplexed displays with some sort of serial communication or I2C between the arduino and it. I could use a separate arduino(or ATTiny) and write some code for it to do this, but is there a class of chips which already do this? Something where you could pass bytes of the digits and the multiplex delay and it continues to multiplex until the next data is received.

I don't mind if in this time the digits are left in their last states similar to how it would operate if they were directly driven rather than multiplexed. If anyone has insight that would be great!

# Answer
> 1 votes
Perhaps a MAX7219 would do what you want.

> The MAX7219CNG+ is a 8-digit serially interfaced LED Display Driver for LED matrix displays. The MAX7219 is compact, serial input/output common-cathode display drivers that interface microprocessors (¦ÌPs) to 7-segment numeric LED displays of up to 8 digits, bar-graph displays or 64 individual LEDs. Included on-chip are a BCD code-B decoder, multiplex scan circuitry, segment and digit drivers and an 8x8 static RAM that stores each digit. Only one external resistor is required to set the segment current for all LEDs. A convenient 4-wire serial interface connects to all common ¦ÌPs. Individual digits may be addressed and updated without rewriting the entire display. The MAX7219 also allow the user to select code-B decoding or no-decode for each digit.

---
Tags: arduino-uno, display, multiplexer, 7-segment
---


# Question
Title: loading custom code onto SparkFun Blynk Board
we're trying to add some code to the SparkFun Blynk Board. We don't want to overwrite the firmware, because that allows it to work with the iphone app, but we need to add our own voids and Blynk. Write commands in order to control this servo RC car via wifi wit the Joystick XY. any ideas?

our code:

```
#include <Servo.h>
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <Adafruit_NeoPixel.h>
#include <SoftwareSerial.h>
//#define BLYNK_PRINT Serial

char BlynkAuth[] = "6dfb81c116d84003a505056239c23559";
char ssid[] = "Linksys23266";
char pass[] = "roboboyz";

Servo servoR;
Servo servoL;

int pos = 90;

void forward()
{
  servoR.write(110);
  servoL.write(110);
}

void turnRight()
{
  servoR.write(80);
  servoL.write(90);
  delay (2000);
}

void turnLeft()
{
  servoR.write(90);
  servoL.write(80);
  delay(2000);
}

void reverse()
{
  servoR.write(70);
  servoL.write(70);
  delay(2000);
}

void Stop()
{
  servoR.write(94);
  servoL.write(94);
  delay(2000);
}

void setup()
{
  Blynk.begin(BlynkAuth, ssid, pass);  // wifi username and password
  servoR.attach(12);
  servoL.attach(13);
  Serial.begin(9600);
  delay(1000);
}

BLYNK_WRITE(V1)
{
  int x = param[0].asInt();
  int y = param[1].asInt();

  // Do something with x and y
  Serial.print("X = ");
  Serial.print(x);
  Serial.print("; Y = ");
  Serial.println(y);
  if(y>220)
  forward();
  else if(y<35)
  reverse();
  else if(x>220)
  turnRight();
  else if(x<35)
  turnLeft();
  else
  Stop();
}

void loop()
{
  Blynk.run();
}

```

# Answer
That's not how microcontrollers work. You have one firmware and only one firmware. When you upload firmware you replace the existing firmware. You cannot "add" to it.

Instead you will have to write a new firmware that contains *all* the code you need to do the *entire* job.
> 1 votes

---
Tags: wifi, servo
---


# Question
Title: Is it possible to save different values on address 0 and 1 in EEPROM?
I want to save different values on address 0 and 1 on eeprom I tried to change it but when I put data on address 0 and also put data on address 1 the address 0 change its value stored into random number and vice versa .. Is it possible to change the value of respective address without affecting others ..

**CODE**

```
in the setup
     int eepromSize=EEPROM.length();
      Serial.print("EEPROM found, size=");
      Serial.println(eepromSize);
        // Get the last fade value (as an integer)
      EEPROM.get(0, WATEREQFORN1);
      Serial.print("Last Value N1: ");
      Serial.println(WATEREQFORN1);

      EEPROM.get(1, WATEREQFORN2);
      Serial.print("Last Value N2: ");
      Serial.println(WATEREQFORN2);

```

The user will input the value that will be save in eeprom i use switch because the user will input like this example .. 100A or 23B

```
case 'A':
        Serial.print("Case A got ");
        Serial.println(val);
        WATEREQFORN1 = val;

            EEPROM.put(0, WATEREQFORN1);
            Serial.print("DATA SAVE TO EEPROM");

        break;
      case 'B':
        Serial.print("Case B got ");
        Serial.println(val);
         WATEREQFORN2 = val;
         EEPROM.put(1, WATEREQFORN2);
         Serial.print("DATA SAVE TO EEPROM");

        break;

```

The problem is, when I change/write value into address 0 and after that change/write also into address 1 the value on address 0 also change into different random numbers.

# Answer
The variable names in all upper case is a style problem you should address. Conventionally, C and C++ programmers use all-upper-case names to designate defined constants or macros. Contravening that convention can lead to confusion if other people use or maintain the code. Instead of `WATEREQFORN1` consider `waterEq1`, etc.

The problem of your second value overwriting part of the first in EEPROM is an allocation problem. Presumably the `WATEREQ...` variables are multiple bytes in length. `EEPROM.get()` and `put()` read and write data types with multiple bytes using several consecutive bytes of EEPROM. For example, if `WATEREQFORN1` is a real and takes 4 bytes, it will occupy cells 0, 1, 2, 3 in EEPROM.

The following code snippet shows a way to automatically and systematically allocate EEPROM space. The `sizeof` operator returns the size in bytes of its argument. Thus, an expression like `WaterAddr2=WaterAddr1+sizeof waterEq1` correctly sets `WaterAddr2` to be the next available cell after `waterEq1`, no matter what type `waterEq1` is.

```
enum { WaterAddr1=0, WaterAddr2=WaterAddr1+sizeof waterEq1, DelayAddr=WaterAddr2+sizeof waterEq2 };
...
case 'A':
  waterEq1 = val;
  EEPROM.put(WaterAddr1, waterEq1);
  break;
case 'B':
  waterEq2 = val;
  EEPROM.put(WaterAddr2, waterEq2);
  break;
case 'D':
  Delay = val;
  EEPROM.put(DelayAddr, Delay);
  break;
  ...

```
> 1 votes

# Answer
EEPROM.put() and EEPROM.get() write or read the object you pass them. An `int` is 2 bytes so that is what they write or read. It sounds like you intended for the functions to only handle 1 byte. In that case, make the your variable's data type something that is 1 byte, such as `int8_t`; otherwise allocate 2 bytes of EEPROM to each.

Update: It works because you had only allocated 1 byte in EEPROM for each variable but you store 2-byte variables. Now you're storing 1-byte variables, which matches your EEPROM allocation.
> 1 votes

# Answer
Probably WATEREQFORN1 is an int or word, at least more than one byte.

If you write a 2 byte value on address 0, it will occupy address 0 and 1.

When you overwrite address 1 (again with a 2 byte value), it will occupy addres 2 and 3, destroying the LSB part of the value written to byte 0.

Try writing on address 0 and 2 (or 0 and 4 when using 4 bytes).
> 0 votes

# Answer
> Is it possible to change the value of respective address without affecting others ..

Yes, if the two values are 8-bit types.

Otherwise, No.
> 0 votes

---
Tags: arduino-uno, eeprom
---


title: Can't communicate with SIM800 module

text:
# Question
Title: Can't communicate with SIM800 module
I am using Arduino Uno R3 and a SIM800L (voltage regulator built in). My initial setup included a 10kΩ resistor soldered between the lower end of the RX and GND pins on the SIM800L, and a 4.6kΩ resistor soldered on the jumper connecting SIM800L's RX and Arduino's declared TX (pin 7). SIM800L has its own power supply (5v-2A). This is a setup I have used previously on two different SIM800L modules, and everything worked fine without any (visible) problems.

Baud rate is set to 9600 in Arduino IDE, PC port (via Device manager), and the module, through the sketch.

After loading the sketch (first one) shown on this site, the SIM800L connects to the GSM network (I can tell by the delay between blinks), but the module does not respond to AT commands send via serial monitor.

**The sketch**

```
#include <SoftwareSerial.h>

//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 8

//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7

//Create software serial object to communicate with SIM800
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup() {
  //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(9600);
  delay(1000);
}

void loop() {
  //Read SIM800 output (if available) and print it in Arduino IDE Serial Monitor
  if(serialSIM800.available()){
    Serial.write(serialSIM800.read());
  }
  //Read Arduino IDE Serial Monitor inputs (if available) and send them to SIM800
  if(Serial.available()){
    serialSIM800.write(Serial.read());
  }
}

```

**Things tried**

Thinking that the resistors might be causing this, I removed all of them, and made a clean connection with Arduino. And the problem persisted.

I tried resetting the module, by passing the ATW command into a sketch:

```
serialSIM800.write("ATW\r\n");

```

and that also gave no results. Further testing with:

```
if(!serialSIM800.available()) {
    Serial.println("Not working");
}

```

indicated where the problem might be.

I have also tried changing the baud rate to 48000, 57600, and 115200, but that did not solve my problem.

**The question**

Am I right in assuming that a reset to factory settings could solve my problem? If so, how can I reset the module, **without** the AT commands? If resetting would do me no good, what else could I try?

# Answer
This is widely happen problem - serial communication with SIM800L stopped working. You *can* do reset, but in my case it didn't help: on powered SIM800L module shortcut "RST" pin with the ground for half of second - unit should reset and restart. I think it's defective architecture/firmware, but unfortunately SIMCOM dropped support for this model, so best advise is to avoid SIMCOM until they study how to make quality products.
> 1 votes

---
Tags: arduino-uno
---


title: Speedometer slow reaction arduino

text:
# Question
Title: Speedometer slow reaction arduino
I'm trying to make a speedometer, with utilization of interrupt for get number of pulse and some calculation for getting speed, but when compute speed the arduino freeze for some second and i lose alot of impulse and false all my successive capture of impulse. Why? thanks for reply

```
const int contaImpulsi = 2;
volatile int impulsi =  0;
int impulsiOld = 0;
static int appoggio = 0;
unsigned deltaT[3];
unsigned vel = 0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(contaImpulsi, definisciTempi, RISING);
}

void loop() {

  if (impulsiOld == impulsi || impulsi > impulsiOld)
  {
    if (appoggio == 3) {
      deltaT[3] = millis();
      appoggio = 0;
    }
    if (appoggio == 2) {
      //Serial.println("ASSEGNO DELTA T 2");
      deltaT[2] = millis();
      //Serial.println(deltaT[2]);
      appoggio = 3;
    }
    if (appoggio == 1) {
      //Serial.println("ASSEGNO DELTA T 1");
      deltaT[1] = millis();
      appoggio = 2;
    }
    if (appoggio == 0) {
      //Serial.println("ASSEGNO DELTA T 0");
      deltaT[0] = millis();
      appoggio = 1;
    }
  }
  impulsiOld = impulsi;

  if (appoggio == 3) {

    int t1 = (deltaT[1] - deltaT[0]);
    int t2 = (deltaT[2] - deltaT[1]);
    int dividi = t1 + t2;
    vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85; // here i think is where the program freeze

    Serial.println("------------------------------------------");
    Serial.print("SPEED: ");
    Serial.println(vel);
    Serial.println("------------------------------------------");
  }
}

void definisciTempi() {
  impulsi++;
}

```

# Answer
> 1 votes
First off a comment on your variable types. It's not the cause of your problem, but just something to watch for in future:

```
int impulsi =  0;

```

This should be voltatile (Edit: I see you updated that, that's ok).

```
unsigned deltaT[3];
unsigned vel = 0;

```

These lack a type. As such the default to `int`. Your deltaT array should be `unsigned long` since it stores time. It will overflow very rapidly otherwise.

Now on to your problem.

The core of your problem is your methodology of calculating the speed. This bit:

```
if (impulsiOld == impulsi || impulsi > impulsiOld)
{
  ...
}
impulsiOld = impulsi;

```

is going to be running pretty much always. That's because `impulsiOld` and `impulsi` will either always be the same (since you set them to be the same) or `impulsi` is going to be greater than `impilsiOld` since you received a pulse in the brief interlude when it's not running that bit.

And that means that all your `deltaT` entries are going to be the same most of the time. Which leads me on to the next bit:

```
int t1 = (deltaT[1] - deltaT[0]);
int t2 = (deltaT[2] - deltaT[1]);
int dividi = t1 + t2;
vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85;

```

If `delatT[1]` and `deltaT[0]` are the same, then `t1` will be `0`. The same goes for `t2`. `0 + 0 = 0`, so `dividi` will also be 0.

And that means:

```
690 * 2000 / 0

```

Which will be a *divide by zero exception* and will cause the MCU either to lock up or to reboot. If the latter you will see the bootloader run for a couple of seconds.

There are two normal methods of calculating the speed from pulses, and I am not sure what your method is trying to be.

The simplest one is to just count the number of pulses over a given period. Increment the count in your ISR, and after a second has elapsed (or longer, or shorter, depending on the frequencies you are working with) you reset the count to 0 (after storing it elsewhere) and calculate the speed from that stored count.

The other way is to just take the time between two successive pulses. You can average it, maybe with a rolling (AKA moving) average, or just take the raw value depending on what you are measuring. This method is a little harder since you need to do more work per pulse.

The two methods differ in critical ways when it comes to outputting the results. The first method will always give you a value every second (or whatever time period you use), but it can't cope with pulses that are further apart than the time period you use. The second method doesn't much care about the time between the pulses, but you can only get a meaningful reading if a pulse arrives, which if that is a while means you get no reading for a while. It's harder to determine "not moving" from that.

Also you should look at the use of *critical sections* when accessing your `impulsi` variable outside the interrupt routine. It more than 8 bits, so all access to it will be *non-atomic* and could be interrupted by the ISR.

---
Tags: arduino-uno, interrupt, pulsein, performance
---


# Question
Title: Arduino Mega + XBee Shield + RAMPS 1.4 Is it possible?
Is it possible to sandwich an XBee shield between Arduino Mega and Ramps 1.4 without damaging any of the boards or lose of Ramps functionality ?

I am not trying to make a 3D printer it is rather a completely different project and I am afraid of burning my XBee or losing some functionality of ramps.

Since XBee shield has the form factor of Arduino UNO I had to 3D print the rest of the shield and use some connectors to completely cover the Mega.

# Answer
Yes, it would seem like folks on the RepRap forums have gotten this to work with the following setup that should work in general:

> Attach the XBee shield to the RAMPS board by attaching 4 pins on AUX-1 (namely, 5V, Gnd, D1 and D0) to the 5V, Gnd, Rx and Tx pins on the XBee Shield
>
> Switch the UART / DLINE switch on the XBee Shield to UART

Source: RepRap Forum: Printing completely wirelessly - can it be done?

This forum thread may also be useful.
> 1 votes

# Answer
Yes, and the answer is really simple. You need to extend the connectors between the xbee shield and the ramps shield. Either by adding another layer of the through pin connectors you have or by resoldering some longer ones on the RAMPS board.

You might have an issue with the RF signal, sticking that much metal near the xbee board might cause problems, but I think you can get external aerials for them, if that becomes an issue.
> 1 votes

---
Tags: arduino-mega, shields, xbee
---


title: HMC5883L tilt compensation

text:
# Question
Title: HMC5883L tilt compensation
I have a HMC5883L 3-axis magnetometer. I would like to add tilt compensation to my Arduino Uno project.

Since the IC has 3 axis that it measures (X,Y,Z) is it possible to add tilt compensation without an accelerometer? If yes would this how do I find an equation to do the calculation. Is this equation found from http://bluelemonlabs.blogspot.fi/2013/08/arduino-simple-compass-with-hmc5883l.html correct?

# Answer
> 0 votes
No. You need an accelerometer.

If you read the article you link to you can see this bit:

> There are many margin of improvement. First, we ought compensate the potential tilt of the device using the accelerometer data from the ADXL345, for example using the info on my previous post!

To do tilt compensation you need three axes of both magnetometer data and accelerometer data to scale and merge those three axes.

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


title: Wrong computation Number

text:
# Question
Title: Wrong computation Number
im trying to make a speedometer with arduino Nano Board but when i use interrupt im getting "strange" number on variables `t1` or `t2` going under 0 there is the code:

```
volatile int impulsi =  0;
int impulsiOld = 0;
volatile int appoggio = 0;
//static int inizioDiNuovo = 0;
volatile unsigned int deltaT[3];
long t1=0;
long t2=0;

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

  pinMode(2, INPUT_PULLUP);
  attachInterrupt(0, definisciTempi, RISING);

}

void loop() {

  Serial.println(impulsi);
  if (impulsi == impulsiOld || impulsi > impulsiOld)
  {
    ;
  }
  //Serial.print("N IMPULSI: ");
  //Serial.println(impulsi);
  if (appoggio == 3) {
    appoggio = 0;
    Serial.print("DELTA T 0 : ");
    Serial.println(deltaT[0]);
    Serial.print("DELTA T 1 : ");
    Serial.println(deltaT[1]);
    Serial.print("DELTA T 2 : ");
    Serial.println(deltaT[2]);

    t1 = (deltaT[1] - deltaT[0]);
    if (t1 == 0) {
      t1 = 1;
    }
    t2 = (deltaT[2] - deltaT[1]);
    if (t2 == 0) {
      t2 = 1;
    }
    int t = t1 + t2;

    Serial.print("TEMPO T1 ");
    Serial.println(t1);
    Serial.print("TEMPO T2 ");
    Serial.println(t2);

  }

}

void definisciTempi() {
  impulsi++;
  switch(appoggio){

    case 2:
    //Serial.println("ASSEGNO DELTA T 2");
    deltaT[2] = millis();
    //Serial.println(deltaT[2]);
    appoggio = 3;
    break;

    case 1:
    //Serial.println("ASSEGNO DELTA T 1");
    deltaT[1] = millis();
    appoggio = 2;
    break;

    case 0:
    //Serial.println("ASSEGNO DELTA T 0");
    deltaT[0] = millis();
    appoggio = 1;
    break;

  }
}

```

how suggest i changed

```
unsigned int t1=0; unsigned int t2=0; into `long t1=0; long t2=0;`

```

output on Serial now have negative number it's for the interrupt??:

```
DELTA T 0 : 8785
DELTA T 1 : 8666
DELTA T 2 : 8706
TEMPO T1 40
TEMPO T2 -119  <------how 8706-8666= -119 ?

```

this is my pulse generator code:

```
const int pin = 2;
void setup() {
  pinMode(pin,OUTPUT);

}

void loop() {
 digitalWrite(pin,HIGH);
 delay(40);
 digitalWrite(pin,LOW);
 delay(40);
}

```

# Answer
The interrupt may be triggering between the Serial.print and the actual calculations, as stated by @Andrew.

Evidence supporting that fact is that your deltas are recorded in order 0, 1, 2 (ie: delta 0 \< delta 1 \< delta 2), However in the example output delta 0 is larger than delta 2, which suggests that a new round of delta recordings had started but not yet completed.

Updating this section as follows should fix the issue:

```
if (appoggio == 3) {

  noInterrupts(); // Disable interrupts while calculating

  appoggio = 0;
  Serial.print("DELTA T 0 : ");
  Serial.println(deltaT[0]);
  Serial.print("DELTA T 1 : ");
  Serial.println(deltaT[1]);
  Serial.print("DELTA T 2 : ");
  Serial.println(deltaT[2]);

  t1 = (deltaT[1] - deltaT[0]);
  if (t1 == 0) {
    t1 = 1;
  }
  t2 = (deltaT[2] - deltaT[1]);
  if (t2 == 0) {
    t2 = 1;
  }
  int t = t1 + t2;

  Serial.print("TEMPO T1 ");
  Serial.println(t1);
  Serial.print("TEMPO T2 ");
  Serial.println(t2);

  interrupts(); // re-enable interrupts

}

```
> 0 votes

# Answer
```
unsigned int t1=0;
unsigned int t2=0;

```

Integers on an 8 bit system can only store 16 bits of data. For `unsigned` that is 0 - 216-1, or 0 - 65535.

Make them `unsigned long` and they can store 0 - 232-1, or 0 - 4294967295.

Also, since they are `unsigned`, any negative value will *wrap around* to the maximum again. An `unsigned` can't store a negative value.
> 0 votes

---
Tags: arduino-nano, interrupt
---


# Question
Title: I2C begginer with I/O expander with mega328p C code
I've just started with the I2C protocol. I read about it in the datasheet, other documents, blogs and videos.

So, I started to develop my code and I think I did my first success, I succeeded to send start and check TWST for sending start signal.

I get started OK, but I can't proceed to send data. What I'm missing? I'm thinking I didn't send the correct address.

```
void I2C_init(void);
void I2C_start(void);
void I2C_stop(void);
void I2C_tx(uint8_t data);
void I2C_TWSR_Check(void);

void setup() {
  Serial.begin(9600);
  I2C_init();
  //  I2C_TWSR_Check();
  I2C_start();
  I2C_TWSR_Check();
  I2C_tx(0x40);           // sending the address
  I2C_TWSR_Check();       // waiting for response
}

void loop() {
  uint8_t i;
  // simple loop to blink an LED on the I/O expander pin
  for (i=0;i<5;i++) {
    I2C_tx(0xff);
    I2C_TWSR_Check();
    _delay_ms(500);
    I2C_tx(0x00);
    I2C_TWSR_Check();
    _delay_ms(500);
  }
}

void I2C_init(void) {
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1<<TWEN);
}

void I2C_start(void) {
  TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while (!(TWCR & (1<<TWINT)));
}

void I2C_stop(void) {
  TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t u8data) {
  TWDR = u8data;
  while (!(TWCR & (1<<TWINT)));
}

void I2C_TWSR_Check(void) {
  uint8_t Status;
  Status = TWSR & 0xF8;
  switch(Status) {
    case 0x08: // start OK
    Serial.println("Start is OK");
     break;
    case 0x10: // Re start
    Serial.println("Re start");
     break;
    case 0x18: // SLA+W OK ACK
    Serial.println("SLA+W OK ACK");
     break;
    case 0x20: // SLA+W no ACK
    Serial.println("SLA+W no ACK");
     break;
    case 0x28: // data OK ACK
    Serial.println("data OK ACK");
     break;
    case 0x30: // data OK no ACK
    Serial.println("data OK no ACK");
     break;
    case 0x38: // arbitration lost in SLA+W or data TX
    Serial.println("arbitration lost in SLA+W or data TX");
     break;
     default:
     Serial.println("Error");
    break;
  }
}

```

# Answer
> 0 votes
OK the answer is that I didn't send the correct address!

Because if the I2C starting command with the slave is successful, then you should get successful sending ACK according reading the value of transmission status from the status register TWSR and ANDing this value with 0xF8. Then by reading the datasheet you know the value of transmission status. I developed a function to determine the status of transmission with Arduino Serial library which is I2C\_TWSR\_Check();.

I did this code for Master transmitter and receiver only.

So the trick is that you have to fix the address according to the AVR's TW address command format, which is the first bit is for read/write command and the remaining 7-bits are for the address, so you have to shift the real address which I got by "I2C address scanner" I got from one of AVRfreaks members.

For example, if the address is 0x20, then after shifting it 1-bit to the left, the new address is 0x40 for write operation and 0x41 for read operation.

```
void I2C_init(void);
void I2C_start(uint8_t address);
void I2C_stop(void);
void I2C_tx(uint8_t data);
uint8_t I2C_rx(void);
void I2C_TWSR_Check(void);

uint8_t bitmask;

/////////// I2C modules addresses ////////////
// 8-bit I/O expander 0x20
#define IOEXP_WR  0x40    // I/O 8-bits expander address
#define IOEXP_RD  0x41

// LCD1602 adapter
#define LCD1602_WR  0x4E  // LCD1602 I2C adapter address
#define LCD1602_RD  0x4F

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  I2C_init();
}

void loop() {

  I2C_start(LCD1602_WR);
  I2C_TWSR_Check();
  I2C_tx(0xff);
  I2C_TWSR_Check();
  I2C_stop();
  _delay_ms(500);

  I2C_start(LCD1602_WR);
  I2C_tx(0x00);
  I2C_stop();
  _delay_ms(500);
}

void I2C_init(void)
{
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1<<TWEN);
}

void I2C_start(uint8_t address)
{
  TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while (!(TWCR & (1<<TWINT)));
  //I2C_TWSR_Check();
  TWDR = address;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  //I2C_TWSR_Check();
}

void I2C_stop(void)
{
  TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t data)
{
  TWDR = data;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  //I2C_TWSR_Check();
}

uint8_t I2C_rx(void)
{
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

void I2C_TWSR_Check(void)
{
  uint8_t Status;
  Status = TWSR & 0xF8;
  switch(Status)
  {
    /////////////// MASTER TRANSMITTER //////////////
    case 0x08:
    Serial.println("Start is OK");
     break;
    case 0x10:
    Serial.println("Re start");
     break;
    case 0x18:
    Serial.println("SLA+W OK ACK");
     break;
    case 0x20:
    Serial.println("SLA+W no ACK");
     break;
    case 0x28:
    Serial.println("data TX OK ACK");
     break;
    case 0x30:
    Serial.println("data TX OK no ACK");
     break;
    case 0x38:        // arbitration lost in SLA+W or data TX
    Serial.println("arbitration lost in SLA+W or data TX");
     break;

    /////////////// MASTER RECEIVER //////////////
    case 0x40:
    Serial.println("SLA+R OK ACK");
     break;
    case 0x48:
    Serial.println("SLA+R OK NO ACK");
     break;
    case 0x50:
    Serial.println("data RX OK ACK");
     break;
    case 0x58:
    Serial.println("data RX OK NO ACK");
     break;

     default:
     Serial.println("Error");
    break;
  }
}

```

---
Tags: i2c, c, avr
---


# Question
Title: How to keep a specific bit set all the time for bit masking I2C operations?
I've been working on I2C and I learned how to initialize, send and receive with I2C communication protocol.

Next, I wanted to run the LCD1602 I2C adapter. But the module has a different bit masking, it turns out that I have to keep a specific bit set so I can control the remaining 7-bits, because otherwise I can't control the upper 4-bits if this bit is 0.

So, I put the 8-bit variable for the bit masking operations in the global section and initialize it with uint8\_T bitmasking = 0x08; but it's volatile. I used static keyword, but the bit is not constant.

So what's the solution?

Regards,

# Answer
> 1 votes
'static' just avoids reinitialization and is used for local vars in timed interrupts for example.

`volatile` is another keyword you should not be using without thinking about it and does not appear to be useful for your case. See https://stackoverflow.com/questions/4592762/difference-between-const-const-volatile for more information

The appropiate keyword would be `const`, which tells the compiler this var mustn't be changed.

But I suspect there is another problem with your code, which will make the compiler throw an error as soon as you use `const` in the declaration. I assume you are not using the variable correctly. You are meant to use a bitwise OR `|` in order to set the required bit **along** your actual data.

So do it like this:

```
data_byte |= bitmasking;
write8(data_byte);

```

---
Tags: c, variables
---


# Question
Title: Is it any way to connect ESP8266 to wifi faster?
I'm uploading this sketch to try connecting ESP to internet. However, most of the times I've ran it it takes a very long time to connect, a lot of times I've had to break the process because it seems it goes to nowhere. Few times it has connected in less than a minute. Is it any alternative to boost the connection?

Also, when I reset the module, it writes to the terminal 3 strange characters, and freezes without even starting to execute its sketch. Do you mind me asking how to solve that?

Regards!

```
#include <ESP8266WiFi.h>

const char red[] = "CDT10";
const char pass[] = "G7ZSY74Cs";
unsigned long muestra = 0;

void setup() {
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(red,pass);
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(1000);
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: "); Serial.println(WiFi.localIP());
  Serial.print("Chip ID: "); Serial.println(ESP.getChipId());
}

void loop() {
  delay(5000);
  muestra = millis();
  Serial.println(muestra);
}

```

# Answer
> 1 votes
I have also experienced the inability to connect sometimes. I wait a certain amount of time for it to connect then do a ESP.reset() if it fails.

As for the boot problem it sounds like you are keeping GPIO0 low so it goes back into programming mode. Hold it high and it will run your program instead.

---
Tags: esp8266, wifi, sketch
---


# Question
Title: Accelerometer MPU-6050 marks timeout in Unity
I've been having this problem, that I am trying to use an accelerometer MPU-6050 to get the rotation and pass that information to Unity.

I also have some buttons in the same Arduino. I'm using an Arduino Uno. With those buttons, everything works well, but the moment I put something related to the accelerometer in the Arduino code, Unity marks a time out. When I run it on Arduino it sends me all the info I'm asking, so I don't really know what's the problem. I really appreciate if someone could help me.

Here is code on Arduino:

```
#include<Wire.h>
#define A_R 16384.0
#define G_R 131.0
 #define RAD_A_DEG = 57.295779
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int AcX,AcY,AcZ,GyX,GyY;

float Acc[2];
float Gy[2];
float Angle[2];
int button = 0;
int button2 = 0;
int button3 = 0;

float arriba=0, abajo=0,mouse=0;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  pinMode(7, INPUT); // declare pushbutton as input
pinMode(6, INPUT);
pinMode(5,INPUT);
  Serial.begin(9600);
}

void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  //Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers

  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
 AcZ=Wire.read()<<8|Wire.read();

  Acc[1] = atan(-1*(AcX/A_R)/sqrt(pow((AcY/A_R),2) + pow((AcZ/A_R),2)))*RAD_TO_DEG;
   Acc[0] = atan((AcY/A_R)/sqrt(pow((AcX/A_R),2) + pow((AcZ/A_R),2)))*RAD_TO_DEG;

  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)

  Angle[0] = 0.98 *(Angle[0]+Gy[0]*0.010) + 0.02*Acc[0];
   Angle[1] = 0.98 *(Angle[1]+Gy[1]*0.010) + 0.02*Acc[1];

        button = digitalRead(7);
  button2 = digitalRead(6);
  button3 = digitalRead (5);

   //Mostrar los valores por consola
   if(button == HIGH){
 arriba=1;
  }else if(button==LOW){
  arriba=0;
  }

  if(button2 == HIGH){
    abajo=1;
  }else if(button2==LOW){
    abajo=0;
  }

  if(button3 == HIGH){  //boton 3
    mouse=1;
  }else if(button3==LOW){
    mouse=0;
  }
  Serial.print(arriba);
  Serial.print(",");
  Serial.print(abajo);
  Serial.print(",");
  Serial.print(mouse);
   Serial.print(",");

   Serial.print(Angle[0]);
   Serial.print(",");
   Serial.println(Angle[1]);

  delay(200);
}

```

I know this isn't an Unity forum, but here is the code in Unity. The only thing it does, is read it and put the results in an array.

```
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Globalization;
using System;

using UnityEngine;

public class ConectarArduino: MonoBehaviour
{
    string Recibidos;
    public string Linea, Linea1,Linea2;
    public int Arrib, Abajo,Boton;
    SerialPort stream;
    // Use this for initialization

    void Start()
    {
        stream = new SerialPort("COM3", 9600);
        //  stream.
        stream.Open();
        stream.ReadTimeout = 300;

    }

    // Update is called once per frame
    void Update()
    {
        try
        {
            Recibidos = stream.ReadLine();
            Debug.Log(Recibidos);
        }
        catch (System.Exception e)
        {
            Debug.Log(e.Message);
            throw;
        }

        string[] Values = Recibidos.Split(',').Select(str => str.Trim()).ToArray();
        Linea = Values[0];
        Linea1 = Values[1];
        Linea2 = Values[2];

```

# Answer
Running MPU-6050 at 57600bps seemed to be the good rate for me:

```
  pinMode(5,INPUT);
  Serial.begin(57600);
}

```

It worked for me and I found these guys for whom it was the good rate :

From MPU-6050-simple-library, specifically MPU6050\_test.ino:

> ```
> void setup() {
>   Serial.begin(57600);
>   MPU6050mgr.begin(); // Initializes IMU module
> }
>
> ```

From Another Arduino as external i2c device for MPU6050:

> ```
> void setup() {
>   Wire.begin(0x1E);                // join i2c bus with address #8
>   Wire.onReceive(receiveEvent); // register event
>   Serial.begin(57600);           // start serial for output
> }
>
> ```

From Library for Arduino and MPU-6050 communication:

> ```
> void setup() {
>   Serial.begin(57600);
>   MPU6050mgr.begin(); // Initializes IMU module
> }
>
> ```

You may also find this link useful: MPU-6050 Redux: DMP Data Fusion vs. Complementary Filter.
> 1 votes

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


title: Arduino Uno: Receive MIDI data from DAW

text:
# Question
Title: Arduino Uno: Receive MIDI data from DAW
I basically want to have my Arduino accept MIDI data from my digital audio workstation, my choice is Ableton Live. I would then like it to check the received data and change the state of a digital pin accordingly. I made a pretty basic schematic to show you.

(Just a very quick diagram, I intend to use RGB LEDs and transistors of some sort in the final product)

I would be happy using a Serial\>Midi of some sort if it's the only way, but true USB MIDI would be nice.

# Answer
> 1 votes
The R3's ATmega16U2 supports USB, so all you need to create a USB MIDI device is software.

On AVRs, you typically use the Lightweight USB Framework for AVRs (LUFA), which has support code for both the basic USB protocol and for USB MIDI.

# Answer
> 0 votes
For USB Midi you could use: Arduino UNO + USB Host Shield + USBH\_MIDI Library

The library is specifically for the USB Host Shield. I've used this to take MIDI over USB from a digital piano and used it to control some LEDs. It's pretty strait forward to get it all working.

---
Tags: midi
---


# Question
Title: 7 Segments display with arduino mega2560
I doing a small project with 6 display 7 segment (I will call A1, A2, A3, A4, A5, A6) and 3 cd4543B (I will call Da, Db, Dc) with an arduino mega 2560. I also use 6 transistor to control power supply of display.

Da is use for A1, A2

Db is use for A3, A4

Dc is use for A5, A6

The circuit is done, and work if I use only 4 display I have tried different combination (A1, A2, A3, A4, or A1, A2, A5, A6 or A2, A3, A4, A5, or A3, A4, A5, A6) and all work well.

but If I want to use five or six display, nothing work....

there is resistance for each segment of each display which not appear on the diagram.

my code for 5 display :

```
//Da
const int bit_A=8;
const int bit_B=9;
const int bit_C=10;
const int bit_D=11;
//Db
const int bit_E=22;
const int bit_F=24;
const int bit_G=26;
const int bit_H=28;
//Dc
const int bit_I=40;
const int bit_J=42;
const int bit_K=44;
const int bit_L=46;

// transistors
const int alim_dizainemillier= 3;
const int alim_millier=4;
const int alim_centaine=5;
const int alim_dizaine=6;
const int alim_unite=7;

void setup()
{

pinMode(bit_A,OUTPUT);
pinMode(bit_B,OUTPUT);
pinMode(bit_C,OUTPUT);
pinMode(bit_D,OUTPUT);
pinMode(bit_E,OUTPUT);
pinMode(bit_F,OUTPUT);
pinMode(bit_G,OUTPUT);
pinMode(bit_H,OUTPUT);
pinMode(bit_I,OUTPUT);
pinMode(bit_J,OUTPUT);
pinMode(bit_K,OUTPUT);
pinMode(bit_L,OUTPUT);
pinMode(alim_dizainemillier,OUTPUT);
pinMode(alim_millier,OUTPUT);
pinMode(alim_centaine,OUTPUT);
pinMode(alim_dizaine,OUTPUT);
pinMode(alim_unite,OUTPUT);

digitalWrite(bit_A,LOW);
digitalWrite(bit_B,LOW);
digitalWrite(bit_C,LOW);
digitalWrite(bit_D,LOW);
digitalWrite(bit_E,LOW);
digitalWrite(bit_F,LOW);
digitalWrite(bit_G,LOW);
digitalWrite(bit_H,LOW);
digitalWrite(bit_I,LOW);
digitalWrite(bit_J,LOW);
digitalWrite(bit_K,LOW);
digitalWrite(bit_L,LOW);
digitalWrite(alim_dizainemillier,LOW);
digitalWrite(alim_millier,LOW);
digitalWrite(alim_centaine,LOW);
digitalWrite(alim_dizaine,LOW);
digitalWrite(alim_unite,LOW);
}

void loop()
{
 for(int i=0;i<100000;i++)
 {
   afficher_nombre(i);

 }
}

void afficher_nombre(int nombre)

{
 long temps;
 int unite=0,dizaine=0,centaine=0, millier=0, dizainemillier=0;
 dizainemillier=nombre/10000;
 millier=(nombre-(10000*dizainemillier))/1000;
 centaine=(nombre-1000*millier)-(10000+dizainemillier)/100;
 dizaine=(nombre-(centaine*100)-(millier*1000)-(dizainemillier*10000))/10;
 unite=nombre-(dizainemillier*10000)-(millier*1000)-(centaine*100)-(dizaine*10);

 temps=millis();
 while((millis()-temps)<500){

    digitalWrite(alim_dizainemillier,HIGH);
    afficher_CD(dizainemillier);
    digitalWrite(alim_millier,LOW);
    digitalWrite(alim_centaine,LOW);
    digitalWrite(alim_dizaine,LOW);
    digitalWrite(alim_unite,LOW);
    delay(5);

    digitalWrite(alim_dizainemillier,LOW);
    digitalWrite(alim_millier,HIGH);
    afficher_CM(millier);
    digitalWrite(alim_centaine,LOW);
    digitalWrite(alim_dizaine,LOW);
    digitalWrite(alim_unite,LOW);
    delay(5);

   digitalWrite(alim_dizainemillier,LOW);
   digitalWrite(alim_millier,LOW);
   digitalWrite(alim_centaine,HIGH);
   afficher_CM(centaine);
   digitalWrite(alim_dizaine,LOW);
   digitalWrite(alim_unite,LOW);
   delay(5);

   digitalWrite(alim_dizainemillier,LOW);
   digitalWrite(alim_millier,LOW);
   digitalWrite(alim_centaine,LOW);
   digitalWrite(alim_dizaine,HIGH);
   afficher_UD(dizaine);
   digitalWrite(alim_unite,LOW);
   delay(5);

   digitalWrite(alim_dizainemillier,LOW);
   digitalWrite(alim_millier,LOW);
   digitalWrite(alim_centaine,LOW);
   digitalWrite(alim_dizaine,LOW);
   digitalWrite(alim_unite,HIGH);
   afficher_UD(unite);
   delay(5);
 }
}

void afficher_UD(int chiffre)
{
  digitalWrite(bit_A,LOW);
  digitalWrite(bit_B,LOW);
  digitalWrite(bit_C,LOW);
  digitalWrite(bit_D,LOW);

      if(chiffre>=8)
         {
           digitalWrite(bit_D,HIGH);
           chiffre=chiffre-8;
         }
     if(chiffre>=4)
         {
           digitalWrite(bit_C,HIGH);
           chiffre=chiffre-4;
         }
    if(chiffre>=2)
         {
           digitalWrite(bit_B,HIGH);
           chiffre=chiffre-2;
         }
    if(chiffre>=1)
         {
           digitalWrite(bit_A,HIGH);
           chiffre=chiffre-1;
         }
}

void afficher_CM(int chiffre)
{
  digitalWrite(bit_E,LOW);
  digitalWrite(bit_F,LOW);
  digitalWrite(bit_G,LOW);
  digitalWrite(bit_H,LOW);

      if(chiffre>=8)
         {
           digitalWrite(bit_H,HIGH);
           chiffre=chiffre-8;
         }
     if(chiffre>=4)
         {
           digitalWrite(bit_G,HIGH);
           chiffre=chiffre-4;
         }
    if(chiffre>=2)
         {
           digitalWrite(bit_F,HIGH);
           chiffre=chiffre-2;
         }
    if(chiffre>=1)
         {
           digitalWrite(bit_E,HIGH);
           chiffre=chiffre-1;
         }
}

void afficher_CD(int chiffre)
{
  digitalWrite(bit_I,LOW);
  digitalWrite(bit_J,LOW);
  digitalWrite(bit_K,LOW);
  digitalWrite(bit_L,LOW);

      if(chiffre>=8)
         {
           digitalWrite(bit_L,HIGH);
           chiffre=chiffre-8;
         }
     if(chiffre>=4)
         {
           digitalWrite(bit_K,HIGH);
           chiffre=chiffre-4;
         }
    if(chiffre>=2)
         {
           digitalWrite(bit_J,HIGH);
           chiffre=chiffre-2;
         }
    if(chiffre>=1)
         {
           digitalWrite(bit_I,HIGH);
           chiffre=chiffre-1;
         }
}

```

I don't understand why it's not working. Could it be a power supply problem ? even if there is never two display used at the same time (delay between them, see code)

Thanks a lot for any help.

# Answer
> 1 votes
Try this link Arduino and CD4543

To control a common cathode seven segment display using CD4543

```
PH ( Pin 6 ) should be set LOW.
LD ( Pin 1 ) should be set HIGH.
BL ( Pin 7 ) should be set LOW.

```

Try this code for each segment, could be faulty segment too :)

```
int Ph  = 6;      //arduino pin connected to the Ph pin of 4543
int BL  = 5;     //arduino pin connected to the BL pin of 4543
int LD  = 11;   //arduino pin connected to the LD pin of 4543

int A   = 7;
int B   = 9;
int C   = 10;
int D   = 8;

void setup()
{
    // Declare all the pins as OUTPUT pins

  pinMode(Ph,  OUTPUT);
  pinMode(BL,  OUTPUT);
  pinMode(LD, OUTPUT);

  pinMode(A , OUTPUT);
  pinMode(B  , OUTPUT);
  pinMode(C  , OUTPUT);
  pinMode(D, OUTPUT);

}

void loop()
{

    // Display 0

  digitalWrite(Ph,  LOW);
  digitalWrite(BL,  LOW);
  digitalWrite(LD,  HIGH);

  digitalWrite(A , LOW);
  digitalWrite(B , LOW);
  digitalWrite(C , LOW);
  digitalWrite(D , LOW);

  delay(1000);

    // Display 1

  digitalWrite(A , HIGH);
  digitalWrite(B , LOW);
  digitalWrite(C , LOW);
  digitalWrite(D , LOW);

  delay(1000);

    // Display 2

  digitalWrite(A , LOW);
  digitalWrite(B , HIGH);
  digitalWrite(C , LOW);
  digitalWrite(D , LOW);

  delay(1000);

    // Display 3

  digitalWrite(A , HIGH);
  digitalWrite(B , HIGH);
  digitalWrite(C , LOW);
  digitalWrite(D , LOW);

  delay(1000);

    // Display 4

  digitalWrite(A , LOW);
  digitalWrite(B , LOW);
  digitalWrite(C , HIGH);
  digitalWrite(D , LOW);

  delay(1000);
}

```

# Answer
> -1 votes
> The circuit is done,

unnecessarily complex: you can share the data lines among the drivers.

---
Tags: arduino-mega, display
---


title: Wakeup Pin ESP8266

text:
# Question
Title: Wakeup Pin ESP8266
Is there a way to put an ESP8266 into a sort of "sleep" mode where it draws less power than usual, and then wakes up on a pin going high? I've tried doing this with delay, which still draws 20 mA, and with the deepsleep function that comes with the esp library, which can't sleep for short periods of time to watch for the pin going high. I'm building a watch, and power draw is of great concern to me. Is there possibly a way I could build or code this differently to make it more power efficient? Basically it works like this, but the full code (at it's current state) can be found here.

```
void loop() {
    delay(1);
    // check for power signal stuff
    if(digitalRead(0)) {
        // execute data fetching 'n stuff
    }
}

```

# Answer
> 2 votes
Without seeing the code and optimizing it I can tell you the following:

ESP8266 has three ways to save power:

1. Modem sleep - only wlan modem shutdown, connection kept open
2. Light sleep - less cpu usage, fast recovery
3. Deep sleep - suspend all, close wifi too, slow recovery

http://bbs.espressif.com/viewtopic.php?t=133

# Answer
> 0 votes
ESP8266 does have deep sleep mode. The link to http://bbs.espressif.com/viewtopic.php?t=133 posted earlier sums it up pretty well, despite being old.

However, a few things that are different from Arduino or should be considered if you're building a battery-operated device:

* when the MCU wakes up from deep sleep, the entire application is restarted. Yes, beginning from the setup() function - just as if it was reset. You cannot put it to the deep sleep and then resume from the same place keeping all variables etc. You can only detect that the device was woken up from the sleep by reading a flag in the setup() function.
* check your board. If you're not using bare ESP8266, but some development board such as NodeMCU or WittyCloud, it usually has number of other circuits powered on even when the MCU is sleeping. Particularly, USB-UART bridge and maybe power LED.
* check your power source. Again, if you're using a development board, very likely it has an inefficient LDO voltage regulator. Even when MCU is powered down, the LDO can still use a few mA just to power itself (quiescent current). There are special low quiescent current regulators exist, very useful for battery-operated application.
* finally, I see your code refers some OLED display. Just to be sure - is it powered down or excluded from the measurement? OLED doesn't need a lot of energy, but will drain a battery in a few days.

Personally, I do have experience creating a battery-operated device on ESP8266, which wakes up every few minutes, connects to wifi and sends some data. An old 700mAh Lithium battery is enough to run it for approximately a month. And I managed to get the sleep power to about 40 microAmps. Still a few times more than the chip itself needs, but good enough for me.

---
Tags: esp8266, power, sleep
---


title: Did I damage my Arduino?

text:
# Question
Title: Did I damage my Arduino?
I was trying to build a Bluetooth controlled car. I was near completing it but what I did wrong was that I connected the 5 V output of L298 motor driver to 5V pin of Arduino where I was supposed to connect it in Vin. My Arduino got heated for a couple of seconds. Knowing that I immediately disconnected. Now serial port doesn't work in my Arduino. The serial port option turned gray. I even tried replacing the ATmega IC but got the same result. What might have happened?

# Answer
> 1 votes
Yes, it sounds like you fried something.

I can't quite make out what it was you did from your description (I'm sure it makes perfect sense to you with the hardware in front of you), but the symptoms do sound somewhat fatal.

What actually happened depends very much on the Arduino you have - if it's a genuine one or a cheap Chinese clone. Either way the USB circuitry seems to not be functioning. Whether that is because the USB chip (varies depending on if it's a real Arduino \[ATMega16U2\] or a clone \[CH340G\]) or one of the voltage regulators is unknown.

You should power the board up normally and test the voltages at the 5V and 3.3V pins. Also if a component is still getting hot you should note which component it is, and that will give more of a clue as to what went wrong.

# Answer
> 0 votes
You fried it you should ALWAYS double check connections before powering on your arduino but I do suggest doing a normal power up without any connections to see what happens

# Answer
> 0 votes
The ATmega328 on these boards is 5V tolerant on GPIOs so it depends on where exactly you connected the cable.

GND pins, for example, would've been fatal.

# Answer
> 0 votes
it feel sad to hear that you just fried it up. Every mistakes gives opportunity to learn tons of knowledge. In this case you supplied 5v supply to 5v output pin. If you've seen the datasheet of **8-bit AVR Micro-controller ATmega328/P** you'll know that it just possess VCC for 5v supply pin (input) neither an output 5v pin. Its the job of voltage regulator attached next to the power jack to supply 5V to provide the necessary juice to the chip. If you supplied 5v to GPIO output pin then you may or may not have burnt the chip but for sure you burnt the arduino board ,technically its power control system. So i think it'll be better buying a new board rather then fixing it.But i salute your attempts.

---
Tags: arduino-uno
---


title: Arduino/Genuino 101 5 volts pin

text:
# Question
Title: Arduino/Genuino 101 5 volts pin
Still trying to understand the nomenclature of the pins, I am confused of what's the function of the +5V pin, as I read that the 101 should not operate at that tension.

What's it for?

# Answer
In Genuino 5V pin is a DC regulated pin. That means when you supply Power (9 to 12 V) to Vin or through the DC Jack, a 5V voltage regulator regulates to give constant output at 5 V. The purpose of that pin is to provide 5V output for other use- as a power supply to some sensor you are interfacing or anything.

However, you can power up the Genuino 101 via the 5V pin. But that is not advisable because in that case it will bypass the regulator present in the board and can damage the circuit if improperly regulated.
> 2 votes

---
Tags: pins, voltage-level, 101
---


title: ESP-32 with tft display

text:
# Question
Title: ESP-32 with tft display
I recently got a Adafruit TFT screen and an ESP-32 development kit. I was trying to interface these two the pin connections I used areas follows:

```
TFT   |   ESP-32
------+----------
3V3   |   Vcc
Gnd   |   Gnd
MOSI  |   GPIO19
SCK   |   GPIO18
CS    |   GPIO5
D/C   |   GPIO16
RST   |   GPIO 17

```

I used this library: https://github.com/MartyMacGyver/ESP32\_Adafruit\_ILI9341

The SPI library used was the one that comes while installing Arduino support for ESP-32.

The code compiles and uploads without any error/ warning but the TFT screen does not show any response (except powering up).

This is the code I used for testing:

```
//#include <Adafruit_ST7735.h>

#include<Adafruit_ILI9341.h>
#include <Adafruit_GFX.h>
#include "SPI.h"

#define TFT_CS     5
#define TFT_RST    17
#define TFT_DC     16

// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
//Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// If using the breakout, change pins as desired
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS ,TFT_DC, 23, 18, TFT_RST);

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.println("In the setup.");
    //tft.initR(INITR_BLACKTAB);
    unsigned long t=micros();
    tft.fillScreen(ILI9341_RED);
    Serial.println(micros()-t);
}

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

}

```

The code compiles and uploads without any error/warning but the TFT screen does not show any response (except powering up).

NOTE: The library works fine with Arduino Mega and TFT display.

# Answer
Ok, sorry for the delay, I had my exams. But I have finally solved the issue. There were several issues:

1. MOSI should be connected to pin 23 not 19.
2. `tft.begin()` function should be in the setup to initialize the TFT. (for ILI9341)
3. The SPI library used should be the one that comes with ESP-32 support. The general SPI library for Arduino does not work with ESP-32.

Note: the ST7735 library currently does not work with ESP-32. It can be made to work by adding the following definitions given bellow to the Adafruit\_ST7735.h header file.

```
    #elif defined(ESP32)
    volatile uint32_t *dataport, *clkport, *csport, *rsport;
    uint32_t  _cs, _rs, _rst, _sid, _sclk,
    datapinmask, clkpinmask, cspinmask, rspinmask,
    colstart, rowstart;

```

(add this just after the ESP8266 definitions).
> 0 votes

---
Tags: adafruit, tft
---


title: Why doesn't analogWrite() work

text:
# Question
Title: Why doesn't analogWrite() work
Can anybody tell me why these analogWrite() statements are being ignored. The code is entering the "if"statements because the Serial.println() statements are being executed.

```
    class Pwm
{
  unsigned long previousMillis = 0;
  unsigned long currentMillis;
  int LED;
  int DELAY;
  int up;
  int down;
  int x;

  public:
  Pwm(int led, int Delay) {

    int LED = led;
    pinMode(LED, OUTPUT);

    DELAY = Delay;
    up = 1;
    down = 0;
    x = 0;

  }

  void Update() {
    currentMillis = millis();
    if (currentMillis - previousMillis >= DELAY && up == 1) {
    analogWrite(LED, x);
    x++;
    previousMillis = currentMillis;
    Serial.println(x);
    if (x == 256) {
      up = 0;
      down = 1;
    }
  }
  if (currentMillis - previousMillis >= DELAY && down == 1) {
    analogWrite(LED, x);
    x--;
    previousMillis = currentMillis;
    Serial.println(x);
    if (x == 0) {
      up = 1;
      down = 0;
    }
   }
  }

};

// create Flasher Objects
Flasher red(12, 1000, 250);
//Flasher yellow(11, 500, 500);
//Flasher green(10, 250, 1000);
//Flasher blue(8, 250, 500);

// create PWM Objects
Pwm pin9(9,8);

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

void loop()
{
  red.Update();
  //yellow.Update();
  //green.Update();
  //blue.Update();
  pin9.Update();
}

```

if I load this code everything works fine. I only have issues with the OOP method.

```
int LED = 9;
int DELAY = 8;
int up = 1;
int down = 0;
int x;
unsigned long currentMillis;
unsigned long previousMillis = 0;

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

void loop() {
  currentMillis = millis();
  if (currentMillis - previousMillis >= DELAY && up == 1) {
    analogWrite(LED, x);
    x++;
    previousMillis = currentMillis;
    if (x == 256) {
      up = 0;
      down = 1;
    }
  }
  if (currentMillis - previousMillis >= DELAY && down == 1) {
    analogWrite(LED, x);
    x--;
    previousMillis = currentMillis;
    if (x == 0) {
      up = 1;
      down = 0;
    }
  }
}

```

# Answer
> 3 votes
The constructor in your `Pwm` class declares a local variable `LED` which it sets equal to the parameter `led`. You use the member variable `LED` in other methods, so you probably meant to set the member variable of the same name, not create a local.

Remove the `int` from before `LED = led` in the constructor.

---
Tags: arduino-uno, analogwrite
---


# Question
Title: Communication between Arduino and raspberry Pi
So I am working on a ground surveillance robot using Arduino for coding the Gps, motors and ultrasonic sensors and coding in raspberry Pi for facial recognition but now what I want to do is when my robot has gotten to its final waypoint and has stopped it should excute the python file that does the facial recognition by calling it in the Arduino sketch but I don't know how to do it would be nice if someone could please help me out I appreciate your help in advance thank you

# Answer
> 1 votes
You can't make the Arduino just run the Python script on the Pi. Instead you will have to run some software (probably of your own devising) on the Pi that listens for instructions from the Arduino.

The simplest way is probably to modify your existing Python script so that it runs all the time but sits idling waiting for instructions through the serial port (using pySerial). When it gets the instruction to perform the task you need it then goes off and runs the main bulk of its code. When that is done it can then return the results back through the serial port to the Arduino (if you need such results returning).

How you arrange those instructions to get it to do things is entirely up to you.

---
Tags: arduino-mega, c, python, raspberrypi
---


title: Run program from SRAM on SAMD21?

text:
# Question
Title: Run program from SRAM on SAMD21?
I am looking for an example of how to load a program from sd card to SRAM and execute it from there on the SAMD21.

I understand that the given MCU use the Von Neumann architecture and all code is privileged.

# Answer
> 0 votes
There's two aspects to what you want to do - one (relatively) easy, and one (comparatively) hard.

The first thing you will need is some way of getting your program into RAM. That would mean some software running on the chip that will accept the program and place it into RAM then execute it. You will have to write your own bootloader-like program that runs in Flash that will perform the task.

The second, harder, thing is to compile your program in such a way that it will execute from RAM. And that's no easy task.

Ideally you want to compile the code as *position independent code* (with the command line flag `-fPIC`), but that depends on the compiler being able to do that for this chip. If not, you will have to compile it so that the code expects to reside in RAM with all addresses used for jumps, etc, going to the right location. And that brings me to the second aspect of compiling, the *linker script*.

If you have your code in RAM you can't also have your variables in the same place in RAM. You will have to subdivide the RAM into two sections - the code execution section and the variable storage section. This is done through the construction of a custom *linker script* which is used during the linking phase of compilation. It tells the compiler where in memory to place everything - code, variables, etc. You will need to craft your own linker script to divide the RAM up in a suitable manner to give you enough room for your code while at the same time not starving it of variable storage space. This will also make sure all jumps, etc, in your code use the right addresses in case you can't (or don't want to) use `-fPIC`.

So, given all that, do you still *really* want to execute code from RAM?

---
Tags: arduino-zero
---


# Question
Title: How to include userid, pass to WifiClient connect() api
These are my remote server credentials that I want to connect from my local device.

```
Server  m12.cloudserver.com
User    <myname>
Password    <mypassword>
Port    19999
_ or
api_key 5678909876-009-00d

```

I want to use the WiFiClient client() API as shown, but where or how do I include the User credentials ? so that I can make a successful connection to the remote server from my device connected over Wifi.

Cut and paste from my Arduino code.

```
const int httpPort = 19999;
if (!client.connect("m12.cloudserver.com", httpPort)) {
 Serial.println("connection failed");
 return;
}

```

# Answer
> 1 votes
WifiClient provides low level tcp connection. Your server seems to be implementing a REST API interface. Thus you need to construct HTTP headers (GET, POST, etc.) manually as a string. Then you can add your credentials. Before doing so, try to use your server, I mean call api's with the program named `Postman`. Postman runs on Chrome browser. `Postman` can compose such headers for you. Then you can insert them into your arduino code.

---
Tags: wifi
---


title: CurieBLE receive data without pairing

text:
# Question
Title: CurieBLE receive data without pairing
I read exist articles about it, but still not understand how to do that. I have a Genuino 101 and an EEG Headband (neuro interface). Need to get data from neuro device. With external HC-05 bluetooth module the code look like this:

```
 SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
 bluetooth.begin(57600);
 while (!bluetooth.available()) {}
 byteRead = bluetooth.read();

```

Has anyone encountered a similar problem? Thanks!

# Answer
HC-05 module is not BLE (Bluetooth 4.0)! HC-05 implements SPP (Serial port profile) over Bluetooth Classic (Bluetooth 2.0). You will need a module with BLE capability and that is not over yet. BLE implements several (hundred) profiles for each task such as heartrate monitor, neuro monitor, time etc etc. Your BLE module must be condigured to receive a specific profile data.
> 0 votes

---
Tags: bluetooth, genuino, 101
---