# Question
Title: Arduino Mega Serial2 seems to stop functioning mid-sketch
thanks in advance for the advice.

I've got an Arduino Mega talking to a Cavro XL-3000 pump. After a lot of time I got the arduino successfully controlling the Cavro. However, the big problem I have now is after my Mega sends about a dozen commands, communication breaks down between the two. The Arduino sends commands and gets no response back from the Cavro. I've written code that, when the Arduino gets no response, it tries twice more before terminating the program.

For a while I thought the problem to be pump related. After all, my test code (the vast majority of my code is in a library I created to have the Mega talk to the Cavro pump) simply tells it to move the Cavro between two different positions interminably. But when I reset my arduino, it starts working again. Not when I reset the pump.

Finally, I hooked my logic analyzer up. It turns out that, when I get no response from the pump, it's because no command is reaching the Cavro. I am definitely successfully creating a command packet and sending it using Serial2.write(packet,packet\_length). And though the Arduino is calling these lines of code and thinks data is going out, nothing is actually going out on the TX line. It's like Serial2 gets tired after about a dozen calls and stops shifting out data even though I'm calling Serial2.write.

I'm pretty stumped. I'm clearing the receive buffer after each response, so no overflow there. Each time I send a command I wait until it is fully shifted out before moving on, so no overflow on the write buffer either. If I get no response back from the pump I try two more times. On the last try, I shut down Serial2, begin it again, and wait until it is connected (while(!=Serial2)). But even after I do all this, Serial2.write isn't actually sending out data. My logic analyzer isn't picking anything up.

A simple reset of the Arduino and commands are actually going out again. Logic analyzer picks them up immediately. After about a dozen or so commands (it seems fairly random but never lasts very long), the same thing happens. I swapped out Arduino megas and the same thing occured.

So.

1. It seems to be a code issue (repeatable on multiple arduino megas)
2. It does not seem to concern the pump or the rs232 converter
3. A push of the reset button fixes it temporarily
4. My logic analyzer snoops in between the arduino and rs232 converter.
5. Serial2.write(packet, packet-length) is definitely being called.
6. I have no idea what's happening.

Here is a schematic. Any advice would be appreciated!

Here is my test code:

```
#include <Hydro.h>

Hydro pump;
void setup() {
  Serial.begin(9600);
  Serial2.begin(9600);
  pump.InitComm(0,true,"right");
  Serial.println("Communication initialized");
  delay(5000);
}

void loop() {
//  Serial2.begin(9600);
  //long mil = millis() - 10000;
//while(true){
  //if(millis() > mil + 10000){
    //Serial.println("Sending command...");

    //byte datastuff[10]={0x02, 0x31, 0x31, 0x41, 0x35, 0x30, 0x30, 0x52, 0x03, 0x27};
    //Serial2.write(datastuff,10);
    //Serial.println("Sending command...ONE");
    pump.AbsoluteMove(0,4000);
    delay(10000);
    //Serial.println("Sending command...2");
    pump.AbsoluteMove(0,9000);
    delay(10000);
    //Serial2.write(new byte[10] {0x02, 0x31, 0x31, 0x41, 0x35, 0x30, 0x30, 0x52, 0x03, 0x27}, HEX);
    //mil = millis();
}

```

Here is my library.

```
/*
Hydro.c - Library created for OEM communication with Cavro XL-3000 Pump.

11/23/2016
Written for Mega using Serial2, can we tweaked.
*/

#include "Arduino.h"
#include "Hydro.h"

Hydro::Hydro(void){}

const byte LineSynch = 0xFF;
const byte StartByte = 0x02;
byte seq = 0x31; //confirm this
const byte ETX = 0x03;
const byte EX = 0x52;
int length_total = 0;

//Initializes communication and then sets it to Fine (12000 steps) Control.
void Hydro::InitComm(int addr, boolean fc, String initdir){
    Serial2.begin(9600);
    Initialize(addr,initdir);
    delay(2000);
    FineControl(addr,fc);
}

//Top Level Send Command. First Queries the pump to make sure it's ready for a command.
//If Pump is ready, passes along actual command to MidCommand.
void Hydro::SendCommand(int addr, String command){
    byte status = Query(0);
    while(status==false){
        Serial.println("Query: Stat Error: Wait till Pump No Longer Busy.");
        delay(10000);
        status = Query(0);
    }
    Serial.println("Query: Pump Not Busy.");
    MidCommand(addr, command);
    ReadData(false);

}

//Executes the actual command by calling command.
//If no response received (command != true), tries again twice.
void Hydro::MidCommand(int addr, String command){
    bool response = Command(addr, command);
    if (response == true){}
    else if (response == false){
        //resend
        Serial.println("Command Failed. Resending.");
        bool response2 = Command(addr, command);
        if (response2 == false){
            //shut off
            Serial.println("Second Command Failed.");
            Serial2.end();
            delay(2000);
            Serial2.begin(9600);
            while (!Serial2){
                Serial.println("Waiting for S2 to Connect.");
                delay(1000);
            }
            Serial.println("Connected.");

            bool response3 = Command(addr, command);
            if (response3 == false){
                Serial.println("Final Command Failed.");
                while(true){}
            }
        }
    }
}

//Send a Command.
//Returns True if a response is received from the pump.
bool Hydro::Command(int addr, String command){
    command.concat("R");
    byte address = 0x31+ addr;
    int length = command.length()+1;
    byte dat[length];

    Serial.print("Command: The string command is: ");
    Serial.println(command);
    command.getBytes(dat,length);

    //Serial.println("Data----");
    //for (int i = 0; i < length; i++){
        //Serial.print("i equals: ");
        //Serial.println(i);
        //Serial.println(dat[i], HEX);
    //}
    //Serial.println("----");
    //Serial.print("Dat Length is: ");
    //Serial.println(length);

    //line sync, stx, add, seq, etc, checksum. 6. 6 + (length.data) == length.
    //Decided to ignore Line Sync. Pump seems to have no problem without it. So 5+length.data.
    length_total=5+(length-1);
    byte packet[length_total];
    int p = 0;

    //packet[p++] = LineSynch;
    packet[p++] = StartByte;
    packet[p++] = address;
    packet[p++] = seq;

    for (int i = 0; i<(length-1); i++){
        //Serial.print("i equals: ");
        //Serial.print(i);
        packet[p++] = dat[i];
        //Serial.print(".  Inserting Data: ");
        //Serial.println(dat[i], HEX);
    }

    packet[p++] = ETX;
    byte checksum = StartByte;

    for (int i = 1; i<length_total-1; i++){
        checksum = checksum^packet[i];
    }
    packet[p++] = checksum;
    int x = Serial2.write(packet,length_total);
    Serial.print("bytes written: ");
    Serial.println(x);
    seq++;

    //print out packet to verify.
    Serial.println("Packet----");
    for (int i = 0; i < length_total; i++){
        Serial.println(packet[i], HEX);
    }
    Serial.println("----");

    //Waits for packet to be fully shifted out.
    //Serial.flush could be used instead.
    while(Serial2.availableForWrite() != 63){
        Serial.println("Command: Waiting to finish sending command...");
        delay(1000);
    }
    Serial.println("Command: Finished Sending.");

    unsigned long time = millis();

    //looks for a response from the pump.
    //returns true if received.
    while(Serial2.available()==0){
        Serial.println("Waiting for Response...");
        delay(1000);
        if (millis() > (time+5000)){
            Serial.println("Resend Command.");
            return false;
            }
    }
    Serial.println("Command: Response Received.");
  return true;
}

//Both initialize at half force.
//Init with volve output to Right or Left.
void Hydro::Initialize(int addr, String dir){
    if (dir == "right"){SendCommand(addr,"Z1");}
    else if (dir == "left"){SendCommand(addr,"Y1");}
}

//If Fine Control is True (active), Resolution is 0-12000.
//Else If Fine Control is False (deactivate), 0-3000.
void Hydro::FineControl(int addr, boolean control){
    if (control==true){SendCommand(addr,"N1");}
    else if (control==false){SendCommand(addr,"N0");}
}

//See Fine Control for Integer Values
void Hydro::AbsoluteMove(int addr, int move){
    String mc = "A";
    mc.concat(move);
    SendCommand(addr,mc);
}

void Hydro::Execute(int addr){
    SendCommand(addr,"R");
}

//Sends a Query for Status.
//Returns true if Status byte is 60, ready for command.
bool Hydro::Query(int addr){
    MidCommand(addr,"Q");
    if ((ReadData(true)) != 0x60)return false;
    else return true;

}

//True to print out data, false to not.
//Grabs and returns the Status Byte.
byte Hydro::ReadData(bool print){
    byte status;
    int i=0;
    if (print == false){
        while(Serial2.available()){
            if (i==3){
                status = Serial2.read();
            }
            else Serial2.read();
            i++;
        }
    }

    else if (print == true){
        while(Serial2.available()){
            if (i==3){
                status = Serial2.read();
                Serial.print("i is: ");
                Serial.print(i);
                Serial.print(". Reading (s): ");
                Serial.println(status, HEX);
            }
            else {
                Serial.print("i is: ");
                Serial.print(i);
                Serial.print(". Reading: ");
                Serial.println(Serial2.read(), HEX);
            }

            i++;

        }

    }
    return status;
}

```

# Answer
> 1 votes
I'm not a C++ guy, but I have looked at the code and fail to find where some of the index's are set to the proper values (whatever that is.) Some of it may occur during instantiation, but... Most of these I've seen are index related (out of bounds), so.. As an example, the code sequence of

```
for (int i = 0; i < (length - 1); i++)
    packet[p++] = dat[i];

```

Seems to me, if the bytes (length) of 'dat' is 6 assuming 6 bytes, then the loop will run from 0 to 4. That would seem to lose 2 bytes? Some of the array indexes are difficult to track for their value, not knowing what you were thinking.

My suggestion is

1.) ensure indexes stay within bounds
2.) ensure every function call (related to problem) is checked for it's expected return status
3.) attempt to ascertain the number of operations that occur before failure. This may give you a clue about indexes or lead to discover of other problems.

I don't think you have a hardware problem. Intermittent hardware doesn't do this either. This is a software bug, and it's sounds repeatable. Step three may be useful.

Best of luck :)

# Answer
> 1 votes
Difficult to say, but if your last trace is "Final Command Failed." , you are probably stuck in the following infinite loop.

```
if (response3 == false){
    Serial.println("Final Command Failed.");
    while(true){}
}

```

as @Jack says, you might as well have problems with your bound arrays. You have a lot of "length+1, length-1" scattered everywhere, this is really hard to follow.

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


title: comparing the entries of two arrays

text:
# Question
Title: comparing the entries of two arrays
i am trying to compare the elements of two arrays before the code goes on to the next sequence. The elements of note\[x\] are filled with the note values of a song. and i want to be able to input values from a midi controller into learn\[x\]. how can i compare array learn\[ \] to array note\[ \] before the showsequence(); is incremented?

```
 const int x = 100;
    int note[x];
    int learn[x];
    int largestindex = 0;
    int learnindex=0;
    void showsequence();
    void readsequnce();
    const int PLAY = 1;
    const int TRYAGIN = 2;
    int state=0;

 void loop() {
     if (state == PLAY) {
        showsequence();
        readsequnce();
      }
      else if (state == TRYAGIN) {
        incorrect();
       }
     MIDI.read();
    }
    void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
    learn[learnindex]=pitch;
     learnindex++;
    }

 void showsequence() {
      //Add a new index to the end of the songseq
      SongSeq[largestindex];
      largestindex++;
      //loop through the songseq
      for (int index = 0; index < largestindex; index++) {
        SongSeq[index]();
      }
    }

      void readsequnce() {
      static uint16_t nextkey;
      bool mademistake = false;
       nextkey=0;
       learnindex=0;

       if (array_cmp(learn, note, largestindex, largestindex) == true){
               // do this if they are equal
               lcd.setCursor(16, 2);
        lcd.print("True");
         }else{
               // do this if they are different
               lcd.setCursor(16, 2);
        lcd.print("False");
         }
    }

 boolean array_cmp(int *a, int *b, int len_a, int len_b){
         int n;

         // if their lengths are different, return false
         if (len_a != len_b) return false;

         // test each element to be the same. if not, return false
         for (n=0;n<len_a;n++) if (a[n]!=b[n]) return false;

         //ok, if we have not returned yet, they are equal :)
         return true;
    }

```

# Answer
It depends what sort of comparison you want to do. If you want to see if `note[x] == learn[x]` then that's what you do.

If you want to see if all the notes match all of learn then you'll need to put the comparison in a loop.

```
for (int n = 0; n < MAX_NOTE && note[n] == learn[n]; ++n)
{
    // Empty loop
}

```

If you want to see if the first n notes match the current note and the proceeding n notes then its a bit more complex, but its just a loop.

```
int n = 0;
for (int l = currentPos;
(l > (currentPos - 10)) && (note[n] == learn[l]);
 l--, n++)
{
    // Empty loop
}

```

If it is something else you want, please can you try and describe it in idiot proof terms so I can understand it.
> 1 votes

# Answer
Start by assuming they match. Loop over each element pair, compare them, and set a flag when you find a pair that don't match.

```
bool they_match = true; // assume they match
for ( int i = 0; i < x; i++ ) { // for each note/learn element
  if ( note[i] != learn[i] ) { // check if they don't match
    they_match = false; // they don't mach, so set flag
    break; // stop looping
  }
}

```

At the end `they_match` will be `true` if note\[\] and learn\[\] match, or `false` if they don't.

I would suggest you learn how control structures work. https://www.cs.fsu.edu/~myers/c++/notes/control1.html https://www.cs.fsu.edu/~myers/c++/notes/control2.html
> 1 votes

---
Tags: arduino-mega, programming, array
---


title: GPS autonomous robot

text:
# Question
Title: GPS autonomous robot
I am working on a GPS autonomous robot using Arduino, HMC5883 compass, Adafruit GPS module and I have managed to sort of complete the coding for it and I tried compiling / verifying it and I get an error. It would be helpful if anyone could assist help me find out what I am doing wrong in my code as I have spent 2 days looking for what I have done wrong and if someone could suggest a better way of writing my code or even improving it here code I appreciate it. HERE IS MY CODE http://textuploader.com/drhfa

Error:

```
GPS_move_:468: error: unterminated argument list invoking macro "radians"

```

# Answer
I cannot compile because there are libraries missing. However, after auto-formatting the code I have this list of problems:

* Many lines lack semicolons at the end (check your variable definitions near the top of the code)
* You have an extra bracket in one of your `radians()` calls (the one that is giving the error I guess): `differencelongitude = radians((longitudeWaypoint2 - (longitudeWaypoint1));`
* There is an unterminated string literal: `Wire.send("A);`
* You have a colon instead of a semicolon: `turn_left():`

There may be more but as I cannot even begin to compile I cannot find them easily - also there may be similar errors in any included files you have created.
> 2 votes

---
Tags: arduino-uno, arduino-mega, programming, c++, c
---


title: String array glitch

text:
# Question
Title: String array glitch
For a project, I was asked to design a presentation on Arduino. I now have run into the problem of my code suddenly stopping. It worked fine one day, I entered a new item in the array, it stopped working. It looked like I was being returned all newlines insteaed of debug info. Can anyone help?

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

int slide = 0;
const int slideNum = 13;
const String data[] = {
  "What is Arduino?\nArduino is a board\nthat can be used to\neasily program",
  "that can be used to\neasily program\ncomplex behaviors.",
  "Purpose\nMoney\nEase of Use",
  "How are they\ncontrolled?\nIDE, C++, Library\n",
  "Commonly Used\nCommands\ndiditalWrite();\ndidgitalRead();",
  "Commands\ndiditalWrite();\ndidgitalRead();\npinMode();",
  "diditalWrite();\ndidgitalRead();\npinMode();\nanalogWrite();",
  "didgitalRead();\npinMode();\nanalogWrite();\nanalogRead();",
  "Arduino Types\nUno\nMega 2560\nLeonardo",
  "Uno\nMega 2560\nLeonardo\nNano",
  "Mega 2560\nLeonardo\nNano\nMini",
  "Leonardo\nNano\nMini\nEthernet",
  "Nano\nMini\nEthernet\nBluetooth",
  "THE END"};

//Addr: 0x3F, 20 chars & 4 lines
LiquidCrystal_I2C lcd(0x27,20,4);

void setup()
{
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Send Newlne to start");
  Serial.begin(9600);
}
void loop()
{
  while (Serial.available() <= 0){
  }
  Serial.println("Current: " + String(slide));
  while (Serial.available() != 0){
    Serial.read();
  }
  next();
  if (slide == slideNum){
    for(;;){
    }
  }
}

void next(){
  String local = data[slide];
  String current[4];
  for (int i = 0; i != 4; i++){
    current[i] = local.substring(0, local.indexOf("\n"));
    local.replace(local.substring(0, local.indexOf("\n")), "");
    current[i].trim();
    local.trim();
    Serial.print("i=" + String(i) + ", current=" + current[i]);
    Serial.println(", local="+local);
  }
  lcd.clear();
  for (int i = 0; i != 4; i++){
    Serial.println(current[i]);
    lcd.setCursor(0,i);
    lcd.print(current[i]);
  }
  //lcd.print(data[slide]);
  slide += 1;
  Serial.println("New: " + String(slide));
}

```

# Answer
> 1 votes
Since you haven't provided all of your code, I can't say for sure exactly what caused your problem except that Arduino String operations employ dynamic allocation a lot. This will cause heap fragmentation, which is especially bad on a chip like the ATmega328 with little RAM and subsequently cause weird issues like you're getting. I would guess that initializing the String members of the array takes up a lot of heap space while fragmenting it and when you added one more string, you ended up with a stack-meets-heap situation at some point in `loop()`.

You're a lot better off with an array of compact strings using an array of pointers to `char` i.e. `const char * array[] = ...` since the strings are literals and so already known at compile time.

---
Tags: array
---


title: How to code Arduino to follow schedule

text:
# Question
Title: How to code Arduino to follow schedule
I'm working on my system and I have to make arduino repeat such action or block of code if its the set time .. I'm using DS3231 module to track date and time .Example If I set the time in 6:00 AM and when the arduino reads the module and it turns out that its already 6:00 AM the arduino will now execute some action or the block of code .. sorry for my english ..

# Answer
Check out how the DS3231 Alarm functions work. They will interrupt even a delay() statement. At the appointed time the specified function is called.

This same question was answered here:

How to set Alarms on the DS3231 easily?

For another way to see how to set this up, let me refer you to this article:

Build Programmable Time-based Switches Using a Real Time Clock

The code can be downloaded Here
> 1 votes

# Answer
This example shows a simple way of conditionally processing an event at a given time of day, once per day. The example allows 59 seconds of accuracy but in reality if the Arduino is free to read the time this will happen almost exactly at 6.00am.

You need to declare and populate currentTime and currentDate by reading the DS3231. This example assumes the currentTime is in millis.

```
unsigned long action1_LastDoneDate;
unsigned long TIME_600AM = 21600000; // millis 6.00 am = 6*60*60*1000
unsigned long TIME_601AM = 21660000; // millis 6.01 am

void setup()
{
 action1_LastDoneDate=0L;
}

void loop()
{
 //make sure we have not processed today
 if (action1_LastDoneDate != currentDate)
 {
   //make sure the time is within range
   if (currentTime>=TIME_600AM && currentTime<TIME_601AM)
   {
     //save off the current date so we don't try do process this alarm again
     action1LastDoneDate = currentDate;
     //now do the 6am stuff
   }
 }
}

```
> 0 votes

---
Tags: arduino-uno, rtc
---


# Question
Title: waiting for a set number of inputs in an array to be reached
How do i have code wait for an x number of inputs be reached in an array before doing anything else?

```
int largestindex = 0;
int learnindex=0;

    void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
    learn[learnindex]=pitch;
     learnindex++;
    }

    while(learn[largestindex]==0){
          MIDI.read();
          if (learn[largestindex]!=0){
           break;
              }

```

# Answer
If the call to `MIDI.read()` is a blocking call (it stays in there until it has a value) then you are pretty close:

```
const int NumberOfInputs (42);
for (int index = 0; index < NumberOfInputs; ++index)
{
    MIDI.read();
}

```

You can simplify you handler by post incrementing the learnindex counter as you use it. (Post increment will happen after the value has been 'used')

```
void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
    learn[learnindex++] = pitch;
}

```

When you increment a variable on its own line its usually better to pre increment it, because you aren't using the value and it might result in quicker execution. However remember you are increasing the value before using it, so if you use it as above you end up accessing the array element one higher than you intended to!

```
int learnIndex = 0;
++learnindex;            // Pre-increment it to 1
learn[learnIndex++] = 1; // Set element 1 to 1.
learn[++learnIndex] = 3; // Set element 3 to 3.

```
> 1 votes

---
Tags: arduino-mega, programming, array
---


title: Making MCUs Arduino Compatiable

text:
# Question
Title: Making MCUs Arduino Compatiable
I have recently just built a custom arduino using the schematics found on their website. As awesome as this little processor is, I need more power. I have been thinking of making my own MCU, but wanted to know if it is possible to make them compatible with the arduino software. It would be very nice to not have to rewrite my existing programs.

If so, how would I go about doing that? If this is not a possibility (or just not a good idea for any reason), which language should I learn to start programming these upper level MCUs.

If I do have to start using a different language, what kind of software do I use to upload the code to these processors? And do they have the common features like Serial Monitor and Serial Plotter like the Arduino IDE does.

# Answer
You are speaking of ***porting***. The arduino environment is built around a set of libraries and commands that are designed to abstract the low level access to a simpler high level language. In order to make arduino code work on a new microcontroller, you would have to rewrite and recreate the libraries using the low level access of your target microcontroller.

For example, Energia is a port of the Arduino libraries to the Texas Instruments MSP430 line of microcontrollers. Since not all features are the same, some code does not just drop in directly but additional code or libraries could be added to fix that. Even the Arduino IDE, the program used to write code and program the arduino was ported.

It would not be a trivial thing to port an entire library base.

---

As to your other questions, you would code your new microcontroller in any language it's programmer and compiler can use. Likely C or C++. Arduinos are typically programmed in C++. You should look into the manufacturer of your MCU to find out what software to use, and what libraries they offer. They likely do not offer something like the serial monitor right out of the box.
> 2 votes

# Answer
The Arduino IDE supports a whole list of micros:

http://forum.arduino.cc/index.php?topic=145065.0

Some of those have a lot more power than the others. But to answer your question, no you cannot say take an ARM and use the Arduino IDE with it. It all comes down to your compiler and environment. At work we use ARm based processors and Keil uVision to program and Flip to program them. At my previous job we used Freescale Kinetis micros with CodeWarrior to flash and write the software. It all depends on what you decide to go with to fit your application, but it all boils down to it's all C or assembly if you decide to go that way.
> 0 votes

---
Tags: custom
---


# Question
Title: Diorama Controller Part 2 - Need More Outputs
For background see my original post. I've decided to not to use batteries and have it wired up with wall power.

I wish to use the Arduino Pro Mini 5V as the controller for my diorama project. I have five completed buildings which will all have LEDs (with only two wired up so far). The two currently wired buildings have multiple "zones/rooms" that can have its LEDs activated separately.

Building 1 is a saloon with rooms above. It has a total of 7 zones/rooms.

Building 2 is a store with a doctor's office above and rooms in the back of each. It has 4 rooms.

With this setup, I am able to use the software to simulate people coming and going within the rooms. It's pretty neat.

However, I'm currently at 11 outputs out of the Mini. I'm running out of pins. How can I have more outputs?

# Answer
I think I understood what you want. If you want to control more LED's with less pins, consider using a shift register. For example, sn74hc595 could increase your digital outputs drastically. It has 8 bits, so you can have 2^8 combinations of outputs with it! For example, 0000 0001 is something, and 0000 0010 is something else, and so on. Check it out! I hope this helps :)

https://learn.sparkfun.com/tutorials/shift-registers \- Basic knowledge about shift registers http://www.bc-robotics.com/datasheets/sn74hc595.pdf Other shift registers are great as well
> 1 votes

---
Tags: arduino-mini
---


title: Calculating with millis()

text:
# Question
Title: Calculating with millis()
The following code works fine until I turn the `if (tijd - action >= 500)` into `if (tijd - action >= 1000)`

I wonder why this fails.

If I just loop and print the `tijd - action` it has no problem with it and runs well beyond 1000.

The Logic Analyzer on the software serial only returns **'255'** when it fails, I also wonder what that means.

The core I use is this one
The chip I use is an ATtiny85
I run this using the Arduino IDE 1.8.2

**\[update\]**

with "start"

```
Sketch uses 3070 bytes (37%) of program storage space. Maximum is 8192 bytes.
Global variables use 146 bytes (28%) of dynamic memory, leaving 366 bytes for local variables. Maximum is 512 bytes.

```

with "starting"

```
Sketch uses 3072 bytes (37%) of program storage space. Maximum is 8192 bytes.
Global variables use 148 bytes (28%) of dynamic memory, leaving 364 bytes for local variables. Maximum is 512 bytes.

```

**script**

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

#define TX_PIN 4
#define RX_PIN -1

#ifndef cbi
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

SoftwareSerial mySerial(RX_PIN, TX_PIN);

unsigned long tijd;
unsigned long action = 0;

volatile boolean f_wdt = 1;
ISR(WDT_vect) {
  f_wdt=1;
}

void system_sleep() {
  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out
  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

void setup() {
  mySerial.begin(2400);
  mySerial.print("Starting..");
  setup_watchdog(8);
  pinMode(0, OUTPUT);
}

int zie = 0;

void loop() {
  if (f_wdt==1) {
    digitalWrite(0, HIGH);
    tijd = millis();
    mySerial.print(".");
    mySerial.print(tijd - action);
    zie+=1;
    if (tijd - action >= 500) { // fails when set to 1000
      digitalWrite(0, LOW);
      action = tijd;
      mySerial.print("z");
      mySerial.print(zie);
      mySerial.print(".");
      system_sleep();
    }
  }
}

```

# Answer
> if I change the string "Starting.." to "Start" it will run fine! This probably has something to do with filling up the RAM of the Tiny, right?

That symptom does suggest RAM overflow, in spite of the relatively low RAM use (28%) reported during compilation.

To reduce memory use slightly more, you can move the string `"Starting.."` to PROGMEM by changing from line 1 below to line 2.

```
  mySerial.print("Starting..");     // line 1
  mySerial.print(F("Starting.."));  // line 2

```

To save another handful of RAM bytes, change lines like `mySerial.print(".");` and `mySerial.print("z");` to `mySerial.print('.');` and `mySerial.print('z');`. That is, you are printing single-character strings; each string has a null terminating byte; instead just print single characters.

References and discussion of the F() macro include , , , ,  and also see How do I squeeze code to fit onto an ATTiny. Also, there are some really compact software serial libraries targeted for ATtinies, which may save hundreds of bytes of flash and dozens of bytes of RAM.
> 0 votes

---
Tags: timers, attiny, millis
---


# Question
Title: Is there a manometer available to use with Arduino?
I used an analog manometer in a plumb system. I would like to actually track information about water pressure across an entire building on different points and record all this information to analyze changes on pressure. I was wondering if there is a manometer that can be used with arduino. Or if there is some other homemade solution?

If there is any electronic sensor with an analog output that would be enough.

# Answer
> 2 votes
Bruno, there are a number of sensors available, try an Ebay search, to do what you want. However, you need to determine what pressure range you are looking at. As you mention manometer I assume you are working in the mBar range but to me that would be at odds with the pressure typically seen in whole building systems. An Ebay search on 'Pressure transducers' will yield a good range of devices, likely to be primarily industrial types and some using wheatstone bridge type outputs. you may need an op-amp circuit to buffer / amplify the output signal but virtually all sensors can be interfaced to an Arduino with the correct conditioning cicuitry. As you are aware to measure pressure all sensors will need to be invasive into the pipework.

---
Tags: pressure
---


# Question
Title: Port manipulation in Arduino using byte value
I'm trying to write PORTB and PORTD in ATmega328P using byte system like this,

```
    //  PD7  PD6  PD5  PD4  PD3  PD2  PD1  PD0
    //  N     N    N    N    N    U    U    U
    //  7     6    5    4    3    2    1    0
    //======================================
    //  PB7  PB6  PB5  PB4  PB3  PB2  PB1  PB0
    //  X     X    1    1    1    1    1    1
    //  C     C    13   12   11   10   9    8
    //======================================
    //C-Crystal Pins/U-Un used/N-Used/X-unknown value

    byte pins[] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};

    //uint16_t style1=1365; //10101010101
    //uint16_t style2=682;  //01010101010

    void setup() {
      for (int i = 0; i < 11; i++) {
        pinMode(pins[i],OUTPUT);
        PORTD=B00000000;
        PORTB=B00000000;
      }

    }

    void loop() {
      PORTD=B10101000;
      PORTB=B00101010;
      delay(1000);
      PORTD=B01010000;
      PORTB=B00010101;

    }

```

According to this , Port value should be swapped. But, It's still remaining given value of the code before delay()

What is the problem in this code?

# Answer
> 5 votes
> What is the problem in this code?

No problem, it *does* change the bits of port D and B from 0B10101000 and 0B00101010 to 0B01010000 and 0B00010101 respectively.

However, microseconds later `loop()` runs again and changes them back to 0B10101000 and 0B00101010 for a full second.

To better see what's happening, add a second `delay(1000);` statement, placing it just before the closing brace.

---
Tags: arduino-uno, port-mapping
---


# Question
Title: Prevent Arduino Mega from setting all Outputs to HIGH on Reset
The Arduino Mega 2560 Rev 3 has multiple relays connected to its digital output pins.

Whenever the Arduino is reset (using reset button, turning on Serial Monitor etc), the Arduino turns on all relays then turns them off. I cant find any function in my sketch that causes the outputs to go HIGH then LOW. Assuming this is a normal feature of the Arduino, how can we prevent this and ensure that the outputs do not flip to the HIGH state?

# Answer
The ATmega2560 itself comes out of reset with all pins in high-Z (DDRx=0, PORTx=0). Your observations are likely due to the bootloader. Check the bootloader source to verify that it is responsible for this.
> 2 votes

# Answer
The relay board you are using has active low inputs to control the relays. In your sketch when you are initialising the pins as outputs they are by default set low (this is turning all your relays on). set the pins as outputs and set them high, they will be low for a very short time (too short for the relay to turn on effectively).
> 2 votes

# Answer
Just to add my five cents. I also experienced a relay, driven by a bipolar npn lowside. turning on while timers, Serial etc init and then turn off again. Using INTERNAL\_PULLUP mode helped me as well.

have no idea why. It must have something to do with relays beeing current driven. Mine requires 20 mA at 5V
> 1 votes

# Answer
There is an alternative to change the bootloader. Introduce a RC circuit in the relay driver that delay the rely to switch ON.

**Note:** Please add info about the relay and/or driver circuit for a better answer.
> 0 votes

# Answer
> Assuming this is a normal feature of the Arduino,

It doesn't sound normal to me. Check with others to see if they have the same issue before you try to resolve an otherwise non existent problem.

> how can we prevent this and ensure that the outputs do not flip to the HIGH state?

Design the relays to be active now.
> 0 votes

---
Tags: arduino-mega, pins, relay
---


title: Arduino Uno with ESP8266

text:
# Question
Title: Arduino Uno with ESP8266
```
#include <stdlib.h>
#include <SoftwareSerial.h>

#define SSID "name-of-my-network" //replace XXXXX by your router SSID
#define PASS "password-of-network" //replace YYYYY by your router password
#define IP "184.106.153.149" //thingspeak.com IP

const int tempPin = A0; //configure Arduino pins
String GET = "GET /update?key=thingspeak-api-key&field1=";
SoftwareSerial mySerial(10,11); //Serial communication to ESP8266 module(RX, TX)
unsigned long starttime;
unsigned long sampletime_ms = 30000;
unsigned long delay_time = 60000;

void setup() {
  Serial.begin(57600);
  while(!Serial) {
    ;
  }
  mySerial.begin(115200);
  Serial.println("Initializing...");
  //communication with wifi module
  mySerial.flush();
  mySerial.println("AT");
  delay(2000);
  if(mySerial.find("OK")) {
     Serial.println("Communication with ESP8266 module: OK");
   } else {
     Serial.println("ESP8266 module ERROR");
   }
   connectWiFi();
   //initialize timer
   starttime = millis();
}

void loop() {
  // put your main code here, to run repeatedly:
  if ((millis() - starttime) >= sampletime_ms) {
    char buffer[10];
    int analogReading = analogRead(tempPin);
    String temperatureStr = dtostrf(analogReading, 4, 1, buffer);
    temperatureStr.replace(" ","");
    updateSensors(temperatureStr);
    //wait next sampling cycle
    Serial.print("Wait ");
    Serial.print(delay_time/1000);
    Serial.println("s for next sampling");
    Serial.println();
    delay(delay_time);
    //initialize new cycle
    Serial.println();
    Serial.print("Sampling (");
    Serial.print(sampletime_ms/1000);
    Serial.println("s)...");
    starttime = millis();
  }
}

void updateSensors(String tempStr){
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  mySerial.println(cmd);
  delay(2000);
  cmd = GET;
  cmd += tempStr;
  cmd += "\r\n";
  delay(1000);
  int strsize = cmd.length();
  mySerial.println("AT+CIPSEND=" + String(strsize));
  delay(2000);
  mySerial.print(cmd);
  if(mySerial.find("OK")) {
    Serial.println("Transmission completed with success");
  } else {
    Serial.println("Transmission failed!");
  }
}

boolean connectWiFi(){
  Serial.println("Connecting wi-fi...");
  String cmd ="AT+CWMODE=1";
  mySerial.println(cmd);
  delay(2000);
  mySerial.flush(); //clear buffer
  cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  mySerial.println(cmd);
  delay(5000);
  if(mySerial.find("OK")) {
    Serial.println("Connection succeeded!");
    return true;
  } else {
    Serial.println("Connection failed!");
    return false;
  }
  Serial.println();
}

```

I am using the above code and have connected the ESP8266 to the Arduino as follows:

> TX of ESP8266 to pin number 11 of Arduino
> Rx of ESP8266 to pin number 10 of Arduino
> Vcc of ESP8266 to 3.3V power supply taken from Arduino
> GND of ESP8266 to GND taken from Arduino
> CH\_PD of ESP8266 to GND

It seems that I can't get the ESP8266 working. Could anyone could help me? I would really appreciate any help since I cannot continue my project.

# Answer
Often the issue with this module is that the 3.3v of Arduino is unable to maintain enough current for the ESP8266 to work properly. I assume you have the proper firmware flashed to the wifi module
> 1 votes

# Answer
This code is used to upload temperature data on pin A0 to things speak Create thingspeak account and create channel you get api key it seems that this code uses field1 to upload data upload this code to arduino the change ssid and password
> 0 votes

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


title: Arduino with OV7670 - a buffer

text:
# Question
Title: Arduino with OV7670 - a buffer
I have an Arduino UNO and OV7670 camera sensor without FIFO. I wanted to build a device, that would take frame once in a while, and would send it through bluetooth (HC-05) or wi-fi (esp-01). I didn't know though, that the microcontroller inside Uno has so little RAM memory, that the frame doesn't fit inside. Moreover, even Arduino Mega has too little memory...

My question is- **is there anything I could do to take a VGA-resolution photo (circa 1MB) and send it through any serial medium**?

I suppose it'd be some kind of a buffer or memory- I'm asking for references to concrete chips or solutions (like- would it be possible to encode or compress an image on-the-fly)?

# Answer
If you're okay with grayscale, you don't need 1 MB buffer space. With the YUV422 colour space, you can extract only the Y component and need only 640\*480 = 307kB buffer for a VGA grayscale image.

However, according to this, you can set the hardware serial baud rate to 1M-baud and transmit the image bytes as you receive them without buffering. `main()` shows how to set up the serial port and you can also see how they received each VGA pixel byte in Bayer-RGB and transmitted immediately; notice that all interrupts are disabled first, given the high-speed nature of the transfer. But instead of Bayer, I'd recommend you use YUV422 instead, meaning the camera sends 2 bytes per pixel. Because you're only interested in the Y byte, you can place that in the UART buffer and use the time spent in receiving (and discarding) the second U/V byte to give the UART peripheral some additional breathing room to send the Y byte, before you send the next one.

Regarding the high baud rate, the crystal frequency of the Arduino doesn't matter so much because you'll only be transmitting to your PC, which should be able to handle the speed even given the rate error. Note that in `main()`, double speed async is enabled, and UBRR is set to 500 kBaud to obtain 1-Mbaud. Also notice that an 8MHz PWM signal was used to clock the camera (`XCLK` signal) with no PLLs activated in the camera register settings. This is another tutorial related to the same code; may clear up a few things.

If you really want to use a chip solution, you can look up parallel SRAM like the HM628128; it's only 128kB though, you'll need to find a bigger one to hold an entire frame of 307kB. Parallel SRAM are great because you can attain really high write speeds because of the simple interface. You'll need some sort of counter connected to the SRAM address lines clocked by the `PCLK` line (divided by 2, since you only want every other byte) so that every pulse increments the address. This same clock will feed the `nW` signal to actually clock the data into the SRAM (after satisfying address setup times somehow). The camera data lines will be connected directly to the SRAM and you activate the SRAM's chip select signal based on your monitoring of the camera's `VSYNC` signal (to know when a new frame's about to start). When the frame's done, you read from the RAM and forward the bytes to your destination.

All this assumes you aren't trying for video, merely taking frames "once in a while". Though the first solution will work for video, albeit poor video.
> 3 votes

# Answer
You need to add a FIFO buffer to the camera, or work out a scheme for streaming data from the camera over the network, because you don't have anywhere enough memory to store the image.
> 1 votes

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


title: 3x3 LED Matrix with less pins

text:
# Question
Title: 3x3 LED Matrix with less pins
I'm building an audio cable tester/soldering station. XLR cables have 3 pins and they can be wired in a few ways depending on what you want to do. The basic cable is connected 1 for 1 and I want to make a system to verify if each pin is connected to the good ones on the other connector.

Picture the male and female connectors side by side. The 3 pins on the male connectors will be connected to 3 digital outputs and the 3 pins on the female connector will be connected to 3 digital inputs. That way, I can turn one of the outputs High and check my 3 inputs to see where that pin on the male connector is wired on the female connector. Then I can walk the remaining outputs and find out how the rest of the cable is wired.

That part is all good, I can output the wiring via the Serial.print() command and the result is good. The thing is that I would like to show the result with LEDs. It brings me up to 9 LEDs in a 3x3 matrix. I can use 9 outputs to show the result, but it seem like there could be a much better way.

The two solutions I see are the following:

1. Buying addressable LEDs and interface them with my Uno
2. Use 6 outputs, one for each row and one for each column. Each row represents one pin on the male connector, each row represents one pin on the female connector. So while I walk my 3 pins I can turn on the corresponding row and columns, then turn off that row and go to the next one, turn on the corresponding columns, etc. I feel like this would work, but I'm wondering if the LEDs will flicker or if the refresh will be fast enough not to be noticeable.

What would you suggest? Am I on the wrong track with solution #2? Is there another way that does not require that many outputs? I'm already up to 12 IO pins taken with #2 and 15 with #1. It seem like a lot for such a simple build...

# Answer
Option #2 can definitely work, it is based on a widely adopted side effect of human vision called Persistence Of Vision, abbreviated with POV, which is used in Television, LED cubes and many other display devices.

You *SHOULD* notice no flickering if you manage to keep a refresh rate above 24 FPS (Frames Per Seconds or full refreshes), but not all human being are the same, that's why we tend to aim at 60 or 100 FPS to ensure flickering is not perceivable by anybody.

What you *WILL* notice though is a reduced brightness as each LED will be turned on only for a fraction of time.

So, naming your pins as `COL1` to `COL3` and `ROW1` to `ROW3`, you can refer to the following schematic:

simulate this circuit – Schematic created using CircuitLab

You can further extend your option #2 by using an external IC, commonly referred as LED drivers: not something you need unless you get short of outputs.
> 1 votes

# Answer
It might be most cost- and time-effective to use an SPI-interfaced MAX7219-based 8x8 LED module. These cost a couple of dollars. Typically they include an 8x8 array of single-color LED chips, mounted under a cover. The MAX7219 handles LED multiplexing and allows software control of brightness as well as resistor control.

To represent 9 items in a 3x3 arrangement, you could use 4 LEDs per item, so that rows 1 and 2; 4 and 5; 7 and 8 represent rows of items, with LED rows 3 and 6 remaining blank; and similarly for the columns.

Note, with four output lines you can control 12 LEDs, multiplexed via “charlieplexing”. But the time and cost of setting that up probably would be somewhat more than just using a MAX7219 module.
> 1 votes

---
Tags: arduino-uno, led
---


title: serial.write if condition

text:
# Question
Title: serial.write if condition
I am trying to do a simple serial communication control via sending a char and using it as an if condition, the arduino part is below

```
char incomingchar;
void setup() {
    Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
//        Serial.write("g"); // does not work when I explicitly write here either as opposed to through python.
}

void loop() {
    if (Serial.available()) {
            // read the incoming char:
            incomingchar = Serial.read();
               if (incomingchar=="g"){
              Serial.println("hello world!");}
              else{
              Serial.println(incomingchar);
    }
}
}

```

And here is the Python code:

```
import serial;
ser=serial.Serial('COM3',9600,timeout=1)
ser.write(b'g')

```

When I run this, the python program returns a '1', and so does the arduino program in the serial monitor.

Note, if I directly set Serial.write('g'), it simply types out 'g' in the monitor and does nothing else from the loop.

# Answer
You declare `incomingchar` as a `char`. In your `if` you compare that char to a string (double quotes) `incomingchar=="g"`. I think you want to compare it to a `char` (single quotes) like this:

```
if ( incomingchar == 'g' ) {
  // do something
}

```
> 3 votes

---
Tags: serial, python
---


# Question
Title: How to wire up and trigger this SPDT relay?
How do I connect a SPDT relay to an Arduino?

It's a DC 5V Coil 6 Pin relay and ultimately what I want to do is have the Arduino trigger the relay to allow voltage to pass through.

I couldn't find a data sheet, but apparently this is the layout...

```
----------------------------------
|....1......2..............3.....|
|................................|
|....4......5..............6.....|
----------------------------------

2 and 5 are the 5v relay coil
3 and 6 are shorted together
3 and 1 are normally closed
3 and 4 are normally open

```

# Answer
You can use this connection diagram with your relay

**6 pin Relay pin out**

**Code**

```
int Relay = 8;

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

void loop()
{
      digitalWrite(Relay, HIGH);  // turn on relay
      delay(2000);
      digitalWrite(Relay, LOW);   // turn off relay
      delay(2000);
}

```

First check your relay with multi meter then find the Coil, Com, NO and NC points for correct connection. Hope this will help you.
> 1 votes

# Answer
According to the link you've provided, the coil draws very little current, and the person posting that comment suggests that it can be directly driven by an arduino. I would hesitate to use more than one to a board without additional research in that respect.

The comment also suggests that a capacitor be placed across the coil terminals, which will also protect your circuit from excessive power draw causing drop outs.

The research I've done indicates that the digital pins can handle a maximum of 40 ma, but the recommendation is no more than 20 ma, which is lower than the specs for this relay.

If you are going to use more than one on a given arduino board, a shift register or equivalent would protect your board and give you reliable results. For a single relay, consider this resource: https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/transistors

Some additional research may lead one to believe that even 20 ma is too much current to draw, so the transistor option is certainly the safer route.

Be certain to use pull-up or pull-down resistors, depending on your configuration with the digital pin selected.

You didn't indicate what you were going to be connecting to the N/O or N/C pins, but that won't matter if they are external to the arduino and do not exceed the specifications of the relay.
> 0 votes

# Answer
Use a driver transistor (or MOSFET, with a 4K7 pull-down), and a flyback diode with the anode at the negative terminal, and cathode at positive terminal. I used some tiny ones, which failed, so now I use ones that can handle ~0.5A, but that's probably overkill.

If you want galvanic isolation, use an optocoupler instead of a transistor - I only do this for AC. I have never needed decoupling capacitors for this type of relay.

Edit:

* Wire 5V to relay positive terminal.
* Wire relay negative terminal to NPN transistor/MOSFET collector/drain.
* Wire NPN/MOSFET emitter/source to GND. Wire NPN/MOSFET base/gate to some digital pin. If using a transistor, do it across a 1000 ohms resistor.
* If using a N-channel MOSFET add a 4700 ohms pull-down from gate to GND.
* Wire diode cathode to relay positive terminal, and anode to relay negative terminal.

I would not use the decoupling cap, but if OP really wants it, go for 50-100V 10uF.
> 0 votes

---
Tags: relay, wires
---


title: Cheapest Arduino GPRS or 3G solution

text:
# Question
Title: Cheapest Arduino GPRS or 3G solution
I am looking at creating a fleet of low power, Arduino driven devices.

I would need some kind of GPS on them all (or could triangulate through phone network?) plus a connection to the internet - just for HTTP POST requests. GPRS or GSM would do but 3G would be better.

What are the best (price is a major factor because I'm trying to do a fleet) GSM, GPRS or 3G modules that I can use with Arduinos? As I said, I need their location so one with GPS built in would be great.

EDIT: The amount of devices in the fleet will change, so the entire network needs to be dynamic which is why having a GPRS/GSM module on each one would work so well.

# Answer
> 3 votes
Not many possibilities (for the phone part, I suggest a GPRS/3G shield), but not wanting to discourage you, if you are thinking about "a fleet", forget about:

- low power (the phone radio needs power, some say you need \> 1A for both Arduino plus the shield, depending on your distance to the antenna). you must add the GPS part. Even if you communicate just a fraction of the time, you need instant power for feeding the radio.
- low price (gprs shields are not cheap, starting at some 25€, and gps shields about 20€). and don't forget that you need a SIM card with a data plan for every unit....
Depending on what are you trying to achieve, I'd try with less expensive (RF communications, for example) to avoid carrier costs and hardware costs, at the price of a more complex development.
If you want to publish to a web service, you can always make your minions transmit to a centralized Raspberry PI, for example, that would take the task of bridging with the Internets, or your mastermind...:-D

# Answer
> 4 votes
If you are finding Cheapest and working module you can you SIM800L less then 4$.

```
aliexpress.com/item/Free-Shipping-Smallest-SIM800L-GPRS-GSM-Module-MicroSIM-Card-Core-BOard-Quad-band-TTL-Serial-Port/32708504554.html

```

You can find many other cheap alternative but they does not work properly.

Sim800 have good support and you can find many examples to use this with arduino.

Many other model also available in market as per your requirements.

# Answer
> 0 votes
a few new ones have hit the scene recently. There's one by the folks that made the particle board (the electron supports 2G and 3G). There is also a kickstarter by sixfab that made one for the pi-zero footprint (but it's a standard raspberry pi GPIO and also has USB connection support or you can bread-board it to an arduino). They make a more expensive plate on standard RPi footprint that supports laptop-style WWAN modules (bought separately) so it can do 3G or 4G/LTE. One of the better one's I've seen recently is actually part of the AT&T offerings (I believe avtel is the one that put the packages together for them). If you google AT&T IoT starter kit, they have four different offerings, with the lowest being $59. (it's apparently used as just a modem and can be connected via gpio style pins or via usb) It comes with a sim with 300Mb and 300 SMS messages good for up to 6 months from date of activation. There are a few higher end chips coming out with LTE and 4G support also from Simcom (the makers of the Sim900 based devices core chip). Boards I have seen built on their LTE based devices run in the $80-120 range so, unfortunately they don't qualify as cheap. As of yet, I haven't seen anything with 3G or higher under the $40 mark though. Most of them start above $50 and go up. Maybe by the time 2G is completely phased out, LoRa will be well saturated?

---
Tags: gsm, gps
---


# Question
Title: Why Liquid crystal display doesn't give output in code below?
I've been working on project for children showing the codes used by atc transponder. I've used a keypad and a 16×2 display , where user types a 4 digit code and display shows condition related to the code E.g. typing 7500 on keypad will show hijack on display

What has went wrong??

```
My code is ------
    #include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(8, 9, 10, 11, 12, 13);//RS,EN,D4,D5,D6,D7
#include <Keypad.h>//header for keypad commands enabling
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Three columns
// Define the Keymap
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'#','0','*','D'}
};
// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = { 0, 1, 2, 3 };
// Connect keypad COL0, COL1 and COL2 to these Arduino pins.
byte colPins[COLS] = { 4, 5, 6, 7 };
//  Create the Keypad
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

char inputArray[4]; //array to gather user keypad presses
char Vfr[4] = {'1','2','0','0'}; //array to hold keypad password
char Gliders[4] = {'1','2','0','2'};
char Hijack[4] = {'7','5','0','0'};
char Comfail[4] = {'7','6','0','0'};
char Emerg[4] = {'7','7','0','0'};
char Mic[4] = {'7','7','7','7'};

int i = 0;
int state = 1;

void setup()
{
  for(int k=8;k<14;k++)
  {
    pinMode(k,OUTPUT);//pins 8-14 are enabled as output
  }
  lcd.begin(16, 2);//initializing LCD
}

void loop()
{
while (state = 1);
{
 lcd.setCursor(0, 0);

 char key = kpd.getKey();

 //if a key is presseds
   if(key)
     {

     inputArray[i] = key; //store entry into array
     i++;
     lcd.clear(); //print keypad character entry to serial port

     if (key=='C');
       {
         lcd.setCursor(0, 1);
         lcd.print("Reset");
         i=0; //reset i
       }

     if (i == 4) //if 4 presses have been made
       {
         {

         //match input array to password array

           if (inputArray[0] == Vfr[0] &&
           inputArray[1] == Vfr[1] &&
           inputArray[2] == Vfr[2] &&
           inputArray[3] == Vfr[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("VFR");
              }
         }

         {

         //match input array to password array

           if (inputArray[0] == Gliders[0] &&
           inputArray[1] == Gliders[1] &&
           inputArray[2] == Gliders[2] &&
           inputArray[3] == Gliders[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("GLIDERS");
              }
         }

         {

         //match input array to password array

           if (inputArray[0] == Hijack[0] &&
           inputArray[1] == Hijack[1] &&
           inputArray[2] == Hijack[2] &&
           inputArray[3] == Hijack[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("HIJACK");
              }
         }

         {

         //match input array to password array

           if (inputArray[0] == Comfail[0] &&
           inputArray[1] == Comfail[1] &&
           inputArray[2] == Comfail[2] &&
           inputArray[3] == Comfail[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("COMMFAIL");
              }
         }

         {

         //match input array to password array

           if (inputArray[0] == Emerg[0] &&
           inputArray[1] == Emerg[1] &&
           inputArray[2] == Emerg[2] &&
           inputArray[3] == Emerg[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("EMERGENCY!");
              }
         }

         {

         //match input array to password array

           if (inputArray[0] == Emerg[0] &&
           inputArray[1] == Emerg[1] &&
           inputArray[2] == Emerg[2] &&
           inputArray[3] == Emerg[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("EMERGENCY!");
              }
         }

         {

         //match input array to password array

           if (inputArray[0] == Mic[0] &&
           inputArray[1] == Mic[1] &&
           inputArray[2] == Mic[2] &&
           inputArray[3] == Mic[3])
              {
               lcd.setCursor(0, 1);
               lcd.print("MILITARY IC");
              }
         }
       }
}
lcd.print(key);
}
}

```

# Answer
> 1 votes
```
while (state = 1);

```

This line is a loop that will go around forever so long as you can set the variable state to 1. What you mean is:

```
while (state == 1)

```

You don't need semicolons at the end of conditionals, here is another:

```
 if (key=='C');

```

If you fix those two bugs, you'll get a lot further.

---
Tags: arduino-uno, arduino-ide, display
---


# Question
Title: Problem with SIM800L GSM module and servo
I have a SIM800L GSM module like in this link, .

.

The problem is when I connect the GSM to my Arduino Uno the GSM turns on for a while and then turns off. I tried to connect it with a 9-volt battery and an LM7805 voltage regulator, but I have the same problem. Attached to the Arduino are an LM35 temperature sensor, two LEDs, a buzzer, an LCD, a GSM module, a gas sensor and a servo.

The other problem is with the servo. I tested the servo and it works fine but when the servo stops moving, it starts to shake. I do not know what the problem is.

# Answer
> 1 votes
You SIM800 module will pull 2Amps when its transmitting. If your servo is also trying to overcome the inertia at the start of a movement it will pull 4+ times its normal running current.

A 9 volt battery will let you pull a couple of hundred milliamps. So when the GSM transmits you system will shutdown.

You need a proper power supply or a battery pack that can put out these levels of peak current (3+Amps)

---
Tags: arduino-uno, gsm
---


title: WDT and RadioHead with delay()

text:
# Question
Title: WDT and RadioHead with delay()
The core I use is this one
The chip I use is an ATtiny85
I run this using the Arduino IDE 1.8.2
RadioHead ASK library (slimmed down)

What I want to do is:

* deep sleep
* wake up every minute
* turn on sensor
* take measurement
* transmit data
* back to sleep

This works when I test it seperatly, where it goes awry is when I combine RadioHead with WDT and then try to use a delay. This always hangs.

Probably a timer issue, I am looking for a work around. I need the delay because I need to start the sensor, wait .5 sec and then take a measurement. Maybe I should give the ATtiny85 just some job to keep it busy for 0.5 sec?

This is working code, when I uncomment `// driver.init();` it will fail.

```
// RadioHead ASK
#include <RH_ASK.h>

// Sleep
#include <avr/sleep.h>
#include <avr/wdt.h>

#ifndef cbi
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

// Absolute reference PB to overcome inter-IDE issues
#define T_PIN 1 // transmission
#define L_PIN 3 // optional LED pin
#define S1 A2
#define S2 A1
#define BAUD 2000

// Baud rate, receiver, transmitter
RH_ASK driver(BAUD, 9, T_PIN); // pin 9 is non existent

// Watchdog
volatile boolean f_wdt = 1;

ISR(WDT_vect) {
  f_wdt=1;
}

// Sleep
void system_sleep() {
  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out
  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

// Setup for Watchdog
void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

void setup() {
//  driver.init();
  setup_watchdog(8);
}

void loop()
{
  if (f_wdt==1) {
    pinMode(0, OUTPUT);
    digitalWrite(0, HIGH);
    delay(500);
    digitalWrite(0, LOW);
    delay(500);
    system_sleep();
  }
}

```

# Answer
> 3 votes
The RH\_ASK library uses `timer0`, which is also used for `millis` and `delay`.

Quick workaround is to use the standard AVR delay instead.

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

...

_delay_ms(500)

```

---
Tags: timers, attiny, sleep
---


# Question
Title: How do I hook up a 3V device to a 74AHCT125 (Quad Level-Shifter)?
I have this level shifter that I'm trying to feed a 5V power source and then hook up a 3V device.

I've got the 5V source hooked up fine (on the top pinouts), but having trouble figuring what the "power out" would be that's 3V.

Here's the data sheet.

# Answer
It's not a level shifter. It's a buffer chip that *can be used to level shift in one direction only*.

It is good for shifting from a low voltage logic signal (3.3v, say) up to a 5V logic signal. It can't shift down from 5V to 3.3V.

Basically it works by having a fixed voltage that it considers to be a logic HIGH, and any voltage above that will be output as 5V. Any voltage below will be output as 0V. This is the "TTL Logic Level" specification in the datasheet.

So if you have a sensor that emits a 3V logic signal the HIGH logic value will be above its fixed threshold and will trigger a 5V HIGH on the output.

In contrast "CMOS" logic uses a percentage of the supply voltage to set the thresholds (usually \> 0.6 x Vcc), and a 3V signal is less than that (3.3V is about bang on it, so is "iffy"), so won't work (or not reliably).
> 3 votes

# Answer
The datasheet would let you think it cannot shift in that direction, but it's the chip recommended by Adafruit to do so : https://www.adafruit.com/product/1787

The "trick" is to feed it 3V power. It seems it will then happily accept 5V input and produce 3v outputs.
> 1 votes

---
Tags: power, voltage-level
---


# Question
Title: Run motor for a set amount of depending of Pressure Sensor
I'm a noob when it comes to time-based coding.

I have a pressure sensor which shows me readings for when someone is sitting on a chair.

I want to turn a motor for 2 seconds when the pressure sensor says occupied I want to turn the motor the other way for 2 seconds when the pressure sensor says empty.

Also after the motor has turned for 2 seconds, I don't want it to turn the motor at all until the reading of the pressure has changed to the other reading.

Here is my code.

```
#include <AFMotor.h>
AF_DCMotor motor(1,MOTOR12_64KHZ);
AF_DCMotor motor2(2,MOTOR12_64KHZ);
int fsrPin = 0;     //FSR and 10K resistor are connected to pin 0
int fsrReading;     //the analog reading from the resistor divider

bool WheelLock = true;  //controls whether the wheelchair is locked or not
long startTime = millis();
long stopTime = startTime;

void setup(void){
  Serial.begin(9600);
  motor.setSpeed(255);
  startTime = 0;
  stopTime = 5000;
}

void loop(){
  while(startTime < stopTime){
    if(onChair() == false){
      motor.run(BACKWARD);
      startTime = millis();
    }
    else{
      motor.run(FORWARD);
      startTime = millis();
    }
  }
  motor.run(RELEASE);
  Serial.println("RELEASED");
  startTime = 0;
  Serial.println(startTime);
}

bool onChair(){
  fsrReading = analogRead(fsrPin);

  if(fsrReading > 800){
    Serial.println("Wheelchair is occupied");
    WheelLock = false;
  }

  else{
    Serial.println("Wheelchair is empty");
    WheelLock = true;
  }
  delay(200);
  return WheelLock;
}

```

# Answer
> 0 votes
I think you want something like this:

```
int motorRunSecs = 2
bool chairLastState = false;
bool chairCurrState = false;
int motorDirection = FORWARD;

void loop() {
    chairCurrState = onChair();

    // if the chair occupied state has changed, then do something
    if (chairCurrState != chairOccupied) {

        // set the motor Direction based on the state of the chair
        motorDirection = ((chairCurrState) ? FORWARDS : BACKWARDS);

        // run motor for X secs
        motor.run(motorDirection);
        delay(motorRunSecs * 1000);
        motor.run(RELEASE);

        // now update the last chair state
        chairLastState = chairCurrState;
    }
}

```

# Answer
> 0 votes
You really want to look at the finite state machine to model your problem. With this, you are looking at states and the transition between states.

In your problem, for example, you want to turn on a motor for a certain length of time after the chair state changes from empty to occupied. However, in your code you are not retaining the previous state (empty or occupied) so you cannot act when there is a state change fom empty to occupied.

Here is some rough C++ code to show you how this could work in paractice.

```
// states:
// ChairOccupancyState: occupied; empty
// MotorState: on; off

// pseudo code

loop() {
   if ( ChairOccupancyState == empty && onChair == true ) {
      // we have a transition from empty to occupied
      // switch motor on direction 1
      motorState = on ;
      // record time
      motor_on_at_ms  = millis() ;
      ChairOccupancyState = occupied ;
   }

   if ( ChairOccupancyState == occupiedy && onChair == false ) {
      // we have a transition from occupied to empty
      // switch motor on direction 2
      motorState = on ;
      // record time
      motor_on_at_ms  = millis()
      ChairOccupancyState = empty ;
   }

   If (motorState == on && millis() - motor_on_at_ms > 2000 ) {
      motorState == off ;
      // switch motor off
   }

}

```

# Answer
> 0 votes
Fairly easy.

You have to determine if the pressure has changed from its previous reading.

If it has, you can start to turn the motor for two seconds.

Once the time is up, turn the motor off.

Once you put your code in that framework, it would be much easier to code top down.

---
Tags: motor, arduino-motor-shield, pressure
---


# Question
Title: I can't seem to receive data to the ArduinoStudio serial monitor on ubuntu 14.04
I'm using the Arduino Starter Kit so I have a Uno R3 and going through the examples I'm trying to read temperature data from my controller in Arduino Studio.

In essence my problem can be reduced down to

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

void loop() {
    Serial.print("stuff");
}

```

Which I'd expect to keep printing "stuff" on the serial monitor.

(In practice I'm running this exact code but all the temperature-reading going on feels irrelevant to my problem, I'm simply mentioning it because I can observe that mye LEDs light up when the temperature rises so I know the code is uploaded and running on the Duo).

I'm not seeing any errors in the studio console, and if I connect using `gtkterm` or `screen` I can see data being sent so the problem seems to be isolated to the AndroidStudio serial monitor itself.

I'm running Ubuntu 14.04 and I've connected via USB on `/dev/ttyACM3`.

I tried running

> stty -F /dev/ttyACM3 cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

as suggested here and I also tried with baud 115200, taking care to also change the value in my `setup` function.

I also ran

> chmod a+rw /dev/ttyACM3

But I'm still not seeing any errors or output. How do I proceed to debug this issue?

Running `ls -l /dev/ttyACM*` gives

> crw-rw---- 1 root dialout 166, 0 feb. 20 14:22 /dev/ttyACM0
>
> crw-rw---- 1 root dialout 166, 1 feb. 20 14:22 /dev/ttyACM1
>
> crw-rw---- 1 root dialout 166, 2 feb. 20 14:22 /dev/ttyACM2
>
> crw-rw-rw- 1 root dialout 166, 3 feb. 20 14:30 /dev/ttyACM3

# Answer
By default, on a linux system without specific udev binding rules to rename the device into something non standard, the FTDI driver should map the usb to serial port on /dev/ttyUSB\* and not to /dev/ttbACM\*. I suspect that you were just looking in the wrong place. I think it defaults to /dev/ttyUSB\* for any usb to serial dongle:

```
usb-serial.c:   usb_serial_tty_driver->name = "ttyUSB";

```
> 0 votes

---
Tags: arduino-uno, arduino-ide, ubuntu
---


title: Switch to drive Arduino and optocoupler

text:
# Question
Title: Switch to drive Arduino and optocoupler
At the moment I have a switch that connects to a digital pin on an Arduino as per the schematic below. (Obviously there is an pull-up resistor on the pin).

simulate this circuit – Schematic created using CircuitLab

I now want this switch to also connect to another Arduino via an optocoupler. Is it as simple as just adding the optocoupler between the switch and ground with the necessary resistor for it?

# Answer
> Is it as simple as just adding the optocoupler between the switch and ground with the necessary resistor for it?

Probably not, because of two issues. First, adding circuit elements between the switch and ground raises the voltage the pin will see when the switch is closed, which might keep a switch closure from registering as a low pin voltage. For example, with Vcc=5V, table 30.2 *DC Characteristics* in the Rev. 8271J 11/2015 ATmega328P datasheet shows the guaranteed maximum input low voltage as 0.3 Vcc and the guaranteed minimum input high voltage as 0.6 Vcc; that is, 1.5 V and 3 V if Vcc=5V. If the voltage drop across the optocoupler is between 1.5 and 3 V then the pin might register high or low with no guarantee which.

Second, if the pullup is large, not enough current will flow to trigger the optocoupler. For example, at Vcc=5V if the internal pullup is used and the optocoupler drops two volts, I/O Pin Pull-up Resistor Current will be about 80 μA, too little to trigger a typical optocoupler. (See figure 35-17, *ATmega328P: I/O Pin Pull-up Resistor Current vs. Input Voltage (Vcc = 5V)* in datasheet.)

What you might do instead is use two optocoupler channels in parallel or series, one for each of the Arduinos. The switch lets current pass through an appropriate resistor or resistors and the optocoupler inputs; optocoupler outputs go to Arduino inputs.

Or, tie one side of the switch to +5V and the other to a resistor in series with an optocoupler input. Connect the first Arduino's input pin to the low side of the switch. I think that input will register low when the switch is open. It will register high when the switch is closed.
> 0 votes

---
Tags: switch
---


# Question
Title: Arduino Zero - Stepper control (interrupt)?
I have a stepper controller board that I need to pulse every 40 uS or so.

I also have I2C sensors and Serial writes to preform.

Currently I run an update call in a tight loop, but the I2C sensors and Serial writes cause considerable delays which makes the motors stutter and come to a halt.

I would like to use an ISR to call the motor update method periodically.

However I cannot for the life of me figure this timer stuff out.

Here's my current attempt:

```
void TC4_Handler() {
  Stepper::updateAll();
}

void setup() {

  // Timer stuff
  // Set up the generic clock (GCLK4) used to clock timers
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                    GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK4
                     GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                     GCLK_GENCTRL_ID(4);          // Select GCLK4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  // Feed GCLK4 to TC4 and TC5
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                     GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                     GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_TC4_COUNT16_CC0 = 0x000F;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

  //NVIC_DisableIRQ(TC4_IRQn);
  //NVIC_ClearPendingIRQ(TC4_IRQn);
  NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

  REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
  REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
  // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

  REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV1024 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                   TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                   TC_CTRLA_ENABLE;               // Enable TC4
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization
  // ...
}

```

# Answer
As `Stepper::updateAll();` isn't shown I don't know what it does. For accurate timing it would make sense to use hardware-operated output-compare output pins like TIOAx and TIOBx, instead of running some code to drive the pins when an interrupt occurs.

If you need to control several wires per motor – such that a pulse on a single output line isn't enough – you might consider using a 74HC595 (or other shift register) to transfer the bits. Thus, each time an output compare occurs, the TIOAx and TIOBx line would pulse the ST\_CLK (store-clock) line of the SR, to transfer bits from the shift chain flipflops to the output flipflops; then, at its leisure the interrupt routine can shift the next set of bits out to the '595, ready to be transferred at the correct moment, when the next output compare occurs.

During stepper acceleration or deceleration, the timer count-limit would also need to be updated within the ISR.
> 1 votes

---
Tags: interrupt, timers, arduino-zero
---


# Question
Title: Is it possible to use Arduino UNO programmer for other AVR microcontrollers?
I got an Arduino UNO which I started using with microc for avr to add more customizations. I'm wondering if it is possible to use the Arduino UNO programmer to program other AVR microcontrollers (I know that it is possible using ATmega 328p and 168).

# Answer
The AVR microcontrollers that support ISP are all tinyAVRs other than the 4/5/9/10/20/40, and all megaAVRs.

The ATtiny4/5/9/10/20/40 requires TPI (Tiny Programming Interface). AVR XMEGA devices require the use of PDI (Program and Debug Interface). Neither can be programmed using ArduinoISP.
> 2 votes

# Answer
If you are using avrisp you can basically program every AVR compatible with ISP protocol.

For example you can program ATTINY85, ATMEGA8, ATMEGA16 etc... Basically for cheap and usable project with a usable flash size i use ATMEGA8 or 88. Avoid ATMEGA48, you have only 4 kb of flash and that mean you can not do anything instead of blinking LED.

Another way to do this is by using Raspberry pi GPIO for burning code on AVR.

Here is some doc from ozzmaker
> 1 votes

---
Tags: avr
---


title: LED strip and SD card

text:
# Question
Title: LED strip and SD card
My problem is simple yet extremely problematic. For some reason, I cannot interact with an SD card and a LED strip at the same time with my arduino. After hours of testing multiple scripts, I am 99.99% that the issue is due to the SPI.h library. I have tried the simplest LED strip code, such as turning on led number 5. If I include SPI.h, the code does not work, the data LED of the arduino doesn't even light up, the arduino doesn't send anything to the strip data line. If I remove include SPI.h, the code works. This is really odd, I have read about the SPI.h messing with the pins, so now I'm looking for a solution, to use the SD card module without the SPI library if it is possible. Here is an example of a code that does not work due to the use of the SPI.h library.

Any help is greatly appreciated, this is extremely odd and problematic.

```
#include <Time.h>
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#include <SPI.h>
#include <SD.h>

Sd2Card card;
SdVolume volume;
SdFile root;

const int chipSelect = 4;

#define PIN            6
#define NUMPIXELS      400

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB +   NEO_KHZ800);

boolean stringComplete = false;  // whether the string is complete
boolean readarray=false;
String inString = "";
int c=0;
int cc=0;
int led=0;
int i=0;
int j=0;
int pixel_n=0;
unsigned long start;
unsigned long endd;

//char* ledd[]={"", "", ""};
int ledd[3]={0,0,0};

File myFile;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
pixels.begin();
while (!Serial) {
  ; // wait for serial port to connect. Needed for Leonardo only
}

Serial.print("\nInitializing SD card...");

// Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
if (!volume.init(card)) {
  Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
  return;
}

// print the type and size of the first FAT-type volume
uint32_t volumesize;
Serial.print("\nVolume type is FAT");
Serial.println(volume.fatType(), DEC);
Serial.println();

Serial.println("Ok we're done");
delay(2000);

pixels.setPixelColor(5, (200,200,200)); // THIS DOES NOT WORK
pixels.show(); // THIS EITHER

  Serial.begin(9600);
}

void loop(void) {

}

```

# Answer
I had the same problem with using the SD reader with a SPI SRAM. It turns out that the very cheap SD reader cards do not like multiple SPI components on the same port. Since the Arduino has only one SPI, the only thing that worked was to use a SD data logger card.

To add a tristate solution by using two resistors on the MISO line also did not work in my case.

See my post for the post I created regarding this probably similar problem.
> 1 votes

---
Tags: neopixel, sd
---


title: Arduino serial port implementation

text:
# Question
Title: Arduino serial port implementation
It might be an obvious answer to this, but I can't find it via a quick google search. To give my question a bit of more context, I'm writing an application which simulates a communication with Arduino via serial port, therefore I need to know how it is implemented internally.

From my previous experience with micro-controllers, the serial port is normally presented in micro-controller as two separate queues, one for TX and another for RX. For transmit out of MC, my software writes a byte to the end of transmit queue, and MC hardware reads byte from the beginning of the queue, converts it to bits, and toggles the pin to transmit data/parity/stop bits. And it keep doing that until queue is exhausted. The opposite happens for receive queue.

Am I right in assuming that Arduino has similar implementation with two separate queues? In particular, I want to read and write to serial port simultaneously.

# Answer
> 1 votes
Yes. Arduino has two buffers. See the HardwareSerial.h and HardwareSerial.cpp

# Answer
> 0 votes
I have a lengthy post about Arduino serial communications: How does serial communications work on the Arduino?

In short, the hardware (on an Atmega328 like on the Uno) has a two-byte receive queue (so you can be putting one byte into memory while the next byte is being received). It has a one-byte send queue.

Lengthier queues are implemented in software using interrupts to move data from the RAM queues in/out of the hardware queues.

---
Tags: serial
---


title: MPU6050 doesn't work

text:
# Question
Title: MPU6050 doesn't work
I am trying to do a self-balancing bot as a school project, but I got stuck with the MPU6050.

I tried using the code by Jeff Rowberg (MPU\_6050\_raw) but it's reading only zeros.

I tried the MPU\_6050\_DMP and got stuck at "initializing DMP..." and no reading is shown.

I tried other code, but same thing happens, either reading zeros or getting stuck at "initializing DMP..".

And how can I make sure that the chip isn't broken?

# Answer
> 3 votes
The MPU-6050 is a 3.3V chip. When you are using a 5V Arduino board, you should take care that you don't put current into the SDA and SCL pins of the MPU-6050.

Start with a i2c scanner.
This one: Arduino Playground I2C scanner
Or this one: Nick Gammon I2C scanner
If the I2C scanner halts, then there is a hardware problem with the I2C bus. It might be a shortcut of SDA or SCL to GND, or the MPU-6050 module is not powered.

If the I2C scanner is working, then you know the address (0x68 or 0x69). With that address you can try the Short example sketch to read data from the chip.

If that is working, then you can try the Jeff Rowberg library.

---
Tags: mpu6050
---


title: Broken Loop and dim LEDs

text:
# Question
Title: Broken Loop and dim LEDs
I want to make 2 LEDs blink back and forth continuously, but they only do so once, and the second one is very dim.

code:

```
int ledone = 12;
int ledtwo = 10;
int keepgoing = 1;

void setup() {
pinMode(ledone, OUTPUT);
pinMode(ledtwo, OUTPUT);
}

void loop() {
 while (keepgoing == 1) {
  digitalWrite(ledone, HIGH);
  delay(80);
  digitalWrite(ledone, LOW);
  digitalWrite(ledtwo, HIGH);
  delay(80);
  digitalWrite(ledtwo, LOW);
  delay(500);
 }
}

```

I am using an Arduino Uno and one 220 ohm resistor for each LED.

# Answer
I think the problem is, that your delays are just too short, so you see the blinking not as blinking, but as a dim lit led.

Maybe you can try the following code:

```
void loop() {
 while (keepgoing == 1) {
  digitalWrite(ledone, HIGH);
  digitalWrite(ledtwo, LOW);
  delay(500);
  digitalWrite(ledone, LOW);
  digitalWrite(ledtwo, HIGH);
  delay(500);
 }
}

```

Is this working?
> 1 votes

---
Tags: arduino-uno, digitalwrite
---


title: Generate 1.7 Mhz with PWM in Uno?

text:
# Question
Title: Generate 1.7 Mhz with PWM in Uno?
I have this code:

```
void setup() {
  pinMode(11, OUTPUT);
  TCCR2B = 0;
  TCNT2 = 0;
  TCCR2A = _BV(WGM21);
  TCCR2A |= _BV(COM2A0);
  OCR2A = 249;
}

void loop() {
  soundBuzzer();
}

void soundBuzzer() {
  TCCR2B |= _BV(CS21);
}

void silenceBuzzer() {
  TCCR2B &= ~_BV(CS21);
  TCNT2 = 0;
}

```

(Got it from here).

And I have an ultrasonic water atomizer that works in a frequency of 1.7 Mhz. Writing another number instead of 249 in the line "OCR2A = 249;", the frequency generated changes. With 249 it generates a frequency of 4 Khz. So, my question is: Which number do I have to write to get approximately 1.7 Mhz?

# Answer
> 3 votes
Expanding from my comment... any signal level generated by this kind of microcontroller can only last for an integer number of CPU cycles. In order to generate it, you first have to compute the timing characteristics of the desired signal in terms of CPU cycles:

```
period = 16 MHz ÷ 1.7 MHz = 9.412 cycles

```

The closest you can get is 9 cycles, which gives the frequency

```
frequency = 16 MHz ÷ 9 = 1.778 MHz

```

Assuming this is acceptably close to your target, you can configure a timer to do it. The example code you provided uses Timer 2 with the OC2A output set to toggle mode. This approach can only give periods which are an *even* number of cycles, thus I am using the regular “non-inverting fast PWM” mode instead in the solution below. In this mode, the pin OC2A cannot be used with a controlled frequency, then I changed it to OC2B (pin 3 on the Uno). Here is the code:

```
const uint8_t OUTPUT_PIN = 3;  // = OC2B
const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

void setup()
{
    pinMode(OUTPUT_PIN, OUTPUT);
    TCCR2B = 0;           // stop timer
    TCNT2  = 0;           // reset timer
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22);  // ...ditto
    OCR2A = PERIOD - 1;
    OCR2B = PERIOD/2 - 1;
}

void soundBuzzer() {
    TCCR2B |= _BV(CS20);  // F_CPU / 1
}

void silenceBuzzer() {
    TCCR2B &= ~_BV(CS20);
    TCNT2 = 0;
}

```

The generated signal is slightly asymmetric: it stays HIGH during 4 cycles and LOW for 5 cycles. If you want a symmetric signal (50% duty cycle), you can set `PERIOD` to 10 (5 cycles HIGH and 5 cycles LOW), but then the frequency drops to 1.6 MHz.

**Edit**: You could also replace your Arduino Uno by a cheap ATtiny85 microcontroller, or maybe an Arduino-compatible dev board based on it, like the Trinket or the Digispark.

This microcontroller has a built-in PLL which allows it to run one of its timers at 64 MHz, even though the CPU is running much slower. A 64 MHz timer allows you to hit the target 1.7 MHz frequency to within 1%:

```
64 MHz ÷ 38 = 1.684 MHz

```

---
Tags: arduino-uno, pwm, frequency
---


# Question
Title: Different questions regarding Arduino C++ library coding style
I'm reading the two wire library in Arduino libraries and in the C++ source code I found different methods which I don't know what they mean, in the following:

```
// Initialize Class Variables //////////////////////////////////////////////////

uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
uint8_t TwoWire::rxBufferIndex = 0;
uint8_t TwoWire::rxBufferLength = 0;

uint8_t TwoWire::txAddress = 0;
uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
uint8_t TwoWire::txBufferIndex = 0;
uint8_t TwoWire::txBufferLength = 0;

uint8_t TwoWire::transmitting = 0;
void (*TwoWire::user_onRequest)(void);
void (*TwoWire::user_onReceive)(int);

// Public Methods //////////////////////////////////////////////////////////////
void TwoWire::begin(void)
{
  rxBufferIndex = 0;
  rxBufferLength = 0;

  txBufferIndex = 0;
  txBufferLength = 0;

  twi_init();
}

void TwoWire::begin(uint8_t address)
{
  twi_setAddress(address);
  twi_attachSlaveTxEvent(onRequestService);
  twi_attachSlaveRxEvent(onReceiveService);
  begin();
}

void TwoWire::begin(int address)
{
  begin((uint8_t)address);
}

```

My first question, regarding to class variables:

1. Why has the author connected the variables to the class with scope-resolution operator "::"?
2. I want to understand the last two lines of class variables, I know they are function pointers, but I want to know more details and benefits of function pointers?

---

My second question, regarding to public methods:

1. There are three versions of the "begin" function, can someone explain why?
2. Why is begin(); called inside the second function declaration?

# Answer
> 1 votes
> Why they connect the variables to the class with scope-resolution operator "::"?

Those are *static* variables. They don't exist within an instantiated class instance since they are common to *all* class instances - so they have to be defined elsewhere, and for that you need the full "class path" for them to associate them with the class itself.

> I want to understand the last two lines of class variables, I know they are function pointers, but I want to know more details and benefits of function pointers?

Yes, they are function pointers. They are used to store the address of functions the user supplies at runtime. Without them it is very hard for the user to tell the class which of his own functions should be called for various events.

> There are three versions of the "begin" function, can someone explain why?

This is called *function overloading*. It allows you to have the same function but provide different combinations of parameters. In this case one with no functions (in master mode) and two with different numeric parameters (for slave mode) with those numeric parameters in different storage formats.

> Why begin(); is called inside the second function declaration?

It saves having to duplicate all the code from the other begin() function within that function. You call the function with a numeric parameter, it does a little bit of "extra" work, then it calls the "common" begin code from the other `begin()` function. Code duplication is generally a bad thing since any changes you make have to be made in multiple places. This keeps the common code in one location, and the most convenient place for that is the `begin()` function that takes no parameters.

---
Tags: c++, wire-library
---


title: Interrupt handler in library

text:
# Question
Title: Interrupt handler in library
This is my first library so feel free to burn me and vote this down :D This is a library that provides me with Watchdog deep sleep on my ATtiny85 projects.

In the test sketch I use the `watchdog timer's interrupt vector` but I want to place this within the library. How can I do this?

I have tried to add this to the `init` method but that did not work out;
`powernap.h:26: error: expected unqualified-id before string constant
 ISR(WDT_vect) {`

Also; feel free to shoot at the rest of the library, I am here to learn.

**Test Sketch**

```
#include "powernap.h"

#define LED 0

Napper napper = Napper();

volatile boolean f_wdt = 1;

ISR(WDT_vect) {
  f_wdt=1;
}

void setup() {
  delay(2000);
  napper.setup(8); // configure watchdog timer
}

void loop() { // blink
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
  delay(200);
  digitalWrite(LED, HIGH);
  delay(200);
  digitalWrite(LED, LOW);
  delay(200);

  napper.sleep(); // deep sleep
}

```

**powernap.cpp**

```
#include "powernap.h"

 #ifndef cbi
   #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
 #endif
 #ifndef sbi
   #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
 #endif

Napper::Napper() {

}

void Napper::init(float initial) {
//  volatile boolean f_wdt = 1;

//  ISR(WDT_vect) {
//  f_wdt=1;
//  }
}

void Napper::setup(int cycle) {
    byte bb;
    int ww;
    if (cycle > 9 ) cycle=9;
    bb=cycle & 7;
    if (cycle > 7) bb|= (1<<5);
    bb|= (1<<WDCE);
    ww=bb;

    MCUSR &= ~(1<<WDRF);
    // start timed sequence
    WDTCR |= (1<<WDCE) | (1<<WDE);
    // set new watchdog timeout value
    WDTCR = bb;
    WDTCR |= _BV(WDIE);
}

void Napper::sleep() {
    cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

    set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
    sleep_enable();

    sleep_mode();                        // System sleeps here

    sleep_disable();                     // System continues execution here when watchdog timed out
    sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

```

**powernap.h**

```
#ifndef Fader_h
#define Fader_h

#if ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
  #include "pins_arduino.h"
  #include "WConstants.h"
#endif

#include <avr/sleep.h>
#include <avr/wdt.h>
#include <util/delay.h>

class Napper {
    public:
        Napper();

        void init(float initial);
        void setup(int cycle);
        void sleep();

    private:
        int flag;

};

#endif

```

# Answer
To answer your actual question, you just have to define `ISR(WDT_vect)` outside any function.

Now, for the general critique, let me start by quoting Antoine de Saint Exupéry: “It seems that perfection is attained not when there is nothing more to add, but when there is nothing more to remove.” There are quite a few things to remove from your code, like unused variables, parameters or methods. I understand that you may be tempted to leave useless stuff in there anticipating that you may need it in a future, extended version. But please, don't do that. Try to keep clean and lean any code that you post in public, and only add extra stuff when you actually need it.

I would remove most of the `#include`s from powernap.h. If the compiler needs one of these to understand your .h, then live it there. If it's only needed to compile your library, then it belongs to your .cpp.

Also, there is no point in making your library dependent on the Arduino core, as you are using no core functionality. By removing this dependency, you can make your library more versatile, as it can be used both for Arduino and non-Arduino projects.

The line `#ifndef Fader_h` looks weird. Standard practice is to use the name of the .h file, capitalized. Don't depart from common practice unless you have some reason to do so.

I would also add `static` to your methods, this way they can be used without having to instantiate an object, like in `Napper::setup(WDTO_4S);`.

You are using three different syntaxes for setting and clearing bits in I/O registers. Your code will look more consistent if you choose one and stick with it.

I almost forgot... you have to make sure the timed sequence is done atomically, i.e. it's not interrupted.

Below is a version of the library that implements the suggestions above:

**powernap.h**

```
#ifndef POWERNAP_H
#define POWERNAP_H

#include <stdint.h>

class Napper {
    public:
        Napper() {}
        static void setup(uint8_t cycle);
        static void sleep();
};

#endif  // defined(POWERNAP_H)

```

**powernap.cpp**

```
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <util/atomic.h>
#include "powernap.h"

// This interrupt is used only as a wakeup source.
EMPTY_INTERRUPT(WDT_vect);

// Configure the watchdog as an interrupt source.
// `cycle' should be an integer from 0 to 9, or one of the constants
// WDTO_XXS from <avr/wdt.h>.
void Napper::setup(uint8_t cycle) {
    uint8_t prescaler;         // prescaler bits in WDTCR
    if (cycle > 9) cycle = 9;  // largest supported value
    prescaler = cycle & 7;     // bits WDP2:WDP0 are right aligned in WDTCR
    if (cycle > 7) prescaler |= _BV(WDP3);

    MCUSR &= ~_BV(WDRF);  // clear this bit: it overrides WDE
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        WDTCR |= _BV(WDCE)    // start timed sequence
              |  _BV(WDE);
        WDTCR =  prescaler    // set new watchdog timeout value
              |  _BV(WDIE);   // enable watchdog interrupt
    }
}

void Napper::sleep() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_mode();
}

```
> 1 votes

# Answer
It is hard to help you improve your library or code if you don't tell others what your code pieces are trying to do.

In general, you will have a piece of code that sets up the whole thing, a piece of code that will be executed in the isr, and other helper code pieces, like getting status and clear status, as appropriate.

I often use a function pointer that the user can hook to the user handler so my isr portion of the code is fixed. Just hook to different functions in the user space and you are ready to go.

Obviously other ways exist, each with their pros and cons.
> 1 votes

---
Tags: library, interrupt, attiny
---


# Question
Title: Powering SD breakout board with 3.7V battery
So in a previous post I asked if I could charge an SD card breakout board with a 3.7V LiPo battery, and I got a positive response, so I did it.

The problem is that it seems not to be enough, since, with the exact same wiring, if I supply it with my Arduino Uno, it works perfectly, but when I change the supply to the battery it gives an error. The following text is the result of an Arduino example script:

When connected with the Arduino:

```
Initializing SD card...Wiring is correct and a card is present.

Card type: SDHC

Volume type is FAT32

Volume size (bytes): 2696937472
Volume size (Kbytes): 2633728
Volume size (Mbytes): 2572

Files found on the card (name, date and size in bytes):
SYSTEM~1/     2017-04-27 15:20:04
  WPSETT~1.DAT  2017-04-27 15:20:04 12
  INDEXE~1      2017-04-27 15:20:14 76
TEST0.TXT     2000-01-01 01:00:00 49050
TEST1.TXT     2000-01-01 01:00:00 60231
TEST2.TXT     2000-01-01 01:00:00 1044
TEST3.TXT     2000-01-01 01:00:00 34831
TEST4.TXT     2000-01-01 01:00:00 189736
TEST5.TXT     2000-01-01 01:00:00 12419

```

When connected to the battery:

```
Initializing SD card...initialization failed. Things to check:
* is a card inserted?
* is your wiring correct?
* did you change the chipSelect pin to match your shield or module?

```

or

```
Initializing SD card...Wiring is correct and a card is present.

Card type: SD1
Could not find FAT16/FAT32 partition.
Make sure you've formatted the card

```

I've tried to supply the breakout board both through the 3V and 5V input. Can anyone notice what am I doing wrong?

# Answer
> 2 votes
You haven't connected the grounds together in your circuit. You need to connect all the grounds together so every connection has a return path back to where it came from. That means connect together:

* An Ardino GND pin
* The GND pin of the SD card breakout board
* The negative (or ground) pin of the battery

---
Tags: sd-card, battery
---