# Question
Title: Accelerometer (I2C) and Fona Shield (software serial) won't work together
I am using a Fona 808 shield with an Arduino Uno and the LSM303 accelerometer. The accelerometer is connected via I2C and the Fona uses software serial.

My project requires the accelerometer to be continuously polled and occasionally talk with the fona. I wrote a program that just used the fona, but once I added the accelerometer code the program would hang a few seconds after comms had been opened with the Fona. I have tested both the accelerometer and the fona shield separately, and they work fine. So, I wrote another smaller (test) program (which is attached below) to find the origin of the program, which I identified to be:

```
fonaSerial->begin(4800);

fona.begin(*fonaSerial);

```

After these lines of code are added, the problem arises. As I said before, this is what I see a few seconds after comms have been opened with the Fona. http://pasteboard.co/A16708fo3.png

My test program reads the value from the accelerometer, calculates the magnitude of the acceleration and if it's over 20, it prints "Over 20", while also initialising Fona serial.

My question is: Why don't the accelerometer (I2C) and the Fona (Serial) work together and how this be fixed?

This is quite urgent so a quick responses are greatly appreciated!

My Code:

```
#include <Adafruit_FONA.h>
#include <Adafruit_Sensor.h>
#include <My2_Adafruit_LSM303_U.h>
#include <Wire.h>

#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4

#include <SoftwareSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;

Adafruit_FONA fona = Adafruit_FONA(FONA_RST);

volatile byte accelMagnitude;

Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(54321);

void setup() {
  // put your setup code here, to run once:

    accel.begin();

    Serial.begin(115200);

    fonaSerial->begin(4800);
    fona.begin(*fonaSerial);

}

void ReadAccel(){

//Get a new accelerometer sensor event
  sensors_event_t event;
 // Serial.println(F("Accel---------"));
  accel.getEvent(&event);

  accelMagnitude = sqrt( sq(event.acceleration.x) + sq(event.acceleration.y) + sq(event.acceleration.z));

}

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

    ReadAccel();

    if (accelMagnitude > 20){

        while (accelMagnitude > 20){

            Serial.println("waiting");
            ReadAccel();
        }

        Serial.println("Over 20");

    }
}

```

# Answer
As Gerben suggests, it would not be a good practice to just add a delay and call it a day.

1) Have a large electrolytic capacitor between Vcc and GND as near as you can to the FONA and

2) FONA has `getNetworkStatus();` make a small control loop and query it until you get status 1 or 5, depending on what network are you on. From FONA's example:

```
if (n == 0) Serial.println(F("Not registered"));
if (n == 1) Serial.println(F("Registered (home)"));
if (n == 2) Serial.println(F("Not registered (searching)"));
if (n == 3) Serial.println(F("Denied"));
if (n == 4) Serial.println(F("Unknown"));
if (n == 5) Serial.println(F("Registered roaming"));

```

And then proceed with the rest of your code. You can make additional checks for signal quality with `getRSSI();`
> 1 votes

---
Tags: arduino-uno, i2c, shields, softwareserial
---


# Question
Title: How does one **get** attributes for SD files?
To be able to set the date and time of the files on my SD card I followed this answer: https://arduino.stackexchange.com/a/39127/49678

Now I am wondering **How do I read the values out in the microcontroller?** To clearify, I get the correct timestamps when I remove the SD card and view them on a PC, but I also want to be able to read this on the microcontroller.

Inside SdFile.cpp on line 1025 there is a function called timestamp which is used to set the timestamp but I cant seem to find any function to read it. https://github.com/adafruit/SD/blob/master/utility/SdFile.cpp

I would prefer a solution where I don't have to add it to the library myself.

The underlying problem I am facing is that I want to log files, and once the memory is full I which to remove the oldest files.

# Answer
> 2 votes
In the FAT filesystem the timestamps and other attributes are stored in the directory, not in the file. So you need to read the "file" that is the directory that contains the file you're interested in.

That "file" contains entries in a pre-defined structure. Reading each block of data using that structure gives you the information for each file in turn.

You can just do a normal `SD.open(...)` call to open the directory that contains your file, and then read chunks of data from it to get each file entry.

That data is arranged in the `directoryEntry` structure (here), so reading a block of data with `File.read(...)` into a variable of that structure type will yield your data:

```
struct directoryEntry dirent;

// myDir has already been opened and points at the start of your dir
while (myDir.read((uint8_t *)&dirent, sizeof(struct directoryEntry))) {

    // Names are tricky to print. Also you should check for deleted files here.
    Serial.print("Name: ");
    for (int i = 0; i < 11; i++) {
        Serial.print(dirent.name[i]);
        if (i == 7) {
            Serial.print(".");
        }
    }
    Serial.println();
    Serial.print("Creation Time: ");
    Serial.println(dirent.creationTime);
    Serial.print("Creation Date: ");
    Serial.println(dirent.creationDate);
}

```

# Answer
> 2 votes
You need to get an `SdFile` object for your file then use the `SdFile::dirEntry` method to get the directory entry for the file.

The directory entry (`struct directoryEntry`) has the timestamps.

---
Tags: sd-card, sd, sd.h
---


# Question
Title: Cloud function getting stopped Parse.com in loop when calling from Arduino-yun
I have created a cloud function using the Parse.com Javascript SDK and I am calling those functions from Arduino. Following is code for the `hello` function:

```
Parse.Cloud.define("hello", function(request, response) {
                response.success("This is hello function");
}); //hello function Block

```

I am calling this function from the Arduino side using the following code:

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

  while (!Serial);

  Parse.begin("***zE0uUjQkMa7nj5D5BALvzegzfyVNSG22BD***", "***Ssggp5JgMFmSHfloewW5oixlM5ibt9LBSE***");
  //commented my keys with * here only

  // In this example, we associate this device with a pre-generated installation
  Parse.getInstallationId();
  Parse.startPushService();
}

void loop() {
  Serial.println("Start loop");
  demoBasic("meeting", 0);
}

void demoBasic(String functionname, int light) {
  char fnname[11];
  functionname.toCharArray(fnname, 11);

  Serial.print("In ");
  Serial.print(functionname);
  Serial.println(" Function");

  ParseCloudFunction cloudFunction;
  cloudFunction.setFunctionName(fnname);
  cloudFunction.add("light_sensor", light);
  cloudFunction.add("value", "Arduino Hello");//parameters

  ParseResponse response = cloudFunction.send();
  Serial.println(response.getJSONBody());
}

```

Problem is that I am getting response 8 times only. After that whole program flow gets blocked. What is the problem?

# Answer
Give this a shot, I really hate String, maybe that 8-times thing has to do with memory issues caused by it.

```
void loop() {

  char functionToCall[8] = "meeting";
  Serial.println("Start loop");
  demoBasicCharArray(functionToCall, 0);
}

void demoBasicCharArray(char *functionname, int light) {

  Serial.print("In ");
  for (byte i=0;i<sizeof(functionname);i++){
    Serial.print(functionname[i]);
  }
  Serial.println(" Function");

  ParseCloudFunction cloudFunction;
  cloudFunction.setFunctionName(functionname);
  cloudFunction.add("light_sensor", light);
  cloudFunction.add("value", "Arduino Hello");//parameters

  ParseResponse response = cloudFunction.send();
  Serial.println(response.getJSONBody());
}

```
> 1 votes

---
Tags: arduino-yun, code-review
---


# Question
Title: Uni-directional communication between NodeMCU and Arduino spits out garbage
I am sending data from ESP8266 (NodeMCU) to Arduino using serial and 9600 baud rate on both sides. Since it is uni-directional and from NodeMCU to Arduino, I am not using a voltage regulator and I have connected tx (Software Serial) of NodeMcu to Rx of Arduino. I've connected the usb of nodeMCU to my computer. I've done the same thing to power Arduino.

Here is some sample code on NodeMCU:

```
#define Arduino_RX 4 // D2
#define Arduino_TX 5 // D1
SoftwareSerial ArduinoSerial(Arduino_RX, Arduino_TX); // RX | TX

void setup() {
  Serial.begin(115200);
  ArduinoSerial.begin(9600);
  delay(10);

  // Connect to WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");
}

void loop()
{
    ArduinoSerial.println("hi");
    Serial.println("hi");
    delay(1);
}

```

Code on Arduino

```
#define ESP8266_RX   2
#define ESP8266_TX   3
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(ESP8266_RX, ESP8266_TX); // RX | TX

void setup() {
  // put your setup code here, to run once:
    Serial.begin(9600);     // communication with the host computer
    ESPserial.begin(9600);
    Serial.println("Ready");

}

void loop() {
  if ( ESPserial.available() )   {
    Serial.write( ESPserial.read() );
  }
}

```

# Answer
1. https://www.pjrc.com/teensy/td\_libs\_AltSoftSerial.html
2. Do you GND them via your PC USB? Try connecting their GND as well.
3. External power could be an issue as well, I am not aware of power consumption of ESP when they do stuff with their WiFi.
> 1 votes

---
Tags: arduino-uno, esp8266, nodemcu
---


# Question
Title: LCD prints weird characters when I place the print statement in setup after pinMode statements
```
#include "LiquidCrystal.h"

const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7)

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(22, INPUT_PULLUP); // Reed switch - Row1
  pinMode(24, INPUT_PULLUP); // Reed switch - Row2
  pinMode(26, INPUT_PULLUP); // Reed switch - Row3
  pinMode(28, INPUT_PULLUP); // Reed switch - Row4
  pinMode(32, OUTPUT);
  digitalWrite(32, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("hello");
}

```

When I run the above code I get weird characters in my LCD. I removed all the connections to the pins\` defined in pinMode and left only the lcd connections but kept the pinMode and digitalWrite statements in the code, but am still getting weird characters. But when I remove the pinMode and digitalWrite statements from my code the lcd works fine. Can anyone help me out.

**Edit**:
Another weird thing happened, I removed all the pinMode and digitalWrite statements do my setup() had only Serial.begin() and lcd.begin() and I only had the lcd connections. Now I put this code to print into an function called lcdprintMove() and there were other functions too which were performing other tasks when I ran it as such I got weird characters in the LCD but when I removed all of the other functions,the lcd printed fine. From this I was able to conclude that this problem can't be because of the supply but has to be something else. But I still can't figure it out.

**Problem Solved**

Today I commented all the digitalWrite statements and uploaded the program and it worked! So, I am going to connect the lcd onto a separate arduino and communicate serially. Someone suggested the solution of putting a cap to ground and buff the power of 5 v pin can you explain this in more detail.

**Circuit diagram** Note: Rs is connected to pin 7 and E to 6

# Answer
> -1 votes
The capacitor between 5V and GND effectively acts as a small battery. When a sudden demand in a current relatively large occurs, the system can get that extra small amount from the cap and not experience a voltage drop.

---
Tags: arduino-mega, lcd
---


title: Burning bootloader

text:
# Question
Title: Burning bootloader
I'm using arduino atmega 328p and currently using on custom PCB I programmed using the arduino board and take the IC and migrated to my custom PCB currently the program run well on the arduino board but after i tried to run it in my custom PCB and i found it didn't worked im using along with 16000 mhz oscillator with 22n capacitor

as shown this is my schematic for my PCB

this is my trace for my PCB board

so is this problem caused by my schematics or i didn't upload the bootloader?

# Answer
Schematic corrections:

Missing 0.1uF caps on VCC, AREF pins.

AREF pin connected to 5V - don't do that. It will connect internally using the ADC Mux if used.

C1, C6 need to be 22pF as noted earlier.

Xtal and C1, C6 should be right next to the chip as noted, with no traces going under the xtal.

Board should have Gnd plane anywhere there is not a trace.

Use Vias to connect top & bottom Gnd planes.

Do not use traces to connect all the Gnds - have pins connect to the Gnd planes instead.

Add a 1uF or 10uF electrolytic capacitor where power comes into the board, especially if the power leads will be long.
> 4 votes

---
Tags: atmega328, pcb-design
---


# Question
Title: ESP8266EX along with Arduino Due rev3 to check wifi status
Hi i am using ESP8266EX along with Arduino Due rev3 to check wifi status. when i compile my following sketch compiler give me error User\Awais\Document\Arduino\liberaries\espsoftserialmaster\softserial.cpp:27:18: fatal error: gpio.h: no file or directory found any one help me solve this problem

```
    #include <SoftwareSerial.h>
    SoftwareSerial ESPserial (15,14); //RX|TX

     void setup() {
  // put your setup code here, to run once:

  Serial.begin(115200);
  ESPserial.begin(115200);
  Serial.println("NL & CR");
}

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

  if (ESPserial.available()){
   Serial.write(ESPserial.read());
  }

if (Serial.available()){
ESPserial.write(Serial.read());
}
  }

```

# Answer
And where did you get that SoftwareSerial library? SoftwareSerial libraries are architecture dependent. You can't use AVR ore esp8266 SoftwareSerial library with ARM.

Due has no need for SoftwareSerial, it has 4 Serial ports configured.
> 1 votes

---
Tags: arduino-due
---


# Question
Title: Simplify if then else statements for Neopixel/compass project
I am working on a project where a rotary encoder is generating 0 - 359° output and I am feeding that to a 60 Neopixel ring but I need a way to simplify or come up with a better way of a bunch of *if-then-else* statements. Here is some sample code.

```
// NeoPixel Display
  if ((counter >=3) && (counter <=9))
(
  strip.setPixelColor(0, 255, 0, 0); //set pixel number 1 and set color to red
  strip.show(); //send color to pixel 1 on NeoPixel Ring
)
else if strip.setPixelColor(0, 0, 0, 0);
        strip.show();

  if ((counter >=10) && (counter <=15))
(
  strip.setPixelColor(1, 255, 0, 0); //set pixel number 2 and set color to red
  strip.show(); //send color to pixel 2 on NeoPixel Ring
)
else if strip.setPixelColor(1, 0, 0, 0);
        strip.show();

  if ((counter >=16) && (counter <=21))
(
  strip.setPixelColor(2, 255, 0, 0); //set pixel number 3 and set color to red
  strip.show(); //send color to pixel 3 on NeoPixel Ring
)
else if strip.setPixelColor(2, 0, 0, 0);
        strip.show();

```

# Answer
You don't use the correct syntax. I assume you mean:

```
// NeoPixel Display
if ((counter >=3) && (counter <=9))
{
  strip.setPixelColor(0, 255, 0, 0); //set pixel number 1 and set color to red
  strip.show(); //send color to pixel 1 on NeoPixel Ring
}
else
{
  strip.setPixelColor(0, 0, 0, 0)
  strip.show();
}

```

And similar for the other colors.

First you see there are a lot of occurences of calls to setPixelColor and show. We make a function of this, where the color and the red value is parameterized:

```
void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
}

```

Now we can write your code as

```
// NeoPixel Display
if ((counter >=3) && (counter <=9))
{
  setPixel(0, 255);
}
else
{
  setPixel(0, 0);
}

void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
  strip.show();
}

```

And similar for the other colors.

Now we get rid of the if statements. For the first color this will become:

```
// NeoPixel Display
setPixel(0, ((counter >= 3) && (counter <= 9)) ? 255 : 0);

```

Combined with the other colors we get

```
// NeoPixel Display
setPixel(0, ((counter >=  3) && (counter <=  9)) ? 255 : 0);
setPixel(1, ((counter >= 10) && (counter <= 15)) ? 255 : 0);
setPixel(2, ((counter >= 16) && (counter <= 21)) ? 255 : 0);

void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
  strip.show();
}

```

However, the conditions can be simplified by adding them into the function. So we get

```
// NeoPixel Display
setPixel(0, counter,  3,  9);
setPixel(1, counter, 10, 15);
setPixel(2, counter, 16, 21);

void setPixel(int pixelNumber, int counter, int lowValue, int highValue)
{
  strip.setPixelColor(pixelNumber,
     ((counter >= lowValue) && (counter <= highValue)) ? 255 : 0,
     0, 0);
  strip.show();
}

```

If you need to have more checks if a value is in range you can make it a specific function. This will increase the code, but makes it easier to reuse code. So you will get:

```
// NeoPixel Display
setPixel(0, counter,  3,  9);
setPixel(1, counter, 10, 15);
setPixel(2, counter, 16, 21);

void setPixel(int pixelNumber, int counter, int lowValue, int highValue)
{
  strip.setPixelColor(pixelNumber,
    inRange(counter, lowValue, highValue) ? 255 : 0,
     0, 0);
  strip.show();
}

int inRange(int counter, int lowValue, int highValue)
{
   return ((counter >= lowValue) && (counter <= highValue));
}

```
> 3 votes

---
Tags: neopixel
---


# Question
Title: Can't write to serial immediately from PC to Arduino nano via pl2303 usb to ttl converter
**Goal:**

I am trying to send some characters to Arduino through serial from PC via a Prolific PL2303 USB to TTL converter(Chinese clone).

I have wrote a simple sketch(attached bellow) which should light up the LED if 'n' is found or should switch the LED off if 'f' is found from serial.

**What's Happening:**

I opened up the serial monitor. Send a character(say 'n' which should light up the LED). But nothing happened though the RX/TX LEDs flashed. Then I re opened the serial monitor. And just after re opening the serial monitor LED light up! Every time when I issue a character from serial monitor nothing happens. But just after re opening the monitor character is sent.

**H/W Connection:**

* Arduino Vin -\> LiPo positive rail(+11V)
* Arduino GND -\> LiPo negative rail(GND)
* Prolific GND -\> Arduino GND
* Prolific RX -\> Arduino TX
* Prolific TX -\> Arduino RX

**Arduino Sketch:**

```
int led = 13;

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

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0){
    char bytesReceived = Serial.read();
    Serial.println(bytesReceived);

    if(bytesReceived == 'n'){
      digitalWrite(led, HIGH);
    }
    else if(bytesReceived == 'f'){
      digitalWrite(led, LOW);
    }
  }
}

```

**Additional Notes:**

* Platform Windows 10
* Installed Prolific PL2303 driver from here
* This code is working using USB cable provided with Arduino.(I need longer cable)

Can't understand why this strange thing is happening. Any kind of help will be appreciated.

Thanks!

# Answer
I have experienced similar behavior with clone chips. What worked for me is using ferrite choked USB cables similar to these; as you referenced as well, I observed that the problem occurs with either longer cable, or with cables without ferrite chokes on them. This might have to do with the PCB or the cheap chips being prone to electromagnetic interference.
> 1 votes

---
Tags: serial, arduino-nano
---


# Question
Title: Uno to Mega and where is the error for the interrupt that isn't delared?
I want to read a Omron E6B2-CWZ6C Incremental Rotary Encoder w/Index (360P/R). A couple questions, I found out that an Uno can only handle 2 interrupt pins and I think I need 3 for the Index. What do I need to do to the following code to get it to run on a Mega which I believe can handle 3 interrupt pins?

Also I am getting a 'outAChange' was not declared in this scope. What am I missing here.

I will be using the data from the encoder value to run a NeoPixel 60 for a directional mast/antenna.

Here is the code I am trying to use:

```
// Wiring connections for my encoder:
// Brown : VCC = 5 to 24VDC
// Blue: 0V(Common) = GND
// Shield: GND
// Black: outA = Digital pin 2
// White: outB = Digital pin 3
// Orange: outZ = Digital pin 4 (Index)
// With these outA/outB/outZ connections and the interrupt code below
// clockwise rotation gives positive encoder counts

const int outA = 2;
const int outB = 3;
const int outZ = 4;

volatile long encoder = 0; // declare volatile since modified by interrupt routines
float encoder_save = 0;

void setup(){  // set encoder pins
pinMode(outA, INPUT_PULLUP);
pinMode(outB, INPUT_PULLUP);
pinMode(outZ, INPUT_PULLUP);  //Index

// attach interrupts to pins
attachInterrupt(digitalPinToInterrupt(outA), outAChange, CHANGE);
attachInterrupt(digitalPinToInterrupt(outB), outBChange, CHANGE);
attachInterrupt(digitalPinToInterrupt(outZ), outZChange, CHANGE);

// initialize serial
Serial.begin(57600);
}

void loop(){

if (encoder_save != encoder)  // only print if new value
encoder_save = encoder;

// If Index(Z) reads low reset encoder to 0
if (digitalRead(outZ) == LOW)
{
  encoder = 0;
}
}

{
Serial.println((encoder * 360)/360);
}
}

// interrupt routines
void outAChange(){
// when outA changes, outA==outB means negative direction
encoder += digitalRead(outA) == digitalRead(outB) ? -1 : 1;
if (encoder < 0)
{
  encoder = (encoder + 360);
}
}

void outBChange(){
// when outB changes, outA==outB means positive direction
encoder += digitalRead(outA) == digitalRead(outB) ? 1 : -1;
if (encoder >= 360)
{
  encoder = (encoder - 360);
}
}

```

# Answer
Your brackets are all messed up. If you pass your code through an autoformatter (such as the one included in the IDE) you end up with this:

```
// Wiring connections for my encoder:
// Brown : VCC = 5 to 24VDC
// Blue: 0V(Common) = GND
// Shield: GND
// Black: outA = Digital pin 2
// White: outB = Digital pin 3
// Orange: outZ = Digital pin 4 (Index)
// With these outA/outB/outZ connections and the interrupt code below
// clockwise rotation gives positive encoder counts

const int outA = 2;
const int outB = 3;
const int outZ = 4;

volatile long encoder = 0; // declare volatile since modified by interrupt routines
float encoder_save = 0;

void setup() { // set encoder pins
    pinMode(outA, INPUT_PULLUP);
    pinMode(outB, INPUT_PULLUP);
    pinMode(outZ, INPUT_PULLUP);  //Index
// attach interrupts to pins
    attachInterrupt(digitalPinToInterrupt(outA), outAChange, CHANGE);
    attachInterrupt(digitalPinToInterrupt(outB), outBChange, CHANGE);
    attachInterrupt(digitalPinToInterrupt(outZ), outZChange, CHANGE);
// initialize serial
    Serial.begin(57600);
}

void loop() {
    if (encoder_save != encoder) { // only print if new value
        encoder_save = encoder;
    }

// If Index(Z) reads low reset encoder to 0
    if (digitalRead(outZ) == LOW) {
        encoder = 0;
    }
}

{                                                << WHAT
    Serial.println((encoder * 360) / 360);       << IS
}                                                << THIS
}                                                << CODE?

// interrupt routines
void outAChange() {
// when outA changes, outA==outB means negative direction
    encoder += digitalRead(outA) == digitalRead(outB) ? -1 : 1;

    if (encoder < 0) {
        encoder = (encoder + 360);
    }
}

void outBChange() {
// when outB changes, outA==outB means positive direction
    encoder += digitalRead(outA) == digitalRead(outB) ? 1 : -1;

    if (encoder >= 360) {
        encoder = (encoder - 360);
    }
}

```

As you can see, after the end of your `loop()` function, you have an extraneous block of code with a bunch of random brackets.

You need to decide where in your program that should actually be and move it there, deleting those extra brackets.
> 1 votes

---
Tags: arduino-uno, arduino-mega, interrupt, rotary-encoder
---


# Question
Title: Arduino code for thermistor respiratory monitor
I have designed a thermistor-based respiratory monitor which detects changes in temperature during respiration, but I am having problems with the coding part. Can someone help, my code given below is not working.

```
void setup() {
  Serial.begin(9600);
}
unsigned long timer;
void loop(void)
{
    delay (500)
  int sensorValue = analogRead(A0);
timer=millis ();
    if ( sensorValue<200) {
unsigned long currentTime = millis();
float period_respiration = currentTime-timer;
float breathrate= 60000/period_respiration;
Serial.println("Respirations per minute:");
Serial.println(breathrate);
  }
}

```

The sensor value is 600-800 during inspiration, and about 100 during expiration.

# Answer
The *primary* reason your code doesn't work is very simple: every time you go around the loop you set

```
timer = millis();

```

and if the reading is greater than 200 you set

```
currentTime = millis();

```

but ***those two statements are executed just a few microseconds apart***, so the difference between them (in milliseconds) will almost always be zero (it might occasionally be one if you happened to cross a tick boundary, but it will never be more than that).

There are a few other problems with the logic of your code, which I think you'll understand when you look at some code that *will* work. Try something like this:

```
enum respState {
    Inhaling,
    Exhaling
};
unsigned long prevRespTime = 0;
unsigned long currRespTime = 0;
respState currentRespState;
int movingAvgRespRate = 0;

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

void loop()
{
    //delay(500);
    // don't need to delay because we'll only fire once per inhalation and once per exhalation
    int sensorValue = analogRead(A0);

    if ((sensorValue > 300) && (currentRespState == Exhaling))
    {
        currentRespState = Inhaling;
        prevRespTime = currRespTime;  // save time from last cycle
        currRespTime = millis();

        float period_respiration = currRespTime - prevRespTime;
        float breathrate = 60000 / period_respiration;
        Serial.print("Inhaling /tRespirations per minute: ");
        Serial.println(breathrate);
    }
    else if ((currentRespState == Inhaling) && (sensorValue < 200))
    {
        currentRespState = Exhaling;
        Serial.println("Exhaling");
    }
}

```

The above code will give you the instantaneous respiratory rate, which probably will jump around a bit more than you would like. You probably want to add some dependency on prior history (hysteresis) to smooth it out a bit. One easy way is to put this through a low-pass filter algorithm to get a moving average value for the respiratory rate. That way the rate goes up when you breathe faster and down when you breathe slower but it doesn't instantaneously jump around on every breath. Here's what that might look like:

```
// Global variables
enum respState {
    Inhaling,
    Exhaling
};
unsigned long prevRespTime = 0;
unsigned long currRespTime = 0;
respState currentRespState = Exhaling;
float breathrate = 0;
int movingAvgRespRate = 0;

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

void loop()
{
    //delay(500);
    // don't need to delay because we'll only fire once per inhalation and once per exhalation
    int sensorValue = analogRead(A0);

    if ((sensorValue > 300) && (currentRespState == Exhaling))
    {
        currentRespState = Inhaling;
        prevRespTime = currRespTime;  // save time from last cycle
        currRespTime = millis();

        float period_respiration = currRespTime - prevRespTime;

        if (period_respiration == 0)
            breathrate = 0;
        else
            breathrate = 60000 / period_respiration;

        Serial.print("Inhaling /tResp Rate: ");
        Serial.print(breathrate);

        if (movingAvgRespRate == 0)
            movingAvgRespRate = breathrate;
        else
            movingAvgRespRate = (int) ((0.2 * breathrate) + (0.8 * movingAvgRespRate));

        Serial.print("/tAvg Resp Rate: ");
        Serial.println(movingAvgRespRate);
    }
    else if ((currentRespState == Inhaling) && (sensorValue < 200))
    {
        currentRespState = Exhaling;
        Serial.println("Exhaling");
    }
}

```

This code compiles, but I did not happen to be near an arduino with a sensor, so I didn't run it -- there could be issues, but this should be enough to put you on the right track. Good Luck!
> 4 votes

# Answer
This code is missing 2 critical components. First, with out some form of hysteresis it is unlikely the program will respond in a dependable manner. Second, it would be best if a finite state machine were utilized to assist in the collection of data and calculation of a reparation rate. In this case, 4 states to track exhale, transition from exhale to inhale, inhale & transition from inhale to exhale.
> 1 votes

# Answer
Aside from all the useful code provided, here is some additional input for a relatively accurate flow measurement using thermistors. Sage metering provides a useful overview of the most established modes of operation. You'd need an array of two or more thermistors; by heating the central element and measuring the temperature field displacement induced by the flow using the other thermistors you would get a really accurate reading. Google Scholar has a lot of papers on constant temperature and constant current flow meters.

Also, I suppose you are using some short of tubing where you inhale/exhale; there is a critical length for this tube, where you would want to place your sensors to measure a good, steady flow (this is called laminar flow). You can look up Reynolds number and laminar - turbulent flow in pipes; I can say from experience that after approx. 15cm you would measure well, but have a reading, this is really interesting information on setting up a proper measurement setup.
> 0 votes

---
Tags: arduino-uno
---


title: Functions with string parameters

text:
# Question
Title: Functions with string parameters
Inside my main loop there is this string:

```
String string1;

```

I have a function that will take string1 as parameter, and use it to send this string as SMS.

```
sendSMS(string1);

```

This is the sendSMS() function (without parameters):

```
void sendSMS()
{ sms.beginSMS(remoteNumber);
  sms.print(finalstr);
  sms.endSMS();
  lcd.setCursor(0, 0);
  lcd.print("Message sent!");
  delay(10000);
}

```

My questions are:

1. How do I put the string input parameter in sendSMS?
2. Do I also need to use a function prototype for sendSMS()? (so that it appears three times, 1 in the prototype, 1 in the declaration and one in the call). Or I don't need to use function prototype before the main loop()?

# Answer
1. Just change

```
void sendSMS()

```

to

```
void sendSMS(const String& thisIsAString)

```

You can then access the parameter inside the function with `thisIsAString`.
2. No, you do not need a prototype.
> 11 votes

# Answer
I'd say to never use String again. When code gets bigger and memory usage will be critical you'll hit a dead-end. I know it's more convenient, but give char arrays a shot. Something like:

```
bool sendSMS(int remoteNumber, char *finalstr){
  bool isFinished = 0;
  sms.beginSMS(remoteNumber);
  for (int i=0;i<sizeof(finalstr);i++){
      sms.print(finalstr);
  }
  sms.endSMS();
  lcd.setCursor(0, 0);
  lcd.print("Message sent!");
  delay(10000);
  isFinished = 1;
  return isFinished;
}

```

I changed the function to bool. It means that you can use it inside an if statement, where you would want it completed before continuing with your code.

You will need to allocate memory yourself for the array; declare it like this:

```
char stringArray[33] = {'\0'};

```

Here, I allocate 32 bytes for data and one additional byte for the character that means "end of string" (it's that \0).
> 2 votes

# Answer
You can change

`void sendSMS()`

to

`void sendSMS(String myinputstring)`

you can use myinputstring in your code.
> 0 votes

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


# Question
Title: How do I directly access a memory mapped register of AVR with C
Assume I want to write the following without using `DDRD` or `PORTD`:

```
#include <avr/io.h>
#include <util/delay.h>

int main(void) {
    DDRD = 0xFF;
    PORTD = 0xFF;
}

```

I found this link which includes a list of mapped registers to memory addresses: https://github.com/DarkSector/AVR/blob/master/asm/include/m328Pdef.inc

So I replaced one of the keywords with a pointer:

```
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    DDRD = 0xFF;
    unsigned char *portd = 0x0b;
    *portd = 0xFF;
}

```

But it's not working (my LED isn't turning on with the second code). Why is that?

# Answer
> 11 votes
It's worth exploring how `PORTD` is defined in the actual AVR header file. The relevant file is `iom328p.h`, and it's defined as:

```
#define PORTD   _SFR_IO8(0x0B)

```

`_SFR_IO8` is defined as

```
#define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET)

```

and

```
#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

```

This shows that 0x0b is *not* the address of the `PORTD` register, but its offset from the address `__SFR_OFFSET`, which is 0x20. Indeed, if you look at the ATMEGA328 datasheet, the register summary shows that `PORTD` is at offset 0x2b. So that is the address that you would want to access via a pointer.

Note that this also shows the type of the pointer, if we fully expand the original definition of `PORTD` we get:

```
#define PORTD   _SFR_IO8(0x0B)
#define PORTD _MMIO_BYTE((0x0B) + __SFR_OFFSET)
#define PORTD _MMIO_BYTE((0x0B) + 0x20)
#define PORTD (*(volatile uint8_t *)(0x2B))

```

This syntax takes the integer 0x2B, casts it to type `pointer to volatile uint8_t`, and dereferences that pointer so you can assign to or read from the location the pointer references. The `volatile` qualifier is important because it prevents the compiler from optimizing out accesses to memory. Without it, the compiler may store the value to a register instead, or not store it at all, which would mean your IO port would remain unchanged or appear to report an incorrect value.

To go back to the title of your question, you have asked how to "directly access a memory mapped register in C", well the answer is you do that exactly the way the header file defines for you:

```
(*(volatile uint8_t *)(0x2B) = 0xFF

```

aka

```
PORTD = 0xff

```

There is no more direct way than this. The compiler sees a literal address and writes to it. What you've written is very different (adjusting to use the correct address and type:

```
volatile uint8_t * portd = 0x2b;
 *portd = 0xFF;

```

This allocates a location in memory symbolized by `portd`, which holds the value 0x2B. When you write `*portd = foo`, the MCU has to access the location where `portd` is stored, take the value found there as an address to find the location you actually want to write to. This method requires that you allocate a place in memory to hold `portd` and requires an extra memory access to be able to read or write to the port register. This method is therefore *indirect*.

In reality, if optimization is enabled, the compiler may optimize the pointer away and replace it with the same literal access as in the PORTD case, however this depends on the program structure, and in particular the qualification and scope of the pointer. Limiting the scope of `portd` as much as possible and/or declaring it as `volatile uint8_t * const portd = 0x2b` (which indicates that the pointer's value is constant even if the value *pointed to* is volatile) will increase the likelihood of the pointer being optimized away.

---

The reason the AVR headers define the IO port registers this way is because in addition to the standard load/store instructions that can access the entire data memory address space and take three clock cycles to complete, the IO registers are special, and can also be accessed using IN/OUT instructions, which complete in two cycles. The load/store instructions use the memory address for the IO registers (starting at offset 0x20), whereas the IN/OUT instructions use the IO address, which starts at 0x00, but corresponds to 0x20 in the memory address space. From the datasheet:

So when you access an IO location, the optimizer should recognize that it can issue a more efficient instruction than the standard load/store, and it will replace the load/store to 0x2b with an in/out to 0x0b.

---
Tags: c
---


# Question
Title: Arduino sketch not uploading to Arduino Nano
Port is detected and selected but sketch is not uploading to it. I am getting error:

```
         avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\ACER\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x2c

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

# Answer
> 1 votes
In IDE in the Tools menu, select in submenu Processor the "Atmega 328P (Old Bootloader)" option.

The upload speed 115200 in your console output indicates the you try to upload for new bootloader. The fail to upload could indicate that your Nano has the old bootloader.

---
Tags: arduino-nano
---


# Question
Title: getting SPI SSD1307 to work on Arduino Mega
After some time off, I decided to get back into my project after some help from this topic I started earlier Difference in pinout (types?) Uno/Mega. Unfortunately, even tho I have read multiple times what has been said about the SPI pins on a mega, the displays simply will not work. Both my LED strips and rotary encoder are working, so my code compiles and uploads as it should. The displays are ssd1307 using SPI.

```
Pinout from MEGA to displays
49 > RST for display1/display2/display3
50 > DC for display1/display2/display3
51 > SDA for display1/display2/display3
52 > SCK for display1/display2/display3

33 > CS for display1
34 > CS for display2
35 > CS for display3

```

Here is the code I am trying to use:

```
#include <Adafruit_NeoPixel.h>
#include "HCuOLED.h"
#include "SPI.h"

Adafruit_NeoPixel REVLEDS = Adafruit_NeoPixel(7, 2, NEO_GRB);
Adafruit_NeoPixel DASHLEDS = Adafruit_NeoPixel(3, 3, NEO_GRB);

#define SCK 52
#define SDA 51
#define DC 50
#define RST 49

HCuOLED HCuOLED_5(SSD1307, 33, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_4(SSD1307, 34, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_3(SSD1307, 35, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)

#define s1 6
#define s2 5
#define key 4

int newCounter = 0;
int oldCounter = 0;
int oldState;
int newState;
int rotated = 0;
int keyState = 0;
int keyReset = 0;

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

  REVLEDS.begin();
  REVLEDS.setBrightness(25);

  DASHLEDS.begin();
  DASHLEDS.setBrightness(25);

  pinMode(s1, INPUT);
  pinMode(s2, INPUT);

  oldState = 1;
  newState = oldState;

  HCuOLED_5.Reset();
  pinMode(53, OUTPUT);
}

void loop() {

  newState = digitalRead(s1);
  if(newState != oldState){
    if(digitalRead(s2)!= oldState){
      newCounter ++;
    } else {
      newCounter --;
    }
    if(newCounter == (oldCounter+2) ||newCounter == (oldCounter-2)){
      if(newCounter > oldCounter) rotateRight();
      else rotateLeft();
      oldCounter = newCounter;
    }
  }
  oldState = newState;

  keyState = digitalRead(key);
  //Serial.println(keyState);
  if(keyState == LOW && keyReset == 0){
    onButtonPress();
    keyReset = 1;
  } else if (keyReset == 1 && keyState == HIGH){
    keyReset = 0;
  }

  for(int i = 0; i < 7; i++){
  REVLEDS.setPixelColor(i, 0,255,0);}
  REVLEDS.show();

  for(int i = 0; i < 3; i++){
  DASHLEDS.setPixelColor(i, 0,0,255);}
  DASHLEDS.show();

  //display 5
  HCuOLED_5.SetFont(Terminal_8pt);
  HCuOLED_5.Cursor(44,0);
  HCuOLED_5.Print("Cpt");
  HCuOLED_5.Cursor(20,10);
  HCuOLED_5.Print("Fastlane");
}

void onButtonPress(){
  Serial.println("Pressed button");
}

void rotateLeft(){
  Serial.println("Rotated left");
}

void rotateRight(){
  Serial.println("Rotated right");
}

```

Now the question is, what am I missing? TIA!

# Answer
> 0 votes
The displays do not use SPI MISO pin. It is 12 in Uno and 50 on Mega. On Mega you try to use pin 50 for DC pin of the displays and it creates a conflict with SPI. MISO should be an INPUT and DC is OUTPUT.

# Answer
> 0 votes
Found the problem... after my break, i forgot that the .refresh() command is actually the command that displays something on the screen, while I kept thinking it was to clear the screen. After adding that to my code together with .clearBuffer(), everything works with the following pinout:

```
Pinout from MEGA to displays
48 > RST for display1/display2/display3
49 > DC for display1/display2/display3
51 > SDA for display1/display2/display3
52 > SCK for display1/display2/display3

33 > CS for display1
34 > CS for display2
35 > CS for display3

```

With the following code to show different stuff on screen:

```
#include "HCuOLED.h"
#include "SPI.h"

#define SCK 52
#define SDA 51
#define DC 49
#define RST 48

HCuOLED HCuOLED_5(SH1106, 33, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_4(SH1106, 34, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_3(SH1106, 35, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)

int tCounter = 0;

void setup(){
  HCuOLED_5.Reset();
  //pinMode(53, OUTPUT);
}

void loop() {
  //display 3
  HCuOLED_3.SetFont(Terminal_8pt);
  HCuOLED_3.Cursor(44,0);
  HCuOLED_3.Print("Cpt");
  HCuOLED_3.Cursor(20,10);
  HCuOLED_3.Print("Fastlane");
  HCuOLED_3.SetFont(LCDLarge_24pt);
  HCuOLED_3.Cursor(20,30);
  HCuOLED_3.Print("3 - ");
  HCuOLED_3.Cursor(65,30);
  HCuOLED_3.Print(tCounter);
  HCuOLED_3.Refresh();
  HCuOLED_3.ClearBuffer();

  //display 4
  HCuOLED_4.SetFont(Terminal_8pt);
  HCuOLED_4.Cursor(44,0);
  HCuOLED_4.Print("Cpt");
  HCuOLED_4.Cursor(20,10);
  HCuOLED_4.Print("Fastlane");
  HCuOLED_4.SetFont(LCDLarge_24pt);
  HCuOLED_4.Cursor(20,30);
  HCuOLED_4.Print("4 - ");
  HCuOLED_4.Cursor(65,30);
  HCuOLED_4.Print(tCounter);
  HCuOLED_4.Refresh();
  HCuOLED_4.ClearBuffer();

  //display 5
  HCuOLED_5.SetFont(Terminal_8pt);
  HCuOLED_5.Cursor(44,0);
  HCuOLED_5.Print("Cpt");
  HCuOLED_5.Cursor(20,10);
  HCuOLED_5.Print("Fastlane");
  HCuOLED_5.SetFont(LCDLarge_24pt);
  HCuOLED_5.Cursor(20,30);
  HCuOLED_5.Print("5 - ");
  HCuOLED_5.Cursor(65,30);
  HCuOLED_5.Print(tCounter);
  HCuOLED_5.Refresh();
  HCuOLED_5.ClearBuffer();

  tCounter++;
}

```

---
Tags: arduino-mega, ssd1306
---


title: help with a loop

text:
# Question
Title: help with a loop
I recently got into programing and I'm making an alarm. I cant figure out how to make a buzzer loop. I have two blinking LED's and two fading ones. Now I plan to have sound and it won't work. It only blinks once and stops. I would also like the two fading LED's to fade at different times. I can't figure that out. Here's the code. 8 is the buzzer and red and blue are the fading LED's.

```
int blue = 6;
int red = 9;
int brightness = 0;
int fadeAmount = 500;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(red, OUTPUT);
     pinMode(blue, OUTPUT);
      pinMode(8, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
  delay(200);
  digitalWrite(11, LOW);
  digitalWrite(12, HIGH);
  delay(200);
  digitalWrite(8, LOW);
  digitalWrite(8, HIGH);
  delay(10);

 analogWrite(red, brightness);
  analogWrite(blue, brightness);
   brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 millis();
}

```

# Answer
> 1 votes
Have a look here, on how you can use different peripherals in a non-blocking manner. The following code is from the link:

```
// These variables store the flash pattern
// and the current state of the LED

int ledPin1 =  12;      // the number of the LED pin
int ledState1 = LOW;             // ledState used to set the LED
unsigned long previousMillis1 = 0;        // will store last time LED was updated
long OnTime1 = 250;           // milliseconds of on-time
long OffTime1 = 750;          // milliseconds of off-time

int ledPin2 =  13;      // the number of the LED pin
int ledState2 = LOW;             // ledState used to set the LED
unsigned long previousMillis2 = 0;        // will store last time LED was updated
long OnTime2 = 330;           // milliseconds of on-time
byte brightness = 0;
byte brigthnessInterval = 10;

void setup()
{
  // set the digital pin as output:
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

void loop()
{
  // check to see if it's time to change the state of the LED
  unsigned long currentMillis = millis();

  if((ledState1 == HIGH) && (currentMillis - previousMillis1 >= OnTime1))
  {
    ledState1 = LOW;  // Turn it off
    previousMillis1 = currentMillis;  // Remember the time
    digitalWrite(ledPin1, ledState1);  // Update the actual LED
  }
  else if ((ledState1 == LOW) && (currentMillis - previousMillis1 >= OffTime1))
  {
    ledState1 = HIGH;  // turn it on
    previousMillis1 = currentMillis;   // Remember the time
    digitalWrite(ledPin1, ledState1);     // Update the actual LED
  }

  if(currentMillis - previousMillis2 >= OnTime2)
  {
    previousMillis2 = currentMillis;  // Remember the time
    if (brigthness <= 254) brigthness += brigthnessInterval;
    if (brigthness == 255) brigthness = 0;
    analogWrite(ledPin2, brigthness);
  }
}

```

Here, two LEDs are controlled with different intervals, I changed LED number 2 to fade in with an interval specified with OnTime2; watch out your fade amount though, because analogWrite has 255 levels, and you immediately increased it to 500. You can add as many intervals as you want in the same manner, and perform tasks in pseudoparallel.

# Answer
> 0 votes
try and analyze this alarm sound sketch

```
const byte TONE_PIN = 4;
const int ALARM_BEEP_1 = 4186;
const int ALARM_BEEP_2 = 4699;

const int ALARM_TONE_LENGTH = 200;
const int ALARM_TONE_PAUSE = 800;
const int ALARM_TONE_REPEAT = 6;

void setup()
{
}

void loop()
{
  alarmSound();
}

void alarmSound() {
  static unsigned long next = millis();
  static byte count = 0;
  if (millis() > next) {
    next += ALARM_TONE_LENGTH;
    count++;
    if (count == ALARM_TONE_REPEAT) {
      next += ALARM_TONE_PAUSE;
      count = 0;
    }
    tone(TONE_PIN, (count % 2) ? ALARM_BEEP_1 : ALARM_BEEP_2, ALARM_TONE_LENGTH);
  }
}

```

# Answer
> 0 votes
I suggested the basics in my answer to your previous question - "To fade them out of phase, you'll need a second brightness-variable (and possibly a second fade-amount), and an increment/decrement and limit test for each LED."

To put that more concretely, instead of `brightness`, you'll need a `redBrightness` and a `blueBrightness`, and initialize them to different values.

```
   brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}

```

For instance, initializing them to '0' and '128', respectively, would drive the LEDs 180 degrees out of phase, or one fading up while the other fades down, assuming you use the same `fadeAmount` variable for both. If you use a `redFadeAmount` and `blueFadeAmount`, you can make them fade at different rates, as well.

# Answer
> -1 votes
"I recently got into programing" So start here : https://en.wikipedia.org/wiki/Divide\_and\_conquer\_algorithm

To apply such principle start by finding suitable "blink (SINGLE) LED" in Arduino IDE examples. There is no real need to reinvent the wheel / code when you just starting to learn programming as long as you do not just "cut and paste".

You can blink LED attached to pin 13 without using any additional hardware. Then find an example doing same without using "delay".

Most newcomers have issues with Arduino hidden main function and navigating "loop".

Once you have hang of the loop function you can add multiple "instances" of blinking LED's, and later consolidate these instances into suitable function.

Then use same approach to your buzzer or any other device. Good luck.

---
Tags: led, sound, buzzer, loop
---


# Question
Title: My Arduino Fingerprint Sensor FPM10A is not working with an Arduino Nano with Atmega168 processor
I recently bought this Arduino Fingerprint Sensor FPM10A from Aliexpress. So, when I connected it with my Arduino Nano and uploaded the 'enroll' example and opened the serial monitor. The fingerprint print sensor got detected but when I enter #1 to enroll the fingerprint no output is given on the serial monitor. I think my Arduino Nano just freezes.But other examples such as 'Empty database, it works with no problems. Is this caused by the less powerful Atmega168 microprocessor? If I get a Arduino Uno or an Arduino Nano with an Atmega328P microprocessor will this problem be solved? And I do not think the fingerprint module is defective as other examples worked like a charm. Please see the attached photo above.

# Answer
> 1 votes
Did you buy the arduino board Nano Atmega168 on Aliexpress? Sometimes the cheapest arduino compatible boards are okay, but sometimes they are stripped of decoupling capacitors or the polyfuse is missing (on a uno board). Sometimes they put a Atmega168 on the board, it is a few cents cheaper.

If you buy the cheapest nano compatible board, look at the photo if the quality is reasonable. The newer arduino boards have a ARM Cortex processors. The Atmega328p is still okay for small projects. I suggest to use the Atmega328p as the minimum.
A Arduino nano Atmega328p clone at Aliexpress costs about 2 dollars, so there is no reason to buy an Atmega168.

When the compiler tells you that "Low memory available, stability problems may occur" for the ram, then you can almost be sure that it will not work.

I try to keep about 300 bytes ram available for local variables, stack and the heap. It depends how much memory the libraries require. I also don't use the String objects for the Arduino uno or nano.
For a beginner, you can try to keep at least 500 bytes ram available.

---
Tags: arduino-nano
---


title: EEPROM size limitation issue

text:
# Question
Title: EEPROM size limitation issue
I am creating a test program with Arduino Nano where I can save network and password. Here is my code to start with:

```
void SaveNetwork(String ssid, String pass){
  String com = ssid + "~" + pass;
  const char *array = com.c_str();
  for(int i = 0; i<sizeof(com); i++){
    EEPROM.write(i, array[i]);
  }
  Serial.println("Saved");
  char ar[255] = "";  //test read string.
  for(int i = 0; i<sizeof(com); i++){
    ar[i] = EEPROM.read(i);
  }
  Serial.println(ar);
}

SaveNetwork("Testing", "Network123......");

```

Now I print ar string which is suppose to return ssid, "~" and password.

BUT what I get is "Testin" instead of "Testing~Network123......".

Is there is a limitation for EEPROM size? If so, how can I expand the capacity, should I use a memory chip, or what is the code I should use to resolve this?

# Answer
The problem is with `sizeof(com)` in your loops. `sizeof()` is for C arrays, not string objects. If you print it, it will report 6, which is not the length of the array. For string objects you should use `com.length()` instead. Then the output becomes

> Saved
>
> Testing~Network123......

P.S. The EEPROM can store 1024 bytes on ATmega328P-based boards (I believe that's what most Arduino Nanos use (clones included).
> 3 votes

---
Tags: arduino-nano, eeprom
---


title: CH340 max serial speed

text:
# Question
Title: CH340 max serial speed
With an Arduino-like board using a CH340 USB Serial chip, I'd like to send text lines as fast as possible to a Raspberry Pi through USB using the *Serial.println()* function. The problem is that when I set the serial speed to values above 230 400 with the *Serial.begin(speed)* function, the Arduino console crashes and the C program on the Rapsberry Pi displays garbage in its console, even though I set the same serial speed.

Short examples :

```
Serial.begin(230400);
Serial.println("Test !"); // Works fine.

Serial.begin(250000);     // Or any speed above 250 000.
Serial.println("Test !"); // Doesn't work at all.

```

This answered question states that 2 Mbauds is possible, so I'm a bit lost.

The Arduino IDE console offers various speed from 300 to 2 000 000 bauds, so why don't speeds above 230 400 work ?

# Answer
CHG340 supports common baud rates: 50, 75, 100, 110, 134.5, 150, 300, 600, 900, 1200, 1800, 2400, 3600, 4800, 9600, 14400, 19200, 28800, 33600, 38400, 56000, 57600, 76800, 115200, 128000, 153600, 230400, 460800, 921600, 1500000, 2000000 baud.

**250 000 baud** isn't supported by that IC.

The Baud steps is either 200% or 150% of the previous value (There is exceptions).

**Tested and working Baud rates.**

I used putty as serial monitor since the built in monitor didn't have all baud rates preprogrammed.

**SpeedTest.ino**

```
// Serial port Baudrates:
// const int Speed = 115200;
// const int Speed = 128000;
// const int Speed = 153600;
// const int Speed = 230400;
// const int Speed = 460800;
// const int Speed = 921600;
// const int Speed = 1500000;
const int Speed = 2000000;

void setup() {
  // Initialize serial:
  Serial.begin(Speed);

  // Initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  Serial.print("Speed :  ");
  Serial.println(Speed);
}

```
> 8 votes

# Answer
There may just be a workaround to allow this adapter to operate at 250000 baud (at least in the Raspberry Pi). The author of this article: http://dmxpi.blogspot.com/2014/04/dmx-on-raspberry-pi-start-here.html has modified the linux driver and claims it works. I hope this helps.
> -1 votes

---
Tags: serial, usb, clones
---


title: Need to cycle through LED brightness

text:
# Question
Title: Need to cycle through LED brightness
So this is pretty much explanatory. I am new to arduino, and i am learning the best i can. I need to sketch a code in which will cycle through 5 different brightness settings of an led. One push will cycle through the five, another push of the button will turn the led off, and another push will restart the cycle.

```
const int led =11;
const int BUTTON = 7;
boolean lastButton = LOW;
boolean currentButton = LOW;
int ledLevel = 0;

void setup()
{
  pinMode(led,OUTPUT);
  pinMode(BUTTON,INPUT);
}
boolean debounce(boolean last)
{
  boolean current = digitalRead(BUTTON);
  if (last != current)
{
  delay(5);
  current = digitalRead(BUTTON);
}
return current;
}

void loop()
{
  currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    ledLevel = ledLevel + 51;
  }
  lastButton = currentButton;
  if (ledLevel > 255) ledLevel = 0;
  analogWrite(led, ledLevel);
  analogWrite(led, ledLevel + 51);
  delay(200);
  analogWrite(led, ledLevel + 102);
  delay(200);
  analogWrite(led, ledLevel + 153);
  delay(200);
  analogWrite(led, ledLevel + 204);
  delay(200);
  analogWrite(led, ledLevel + 255);
}

```

The code above turns the led on and cycles brightness, like it should it however for some reason it does disable the button. Take the analogWrites out except for the first one, and the button will cycle the led. any suggestions on what i could do? Im very new at this.

# Answer
> 0 votes
Something like this, with variable declarations & setup() left to you. All time elements are of type unsigned long.

```
pwmValue {} = [51, 102, 153, 204, 255];

void loop(){
  if (digitalRead(startButton) == LOW && pwmCycling == 0){
    // start button pressed, and not already running
    startTime = millis(); // capture the time of the button press
    pwmCycling = 1; // keep track of the running state. 0 for off, 1 for on.
    }
  if (pwmCycling == 1){ // cycling is running
    // this is where the blink without delay is:
    currentTime = millis(); // capture the time now
    elapsedTime = currentTime - startTime; // see how much time went by
    if (elapsedTime >= eventDuration){  // enough?  start next brightness
      currentTime = startTime; // set up for next event time
      brightNumber = brightNumber +1; // keep track of brightness level
      if (brightNumber >= 5){ brightNumber = 0; } // reset after the last level
      analogWrite (ledPin, pwmValue[brightNumber]); // write the LED pin
      }
    }
  if (digitalRead(startButton) == LOW && pwmCycling == 1){
    // start button pressed while LEDs are cycling, stop them
    pwmCycling = 0;
    analogWrite (ledPin, 0);
    brightNumner = 4; //reset the brightness level to the end
    delay (100); // little bit of dumb debounce delay
    }
}

```

# Answer
> -1 votes
All the delay(200) lines keep the sketch from reading button presses.

You need to learn about Blink Without Delay so your sketch can do things other than sit there blindly letting time pass.

---
Tags: arduino-uno
---


# Question
Title: Connecting two Arduinos via I2C while I2C Pins A4/A5 are already in use
I have the following problem: Since the BH1750 Sensor only supports two different I2C adresses, but i need to use 6 of those sensors, i wanna use 3 arduinos, 2 nanos, 1 uno and send the data from the nanos to the uno. Problem is that the I2C bus is already in use and while trying to send data, it does not work properly. Is this even possible? When trying it out, i can't get anything correct

---

Update:

That's what i tried now:

Results i get are still not correct

```
#include <Wire.h>
#include <BH1750.h>

// This code will feature the use of 6 gy 30 light sensors

BH1750 active_sensor(0x23); // We will use this adress for stating the active sensor
BH1750 inactive_sensor(0x5C);

void setup(){

  Serial.begin(9600);

  // Setting the input pins for controling the addr pins of the modules
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(12, OUTPUT);
    pinMode(13, OUTPUT);

    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    digitalWrite(10, LOW);
    digitalWrite(11, LOW);
    digitalWrite(12, LOW);
    digitalWrite(13, LOW);

  // Initialize the i2c bus
  Wire.begin();

 // Here we will set the mode of the module
  if (active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) {
    Serial.println(F("BH1750 Advanced begin"));
  }
  else {
    Serial.println(F("Error initialising BH1750"));
    Serial.println("Problem on 1");
  }
}

void loop() {
  get_values();

}

void get_values(){
  int i;
  Serial.println("----");
  for(i = 8; i<=13;i++){
    digitalWrite(i,HIGH);
    delay(50);
    int lux = 0;
    lux = active_sensor.readLightLevel();
    Serial.println(lux);
    delay(50);
    digitalWrite(i,LOW);
    delay(150);
  }
}

```

# Answer
> 2 votes
Use the ADDR pin as a chip select. Pull both pins high normally. When you want to talk to one, pull the ADDR pin low and use the ADDR = 0 address to talk to the selected device. Then you can have all 6 connected to one Arduino.

# Answer
> 2 votes
You can make the nanos use software I2C to isolate those I2C buses from the UNO's I2C bus. Then have the UNO be the master on it's own bus, requesting the data when needed.

Though if you go for software I2C you can make the UNO do all the I2C work, assuming you have enough free pins for that.

Another option is to get a proper I2C multiplexer like the TCA9548A.

---
Tags: arduino-uno, sensors, arduino-nano, i2c
---


# Question
Title: The reason for signal not going back to LOW
I have written a simple Arduino sketch, that shall produce a clock signal.

Here is the code:

```
void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(8,HIGH);
  delayMicroseconds(500);
  digitalWrite(8,LOW);
  delayMicroseconds(500);
}

```

Namely the pin 8 of Arduino Uno is periodicaly set to HIGH and LOW.

The output that I receive, for three different frequencies, is:

My question is: Why is falling edge not as sharp as rising edge? As can be noted, for high frequencies the signal wouldn't go to LOW after all.

# Answer
The pin is not configured as OUTPUT.

By default, all of the GPIO pins on pretty much any microcontroller are configured as inputs following reset. This prevents the chip from "fighting" an external device that might be driving any of those pins before the firmware has had a chance to configure the GPIO correctly.

On the MCU used on the Arduino, the output latch controls the state of an internal pullup resistor when the pin is configured as an input. Your code was simply enabling and disabling this resistor. When you set the pin low, it makes the pin open-circuit, and you see a slow decay of voltage through your oscilloscope probe.
> 4 votes

---
Tags: pins
---


# Question
Title: Increase PWM bit resolution on only one timer 2 output
I am new here and I know that this basic question has been answered in the past but what I want to know is this. And I cant figure out how to add this to one of those threads. Sorry in advance if I am posting this wrong.

Arduino Uno

I have a motor driven PWM off output 10 and output 9 is used for the display, can I change the resolution of output 10 only to 16 bit? or will both outputs need to be used as PWM when changing timer 2 to 16 bit? All of the coding samples I see are for changing both outputs.

# Answer
> 1 votes
As long as you don't use PWM (i.e. analogWrite) on pin 9, any changes made to timer1 won't affect pin 9.

It will change both outputs, as both use the same (single) timer.

But you can use code to convert a 8-bit PWM value to a 16-bit value by simply multiplying the 8-bit value by 256.

---
Tags: pwm
---


# Question
Title: "char inChar = (char)Serial.read();" why is the "char" in brackets? and what is it called
I am sure this is a very simple answer, but I don't know to look it up on google

In the example "SerialEvent" in the arduino IDE (v1.8.7), there is the following function

```
    void serialEvent() {
        while (Serial.available()) {
           // get the new byte:
           char inChar = (char)Serial.read();
           // add it to the inputString:
           inputString += inChar;
           // if the incoming character is a newline, set a flag so the main loop can
           // do something about it:
           if (inChar == '\n') {
               stringComplete = true;
           }
        }
     }

```

On the third line "**char inChar = (char)Serial.read();**" the (char) is given in brackets before the serial read. Why is this? and more specifically how is called ?

# Answer
It is called type casting and will convert one type to another. The return type of `Serial.read()` is `int`, because it will return `-1`, when you try to read without any bytes being available. The casting with `(char)` will drop the high byte of the (2-byte long) integer, leaving only the lower byte. This byte will contain the actual read data, in which you are interested here.

Casting is a complex thing, because there can be different ways to convert different types (for example maintaining the bit-content vs. maintaining the decimal value). The casting, that you are seeing here, should only be done, if you really know, what you are doing. The bits will not be changed to maintain the correct value, but the bit-content will be preserved, unless the new type is smaller than the former. In this case the rest is lost. Also, if you try to cast a `float` value to an `int` value with this, you will get a totally different decimal value out of it, because the numbers are encoded in the bits in a totally different way. Here it is known to be OK, especially, if you are checking for available bytes before reading with `Serial.available()`, because the library puts the ASCII data in the lower byte.

For further explanations you should consult C/C++ guides.
> 4 votes

---
Tags: serial
---


title: Arduino Convert std:string to String

text:
# Question
Title: Arduino Convert std:string to String
I'm working on BLE project with espressif library. And It returns me founded BLE device.

```
std::string getManufacturerData();
std::string getName();
int         getRSSI();
BLEScan*    getScan();

```

When I want to print device name to serial port

```
BLEAdvertisedDevice founded_dev;
founded_dev=foundDevices.getDevice(0);
Serial.println("Name -> " + founded_dev.getName());

```

It gives me error like this

```
no matching function for call to 'HardwareSerial::println(std::__cxx11::basic_string<char>)'

```

So how can i convert to std:string to String in Arduino?

# Answer
Don't. Instead just access the underlying C string:

```
Serial.print(F("Name -> "));
Serial.println(founded_dev.getName().c_str());

```
> 11 votes

---
Tags: serial, c++, string
---


# Question
Title: Using Modbus-RTU with Arduino and temperature controller
I'm trying to connect with a 4 channel temperature controller using Arduino Modbus Library.

This is a part of my temperature controller datasheet. It has register for read PV of each channel.

I have studied example code of the library and now i'm trying to read PV of each channel.

So, I have modified the example code as below,

```
#include <ModbusMaster.h>

    // instantiate ModbusMaster object
    ModbusMaster node;

    void setup()
    {
      // use Serial (port 0); initialize Modbus communication baud rate
      Serial.begin(19200);

      // communicate with Modbus slave ID 2 over Serial (port 0)
      node.begin(2, Serial);
    }

    void loop()
    {
      static uint32_t i;
      uint8_t j, result;
      uint16_t data[6];

      i++;

      // set word 0 of TX buffer to least-significant word of counter (bits 15..0)
      node.setTransmitBuffer(0, lowWord(i));

      // set word 1 of TX buffer to most-significant word of counter (bits 31..16)
      node.setTransmitBuffer(1, highWord(i));

      // slave: read (4) 16-bit registers starting at register 2 to RX buffer
      result = node.readHoldingRegisters(1, 4);

      // do something with data if read is successful
      if (result == node.ku8MBSuccess)
      {
        for (j = 0; j < 4; j++)
        {
          data[j] = node.getResponseBuffer(j);
        }
      }

    }

```

My questions are, Explain below lines in the code

```
          // set word 0 of TX buffer to least-significant word of counter (bits 15..0)
      node.setTransmitBuffer(0, lowWord(i));

      // set word 1 of TX buffer to most-significant word of counter (bits 31..16)
      node.setTransmitBuffer(1, highWord(i));

```

I didn't pass any request to slave, So, can I get the 4 PV value like this? If not, please explain how can I do it.

# Answer
> 1 votes
The setTransmitBuffer calls are for writeMultipleRegisters, which you removed from the example.

The first parameter of the readHoldingRegisters is the address of the register. The second parameter is the count of registers to read.

Your sketch doesn't show the retrieved data. You have no indication of success or fail.

---
Tags: arduino-uno, temperature-sensor, rs485, modbus
---


title: rotary encoder spamming output

text:
# Question
Title: rotary encoder spamming output
im building my second arduino project. Im very new to this all so I could certainly use some help fixing everything.
Im trying to make a controller for a pc port of an arcade game. It uses two rotary encoders, something I never heard about before going into this project
I had found some code on github that works perfectly in my case, but the code has the rotary encoders move the mouse. something that dosent work for the games controls unfortunately (i tried)
so i attempted to change them and now they do spit out text like i need them but when i rotate them instead of getting the needed out put of

```
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

```

i get something more along the lines of

```
babababababababababababababababbabb

```

like if im turning the knob both ways at the same time when im just turning it one direction.

heres the code im working on

```
/*
* By Daniel Tam (daniel@danieltam.net)
============ NOTES ============
This will create a SDVX Controller using an Arduino Leonardo.
You will hook up one wire of the button to the Arduino pin and the other to Arduino's ground. When pushed, the button should go to ground.
You will need to download the encoder library and use it in your project for this to work (ww.circuitsathome.com/mcu/reading-rotary-encoder-on-arduino)
===============================
*/

// buttons
#include <Mouse.h>
#include <Keyboard.h>
#define BT_A 2
#define BT_B 3
#define BT_C 4
#define BT_D 5
#define FX_L 6
#define FX_R 7
#define BT_ST 8

// encoders
#include <Encoder.h>
Encoder enc1(15, 14);
Encoder enc2(16, 10);
float knob1 = 0;
float knob2 = 0;
float old_knob1 = 0;
float old_knob2 = 0;

void setup()
{
  // set pins to read, and output high
  // when the pins read low, we know that the buttons have went to ground (aka, pushed down)
  pinMode(BT_A, INPUT);
  pinMode(BT_B, INPUT);
  pinMode(BT_C, INPUT);
  pinMode(BT_D, INPUT);
  pinMode(FX_L, INPUT);
  pinMode(FX_R, INPUT);
  pinMode(BT_ST, INPUT);

  digitalWrite(BT_A, HIGH);
  digitalWrite(BT_B, HIGH);
  digitalWrite(BT_C, HIGH);
  digitalWrite(BT_D, HIGH);
  digitalWrite(FX_L, HIGH);
  digitalWrite(FX_R, HIGH);
  digitalWrite(BT_ST, HIGH);

  Mouse.begin();
  Keyboard.begin();
}

void loop()
{
  // read encoders
  knob1 =  (float)(enc1.read());
  knob2 = (float)enc2.read();

  if(knob1 != old_knob1)
  {
    // if there's a difference in encoder movement from last pass, move the mouse
    if(knob1 < old_knob1)
    {
     // Mouse.move(0, -5);
      Keyboard.press('a');
      delay(100);
      Keyboard.release('a');
    }
    else
    {
    //  Mouse.move(0, 5);
      Keyboard.press('b');
      delay(100);
      Keyboard.release('b');
    }

  // we count the difference in the encoders, but we must not go over arduino's int limit
    if(knob1 < -255)
    {
      enc1.write(0);
      old_knob1 = 0;
    }
    else if (knob1 > 255)
    {
      enc1.write(0);
      old_knob1 = 0;
    }
    else
    {
      old_knob1 = knob1;
    }
  }

  if(knob2 != old_knob2)
  {
    if(knob2 > old_knob2)
    {
     // Mouse.move(-5, 0);
      Keyboard.press('c');
    }
    else
    {
     // Mouse.move(5, 0);
      Keyboard.press('d');
    }

    if(knob2 < -255)
    {
      enc2.write(0);
      old_knob2 = 0;
    }
    else if(knob2 > 255)
    {
      enc2.write(0);
      old_knob2 = 0;
    }
    else
    {
      old_knob2 = knob2;
    }
  }

  // read the buttons for low, if it's low, output a keyboard press
  if(digitalRead(BT_A) == LOW)
  {
    Keyboard.press('f');
  }
  else
  {
    Keyboard.release('f');
  }

  if(digitalRead(BT_B) == LOW)
  {
    Keyboard.press('b');
  }
  else
  {
    Keyboard.release('b');
  }

  if(digitalRead(BT_C) == LOW)
  {
    Keyboard.press('c');
  }
  else
  {
    Keyboard.release('c');
  }

  if(digitalRead(BT_D) == LOW)
  {
    Keyboard.press('d');
  }
  else
  {
    Keyboard.release('d');
  }

  if(digitalRead(FX_L) == LOW)
  {
    Keyboard.press('z');
  }
  else
  {
    Keyboard.release('z');
  }

  if(digitalRead(FX_R) == LOW)
  {
    Keyboard.press('x');
  }
  else
  {
    Keyboard.release('x');
  }

  if(digitalRead(BT_ST) == LOW)
  {
    Keyboard.press('n');
  }
  else
  {
    Keyboard.release('n');
  }
}

```

# Answer
Your aren't using the recommended pins to attach the encoders. Because of this the library isn't using interrupts, but depends on you calling `encX.read()` often enough, to not miss any changes. This, combined with the 100ms delay in your code, will almost guarantee that you will miss some changes, making the library think you are rotating the other way around.

Change the pins to 0, 1, 2, 3 (or at least one of those for each encoder).

Otherwise lower the delay to for example 1ms. I couldn't find whether this delay is even necessary, or how long it needs to be, so you'd have to experiment a bit, and see what works.

Lastly; why are you using `float` to store the position? Try using `long` instead, as that's the type enc.read() returns.
> 0 votes

---
Tags: arduino-pro-micro, rotary-encoder
---


# Question
Title: Krida 4 ch ac dimmer triac fails to initialize from an Arduino
None of my channels initialize. I suspect a driver issue, but I have tried 2 different libraries.

I have this device:

Krida 4 channel

connected exactly like:

```
GND - > GND
VCC -> 5V
SYNC -> DIGITAL.3
CH1 -> DIGITAL.7

```

Libraries attempted:

https://code.google.com/archive/p/arduino-timerone/downloads

and the stock Arduino \<TimerOne.h\> from libraries manager

I tried all the different code samples but here is the most recent. Code sample:

```
#include <TimerOne.h>

unsigned char channel_1 = 7;    // Output to Opto Triac pin, channel 1
unsigned char channel_2 = 6;    // Output to Opto Triac pin, channel 2
unsigned char channel_3 = 5;    // Output to Opto Triac pin, channel 3
unsigned char channel_4 = 4;    // Output to Opto Triac pin, channel 4
unsigned char CH1, CH2, CH3, CH4;
unsigned char i=0;
unsigned char delay_time=25;     // delay ms or flashing SPEED
unsigned char clock_tick;        // variable for Timer1
unsigned char CHANNEL_SELECT;    // variable for channel select

unsigned char CH[]={CH1,CH2,CH3,CH4};

unsigned char dim_level[]={5,8,10,12,15,18,20,25,30,35,45,50,55,60,65,70,75,80,82,85,88,92,95};   // don't use this massive for 60Hz
                                                                                // create new massive for 60Hz
void setup() {

  pinMode(channel_1, OUTPUT);// Set AC Load pin as output
  pinMode(channel_2, OUTPUT);// Set AC Load pin as output
  pinMode(channel_3, OUTPUT);// Set AC Load pin as output
  pinMode(channel_4, OUTPUT);// Set AC Load pin as output
  attachInterrupt(1, zero_crosss_int, RISING);
  Timer1.initialize(100); // set a timer of length 100 microseconds for 50Hz or 83 microseconds for 60Hz;
  Timer1.attachInterrupt( timerIsr ); // attach the service routine here

}

void timerIsr()
{
    clock_tick++;

      if (CH[0]==clock_tick)
    {
      digitalWrite(channel_1, HIGH);   // triac firing
      delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
      digitalWrite(channel_1, LOW);    // triac Off
    }

      if (CH[1]==clock_tick)
    {
      digitalWrite(channel_2, HIGH);   // triac firing
      delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
      digitalWrite(channel_2, LOW);    // triac Off
    }

      if (CH[2]==clock_tick)
    {
      digitalWrite(channel_3, HIGH);   // triac firing
      delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
      digitalWrite(channel_3, LOW);    // triac Off
    }

      if (CH[3]==clock_tick)
    {
      digitalWrite(channel_4, HIGH);   // triac firing
      delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
      digitalWrite(channel_4, LOW);    // triac Off
    }
}

void zero_crosss_int()  // function to be fired at the zero crossing to dim the light
{
  // Every zerocrossing interrupt: For 50Hz (1/2 Cycle) => 10ms  ; For 60Hz (1/2 Cycle) => 8.33ms
  // 10ms=10000us , 8.33ms=8330us

    clock_tick=0;
}

void loop() {

for (CHANNEL_SELECT=0;CHANNEL_SELECT<4;CHANNEL_SELECT++)  // fade up
 {
  for (i=22;i>1;i--)
  {
    CH[CHANNEL_SELECT]=dim_level[i];
    delay(delay_time);
  }
 }

delay(2000);

for (CHANNEL_SELECT=0;CHANNEL_SELECT<4;CHANNEL_SELECT++)  // fade down
 {
  for (i=0;i<22;i++)
  {
    CH[CHANNEL_SELECT]=dim_level[i];
    delay(delay_time);
  }
 }
delay(1000);

}

```

The code uploads error free to one of the many Arduino Nanos (I tried fresh hardware) that I have.

I cannot establish continuity with my load input channel to any of the load output channels. It is though D7 never never does its job and flip the channel open. Nor can I get any continuity on any of the other channels.

The code is supposed to cycling through all of them but no current ever hits any of the 'load' on any of my channels (Chan 1-4).

Deeper inspection of the Arduino with a voltage meter shows that I am getting reverse polarity on my d7 pin. actually, d7 - d4 all have what appear to be incorrect cycles (reverse polarity) on them. These are all the pins that are supposed to be turning on channels. This does not look correct to me at all.

I suspect driver but I cannot find any other libraries to try that look sane.

How do I initialize my d7 Arduino pin correctly to bring my Krida 4 chan triac Load channel live?

or, did I miss something exceptionally ignorant? I am not experienced with this particular module.

photos:

# Answer
> 1 votes
First of all you should test if the SYNC interrupt is working, like turning on one LED or something you can debug. You switch on the mains AC and then you should detect this zero cross interrupt. If not, then maybe you configured an interrupt event on wrong pin.

Further, making do-while loops in interrupt routine is a no go. Your timeISR turns on one triac, then loops for 10us and turns the triac off. Well not so good implementation. You could skip delay, and turn off after another timeISR by making this ISR at 10us instead.

```
void timerIsr()  //10us
{
    clock_tick++;
    digitalWrite(channel_1, LOW);    // triac Off
    digitalWrite(channel_2, LOW);    // triac Off
    .....
    if (CH[0]==clock_tick)
      {
        digitalWrite(channel_1, HIGH);   // triac firing
      }

```

---
Tags: arduino-nano
---


title: Frequent ON OFF in SSR

text:
# Question
Title: Frequent ON OFF in SSR
I am working on a project on Arduino OLED MAX6675 thermocouple and SSR for my oven. My problem is when my SSR goes in LOW or HIGH state it turn ON and OFF several times before going to permanent HIGH or LOW state. This make my load(Heater) on and off many times. Since the temperature crosses the set-point to change the output state, the process temperature will be cycling rapidly, going from below set-point to above, and back below. This frequent ON OFF will damage my SSR and heater. My Question. Is there any hardware or software solution. To reduce the frequency of ON OFF . I can’t increase the delay() time because it make my button input slow. My codes are below.

```
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include "max6675.h"

//oled
//oled i2c addresss
#define OLED_ADDR 0x3C
Adafruit_SSD1306 display(-1);
// 128 x 64 pixel display
#define SSD1306_LCDHEIGHT 64

//MAX6675
//Pin initialization
int so = 2;
int cs = 3;
int sck = 4;
MAX6675 thermocouple(sck, cs, so);
float current_temp;
int set_temp;
int const h_temp = 2;

//Button
int button_up = 7;
int button_down = 8;
int button_upv;
int button_downv;

//SSR
int ssr_u = 10;
int ssr_d = 12;

void setup() {
    Wire.begin();
    delay(1000);

    // initialize and clear display
    display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(8, 20);
    display.println("Welcome..");
    display.display();
    display.clearDisplay();
    delay(1000);

    //Button
    pinMode(button_up, INPUT);
    pinMode(button_down, INPUT);
    set_temp = 20;
    pinMode(ssr_u, OUTPUT);
    pinMode(ssr_d, OUTPUT);
}

void loop() {
    current_temp = thermocouple.readCelsius();
    delay(100);
    button_upv = digitalRead(button_up);
    button_downv = digitalRead(button_down);

    //button
    if (button_upv == HIGH && set_temp < 180) {
        set_temp = set_temp + 5;
    }
    if (button_downv == HIGH && set_temp > 20) {
        set_temp = set_temp - 5;
    }

    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(5, 10);
    display.println(current_temp);
    display.setCursor(5, 30);
    display.println(set_temp);

    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(30, 40);
    if (button_upv == HIGH) {
        display.println("Up");
    }
    if (button_downv == HIGH) {
        display.println("Down");
    }
    display.display();

    //SSR
    if (current_temp < set_temp - h_temp) {
        digitalWrite(ssr_u, HIGH);
        digitalWrite(ssr_d, HIGH);
        delay(500);
    }
    if else(current_temp > set_temp + h_temp) {
        digitalWrite(ssr_u, LOW);
        digitalWrite(ssr_d, LOW);
        delay(500);
    }
}

```

Thanks in advance for help

# Answer
> 7 votes
You need to implement hysteresis. Set two temperature points around set\_temp. One a little higher to be a limit for turning the heater off and a one a little lower then set\_temp to turn the heater on.

You only need to change your if else condition a little

```
if (current_temp < set_temp - HYST_VALUE) {
  digitalWrite(ssr_u, HIGH);
} else if (current_temp > set_temp + HYST_VALUE) {
  digitalWrite(ssr_u, LOW);
}

```

you could start with

```
int const HYST_VALUE = 1;

```

---
Tags: relay, temperature-sensor, display, pid
---


title: ESP 12 unusable pins

text:
# Question
Title: ESP 12 unusable pins
The ESP 12 board has 22 pins

Are all of them usable?

I understand that there is an external flash memory that is accessed through SPI, but I'm not sure what the impact on the pins is.

And if it is so, then why are the pins available?

Is there a sort of a decoder board that receive as an input, let's say 3 SPIOs and outputs 8 GPIOs?

Is there a way to obtain more GPIO pins?

# Answer
> 4 votes
The flash memory is connected to io 6 to io 11 if it is connected in QIO mode. DIO mode lets two of the pins free. According to Arduino core reference the two pins are 9 and 11. The flash pins are labeled SD and most of them are the first SPI interface of the esp8266. You can't use this SPI pins as digital pins, but supposedly you can connect another SPI device.

Some of the esp8266 'free' pins have some restrictions. Boot configuration pins io 0, io 2 and io 15 need to have some state at boot. io2 not LOW, io 15 LOW and with io 0 flashing mode is activated. The A0 is ADC only pin. And you can't count power, EN, Reset and ground as 'pins'.

You can use a multiplexer or an I2C expansion board to get more pins.

---
Tags: esp8266, pins
---


# Question
Title: DHT11 data in Arduino UNO to Firebase through ESP8266
Hello Good Day to Everyone. I have a project where I need to send DHT11 sensor data to a Firebase database using both Arduino UNO and Esp8266 esp-01 wifi module. Both of them must work together to send the data.

Arduino Code:

```
#include <dht.h>

dht DHT;

#define DHT11_PIN 7

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

}

void loop() {
 // put your main code here, to run repeatedly:
int chk = DHT.read11(DHT11_PIN);
Serial.print("Temperature = ");
Serial.println(DHT.temperature);
Serial.print("Humidity = ");
Serial.println(DHT.humidity);
delay(1000);

}

```

My arduino code is working fine. Now comes the part where I need to program the ESP8266 which I am really confused how to pass the data to the wifi module and send it to firebase. I tried to code some and this is my

ESP8266 Code:

```
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include <DHT.h>

#define FIREBASE_HOST "test.firebaseio.com"
#define FIREBASE_AUTH "authcode"

#define WIFI_SSID "mywifi"
#define WIFI_PASSWORD "12345"

#define DHTTYPE DHT11
#define DHTPIN  7

DHT dht(DHTPIN, DHTTYPE);
float temp_f;
unsigned long previousMillis = 0;
const long interval = 2300;

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

WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
 Serial.println();
 Serial.print("connected: ");
 Serial.println(WiFi.localIP());

Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

 }

void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
delay(50);
Firebase.setFloat("temp",t);
Firebase.setFloat("hum",h);
delay(1000);
}

```

I don't want my esp8266 to go stand alone. I wanted the data to come from the arduino but somehow I don't know how to receive the data from the arduino in the esp8266.

I hope someone can enlighten me.. thank you

# Answer
> 1 votes
First of all, FirebaseArduino.h library is for ESP8266 itself and not for Arduino UNO. The code you have written will not work as you are giving instructions like `Firebase.setFloat("temp",t);` to UNO. It will not compile. What you should do is set ESP8266-01 as your primary board and let the UNO transmit the data by software serial. ESP8266-01 will capture that data and transmit it over the Internet. YOU CAN'T USE FirebaseArduino.h FOR ARDUINO UNO! It is for the ESP8266. All YouTube videos will show you how to code for NodeMCU esp8266-12E. Do that for ESP-01 and communicate with Arduino for data (converting data calculated to string will help to reduce problems). Get data in form of string from UNO and transmit it using ESP-01!

If you want I can share all video list that I found useful!

---
Tags: arduino-uno, esp8266, temperature-sensor, code-review
---


title: Arduino on Windows vs Ubuntu

text:
# Question
Title: Arduino on Windows vs Ubuntu
I have some code that works fine on Windows but is giving me errors on Ubuntu. I noticed that while Windows is running the code using avr-gcc, Ubuntu is trying to make it run using avr-g++. Any functions not defined within void setup() comes up as "was not declared in this scope". Is there a way to force it to use avr-gcc ?

# Answer
In my case, i would tell you compile/upload your sketch Arduino on Ubuntu 17.10 like my owned.

I have

* Wemos D1 MINI Board based ESP8266 chip.
* Define ttyUSB0 port like my Owned.

Before upload your sketch, you need Arduino Package for Ubuntu in Arduino Official Pages or if you have Arduino Package on your Aptitude Source list / PPA Repository of Arduino with following `sudo apt-get install -y arduino`. that's same to me.

After your Arduino Package installed, try to following commnand :

```
cd /path/installation/package/ //for change directory to Arduino Package

ARDUINO-DIR(pwd) //for make environment of Arduino directory

cd $HOME/Arduino/sketch/ //for change directory to your Arduino sketch

ls -l //for list all items in your folder

$ARDUINO-DIR/arduino --verify sketch.ino --board (board) --port (port) --verbose //for compile your sketch

$ARDUINO-DIR/arduino --upload sketch.ino --board (board) --port (port) --verbose //for upload your sketch

```

**NOTE:**

e.g --board esp8266:esp8266:d1\_mini //for WemosD1Mini board or
e.g --board arduino:avr:uno //for ArduinoUNO board.
e.g --port /dev/ttyUSB0 or /dev/ttyACM0 //if your define ttyUSB0 or ttyACM0 port you have.

**See Below** to my verbose log appears a avr-gcc and a avr-g++ automatically called in arduino-builder binary to compile all my library defined.

Hope you can get it.
> 2 votes

---
Tags: ubuntu
---


# Question
Title: Can't add more code to loop() when use server.handleClient
Here's my code

```
void loop() {
  if (analogRead(A0) > 500)
  {
    statuss = true ;
  }
  if (statuss)
  {
    digitalWrite(D7, HIGH);
    if (millis() - lasttime > 500)
    {
      digitalWrite(D8, etat);
      digitalWrite(D6, etat);
      etat = !etat;
      lasttime = millis();
    }
  }
  server.handleClient();
}

```

When I use only `server.handleClient` everything works fine but when I add any type of code to the `loop()` function the server goes down and I can't see the ESP8266 access point.

# Answer
> 4 votes
The problem is analogRead. The esp8266 uses the ADC to evaluate the strength of the WiFi signal. Hard use of analogRead disturbs it and the signal goes down. Use millis() to time analogRead.

```
unsigned int tempSensRead() {

  const unsigned long MEASURE_INTERVAL = 2L * 1000 * 60; // 2 minutes
  static unsigned long lastMeasureMillis;
  static unsigned int lastValue;

  if (millis() - lastMeasureMillis > MEASURE_INTERVAL) {
    lastMeasureMillis = millis();
    lastValue = analogRead(A0);
  }
  return lastValue;
}

```

---
Tags: esp8266, nodemcu
---


title: Using external battery for motor

text:
# Question
Title: Using external battery for motor
i have a little project going on, where i want to connect vibration motors to an arduino. I found this, with example code but also found other tutorials wish use a capacitor for the motor. What is the advantage of using one ?

I am currently planning to power the arduino by a 9V battery, with 3 ultrasound sensors being connected to the 5v output of the arduino. Hence, i believe that i need an external battery for the 2 vibration motors. I think 2x AA's should do the job for some hours, right ?

I also have a question about the rating of the resistor to use at the base of the transistor. How do i calculate the rating that i need ?

# Answer
> 1 votes
a transistor is a current controlled current source. it means that you can control how much current is "Allowed" to flow from emitter to collector, by controlling the minor current flowing through the base of transistor. there is a specific ratio for this two currents for various transistors. (I recommend reading some transistor tutorials). let's say, your motor is drawing 250mA in full speed. you want to "allow" up to 300mA to be available to it.

1. base is connected to 5V through a 2.2 kOhm resistor. The base current is : (5/220) ~= 2.2mA
2. the hfe of your transistor is 150 (it depends on transistor model. It’s written in the datasheet available for every transistor on the market. it's the ratio of base current and emitter collector current mentioned above. You “must” read it first as it’s highly various between transistor models).
3. The current allowed to flow from emitter to collector is 2.2mA * 150 = 330mA which is sufficient for you motor.

note : many simplifications are made to make it easier to understand.

# Answer
> 0 votes
Resistor is there to limit Arduino current out. 220, 270, 330, any should be okay.

Be sure to connect battery - to Arduino Gnd. Transistor will be used to connect motor '-' to Gnd? Be sure to put a diode across it - anode to motor '+', cathode to motor '-' to dissipate current surge generated by the motor when the transistor turns off.

2AAs will last a little while. Better than using 9V for them, that will drain a battery quick.

---
Tags: arduino-nano, motor
---


# Question
Title: Arduino std::map returning random values
I'm working with an arduino UNO. I would like to be able to send it `set` and `get` commands over serial and have it update class data class members accordingly by key value pair. I spoke to users in the cpp room, and they suggested I try using map to map every key to value.

command structure `command:key:value`

ex. `set:key1:20` ex. `get:key2`

I created a class called Uno, assigned all my keys to private data members, and defined set and get functions. However, I am experiencing unintended behavior.

**Unintended behavior** The set function ends up setting `key1` and `key2` to the same value, and the `get` function returns a random integer value that wasn't assigned.

```
  #include <ArduinoSTL.h>
  #include <string.h>
  #include <map>

class Uno{
  //private
    int key1;
    int key2;
    std::map<String, int Uno::*> keys;
  public:
  //Constructor
    Uno(){
      key1 = 0;
      key2 = 0;
      keys["key1"] = &Uno::key1;
      keys["key2"] = &Uno::key2;
    }
    bool setKey(String key, int value){
      if (keys.count(key)) {
          this->*keys[key] = value;
          return true;
      }
      return false;
    }
    int getKey(String key){
      if (keys.count(key)) {
          return this->*keys[key];
      }
    }
};

String inputString = "";      // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete
bool scan = false;            // whether a scan is in progress
Uno myMS;                      // global declaration of Mass Spec Class

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 250 bytes for the inputString:
  inputString.reserve(250);
}

void loop() {
  if (stringComplete) {
    t(inputString); // tokenize and process string

    //RESET STRING
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

void t(String inputString) {
    //get command
    String command = getValue(inputString, ':', 0);

    if(command == "set"){
      // get key, get value
       String key = getValue(inputString, ':', 1);
       int value = (getValue(inputString, ':', 2)).toInt();
       Serial.println(myMS.setKey(key,value));
    }
    else if(command == "get"){
       String key = getValue(inputString, ':', 1);
       int value = myMS.getKey(key);
       Serial.println(value);
    }
    else if(command == "stop"){
       scan = false;
    }
    else if(command == "scan"){
       scan = true;
       while(scan){
//        Serial.println(myMS.scan());
       }
    }
    else{
       Serial.println("not recognized");
    }
}

String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;

  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }
  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

```

**EDIT:** Here is a REPL IT working demo of concept provided by nwp. https://repl.it/repls/AntiqueProductiveMineral

Sample output

```
set:key1:10 ===> 1 (GOOD)
get:key1 ===> 32512

```

# Answer
> 3 votes
You get random values because if the key is not found in getKey, then there is no return statement.

You attach the \n to the key in serialEvent(), then the key for getKey is "key1\n" and it is not found.

```
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    if (inChar == '\n') {
      stringComplete = true;
    } else {
      inputString += inChar;
    }
  }
}

```

If you have CR/LF set in Serial Monitor, then the \r character is send too and the parsed key is "key1\r\n".

There are obsolete things in your code, like the this-\>\* or Uno::. Make the map `std::map<String, int> keys;`, because now you mix pointers and ints.

---
Tags: c++, map
---


# Question
Title: Read sensor data repeatedly after specified time?
I want to read sensor data using *analogRead()* after every 5ms. I have read other answers to similar questions but what I'm confused about is:

* let's say, I made a loop to read sensor data using *analogRead()* at the end of which I write *delay(50)*
* it means it'll take some time to read data(adc) , then it'll wait for 50ms
* time to execute loop isn't same for every iteration so we get the pattern as: *some time for loop execution*, *delay of 50ms*, *some time for next iteration*........and so on **I want to ask if I want arduino to read sensor data exactly every 5ms, what should I do?** Thanks

# Answer
You store the time (`millis()`) of the last measurement. Then wait till 5ms have past since the last measurement. Do your measurement, and update the time.

Something like:

```
unsigned long lastMeasurement = millis();

void loop()
{
  while( (millis()-lastMeasurement)<5 ){/* do nothing */}
  lastMeasurement = lastMeasurement + 5; //or use `lastMeasurement=millis();` depending on whether you want accuracy between measurement, or accuracy over time
  auto measurement = analogRead(A0);
}

```
> 1 votes

# Answer
You do something like this

```
unsigned long timerMesurement = 0;

void loop()
{
  if (millis() - timerMesurement > 5UL) {
    timerMesurement = millis();
    int measurement = analogRead(A0);
  }
}

```
> 0 votes

---
Tags: arduino-mega, programming, interrupt, timers, atmega2560
---